/// <summary>
        /// write manifest into target path.
        /// </summary>
        static void WriteManifestFile(string path, IBundleBuildResults bundleResults, BuildTarget target, string remoteURL)
        {
            var manifest = new AssetbundleBuildManifest();

            manifest.BuildTarget = target.ToString();

            //we use unity provided dependency result for final check
            var deps = bundleResults.BundleInfos.ToDictionary(kv => kv.Key, kv => kv.Value.Dependencies.ToList());

            foreach (var result in bundleResults.BundleInfos)
            {
                var bundleInfo = new AssetbundleBuildManifest.BundleInfo();
                bundleInfo.BundleName   = result.Key;
                bundleInfo.Dependencies = Utility.CollectBundleDependencies(deps, result.Key);
                bundleInfo.Hash         = result.Value.Hash;
                bundleInfo.Size         = new FileInfo(result.Value.FileName).Length;
                manifest.BundleInfos.Add(bundleInfo);
            }

            //sort by size
            manifest.BundleInfos.Sort((a, b) => b.Size.CompareTo(a.Size));
            var manifestString = JsonUtility.ToJson(manifest);

            manifest.GlobalHash = Hash128.Compute(manifestString);
            manifest.BuildTime  = DateTime.UtcNow.Ticks;
            manifest.RemoteURL  = remoteURL;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            File.WriteAllText(Utility.CombinePath(path, AssetbundleBuildSettings.ManifestFileName), JsonUtility.ToJson(manifest, true));
        }
Esempio n. 2
0
        public virtual Texture2D LoadImage(long productId, string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                return(null);
            }

            var hash = Hash128.Compute(url);

            try
            {
                var path = m_IOProxy.PathsCombine(m_Application.userAppDataPath, "Asset Store", "Cache", "Images", productId.ToString(), hash.ToString());
                if (m_IOProxy.FileExists(path))
                {
                    var texture = new Texture2D(2, 2);
                    if (texture.LoadImage(m_IOProxy.FileReadAllBytes(path)))
                    {
                        return(texture);
                    }
                }
            }
            catch (System.IO.IOException e)
            {
                Debug.Log($"[Package Manager] Cannot load image: {e.Message}");
            }

            return(null);
        }
Esempio n. 3
0
 public ImageData(string assetPath)
 {
     guid       = Hash128.Compute(assetPath);
     bestColors = new ColorInfo[5];
     bestShades = new ColorInfo[5];
     histogram  = new Histogram();
 }
        public void ShaderBundleNaming_GeneratesCorrectShaderBundlePrefix(ShaderBundleNaming shaderBundleNaming, string customName)
        {
            //Setup
            string             savedCustomName   = m_BuildContext.Settings.ShaderBundleCustomNaming;
            ShaderBundleNaming savedBundleNaming = m_BuildContext.Settings.ShaderBundleNaming;

            m_BuildContext.Settings.ShaderBundleCustomNaming = customName;
            m_BuildContext.Settings.ShaderBundleNaming       = shaderBundleNaming;
            string expectedValue = "";

            switch (shaderBundleNaming)
            {
            case ShaderBundleNaming.ProjectName:
                expectedValue = Hash128.Compute(m_BuildScript.GetProjectName()).ToString();
                break;

            case ShaderBundleNaming.DefaultGroupGuid:
                expectedValue = m_BuildContext.Settings.DefaultGroup.Guid;
                break;

            case ShaderBundleNaming.Custom:
                expectedValue = customName;
                break;
            }

            //Test
            string bundleName = m_BuildScript.GetBuiltInShaderBundleName(m_BuildContext);

            //Assert
            Assert.AreEqual(expectedValue, bundleName);

            //Cleanup
            m_BuildContext.Settings.ShaderBundleCustomNaming = savedCustomName;
            m_BuildContext.Settings.ShaderBundleNaming       = savedBundleNaming;
        }
Esempio n. 5
0
    static string GenerateHash(string vName)
    {
        var tDevice = SystemInfo.deviceUniqueIdentifier;
        var tID     = tDevice + vName;

        return(Hash128.Compute(tID).ToString());
    }
        void OnDrawGizmosSelected()
        {
            var color = Color.green;

            color.g      = Hash128.Compute(this.category).GetHashCode() % 255 / 256f;
            Gizmos.color = color;
            Gizmos.DrawSphere(center: this.transform.position, radius: this.gizmo_radius);
        }
