< Summary

Class:DCL.Helpers.Utils
Assembly:Utils
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Helpers/Utils/Utils.cs
Covered lines:121
Uncovered lines:69
Coverable lines:190
Total lines:536
Line coverage:63.6% (121 of 190)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
EnsureResourcesMaterial(...)0%440100%
CleanMaterials(...)0%440100%
FloatArrayToV2List(...)0%220100%
ResetLocalTRS(...)0%110100%
SetToMaxStretch(...)0%110100%
SetToCentered(...)0%2100%
SetToBottomLeft(...)0%2100%
ForceUpdateLayout(...)0%440100%
ForceRebuildLayoutImmediate(...)0%660100%
ForceUpdateLayoutRoutine()0%440100%
InverseTransformChildTraversal[TComponent](...)0%550100%
ForwardTransformChildTraversal[TComponent](...)0%30500%
GetOrCreateComponent[T](...)0%220100%
FetchTexture(...)0%110100%
SafeFromJsonOverwrite(...)0%2100%
FromJsonWithNulls[T](...)0%110100%
SafeFromJson[T](...)0%4.434070%
AttachPlaceholderRendererGameObject(...)0%110100%
SafeDestroy(...)0%2.52050%
GridToWorldPosition(...)0%110100%
WorldToGridPosition(...)0%110100%
WorldToGridPositionUnclamped(...)0%110100%
AproxComparison(...)0%440100%
ParseJsonArray[T](...)0%110100%
Utils()0%110100%
LockedThisFrame()0%2100%
LockCursor()0%220100%
UnlockCursor()0%220100%
BrowserSetCursorState(...)0%12300%
DestroyAllChild(...)0%330100%
GetBottomLeftZoneArray(...)0%12300%
GetCenteredZoneArray(...)0%12300%
DrawRectGizmo(...)0%2100%
ToUpperFirst(...)0%6200%
Sanitize(...)0%770100%
CompareFloats(...)0%2100%
Deconstruct[T1, T2](...)0%110100%
SetLayerRecursively(...)0%330100%
ToVolumeCurve(...)0%2100%
ToAudioMixerGroupVolume(...)0%2100%

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        {
 89225            if (staticMaterials == null)
 26            {
 127                staticMaterials = new Dictionary<string, Material>();
 28            }
 29
 89230            if (!staticMaterials.ContainsKey(path))
 31            {
 432                Material material = Resources.Load(path) as Material;
 33
 434                if (material != null)
 35                {
 436                    staticMaterials.Add(path, material);
 37                }
 38
 439                return material;
 40            }
 41
 88842            return staticMaterials[path];
 43        }
 44
 45        public static void CleanMaterials(Renderer r)
 46        {
 12847            if (r != null)
 48            {
 51249                foreach (Material m in r.materials)
 50                {
 12851                    if (m != null)
 52                    {
 12853                        Material.Destroy(m);
 54                    }
 55                }
 56            }
 12857        }
 58
 59        public static Vector2[] FloatArrayToV2List(float[] uvs)
 60        {
 461            Vector2[] uvsResult = new Vector2[uvs.Length / 2];
 462            int uvsResultIndex = 0;
 63
 7264            for (int i = 0; i < uvs.Length;)
 65            {
 6466                Vector2 tmpUv = Vector2.zero;
 6467                tmpUv.x = uvs[i++];
 6468                tmpUv.y = uvs[i++];
 69
 6470                uvsResult[uvsResultIndex++] = tmpUv;
 71            }
 72
 473            return uvsResult;
 74        }
 75
 76        public static void ResetLocalTRS(this Transform t)
 77        {
 148178            t.localPosition = Vector3.zero;
 148179            t.localRotation = Quaternion.identity;
 148180            t.localScale = Vector3.one;
 148181        }
 82
 83        public static void SetToMaxStretch(this RectTransform t)
 84        {
 19985            t.anchorMin = Vector2.zero;
 19986            t.offsetMin = Vector2.zero;
 19987            t.anchorMax = Vector2.one;
 19988            t.offsetMax = Vector2.one;
 19989            t.sizeDelta = Vector2.zero;
 19990            t.anchoredPosition = Vector2.zero;
 19991        }
 92
 93        public static void SetToCentered(this RectTransform t)
 94        {
 095            t.anchorMin = Vector2.one * 0.5f;
 096            t.offsetMin = Vector2.one * 0.5f;
 097            t.anchorMax = Vector2.one * 0.5f;
 098            t.offsetMax = Vector2.one * 0.5f;
 099            t.sizeDelta = Vector2.one * 100;
 0100        }
 101
 102        public static void SetToBottomLeft(this RectTransform t)
 103        {
 0104            t.anchorMin = Vector2.zero;
 0105            t.offsetMin = Vector2.zero;
 0106            t.anchorMax = Vector2.zero;
 0107            t.offsetMax = Vector2.zero;
 0108            t.sizeDelta = Vector2.one * 100;
 0109        }
 110
 111        public static void ForceUpdateLayout(this RectTransform rt, bool delayed = true)
 112        {
 207113            if (!rt.gameObject.activeInHierarchy)
 12114                return;
 115
 195116            if (delayed)
 123117                CoroutineStarter.Start(ForceUpdateLayoutRoutine(rt));
 118            else
 119            {
 72120                Utils.InverseTransformChildTraversal<RectTransform>(
 1732121                    (x) => { Utils.ForceRebuildLayoutImmediate(x); },
 122                    rt);
 123            }
 72124        }
 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        {
 4583132            if (rectTransformRoot == null)
 3133                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
 4580137            var layoutElements = rectTransformRoot.GetComponentsInChildren(typeof(ILayoutElement), true).ToList();
 31515138            layoutElements.RemoveAll(e => (e is Behaviour && !((Behaviour) e).isActiveAndEnabled) || e is TextMeshProUGU
 21410139            foreach (var layoutElem in layoutElements)
 140            {
 6125141                (layoutElem as ILayoutElement).CalculateLayoutInputHorizontal();
 6125142                (layoutElem as ILayoutElement).CalculateLayoutInputVertical();
 143            }
 144
 4580145            var layoutControllers = rectTransformRoot.GetComponentsInChildren(typeof(ILayoutController), true).ToList();
 10077146            layoutControllers.RemoveAll(e => e is Behaviour && !((Behaviour) e).isActiveAndEnabled);
 14292147            foreach (var layoutCtrl in layoutControllers)
 148            {
 2566149                (layoutCtrl as ILayoutController).SetLayoutHorizontal();
 2566150                (layoutCtrl as ILayoutController).SetLayoutVertical();
 151            }
 4580152        }
 153
 154        private static IEnumerator ForceUpdateLayoutRoutine(RectTransform rt)
 155        {
 123156            yield return null;
 157
 123158            Utils.InverseTransformChildTraversal<RectTransform>(
 5866159                (x) => { Utils.ForceRebuildLayoutImmediate(x); },
 160                rt);
 123161        }
 162
 163        public static void InverseTransformChildTraversal<TComponent>(Action<TComponent> action, Transform startTransfor
 164            where TComponent : Component
 165        {
 7885166            if (startTransform == null)
 75167                return;
 168
 30362169            foreach (Transform t in startTransform)
 170            {
 7371171                InverseTransformChildTraversal(action, t);
 172            }
 173
 7810174            var component = startTransform.GetComponent<TComponent>();
 175
 7810176            if (component != null)
 177            {
 4695178                action.Invoke(component);
 179            }
 7810180        }
 181
 182        public static void ForwardTransformChildTraversal<TComponent>(Func<TComponent, bool> action, Transform startTran
 183            where TComponent : Component
 184        {
 0185            Assert.IsTrue(startTransform != null, "startTransform must not be null");
 186
 0187            var component = startTransform.GetComponent<TComponent>();
 188
 0189            if (component != null)
 190            {
 0191                if (!action.Invoke(component))
 0192                    return;
 193            }
 194
 0195            foreach (Transform t in startTransform)
 196            {
 0197                ForwardTransformChildTraversal(action, t);
 198            }
 0199        }
 200
 201        public static T GetOrCreateComponent<T>(this GameObject gameObject) where T : UnityEngine.Component
 202        {
 74203            T component = gameObject.GetComponent<T>();
 204
 74205            if (!component)
 206            {
 63207                return gameObject.AddComponent<T>();
 208            }
 209
 11210            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            {
 0218                var texture = DownloadHandlerTexture.GetContent(request);
 0219                OnSuccess?.Invoke(texture);
 0220            }
 221
 49222            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            {
 0232                JsonUtility.FromJsonOverwrite(json, objectToOverwrite);
 0233            }
 0234            catch (System.ArgumentException e)
 235            {
 0236                Debug.LogError("ArgumentException Fail!... Json = " + json + " " + e.ToString());
 0237                return false;
 238            }
 239
 0240            return true;
 0241        }
 242
 60243        public static T FromJsonWithNulls<T>(string json) { return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json
 244
 245        public static T SafeFromJson<T>(string json)
 246        {
 719247            ProfilingEvents.OnMessageDecodeStart?.Invoke("Misc");
 248
 719249            T returningValue = default(T);
 250
 719251            if (!string.IsNullOrEmpty(json))
 252            {
 253                try
 254                {
 718255                    returningValue = JsonUtility.FromJson<T>(json);
 718256                }
 0257                catch (System.ArgumentException e)
 258                {
 0259                    Debug.LogError("ArgumentException Fail!... Json = " + json + " " + e.ToString());
 0260                }
 261            }
 262
 719263            ProfilingEvents.OnMessageDecodeEnds?.Invoke("Misc");
 264
 719265            return returningValue;
 266        }
 267
 268        public static GameObject AttachPlaceholderRendererGameObject(UnityEngine.Transform targetTransform)
 269        {
 1270            var placeholderRenderer = GameObject.CreatePrimitive(PrimitiveType.Cube).GetComponent<MeshRenderer>();
 271
 1272            placeholderRenderer.material = Resources.Load<Material>("Materials/AssetLoading");
 1273            placeholderRenderer.transform.SetParent(targetTransform);
 1274            placeholderRenderer.transform.localPosition = Vector3.zero;
 1275            placeholderRenderer.name = "PlaceholderRenderer";
 276
 1277            return placeholderRenderer.gameObject;
 278        }
 279
 280        public static void SafeDestroy(UnityEngine.Object obj)
 281        {
 282#if UNITY_EDITOR
 629283            if (Application.isPlaying)
 629284                UnityEngine.Object.Destroy(obj);
 285            else
 0286                UnityEngine.Object.DestroyImmediate(obj, false);
 287#else
 288                UnityEngine.Object.Destroy(obj);
 289#endif
 0290        }
 291
 292        /**
 293         * Transforms a grid position into a world-relative 3d position
 294         */
 295        public static Vector3 GridToWorldPosition(float xGridPosition, float yGridPosition)
 296        {
 1685297            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        {
 19221309            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        {
 343317            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        {
 2968325            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            {
 289329                return true;
 330            }
 331
 2679332            return false;
 333        }
 334
 5335        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            {
 345                string newJson = $"{{ \"value\": {jsonArray}}}";
 346                return JsonUtility.FromJson<Utils.DummyJsonUtilityFromArray<T>>(newJson).value;
 347            }
 348        }
 349
 1350        private static int lockedInFrame = -1;
 0351        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.
 1354        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
 20371            isCursorLocked = true;
 20372            Cursor.visible = false;
 373#endif
 20374            Cursor.lockState = CursorLockMode.Locked;
 20375            lockedInFrame = Time.frameCount;
 376
 20377            EventSystem.current?.SetSelectedGameObject(null);
 20378        }
 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
 146395            isCursorLocked = false;
 146396            Cursor.visible = true;
 397#endif
 146398            Cursor.lockState = CursorLockMode.None;
 399
 146400            EventSystem.current?.SetSelectedGameObject(null);
 146401        }
 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.
 1407        private static bool requestedUnlock = false;
 1408        private static bool requestedLock = false;
 409
 410        // NOTE: This should come from browser's pointerlockchange callback
 411        public static void BrowserSetCursorState(bool locked)
 412        {
 0413            if (!locked && !requestedUnlock)
 414            {
 0415                Cursor.lockState = CursorLockMode.None;
 416            }
 417
 0418            isCursorLocked = locked;
 0419            Cursor.visible = !locked;
 0420            requestedUnlock = false;
 0421            requestedLock = false;
 0422        }
 423
 424        #endregion
 425
 426        public static void DestroyAllChild(this Transform transform)
 427        {
 82428            foreach (Transform child in transform)
 429            {
 3430                UnityEngine.Object.Destroy(child.gameObject);
 431            }
 38432        }
 433
 434        public static List<Vector2Int> GetBottomLeftZoneArray(Vector2Int bottomLeftAnchor, Vector2Int size)
 435        {
 0436            List<Vector2Int> coords = new List<Vector2Int>();
 437
 0438            for (int x = bottomLeftAnchor.x; x < bottomLeftAnchor.x + size.x; x++)
 439            {
 0440                for (int y = bottomLeftAnchor.y; y < bottomLeftAnchor.y + size.y; y++)
 441                {
 0442                    coords.Add(new Vector2Int(x, y));
 443                }
 444            }
 445
 0446            return coords;
 447        }
 448
 449        public static List<Vector2Int> GetCenteredZoneArray(Vector2Int center, Vector2Int size)
 450        {
 0451            List<Vector2Int> coords = new List<Vector2Int>();
 452
 0453            for (int x = center.x - size.x; x < center.x + size.x; x++)
 454            {
 0455                for (int y = center.y - size.y; y < center.y + size.y; y++)
 456                {
 0457                    coords.Add(new Vector2Int(x, y));
 458                }
 459            }
 460
 0461            return coords;
 462        }
 463
 464        public static void DrawRectGizmo(Rect rect, Color color, float duration)
 465        {
 0466            Vector3 tl2 = new Vector3(rect.xMin, rect.yMax, 0);
 0467            Vector3 bl2 = new Vector3(rect.xMin, rect.yMin, 0);
 0468            Vector3 tr2 = new Vector3(rect.xMax, rect.yMax, 0);
 0469            Vector3 br2 = new Vector3(rect.xMax, rect.yMin, 0);
 470
 0471            Debug.DrawLine(tl2, bl2, color, duration);
 0472            Debug.DrawLine(tl2, tr2, color, duration);
 0473            Debug.DrawLine(bl2, br2, color, duration);
 0474            Debug.DrawLine(tr2, br2, color, duration);
 0475        }
 476
 477        public static string ToUpperFirst(this string value)
 478        {
 0479            if (!string.IsNullOrEmpty(value))
 480            {
 0481                var capital = char.ToUpper(value[0]);
 0482                value = capital + value.Substring(1);
 483            }
 484
 0485            return value;
 486        }
 487
 488        public static Vector3 Sanitize(Vector3 value)
 489        {
 267490            float x = float.IsInfinity(value.x) ? 0 : value.x;
 267491            float y = float.IsInfinity(value.y) ? 0 : value.y;
 267492            float z = float.IsInfinity(value.z) ? 0 : value.z;
 493
 267494            return new Vector3(x, y, z);
 495        }
 496
 0497        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        {
 15501            key = tuple.Key;
 15502            value = tuple.Value;
 15503        }
 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        {
 610511            transform.gameObject.layer = layer;
 2404512            foreach (Transform child in transform)
 513            {
 592514                SetLayerRecursively(child, layer);
 515            }
 610516        }
 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) {
 0524            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) {
 0533            return (ToVolumeCurve(volume) * 80f) - 80f;
 534        }
 535    }
 536}

Methods/Properties

EnsureResourcesMaterial(System.String)
CleanMaterials(UnityEngine.Renderer)
FloatArrayToV2List(System.Single[])
ResetLocalTRS(UnityEngine.Transform)
SetToMaxStretch(UnityEngine.RectTransform)
SetToCentered(UnityEngine.RectTransform)
SetToBottomLeft(UnityEngine.RectTransform)
ForceUpdateLayout(UnityEngine.RectTransform, System.Boolean)
ForceRebuildLayoutImmediate(UnityEngine.RectTransform)
ForceUpdateLayoutRoutine()
InverseTransformChildTraversal[TComponent](System.Action[TComponent], UnityEngine.Transform)
ForwardTransformChildTraversal[TComponent](System.Func[TComponent,Boolean], UnityEngine.Transform)
GetOrCreateComponent[T](UnityEngine.GameObject)
FetchTexture(System.String, System.Action[Texture2D], System.Action[UnityWebRequest])
SafeFromJsonOverwrite(System.String, System.Object)
FromJsonWithNulls[T](System.String)
SafeFromJson[T](System.String)
AttachPlaceholderRendererGameObject(UnityEngine.Transform)
SafeDestroy(UnityEngine.Object)
GridToWorldPosition(System.Single, System.Single)
WorldToGridPosition(UnityEngine.Vector3)
WorldToGridPositionUnclamped(UnityEngine.Vector3)
AproxComparison(UnityEngine.Color, UnityEngine.Color, System.Single)
ParseJsonArray[T](System.String)
Utils()
LockedThisFrame()
isCursorLocked()
isCursorLocked(System.Boolean)
LockCursor()
UnlockCursor()
BrowserSetCursorState(System.Boolean)
DestroyAllChild(UnityEngine.Transform)
GetBottomLeftZoneArray(UnityEngine.Vector2Int, UnityEngine.Vector2Int)
GetCenteredZoneArray(UnityEngine.Vector2Int, UnityEngine.Vector2Int)
DrawRectGizmo(UnityEngine.Rect, UnityEngine.Color, System.Single)
ToUpperFirst(System.String)
Sanitize(UnityEngine.Vector3)
CompareFloats(System.Single, System.Single, System.Single)
Deconstruct[T1, T2](System.Collections.Generic.KeyValuePair[T1,T2], , )
SetLayerRecursively(UnityEngine.Transform, System.Int32)
ToVolumeCurve(System.Single)
ToAudioMixerGroupVolume(System.Single)