< Summary

Class:DCL.Helpers.UtilsDummyJsonUtilityFromArray[T]
Assembly:Utils
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Helpers/Utils/Utils.cs
Covered lines:2
Uncovered lines:0
Coverable lines:2
Total lines:536
Line coverage:100% (2 of 2)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
GetFromJsonArray(...)0%110100%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Helpers/Utils/Utils.cs

#LineLine coverage
 1#if UNITY_WEBGL && !UNITY_EDITOR
 2#define WEB_PLATFORM
 3#endif
 4
 5using System;
 6using System.Collections;
 7using System.Collections.Generic;
 8using System.Linq;
 9using DCL.Configuration;
 10using TMPro;
 11using UnityEngine;
 12using UnityEngine.Assertions;
 13using UnityEngine.EventSystems;
 14using UnityEngine.Networking;
 15using UnityEngine.UI;
 16
 17namespace DCL.Helpers
 18{
 19    public static class Utils
 20    {
 21        public static Dictionary<string, Material> staticMaterials;
 22
 23        public static Material EnsureResourcesMaterial(string path)
 24        {
 25            if (staticMaterials == null)
 26            {
 27                staticMaterials = new Dictionary<string, Material>();
 28            }
 29
 30            if (!staticMaterials.ContainsKey(path))
 31            {
 32                Material material = Resources.Load(path) as Material;
 33
 34                if (material != null)
 35                {
 36                    staticMaterials.Add(path, material);
 37                }
 38
 39                return material;
 40            }
 41
 42            return staticMaterials[path];
 43        }
 44
 45        public static void CleanMaterials(Renderer r)
 46        {
 47            if (r != null)
 48            {
 49                foreach (Material m in r.materials)
 50                {
 51                    if (m != null)
 52                    {
 53                        Material.Destroy(m);
 54                    }
 55                }
 56            }
 57        }
 58
 59        public static Vector2[] FloatArrayToV2List(float[] uvs)
 60        {
 61            Vector2[] uvsResult = new Vector2[uvs.Length / 2];
 62            int uvsResultIndex = 0;
 63
 64            for (int i = 0; i < uvs.Length;)
 65            {
 66                Vector2 tmpUv = Vector2.zero;
 67                tmpUv.x = uvs[i++];
 68                tmpUv.y = uvs[i++];
 69
 70                uvsResult[uvsResultIndex++] = tmpUv;
 71            }
 72
 73            return uvsResult;
 74        }
 75
 76        public static void ResetLocalTRS(this Transform t)
 77        {
 78            t.localPosition = Vector3.zero;
 79            t.localRotation = Quaternion.identity;
 80            t.localScale = Vector3.one;
 81        }
 82
 83        public static void SetToMaxStretch(this RectTransform t)
 84        {
 85            t.anchorMin = Vector2.zero;
 86            t.offsetMin = Vector2.zero;
 87            t.anchorMax = Vector2.one;
 88            t.offsetMax = Vector2.one;
 89            t.sizeDelta = Vector2.zero;
 90            t.anchoredPosition = Vector2.zero;
 91        }
 92
 93        public static void SetToCentered(this RectTransform t)
 94        {
 95            t.anchorMin = Vector2.one * 0.5f;
 96            t.offsetMin = Vector2.one * 0.5f;
 97            t.anchorMax = Vector2.one * 0.5f;
 98            t.offsetMax = Vector2.one * 0.5f;
 99            t.sizeDelta = Vector2.one * 100;
 100        }
 101
 102        public static void SetToBottomLeft(this RectTransform t)
 103        {
 104            t.anchorMin = Vector2.zero;
 105            t.offsetMin = Vector2.zero;
 106            t.anchorMax = Vector2.zero;
 107            t.offsetMax = Vector2.zero;
 108            t.sizeDelta = Vector2.one * 100;
 109        }
 110
 111        public static void ForceUpdateLayout(this RectTransform rt, bool delayed = true)
 112        {
 113            if (!rt.gameObject.activeInHierarchy)
 114                return;
 115
 116            if (delayed)
 117                CoroutineStarter.Start(ForceUpdateLayoutRoutine(rt));
 118            else
 119            {
 120                Utils.InverseTransformChildTraversal<RectTransform>(
 121                    (x) => { Utils.ForceRebuildLayoutImmediate(x); },
 122                    rt);
 123            }
 124        }
 125
 126        /// <summary>
 127        /// Reimplementation of the LayoutRebuilder.ForceRebuildLayoutImmediate() function (Unity UI API) for make it mo
 128        /// </summary>
 129        /// <param name="rectTransformRoot">Root from which to rebuild.</param>
 130        public static void ForceRebuildLayoutImmediate(RectTransform rectTransformRoot)
 131        {
 132            if (rectTransformRoot == null)
 133                return;
 134
 135            // NOTE(Santi): It seems to be very much cheaper to execute the next instructions manually than execute dire
 136            //              'LayoutRebuilder.ForceRebuildLayoutImmediate()', that theorically already contains these ins
 137            var layoutElements = rectTransformRoot.GetComponentsInChildren(typeof(ILayoutElement), true).ToList();
 138            layoutElements.RemoveAll(e => (e is Behaviour && !((Behaviour) e).isActiveAndEnabled) || e is TextMeshProUGU
 139            foreach (var layoutElem in layoutElements)
 140            {
 141                (layoutElem as ILayoutElement).CalculateLayoutInputHorizontal();
 142                (layoutElem as ILayoutElement).CalculateLayoutInputVertical();
 143            }
 144
 145            var layoutControllers = rectTransformRoot.GetComponentsInChildren(typeof(ILayoutController), true).ToList();
 146            layoutControllers.RemoveAll(e => e is Behaviour && !((Behaviour) e).isActiveAndEnabled);
 147            foreach (var layoutCtrl in layoutControllers)
 148            {
 149                (layoutCtrl as ILayoutController).SetLayoutHorizontal();
 150                (layoutCtrl as ILayoutController).SetLayoutVertical();
 151            }
 152        }
 153
 154        private static IEnumerator ForceUpdateLayoutRoutine(RectTransform rt)
 155        {
 156            yield return null;
 157
 158            Utils.InverseTransformChildTraversal<RectTransform>(
 159                (x) => { Utils.ForceRebuildLayoutImmediate(x); },
 160                rt);
 161        }
 162
 163        public static void InverseTransformChildTraversal<TComponent>(Action<TComponent> action, Transform startTransfor
 164            where TComponent : Component
 165        {
 166            if (startTransform == null)
 167                return;
 168
 169            foreach (Transform t in startTransform)
 170            {
 171                InverseTransformChildTraversal(action, t);
 172            }
 173
 174            var component = startTransform.GetComponent<TComponent>();
 175
 176            if (component != null)
 177            {
 178                action.Invoke(component);
 179            }
 180        }
 181
 182        public static void ForwardTransformChildTraversal<TComponent>(Func<TComponent, bool> action, Transform startTran
 183            where TComponent : Component
 184        {
 185            Assert.IsTrue(startTransform != null, "startTransform must not be null");
 186
 187            var component = startTransform.GetComponent<TComponent>();
 188
 189            if (component != null)
 190            {
 191                if (!action.Invoke(component))
 192                    return;
 193            }
 194
 195            foreach (Transform t in startTransform)
 196            {
 197                ForwardTransformChildTraversal(action, t);
 198            }
 199        }
 200
 201        public static T GetOrCreateComponent<T>(this GameObject gameObject) where T : UnityEngine.Component
 202        {
 203            T component = gameObject.GetComponent<T>();
 204
 205            if (!component)
 206            {
 207                return gameObject.AddComponent<T>();
 208            }
 209
 210            return component;
 211        }
 212
 213        public static WebRequestAsyncOperation FetchTexture(string textureURL, Action<Texture2D> OnSuccess, Action<Unity
 214        {
 215            //NOTE(Brian): This closure is called when the download is a success.
 216            void SuccessInternal(UnityWebRequest request)
 217            {
 218                var texture = DownloadHandlerTexture.GetContent(request);
 219                OnSuccess?.Invoke(texture);
 220            }
 221
 222            return DCL.Environment.i.platform.webRequest.GetTexture(
 223                url: textureURL,
 224                OnSuccess: SuccessInternal,
 225                OnFail: OnFail);
 226        }
 227
 228        public static bool SafeFromJsonOverwrite(string json, object objectToOverwrite)
 229        {
 230            try
 231            {
 232                JsonUtility.FromJsonOverwrite(json, objectToOverwrite);
 233            }
 234            catch (System.ArgumentException e)
 235            {
 236                Debug.LogError("ArgumentException Fail!... Json = " + json + " " + e.ToString());
 237                return false;
 238            }
 239
 240            return true;
 241        }
 242
 243        public static T FromJsonWithNulls<T>(string json) { return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json
 244
 245        public static T SafeFromJson<T>(string json)
 246        {
 247            ProfilingEvents.OnMessageDecodeStart?.Invoke("Misc");
 248
 249            T returningValue = default(T);
 250
 251            if (!string.IsNullOrEmpty(json))
 252            {
 253                try
 254                {
 255                    returningValue = JsonUtility.FromJson<T>(json);
 256                }
 257                catch (System.ArgumentException e)
 258                {
 259                    Debug.LogError("ArgumentException Fail!... Json = " + json + " " + e.ToString());
 260                }
 261            }
 262
 263            ProfilingEvents.OnMessageDecodeEnds?.Invoke("Misc");
 264
 265            return returningValue;
 266        }
 267
 268        public static GameObject AttachPlaceholderRendererGameObject(UnityEngine.Transform targetTransform)
 269        {
 270            var placeholderRenderer = GameObject.CreatePrimitive(PrimitiveType.Cube).GetComponent<MeshRenderer>();
 271
 272            placeholderRenderer.material = Resources.Load<Material>("Materials/AssetLoading");
 273            placeholderRenderer.transform.SetParent(targetTransform);
 274            placeholderRenderer.transform.localPosition = Vector3.zero;
 275            placeholderRenderer.name = "PlaceholderRenderer";
 276
 277            return placeholderRenderer.gameObject;
 278        }
 279
 280        public static void SafeDestroy(UnityEngine.Object obj)
 281        {
 282#if UNITY_EDITOR
 283            if (Application.isPlaying)
 284                UnityEngine.Object.Destroy(obj);
 285            else
 286                UnityEngine.Object.DestroyImmediate(obj, false);
 287#else
 288                UnityEngine.Object.Destroy(obj);
 289#endif
 290        }
 291
 292        /**
 293         * Transforms a grid position into a world-relative 3d position
 294         */
 295        public static Vector3 GridToWorldPosition(float xGridPosition, float yGridPosition)
 296        {
 297            return new Vector3(
 298                x: xGridPosition * ParcelSettings.PARCEL_SIZE,
 299                y: 0f,
 300                z: yGridPosition * ParcelSettings.PARCEL_SIZE
 301            );
 302        }
 303
 304        /**
 305         * Transforms a world position into a grid position
 306         */
 307        public static Vector2Int WorldToGridPosition(Vector3 worldPosition)
 308        {
 309            return new Vector2Int(
 310                (int) Mathf.Floor(worldPosition.x / ParcelSettings.PARCEL_SIZE),
 311                (int) Mathf.Floor(worldPosition.z / ParcelSettings.PARCEL_SIZE)
 312            );
 313        }
 314
 315        public static Vector2 WorldToGridPositionUnclamped(Vector3 worldPosition)
 316        {
 317            return new Vector2(
 318                worldPosition.x / ParcelSettings.PARCEL_SIZE,
 319                worldPosition.z / ParcelSettings.PARCEL_SIZE
 320            );
 321        }
 322
 323        public static bool AproxComparison(this Color color1, Color color2, float tolerance = 0.01f) // tolerance of rou
 324        {
 325            if (Mathf.Abs(color1.r - color2.r) < tolerance
 326                && Mathf.Abs(color1.g - color2.g) < tolerance
 327                && Mathf.Abs(color1.b - color2.b) < tolerance)
 328            {
 329                return true;
 330            }
 331
 332            return false;
 333        }
 334
 335        public static T ParseJsonArray<T>(string jsonArray) where T : IEnumerable => DummyJsonUtilityFromArray<T>.GetFro
 336
 337        [Serializable]
 338        private class DummyJsonUtilityFromArray<T> where T : IEnumerable //UnityEngine.JsonUtility is really fast but ca
 339        {
 340            [SerializeField]
 341            private T value;
 342
 343            public static T GetFromJsonArray(string jsonArray)
 344            {
 5345                string newJson = $"{{ \"value\": {jsonArray}}}";
 5346                return JsonUtility.FromJson<Utils.DummyJsonUtilityFromArray<T>>(newJson).value;
 347            }
 348        }
 349
 350        private static int lockedInFrame = -1;
 351        public static bool LockedThisFrame() => lockedInFrame == Time.frameCount;
 352
 353        //NOTE(Brian): Made as an independent flag because the CI doesn't work well with the Cursor.lockState check.
 354        public static bool isCursorLocked { get; private set; } = false;
 355
 356        public static void LockCursor()
 357        {
 358#if WEB_PLATFORM
 359            //TODO(Brian): Encapsulate all this mechanism to a new MouseLockController and branch
 360            //             behaviour using strategy pattern instead of this.
 361            if (isCursorLocked)
 362            {
 363                return;
 364            }
 365            if (requestedUnlock || requestedLock)
 366            {
 367                return;
 368            }
 369            requestedLock = true;
 370#else
 371            isCursorLocked = true;
 372            Cursor.visible = false;
 373#endif
 374            Cursor.lockState = CursorLockMode.Locked;
 375            lockedInFrame = Time.frameCount;
 376
 377            EventSystem.current?.SetSelectedGameObject(null);
 378        }
 379
 380        public static void UnlockCursor()
 381        {
 382#if WEB_PLATFORM
 383            //TODO(Brian): Encapsulate all this mechanism to a new MouseLockController and branch
 384            //             behaviour using strategy pattern instead of this.
 385            if (!isCursorLocked)
 386            {
 387                return;
 388            }
 389            if (requestedUnlock || requestedLock)
 390            {
 391                return;
 392            }
 393            requestedUnlock = true;
 394#else
 395            isCursorLocked = false;
 396            Cursor.visible = true;
 397#endif
 398            Cursor.lockState = CursorLockMode.None;
 399
 400            EventSystem.current?.SetSelectedGameObject(null);
 401        }
 402
 403        #region BROWSER_ONLY
 404
 405        //TODO(Brian): Encapsulate all this mechanism to a new MouseLockController and branch
 406        //             behaviour using strategy pattern instead of this.
 407        private static bool requestedUnlock = false;
 408        private static bool requestedLock = false;
 409
 410        // NOTE: This should come from browser's pointerlockchange callback
 411        public static void BrowserSetCursorState(bool locked)
 412        {
 413            if (!locked && !requestedUnlock)
 414            {
 415                Cursor.lockState = CursorLockMode.None;
 416            }
 417
 418            isCursorLocked = locked;
 419            Cursor.visible = !locked;
 420            requestedUnlock = false;
 421            requestedLock = false;
 422        }
 423
 424        #endregion
 425
 426        public static void DestroyAllChild(this Transform transform)
 427        {
 428            foreach (Transform child in transform)
 429            {
 430                UnityEngine.Object.Destroy(child.gameObject);
 431            }
 432        }
 433
 434        public static List<Vector2Int> GetBottomLeftZoneArray(Vector2Int bottomLeftAnchor, Vector2Int size)
 435        {
 436            List<Vector2Int> coords = new List<Vector2Int>();
 437
 438            for (int x = bottomLeftAnchor.x; x < bottomLeftAnchor.x + size.x; x++)
 439            {
 440                for (int y = bottomLeftAnchor.y; y < bottomLeftAnchor.y + size.y; y++)
 441                {
 442                    coords.Add(new Vector2Int(x, y));
 443                }
 444            }
 445
 446            return coords;
 447        }
 448
 449        public static List<Vector2Int> GetCenteredZoneArray(Vector2Int center, Vector2Int size)
 450        {
 451            List<Vector2Int> coords = new List<Vector2Int>();
 452
 453            for (int x = center.x - size.x; x < center.x + size.x; x++)
 454            {
 455                for (int y = center.y - size.y; y < center.y + size.y; y++)
 456                {
 457                    coords.Add(new Vector2Int(x, y));
 458                }
 459            }
 460
 461            return coords;
 462        }
 463
 464        public static void DrawRectGizmo(Rect rect, Color color, float duration)
 465        {
 466            Vector3 tl2 = new Vector3(rect.xMin, rect.yMax, 0);
 467            Vector3 bl2 = new Vector3(rect.xMin, rect.yMin, 0);
 468            Vector3 tr2 = new Vector3(rect.xMax, rect.yMax, 0);
 469            Vector3 br2 = new Vector3(rect.xMax, rect.yMin, 0);
 470
 471            Debug.DrawLine(tl2, bl2, color, duration);
 472            Debug.DrawLine(tl2, tr2, color, duration);
 473            Debug.DrawLine(bl2, br2, color, duration);
 474            Debug.DrawLine(tr2, br2, color, duration);
 475        }
 476
 477        public static string ToUpperFirst(this string value)
 478        {
 479            if (!string.IsNullOrEmpty(value))
 480            {
 481                var capital = char.ToUpper(value[0]);
 482                value = capital + value.Substring(1);
 483            }
 484
 485            return value;
 486        }
 487
 488        public static Vector3 Sanitize(Vector3 value)
 489        {
 490            float x = float.IsInfinity(value.x) ? 0 : value.x;
 491            float y = float.IsInfinity(value.y) ? 0 : value.y;
 492            float z = float.IsInfinity(value.z) ? 0 : value.z;
 493
 494            return new Vector3(x, y, z);
 495        }
 496
 497        public static bool CompareFloats( float a, float b, float precision = 0.1f ) { return Mathf.Abs(a - b) < precisi
 498
 499        public static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> tuple, out T1 key, out T2 value)
 500        {
 501            key = tuple.Key;
 502            value = tuple.Value;
 503        }
 504
 505        /// <summary>
 506        /// Set a layer to the given transform and its child
 507        /// </summary>
 508        /// <param name="transform"></param>
 509        public static void SetLayerRecursively(Transform transform, int layer)
 510        {
 511            transform.gameObject.layer = layer;
 512            foreach (Transform child in transform)
 513            {
 514                SetLayerRecursively(child, layer);
 515            }
 516        }
 517
 518        /// <summary>
 519        /// Converts a linear float (between 0 and 1) into an exponential curve fitting for audio volume.
 520        /// </summary>
 521        /// <param name="volume">Linear volume float</param>
 522        /// <returns>Exponential volume curve float</returns>
 523        public static float ToVolumeCurve(float volume) {
 524            return volume * (2f - volume);
 525        }
 526
 527        /// <summary>
 528        /// Takes a linear volume value between 0 and 1, converts to exponential curve and maps to a value fitting for a
 529        /// </summary>
 530        /// <param name="volume">Linear volume (0 to 1)</param>
 531        /// <returns>Value for audio mixer group volume</returns>
 532        public static float ToAudioMixerGroupVolume(float volume) {
 533            return (ToVolumeCurve(volume) * 80f) - 80f;
 534        }
 535    }
 536}

Methods/Properties

GetFromJsonArray(System.String)