Esempio n. 7
0
    private void Awake()
    {
        string temp = model.ToString();

        temp += score.ToString();
        temp += damage.ToString();
        temp += buoyancy.ToString();
        ID    = Hash128.Compute(temp).GetHashCode();
    }
        public static Hash128 GetPrefabAssetIdentifier(string guid)
        {
            if (string.IsNullOrEmpty(guid))
            {
                throw new ArgumentNullException(nameof(guid));
            }

            return(Hash128.Compute(guid));
        }
        private static string GetDbGuid(string settingsPath)
        {
            var guid = AssetDatabase.AssetPathToGUID(settingsPath);

            if (string.IsNullOrEmpty(guid))
            {
                return(Hash128.Compute(settingsPath).ToString());
            }
            return(guid);
        }
Esempio n. 10
0
        internal static Hash128 CreateWindowAndStageIdentifier(string windowGUID, Stage stage)
        {
            Hash128 hash          = stage.GetHashForStateStorage();
            Hash128 windowHash    = Hash128.Compute(windowGUID);
            Hash128 stageTypeHash = Hash128.Compute(stage.GetType().FullName);

            HashUtilities.AppendHash(ref windowHash, ref hash);
            HashUtilities.AppendHash(ref stageTypeHash, ref hash);
            return(hash);
        }
Esempio n. 11
0
        // Used for writing state files to HDD
        // Should typically be a persistent unique hash per content shown.
        // For stages that use the assetPath property, the hash is by default based on the asset GUID.
        protected internal virtual Hash128 GetHashForStateStorage()
        {
            if (!string.IsNullOrEmpty(assetPath))
            {
                return(Hash128.Compute(AssetDatabase.AssetPathToGUID(assetPath)));
            }

            // If no assetPath is specified, the default behavior is that
            // every stage of the same type will reuse the same state files.
            return(new Hash128());
        }
Esempio n. 12
0
    IEnumerator LoadSceneAB()
    {
        string url = sceneUrl;

        UnityWebRequest uwr;

        if (m_useCache)
        {
            uwr = UnityWebRequestAssetBundle.GetAssetBundle(url, Hash128.Compute(sceneName), 0);
        }
        else
        {
            uwr = UnityWebRequestAssetBundle.GetAssetBundle(url);
        }

        using (uwr)
        {
            m_state = "SendWebRequest : " + url;
            //Debug.Log(m_state);
            yield return(uwr.SendWebRequest());

            if (uwr.isNetworkError || uwr.isHttpError)
            {
                m_state = uwr.error + ", ResponseCode: " + uwr.responseCode + ", NetworkError: " +
                          uwr.isNetworkError + ", HttpError: " + uwr.isHttpError;

                Debug.Log(m_state);
            }
            else
            {
                m_state = "DownloadHandlerAssetBundle.GetContent";
                //Debug.Log(m_state);
                // Get downloaded asset bundle
                AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(uwr);
                m_bundleList.Add(bundle.name, bundle);

                string[] deps = m_rootManifest.GetAllDependencies(bundle.name);
                Debug.Log(bundle.name + " dependencies count : " + deps.Length);
                foreach (var d in deps)
                {
                    if (!m_bundleList.ContainsKey(d))
                    {
                        yield return(StartCoroutine(LoadAssetbundle(d, "")));
                    }
                }

                m_state = "SceneManager.LoadSceneAsync";
                //Debug.Log(m_state);
                AsyncOperation opt = SceneManager.LoadSceneAsync(sceneName);
            }
        }
    }
