Forráskód Böngészése

增加使用本地资源测试的模式

baxi 2 hete
szülő
commit
1d9251d443

+ 1 - 0
CHANGELOG.md

@@ -2,6 +2,7 @@
 
 ## Unreleased — Hot Patch
 
+- Switch StreamingAssets between the latest complete original/update resource sets in AppSettings; support local-only Launch loading with an isolated cache and disable resource actions until a matching package exists.
 - Automatically install the missing HybridCLR UPM Git package after import, preserve existing installations, and expose installation status and retry in AppSettings.
 - Resolve the current UPM package name when normalizing Xcode Frameworks/Libraries paths, removing the come.runtimes.hot wrapper after export.
 - Keep Sources as Editor-only C# templates; synchronize them into HexaCrazy.Runtime without the marked outer UNITY_EDITOR envelope.

+ 8 - 0
Documentation~/HotPatch.md

@@ -20,6 +20,14 @@ DownloadUrl accepts a resource directory (automatically appending `manifest.json
 
 The game scene is provided by its bundle and excluded from the Player scene list. Resource builds first normalize the global scene list and any active Build Profile override to a single enabled Launch scene. Other entries are removed from the list; scene assets are retained. Keep the game scene's own MonoBehaviours. Launch loads the configured scene without a separate game-entry call.
 
+## Local resource testing
+
+AppSettings enables **使用本地资源测试**, **恢复正式资源**, and **上传资源** when `Build/HotUpdate` contains a complete `AllRes_<timestamp>` directory matching the saved assembly, game scene, and active build target. It selects the newest complete matching directory. Both manifests and their referenced files must exist. Build, upload, compilation, and Play Mode temporarily disable resource switching.
+
+**使用本地资源测试** verifies and stages `manifest_hot.json`, its assembly and scene bundles, and the fixed AOT bundle. It replaces all StreamingAssets contents and names the selected manifest `manifest.json`. It saves local testing mode in AppSettings. Launch extracts and verifies those resources using a separate `HotUpdate/LocalTest` cache and makes no remote manifest or resource requests. DownloadUrl is preserved and may be empty in this mode. This also works in iOS and Android Players; Editor execution continues to use its local script assemblies as before.
+
+**恢复正式资源** replaces StreamingAssets with `manifest.json` and only its referenced original resources from the same latest archive. It disables local testing mode, so Launch resumes remote updates. A successful original resource publication during 一键打包资源 also restores normal mode. Source validation and staging finish before replacing StreamingAssets; missing or corrupt inputs leave the previous installation intact.
+
 ## Bundle strategy
 
 | Bundle | Input | Update policy |

+ 1 - 1
Documentation~/S3Upload.md

@@ -1,6 +1,6 @@
 # S3 resource upload
 
-Open AppSettings and click **上传资源**, then choose a folder. The uploader sends its contents recursively, preserving relative paths and empty folders. The selected folder's own name is not added to the destination.
+After completing 一键打包资源, open AppSettings and click **上传资源**, then choose a folder. The folder picker starts in the latest complete AllRes directory matching the saved assembly, game scene, and current platform. Without such a directory, the upload button is disabled. DownloadUrl and S3 configuration are validated before opening the picker. The uploader sends the selected folder's contents recursively, preserving relative paths and empty folders. The selected folder's own name is not added to the destination.
 
 The destination prefix is the final directory in the current DownloadUrl field. Both `https://cdn.example.com/hexa_crazy/` and `https://cdn.example.com/hexa_crazy/manifest_hot.json` upload to `s3://ios-games/hexa_crazy/`. A nested URL ending in `/games/hexa_crazy/` also uses only `hexa_crazy/`. A domain root without a directory is rejected.
 

+ 29 - 2
Editor/AppSettingsWindow.cs

@@ -130,9 +130,22 @@ public sealed class AppSettingsWindow : EditorWindow
             using (new EditorGUI.DisabledScope(S3UploadController.IsUploading))
                 if (GUILayout.Button("一键打包资源")) EditorApplication.ExecuteMenuItem("资源构建/一键打包资源");
         }
