< Summary

Class:DCL.SceneController
Assembly:DCL.Runtime
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/WorldRuntime/SceneController.cs
Covered lines:191
Uncovered lines:151
Coverable lines:342
Total lines:869
Line coverage:55.8% (191 of 342)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
SceneController()0%110100%
Initialize()0%22093.33%
SetupDeferredRunners()0%110100%
PrewarmSceneMessagesPool()0%20400%
OnDebugModeSet(...)0%4.123050%
Dispose()0%220100%
Update()0%440100%
LateUpdate()0%220100%
ProcessMessage(...)0%10.3410085%
ProcessMessage(...)0%1378.3246014.29%
ParseQuery(...)0%12300%
SendSceneMessage(...)0%6200%
Decode(...)0%20400%
DeferredDecodingAndEnqueue()0%7.777075%
EnqueueChunk(...)0%12300%
WatchForNewChunksToDecode()0%30500%
ThreadedDecodeAndEnqueue(...)0%20400%
EnqueueSceneMessage(...)0%110100%
SendSceneReady(...)0%2.022083.33%
ActivateBuilderInWorldEditScene()0%2100%
DeactivateBuilderInWorldEditScene()0%2100%
SetPositionDirty(...)0%4.054085.71%
SortScenesByDistance()0%440100%
OnCurrentSceneNumberChange(...)0%440100%
LoadParcelScenesExecute(...)0%16.1514077.78%
UpdateParcelScenesExecute(...)0%20400%
UpdateParcelScenesExecute(...)0%42600%
UnloadScene(...)0%220100%
UnloadParcelSceneExecute(...)0%6.116085.71%
UnloadAllScenes(...)0%440100%
LoadParcelScenes(...)0%3.043083.33%
UpdateParcelScenes(...)0%6200%
UnloadAllScenesQueued()0%6200%
CreateGlobalScene(...)0%10.8910079.31%
IsolateScene(...)0%3.043083.33%
ReIntegrateIsolatedScene()0%220100%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/WorldRuntime/SceneController.cs