Esempio n. 13
0
    /// <summary>キーを受け取ってハッシュと照合済みの文字列を返す</summary>
    private static string getStringWithHash(string key)
    {
        var cstr          = PlayerPrefs.GetString(key);
        var dstr          = cstr.Substring(hashStrLength);
        var hash_saved    = Hash128.Parse(cstr.Substring(0, hashStrLength));
        var hash_computed = Hash128.Compute(dstr);

        if (hash_saved.isValid && hash_saved == hash_computed)
        {
            return(dstr);
        }
        throw new PlayerPrefsException($"hash mismatch saved:'{hash_saved}', computed:'{hash_computed}'");
    }
        /// <summary>
        /// Saves all settings to their serialized state.
        /// </summary>
        /// <seealso cref="ISettingsRepository.Save"/>
        public void Save()
        {
            Init();

            if (!File.Exists(path))
            {
                var directory = Path.GetDirectoryName(path);

                if (string.IsNullOrEmpty(directory))
                {
                    Debug.LogError(
                        $"Settings file {name} is saved to an invalid path: {path}. Settings will not be saved.");
                    return;
                }

                Directory.CreateDirectory(directory);
            }

            string json = EditorJsonUtility.ToJson(this, k_PrettyPrintJson);

            // While unlikely, a hash collision is possible. Always test the actual saved contents before early exit.
            if (m_JsonHash == Hash128.Compute(json) &&
                TryLoadSavedJson(out string existing) &&
                existing.Equals(json))
            {
                return;
            }

#if UNITY_2019_3_OR_NEWER
            // AssetDatabase.IsOpenForEdit can be a very slow synchronous blocking call when Unity is connected to
            // Perforce Version Control. Especially if it's called repeatedly with every EditorGUI redraw.
            if (File.Exists(path) && !AssetDatabase.IsOpenForEdit(path))
            {
                if (!AssetDatabase.MakeEditable(path))
                {
                    Debug.LogWarning($"Could not save package settings to {path}");
                    return;
                }
            }
#endif

            try
            {
                m_JsonHash = Hash128.Compute(json);
                File.WriteAllText(path, json);
            }
            catch (UnauthorizedAccessException)
            {
                Debug.LogWarning($"Could not save package settings to {path}");
            }
        }
    private void OnGoClicked()
    {
        string tmp_txt = txt_ID.text;

        char[] reversed = new char[tmp_txt.Length];
        for (int i = 0; i < tmp_txt.Length; i++)
        {
            reversed[i] = tmp_txt[tmp_txt.Length - 1 - i];
        }
        tmp_txt        = Hash128.Compute(new string(reversed)).ToString();
        _participantID = tmp_txt.Substring(tmp_txt.Length - 10, 10);
        cv.enabled     = false;
        EventsController.instance.SendBegin();
    }