-        using (new EditorGUI.DisabledScope(S3UploadController.IsUploading || EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode || BuildPipeline.isBuildingPlayer))
+        using (new EditorGUI.DisabledScope(S3UploadController.IsUploading || HotPatchResourceActions.IsBuilding || EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode || BuildPipeline.isBuildingPlayer))
         {
-            if (GUILayout.Button("上传资源")) S3UploadController.ChooseAndUpload(downloadUrl);
+            var latest = HotPatchResourceActions.LatestDirectory;
+            using (new EditorGUI.DisabledScope(string.IsNullOrEmpty(latest)))
+            {
+                using (new EditorGUILayout.HorizontalScope())
+                {
+                    if (GUILayout.Button("使用本地资源测试")) ApplyResourceMode(true);
+                    if (GUILayout.Button("恢复正式资源")) ApplyResourceMode(false);
+                }
+                if (GUILayout.Button("上传资源")) S3UploadController.ChooseAndUpload(downloadUrl);
+            }
+            EditorGUILayout.LabelField("启动资源模式", settings.UseLocalHotPatchResources ? "本地资源测试(跳过远程热更新)" : "正式资源(检查远程更新)");
+            if (string.IsNullOrEmpty(latest))
+                EditorGUILayout.HelpBox("没有当前平台、程序集和场景对应的完整打包资源,请先 Save,再执行一键打包资源。", MessageType.Info);
+            else EditorGUILayout.LabelField("最近打包资源", System.IO.Path.GetFileName(latest));
             try { EditorGUILayout.LabelField("上传目标", "s3://" + S3UploadSettings.Bucket + "/" + S3ResourceUploader.TargetPrefix(downloadUrl) + "/"); }
             catch (ArgumentException) { EditorGUILayout.LabelField("上传目标", "请设置包含目录的 DownloadUrl"); }
             DrawS3Settings();
@@ -141,6 +154,20 @@ public sealed class AppSettingsWindow : EditorWindow
         EditorGUILayout.EndScrollView();
     }
 
