-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathMainSceneLoader.cs
More file actions
927 lines (735 loc) · 40.9 KB
/
Copy pathMainSceneLoader.cs
File metadata and controls
927 lines (735 loc) · 40.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
using AltTester.AltTesterUnitySDK.Commands;
using Arch.Core;
using CommunicationData.URLHelpers;
using CRDT;
using CrdtEcsBridge.Components;
using Cysharp.Threading.Tasks;
using DCL.ApplicationGuards;
using DCL.AssetsProvision;
using DCL.Audio;
using DCL.Browser;
using DCL.Browser.DecentralandUrls;
using DCL.DebugUtilities;
using DCL.Diagnostics;
using DCL.FeatureFlags;
using DCL.Global.Dynamic;
using DCL.Infrastructure.Global;
using DCL.Input.Component;
using DCL.Multiplayer.Connections.DecentralandUrls;
using DCL.Multiplayer.HealthChecks;
using DCL.Multiplayer.HealthChecks.Struct;
using DCL.Optimization.PerformanceBudgeting;
using DCL.PerformanceAndDiagnostics.Analytics;
using DCL.PluginSystem;
using DCL.PluginSystem.Global;
using DCL.PluginSystem.World;
using DCL.Prefs;
using DCL.Quality.Runtime;
using DCL.SceneLoadingScreens.SplashScreen;
using DCL.UI.ErrorPopup;
using DCL.Utilities;
using DCL.Utilities.Extensions;
using DCL.Utility;
using DCL.Utility.Types;
using DCL.Web3.Accounts.Factory;
using DCL.Web3.Identities;
using DCL.WebRequests;
using DG.Tweening;
using ECS;
using ECS.StreamableLoading.Cache.Disk;
using ECS.StreamableLoading.Cache.Disk.CleanUp;
using ECS.StreamableLoading.Cache.Disk.Lock; // IGNORE_LINE_WEBGL_THREAD_SAFETY_FLAG
using ECS.StreamableLoading.Common;
using ECS.StreamableLoading.Common.Components;
using Global.AppArgs;
using Global.Versioning;
using MVC;
using Newtonsoft.Json.Linq;
using Plugins.NativeWindowManager;
using SceneRunner.Debugging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.UI;
using Utility;
using MinimumSpecsScreenView = DCL.ApplicationGuards.MinimumSpecsScreenView;
// ReSharper disable once CheckNamespace
namespace Global.Dynamic
{
public class MainSceneLoader : MonoBehaviour, ICoroutineRunner
{
[Header("STARTUP CONFIG")] [SerializeField]
private RealmLaunchSettings launchSettings = null!;
[Space]
[SerializeField] private DecentralandEnvironment decentralandEnvironment;
[Space]
[SerializeField] private DebugSettings.DebugSettings debugSettings = new ();
[Header("REFERENCES")]
[SerializeField] private PluginSettingsContainer pluginSettingsContainer = null!;
[SerializeField] private DynamicSceneLoaderSettings settings = null!;
[SerializeField] private SplashScreenRef splashScreenRef = null!;
[SerializeField] private DynamicSettings dynamicSettings = null!;
[SerializeField] private AudioClipConfig backgroundMusic = null!;
[SerializeField] private WorldInfoTool worldInfoTool = null!;
[SerializeField] private AssetReferenceGameObject untrustedRealmConfirmationPrefab = null!;
[SerializeField] private AssetReferenceGameObject singleInstanceRunningPopupPrefab = null!;
[SerializeField] private ErrorPopupWithRetryRef clockDesyncPopupRef = null!;
[SerializeField] private GameObject altTesterPrefab = null!;
private BootstrapContainer? bootstrapContainer;
private StaticContainer? staticContainer;
private DynamicWorldContainer? dynamicWorldContainer;
private GlobalWorld? globalWorld;
private ProvidedInstance<SplashScreen> splashScreen;
private FileStream? singleInstanceLock;
private ErrorPopupWithRetryView? clockDesyncPopupPrefab;
private bool canShutdown;
private void Awake()
{
InitializeFlowAsync(destroyCancellationToken).Forget();
}
private void OnDestroy()
{
Shutdown();
}
private void Shutdown()
{
if (PlayerLoopHelper.IsMainThread == false)
return;
if (canShutdown == false)
return;
canShutdown = false;
var stopwatch = ShutdownStopwatch.StartNew(nameof(MainSceneLoader));
DisableAllSelectableTransitions();
stopwatch.LogStep(nameof(DisableAllSelectableTransitions));
if (dynamicWorldContainer != null)
{
foreach (IDCLGlobalPlugin plugin in dynamicWorldContainer.GlobalPlugins)
{
plugin.SafeDispose(ReportCategory.ENGINE);
stopwatch.LogStep($"GlobalPlugin {plugin.GetType().Name}");
}
foreach (IDCLWorldPlugin worldPlugin in dynamicWorldContainer.WorldPlugins)
{
worldPlugin.SafeDispose(ReportCategory.ENGINE);
stopwatch.LogStep($"WorldPlugin {worldPlugin.GetType().Name}");
}
if (globalWorld != null)
{
dynamicWorldContainer.RealmController.DisposeGlobalWorld();
stopwatch.LogStep("DisposeGlobalWorld");
}
dynamicWorldContainer.SafeDispose(ReportCategory.ENGINE);
stopwatch.LogStep("dynamicWorldContainer.SafeDispose");
}
if (staticContainer != null)
{
// Exclude SharedPlugins as they were disposed as they were already disposed of as `GlobalPlugins`
foreach (IDCLPlugin worldPlugin in staticContainer.ECSWorldPlugins.Except<IDCLPlugin>(staticContainer.SharedPlugins))
{
worldPlugin.SafeDispose(ReportCategory.ENGINE);
stopwatch.LogStep($"ECSWorldPlugin {worldPlugin.GetType().Name}");
}
staticContainer.SafeDispose(ReportCategory.ENGINE);
stopwatch.LogStep("staticContainer.SafeDispose");
}
bootstrapContainer?.Dispose();
stopwatch.LogStep("bootstrapContainer.Dispose");
splashScreen.Dispose();
stopwatch.LogStep("splashScreen.Dispose");
ReportHub.LogProductionInfo($"[MainSceneLoader] OnDestroy successfully finished in {stopwatch.ElapsedMilliseconds}ms");
}
private void OnApplicationQuit()
{
// Dispose just in case, but if the process ends normally or by a crash, the lock should also be released due to how native OS works
try { singleInstanceLock?.Dispose(); }
catch { }
DisableAllSelectableTransitions();
}
public void ApplyConfig(IAppArgs applicationParametersParser)
{
if (applicationParametersParser.TryGetValue(AppArgsFlags.ENVIRONMENT, out string? environment))
ParseEnvironment(environment!);
ExitUtils.Configure(
softShutdown: applicationParametersParser.HasFlag(AppArgsFlags.SOFT_SHUTDOWN),
nativeShutdownStopwatch: applicationParametersParser.HasFlag(AppArgsFlags.NATIVE_SHUTDOWN_STOPWATCH)
);
}
private void ParseEnvironment(string environment)
{
if (Enum.TryParse(environment, true, out DecentralandEnvironment env))
decentralandEnvironment = env;
}
private async UniTask InitializeFlowAsync(CancellationToken ct)
{
canShutdown = true;
ExitUtils.RegisterCleanUpCandidate(new OnQuittingCleanUpCandidate(nameof(MainSceneLoader), Shutdown));
IAppArgs applicationParametersParser = new ApplicationParametersParser(
#if UNITY_EDITOR
debugSettings.AppParameters
#else
Environment.GetCommandLineArgs()
#endif
);
FeatureFlagsConfiguration.Initialize(new FeatureFlagsConfiguration(FeatureFlagsResultDto.Empty));
DCLVersion dclVersion = DCLVersion.FromAppArgs(applicationParametersParser);
DiagnosticInfoUtils.LogSystem(dclVersion.Version);
// Memory limit
bool hasSimulatedMemory = applicationParametersParser.TryGetValue(AppArgsFlags.SIMULATE_MEMORY, out string simulatedMemory);
int systemMemory = hasSimulatedMemory ? int.Parse(simulatedMemory) : SystemInfo.systemMemorySize;
ISystemMemoryCap memoryCap = hasSimulatedMemory
? new SystemMemoryCap(systemMemory)
: new SystemMemoryCap();
ApplyConfig(applicationParametersParser);
launchSettings.ApplyConfig(applicationParametersParser);
NativeWindowManager.Initialize(
applicationParametersParser.HasFlag(AppArgsFlags.DISABLE_WINDOW_RESTRICTIONS),
applicationParametersParser.HasFlag(AppArgsFlags.WINDOWED_MODE),
GetResolutionFromAppArgs(applicationParametersParser));
World world = World.Create();
var realmData = new RealmData();
applicationParametersParser.TryGetValue(AppArgsFlags.GATEKEEPER_URL, out string? cliGatekeeperUrl);
applicationParametersParser.TryGetValue(AppArgsFlags.OPTIMIZED_ASSETS_URL, out string? cliOptimizedAssetsUrl);
if (string.IsNullOrEmpty(cliOptimizedAssetsUrl) && launchSettings.useLocalAssetBundles)
cliOptimizedAssetsUrl = launchSettings.LocalAssetBundlesBaseUrl();
var decentralandUrlsSource = new GatewayUrlsSource(
decentralandEnvironment,
realmData,
launchSettings,
debugSettings.GatekeeperMode,
debugSettings.CustomGatekeeperUrl,
cliGatekeeperUrl,
cliOptimizedAssetsUrl);
DiagnosticInfoUtils.LogEnvironment(decentralandUrlsSource);
var assetsProvisioner = new AddressablesProvisioner();
splashScreen = (await assetsProvisioner.ProvideInstanceAsync(splashScreenRef, ct: ct));
// Alttester Automation (only works when ALTTESTER define is set), needs to run after splash is instantiated
if (applicationParametersParser.HasFlag(AppArgsFlags.ALTTESTER))
InstantiateAltTester(applicationParametersParser);
var web3AccountFactory = new Web3AccountFactory();
var identityCache = new IWeb3IdentityCache.Default(web3AccountFactory, decentralandEnvironment);
var debugViewsCatalog = (await assetsProvisioner.ProvideMainAssetAsync(dynamicSettings.DebugViewsCatalog, ct)).Value;
var debugContainer = DebugUtilitiesContainer.Create(debugViewsCatalog, applicationParametersParser.HasDebugFlag(), applicationParametersParser.HasFlag(AppArgsFlags.LOCAL_SCENE));
var diskCache = NewInstanceDiskCache(applicationParametersParser, launchSettings);
var partialsDiskCache = NewInstancePartialDiskCache(applicationParametersParser, launchSettings);
bootstrapContainer = await BootstrapContainer.CreateAsync(
assetsProvisioner,
debugSettings,
sceneLoaderSettings: settings,
decentralandUrlsSource,
debugContainer,
identityCache,
pluginSettingsContainer,
launchSettings,
applicationParametersParser,
splashScreen.Value,
diskCache,
partialsDiskCache,
world,
decentralandEnvironment,
dclVersion,
destroyCancellationToken
);
IBootstrap bootstrap = bootstrapContainer!.Bootstrap!;
try
{
await bootstrap.PreInitializeSetupAsync(destroyCancellationToken);
if (ShouldForceSingleRunningInstance(applicationParametersParser))
{
await ShowSingleRunningInstancePopupAsync(assetsProvisioner, ct);
return;
}
Entity playerEntity = world.Create(new CRDTEntity(SpecialEntitiesID.PLAYER_ENTITY));
await bootstrap.InitializeFeatureFlagsAsync(bootstrapContainer.IdentityCache!.Identity,
bootstrapContainer.DecentralandUrlsSource, ct);
bootstrap.InitializeFeaturesRegistry();
bootstrap.ApplyFeatureFlagConfigs(FeatureFlagsConfiguration.Instance);
DiagnosticInfoUtils.LogFeatureFlags(FeatureFlagsConfiguration.Instance.AllEnabledFlags);
// Need to ensure clock sync ASAP due to some requests may fail due this problem.
// Checking for clock desync after feature flags (or any other process that performs an http request)
// potentially saves one extra HEAD request
var ensureClockSyncAction = new EnsureClockSync(bootstrapContainer.RealmClock, bootstrapContainer.WebRequestsContainer.WebRequestController,
ShowClockDesyncPopupAsync, bootstrapContainer.DecentralandUrlsSource);
await ensureClockSyncAction.ExecuteAsync(ct);
bool isLoaded;
(staticContainer, isLoaded) = await bootstrap.LoadStaticContainerAsync(bootstrapContainer, pluginSettingsContainer, debugContainer.Builder, realmData, playerEntity, memoryCap, applicationParametersParser, ct);
if (!isLoaded)
{
GameReports.PrintIsDead();
return;
}
bootstrap.InitializePlayerEntity(staticContainer!, playerEntity);
staticContainer!.SceneLoadingLimit.SetEnabled(FeatureFlagsConfiguration.Instance.IsEnabled(FeatureFlagsStrings.SCENE_MEMORY_LIMIT));
OfficialWalletsHelper.Initialize(new OfficialWalletsHelper());
(dynamicWorldContainer, isLoaded) = await bootstrap.LoadDynamicWorldContainerAsync(
bootstrapContainer,
staticContainer!,
pluginSettingsContainer,
settings,
dynamicSettings,
backgroundMusic,
worldInfoTool.EnsureNotNull(),
playerEntity,
applicationParametersParser,
coroutineRunner: this,
dclVersion,
destroyCancellationToken);
if (!isLoaded)
{
GameReports.PrintIsDead();
return;
}
if (!await InitialGuardsCheckSuccessAsync(applicationParametersParser, decentralandUrlsSource, ct))
return;
var specResults = await VerifyMinimumHardwareRequirementMetAsync(applicationParametersParser, bootstrapContainer.WebBrowser, bootstrapContainer.Analytics.Controller, ct);
if (FeaturesRegistry.Instance.IsEnabled(FeatureId.CheckDiskSpace))
await BlockOnInsufficientDiskSpaceAsync(specResults, applicationParametersParser, ct);
if (!await IsTrustedRealmAsync(decentralandUrlsSource, ct))
{
splashScreen.Value.Hide();
if (!await ShowUntrustedRealmConfirmationAsync(ct))
{
ExitUtils.Exit();
return;
}
splashScreen.Value.Show();
}
DisableInputs();
if (await bootstrap.InitializePluginsAsync(staticContainer!, dynamicWorldContainer!, pluginSettingsContainer, bootstrapContainer.Analytics.Controller, ct))
{
GameReports.PrintIsDead();
return;
}
globalWorld = bootstrap.CreateGlobalWorld(bootstrapContainer, staticContainer!, dynamicWorldContainer!, debugContainer.RootDocument, playerEntity);
await LoadStartingRealmAsync(ct);
await LoadUserFlowAsync(playerEntity, ct);
//This is done to release the memory usage of the splash screen logo animation sprites
//The logo is used only at first launch, so we can safely release it after the game is loaded
splashScreen.Dispose();
RestoreInputs();
}
catch (OperationCanceledException)
{
// ignore
}
catch (Exception)
{
// unhandled exception
GameReports.PrintIsDead();
throw;
}
return;
async UniTask LoadStartingRealmAsync(CancellationToken ct)
{
try { await bootstrap.LoadStartingRealmAsync(dynamicWorldContainer!, ct); }
catch (RealmChangeException)
{
if (await ShowLoadErrorPopupAsync(ct) == ErrorPopupWithRetryController.Result.Restart)
await LoadStartingRealmAsync(ct);
else
ExitUtils.Exit();
}
}
async UniTask LoadUserFlowAsync(Entity playerEntity, CancellationToken ct)
{
try { await bootstrap.UserInitializationAsync(dynamicWorldContainer!, bootstrapContainer, globalWorld, playerEntity, ct); }
catch (TimeoutException)
{
if (await ShowLoadErrorPopupAsync(ct) == ErrorPopupWithRetryController.Result.Restart)
await LoadUserFlowAsync(playerEntity, ct);
else
throw;
}
catch (RealmChangeException)
{
if (await ShowLoadErrorPopupAsync(ct) == ErrorPopupWithRetryController.Result.Restart)
await LoadUserFlowAsync(playerEntity, ct);
else
ExitUtils.Exit();
}
}
}
private async UniTask ShowSingleRunningInstancePopupAsync(AddressablesProvisioner assetsProvisioner, CancellationToken ct)
{
ErrorPopupView prefab = (await assetsProvisioner.ProvideMainAssetAsync(singleInstanceRunningPopupPrefab, ct)).Value.GetComponent<ErrorPopupView>();
ErrorPopupView popup = Instantiate(prefab);
popup.OkButton.onClick.AddListener(ExitUtils.Exit);
}
private bool ShouldForceSingleRunningInstance(IAppArgs appArgs)
{
#if UNITY_EDITOR
return false;
#endif
if (appArgs.HasFlag(AppArgsFlags.MULTIPLE_RUNNING_INSTANCES)) return false;
try
{
string lockPath = Path.Combine(Application.persistentDataPath, "instance.lock");
// Note that FileShare.None should lock the file to other processes, and it does,
// but only on Windows. And .Lock(0, 0) does the same, but only on MacOS. // IGNORE_LINE_WEBGL_THREAD_SAFETY_FLAG
singleInstanceLock = new FileStream(lockPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
singleInstanceLock.Lock(0, 0); // IGNORE_LINE_WEBGL_THREAD_SAFETY_FLAG
}
catch (IOException) { return true; }
catch (Exception e) { ReportHub.LogException(e, ReportCategory.STARTUP); }
return false;
}
private async UniTask RegisterBlockedPopupAsync(UnityAppWebBrowser webBrowser, CancellationToken ct)
{
var blockedPopupPrefab = await bootstrapContainer!.AssetsProvisioner!.ProvideMainAssetAsync(dynamicSettings.BlockedScreenPrefab, ct);
ControllerBase<BlockedScreenView, BlockedScreenParameters>.ViewFactoryMethod viewFactory =
BlockedScreenController.CreateLazily(blockedPopupPrefab.Value.GetComponent<BlockedScreenView>(), null);
var launcherRedirectionScreenController = new BlockedScreenController(viewFactory, webBrowser);
dynamicWorldContainer!.MvcManager.RegisterController(launcherRedirectionScreenController);
}
private async UniTask<IReadOnlyList<SpecResult>> VerifyMinimumHardwareRequirementMetAsync(IAppArgs applicationParametersParser, UnityAppWebBrowser webBrowser, IAnalyticsController analytics, CancellationToken ct)
{
var minimumSpecsGuard = new MinimumSpecsGuard(new DefaultSpecProfileProvider(),
new UnitySystemInfoProvider());
bool forceShow = applicationParametersParser.HasFlag(AppArgsFlags.FORCE_MINIMUM_SPECS_SCREEN);
bool skipScreen = applicationParametersParser.HasFlag(AppArgsFlags.SKIP_MINIMUM_SPECS_SCREEN) && !forceShow;
bool hasMinimumSpecs = minimumSpecsGuard.HasMinimumSpecs() && !forceShow;
if (!hasMinimumSpecs && !skipScreen)
SavedQualitySettingsApplier.EnforceLowPreset();
bool userWantsToSkip = DCLPlayerPrefs.GetBool(DCLPrefKeys.DONT_SHOW_MIN_SPECS_SCREEN);
bootstrapContainer.DiagnosticsContainer.AddSentryScopeConfigurator(scope => { bootstrapContainer.DiagnosticsContainer.Sentry!.AddMeetMinimumRequirements(scope, hasMinimumSpecs); });
UnityDiagnosticsCenter.Instance.SetMeetsMinimumRequirements(hasMinimumSpecs);
var specsProperties = new JObject
{
["meets_requirements"] = hasMinimumSpecs,
};
foreach (SpecResult result in minimumSpecsGuard.Results)
{
string categoryKey = result.Category.ToString().ToLowerInvariant();
specsProperties[$"{categoryKey}_met"] = result.IsMet;
if (!result.IsMet)
{
specsProperties[$"{categoryKey}_required"] = result.Required;
specsProperties[$"{categoryKey}_actual"] = result.Actual;
}
}
analytics.Track(AnalyticsEvents.General.MEETS_MINIMUM_REQUIREMENTS, specsProperties);
bool shouldShowScreen = forceShow || (!skipScreen && !userWantsToSkip && !hasMinimumSpecs);
if (!shouldShowScreen)
return minimumSpecsGuard.Results;
var minimumRequirementsPrefab = await bootstrapContainer!
.AssetsProvisioner!
.ProvideMainAssetAsync(dynamicSettings.MinimumSpecsScreenPrefab, ct);
ControllerBase<MinimumSpecsScreenView, ControllerNoData>.ViewFactoryMethod viewFactory = MinimumSpecsScreenController
.CreateLazily(minimumRequirementsPrefab.Value.GetComponent<MinimumSpecsScreenView>(), null);
var minimumSpecsResults = minimumSpecsGuard.Results;
var minimumSpecsScreenController = new MinimumSpecsScreenController(viewFactory, webBrowser, analytics, minimumSpecsResults);
dynamicWorldContainer!.MvcManager.RegisterController(minimumSpecsScreenController);
dynamicWorldContainer!.MvcManager.ShowAsync(MinimumSpecsScreenController.IssueCommand(), ct).Forget();
await minimumSpecsScreenController.HoldingTask.Task;
return minimumSpecsGuard.Results;
}
private async UniTask BlockOnInsufficientDiskSpaceAsync(IReadOnlyList<SpecResult> specResults, IAppArgs applicationParametersParser, CancellationToken ct)
{
bool forceShow = applicationParametersParser.HasFlag(AppArgsFlags.FORCE_CHECK_DISK_SPACE);
bool storageMet = true;
foreach (SpecResult result in specResults)
{
if (result.Category == SpecCategory.Storage)
{
storageMet = result.IsMet;
break;
}
}
if (storageMet && !forceShow)
return;
var insufficientDiskSpacePrefab = await bootstrapContainer!
.AssetsProvisioner!
.ProvideMainAssetAsync(dynamicSettings.InsufficientDiskSpaceScreenPrefab, ct);
ControllerBase<InsufficientDiskSpaceScreenView, ControllerNoData>.ViewFactoryMethod viewFactory =
InsufficientDiskSpaceScreenController.CreateLazily(insufficientDiskSpacePrefab.Value.GetComponent<InsufficientDiskSpaceScreenView>(), null);
var controller = new InsufficientDiskSpaceScreenController(viewFactory);
dynamicWorldContainer!.MvcManager.RegisterController(controller);
await dynamicWorldContainer!.MvcManager.ShowAsync(InsufficientDiskSpaceScreenController.IssueCommand(), ct);
}
private async UniTask<bool> InitialGuardsCheckSuccessAsync(IAppArgs applicationParametersParser, DecentralandUrlsSource dclSources,
CancellationToken ct)
{
//If Livekit is down, stop bootstrapping
if (await IsLIvekitDeadAsync(staticContainer!.WebRequestsContainer.WebRequestController, dclSources, ct))
return false;
//If application requires version update, stop bootstrapping
if (await DoesApplicationRequireVersionUpdateAsync(applicationParametersParser, splashScreen.Value, ct))
return false;
//The BlockedGuard is registered here, but nothing to do. We need the user to be able to detect if block is required
await RegisterBlockedPopupAsync(bootstrapContainer!.WebBrowser, ct);
return true;
}
private async UniTask<bool> IsLIvekitDeadAsync(IWebRequestController webRequestController, DecentralandUrlsSource decentralandUrlsSource, CancellationToken ct)
{
SequentialHealthCheck healthCheck = new SequentialHealthCheck(
new MultipleURLHealthCheck(webRequestController, decentralandUrlsSource,
DecentralandUrl.ArchipelagoStatus,
DecentralandUrl.GatekeeperStatus
).WithRetries(3));
Result result = await healthCheck.IsRemoteAvailableAsync(ct);
if (result.Success) return false;
var livekitDownPrefab = await bootstrapContainer!.AssetsProvisioner!.ProvideMainAssetAsync(dynamicSettings.LivekitDownPrefab, ct);
ControllerBase<LivekitHealthGuardView, ControllerNoData>.ViewFactoryMethod viewFactory =
LivekitHealthGuardController.CreateLazily(livekitDownPrefab.Value.GetComponent<LivekitHealthGuardView>(), null);
dynamicWorldContainer!.MvcManager.RegisterController(new LivekitHealthGuardController(viewFactory));
dynamicWorldContainer!.MvcManager.ShowAsync(LivekitHealthGuardController.IssueCommand(), ct).Forget();
return true;
}
private async UniTask<bool> DoesApplicationRequireVersionUpdateAsync(IAppArgs applicationParametersParser, SplashScreen splashScreen, CancellationToken ct)
{
DCLVersion currentVersion = DCLVersion.FromAppArgs(applicationParametersParser);
bool runVersionControl = debugSettings.EnableVersionUpdateGuard;
if (!Application.isEditor)
runVersionControl = !applicationParametersParser.HasDebugFlag() &&
!applicationParametersParser.HasFlag(AppArgsFlags.SKIP_VERSION_CHECK) &&
!applicationParametersParser.HasFlag(AppArgsFlags.AUTOPILOT);
if (!runVersionControl)
return false;
var appVersionGuard = new ApplicationVersionGuard(staticContainer!.WebRequestsContainer.WebRequestController, bootstrapContainer!.WebBrowser);
string? latestVersion = await appVersionGuard.GetLatestVersionAsync(ct);
if (!currentVersion.Version.IsOlderThan(latestVersion))
return false;
splashScreen.Hide();
var appVerRedirectionScreenPrefab = await bootstrapContainer!.AssetsProvisioner!.ProvideMainAssetAsync(dynamicSettings.AppVerRedirectionScreenPrefab, ct);
ControllerBase<LauncherRedirectionScreenView, ControllerNoData>.ViewFactoryMethod authScreenFactory =
LauncherRedirectionScreenController.CreateLazily(appVerRedirectionScreenPrefab.Value.GetComponent<LauncherRedirectionScreenView>(), null);
var launcherRedirectionScreenController = new LauncherRedirectionScreenController(appVersionGuard, authScreenFactory, currentVersion.Version, latestVersion);
dynamicWorldContainer!.MvcManager.RegisterController(launcherRedirectionScreenController);
await dynamicWorldContainer!.MvcManager.ShowAsync(LauncherRedirectionScreenController.IssueCommand(), ct);
return true;
}
private void DisableInputs()
{
// We disable Inputs directly because otherwise before login (so before the Input component was created and the system that handles it is working)
// all inputs will be valid, and it allows for weird behaviour, including opening menus that are not ready to be open yet.
DCLInput dclInput = DCLInput.Instance;
dclInput.Shortcuts.Disable();
dclInput.Player.Disable();
dclInput.Emotes.Disable();
dclInput.EmoteWheel.Disable();
dclInput.FreeCamera.Disable();
dclInput.Camera.Disable();
dclInput.UI.Disable();
}
private void RestoreInputs()
{
// We enable Inputs through the inputBlock so the block counters can be properly updated and the component Active flags are up-to-date as well
// We restore all inputs except EmoteWheel and FreeCamera as they should be disabled by default
staticContainer!.InputBlock.EnableAll(InputMapComponent.Kind.FreeCamera,
InputMapComponent.Kind.EmoteWheel);
DCLInput.Instance.UI.Enable();
}
private static IDiskCache<PartialLoadingState> NewInstancePartialDiskCache(IAppArgs appArgs, RealmLaunchSettings launchSettings)
{
if (launchSettings.CurrentMode == LaunchMode.LocalSceneDevelopment)
{
ReportHub.Log(ReportData.UNSPECIFIED, "Disk cached disabled while LSD");
return IDiskCache<PartialLoadingState>.Null.INSTANCE;
}
if (appArgs.HasFlag(AppArgsFlags.DISABLE_DISK_CACHE))
{
ReportHub.Log(ReportData.UNSPECIFIED, $"Disable disk cache, flag --{AppArgsFlags.DISABLE_DISK_CACHE} is passed");
return IDiskCache<PartialLoadingState>.Null.INSTANCE;
}
var cacheDirectory = CacheDirectory.NewDefaultSubdirectory("partials");
var filesLock = new FilesLock();
IDiskCleanUp diskCleanUp;
if (appArgs.HasFlag(AppArgsFlags.DISABLE_DISK_CACHE_CLEANUP))
{
ReportHub.Log(ReportData.UNSPECIFIED, $"Disable disk cache cleanup, flag --{AppArgsFlags.DISABLE_DISK_CACHE_CLEANUP} is passed");
diskCleanUp = IDiskCleanUp.None.INSTANCE;
}
else
diskCleanUp = new LRUDiskCleanUp(cacheDirectory, filesLock);
var partialCache = new DiskCache<PartialLoadingState, SerializeMemoryIterator<PartialDiskSerializer.State>>(new DiskCache(cacheDirectory, filesLock, diskCleanUp), new PartialDiskSerializer());
return partialCache;
}
private static IDiskCache NewInstanceDiskCache(IAppArgs appArgs, RealmLaunchSettings launchSettings)
{
if (launchSettings.CurrentMode == LaunchMode.LocalSceneDevelopment)
{
ReportHub.Log(ReportData.UNSPECIFIED, "Disk cached disabled while LSD");
return new IDiskCache.Fake();
}
if (appArgs.HasFlag(AppArgsFlags.DISABLE_DISK_CACHE))
{
ReportHub.Log(ReportData.UNSPECIFIED, $"Disable disk cache, flag --{AppArgsFlags.DISABLE_DISK_CACHE} is passed");
return new IDiskCache.Fake();
}
var cacheDirectory = CacheDirectory.NewDefault();
var filesLock = new FilesLock();
IDiskCleanUp diskCleanUp;
if (appArgs.HasFlag(AppArgsFlags.DISABLE_DISK_CACHE_CLEANUP))
{
ReportHub.Log(ReportData.UNSPECIFIED, $"Disable disk cache cleanup, flag --{AppArgsFlags.DISABLE_DISK_CACHE_CLEANUP} is passed");
diskCleanUp = IDiskCleanUp.None.INSTANCE;
}
else
diskCleanUp = new LRUDiskCleanUp(cacheDirectory, filesLock);
var diskCache = new DiskCache(cacheDirectory, filesLock, diskCleanUp);
return diskCache;
}
[ContextMenu(nameof(ValidateSettingsAsync))]
public async UniTask ValidateSettingsAsync()
{
using var scope = new CheckingScope(ReportData.UNSPECIFIED);
await pluginSettingsContainer.EnsureValidAsync();
ReportHub.Log(ReportData.UNSPECIFIED, "Success checking");
}
private async UniTask<bool> IsTrustedRealmAsync(DecentralandUrlsSource dclUrls, CancellationToken ct)
{
if (launchSettings.initialRealm != InitialRealm.Custom) return true;
if (launchSettings.CurrentMode == LaunchMode.LocalSceneDevelopment) return true;
string realm = launchSettings.customRealm;
if (string.IsNullOrEmpty(realm)) return true;
var uri = new Uri(realm);
if (uri.Host == "127.0.0.1") return true;
if (uri.Host == "localhost") return true;
if (uri.Host == "sdk-team-cdn.decentraland.org") return true;
if (uri.Host == "sdk-test-scenes.decentraland.zone") return true;
if (uri.Host == "realm-provider-ea.decentraland.org") return true;
if (uri.Host == "realm-provider-ea.decentraland.zone") return true;
if (uri.Host == "worlds-content-server.decentraland.org") return true;
if (uri.Host == "worlds-content-server.decentraland.zone") return true;
IWebRequestController webRequestController = staticContainer!.WebRequestsContainer.WebRequestController;
// If we want to save one http request, we could have a hardcoded list of trusted realms instead
var url = URLAddress.FromString(dclUrls.Url(DecentralandUrl.Servers));
var adapter = webRequestController.GetAsync(new CommonArguments(url), ct, ReportCategory.REALM);
TrustedRealmApiResponse[] realms = await adapter.CreateFromJson<TrustedRealmApiResponse[]>(WRJsonParser.Newtonsoft);
foreach (TrustedRealmApiResponse trustedRealm in realms)
if (string.Equals(trustedRealm.baseUrl, realm, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
private async UniTask<bool> ShowUntrustedRealmConfirmationAsync(CancellationToken ct)
{
var prefab = await bootstrapContainer!.AssetsProvisioner!.ProvideMainAssetAsync(untrustedRealmConfirmationPrefab, ct);
UntrustedRealmConfirmationController controller = new UntrustedRealmConfirmationController(
UntrustedRealmConfirmationController.CreateLazily(prefab.Value.GetComponent<UntrustedRealmConfirmationView>(), null));
IMVCManager mvcManager = dynamicWorldContainer!.MvcManager;
mvcManager.RegisterController(controller);
var args = new UntrustedRealmConfirmationController.Args { realm = launchSettings.customRealm };
await mvcManager.ShowAsync(UntrustedRealmConfirmationController.IssueCommand(args), ct);
return controller.SelectedOption;
}
private async UniTask<ErrorPopupWithRetryController.Result> ShowLoadErrorPopupAsync(CancellationToken ct)
{
IMVCManager mvcManager = dynamicWorldContainer!.MvcManager;
var input = new ErrorPopupWithRetryController.Input(
title: "Load Error",
description: "A loading error was encountered. Please reload to try again.",
iconType: ErrorPopupWithRetryController.IconType.Error);
await mvcManager.ShowAsync(ErrorPopupWithRetryController.IssueCommand(input), ct);
return input.SelectedOption;
}
private void InstantiateAltTester(IAppArgs appArgs)
{
#if ALTTESTER
// Temporary parent needed because AltTester's Awake method relies on the name being
// AltTesterPrefab (and not AltTesterPrefab(Clone))
var tempParent = new GameObject("AltTesterParent");
tempParent.SetActive(false);
var instance = Instantiate(altTesterPrefab, tempParent.transform);
instance.name = "AltTesterPrefab";
instance.transform.SetParent(null);
Destroy(tempParent);
if (appArgs.TryGetValue(AppArgsFlags.ALTTESTER, out var endpoint) && !string.IsNullOrEmpty(endpoint))
{
var runner = instance.GetComponent<AltRunner>();
var split = endpoint.Split(':');
if (split.Length != 2 || !int.TryParse(split[1], out var port))
{
ReportHub.LogError(ReportData.UNSPECIFIED, $"Invalid Alttester endpoint (needs to be host:port): {endpoint}");
return;
}
runner.InstrumentationSettings.AltServerHost = split[0];
runner.InstrumentationSettings.AltServerPort = port;
}
#endif
}
/// <summary>
/// Required to fix crash on exit, ticket - https://github.com/decentraland/unity-explorer/issues/6180
/// </summary>
private static void DisableAllSelectableTransitions()
{
DOTween.KillAll();
Selectable[] all = FindObjectsByType<Selectable>(FindObjectsInactive.Include, FindObjectsSortMode.None) ?? Array.Empty<Selectable>();
foreach (var s in all)
{
// Prevent Unity from executing DestroyTween / StartTween during shutdown
s.transition = Selectable.Transition.None;
// Disable any graphic tween still in progress
Graphic? g = s.targetGraphic;
if (g != null)
g.CrossFadeColor(g.color, 0f, false, false); // instantly settle
}
}
[Serializable]
public struct TrustedRealmApiResponse
{
public string baseUrl;
}
private readonly struct CheckingScope : IDisposable
{
private readonly ReportData data;
public CheckingScope(ReportData data)
{
this.data = data;
ReportHub.Log(data, "Start checking");
}
public void Dispose()
{
ReportHub.Log(data, "Finish checking");
}
}
private async UniTask<EnsureClockSync.Result> ShowClockDesyncPopupAsync(CancellationToken ct)
{
if (clockDesyncPopupPrefab == null)
clockDesyncPopupPrefab = (await bootstrapContainer!.AssetsProvisioner!.ProvideMainAssetAsync(clockDesyncPopupRef, ct)).Value;
ControllerBase<ErrorPopupWithRetryView, ErrorPopupWithRetryController.Input>.ViewFactoryMethod viewFactory =
ControllerBase<ErrorPopupWithRetryView, ErrorPopupWithRetryController.Input>.Preallocate(clockDesyncPopupPrefab, null, out ErrorPopupWithRetryView viewInstance);
using var controller = new ErrorPopupWithRetryController(viewFactory);
var input = new ErrorPopupWithRetryController.Input(
title: "Time sync needed",
description: "Your clock may be out of sync. Turn on “Set time automatically” in Date & Time settings and try again.",
iconType: ErrorPopupWithRetryController.IconType.Clock);
var ordering = new CanvasOrdering(controller.Layer, splashScreen.Value.GetComponent<Canvas>().sortingOrder + 1);
// Cant use the MVC here, it doesn't exist at this point
await controller.LaunchViewLifeCycleAsync(ordering, input, ct);
await controller.HideViewAsync(ct);
Destroy(viewInstance.gameObject);
switch (input.SelectedOption)
{
case ErrorPopupWithRetryController.Result.Exit:
// The error popup will automatically request application exit
return EnsureClockSync.Result.Continue;
case ErrorPopupWithRetryController.Result.Restart:
return EnsureClockSync.Result.Restart;
}
return EnsureClockSync.Result.Continue;
}
private static Vector2Int? GetResolutionFromAppArgs(IAppArgs appArgs)
{
if (!appArgs.TryGetValue(AppArgsFlags.RESOLUTION, out string resolutionArg) || string.IsNullOrEmpty(resolutionArg))
return null;
string[] parts = resolutionArg.Split('x');
if (parts.Length == 2 && int.TryParse(parts[0], out int w) && int.TryParse(parts[1], out int h))
return new Vector2Int(w, h);
ReportHub.LogWarning(ReportCategory.STARTUP, $"Invalid --{AppArgsFlags.RESOLUTION} value '{resolutionArg}'. Expected format: WxH (e.g. 1920x1080)");
return null;
}
[Serializable]
public class SplashScreenRef : ComponentReference<SplashScreen>
{
public SplashScreenRef(string guid) : base(guid) { }
}
[Serializable]
public class ErrorPopupWithRetryRef : ComponentReference<ErrorPopupWithRetryView>
{
public ErrorPopupWithRetryRef(string guid) : base(guid) { }
}
}
}