Esempio n. 16
0
        public static GameObject PrefabFromGameObject(GameObject gameObject,
                                                      [System.Runtime.CompilerServices.CallerMemberName] string memberName    = "",
                                                      [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath  = "",
                                                      [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
        {
            var prefab    = UnityEngine.Object.Instantiate(gameObject, prefabParent.transform);
            var networkId = prefab.GetComponent <NetworkIdentity>();

            if (networkId)
            {
                networkId.m_AssetId = NetworkHash128.Parse(Hash128.Compute(sourceLineNumber + memberName + sourceFilePath).ToString());
            }
            return(prefab);
        }
Esempio n. 17
0
        public void OnProcessScene(UnityEngine.SceneManagement.Scene scene, Build.Reporting.BuildReport report)
        {
            int staticBatching, dynamicBatching;

            PlayerSettings.GetBatchingForPlatform(EditorUserBuildSettings.activeBuildTarget, out staticBatching, out dynamicBatching);
            if (staticBatching != 0)
            {
                using (StaticBatchingUtility.s_CombineMarker.Auto())
                {
                    ulong sceneHash = Hash128.Compute(AssetDatabase.AssetPathToGUID(scene.path)).u64_0;
                    StaticBatchingEditorHelper.CombineAllStaticMeshesForScenePostProcessing(sceneHash, scene);
                }
            }
        }
 void TaskOnClick()
 {
     //On récupére le Pseudo et le Mot de passe entrée par l'utilisateur pour se connecter
     _Pseudo = PseudoGameObject.GetComponent <InputEventHandler>();
     _Mdp    = MdpGameObject.GetComponent <InputEventHandler>();
     if (_Pseudo.inputEntered && _Mdp.inputEntered)
     {
         //On fait appel à la fonction d'envoi de Requete associé en Hashant le contenu du champ mot de passe
         StartCoroutine(_httpRequest.LoginRequest(_Pseudo.textInput, Hash128.Compute(_Mdp.textInput).ToString()));
     }
     else
     {
         Debug.Log("Remplissez les champs");
     }
 }
Esempio n. 19
0
 public UserModel Load()
 {
     if (PlayerPrefs.HasKey(CheckSumKey) && PlayerPrefs.HasKey(DataKey))
     {
         var json     = PlayerPrefs.GetString(DataKey);
         var checkSum = PlayerPrefs.GetString(CheckSumKey);
         if (Hash128.Compute(json).ToString() != checkSum)
         {
             Debug.LogError("不正なデータを検知しました。");
             return(null);
         }
         var data = JsonUtility.FromJson <UserData>(json);
         return(new UserModel(data));
     }
     return(null);
 }
Esempio n. 20
0
        /// <summary>
        /// Generate an InferenceEvent for the model.
        /// </summary>
        /// <param name="nnModel"></param>
        /// <param name="behaviorName"></param>
        /// <param name="inferenceDevice"></param>
        /// <param name="sensors"></param>
        /// <param name="actionSpec"></param>
        /// <returns></returns>
        internal static InferenceEvent GetEventForModel(
            NNModel nnModel,
            string behaviorName,
            InferenceDevice inferenceDevice,
            IList <ISensor> sensors,
            ActionSpec actionSpec
            )
        {
            var barracudaModel = ModelLoader.Load(nnModel);
            var inferenceEvent = new InferenceEvent();

            // Hash the behavior name so that there's no concern about PII or "secret" data being leaked.
            var behaviorNameHash = Hash128.Compute(behaviorName);

            inferenceEvent.BehaviorName = behaviorNameHash.ToString();

            inferenceEvent.BarracudaModelSource   = barracudaModel.IrSource;
            inferenceEvent.BarracudaModelVersion  = barracudaModel.IrVersion;
            inferenceEvent.BarracudaModelProducer = barracudaModel.ProducerName;
            inferenceEvent.MemorySize             = (int)barracudaModel.GetTensorByName(TensorNames.MemorySize)[0];
            inferenceEvent.InferenceDevice        = (int)inferenceDevice;

            if (barracudaModel.ProducerName == "Script")
            {
                // .nn files don't have these fields set correctly. Assign some placeholder values.
                inferenceEvent.BarracudaModelSource   = "NN";
                inferenceEvent.BarracudaModelProducer = "tensorflow_to_barracuda.py";
            }

#if UNITY_2019_3_OR_NEWER && UNITY_EDITOR
            var barracudaPackageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssembly(typeof(Tensor).Assembly);
            inferenceEvent.BarracudaPackageVersion = barracudaPackageInfo.version;
#else
            inferenceEvent.BarracudaPackageVersion = null;
#endif

            inferenceEvent.ActionSpec       = EventActionSpec.FromActionSpec(actionSpec);
            inferenceEvent.ObservationSpecs = new List <EventObservationSpec>(sensors.Count);
            foreach (var sensor in sensors)
            {
                inferenceEvent.ObservationSpecs.Add(EventObservationSpec.FromSensor(sensor));
            }

            inferenceEvent.TotalWeightSizeBytes = GetModelWeightSize(barracudaModel);
            inferenceEvent.ModelHash            = GetModelHash(barracudaModel);
            return(inferenceEvent);
        }
Esempio n. 21
0
    private IEnumerator Start()
    {
        // Define the caching information once. The same caching information is used for
        // every load, so we know the same version will be cached after the first load
        // completes.
        var cacheInfo = new CachedAssetBundle(_bundleUrl, Hash128.Compute(_bundleUrl));

        do
        {
            // Ensure that we're starting with a clean cache each time.
            while (!Caching.ClearCache())
            {
                yield return(true);
            }

            // Load the bundle once to populate the cache. We make sure this load
            // finishes before starting subsequent loads.
            Debug.Log("Loading bundle first time");
            yield return(LoadBundleRoutine(cacheInfo, false));

            Debug.Assert(
                Caching.IsVersionCached(cacheInfo),
                "Bundle was not cached after first load");

            // Load the bundle from the cache twice concurrently. We use SpawnCoroutine()
            // to ensure that both loads will happen concurrently. The inner coroutine
            // yields while waiting for the bundle to load, so the third load is
            // guaranteed to start while the second one is in progress.
            Debug.Log("Spawning second load");
            var secondLoad = StartCoroutine(LoadBundleRoutine(cacheInfo, true));
            Debug.Assert(
                Caching.IsVersionCached(cacheInfo),
                "Bundle was not cached after second load");

            Debug.Log("Spawning third load");
            var thirdLoad = StartCoroutine(LoadBundleRoutine(cacheInfo, true));
            Debug.Assert(
                Caching.IsVersionCached(cacheInfo),
                "Bundle was not cached after third load");

            // Make sure all loading has finished before starting the next iteration.
            yield return(secondLoad);

            yield return(thirdLoad);
        } while (_runInLoop);
    }
Esempio n. 22
0
            internal string DetermineIdToLoad(IResourceLocation location, IList <object> dependencyObjects, bool disableCatalogUpdateOnStart = false)
            {
                //default to load actual local source catalog
                string idToLoad = GetTransformedInternalId(location);

                if (dependencyObjects != null &&
                    location.Dependencies != null &&
                    dependencyObjects.Count == (int)DependencyHashIndex.Count &&
                    location.Dependencies.Count == (int)DependencyHashIndex.Count)
                {
                    var remoteHash = dependencyObjects[(int)DependencyHashIndex.Remote] as string;
                    m_LocalHashValue = dependencyObjects[(int)DependencyHashIndex.Cache] as string;
                    Addressables.LogFormat("Addressables - ContentCatalogProvider CachedHash = {0}, RemoteHash = {1}.", m_LocalHashValue, remoteHash);

                    if (string.IsNullOrEmpty(remoteHash))            //offline
                    {
                        if (!string.IsNullOrEmpty(m_LocalHashValue)) //cache exists
                        {
                            idToLoad = GetTransformedInternalId(location.Dependencies[(int)DependencyHashIndex.Cache]).Replace(".hash", ".json");
                        }
                    }
                    else //online
                    {
                        if (remoteHash == m_LocalHashValue) //cache of remote is good
                        {
                            idToLoad = GetTransformedInternalId(location.Dependencies[(int)DependencyHashIndex.Cache]).Replace(".hash", ".json");
                        }
                        else //remote is different than cache, or no cache
                        {
                            if (disableCatalogUpdateOnStart)
                            {
                                m_LocalHashValue = Hash128.Compute(idToLoad).ToString();
                            }
                            else
                            {
                                idToLoad        = GetTransformedInternalId(location.Dependencies[(int)DependencyHashIndex.Remote]).Replace(".hash", ".json");
                                m_LocalDataPath = GetTransformedInternalId(location.Dependencies[(int)DependencyHashIndex.Cache]).Replace(".hash", ".json");
                            }

                            m_RemoteHashValue = remoteHash;
                        }
                    }
                }
                return(idToLoad);
            }
Esempio n. 23
0
        public void Save(UserModel user)
        {
            var data = new UserData();

            data.id             = user.Id;
            data.characterId    = user.CharacterId;
            data.power          = user.Power;
            data.powerUpLevel   = user.PowerUpLevel;
            data.memberLevel    = user.MemberLevel;
            data.nextBattleId   = user.NextBattleId;
            data.nextBattleTime = user.NextBattleTime.Ticks;
            var json     = JsonUtility.ToJson(data);
            var checkSum = Hash128.Compute(json).ToString();

            PlayerPrefs.SetString(DataKey, json);
            PlayerPrefs.SetString(CheckSumKey, checkSum);
            PlayerPrefs.Save();
        }
Esempio n. 24
0
            public void SaveImage(long productId, string url, Texture2D texture)
            {
                if (string.IsNullOrEmpty(url) || texture == null)
                {
                    return;
                }

                var path = Paths.Combine(ApplicationUtil.instance.userAppDataPath, "Asset Store", "Cache", "Images", productId.ToString());

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                var hash = Hash128.Compute(url);

                path = Paths.Combine(path, hash.ToString());
                File.WriteAllBytes(path, texture.EncodeToJPG());
            }
Esempio n. 25
0
        public virtual void SaveImage(long productId, string url, Texture2D texture)
        {
            if (string.IsNullOrEmpty(url) || texture == null)
            {
                return;
            }

            var path = Paths.Combine(m_Application.userAppDataPath, "Asset Store", "Cache", "Images", productId.ToString());

            if (!m_IOProxy.DirectoryExists(path))
            {
                m_IOProxy.CreateDirectory(path);
            }

            var hash = Hash128.Compute(url);

            path = Paths.Combine(path, hash.ToString());
            m_IOProxy.FileWriteAllBytes(path, texture.EncodeToJPG());
        }
    unsafe public static EntityGuid GetEntityGuid(GameObject go, int index)
    {
#if false
        var id = GlobalObjectId.GetGlobalObjectId(go);
        // For the time being use InstanceID until we support GlobalObjectID API
        //Debug.Log(id);
        var hash = Hash128.Compute($"{id}:{index}");

        EntityGuid entityGuid;
        Assert.AreEqual(sizeof(EntityGuid), sizeof(Hash128));
        UnsafeUtility.MemCpy(&entityGuid, &hash, sizeof(Hash128));
        return(entityGuid);
#else
        EntityGuid entityGuid;
        entityGuid.a = (ulong)go.GetInstanceID();
        entityGuid.b = (ulong)index;

        return(entityGuid);
#endif
    }
Esempio n. 27
0
            public Texture2D LoadImage(long productId, string url)
            {
                if (string.IsNullOrEmpty(url))
                {
                    return(null);
                }

                var hash = Hash128.Compute(url);
                var path = Paths.Combine(ApplicationUtil.instance.userAppDataPath, "Asset Store", "Cache", "Images", productId.ToString(), hash.ToString());

                if (File.Exists(path))
                {
                    var texture = new Texture2D(2, 2);
                    if (texture.LoadImage(File.ReadAllBytes(path)))
                    {
                        return(texture);
                    }
                }

                return(null);
            }
        void Init()
        {
            if (m_Initialized)
            {
                return;
            }

            m_Initialized = true;

            if (TryLoadSavedJson(out string json))
            {
                m_Dictionary = null;
                m_JsonHash   = Hash128.Compute(json);
                EditorJsonUtility.FromJsonOverwrite(json, this);
            }

            if (m_Dictionary == null)
            {
                m_Dictionary = new SettingsDictionary();
            }
        }
        internal void ImportXmlFromString(string xml, out VisualTreeAsset vta)
        {
            byte[] b = Encoding.UTF8.GetBytes(xml);
            var    h = Hash128.Compute(b);

            CreateVisualTreeAsset(out vta, h);

            XDocument doc;

            try
            {
                doc = XDocument.Parse(xml, LoadOptions.SetLineInfo);
            }
            catch (Exception e)
            {
                logger.LogError(ImportErrorType.Syntax, ImportErrorCode.InvalidXml, e, Error.Level.Fatal, null);
                return;
            }

            LoadXmlRoot(doc, vta);
            TryCreateInlineStyleSheet(vta);
        }
Esempio n. 30
0
    unsafe Entity CreateEntity(GameObject go, int index)
    {
        var entity = m_DstManager.CreateEntity();

        #if UNITY_EDITOR
        m_DstManager.SetName(entity, go.name);
        #endif

        if (m_AddEntityGUID)
        {
            // var id = GlobalObjectID.GetGlobalObjectID(go);
            // For the time being use InstanceID until we support GlobalObjectID API
            var id = go.GetInstanceID();

            //Debug.Log(id);
            var hash = Hash128.Compute($"{id}:{index}");

            EntityGuid entityGuid;
            Assert.AreEqual(sizeof(EntityGuid), sizeof(Hash128));
            UnsafeUtility.MemCpy(&entityGuid, &hash, sizeof(Hash128));
            m_DstManager.AddComponentData(entity, entityGuid);
        }
        return(entity);
    }