#LineLine coverage
 1using DCL.Controllers;
 2using DCL.Helpers;
 3using DCL.Interface;
 4using DCL.Models;
 5using DCL.Configuration;
 6using System;
 7using System.Collections;
 8using System.Collections.Concurrent;
 9using System.ComponentModel;
 10using System.Linq;
 11using System.Threading;
 12using Cysharp.Threading.Tasks;
 13using DCL.Components;
 14using DCL.CRDT;
 15using UnityEngine;
 16using Debug = UnityEngine.Debug;
 17
 18namespace DCL
 19{
 20    public class SceneController : ISceneController
 21    {
 22        public static bool VERBOSE = false;
 23        const int SCENE_MESSAGES_PREWARM_COUNT = 100000;
 24
 5822225        public bool enabled { get; set; } = true;
 226        internal BaseVariable<Transform> isPexViewerInitialized => DataStore.i.experiencesViewer.isInitialized;
 27
 28        //TODO(Brian): Move to WorldRuntimePlugin later
 29        private LoadingFeedbackController loadingFeedbackController;
 30        private Coroutine deferredDecodingCoroutine;
 31
 32        private CancellationTokenSource tokenSource;
 68433        private IMessagingControllersManager messagingControllersManager => Environment.i.messaging.manager;
 34
 57735        public EntityIdHelper entityIdHelper { get; } = new EntityIdHelper();
 36
 37        public void Initialize()
 38        {
 57739            tokenSource = new CancellationTokenSource();
 57740            sceneSortDirty = true;
 57741            positionDirty = true;
 57742            lastSortFrame = 0;
 57743            enabled = true;
 44
 57745            loadingFeedbackController = new LoadingFeedbackController();
 46
 57747            DataStore.i.debugConfig.isDebugMode.OnChange += OnDebugModeSet;
 48
 57749            SetupDeferredRunners();
 50
 57751            DataStore.i.player.playerGridPosition.OnChange += SetPositionDirty;
 57752            CommonScriptableObjects.sceneNumber.OnChange += OnCurrentSceneNumberChange;
 53
 54            // TODO(Brian): Move this later to Main.cs
 57755            if ( !EnvironmentSettings.RUNNING_TESTS )
 56            {
 057                PrewarmSceneMessagesPool();
 58            }
 59
 57760            Environment.i.platform.updateEventHandler.AddListener(IUpdateEventHandler.EventType.Update, Update);
 57761            Environment.i.platform.updateEventHandler.AddListener(IUpdateEventHandler.EventType.LateUpdate, LateUpdate);
 57762        }
 63        private void SetupDeferredRunners()
 64        {
 65#if UNITY_WEBGL
 57766            deferredDecodingCoroutine = CoroutineStarter.Start(DeferredDecodingAndEnqueue());
 67#else
 68            CancellationToken tokenSourceToken = tokenSource.Token;
 69            TaskUtils.Run(async () => await WatchForNewChunksToDecode(tokenSourceToken), cancellationToken: tokenSourceT
 70#endif
 57771        }
 72
 73        private void PrewarmSceneMessagesPool()
 74        {
 075            if (prewarmSceneMessagesPool)
 76            {
 077                for (int i = 0; i < SCENE_MESSAGES_PREWARM_COUNT; i++)
 78                {
 079                    sceneMessagesPool.Enqueue(new QueuedSceneMessage_Scene());
 80                }
 81            }
 82
 083            if (prewarmEntitiesPool)
 84            {
 085                PoolManagerFactory.EnsureEntityPool(prewarmEntitiesPool);
 86            }
 087        }
 88
 89        private void OnDebugModeSet(bool current, bool previous)
 90        {
 2991            if (current == previous)
 092                return;
 93
 2994            if (current)
 95            {
 2996                Environment.i.world.sceneBoundsChecker.SetFeedbackStyle(new SceneBoundsFeedbackStyle_RedBox());
 97            }
 98            else
 99            {
 0100                Environment.i.world.sceneBoundsChecker.SetFeedbackStyle(new SceneBoundsFeedbackStyle_Simple());
 101            }
 0102        }
 103
 104        public void Dispose()
 105        {
 577106            tokenSource.Cancel();
 577107            tokenSource.Dispose();
 577108            loadingFeedbackController.Dispose();
 109
 577110            Environment.i.platform.updateEventHandler.RemoveListener(IUpdateEventHandler.EventType.Update, Update);
 577111            Environment.i.platform.updateEventHandler.RemoveListener(IUpdateEventHandler.EventType.LateUpdate, LateUpdat
 112
 577113            PoolManager.i.OnGet -= Environment.i.platform.physicsSyncController.MarkDirty;
 577114            PoolManager.i.OnGet -= Environment.i.platform.cullingController.objectsTracker.MarkDirty;
 115
 577116            DataStore.i.player.playerGridPosition.OnChange -= SetPositionDirty;
 577117            DataStore.i.debugConfig.isDebugMode.OnChange -= OnDebugModeSet;
 118
 577119            CommonScriptableObjects.sceneNumber.OnChange -= OnCurrentSceneNumberChange;
 120
 577121            UnloadAllScenes(includePersistent: true);
 122
 577123            if (deferredDecodingCoroutine != null)
 577124                CoroutineStarter.Stop(deferredDecodingCoroutine);
 577125        }
 126
 127        public void Update()
 128        {
 28522129            if (!enabled)
 2827130                return;
 131
 25695132            if (lastSortFrame != Time.frameCount && sceneSortDirty)
 133            {
 576134                lastSortFrame = Time.frameCount;
 576135                sceneSortDirty = false;
 576136                SortScenesByDistance();
 137            }
 25695138        }
 139
 140        public void LateUpdate()
 141        {
 28522142            if (!enabled)
 2827143                return;
 144
 25695145            Environment.i.platform.physicsSyncController.Sync();
 25695146        }
 147
 148        //======================================================================
 149
 150        #region MESSAGES_HANDLING
 151
 152        //======================================================================
 153
 154#if UNITY_EDITOR
 155        public delegate void ProcessDelegate(int sceneNumber, string method);
 156
 157        public event ProcessDelegate OnMessageProcessInfoStart;
 158        public event ProcessDelegate OnMessageProcessInfoEnds;
 159#endif
 0160        public bool deferredMessagesDecoding { get; set; } = false;
 161
 577162        readonly ConcurrentQueue<string> chunksToDecode = new ConcurrentQueue<string>();
 577163        private readonly ConcurrentQueue<QueuedSceneMessage_Scene> messagesToProcess = new ConcurrentQueue<QueuedSceneMe
 164
 165        const float MAX_TIME_FOR_DECODE = 0.005f;
 166
 167        public bool ProcessMessage(QueuedSceneMessage_Scene msgObject, out CustomYieldInstruction yieldInstruction)
 168        {
 2169            int sceneNumber = msgObject.sceneNumber;
 2170            string method = msgObject.method;
 171
 2172            yieldInstruction = null;
 173
 174            IParcelScene scene;
 2175            bool res = false;
 2176            IWorldState worldState = Environment.i.world.state;
 2177            DebugConfig debugConfig = DataStore.i.debugConfig;
 178
 2179            if (worldState.TryGetScene(sceneNumber, out scene))
 180            {
 181#if UNITY_EDITOR
 2182                if (debugConfig.soloScene && scene is GlobalScene && debugConfig.ignoreGlobalScenes)
 183                {
 0184                    return false;
 185                }
 186#endif
 2187                if (!scene.GetSceneTransform().gameObject.activeInHierarchy)
 188                {
 0189                    return true;
 190                }
 191
 192#if UNITY_EDITOR
 2193                OnMessageProcessInfoStart?.Invoke(sceneNumber, method);
 194#endif
 2195                ProfilingEvents.OnMessageProcessStart?.Invoke(method);
 196
 2197                ProcessMessage(scene as ParcelScene, method, msgObject.payload, out yieldInstruction);
 198
 2199                ProfilingEvents.OnMessageProcessEnds?.Invoke(method);
 200
 201#if UNITY_EDITOR
 2202                OnMessageProcessInfoEnds?.Invoke(sceneNumber, method);
 203#endif
 204
 2205                res = true;
 206            }
 207
 208            else
 209            {
 0210                res = false;
 211            }
 212
 2213            sceneMessagesPool.Enqueue(msgObject);
 214
 2215            return res;
 216        }
 217
 218        private void ProcessMessage(ParcelScene scene, string method, object msgPayload,
 219            out CustomYieldInstruction yieldInstruction)
 220        {
 2221            yieldInstruction = null;
 2222            IDelayedComponent delayedComponent = null;
 223
 224            try
 225            {
 226                switch (method)
 227                {
 228                    case MessagingTypes.ENTITY_CREATE:
 229                        {
 0230                            if (msgPayload is Protocol.CreateEntity payload)
 0231                                scene.CreateEntity(entityIdHelper.EntityFromLegacyEntityString(payload.entityId));
 232
 0233                            break;
 234                        }
 235                    case MessagingTypes.ENTITY_REPARENT:
 236                        {
 0237                            if (msgPayload is Protocol.SetEntityParent payload)
 0238                                scene.SetEntityParent(entityIdHelper.EntityFromLegacyEntityString(payload.entityId),
 239                                    entityIdHelper.EntityFromLegacyEntityString(payload.parentId));
 240
 0241                            break;
 242                        }
 243
 244                    case MessagingTypes.ENTITY_COMPONENT_CREATE_OR_UPDATE:
 245                        {
 0246                            if (msgPayload is Protocol.EntityComponentCreateOrUpdate payload)
 247                            {
 0248                                delayedComponent = scene.componentsManagerLegacy.EntityComponentCreateOrUpdate(
 249                                    entityIdHelper.EntityFromLegacyEntityString(payload.entityId),
 250                                    (CLASS_ID_COMPONENT) payload.classId, payload.json) as IDelayedComponent;
 251                            }
 252
 0253                            break;
 254                        }
 255
 256                    case MessagingTypes.ENTITY_COMPONENT_DESTROY:
 257                        {
 0258                            if (msgPayload is Protocol.EntityComponentDestroy payload)
 0259                                scene.componentsManagerLegacy.EntityComponentRemove(
 260                                    entityIdHelper.EntityFromLegacyEntityString(payload.entityId), payload.name);
 261
 0262                            break;
 263                        }
 264
 265                    case MessagingTypes.SHARED_COMPONENT_ATTACH:
 266                        {
 0267                            if (msgPayload is Protocol.SharedComponentAttach payload)
 0268                                scene.componentsManagerLegacy.SceneSharedComponentAttach(
 269                                    entityIdHelper.EntityFromLegacyEntityString(payload.entityId), payload.id);
 270
 0271                            break;
 272                        }
 273
 274                    case MessagingTypes.SHARED_COMPONENT_CREATE:
 275                        {
 0276                            if (msgPayload is Protocol.SharedComponentCreate payload)
 0277                                scene.componentsManagerLegacy.SceneSharedComponentCreate(payload.id, payload.classId);
 278
 0279                            break;
 280                        }
 281
 282                    case MessagingTypes.SHARED_COMPONENT_DISPOSE:
 283                        {
 0284                            if (msgPayload is Protocol.SharedComponentDispose payload)
 0285                                scene.componentsManagerLegacy.SceneSharedComponentDispose(payload.id);
 286
 0287                            break;
 288                        }
 289
 290                    case MessagingTypes.SHARED_COMPONENT_UPDATE:
 291                        {
 0292                            if (msgPayload is Protocol.SharedComponentUpdate payload)
 0293                                delayedComponent = scene.componentsManagerLegacy.SceneSharedComponentUpdate(payload.comp
 294
 0295                            break;
 296                        }
 297
 298                    case MessagingTypes.ENTITY_DESTROY:
 299                        {
 0300                            if (msgPayload is Protocol.RemoveEntity payload)
 0301                                scene.RemoveEntity(entityIdHelper.EntityFromLegacyEntityString(payload.entityId));
 302
 0303                            break;
 304                        }
 305
 306                    case MessagingTypes.INIT_DONE:
 307                        {
 2308                            scene.sceneLifecycleHandler.SetInitMessagesDone();
 309
 2310                            break;
 311                        }
 312
 313                    case MessagingTypes.QUERY:
 314                        {
 0315                            if (msgPayload is QueryMessage queryMessage)
 0316                                ParseQuery(queryMessage.payload, scene.sceneData.sceneNumber);
 317
 0318                            break;
 319                        }
 320
 321                    case MessagingTypes.OPEN_EXTERNAL_URL:
 322                        {
 0323                            if (msgPayload is Protocol.OpenExternalUrl payload)
 0324                                OnOpenExternalUrlRequest?.Invoke(scene, payload.url);
 325
 0326                            break;
 327                        }
 328
 329                    case MessagingTypes.OPEN_NFT_DIALOG:
 330                        {
 0331                            if (msgPayload is Protocol.OpenNftDialog payload)
 0332                                DataStore.i.common.onOpenNFTPrompt.Set(new NFTPromptModel(payload.contactAddress, payloa
 333                                    payload.comment), true);
 334
 0335                            break;
 336                        }
 337
 338                    default:
 0339                        Debug.LogError($"Unknown method {method}");
 340
 341                        break;
 342                }
 2343            }
 344            catch (Exception e)
 345            {
 0346                Debug.LogException(e);
 0347                Debug.LogError($"Scene message error. scene: {scene.sceneData.sceneNumber} method: {method} payload: {Js
 0348            }
 349
 2350            if (delayedComponent != null)
 351            {
 0352                if (delayedComponent.isRoutineRunning)
 0353                    yieldInstruction = delayedComponent.yieldInstruction;
 354            }
 2355        }
 356
 357        public void ParseQuery(object payload, int sceneNumber)
 358        {
 0359            if (!Environment.i.world.state.TryGetScene(sceneNumber, out var scene)) return;
 360
 0361            if (!(payload is RaycastQuery raycastQuery))
 0362                return;
 363
 0364            Vector3 worldOrigin = raycastQuery.ray.origin + Utils.GridToWorldPosition(scene.sceneData.basePosition.x, sc
 365
 0366            raycastQuery.ray.unityOrigin = PositionUtils.WorldToUnityPosition(worldOrigin);
 0367            raycastQuery.sceneNumber = sceneNumber;
 0368            PhysicsCast.i.Query(raycastQuery, entityIdHelper);
 0369        }
 370
 371        public void SendSceneMessage(string chunk)
 372        {
 0373            var renderer = CommonScriptableObjects.rendererState.Get();
 374
 0375            if (!renderer)
 376            {
 0377                EnqueueChunk(chunk);
 378            }
 379            else
 380            {
 0381                chunksToDecode.Enqueue(chunk);
 382            }
 0383        }
 384
 385        private QueuedSceneMessage_Scene Decode(string payload, QueuedSceneMessage_Scene queuedMessage)
 386        {
 0387            ProfilingEvents.OnMessageDecodeStart?.Invoke("Misc");
 388
 0389            if (!MessageDecoder.DecodePayloadChunk(payload,
 390                    out int sceneNumber,
 391                    out string message,
 392                    out string messageTag,
 393                    out PB_SendSceneMessage sendSceneMessage))
 394            {
 0395                return null;
 396            }
 397
 0398            MessageDecoder.DecodeSceneMessage(sceneNumber, message, messageTag, sendSceneMessage, ref queuedMessage);
 399
 0400            ProfilingEvents.OnMessageDecodeEnds?.Invoke("Misc");
 401
 0402            return queuedMessage;
 403        }
 404
 405        private IEnumerator DeferredDecodingAndEnqueue()
 406        {
 577407            float start = Time.realtimeSinceStartup;
 408            float maxTimeForDecode;
 409
 28860410            while (true)
 411            {
 29437412                maxTimeForDecode = CommonScriptableObjects.rendererState.Get() ? MAX_TIME_FOR_DECODE : float.MaxValue;
 413
 29437414                if (chunksToDecode.TryDequeue(out string chunk))
 415                {
 0416                    EnqueueChunk(chunk);
 417
 0418                    if (Time.realtimeSinceStartup - start < maxTimeForDecode)
 419                        continue;
 420                }
 421
 29437422                yield return null;
 423
 28860424                start = Time.unscaledTime;
 425            }
 426        }
 427        private void EnqueueChunk(string chunk)
 428        {
 0429            string[] payloads = chunk.Split(new [] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
 0430            var count = payloads.Length;
 431
 0432            for (int i = 0; i < count; i++)
 433            {
 0434                bool availableMessage = sceneMessagesPool.TryDequeue(out QueuedSceneMessage_Scene freeMessage);
 435
 0436                if (availableMessage)
 437                {
 0438                    EnqueueSceneMessage(Decode(payloads[i], freeMessage));
 439                }
 440                else
 441                {
 0442                    EnqueueSceneMessage(Decode(payloads[i], new QueuedSceneMessage_Scene()));
 443                }
 444            }
 0445        }
 446        private async UniTask WatchForNewChunksToDecode(CancellationToken cancellationToken)
 447        {
 0448            while (!cancellationToken.IsCancellationRequested)
 449            {
 450                try
 451                {
 0452                    if (chunksToDecode.Count > 0)
 453                    {
 0454                        ThreadedDecodeAndEnqueue(cancellationToken);
 455                    }
 0456                }
 457                catch (Exception e)
 458                {
 0459                    Debug.LogException(e);
 0460                }
 461
 0462                await UniTask.Yield();
 463            }
 0464        }
 465        private void ThreadedDecodeAndEnqueue(CancellationToken cancellationToken)
 466        {
 0467            while (chunksToDecode.TryDequeue(out string chunk))
 468            {
 0469                cancellationToken.ThrowIfCancellationRequested();
 470
 0471                string[] payloads = chunk.Split(new [] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
 0472                var count = payloads.Length;
 473
 0474                for (int i = 0; i < count; i++)
 475                {
 0476                    var payload = payloads[i];
 0477                    bool availableMessage = sceneMessagesPool.TryDequeue(out QueuedSceneMessage_Scene freeMessage);
 478
 0479                    if (availableMessage)
 480                    {
 0481                        EnqueueSceneMessage(Decode(payload, freeMessage));
 482                    }
 483                    else
 484                    {
 0485                        EnqueueSceneMessage(Decode(payload, new QueuedSceneMessage_Scene()));
 486                    }
 487                }
 0488            }
 0489        }
 490
 491        public void EnqueueSceneMessage(QueuedSceneMessage_Scene message)
 492        {
 2493            bool isGlobalScene = WorldStateUtils.IsGlobalScene(message.sceneNumber);
 2494            messagingControllersManager.AddControllerIfNotExists(this, message.sceneNumber);
 2495            messagingControllersManager.Enqueue(isGlobalScene, message);
 2496        }
 497
 498        //======================================================================
 499
 500        #endregion
 501
 502        //======================================================================
 503
 504        //======================================================================
 505
 506        #region SCENES_MANAGEMENT
 507
 508        //======================================================================
 509        public event Action<int> OnReadyScene;
 510
 511        public void SendSceneReady(int sceneNumber)
 512        {
 297513            messagingControllersManager.SetSceneReady(sceneNumber);
 514
 297515            WebInterface.ReportControlEvent(new WebInterface.SceneReady(sceneNumber));
 297516            WebInterface.ReportCameraChanged(CommonScriptableObjects.cameraMode.Get(), sceneNumber);
 517
 297518            Environment.i.world.blockersController.SetupWorldBlockers();
 519
 297520            OnReadyScene?.Invoke(sceneNumber);
 0521        }
 522
 0523        public void ActivateBuilderInWorldEditScene() { Environment.i.world.sceneBoundsChecker.SetFeedbackStyle(new Scen
 524
 0525        public void DeactivateBuilderInWorldEditScene() { Environment.i.world.sceneBoundsChecker.SetFeedbackStyle(new Sc
 526
 527        private void SetPositionDirty(Vector2Int gridPosition, Vector2Int previous)
 528        {
 10529            positionDirty = gridPosition.x != currentGridSceneCoordinate.x || gridPosition.y != currentGridSceneCoordina
 530
 10531            if (positionDirty)
 532            {
 10533                sceneSortDirty = true;
 10534                currentGridSceneCoordinate = gridPosition;
 535
 536                // Since the first position for the character is not sent from Kernel until just-before calling
 537                // the rendering activation from Kernel, we need to sort the scenes to get the current scene id
 538                // to lock the rendering accordingly...
 10539                if (!CommonScriptableObjects.rendererState.Get())
 540                {
 0541                    SortScenesByDistance();
 542                }
 543            }
 10544        }
 545
 546        public void SortScenesByDistance()
 547        {
 576548            IWorldState worldState = Environment.i.world.state;
 549
 576550            worldState.SortScenesByDistance(currentGridSceneCoordinate);
 551
 576552            int currentSceneNumber = worldState.GetCurrentSceneNumber();
 553
 576554            if (!DataStore.i.debugConfig.isDebugMode.Get() && currentSceneNumber <= 0)
 555            {
 556                // When we don't know the current scene yet, we must lock the rendering from enabling until it is set
 565557                CommonScriptableObjects.rendererState.AddLock(this);
 558            }
 559            else
 560            {
 561                // 1. Set current scene id
 11562                CommonScriptableObjects.sceneNumber.Set(currentSceneNumber);
 563
 564                // 2. Attempt to remove SceneController's lock on rendering
 11565                CommonScriptableObjects.rendererState.RemoveLock(this);
 566            }
 567
 576568            OnSortScenes?.Invoke();
 576569        }
 570
 571        private void OnCurrentSceneNumberChange(int newSceneNumber, int previousSceneNumber)
 572        {
 70573            if (Environment.i.world.state.TryGetScene(newSceneNumber, out IParcelScene newCurrentScene)
 574                && !(newCurrentScene as ParcelScene).sceneLifecycleHandler.isReady)
 575            {
 5576                CommonScriptableObjects.rendererState.AddLock(newCurrentScene);
 577
 7578                (newCurrentScene as ParcelScene).sceneLifecycleHandler.OnSceneReady += (readyScene) => { CommonScriptabl
 579            }
 70580        }
 581
 582        public void LoadParcelScenesExecute(string scenePayload)
 583        {
 584            LoadParcelScenesMessage.UnityParcelScene sceneToLoad;
 585
 30586            ProfilingEvents.OnMessageDecodeStart?.Invoke(MessagingTypes.SCENE_LOAD);
 30587            sceneToLoad = Utils.SafeFromJson<LoadParcelScenesMessage.UnityParcelScene>(scenePayload);
 30588            ProfilingEvents.OnMessageDecodeEnds?.Invoke(MessagingTypes.SCENE_LOAD);
 589
 30590            if (VERBOSE)
 0591                Debug.Log($"{Time.frameCount}: Trying to load scene: id: {sceneToLoad.id}; number: {sceneToLoad.sceneNum
 592
 30593            if (sceneToLoad == null || sceneToLoad.sceneNumber <= 0)
 0594                return;
 595
 30596            DebugConfig debugConfig = DataStore.i.debugConfig;
 597#if UNITY_EDITOR
 30598            if (debugConfig.soloScene && sceneToLoad.basePosition.ToString() != debugConfig.soloSceneCoords.ToString())
 599            {
 0600                SendSceneReady(sceneToLoad.sceneNumber);
 601
 0602                return;
 603            }
 604#endif
 605
 30606            ProfilingEvents.OnMessageProcessStart?.Invoke(MessagingTypes.SCENE_LOAD);
 607
 30608            IWorldState worldState = Environment.i.world.state;
 609
 30610            if (!worldState.ContainsScene(sceneToLoad.sceneNumber))
 611            {
 30612                var newGameObject = new GameObject("New Scene");
 613
 30614                var newScene = newGameObject.AddComponent<ParcelScene>();
 30615                newScene.SetData(sceneToLoad);
 616
 30617                if (debugConfig.isDebugMode.Get())
 618                {
 28619                    newScene.InitializeDebugPlane();
 620                }
 621
 30622                worldState.AddScene(newScene);
 623
 30624                sceneSortDirty = true;
 625
 30626                OnNewSceneAdded?.Invoke(newScene);
 627
 30628                messagingControllersManager.AddControllerIfNotExists(this, newScene.sceneData.sceneNumber);
 629
 30630                if (VERBOSE)
 0631                    Debug.Log($"{Time.frameCount}: Load parcel scene (id: {newScene.sceneData.sceneNumber})");
 632            }
 633
 30634            ProfilingEvents.OnMessageProcessEnds?.Invoke(MessagingTypes.SCENE_LOAD);
 0635        }
 636
 637        public void UpdateParcelScenesExecute(string scenePayload)
 638        {
 639            LoadParcelScenesMessage.UnityParcelScene sceneData;
 640
 0641            ProfilingEvents.OnMessageDecodeStart?.Invoke(MessagingTypes.SCENE_UPDATE);
 0642            sceneData = Utils.SafeFromJson<LoadParcelScenesMessage.UnityParcelScene>(scenePayload);
 0643            ProfilingEvents.OnMessageDecodeEnds?.Invoke(MessagingTypes.SCENE_UPDATE);
 644
 0645            IWorldState worldState = Environment.i.world.state;
 646
 0647            if (worldState.TryGetScene(sceneData.sceneNumber, out IParcelScene sceneInterface))
 648            {
 0649                ParcelScene scene = sceneInterface as ParcelScene;
 0650                scene.SetUpdateData(sceneData);
 651            }
 652            else
 653            {
 0654                LoadParcelScenesExecute(scenePayload);
 655            }
 0656        }
 657
 658        public void UpdateParcelScenesExecute(LoadParcelScenesMessage.UnityParcelScene scene)
 659        {
 0660            if (scene == null || scene.sceneNumber <= 0)
 0661                return;
 662
 0663            var sceneToLoad = scene;
 664
 0665            ProfilingEvents.OnMessageProcessStart?.Invoke(MessagingTypes.SCENE_UPDATE);
 666
 0667            ParcelScene parcelScene = Environment.i.world.state.GetScene(sceneToLoad.sceneNumber) as ParcelScene;
 668
 0669            if (parcelScene != null)
 0670                parcelScene.SetUpdateData(sceneToLoad);
 671
 0672            ProfilingEvents.OnMessageProcessEnds?.Invoke(MessagingTypes.SCENE_UPDATE);
 0673        }
 674
 675        public void UnloadScene(int sceneNumber)
 676        {
 3677            var queuedMessage = new QueuedSceneMessage()
 678                { type = QueuedSceneMessage.Type.UNLOAD_PARCEL, sceneNumber = sceneNumber };
 679
 3680            ProfilingEvents.OnMessageWillQueue?.Invoke(MessagingTypes.SCENE_DESTROY);
 681
 3682            messagingControllersManager.ForceEnqueueToGlobal(MessagingBusType.INIT, queuedMessage);
 3683            messagingControllersManager.RemoveController(sceneNumber);
 3684        }
 685
 686        public void UnloadParcelSceneExecute(int sceneNumber)
 687        {
 312688            ProfilingEvents.OnMessageProcessStart?.Invoke(MessagingTypes.SCENE_DESTROY);
 689
 312690            IWorldState worldState = Environment.i.world.state;
 691
 312692            if (!worldState.TryGetScene(sceneNumber, out ParcelScene scene))
 0693                return;
 694
 312695            worldState.RemoveScene(sceneNumber);
 696
 312697            DataStore.i.world.portableExperienceIds.Remove(scene.sceneData.id);
 698
 699            // Remove messaging controller for unloaded scene
 312700            messagingControllersManager.RemoveController(sceneNumber);
 701
 312702            scene.Cleanup(!CommonScriptableObjects.rendererState.Get());
 703
 312704            if (VERBOSE)
 705            {
 0706                Debug.Log($"{Time.frameCount} : Destroying scene {scene.sceneData.basePosition}");
 707            }
 708
 312709            Environment.i.world.blockersController.SetupWorldBlockers();
 710
 312711            ProfilingEvents.OnMessageProcessEnds?.Invoke(MessagingTypes.SCENE_DESTROY);
 312712            OnSceneRemoved?.Invoke(scene);
 2713        }
 714
 715        public void UnloadAllScenes(bool includePersistent = false)
 716        {
 579717            var worldState = Environment.i.world.state;
 718
 719            // since the list was changing by this foreach, we make a copy
 579720            var list = worldState.GetLoadedScenes().ToArray();
 721
 1770722            foreach (var kvp in list)
 723            {
 306724                if (kvp.Value.isPersistent && !includePersistent)
 725                    continue;
 726
 306727                UnloadParcelSceneExecute(kvp.Key);
 728            }
 579729        }
 730
 731        public void LoadParcelScenes(string decentralandSceneJSON)
 732        {
 30733            var queuedMessage = new QueuedSceneMessage()
 734            {
 735                type = QueuedSceneMessage.Type.LOAD_PARCEL,
 736                message = decentralandSceneJSON
 737            };
 738
 30739            ProfilingEvents.OnMessageWillQueue?.Invoke(MessagingTypes.SCENE_LOAD);
 740
 30741            messagingControllersManager.ForceEnqueueToGlobal(MessagingBusType.INIT, queuedMessage);
 742
 30743            if (VERBOSE)
 0744                Debug.Log($"{Time.frameCount} : Load parcel scene queue {decentralandSceneJSON}");
 30745        }
 746
 747        public void UpdateParcelScenes(string decentralandSceneJSON)
 748        {
 0749            var queuedMessage = new QueuedSceneMessage()
 750                { type = QueuedSceneMessage.Type.UPDATE_PARCEL, message = decentralandSceneJSON };
 751
 0752            ProfilingEvents.OnMessageWillQueue?.Invoke(MessagingTypes.SCENE_UPDATE);
 753
 0754            messagingControllersManager.ForceEnqueueToGlobal(MessagingBusType.INIT, queuedMessage);
 0755        }
 756
 757        public void UnloadAllScenesQueued()
 758        {
 0759            var queuedMessage = new QueuedSceneMessage() { type = QueuedSceneMessage.Type.UNLOAD_SCENES };
 760
 0761            ProfilingEvents.OnMessageWillQueue?.Invoke(MessagingTypes.SCENE_DESTROY);
 762
 0763            Environment.i.messaging.manager.ForceEnqueueToGlobal(MessagingBusType.INIT, queuedMessage);
 0764        }
 765
 766        public void CreateGlobalScene(string json)
 767        {
 768#if UNITY_EDITOR
 5769            DebugConfig debugConfig = DataStore.i.debugConfig;
 770
 5771            if (debugConfig.soloScene && debugConfig.ignoreGlobalScenes)
 0772                return;
 773#endif
 5774            CreateGlobalSceneMessage globalScene = Utils.SafeFromJson<CreateGlobalSceneMessage>(json);
 775
 776            // NOTE(Brian): We should remove this line. SceneController is a runtime core class.
 777            //              It should never have references to UI systems or higher level systems.
 5778            if (globalScene.isPortableExperience && !isPexViewerInitialized.Get())
 779            {
 0780                Debug.LogError(
 781                    "Portable experiences are trying to be added before the system is initialized!. scene number: " +
 782                    globalScene.sceneNumber);
 0783                return;
 784            }
 785
 5786            int newGlobalSceneNumber = globalScene.sceneNumber;
 5787            IWorldState worldState = Environment.i.world.state;
 788
 5789            if (worldState.ContainsScene(newGlobalSceneNumber))
 0790                return;
 791
 5792            var newGameObject = new GameObject("Global Scene - " + newGlobalSceneNumber);
 793
 5794            var newScene = newGameObject.AddComponent<GlobalScene>();
 5795            newScene.unloadWithDistance = false;
 5796            newScene.isPersistent = true;
 5797            newScene.sceneName = globalScene.name;
 5798            newScene.isPortableExperience = globalScene.isPortableExperience;
 799
 5800            LoadParcelScenesMessage.UnityParcelScene sceneData = new LoadParcelScenesMessage.UnityParcelScene
 801            {
 802                id = globalScene.id,
 803                sceneNumber = newGlobalSceneNumber,
 804                basePosition = new Vector2Int(0, 0),
 805                baseUrl = globalScene.baseUrl,
 806                contents = globalScene.contents
 807            };
 808
 5809            newScene.SetData(sceneData);
 810
 5811            if (!string.IsNullOrEmpty(globalScene.icon))
 812            {
 0813                newScene.iconUrl = newScene.contentProvider.GetContentsUrl(globalScene.icon);
 814            }
 815
 5816            worldState.AddScene(newScene);
 5817            OnNewSceneAdded?.Invoke(newScene);
 818
 5819            if (newScene.isPortableExperience)
 820            {
 2821                DataStore.i.world.portableExperienceIds.Add(sceneData.id);
 822            }
 823
 5824            messagingControllersManager.AddControllerIfNotExists(this, newGlobalSceneNumber, isGlobal: true);
 825
 5826            if (VERBOSE)
 0827                Debug.Log($"Creating Global scene {newGlobalSceneNumber}");
 5828        }
 829
 830        public void IsolateScene(IParcelScene sceneToActive)
 831        {
 136832            foreach (IParcelScene scene in Environment.i.world.state.GetScenesSortedByDistance())
 833            {
 34834                if (scene != sceneToActive)
 0835                    scene.GetSceneTransform().gameObject.SetActive(false);
 836            }
 34837        }
 838
 839        public void ReIntegrateIsolatedScene()
 840        {
 4841            foreach (IParcelScene scene in Environment.i.world.state.GetScenesSortedByDistance())
 842            {
 1843                scene.GetSceneTransform().gameObject.SetActive(true);
 844            }
 1845        }
 846
 847        //======================================================================
 848
 849        #endregion
 850
 851        //======================================================================
 852
 579853        public ConcurrentQueue<QueuedSceneMessage_Scene> sceneMessagesPool { get; } = new ConcurrentQueue<QueuedSceneMes
 854
 577855        public bool prewarmSceneMessagesPool { get; set; } = true;
 577856        public bool prewarmEntitiesPool { get; set; } = true;
 857
 858        private bool sceneSortDirty = false;
 577859        private bool positionDirty = true;
 860        private int lastSortFrame = 0;
 861
 862        public event Action OnSortScenes;
 863        public event Action<IParcelScene, string> OnOpenExternalUrlRequest;
 864        public event Action<IParcelScene> OnNewSceneAdded;
 865        public event Action<IParcelScene> OnSceneRemoved;
 866
 577867        private Vector2Int currentGridSceneCoordinate = new Vector2Int(EnvironmentSettings.MORDOR_SCALAR, EnvironmentSet
 868    }
 869}

Methods/Properties

enabled()
enabled(System.Boolean)
SceneController()
isPexViewerInitialized()
messagingControllersManager()
entityIdHelper()
Initialize()
SetupDeferredRunners()
PrewarmSceneMessagesPool()
OnDebugModeSet(System.Boolean, System.Boolean)
Dispose()
Update()
LateUpdate()
deferredMessagesDecoding()
deferredMessagesDecoding(System.Boolean)
ProcessMessage(DCL.QueuedSceneMessage_Scene, UnityEngine.CustomYieldInstruction&)
ProcessMessage(DCL.Controllers.ParcelScene, System.String, System.Object, UnityEngine.CustomYieldInstruction&)
ParseQuery(System.Object, System.Int32)
SendSceneMessage(System.String)
Decode(System.String, DCL.QueuedSceneMessage_Scene)
DeferredDecodingAndEnqueue()
EnqueueChunk(System.String)
WatchForNewChunksToDecode()
ThreadedDecodeAndEnqueue(System.Threading.CancellationToken)
EnqueueSceneMessage(DCL.QueuedSceneMessage_Scene)
SendSceneReady(System.Int32)
ActivateBuilderInWorldEditScene()
DeactivateBuilderInWorldEditScene()
SetPositionDirty(UnityEngine.Vector2Int, UnityEngine.Vector2Int)
SortScenesByDistance()
OnCurrentSceneNumberChange(System.Int32, System.Int32)
LoadParcelScenesExecute(System.String)
UpdateParcelScenesExecute(System.String)
UpdateParcelScenesExecute(DCL.Models.LoadParcelScenesMessage/UnityParcelScene)
UnloadScene(System.Int32)
UnloadParcelSceneExecute(System.Int32)
UnloadAllScenes(System.Boolean)
LoadParcelScenes(System.String)
UpdateParcelScenes(System.String)
UnloadAllScenesQueued()
CreateGlobalScene(System.String)
IsolateScene(DCL.Controllers.IParcelScene)
ReIntegrateIsolatedScene()
sceneMessagesPool()
prewarmSceneMessagesPool()
prewarmSceneMessagesPool(System.Boolean)
prewarmEntitiesPool()
prewarmEntitiesPool(System.Boolean)