LaunchApp.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. using System;
  2. using System.Threading;
  3. using Cysharp.Threading.Tasks;
  4. using HotPatch;
  5. using UnityEngine;
  6. using UnityEngine.SceneManagement;
  7. public sealed class LaunchApp
  8. {
  9. readonly Scene launchScene;
  10. readonly ILaunchView view;
  11. readonly ILaunchResources resources;
  12. readonly CancellationToken cancellationToken;
  13. public bool IsRunning { get; private set; }
  14. public bool IsResourcesReady { get; private set; }
  15. public bool IsCompleted { get; private set; }
  16. public LaunchApp(Scene launchScene, ILaunchView view, ILaunchResources resources, CancellationToken cancellationToken)
  17. {
  18. this.launchScene = launchScene;
  19. this.view = view ?? throw new ArgumentNullException(nameof(view));
  20. this.resources = resources ?? throw new ArgumentNullException(nameof(resources));
  21. this.cancellationToken = cancellationToken;
  22. }
  23. bool CanRun => !cancellationToken.IsCancellationRequested && view.IsAvailable;
  24. /// <summary>Updates resources, then invokes onUpdated or opens the game scene when no callback is supplied.</summary>
  25. public async UniTask RunAsync(Action onUpdated = null)
  26. {
  27. if (IsRunning || IsCompleted || !CanRun) return;
  28. IsRunning = true;
  29. bool showRetryDialog = false;
  30. try
  31. {
  32. HotPatchLog.Info("launch_start scene=" + resources.GameSceneName);
  33. if (!IsResourcesReady)
  34. {
  35. view.ResetProgress();
  36. Report("Checking version", 0);
  37. await resources.LoadAsync(Report, cancellationToken);
  38. cancellationToken.ThrowIfCancellationRequested();
  39. IsResourcesReady = true;
  40. }
  41. if (onUpdated != null) Report("Update complete", 1);
  42. }
  43. catch (Exception exception)
  44. {
  45. showRetryDialog = HandleFailure(exception);
  46. if (!showRetryDialog) return;
  47. }
  48. finally
  49. {
  50. IsRunning = false;
  51. }
  52. if (showRetryDialog)
  53. {
  54. ShowRetryDialog(() => RunAsync(onUpdated).Forget(Debug.LogException));
  55. return;
  56. }
  57. if (!CanRun) return;
  58. // Release the update guard before invoking user code so the callback can open the scene.
  59. if (onUpdated != null) onUpdated();
  60. else await OpenSceneAsync();
  61. }
  62. /// <summary>Opens the game scene using resources prepared by a successful RunAsync callback.</summary>
  63. public async UniTask OpenSceneAsync()
  64. {
  65. if (IsRunning || IsCompleted || !CanRun) return;
  66. if (!IsResourcesReady)
  67. throw new InvalidOperationException("Resources are not ready. Wait for RunAsync to finish updating before opening the game scene.");
  68. IsRunning = true;
  69. bool showRetryDialog = false;
  70. Scene gameScene = default;
  71. try
  72. {
  73. var sceneName = resources.GameSceneName;
  74. if (SceneManager.GetSceneByName(sceneName).isLoaded)
  75. throw new InvalidOperationException(sceneName + " is already open. Restart the app.");
  76. HotPatchLog.Info("scene_load_start scene=" + sceneName + " version=" + resources.LoadedVersion);
  77. Report("Loading resources", .95f);
  78. var scenePath = resources.LoadedScenePath;
  79. AsyncOperation operation;
  80. #if UNITY_EDITOR
  81. if (resources.UseEditorSceneLoading)
  82. operation = UnityEditor.SceneManagement.EditorSceneManager.LoadSceneAsyncInPlayMode(scenePath, new LoadSceneParameters(LoadSceneMode.Additive));
  83. else
  84. #endif
  85. operation = SceneManager.LoadSceneAsync(scenePath, LoadSceneMode.Additive);
  86. if (operation == null) throw new InvalidOperationException("Unable to open game scene: " + sceneName);
  87. await operation.ToUniTask(progress: Progress.Create<float>(value => Report("Loading resources", .95f + .04f * value)));
  88. gameScene = SceneManager.GetSceneByPath(scenePath);
  89. cancellationToken.ThrowIfCancellationRequested();
  90. if (!gameScene.isLoaded || !SceneManager.SetActiveScene(gameScene))
  91. throw new InvalidOperationException("Failed to activate game scene: " + sceneName);
  92. HotPatchLog.Info("scene_load_complete scene=" + sceneName + " version=" + resources.LoadedVersion);
  93. Report("Loading resources", 1);
  94. await UniTask.Yield();
  95. cancellationToken.ThrowIfCancellationRequested();
  96. LaunchSceneInput.Transfer(launchScene, gameScene);
  97. #if UNITY_EDITOR
  98. await UniTask.NextFrame(cancellationToken: cancellationToken);
  99. HotPatchLog.Info("editor_initialization_start scene=" + gameScene.name);
  100. resources.InitializeEditor();
  101. HotPatchLog.Info("editor_initialization_complete scene=" + gameScene.name);
  102. #endif
  103. await SceneManager.UnloadSceneAsync(launchScene);
  104. IsCompleted = true;
  105. }
  106. catch (Exception exception)
  107. {
  108. showRetryDialog = HandleFailure(exception);
  109. if (gameScene.IsValid() && gameScene.isLoaded) await SceneManager.UnloadSceneAsync(gameScene);
  110. }
  111. finally
  112. {
  113. IsRunning = false;
  114. }
  115. if (showRetryDialog) ShowRetryDialog(() => RunAsync().Forget(Debug.LogException));
  116. }
  117. bool HandleFailure(Exception exception)
  118. {
  119. IsResourcesReady = false;
  120. HotPatchLog.Warning("launch_failed type=" + exception.GetType().Name + " message=" + exception.Message);
  121. if (cancellationToken.IsCancellationRequested || exception is OperationCanceledException) return false;
  122. if (resources.HasLoadedAssembly) resources.MarkEntryFailed();
  123. Debug.LogException(exception);
  124. return true;
  125. }
  126. void ShowRetryDialog(Action retry)
  127. {
  128. if (!CanRun) return;
  129. HotPatchLog.Info("retry_dialog_open requiresRestart=" + resources.RequiresRestart);
  130. view.ShowError(NativeDialog.NetworkErrorMessage, () =>
  131. {
  132. if (!CanRun) return;
  133. HotPatchLog.Info("retry_dialog_confirmed");
  134. retry();
  135. });
  136. }
  137. void Report(string stage, float progress)
  138. {
  139. if (CanRun) view.ReportProgress(stage, progress);
  140. }
  141. }