< Summary

Class:PlayerAvatarController
Assembly:PlayerAvatarController
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Controllers/PlayerAvatarController/PlayerAvatarController.cs
Covered lines:50
Uncovered lines:67
Coverable lines:117
Total lines:306
Line coverage:42.7% (50 of 117)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
PlayerAvatarController()0%110100%
Start()0%3.113076.92%
GetStandardAvatar()0%110100%
GetAvatarWithHologram()0%2100%
OnBaseWereablesFail()0%6200%
ShowWearablesWarning()0%2100%
Update()0%24.436020%
SetAvatarVisibility(...)0%220100%
OnEnable()0%110100%
OnAvatarEmote(...)0%3.023087.5%
OnUserProfileOnUpdate(...)0%330100%
LoadingAvatarRoutine()0%108.4712012.5%
ApplyHideAvatarModifier()0%6200%
RemoveHideAvatarModifier()0%6200%
ApplyHidePassportModifier()0%2100%
RemoveHidePassportModifier()0%2100%
OnDisable()0%110100%
OnDestroy()0%440100%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Controllers/PlayerAvatarController/PlayerAvatarController.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Threading;
 5using AvatarSystem;
 6using Cysharp.Threading.Tasks;
 7using DCL;
 8using DCL.Emotes;
 9using DCL.FatalErrorReporter;
 10using DCL.Interface;
 11using DCL.NotificationModel;
 12using GPUSkinning;
 13using SocialFeaturesAnalytics;
 14using UnityEngine;
 15using Environment = DCL.Environment;
 16using Type = DCL.NotificationModel.Type;
 17
 18public class PlayerAvatarController : MonoBehaviour, IHideAvatarAreaHandler, IHidePassportAreaHandler
 19{
 20    private const string LOADING_WEARABLES_ERROR_MESSAGE = "There was a problem loading your wearables";
 21    private const string IN_HIDE_AREA = "IN_HIDE_AREA";
 22    private const string INSIDE_CAMERA = "INSIDE_CAMERA";
 23
 24    private IAvatar avatar;
 25    private CancellationTokenSource avatarLoadingCts = null;
 26    public GameObject avatarContainer;
 27    public GameObject armatureContainer;
 28    public Transform loadingAvatarContainer;
 29    public StickersController stickersControllers;
 61030    private readonly AvatarModel currentAvatar = new AvatarModel { wearables = new List<string>() };
 31
 32    public Collider avatarCollider;
 33    [SerializeField] private GameObject loadingParticlesPrefab;
 61034    public float cameraDistanceToDeactivate = 1.0f;
 35
 229236    private UserProfile userProfile => UserProfile.GetOwnUserProfile();
 037    private bool repositioningWorld => DCLCharacterController.i.characterPosition.RepositionedWorldLastFrame();
 38
 39    private bool enableCameraCheck = false;
 40    private Camera mainCamera;
 41    private IFatalErrorReporter fatalErrorReporter; // TODO?
 42    private string VISIBILITY_CONSTRAIN;
 43    private BaseRefCounter<AvatarModifierAreaID> currentActiveModifiers;
 44
 45    internal ISocialAnalytics socialAnalytics;
 46
 47    private void Start()
 48    {
 57249        DataStore.i.common.isPlayerRendererLoaded.Set(false);
 57250        socialAnalytics = new SocialAnalytics(
 51            DCL.Environment.i.platform.serviceProviders.analytics,
 52            new UserProfileWebInterfaceBridge());
 53
 57254        if (DataStore.i.avatarConfig.useHologramAvatar.Get())
 055            avatar = GetAvatarWithHologram();
 56        else
 57257            avatar = GetStandardAvatar();
 58
 57259        if ( UserProfileController.i != null )
 60        {
 061            UserProfileController.i.OnBaseWereablesFail -= OnBaseWereablesFail;
 062            UserProfileController.i.OnBaseWereablesFail += OnBaseWereablesFail;
 63        }
 64
 57265        CommonScriptableObjects.rendererState.AddLock(this);
 66
 67#if UNITY_WEBGL
 57268        fatalErrorReporter = new WebFatalErrorReporter();
 69#else
 70        fatalErrorReporter = new DefaultFatalErrorReporter(DataStore.i);
 71#endif
 72
 57273        mainCamera = Camera.main;
 57274        currentActiveModifiers = new BaseRefCounter<AvatarModifierAreaID>();
 57275    }
 76
 77    private AvatarSystem.Avatar GetStandardAvatar()
 78    {
 57279        AvatarAnimatorLegacy animator = GetComponentInChildren<AvatarAnimatorLegacy>();
 57280        AvatarSystem.NoLODs noLod = new NoLODs();
 57281        return new AvatarSystem.Avatar(
 82            new AvatarCurator(new WearableItemResolver(), Environment.i.serviceLocator.Get<IEmotesCatalogService>()),
 83            new Loader(new WearableLoaderFactory(), avatarContainer, new AvatarMeshCombinerHelper()),
 84            animator,
 85            new Visibility(),
 86            noLod,
 87            new SimpleGPUSkinning(),
 88            new GPUSkinningThrottler(),
 89            new EmoteAnimationEquipper(animator, DataStore.i.emotes));
 90    }
 91
 92    private AvatarWithHologram GetAvatarWithHologram()
 93    {
 094        AvatarAnimatorLegacy animator = GetComponentInChildren<AvatarAnimatorLegacy>();
 095        AvatarSystem.NoLODs noLod = new NoLODs();
 096        BaseAvatar baseAvatar = new BaseAvatar(loadingAvatarContainer, armatureContainer, noLod);
 097        return new AvatarSystem.AvatarWithHologram(
 98            baseAvatar,
 99            new AvatarCurator(new WearableItemResolver(), Environment.i.serviceLocator.Get<IEmotesCatalogService>()),
 100            new Loader(new WearableLoaderFactory(), avatarContainer, new AvatarMeshCombinerHelper()),
 101            animator,
 102            new Visibility(),
 103            noLod,
 104            new SimpleGPUSkinning(),
 105            new GPUSkinningThrottler(),
 106            new EmoteAnimationEquipper(animator, DataStore.i.emotes));
 107    }
 108
 109    private void OnBaseWereablesFail()
 110    {
 0111        UserProfileController.i.OnBaseWereablesFail -= OnBaseWereablesFail;
 112
 0113        if (enableCameraCheck)
 0114            ShowWearablesWarning();
 0115    }
 116
 117    private void ShowWearablesWarning()
 118    {
 0119        NotificationsController.i.ShowNotification(new Model
 120        {
 121            message = LOADING_WEARABLES_ERROR_MESSAGE,
 122            type = Type.GENERIC,
 123            timer = 10f,
 124            destroyOnFinish = true
 125        });
 0126    }
 127
 128    private void Update()
 129    {
 5327130        if (!enableCameraCheck || repositioningWorld)
 5327131            return;
 132
 0133        if (mainCamera == null)
 134        {
 0135            mainCamera = Camera.main;
 136
 0137            if (mainCamera == null)
 0138                return;
 139        }
 140
 0141        if (Vector3.Distance(mainCamera.transform.position, transform.position) > cameraDistanceToDeactivate)
 0142            avatar.RemoveVisibilityConstrain(INSIDE_CAMERA);
 143        else
 0144            avatar.AddVisibilityConstraint(INSIDE_CAMERA);
 0145    }
 146
 147    public void SetAvatarVisibility(bool isVisible)
 148    {
 6149        VISIBILITY_CONSTRAIN = "own_player_invisible";
 6150        if (isVisible)
 1151            avatar.RemoveVisibilityConstrain(VISIBILITY_CONSTRAIN);
 152        else
 5153            avatar.AddVisibilityConstraint(VISIBILITY_CONSTRAIN);
 5154    }
 155
 156    private void OnEnable()
 157    {
 573158        userProfile.OnUpdate += OnUserProfileOnUpdate;
 573159        userProfile.OnAvatarEmoteSet += OnAvatarEmote;
 573160    }
 161
 162    private void OnAvatarEmote(string id, long timestamp, UserProfile.EmoteSource source)
 163    {
 1164        avatar.PlayEmote(id, timestamp);
 165
 1166        bool found = DataStore.i.common.wearables.TryGetValue(id, out WearableItem emoteItem);
 1167        if (!found)
 168        {
 1169            var emotesCatalog = Environment.i.serviceLocator.Get<IEmotesCatalogService>();
 1170            emotesCatalog.TryGetLoadedEmote(id, out emoteItem);
 171        }
 172
 1173        if (emoteItem != null)
 174        {
 0175            socialAnalytics.SendPlayEmote(
 176                emoteItem.id,
 177                emoteItem.GetName(),
 178                emoteItem.rarity,
 179                emoteItem.data.tags.Contains(WearableLiterals.Tags.BASE_WEARABLE),
 180                source,
 181                $"{CommonScriptableObjects.playerCoords.Get().x},{CommonScriptableObjects.playerCoords.Get().y}");
 182        }
 1183    }
 184
 185    private void OnUserProfileOnUpdate(UserProfile profile)
 186    {
 7187        avatarLoadingCts?.Cancel();
 7188        avatarLoadingCts?.Dispose();
 7189        avatarLoadingCts = new CancellationTokenSource();
 7190        LoadingAvatarRoutine(profile, avatarLoadingCts.Token);
 7191    }
 192
 193    private async UniTaskVoid LoadingAvatarRoutine(UserProfile profile, CancellationToken ct)
 194    {
 7195        if (string.IsNullOrEmpty(profile.avatar.bodyShape) || profile.avatar.wearables == null)
 196        {
 7197            avatar.Dispose();
 7198            return;
 199        }
 200
 201        try
 202        {
 0203            ct.ThrowIfCancellationRequested();
 0204            if (avatar.status != IAvatar.Status.Loaded || !profile.avatar.HaveSameWearablesAndColors(currentAvatar))
 205            {
 0206                currentAvatar.CopyFrom(profile.avatar);
 207
 0208                List<string> wearableItems = profile.avatar.wearables.ToList();
 0209                wearableItems.Add(profile.avatar.bodyShape);
 210
 0211                HashSet<string> emotes = new HashSet<string>(currentAvatar.emotes.Select(x => x.urn));
 0212                var embeddedEmotesSo = Resources.Load<EmbeddedEmotesSO>("EmbeddedEmotes");
 0213                emotes.UnionWith(embeddedEmotesSo.emotes.Select(x => x.id));
 0214                wearableItems.AddRange(embeddedEmotesSo.emotes.Select(x => x.id));
 215
 0216                await avatar.Load(wearableItems, emotes.ToList(), new AvatarSettings
 217                {
 218                    bodyshapeId = profile.avatar.bodyShape,
 219                    eyesColor = profile.avatar.eyeColor,
 220                    skinColor = profile.avatar.skinColor,
 221                    hairColor = profile.avatar.hairColor,
 222                }, ct);
 223
 0224                if (avatar.lodLevel <= 1)
 0225                    AvatarSystemUtils.SpawnAvatarLoadedParticles(avatarContainer.transform, loadingParticlesPrefab);
 226            }
 0227        }
 0228        catch (OperationCanceledException)
 229        {
 0230            return;
 231        }
 232        catch (Exception e)
 233        {
 0234            Debug.LogException(e);
 0235            WebInterface.ReportAvatarFatalError();
 0236            return;
 237        }
 238
 0239        IAvatarAnchorPoints anchorPoints = new AvatarAnchorPoints();
 0240        anchorPoints.Prepare(avatarContainer.transform, avatar.GetBones(), AvatarSystemUtils.AVATAR_Y_OFFSET + avatar.ex
 241
 0242        var player = new Player()
 243        {
 244            id = userProfile.userId,
 245            name = userProfile.name,
 246            avatar = avatar,
 247            anchorPoints = anchorPoints,
 248            collider = avatarCollider
 249        };
 0250        DataStore.i.player.ownPlayer.Set(player);
 251
 0252        enableCameraCheck = true;
 0253        avatarCollider.gameObject.SetActive(true);
 0254        CommonScriptableObjects.rendererState.RemoveLock(this);
 0255        DataStore.i.common.isPlayerRendererLoaded.Set(true);
 7256    }
 257
 258    public void ApplyHideAvatarModifier()
 259    {
 0260        if (!currentActiveModifiers.ContainsKey(AvatarModifierAreaID.HIDE_AVATAR))
 261        {
 0262            avatar.AddVisibilityConstraint(IN_HIDE_AREA);
 0263            stickersControllers.ToggleHideArea(true);
 264        }
 0265        currentActiveModifiers.AddRefCount(AvatarModifierAreaID.HIDE_AVATAR);
 0266        DataStore.i.HUDs.avatarAreaWarnings.AddRefCount(AvatarModifierAreaID.HIDE_AVATAR);
 0267    }
 268
 269    public void RemoveHideAvatarModifier()
 270    {
 0271        DataStore.i.HUDs.avatarAreaWarnings.RemoveRefCount(AvatarModifierAreaID.HIDE_AVATAR);
 0272        currentActiveModifiers.RemoveRefCount(AvatarModifierAreaID.HIDE_AVATAR);
 0273        if (!currentActiveModifiers.ContainsKey(AvatarModifierAreaID.HIDE_AVATAR))
 274        {
 0275            avatar.RemoveVisibilityConstrain(IN_HIDE_AREA);
 0276            stickersControllers.ToggleHideArea(false);
 277        }
 0278    }
 279
 280    public void ApplyHidePassportModifier()
 281    {
 0282        DataStore.i.HUDs.avatarAreaWarnings.AddRefCount(AvatarModifierAreaID.DISABLE_PASSPORT);
 0283        currentActiveModifiers.AddRefCount(AvatarModifierAreaID.DISABLE_PASSPORT);
 0284    }
 285
 286    public void RemoveHidePassportModifier()
 287    {
 0288        DataStore.i.HUDs.avatarAreaWarnings.RemoveRefCount(AvatarModifierAreaID.DISABLE_PASSPORT);
 0289        currentActiveModifiers.RemoveRefCount(AvatarModifierAreaID.DISABLE_PASSPORT);
 0290    }
 291
 292    private void OnDisable()
 293    {
 573294        userProfile.OnUpdate -= OnUserProfileOnUpdate;
 573295        userProfile.OnAvatarEmoteSet -= OnAvatarEmote;
 573296    }
 297
 298    private void OnDestroy()
 299    {
 596300        avatarLoadingCts?.Cancel();
 596301        avatarLoadingCts?.Dispose();
 596302        avatarLoadingCts = null;
 596303        avatar?.Dispose();
 572304    }
 305
 306}