+    private void ApplyResourceMode(bool localTesting)
+    {
+        try
+        {
+            HotPatchResourceActions.ApplyResources(localTesting);
+            ShowNotification(new GUIContent(localTesting ? "已切换为本地资源测试" : "已恢复正式资源"));
+        }
+        catch (Exception exception)
+        {
+            Debug.LogException(exception);
+            EditorUtility.DisplayDialog("切换资源失败", exception.Message, "确定");
+        }
+    }
+
     private void DrawHybridCLRSetup()
     {
         if (HybridCLRPackageSetup.IsInstalled) return;

+ 2 - 0
Editor/HotPatch/HotPatchBuild.cs

@@ -30,6 +30,7 @@ namespace HotPatch.Editor
         const string StagingRoot = "Library/HotPatch/Staging";
         public static string BaselinePointer => OutputRoot + "/Baselines/" + EditorUserBuildSettings.activeBuildTarget + "/current.json";
         static bool working;
+        public static bool IsBuilding => working || !string.IsNullOrEmpty(SessionState.GetString(Pending, ""));
 
         static HotPatchBuild()
         {
@@ -351,6 +352,7 @@ namespace HotPatch.Editor
                                                                                                                 
             HotPatchResourcePackage.ReplaceDirectory(staging, Application.streamingAssetsPath,
                 Path.GetFullPath(StagingRoot), Application.dataPath);
+            HotPatchLocalTesting.SetLocalMode(false);
             Directory.CreateDirectory(Path.GetDirectoryName(BaselinePointer));
             File.WriteAllText(BaselinePointer, baseline.ToString());
             AssetDatabase.Refresh();

+ 4 - 2
Editor/HotPatch/HotPatchResourcePackage.cs

@@ -60,11 +60,13 @@ namespace HotPatch.Editor
             return manifest;
         }
 
-        public static void CopyOriginal(string sourceDirectory, string destination)
+        public static void CopyOriginal(string sourceDirectory, string destination, string manifestFileName = HotPatchResourceStore.ManifestFileName)
         {
+            if (manifestFileName != HotPatchResourceStore.ManifestFileName && manifestFileName != HotManifestFileName)
+                throw new ArgumentException("资源清单名称不正确。", nameof(manifestFileName));
             if (Directory.Exists(destination) && Directory.EnumerateFileSystemEntries(destination).Any())
                 throw new IOException("资源输出目录必须为空: " + destination);
-            var json = File.ReadAllText(Path.Combine(sourceDirectory, HotPatchResourceStore.ManifestFileName));
+            var json = File.ReadAllText(RequireChild(sourceDirectory, Path.Combine(sourceDirectory, manifestFileName)));
             var original = HotPatchResourceStore.Parse(json);
             original.Validate(original.assemblyName, original.platform, original.gameSceneName);
             if (original.aotBundle == null || (original.aotMetadata?.Length ?? 0) == 0)

+ 4 - 2
Editor/S3UploadController.cs

@@ -17,17 +17,19 @@ public static class S3UploadController
 
     public static async void ChooseAndUpload(string downloadUrl)
     {
-        if (IsUploading || EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode || BuildPipeline.isBuildingPlayer) return;
+        if (IsUploading || HotPatchResourceActions.IsBuilding || EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode || BuildPipeline.isBuildingPlayer) return;
         bool locked = false;
         try
         {
+            var latest = HotPatchResourceActions.LatestDirectory;
+            if (string.IsNullOrEmpty(latest)) throw new InvalidOperationException("没有可用的最近打包资源,请先执行一键打包资源。");
             var prefix = S3ResourceUploader.TargetPrefix(downloadUrl);
             var bucket = S3UploadSettings.Bucket;
             var region = S3UploadSettings.Region;
             S3UploadSettings.ValidateDestination(bucket, region);
             var credentials = S3UploadSettings.LoadCredentials();
             S3UploadSettings.ValidateCredentials(credentials);
-            var directory = EditorUtility.OpenFolderPanel("选择上传资源文件夹", EditorPrefs.GetString("AppRuntimes.S3.LastFolder", Path.GetFullPath("Build/HotUpdate")), "");
+            var directory = EditorUtility.OpenFolderPanel("选择上传资源文件夹", latest, "");
             if (string.IsNullOrEmpty(directory)) return;
             var files = S3ResourceUploader.CreatePlan(directory, prefix);
             EditorPrefs.SetString("AppRuntimes.S3.LastFolder", directory);

+ 8 - 1
Runtime/HotPatch/HotPatchLaunchResources.cs

@@ -20,7 +20,14 @@ namespace HotPatch
         public void MarkEntryFailed() => HotPatchService.MarkEntryFailed();
 
 #if UNITY_EDITOR
-        public bool UseEditorSceneLoading => string.IsNullOrWhiteSpace(UnityEngine.Resources.Load<AppSettings>("AppSettings").DownloadUrl);
+        public bool UseEditorSceneLoading
+        {
+            get
+            {
+                var settings = UnityEngine.Resources.Load<AppSettings>("AppSettings");
+                return !settings.UseLocalHotPatchResources && string.IsNullOrWhiteSpace(settings.DownloadUrl);
+            }
+        }
 
         public void InitializeEditor() => HotPatchService.InvokeInitialization(System.Reflection.Assembly.Load("AppRuntimes.Sources.Editor"));
 #endif

+ 35 - 4
Runtime/HotPatch/HotPatchResourceStore.cs

@@ -26,6 +26,40 @@ namespace HotPatch
     {
         public const string ManifestFileName = "manifest.json";
 
+        public static async UniTask<HotPatchLocalResources> LoadBundledAsync(Uri bundledManifestUri,
+            string cacheDirectory, string assemblyName, string platform, Action<HotPatchProgress> progress, CancellationToken ct, string sceneName = null)
+        {
+            progress?.Invoke(new HotPatchProgress("Checking version", 0));
+            var json = await ReadTextAsync(bundledManifestUri, ct);
+            var manifest = Parse(json);
+            ValidateBundledManifest(manifest, assemblyName, platform, sceneName);
+            var root = Path.Combine(cacheDirectory, "LocalTest", HotPatchHash.Of(Encoding.UTF8.GetBytes(json)));
+            var resources = new[] { manifest.aotBundle }.Concat(manifest.resources).ToArray();
+            HotPatchLog.Info("local_test_cache path=" + root + " version=" + manifest.version);
+            for (int i = 0; i < resources.Length; i++)
+            {
+                ct.ThrowIfCancellationRequested();
+                var resource = resources[i];
+                var destination = Path.Combine(root, resource.RelativePath);
+                if (!IsVerified(destination, resource))
+                    await DownloadFileAsync(new Uri(bundledManifestUri, resource.RelativePath), destination, resource,
+                        bytes => progress?.Invoke(new HotPatchProgress("Checking version", .8f * (i + (float)bytes / resource.size) / resources.Length)), ct);
+            }
+            ct.ThrowIfCancellationRequested();
+            SaveManifest(Path.Combine(root, ManifestFileName), manifest);
+            HotPatchLog.Info("local_test_ready version=" + manifest.version + " remote_requests=0");
+            progress?.Invoke(new HotPatchProgress("Loading resources", .8f));
+            return new HotPatchLocalResources(root, manifest, manifest);
+        }
+
+        static void ValidateBundledManifest(HotPatchManifest manifest, string assemblyName, string platform, string sceneName)
+        {
+            manifest.Validate(assemblyName, platform, sceneName);
+            if (manifest.aotBundle == null || manifest.aotMetadata == null ||
+                !manifest.aotMetadata.Select(r => r.name).OrderBy(n => n).SequenceEqual(HotPatchBundleLoader.AotAssemblyNames.OrderBy(n => n)))
+                throw new InvalidDataException("Original resources must include an AOT bundle and verification records for all four AOT DLLs.");
+        }
+
         public static async UniTask<HotPatchLocalResources> SynchronizeAsync(Uri bundledManifestUri, Uri remoteManifestUri,
             string cacheDirectory, string assemblyName, string platform, Action<HotPatchProgress> progress, CancellationToken ct, string sceneName = null)
         {
@@ -35,10 +69,7 @@ namespace HotPatch
             progress?.Invoke(new HotPatchProgress("Checking version", 0));
             var original = Parse(await ReadTextAsync(bundledManifestUri, ct));
             HotPatchLog.Info($"bundled_manifest platform={original.platform} build={original.playerBuildId} version={original.version}");
-            original.Validate(assemblyName, platform, sceneName);
-            if (original.aotBundle == null || original.aotMetadata == null ||
-                !original.aotMetadata.Select(r => r.name).OrderBy(n => n).SequenceEqual(HotPatchBundleLoader.AotAssemblyNames.OrderBy(n => n)))
-                throw new InvalidDataException("Original resources must include an AOT bundle and verification records for all four AOT DLLs.");
+            ValidateBundledManifest(original, assemblyName, platform, sceneName);
             var root = Path.Combine(cacheDirectory, HotPatchHash.Of(Encoding.UTF8.GetBytes(original.playerBuildId)));
             Directory.CreateDirectory(root);
             HotPatchLog.Info("cache_path path=" + root);

+ 15 - 4
Runtime/HotPatch/HotPatchService.cs

@@ -52,16 +52,27 @@ namespace HotPatch
                 HotPatchLog.Info($"load_start assembly={assemblyName} platform={CurrentPlatform()} appVersion={Application.version} unity={Application.unityVersion}");
                 var settings = Resources.Load<AppSettings>("AppSettings");
                 var sceneName = AppSettings.RequireGameSceneName();
+                bool localOnly = settings != null && settings.UseLocalHotPatchResources;
                 bool synchronize = true;
 #if UNITY_EDITOR
-                synchronize = settings != null && !string.IsNullOrWhiteSpace(settings.DownloadUrl);
+                synchronize = localOnly || settings != null && !string.IsNullOrWhiteSpace(settings.DownloadUrl);
 #endif
                 HotPatchLocalResources local = null;
                 if (synchronize)
                 {
-                    var manifestUri = HotPatchResourceStore.RemoteManifestUri(settings != null ? settings.DownloadUrl : null);
-                    local = await HotPatchResourceStore.SynchronizeAsync(HotPatchResourceStore.StreamingManifestUri(), manifestUri,
-                        Path.Combine(Application.temporaryCachePath, "HotUpdate"), assemblyName, CurrentPlatform(), progress, cancellationToken, sceneName);
+                    var cache = Path.Combine(Application.temporaryCachePath, "HotUpdate");
+                    if (localOnly)
+                    {
+                        HotPatchLog.Info("local_test_start source=StreamingAssets remote_updates=disabled");
+                        local = await HotPatchResourceStore.LoadBundledAsync(HotPatchResourceStore.StreamingManifestUri(), cache,
+                            assemblyName, CurrentPlatform(), progress, cancellationToken, sceneName);
+                    }
+                    else
+                    {
+                        var manifestUri = HotPatchResourceStore.RemoteManifestUri(settings != null ? settings.DownloadUrl : null);
+                        local = await HotPatchResourceStore.SynchronizeAsync(HotPatchResourceStore.StreamingManifestUri(), manifestUri,
+                            cache, assemblyName, CurrentPlatform(), progress, cancellationToken, sceneName);
+                    }
                     progress?.Invoke(new HotPatchProgress("Loading resources", .82f));
                     var aotBundle = await HotPatchBundleLoader.LoadAsync(local.GetPath(local.BundledManifest.aotBundle), "aot", cancellationToken);
                     try

+ 1 - 0
Runtime/Scripts/AppSettings.cs

@@ -8,6 +8,7 @@ public sealed class AppSettings : ScriptableObject
     public string PrivacyUrl = string.Empty;
     [Tooltip("Absolute HTTP(S) URL of the hot patch resource directory or manifest.json")]
     public string DownloadUrl = string.Empty;
+    [HideInInspector] public bool UseLocalHotPatchResources;
     [Tooltip("Hot patch assembly name, saved after selecting an asmdef in the AppSettings window")]
     public string HotPatchAssemblyName = string.Empty;
     [Tooltip("Game scene to open after loading the hot patch. Built as a separate scene AssetBundle and excluded from the Player scene list.")]