< Summary

Class:DCL.SceneController
Assembly:DCL.Runtime
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/WorldRuntime/SceneController.cs
Covered lines:172
Uncovered lines:180
Coverable lines:352
Total lines:883
Line coverage:48.8% (172 of 352)
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%
>c__DisplayClass17_0/<<SetupDeferredRunners()0%330100%
PrewarmSceneMessagesPool()0%20400%
OnDebugModeSet(...)0%3.713057.14%
Dispose()0%22092.86%
Update()0%440100%
LateUpdate()0%220100%
ProcessMessage(...)0%1101000%
ProcessMessage(...)0%27565200%
ParseQuery(...)0%12300%
SendSceneMessage(...)0%6200%
Decode(...)0%20400%
DeferredDecodingAndEnqueue()0%72800%
EnqueueChunk(...)0%12300%
WatchForNewChunksToDecode()0%5.685070%
ThreadedDecodeAndEnqueue(...)0%20400%
EnqueueSceneMessage(...)0%2100%
SendSceneReady(...)0%220100%
ActivateBuilderInWorldEditScene()0%110100%
DeactivateBuilderInWorldEditScene()0%110100%
SetPositionDirty(...)0%4.054085.71%
SortScenesByDistance()0%440100%
OnCurrentSceneIdChange(...)0%64050%
LoadParcelScenesExecute(...)0%14.213080.77%
UpdateParcelScenesExecute(...)0%20400%
UpdateParcelScenesExecute(...)0%6.396077.78%
UnloadScene(...)0%220100%
UnloadParcelSceneExecute(...)0%6.356078.57%
UnloadAllScenes(...)0%440100%
LoadParcelScenes(...)0%3.043083.33%
UpdateParcelScenes(...)0%6200%
UnloadAllScenesQueued()0%6200%
CreateGlobalScene(...)0%10.8910079.31%
IsolateScene(...)0%330100%
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
 70825        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;
 89033        private IMessagingControllersManager messagingControllersManager => Environment.i.messaging.manager;
 34
 71735        public EntityIdHelper entityIdHelper { get; } = new EntityIdHelper();
 36
 37        public void Initialize()
 38        {
 68439            tokenSource = new CancellationTokenSource();
 68440            sceneSortDirty = true;
 68441            positionDirty = true;
 68442            lastSortFrame = 0;
 68443            enabled = true;
 44
 68445            loadingFeedbackController = new LoadingFeedbackController();
 46
 68447            DataStore.i.debugConfig.isDebugMode.OnChange += OnDebugModeSet;
 48
 68449            SetupDeferredRunners();
 50
 68451            DataStore.i.player.playerGridPosition.OnChange += SetPositionDirty;
 68452            CommonScriptableObjects.sceneID.OnChange += OnCurrentSceneIdChange;
 53
 54            // TODO(Brian): Move this later to Main.cs
 68455            if ( !EnvironmentSettings.RUNNING_TESTS )
 56            {
 057                PrewarmSceneMessagesPool();
 58            }
 59
 68460            Environment.i.platform.updateEventHandler.AddListener(IUpdateEventHandler.EventType.Update, Update);
 68461            Environment.i.platform.updateEventHandler.AddListener(IUpdateEventHandler.EventType.LateUpdate, LateUpdate);
 68462        }
 63        private void SetupDeferredRunners()
 64        {
 65#if UNITY_WEBGL
 66            deferredDecodingCoroutine = CoroutineStarter.Start(DeferredDecodingAndEnqueue());
 67#else
 68468            CancellationToken tokenSourceToken = tokenSource.Token;
 273669            TaskUtils.Run(async () => await WatchForNewChunksToDecode(tokenSourceToken), cancellationToken: tokenSourceT
 70#endif
 68471        }
 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        {
 1291            if (current == previous)
 092                return;
 93
 1294            if (current)
 95            {
 1296                Environment.i.world.sceneBoundsChecker.SetFeedbackStyle(new SceneBoundsFeedbackStyle_RedBox());
 1297            }
 98            else
 99            {
 0100                Environment.i.world.sceneBoundsChecker.SetFeedbackStyle(new SceneBoundsFeedbackStyle_Simple());
 101            }
 0102        }
 103
 104        public void Dispose()
 105        {
 684106            tokenSource.Cancel();
 684107            tokenSource.Dispose();
 684108            loadingFeedbackController.Dispose();
 109
 684110            Environment.i.platform.updateEventHandler.RemoveListener(IUpdateEventHandler.EventType.Update, Update);
 684111            Environment.i.platform.updateEventHandler.RemoveListener(IUpdateEventHandler.EventType.LateUpdate, LateUpdat
 112
 684113            PoolManager.i.OnGet -= Environment.i.platform.physicsSyncController.MarkDirty;
 684114            PoolManager.i.OnGet -= Environment.i.platform.cullingController.objectsTracker.MarkDirty;
 115
 684116            DataStore.i.player.playerGridPosition.OnChange -= SetPositionDirty;
 684117            DataStore.i.debugConfig.isDebugMode.OnChange -= OnDebugModeSet;
 118
 684119            CommonScriptableObjects.sceneID.OnChange -= OnCurrentSceneIdChange;
 120
 684121            UnloadAllScenes(includePersistent: true);
 122
 684123            if (deferredDecodingCoroutine != null)
 0124                CoroutineStarter.Stop(deferredDecodingCoroutine);
 684125        }
 126
 127        public void Update()
 128        {
 6965129            if (!enabled)
 408130                return;
 131
 6557132            if (lastSortFrame != Time.frameCount && sceneSortDirty)
 133            {
 680134                lastSortFrame = Time.frameCount;
 680135                sceneSortDirty = false;
 680136                SortScenesByDistance();
 137            }
 6557138        }
 139
 140        public void LateUpdate()
 141        {
 6965142            if (!enabled)
 408143                return;
 144
 6557145            Environment.i.platform.physicsSyncController.Sync();
 6557146        }
 147
 148        //======================================================================
 149
 150        #region MESSAGES_HANDLING
 151
 152        //======================================================================
 153
 154#if UNITY_EDITOR
 155        public delegate void ProcessDelegate(string sceneId, string method);
 156
 157        public event ProcessDelegate OnMessageProcessInfoStart;
 158        public event ProcessDelegate OnMessageProcessInfoEnds;
 159#endif
 0160        public bool deferredMessagesDecoding { get; set; } = false;
 161
 684162        readonly ConcurrentQueue<string> chunksToDecode = new ConcurrentQueue<string>();
 684163        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        {
 0169            string sceneId = msgObject.sceneId;
 0170            string method = msgObject.method;
 171
 0172            yieldInstruction = null;
 173
 174            IParcelScene scene;
 0175            bool res = false;
 0176            IWorldState worldState = Environment.i.world.state;
 0177            DebugConfig debugConfig = DataStore.i.debugConfig;
 178
 0179            if (worldState.TryGetScene(sceneId, out scene))
 180            {
 181#if UNITY_EDITOR
 0182                if (debugConfig.soloScene && scene is GlobalScene && debugConfig.ignoreGlobalScenes)
 183                {
 0184                    return false;
 185                }
 186#endif
 0187                if (!scene.GetSceneTransform().gameObject.activeInHierarchy)
 188                {
 0189                    return true;
 190                }
 191
 192#if UNITY_EDITOR
 0193                OnMessageProcessInfoStart?.Invoke(sceneId, method);
 194#endif
 0195                ProfilingEvents.OnMessageProcessStart?.Invoke(method);
 196
 0197                ProcessMessage(scene as ParcelScene, method, msgObject.payload, out yieldInstruction);
 198
 0199                ProfilingEvents.OnMessageProcessEnds?.Invoke(method);
 200
 201#if UNITY_EDITOR
 0202                OnMessageProcessInfoEnds?.Invoke(sceneId, method);
 203#endif
 204
 0205                res = true;
 0206            }
 207
 208            else
 209            {
 0210                res = false;
 211            }
 212
 0213            sceneMessagesPool.Enqueue(msgObject);
 214
 0215            return res;
 216        }
 217
 218        private void ProcessMessage(ParcelScene scene, string method, object msgPayload,
 219            out CustomYieldInstruction yieldInstruction)
 220        {
 0221            yieldInstruction = null;
 0222            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                        {
 0308                            scene.sceneLifecycleHandler.SetInitMessagesDone();
 309
 0310                            break;
 311                        }
 312
 313                    case MessagingTypes.QUERY:
 314                        {
 0315                            if (msgPayload is QueryMessage queryMessage)
 0316                                ParseQuery(queryMessage.payload, scene.sceneData.id);
 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                    case MessagingTypes.CRDT_MESSAGE:
 339                        {
 0340                            if (msgPayload is CRDTMessage crdtMessage)
 341                            {
 0342                                scene.crdtExecutor?.Execute(crdtMessage);
 343                            }
 0344                            break;
 345                        }
 346
 347                    default:
 0348                        Debug.LogError($"Unknown method {method}");
 349
 350                        break;
 351                }
 0352            }
 0353            catch (Exception e)
 354            {
 0355                throw new Exception(
 356                    $"Scene message error. scene: {scene.sceneData.id} method: {method} payload: {JsonUtility.ToJson(msg
 357            }
 358
 0359            if (delayedComponent != null)
 360            {
 0361                if (delayedComponent.isRoutineRunning)
 0362                    yieldInstruction = delayedComponent.yieldInstruction;
 363            }
 0364        }
 365
 366        public void ParseQuery(object payload, string sceneId)
 367        {
 0368            if (!Environment.i.world.state.TryGetScene(sceneId, out var scene)) return;
 369
 0370            if (!(payload is RaycastQuery raycastQuery))
 0371                return;
 372
 0373            Vector3 worldOrigin = raycastQuery.ray.origin + Utils.GridToWorldPosition(scene.sceneData.basePosition.x, sc
 374
 0375            raycastQuery.ray.unityOrigin = PositionUtils.WorldToUnityPosition(worldOrigin);
 0376            raycastQuery.sceneId = sceneId;
 0377            PhysicsCast.i.Query(raycastQuery, entityIdHelper);
 0378        }
 379
 380        public void SendSceneMessage(string chunk)
 381        {
 0382            var renderer = CommonScriptableObjects.rendererState.Get();
 383
 0384            if (!renderer)
 385            {
 0386                EnqueueChunk(chunk);
 0387            }
 388            else
 389            {
 0390                chunksToDecode.Enqueue(chunk);
 391            }
 0392        }
 393
 394        private QueuedSceneMessage_Scene Decode(string payload, QueuedSceneMessage_Scene queuedMessage)
 395        {
 0396            ProfilingEvents.OnMessageDecodeStart?.Invoke("Misc");
 397
 0398            if (!MessageDecoder.DecodePayloadChunk(payload,
 399                    out string sceneId,
 400                    out string message,
 401                    out string messageTag,
 402                    out PB_SendSceneMessage sendSceneMessage))
 403            {
 0404                return null;
 405            }
 406
 0407            MessageDecoder.DecodeSceneMessage(sceneId, message, messageTag, sendSceneMessage, ref queuedMessage);
 408
 0409            ProfilingEvents.OnMessageDecodeEnds?.Invoke("Misc");
 410
 0411            return queuedMessage;
 412        }
 413
 414        private IEnumerator DeferredDecodingAndEnqueue()
 415        {
 0416            float start = Time.realtimeSinceStartup;
 417            float maxTimeForDecode;
 418
 0419            while (true)
 420            {
 0421                maxTimeForDecode = CommonScriptableObjects.rendererState.Get() ? MAX_TIME_FOR_DECODE : float.MaxValue;
 422
 0423                if (chunksToDecode.Count > 0)
 424                {
 0425                    if (chunksToDecode.TryDequeue(out string chunk))
 426                    {
 0427                        EnqueueChunk(chunk);
 428
 0429                        if (Time.realtimeSinceStartup - start < maxTimeForDecode)
 430                            continue;
 431                    }
 432                }
 433
 0434                yield return null;
 435
 0436                start = Time.unscaledTime;
 437            }
 438        }
 439        private void EnqueueChunk(string chunk)
 440        {
 0441            string[] payloads = chunk.Split(new [] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
 0442            var count = payloads.Length;
 443
 0444            for (int i = 0; i < count; i++)
 445            {
 0446                bool availableMessage = sceneMessagesPool.TryDequeue(out QueuedSceneMessage_Scene freeMessage);
 447
 0448                if (availableMessage)
 449                {
 0450                    EnqueueSceneMessage(Decode(payloads[i], freeMessage));
 0451                }
 452                else
 453                {
 0454                    EnqueueSceneMessage(Decode(payloads[i], new QueuedSceneMessage_Scene()));
 455                }
 456            }
 0457        }
 458        private async UniTask WatchForNewChunksToDecode(CancellationToken cancellationToken)
 459        {
 8528460            while (!cancellationToken.IsCancellationRequested)
 461            {
 462                try
 463                {
 7844464                    if (chunksToDecode.Count > 0)
 465                    {
 0466                        ThreadedDecodeAndEnqueue(cancellationToken);
 467                    }
 7844468                }
 469                catch (Exception e)
 470                {
 0471                    Debug.LogException(e);
 0472                }
 473
 23532474                await UniTask.Yield();
 475            }
 684476        }
 477        private void ThreadedDecodeAndEnqueue(CancellationToken cancellationToken)
 478        {
 0479            while (chunksToDecode.TryDequeue(out string chunk))
 480            {
 0481                cancellationToken.ThrowIfCancellationRequested();
 482
 0483                string[] payloads = chunk.Split(new [] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
 0484                var count = payloads.Length;
 485
 0486                for (int i = 0; i < count; i++)
 487                {
 0488                    var payload = payloads[i];
 0489                    bool availableMessage = sceneMessagesPool.TryDequeue(out QueuedSceneMessage_Scene freeMessage);
 490
 0491                    if (availableMessage)
 492                    {
 0493                        EnqueueSceneMessage(Decode(payload, freeMessage));
 0494                    }
 495                    else
 496                    {
 0497                        EnqueueSceneMessage(Decode(payload, new QueuedSceneMessage_Scene()));
 498                    }
 499                }
 0500            }
 0501        }
 502
 503        public void EnqueueSceneMessage(QueuedSceneMessage_Scene message)
 504        {
 0505            bool isGlobalScene = WorldStateUtils.IsGlobalScene(message.sceneId);
 0506            messagingControllersManager.AddControllerIfNotExists(this, message.sceneId);
 0507            messagingControllersManager.Enqueue(isGlobalScene, message);
 0508        }
 509
 510        //======================================================================
 511
 512        #endregion
 513
 514        //======================================================================
 515
 516        //======================================================================
 517
 518        #region SCENES_MANAGEMENT
 519
 520        //======================================================================
 521        public event Action<string> OnReadyScene;
 522
 523        public void SendSceneReady(string sceneId)
 524        {
 412525            messagingControllersManager.SetSceneReady(sceneId);
 526
 412527            WebInterface.ReportControlEvent(new WebInterface.SceneReady(sceneId));
 412528            WebInterface.ReportCameraChanged(CommonScriptableObjects.cameraMode.Get(), sceneId);
 529
 412530            Environment.i.world.blockersController.SetupWorldBlockers();
 531
 412532            OnReadyScene?.Invoke(sceneId);
 2533        }
 534
 10535        public void ActivateBuilderInWorldEditScene() { Environment.i.world.sceneBoundsChecker.SetFeedbackStyle(new Scen
 536
 2537        public void DeactivateBuilderInWorldEditScene() { Environment.i.world.sceneBoundsChecker.SetFeedbackStyle(new Sc
 538
 539        private void SetPositionDirty(Vector2Int gridPosition, Vector2Int previous)
 540        {
 14541            positionDirty = gridPosition.x != currentGridSceneCoordinate.x || gridPosition.x != currentGridSceneCoordina
 542
 14543            if (positionDirty)
 544            {
 14545                sceneSortDirty = true;
 14546                currentGridSceneCoordinate = gridPosition;
 547
 548                // Since the first position for the character is not sent from Kernel until just-before calling
 549                // the rendering activation from Kernel, we need to sort the scenes to get the current scene id
 550                // to lock the rendering accordingly...
 14551                if (!CommonScriptableObjects.rendererState.Get())
 552                {
 0553                    SortScenesByDistance();
 554                }
 555            }
 14556        }
 557
 558        public void SortScenesByDistance()
 559        {
 560            // if (DCLCharacterController.i == null)
 561            //     return;
 562
 680563            IWorldState worldState = Environment.i.world.state;
 564
 680565            worldState.SortScenesByDistance(currentGridSceneCoordinate);
 566
 680567            string currentSceneId = worldState.GetCurrentSceneId();
 568
 680569            if (!DataStore.i.debugConfig.isDebugMode.Get() && string.IsNullOrEmpty(currentSceneId))
 570            {
 571                // When we don't know the current scene yet, we must lock the rendering from enabling until it is set
 660572                CommonScriptableObjects.rendererState.AddLock(this);
 660573            }
 574            else
 575            {
 576                // 1. Set current scene id
 20577                CommonScriptableObjects.sceneID.Set(currentSceneId);
 578
 579                // 2. Attempt to remove SceneController's lock on rendering
 20580                CommonScriptableObjects.rendererState.RemoveLock(this);
 581            }
 582
 680583            OnSortScenes?.Invoke();
 680584        }
 585
 586        private void OnCurrentSceneIdChange(string newSceneId, string prevSceneId)
 587        {
 78588            if (Environment.i.world.state.TryGetScene(newSceneId, out IParcelScene newCurrentScene)
 589                && !(newCurrentScene as ParcelScene).sceneLifecycleHandler.isReady)
 590            {
 0591                CommonScriptableObjects.rendererState.AddLock(newCurrentScene);
 592
 0593                (newCurrentScene as ParcelScene).sceneLifecycleHandler.OnSceneReady += (readyScene) => { CommonScriptabl
 594            }
 78595        }
 596
 597        public void LoadParcelScenesExecute(string scenePayload)
 598        {
 599            LoadParcelScenesMessage.UnityParcelScene scene;
 600
 26601            ProfilingEvents.OnMessageDecodeStart?.Invoke(MessagingTypes.SCENE_LOAD);
 26602            scene = Utils.SafeFromJson<LoadParcelScenesMessage.UnityParcelScene>(scenePayload);
 26603            ProfilingEvents.OnMessageDecodeEnds?.Invoke(MessagingTypes.SCENE_LOAD);
 604
 26605            if (scene == null || scene.id == null)
 0606                return;
 607
 26608            var sceneToLoad = scene;
 609
 26610            DebugConfig debugConfig = DataStore.i.debugConfig;
 611#if UNITY_EDITOR
 26612            if (debugConfig.soloScene && sceneToLoad.basePosition.ToString() != debugConfig.soloSceneCoords.ToString())
 613            {
 0614                SendSceneReady(sceneToLoad.id);
 615
 0616                return;
 617            }
 618#endif
 619
 26620            ProfilingEvents.OnMessageProcessStart?.Invoke(MessagingTypes.SCENE_LOAD);
 621
 26622            IWorldState worldState = Environment.i.world.state;
 623
 26624            if (!worldState.ContainsScene(sceneToLoad.id))
 625            {
 26626                var newGameObject = new GameObject("New Scene");
 627
 26628                var newScene = newGameObject.AddComponent<ParcelScene>();
 26629                newScene.SetData(sceneToLoad);
 630
 26631                if (debugConfig.isDebugMode.Get())
 632                {
 26633                    newScene.InitializeDebugPlane();
 634                }
 635
 26636                worldState.AddScene(sceneToLoad.id, newScene);
 637
 26638                sceneSortDirty = true;
 639
 26640                OnNewSceneAdded?.Invoke(newScene);
 641
 26642                messagingControllersManager.AddControllerIfNotExists(this, newScene.sceneData.id);
 643
 26644                if (VERBOSE)
 0645                    Debug.Log($"{Time.frameCount}: Load parcel scene (id: {newScene.sceneData.id})");
 646            }
 647
 26648            ProfilingEvents.OnMessageProcessEnds?.Invoke(MessagingTypes.SCENE_LOAD);
 0649        }
 650
 651        public void UpdateParcelScenesExecute(string sceneId)
 652        {
 653            LoadParcelScenesMessage.UnityParcelScene sceneData;
 654
 0655            ProfilingEvents.OnMessageDecodeStart?.Invoke(MessagingTypes.SCENE_UPDATE);
 0656            sceneData = Utils.SafeFromJson<LoadParcelScenesMessage.UnityParcelScene>(sceneId);
 0657            ProfilingEvents.OnMessageDecodeEnds?.Invoke(MessagingTypes.SCENE_UPDATE);
 658
 0659            IWorldState worldState = Environment.i.world.state;
 660
 0661            if (worldState.TryGetScene(sceneData.id, out IParcelScene sceneInterface))
 662            {
 0663                ParcelScene scene = sceneInterface as ParcelScene;
 0664                scene.SetUpdateData(sceneData);
 0665            }
 666            else
 667            {
 0668                LoadParcelScenesExecute(sceneId);
 669            }
 0670        }
 671
 672        public void UpdateParcelScenesExecute(LoadParcelScenesMessage.UnityParcelScene scene)
 673        {
 15674            if (scene == null || scene.id == null)
 0675                return;
 676
 15677            var sceneToLoad = scene;
 678
 15679            ProfilingEvents.OnMessageProcessStart?.Invoke(MessagingTypes.SCENE_UPDATE);
 680
 15681            ParcelScene parcelScene = Environment.i.world.state.GetScene(sceneToLoad.id) as ParcelScene;
 682
 15683            if (parcelScene != null)
 15684                parcelScene.SetUpdateData(sceneToLoad);
 685
 15686            ProfilingEvents.OnMessageProcessEnds?.Invoke(MessagingTypes.SCENE_UPDATE);
 0687        }
 688
 689        public void UnloadScene(string sceneKey)
 690        {
 1691            var queuedMessage = new QueuedSceneMessage()
 692                { type = QueuedSceneMessage.Type.UNLOAD_PARCEL, message = sceneKey };
 693
 1694            ProfilingEvents.OnMessageWillQueue?.Invoke(MessagingTypes.SCENE_DESTROY);
 695
 1696            messagingControllersManager.ForceEnqueueToGlobal(MessagingBusType.INIT, queuedMessage);
 1697            messagingControllersManager.RemoveController(sceneKey);
 1698        }
 699
 700        public void UnloadParcelSceneExecute(string sceneId)
 701        {
 419702            ProfilingEvents.OnMessageProcessStart?.Invoke(MessagingTypes.SCENE_DESTROY);
 703
 419704            IWorldState worldState = Environment.i.world.state;
 705
 419706            if (!worldState.TryGetScene(sceneId, out ParcelScene scene))
 0707                return;
 708
 419709            worldState.RemoveScene(sceneId);
 710
 419711            DataStore.i.world.portableExperienceIds.Remove(sceneId);
 712
 713            // Remove messaging controller for unloaded scene
 419714            messagingControllersManager.RemoveController(sceneId);
 715
 419716            scene.Cleanup(!CommonScriptableObjects.rendererState.Get());
 717
 419718            if (VERBOSE)
 719            {
 0720                Debug.Log($"{Time.frameCount} : Destroying scene {scene.sceneData.basePosition}");
 721            }
 722
 419723            Environment.i.world.blockersController.SetupWorldBlockers();
 724
 419725            ProfilingEvents.OnMessageProcessEnds?.Invoke(MessagingTypes.SCENE_DESTROY);
 419726            OnSceneRemoved?.Invoke(scene);
 0727        }
 728
 729        public void UnloadAllScenes(bool includePersistent = false)
 730        {
 686731            var worldState = Environment.i.world.state;
 732
 733            // since the list was changing by this foreach, we make a copy
 686734            var list = worldState.GetLoadedScenes().ToArray();
 735
 2202736            foreach (var kvp in list)
 737            {
 415738                if (kvp.Value.isPersistent && !includePersistent)
 739                    continue;
 740
 415741                UnloadParcelSceneExecute(kvp.Key);
 742            }
 686743        }
 744
 745        public void LoadParcelScenes(string decentralandSceneJSON)
 746        {
 26747            var queuedMessage = new QueuedSceneMessage()
 748            {
 749                type = QueuedSceneMessage.Type.LOAD_PARCEL,
 750                message = decentralandSceneJSON
 751            };
 752
 26753            ProfilingEvents.OnMessageWillQueue?.Invoke(MessagingTypes.SCENE_LOAD);
 754
 26755            messagingControllersManager.ForceEnqueueToGlobal(MessagingBusType.INIT, queuedMessage);
 756
 26757            if (VERBOSE)
 0758                Debug.Log($"{Time.frameCount} : Load parcel scene queue {decentralandSceneJSON}");
 26759        }
 760
 761        public void UpdateParcelScenes(string decentralandSceneJSON)
 762        {
 0763            var queuedMessage = new QueuedSceneMessage()
 764                { type = QueuedSceneMessage.Type.UPDATE_PARCEL, message = decentralandSceneJSON };
 765
 0766            ProfilingEvents.OnMessageWillQueue?.Invoke(MessagingTypes.SCENE_UPDATE);
 767
 0768            messagingControllersManager.ForceEnqueueToGlobal(MessagingBusType.INIT, queuedMessage);
 0769        }
 770
 771        public void UnloadAllScenesQueued()
 772        {
 0773            var queuedMessage = new QueuedSceneMessage() { type = QueuedSceneMessage.Type.UNLOAD_SCENES };
 774
 0775            ProfilingEvents.OnMessageWillQueue?.Invoke(MessagingTypes.SCENE_DESTROY);
 776
 0777            Environment.i.messaging.manager.ForceEnqueueToGlobal(MessagingBusType.INIT, queuedMessage);
 0778        }
 779
 780        public void CreateGlobalScene(string json)
 781        {
 782#if UNITY_EDITOR
 5783            DebugConfig debugConfig = DataStore.i.debugConfig;
 784
 5785            if (debugConfig.soloScene && debugConfig.ignoreGlobalScenes)
 0786                return;
 787#endif
 5788            CreateGlobalSceneMessage globalScene = Utils.SafeFromJson<CreateGlobalSceneMessage>(json);
 789
 790            // NOTE(Brian): We should remove this line. SceneController is a runtime core class.
 791            //              It should never have references to UI systems or higher level systems.
 5792            if (globalScene.isPortableExperience && !isPexViewerInitialized.Get())
 793            {
 0794                Debug.LogError(
 795                    "Portable experiences are trying to be added before the system is initialized!. SceneID: " +
 796                    globalScene.id);
 0797                return;
 798            }
 799
 5800            string newGlobalSceneId = globalScene.id;
 801
 5802            IWorldState worldState = Environment.i.world.state;
 803
 5804            if (worldState.ContainsScene(newGlobalSceneId))
 0805                return;
 806
 5807            var newGameObject = new GameObject("Global Scene - " + newGlobalSceneId);
 808
 5809            var newScene = newGameObject.AddComponent<GlobalScene>();
 5810            newScene.unloadWithDistance = false;
 5811            newScene.isPersistent = true;
 5812            newScene.sceneName = globalScene.name;
 5813            newScene.isPortableExperience = globalScene.isPortableExperience;
 814
 5815            LoadParcelScenesMessage.UnityParcelScene data = new LoadParcelScenesMessage.UnityParcelScene
 816            {
 817                id = newGlobalSceneId,
 818                basePosition = new Vector2Int(0, 0),
 819                baseUrl = globalScene.baseUrl,
 820                contents = globalScene.contents
 821            };
 822
 5823            newScene.SetData(data);
 824
 5825            if (!string.IsNullOrEmpty(globalScene.icon))
 826            {
 0827                newScene.iconUrl = newScene.contentProvider.GetContentsUrl(globalScene.icon);
 828            }
 829
 5830            worldState.AddGlobalScene(newGlobalSceneId, newScene);
 5831            OnNewSceneAdded?.Invoke(newScene);
 832
 5833            if (newScene.isPortableExperience)
 834            {
 2835                DataStore.i.world.portableExperienceIds.Add(newGlobalSceneId);
 836            }
 837
 5838            messagingControllersManager.AddControllerIfNotExists(this, newGlobalSceneId, isGlobal: true);
 839
 5840            if (VERBOSE)
 0841                Debug.Log($"Creating Global scene {newGlobalSceneId}");
 5842        }
 843
 844        public void IsolateScene(IParcelScene sceneToActive)
 845        {
 156846            foreach (IParcelScene scene in Environment.i.world.state.GetScenesSortedByDistance())
 847            {
 39848                if (scene != sceneToActive)
 5849                    scene.GetSceneTransform().gameObject.SetActive(false);
 850            }
 39851        }
 852
 853        public void ReIntegrateIsolatedScene()
 854        {
 20855            foreach (IParcelScene scene in Environment.i.world.state.GetScenesSortedByDistance())
 856            {
 5857                scene.GetSceneTransform().gameObject.SetActive(true);
 858            }
 5859        }
 860
 861        //======================================================================
 862
 863        #endregion
 864
 865        //======================================================================
 866
 684867        public ConcurrentQueue<QueuedSceneMessage_Scene> sceneMessagesPool { get; } = new ConcurrentQueue<QueuedSceneMes
 868
 684869        public bool prewarmSceneMessagesPool { get; set; } = true;
 684870        public bool prewarmEntitiesPool { get; set; } = true;
 871
 872        private bool sceneSortDirty = false;
 684873        private bool positionDirty = true;
 874        private int lastSortFrame = 0;
 875
 876        public event Action OnSortScenes;
 877        public event Action<IParcelScene, string> OnOpenExternalUrlRequest;
 878        public event Action<IParcelScene> OnNewSceneAdded;
 879        public event Action<IParcelScene> OnSceneRemoved;
 880
 684881        private Vector2Int currentGridSceneCoordinate = new Vector2Int(EnvironmentSettings.MORDOR_SCALAR, EnvironmentSet
 882    }
 883}

Methods/Properties

enabled()
enabled(System.Boolean)
SceneController()
isPexViewerInitialized()
messagingControllersManager()
entityIdHelper()
Initialize()
SetupDeferredRunners()
>c__DisplayClass17_0/<<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.String)
SendSceneMessage(System.String)
Decode(System.String, DCL.QueuedSceneMessage_Scene)
DeferredDecodingAndEnqueue()
EnqueueChunk(System.String)
WatchForNewChunksToDecode()
ThreadedDecodeAndEnqueue(System.Threading.CancellationToken)
EnqueueSceneMessage(DCL.QueuedSceneMessage_Scene)
SendSceneReady(System.String)
ActivateBuilderInWorldEditScene()
DeactivateBuilderInWorldEditScene()
SetPositionDirty(UnityEngine.Vector2Int, UnityEngine.Vector2Int)
SortScenesByDistance()
OnCurrentSceneIdChange(System.String, System.String)
LoadParcelScenesExecute(System.String)
UpdateParcelScenesExecute(System.String)
UpdateParcelScenesExecute(DCL.Models.LoadParcelScenesMessage/UnityParcelScene)
UnloadScene(System.String)
UnloadParcelSceneExecute(System.String)
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)