diff --git a/Editor/LuaHooker/win/ucrtbased.dll b/Editor/LuaHooker/win/ucrtbased.dll new file mode 100644 index 000000000..62ee8d201 Binary files /dev/null and b/Editor/LuaHooker/win/ucrtbased.dll differ diff --git a/Editor/LuaHooker/win/ucrtbased.dll.meta b/Editor/LuaHooker/win/ucrtbased.dll.meta new file mode 100644 index 000000000..e10d4b39e --- /dev/null +++ b/Editor/LuaHooker/win/ucrtbased.dll.meta @@ -0,0 +1,82 @@ +fileFormatVersion: 2 +guid: be799b1631d688242995c11c94a5b318 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + : Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux64: 1 + Exclude OSXUniversal: 1 + Exclude WebGL: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude WindowsStoreApps: 1 + - first: + Android: Android + second: + enabled: 0 + settings: + CPU: ARMv7 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: x86_64 + DefaultValueInitialized: true + OS: Windows + - first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: x86 + - first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: x86_64 + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: false + PlaceholderPath: + SDK: AnySDK + ScriptingBackend: AnyScriptingBackend + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Node/node_modules/binaryen.meta b/Editor/Node/node_modules/binaryen.meta index 626ed8233..5cd9e04c9 100644 --- a/Editor/Node/node_modules/binaryen.meta +++ b/Editor/Node/node_modules/binaryen.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: a3d25085461954ccf96b870bbabd2d51 +guid: 5c4133172957c4ff58904dc589712f66 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Editor/Node/node_modules/binaryen/LICENSE.meta b/Editor/Node/node_modules/binaryen/LICENSE.meta index 7c4f0df2b..012891cfa 100644 --- a/Editor/Node/node_modules/binaryen/LICENSE.meta +++ b/Editor/Node/node_modules/binaryen/LICENSE.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 72db98ce23892438085944429a2f0f1e +guid: 688f385fb02274584bc0da25fc717541 DefaultImporter: externalObjects: {} userData: diff --git a/Editor/Node/node_modules/binaryen/README.md.meta b/Editor/Node/node_modules/binaryen/README.md.meta index 4373a1b0d..b4a92783c 100644 --- a/Editor/Node/node_modules/binaryen/README.md.meta +++ b/Editor/Node/node_modules/binaryen/README.md.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 0786375919a5f4b39a2842d398bab691 +guid: 7f21f78b4cc234191b76cd464483218a TextScriptImporter: externalObjects: {} userData: diff --git a/Editor/Node/node_modules/binaryen/bin.meta b/Editor/Node/node_modules/binaryen/bin.meta index ed3c5fc4c..3de4aaf68 100644 --- a/Editor/Node/node_modules/binaryen/bin.meta +++ b/Editor/Node/node_modules/binaryen/bin.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: e49d6d9d90710412390e04f36c283269 +guid: e2d1865a2511c490fade16ba4a1cb98d folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Editor/Node/node_modules/binaryen/bin/package.json.meta b/Editor/Node/node_modules/binaryen/bin/package.json.meta index 052698917..da39e03a6 100644 --- a/Editor/Node/node_modules/binaryen/bin/package.json.meta +++ b/Editor/Node/node_modules/binaryen/bin/package.json.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: a687be9fecc0c4635a0198f4c84c5a7a +guid: 87afef55b8ecb4102a02702ac98a8c08 TextScriptImporter: externalObjects: {} userData: diff --git a/Editor/Node/node_modules/binaryen/bin/wasm-opt.meta b/Editor/Node/node_modules/binaryen/bin/wasm-opt.meta index 4fd25cdd9..c1b8d22b9 100644 --- a/Editor/Node/node_modules/binaryen/bin/wasm-opt.meta +++ b/Editor/Node/node_modules/binaryen/bin/wasm-opt.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 59195b600f5474a34ab0de959545786a +guid: 15b1d1d2687c240e79f3326305a8e34d DefaultImporter: externalObjects: {} userData: diff --git a/Editor/Node/node_modules/binaryen/bin/wasm2js.meta b/Editor/Node/node_modules/binaryen/bin/wasm2js.meta index 6504dad93..216ac952f 100644 --- a/Editor/Node/node_modules/binaryen/bin/wasm2js.meta +++ b/Editor/Node/node_modules/binaryen/bin/wasm2js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 945d329c042b5422590297f9a668573b +guid: f2f9e284d496f4f0da239b534fc0962e DefaultImporter: externalObjects: {} userData: diff --git a/Editor/Node/node_modules/binaryen/index.d.ts.meta b/Editor/Node/node_modules/binaryen/index.d.ts.meta index d8df13d27..c99788971 100644 --- a/Editor/Node/node_modules/binaryen/index.d.ts.meta +++ b/Editor/Node/node_modules/binaryen/index.d.ts.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 5c728f27cb29c4a7ab957bec87aee79b +guid: c36b18db4fca44e7999111a49563794c DefaultImporter: externalObjects: {} userData: diff --git a/Editor/Node/node_modules/binaryen/index.js.meta b/Editor/Node/node_modules/binaryen/index.js.meta index 908311480..a83cc1c9b 100644 --- a/Editor/Node/node_modules/binaryen/index.js.meta +++ b/Editor/Node/node_modules/binaryen/index.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: e116238b593ee4f118e080fc2e1be1d0 +guid: 18049f8d0a7b340e089d8f6a56329852 TextScriptImporter: externalObjects: {} userData: diff --git a/Editor/Node/node_modules/binaryen/package.json.meta b/Editor/Node/node_modules/binaryen/package.json.meta index c3e45e73f..2e68d812c 100644 --- a/Editor/Node/node_modules/binaryen/package.json.meta +++ b/Editor/Node/node_modules/binaryen/package.json.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 95f171f78f3854726ba37852e7da8ace +guid: 717be45d5d44c471e96a22dbcd2aaddd TextScriptImporter: externalObjects: {} userData: diff --git a/Editor/Playable.meta b/Editor/Playable.meta new file mode 100644 index 000000000..570798478 --- /dev/null +++ b/Editor/Playable.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b9ade20e13f604b10b5328d9cbdeafbe +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Playable/WXPlayableConvertCore.cs b/Editor/Playable/WXPlayableConvertCore.cs new file mode 100644 index 000000000..673f8716c --- /dev/null +++ b/Editor/Playable/WXPlayableConvertCore.cs @@ -0,0 +1,138 @@ +using System; +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace WeChatWASM +{ + public class WXPlayableConvertCore + { + static WXPlayableConvertCore() { } + public static WXPlayableEditorScriptObject config => UnityUtil.GetPlayableEditorConf(); + + public static WXConvertCore.WXExportError DoExport(bool buildWebGL = true) + { + WXConvertCore.isPlayableBuild = true; + // var preCheckResult = WXConvertCore.PreCheck(); + // if (preCheckResult != WXConvertCore.WXExportError.SUCCEED) + // { + // WXConvertCore.isPlayableBuild = false; + // return preCheckResult; + // } + // WXConvertCore.PreInit(); + var exportResult = WXConvertCore.DoExport(); + + WXConvertCore.isPlayableBuild = false; + return exportResult; + } + + public static WXEditorScriptObject GetFakeScriptObject() + { + return SetDefaultProperties(ConvertPlayableConfigToCommon(config)); + } + + public static WXEditorScriptObject ConvertPlayableConfigToCommon( + WXPlayableEditorScriptObject source, + WXEditorScriptObject target = null) + { + // 创建或使用现有的目标实例 + var newTarget = target ?? ScriptableObject.CreateInstance(); + + // 使用序列化方式深度拷贝公共字段 + var so = new SerializedObject(newTarget); + + // 遍历源对象的所有字段 + var sourceType = source.GetType(); + foreach (var sourceField in sourceType.GetFields( + System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.Instance | + System.Reflection.BindingFlags.NonPublic)) + { + // 跳过readonly字段 + if (sourceField.IsInitOnly) continue; + + // 查找目标对象中的对应字段 + var targetField = typeof(WXEditorScriptObject).GetField( + sourceField.Name, + System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.Instance | + System.Reflection.BindingFlags.NonPublic); + + // if (targetField != null && !targetField.FieldType.IsValueType && !targetField.FieldType.IsEnum) + // { + // // // 复制字段值 + // // var value = sourceField.GetValue(source); + // // targetField.SetValue(newTarget, value); + // // 递归复制子对象属性 + // var subObj = targetField.GetValue(newTarget) ?? Activator.CreateInstance(targetField.FieldType); + // CopySubObjectProperties(value, subObj); + // targetField.SetValue(newTarget, subObj); + // } + + // if (targetField != null && + // (targetField.FieldType.IsAssignableFrom(sourceField.FieldType) || + // (targetField.FieldType.IsValueType && sourceField.FieldType.IsValueType && + // targetField.FieldType == sourceField.FieldType))) + // { + // 复制字段值 + var value = sourceField.GetValue(source); + // 特殊处理嵌套对象类型的字段 + if (value != null && !targetField.FieldType.IsValueType && !targetField.FieldType.IsEnum) + { + // 递归复制子对象属性 + var subObj = targetField.GetValue(newTarget) ?? Activator.CreateInstance(targetField.FieldType); + CopySubObjectProperties(value, subObj); + targetField.SetValue(newTarget, subObj); + } + else + { + targetField.SetValue(newTarget, value); + } + // } + } + + // 应用修改到序列化对象 + so.ApplyModifiedProperties(); + return newTarget; + } + + private static void CopySubObjectProperties(object source, object target) + { + var sourceType = source.GetType(); + var targetType = target.GetType(); + + foreach (var sourceField in sourceType.GetFields( + System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.Instance | + System.Reflection.BindingFlags.NonPublic)) + { + if (sourceField.IsInitOnly) continue; + + var targetField = targetType.GetField( + sourceField.Name, + System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.Instance | + System.Reflection.BindingFlags.NonPublic); + + if (targetField != null && + (targetField.FieldType.IsAssignableFrom(sourceField.FieldType) || + (targetField.FieldType.IsValueType && sourceField.FieldType.IsValueType && + targetField.FieldType == sourceField.FieldType))) + { + var value = sourceField.GetValue(source); + targetField.SetValue(target, value); + } + } + } + + public static WXEditorScriptObject SetDefaultProperties(WXEditorScriptObject target) + { + target.ProjectConf.CDN = ""; + target.ProjectConf.assetLoadType = 1; + target.ProjectConf.compressDataPackage = true; + + target.CompileOptions.showMonitorSuggestModal = false; + return target; + } + } +} \ No newline at end of file diff --git a/Editor/Playable/WXPlayableConvertCore.cs.meta b/Editor/Playable/WXPlayableConvertCore.cs.meta new file mode 100644 index 000000000..f50d85c9f --- /dev/null +++ b/Editor/Playable/WXPlayableConvertCore.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ad34d0bbab40b445689701c63f86cf16 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Playable/WXPlayableEditorSettingHelper.cs b/Editor/Playable/WXPlayableEditorSettingHelper.cs new file mode 100644 index 000000000..c3d52a282 --- /dev/null +++ b/Editor/Playable/WXPlayableEditorSettingHelper.cs @@ -0,0 +1,363 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace WeChatWASM +{ + [InitializeOnLoad] + public class WXPlayableSettingsHelperInterface + { + public static WXPlayableSettingsHelper helper = new WXPlayableSettingsHelper(); + } + + public class WXPlayableSettingsHelper + { + public static string projectRootPath; + private static WXPlayableEditorScriptObject config; + private static bool m_EnablePerfTool = false; + + private static string _dstCache; + public static bool UseIL2CPP + { + get + { +#if TUANJIE_2022_3_OR_NEWER + return PlayerSettings.GetScriptingBackend(BuildTargetGroup.WeixinMiniGame) == ScriptingImplementation.IL2CPP; +#else + return true; +#endif + } + } + + public WXPlayableSettingsHelper() + { + projectRootPath = System.IO.Path.GetFullPath(Application.dataPath + "/../"); + _dstCache = ""; + } + + public void OnFocus() + { + loadData(); + } + + public void OnLostFocus() + { + saveData(); + } + + public void OnDisable() + { + EditorUtility.SetDirty(config); + } + + private Vector2 scrollRoot; + private bool foldBaseInfo = true; + private bool foldDebugOptions = true; + public void OnSettingsGUI(EditorWindow window) + { + scrollRoot = EditorGUILayout.BeginScrollView(scrollRoot); + GUIStyle linkStyle = new GUIStyle(GUI.skin.label); + linkStyle.normal.textColor = Color.yellow; + linkStyle.hover.textColor = Color.yellow; + linkStyle.stretchWidth = false; + linkStyle.alignment = TextAnchor.UpperLeft; + linkStyle.wordWrap = true; + + foldBaseInfo = EditorGUILayout.Foldout(foldBaseInfo, "基本信息"); + if (foldBaseInfo) + { + EditorGUILayout.BeginVertical("frameBox", GUILayout.ExpandWidth(true)); + this.formInput("appid", "小游戏试玩AppID"); + this.formInput("projectName", "小游戏试玩项目名"); + this.formIntPopup("orientation", "游戏方向", new[] { "Portrait", "Landscape" }, new[] { 0, 1, 2, 3 }); + this.formInput("memorySize", "UnityHeap预留内存(?)", "单位MB,预分配内存值,超休闲游戏256/中轻度496/重度游戏768,需预估游戏最大UnityHeap值以防止内存自动扩容带来的峰值尖刺。预估方法请查看GIT文档《优化Unity WebGL的内存》"); + + GUILayout.BeginHorizontal(); + string targetDst = "dst"; + if (!formInputData.ContainsKey(targetDst)) + { + formInputData[targetDst] = ""; + } + EditorGUILayout.LabelField(string.Empty, GUILayout.Width(10)); + GUILayout.Label(new GUIContent("导出路径(?)", "支持输入相对于项目根目录的相对路径,如:wxbuild"), GUILayout.Width(140)); + formInputData[targetDst] = GUILayout.TextField(formInputData[targetDst], GUILayout.MaxWidth(EditorGUIUtility.currentViewWidth - 270)); + if (GUILayout.Button(new GUIContent("打开"), GUILayout.Width(40))) + { + if (!formInputData[targetDst].Trim().Equals(string.Empty)) + { + EditorUtility.RevealInFinder(GetAbsolutePath(formInputData[targetDst])); + } + GUIUtility.ExitGUI(); + } + if (GUILayout.Button(new GUIContent("选择"), GUILayout.Width(40))) + { + var dstPath = EditorUtility.SaveFolderPanel("选择你的游戏导出目录", string.Empty, string.Empty); + if (dstPath != string.Empty) + { + formInputData[targetDst] = dstPath; + this.saveData(); + } + GUIUtility.ExitGUI(); + } + GUILayout.EndHorizontal(); + + + EditorGUILayout.EndVertical(); + } + + foldDebugOptions = EditorGUILayout.Foldout(foldDebugOptions, "调试编译选项"); + if (foldDebugOptions) + { + EditorGUILayout.BeginVertical("frameBox", GUILayout.ExpandWidth(true)); + this.formCheckbox("developBuild", "Development Build", "", false, null, OnDevelopmentBuildToggleChanged); + this.formCheckbox("il2CppOptimizeSize", "Il2Cpp Optimize Size(?)", "对应于Il2CppCodeGeneration选项,勾选时使用OptimizeSize(默认推荐),生成代码小15%左右,取消勾选则使用OptimizeSpeed。游戏中大量泛型集合的高频访问建议OptimizeSpeed,在使用HybridCLR等第三方组件时只能用OptimizeSpeed。(Dotnet Runtime模式下该选项无效)", !UseIL2CPP); + this.formCheckbox("profilingFuncs", "Profiling Funcs"); + this.formCheckbox("webgl2", "WebGL2.0(beta)"); + EditorGUILayout.EndVertical(); + } + + EditorGUILayout.EndScrollView(); + } + public void OnBuildButtonGUI(EditorWindow window) + { + GUIStyle linkStyle = new GUIStyle(GUI.skin.label); + linkStyle.normal.textColor = Color.yellow; + linkStyle.hover.textColor = Color.yellow; + linkStyle.stretchWidth = false; + linkStyle.alignment = TextAnchor.UpperLeft; + linkStyle.wordWrap = true; + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.LabelField(string.Empty, GUILayout.MinWidth(10)); + if (GUILayout.Button(new GUIContent("生成并转换"), GUILayout.Width(100), GUILayout.Height(25))) + { + this.saveData(); + if (WXPlayableConvertCore.DoExport() == WXConvertCore.WXExportError.SUCCEED) + { + window.ShowNotification(new GUIContent("转换完成")); + } + GUIUtility.ExitGUI(); + } + EditorGUILayout.EndHorizontal(); + } + private void OnDevelopmentBuildToggleChanged(bool InNewValue) + { + // 针对non-dev build,取消性能分析工具的集成 + if (!InNewValue) + { + this.setData("enablePerfAnalysis", false); + } + } + + private string SDKFilePath; + + private void loadData() + { + SDKFilePath = Path.Combine(UnityUtil.GetWxSDKRootPath(), "Runtime", "wechat-playable-default", "unity-sdk", "index.js"); + config = UnityUtil.GetPlayableEditorConf(); + _dstCache = config.ProjectConf.DST; + + this.setData("projectName", config.ProjectConf.projectName); + this.setData("appid", config.ProjectConf.Appid); + this.setData("orientation", (int)config.ProjectConf.Orientation); + this.setData("dst", _dstCache); + + this.setData("developBuild", config.CompileOptions.DevelopBuild); + this.setData("il2CppOptimizeSize", config.CompileOptions.Il2CppOptimizeSize); + this.setData("profilingFuncs", config.CompileOptions.profilingFuncs); + this.setData("webgl2", config.CompileOptions.Webgl2); + this.setData("customNodePath", config.CompileOptions.CustomNodePath); + + this.setData("memorySize", config.ProjectConf.MemorySize.ToString()); + } + + private void saveData() + { + config.ProjectConf.projectName = this.getDataInput("projectName"); + config.ProjectConf.Appid = this.getDataInput("appid"); + config.ProjectConf.Orientation = (WXScreenOritation)this.getDataPop("orientation"); + _dstCache = this.getDataInput("dst"); + config.ProjectConf.DST = _dstCache; + + config.CompileOptions.DevelopBuild = this.getDataCheckbox("developBuild"); + config.CompileOptions.Il2CppOptimizeSize = this.getDataCheckbox("il2CppOptimizeSize"); + config.CompileOptions.profilingFuncs = this.getDataCheckbox("profilingFuncs"); + config.CompileOptions.CustomNodePath = this.getDataInput("customNodePath"); + config.CompileOptions.Webgl2 = this.getDataCheckbox("webgl2"); + config.ProjectConf.MemorySize = int.Parse(this.getDataInput("memorySize")); + } + + private Dictionary formInputData = new Dictionary(); + private Dictionary formIntPopupData = new Dictionary(); + private Dictionary formCheckboxData = new Dictionary(); + + private string getDataInput(string target) + { + if (this.formInputData.ContainsKey(target)) + return this.formInputData[target]; + return ""; + } + + private int getDataPop(string target) + { + if (this.formIntPopupData.ContainsKey(target)) + return this.formIntPopupData[target]; + return 0; + } + + private bool getDataCheckbox(string target) + { + if (this.formCheckboxData.ContainsKey(target)) + return this.formCheckboxData[target]; + return false; + } + + private void formCheckbox(string target, string label, string help = null, bool disable = false, Action setting = null, Action onValueChanged = null) + { + if (!formCheckboxData.ContainsKey(target)) + { + formCheckboxData[target] = false; + } + GUILayout.BeginHorizontal(); + EditorGUILayout.LabelField(string.Empty, GUILayout.Width(10)); + if (help == null) + { + GUILayout.Label(label, GUILayout.Width(140)); + } + else + { + GUILayout.Label(new GUIContent(label, help), GUILayout.Width(140)); + } + EditorGUI.BeginDisabledGroup(disable); + + // Toggle the checkbox value based on the disable condition + bool newValue = EditorGUILayout.Toggle(disable ? false : formCheckboxData[target]); + // Update the checkbox data if the value has changed and invoke the onValueChanged action + if (newValue != formCheckboxData[target]) + { + formCheckboxData[target] = newValue; + onValueChanged?.Invoke(newValue); + } + + if (setting != null) + { + EditorGUILayout.LabelField("", GUILayout.Width(10)); + // 配置按钮 + if (GUILayout.Button(new GUIContent("设置"), GUILayout.Width(40), GUILayout.Height(18))) + { + setting?.Invoke(true); + } + EditorGUILayout.LabelField("", GUILayout.MinWidth(10)); + } + + EditorGUI.EndDisabledGroup(); + + if (setting == null) + EditorGUILayout.LabelField(string.Empty); + GUILayout.EndHorizontal(); + } + + private void setData(string target, string value) + { + if (formInputData.ContainsKey(target)) + { + formInputData[target] = value; + } + else + { + formInputData.Add(target, value); + } + } + + private void setData(string target, bool value) + { + if (formCheckboxData.ContainsKey(target)) + { + formCheckboxData[target] = value; + } + else + { + formCheckboxData.Add(target, value); + } + } + + private void setData(string target, int value) + { + if (formIntPopupData.ContainsKey(target)) + { + formIntPopupData[target] = value; + } + else + { + formIntPopupData.Add(target, value); + } + } + + private void formInput(string target, string label, string help = null) + { + if (!formInputData.ContainsKey(target)) + { + formInputData[target] = ""; + } + GUILayout.BeginHorizontal(); + EditorGUILayout.LabelField(string.Empty, GUILayout.Width(10)); + if (help == null) + { + GUILayout.Label(label, GUILayout.Width(140)); + } + else + { + GUILayout.Label(new GUIContent(label, help), GUILayout.Width(140)); + } + formInputData[target] = GUILayout.TextField(formInputData[target], GUILayout.MaxWidth(EditorGUIUtility.currentViewWidth - 195)); + GUILayout.EndHorizontal(); + } + + private void formIntPopup(string target, string label, string[] options, int[] values) + { + if (!formIntPopupData.ContainsKey(target)) + { + formIntPopupData[target] = 0; + } + GUILayout.BeginHorizontal(); + EditorGUILayout.LabelField(string.Empty, GUILayout.Width(10)); + GUILayout.Label(label, GUILayout.Width(140)); + formIntPopupData[target] = EditorGUILayout.IntPopup(formIntPopupData[target], options, values, GUILayout.MaxWidth(EditorGUIUtility.currentViewWidth - 195)); + GUILayout.EndHorizontal(); + } + + public static bool IsAbsolutePath(string path) + { + // 检查是否为空或空白 + if (string.IsNullOrWhiteSpace(path)) + { + return false; + } + + // 在 Windows 上,检查驱动器字母或网络路径 + if (Application.platform == RuntimePlatform.WindowsEditor && Path.IsPathRooted(path)) + { + return true; + } + + // 在 Unix/Linux 和 macOS 上,检查是否以 '/' 开头 + if (Application.platform == RuntimePlatform.OSXEditor && path.StartsWith("/")) + { + return true; + } + + return false; // 否则为相对路径 + } + + public static string GetAbsolutePath(string path) + { + if (IsAbsolutePath(path)) + { + return path; + } + + return Path.Combine(projectRootPath, path); + } + } +} \ No newline at end of file diff --git a/Editor/Playable/WXPlayableEditorSettingHelper.cs.meta b/Editor/Playable/WXPlayableEditorSettingHelper.cs.meta new file mode 100644 index 000000000..e1884b4cf --- /dev/null +++ b/Editor/Playable/WXPlayableEditorSettingHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1cc549c674e5b4efe964933831f56e80 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Playable/WXPlayableWindow.cs b/Editor/Playable/WXPlayableWindow.cs new file mode 100644 index 000000000..68c5f1fbf --- /dev/null +++ b/Editor/Playable/WXPlayableWindow.cs @@ -0,0 +1,46 @@ +using UnityEngine; +using UnityEditor; +using static WeChatWASM.WXConvertCore; + +namespace WeChatWASM +{ + + public class WXPlayableWin : EditorWindow + { + [MenuItem("微信小游戏 / 转换小游戏试玩", false, 2)] + public static void Open() + { + var win = GetWindow(typeof(WXPlayableWin), false, "微信小游戏试玩转换工具面板"); + win.minSize = new Vector2(350, 400); + win.position = new Rect(200, 200, 600, 300); + win.Show(); + } + + // 向前兼容,请使用 WXConvertCore.cs + public static WXExportError DoExport(bool buildWebGL = true) + { + return WXPlayableConvertCore.DoExport(buildWebGL); + } + + public void OnFocus() + { + WXPlayableSettingsHelperInterface.helper.OnFocus(); + } + + public void OnLostFocus() + { + WXPlayableSettingsHelperInterface.helper.OnLostFocus(); + } + + public void OnDisable() + { + WXPlayableSettingsHelperInterface.helper.OnDisable(); + } + + public void OnGUI() + { + WXPlayableSettingsHelperInterface.helper.OnSettingsGUI(this); + WXPlayableSettingsHelperInterface.helper.OnBuildButtonGUI(this); + } + } +} \ No newline at end of file diff --git a/Editor/Playable/WXPlayableWindow.cs.meta b/Editor/Playable/WXPlayableWindow.cs.meta new file mode 100644 index 000000000..57156661f --- /dev/null +++ b/Editor/Playable/WXPlayableWindow.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f37c59ed5d1a64bf59ac4657b5fd2cd8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/WXConvertCore.cs b/Editor/WXConvertCore.cs index 899d4d454..7267ae783 100644 --- a/Editor/WXConvertCore.cs +++ b/Editor/WXConvertCore.cs @@ -71,7 +71,9 @@ namespace WeChatWASM BUILD_WEBGL_FAILED = 2, } - public static WXEditorScriptObject config => UnityUtil.GetEditorConf(); + public static WXEditorScriptObject config => isPlayableBuild ? WXPlayableConvertCore.GetFakeScriptObject() : UnityUtil.GetEditorConf(); + + public static string defaultTemplateDir => isPlayableBuild ? "playable-default" : "wechat-default"; public static string webglDir = "webgl"; // 导出的webgl目录 public static string miniGameDir = "minigame"; // 生成小游戏的目录 public static string audioDir = "Assets"; // 音频资源目录 @@ -80,6 +82,10 @@ namespace WeChatWASM public static string codeMd5 = string.Empty; public static string dataMd5 = string.Empty; public static string defaultImgSrc = "Assets/WX-WASM-SDK-V2/Runtime/wechat-default/images/background.jpg"; + /// + /// 是否在构建试玩,构建开始前修改值,构建结束后恢复值 + /// + public static bool isPlayableBuild = false; private static bool lastBrotliType = false; public static bool UseIL2CPP @@ -93,37 +99,67 @@ namespace WeChatWASM #endif } } - // 可以调用这个来集成 - public static WXExportError DoExport(bool buildWebGL = true) + // public static void SetPlayableEnabled(bool enabled) + // { + // isPlayableBuild = enabled; + // } + /// + /// 导出前的初始配置 + /// 小游戏模式和试玩模式都会使用这个函数,如果要在这个函数加新方法,建议都以不兼容试玩模式看待 + /// + public static void PreInit() { - LifeCycleEvent.Init(); - Emit(LifeCycle.beforeExport); - if (!CheckSDK()) - { - Debug.LogError("若游戏曾使用旧版本微信SDK,需删除 Assets/WX-WASM-SDK 文件夹后再导入最新工具包。"); - return WXExportError.BUILD_WEBGL_FAILED; - } - if (!CheckBuildTemplate()) - { - Debug.LogError("因构建模板检查失败终止导出。"); - return WXExportError.BUILD_WEBGL_FAILED; - } - if (CheckInvalidPerfIntegration()) - { - Debug.LogError("性能分析工具只能用于Development Build, 终止导出! "); - return WXExportError.BUILD_WEBGL_FAILED; - } - - CheckBuildTarget(); Init(); - ProcessWxPerfBinaries(); + // 可能有顺序要求?如果没要求,可挪到此函数外 + if (!isPlayableBuild) + { + ProcessWxPerfBinaries(); + } MakeEnvForLuaAdaptor(); // JSLib SettingWXTextureMinJSLib(); UpdateGraphicAPI(); EditorUtility.SetDirty(config); AssetDatabase.SaveAssets(); + } + public static WXExportError PreCheck() + { + if (!CheckSDK()) + { + Debug.LogError("若游戏曾使用旧版本微信SDK,需删除 Assets/WX-WASM-SDK 文件夹后再导入最新工具包。"); + return WXExportError.BUILD_WEBGL_FAILED; + } + if (!isPlayableBuild && !CheckBuildTemplate()) + { + Debug.LogError("因构建模板检查失败终止导出。"); + return WXExportError.BUILD_WEBGL_FAILED; + } + if (!isPlayableBuild && CheckInvalidPerfIntegration()) + { + Debug.LogError("性能分析工具只能用于Development Build, 终止导出!"); + return WXExportError.BUILD_WEBGL_FAILED; + } + dynamic config = isPlayableBuild ? UnityUtil.GetPlayableEditorConf() : UnityUtil.GetEditorConf(); + if (config.ProjectConf.DST == string.Empty) + { + Debug.LogError("请先配置游戏导出路径"); + return WXExportError.BUILD_WEBGL_FAILED; + } + return WXExportError.SUCCEED; + } + // 可以调用这个来集成 + public static WXExportError DoExport(bool buildWebGL = true) + { + LifeCycleEvent.Init(); + Emit(LifeCycle.beforeExport); + var preCheckResult = PreCheck(); + if (preCheckResult != WXExportError.SUCCEED) + { + return preCheckResult; + } + + PreInit(); // 记录上次导出的brotliType { @@ -141,12 +177,6 @@ namespace WeChatWASM } } - if (config.ProjectConf.DST == string.Empty) - { - Debug.LogError("请先配置游戏导出路径"); - return WXExportError.BUILD_WEBGL_FAILED; - } - else { // 仅删除StreamingAssets目录 if (config.CompileOptions.DeleteStreamingAssets) @@ -566,7 +596,7 @@ namespace WeChatWASM private static bool CheckBuildTemplate() { string[] res = BuildTemplate.CheckCustomCoverBaseConflict( - Path.Combine(UnityUtil.GetWxSDKRootPath(), "Runtime", "wechat-default"), + Path.Combine(UnityUtil.GetWxSDKRootPath(), "Runtime", defaultTemplateDir), Path.Combine(Application.dataPath, "WX-WASM-SDK-V2", "Editor", "template"), new string[] { @"\.(js|ts|json)$" } ); @@ -801,7 +831,12 @@ namespace WeChatWASM PlayerSettings.WeixinMiniGame.emscriptenArgs = string.Empty; if (WXExtEnvDef.GETDEF("UNITY_2021_2_OR_NEWER")) { - PlayerSettings.WeixinMiniGame.emscriptenArgs += " -s EXPORTED_FUNCTIONS=_main,_sbrk,_emscripten_stack_get_base,_emscripten_stack_get_end -s ERROR_ON_UNDEFINED_SYMBOLS=0"; + PlayerSettings.WeixinMiniGame.emscriptenArgs += " -s EXPORTED_FUNCTIONS=_main,_sbrk,_emscripten_stack_get_base,_emscripten_stack_get_end"; + if (config.CompileOptions.enablePerfAnalysis) + { + PlayerSettings.WeixinMiniGame.emscriptenArgs += ",_WxPerfFrameIntervalCallback"; + } + PlayerSettings.WeixinMiniGame.emscriptenArgs += " -s ERROR_ON_UNDEFINED_SYMBOLS=0"; } #else @@ -809,6 +844,10 @@ namespace WeChatWASM if (WXExtEnvDef.GETDEF("UNITY_2021_2_OR_NEWER")) { PlayerSettings.WebGL.emscriptenArgs += " -s EXPORTED_FUNCTIONS=_sbrk,_emscripten_stack_get_base,_emscripten_stack_get_end"; + if (config.CompileOptions.enablePerfAnalysis) + { + PlayerSettings.WebGL.emscriptenArgs += ",_WxPerfFrameIntervalCallback"; + } #if UNITY_2021_2_5 PlayerSettings.WebGL.emscriptenArgs += ",_main"; #endif @@ -1156,7 +1195,10 @@ namespace WeChatWASM public static void convertDataPackageJS() { - checkNeedRmovePackageParallelPreload(); + if (!isPlayableBuild) + { + checkNeedRmovePackageParallelPreload(); + } var loadDataFromCdn = config.ProjectConf.assetLoadType == 0; Rule[] rules = @@ -1275,9 +1317,10 @@ namespace WeChatWASM RemoveOldAssetPackage(Path.Combine(config.ProjectConf.DST, webglDir)); RemoveOldAssetPackage(Path.Combine(config.ProjectConf.DST, webglDir + "-min")); var buildTemplate = new BuildTemplate( - Path.Combine(UnityUtil.GetWxSDKRootPath(), "Runtime", "wechat-default"), + Path.Combine(UnityUtil.GetWxSDKRootPath(), "Runtime", defaultTemplateDir), Path.Combine(Application.dataPath, "WX-WASM-SDK-V2", "Editor", "template"), - Path.Combine(config.ProjectConf.DST, miniGameDir) + Path.Combine(config.ProjectConf.DST, miniGameDir), + true ); buildTemplate.start(); // FIX: 2021.2版本生成symbol有bug,导出时生成symbol报错,有symbol才copy @@ -1506,7 +1549,8 @@ namespace WeChatWASM writer.PrettyPrint = true; // 将 game.json 里面关系链相关的配置删除 - if (!config.SDKOptions.UseFriendRelation) + // 试玩 game.json 中不含其他配置 + if (!config.SDKOptions.UseFriendRelation && gameJson.ContainsKey("openDataContext") && gameJson.ContainsKey("plugins")) { gameJson.Remove("openDataContext"); gameJson["plugins"].Remove("Layout"); @@ -1517,7 +1561,7 @@ namespace WeChatWASM Directory.Delete(openDataDir, true); } - if (!config.SDKOptions.UseMiniGameChat) + if (!config.SDKOptions.UseMiniGameChat && gameJson.ContainsKey("plugins")) { gameJson["plugins"].Remove("MiniGameChat"); UnityEngine.Debug.Log(gameJson["plugins"]); @@ -1604,17 +1648,20 @@ namespace WeChatWASM { dst = Path.Combine(config.ProjectConf.DST, miniGameDir); } - string content = File.ReadAllText(Path.Combine(UnityUtil.GetWxSDKRootPath(), "Runtime", "wechat-default", "unity-sdk", "index.js"), Encoding.UTF8); + string content = File.ReadAllText(Path.Combine(UnityUtil.GetWxSDKRootPath(), "Runtime", defaultTemplateDir, "unity-sdk", "index.js"), Encoding.UTF8); content = content.Replace("$unityVersion$", Application.unityVersion); File.WriteAllText(Path.Combine(dst, "unity-sdk", "index.js"), content, Encoding.UTF8); // content = File.ReadAllText(Path.Combine(Application.dataPath, "WX-WASM-SDK-V2", "Runtime", "wechat-default", "unity-sdk", "storage.js"), Encoding.UTF8); - content = File.ReadAllText(Path.Combine(UnityUtil.GetWxSDKRootPath(), "Runtime", "wechat-default", "unity-sdk", "storage.js"), Encoding.UTF8); - var PreLoadKeys = config.PlayerPrefsKeys.Count > 0 ? JsonMapper.ToJson(config.PlayerPrefsKeys) : "[]"; - content = content.Replace("'$PreLoadKeys'", PreLoadKeys); - File.WriteAllText(Path.Combine(dst, "unity-sdk", "storage.js"), content, Encoding.UTF8); + if (!isPlayableBuild) + { + content = File.ReadAllText(Path.Combine(UnityUtil.GetWxSDKRootPath(), "Runtime", defaultTemplateDir, "unity-sdk", "storage.js"), Encoding.UTF8); + var PreLoadKeys = config.PlayerPrefsKeys.Count > 0 ? JsonMapper.ToJson(config.PlayerPrefsKeys) : "[]"; + content = content.Replace("'$PreLoadKeys'", PreLoadKeys); + File.WriteAllText(Path.Combine(dst, "unity-sdk", "storage.js"), content, Encoding.UTF8); + } // 修改纹理dxt // content = File.ReadAllText(Path.Combine(Application.dataPath, "WX-WASM-SDK-V2", "Runtime", "wechat-default", "unity-sdk", "texture.js"), Encoding.UTF8); - content = File.ReadAllText(Path.Combine(UnityUtil.GetWxSDKRootPath(), "Runtime", "wechat-default", "unity-sdk", "texture.js"), Encoding.UTF8); + content = File.ReadAllText(Path.Combine(UnityUtil.GetWxSDKRootPath(), "Runtime", defaultTemplateDir, "unity-sdk", "texture.js"), Encoding.UTF8); File.WriteAllText(Path.Combine(dst, "unity-sdk", "texture.js"), content, Encoding.UTF8); } @@ -1831,14 +1878,15 @@ namespace WeChatWASM UnityEngine.Debug.LogFormat("[Converter] Starting to modify configs"); var PRELOAD_LIST = GetPreloadList(config.ProjectConf.preloadFiles); - var imgSrc = HandleLoadingImage(); + // 试玩不存在封面图 + var imgSrc = isPlayableBuild ? "" : HandleLoadingImage(); var bundlePathIdentifierStr = GetArrayString(config.ProjectConf.bundlePathIdentifier); var excludeFileExtensionsStr = GetArrayString(config.ProjectConf.bundleExcludeExtensions); var screenOrientation = new List() { "portrait", "landscape", "landscapeLeft", "landscapeRight" }[(int)config.ProjectConf.Orientation]; - - var customUnicodeRange = GetCustomUnicodeRange(config.FontOptions.CustomUnicode); + // 试玩不支持系统字体 + var customUnicodeRange = isPlayableBuild ? "[]" : GetCustomUnicodeRange(config.FontOptions.CustomUnicode); Debug.Log("[Converter] customUnicodeRange: " + customUnicodeRange); var boolConfigInfo = GenerateBootInfo(); @@ -1911,6 +1959,10 @@ namespace WeChatWASM List replaceList = new List(replaceArrayList); List files = new List { "game.js", "game.json", "project.config.json", "unity-namespace.js", "check-version.js", "unity-sdk/font/index.js" }; + if (isPlayableBuild) + { + files = new List { "game.js", "game.json", "project.config.json", "unity-namespace.js", "check-version.js" }; + } if (WXRuntimeExtEnvDef.IsPreviewing) { diff --git a/Editor/WXEditorSettingHelper.cs b/Editor/WXEditorSettingHelper.cs index 87c5f2ebc..d19c637b0 100644 --- a/Editor/WXEditorSettingHelper.cs +++ b/Editor/WXEditorSettingHelper.cs @@ -514,7 +514,7 @@ namespace WeChatWASM config.ProjectConf.VideoUrl = this.getDataInput("videoUrl"); config.ProjectConf.Orientation = (WXScreenOritation)this.getDataPop("orientation"); _dstCache = this.getDataInput("dst"); - config.ProjectConf.DST = GetAbsolutePath(_dstCache); + config.ProjectConf.DST = _dstCache; config.ProjectConf.bundleHashLength = int.Parse(this.getDataInput("bundleHashLength")); config.ProjectConf.bundlePathIdentifier = this.getDataInput("bundlePathIdentifier"); config.ProjectConf.bundleExcludeExtensions = this.getDataInput("bundleExcludeExtensions"); diff --git a/Editor/WXPluginVersion.cs b/Editor/WXPluginVersion.cs index 1e1ad4cad..61fd47974 100644 --- a/Editor/WXPluginVersion.cs +++ b/Editor/WXPluginVersion.cs @@ -2,7 +2,7 @@ namespace WeChatWASM { public class WXPluginVersion { - public static string pluginVersion = "202505200750"; // 这一行不要改他,导出的时候会自动替换 + public static string pluginVersion = "202506190922"; // 这一行不要改他,导出的时候会自动替换 } public class WXPluginConf diff --git a/Editor/wx-editor.dll b/Editor/wx-editor.dll index 0e1619865..b22bda139 100644 Binary files a/Editor/wx-editor.dll and b/Editor/wx-editor.dll differ diff --git a/Editor/wx-editor.xml b/Editor/wx-editor.xml index 331e70649..05b31bf33 100644 --- a/Editor/wx-editor.xml +++ b/Editor/wx-editor.xml @@ -9,12 +9,17 @@ 构建模板工具类 + + + 是否忽略用户自定义模板 + + 复制覆盖时不参与覆盖的正则表达式,可在 beforeCoverTemplate(含)前动态修改 - + 防止自定义模板对覆盖基础模板有覆盖在新版本更新后有代码冲突需要做此检查 @@ -289,7 +294,7 @@ 工具函数 - + 微信SDK环境初始化 @@ -758,5 +763,61 @@ 字体配置 + + + 试玩项目名 + + + + + 试玩 appid + + + + + 导出路径(绝对路径) + + + + + 游戏内存大小(MB) + + + + + 游戏方向 + + + + + IOS限制固定的分辨率,以减少内存,但是会降低游戏画面品质 + 注意:不要随意修改,默认值为0,0表示不限制 + + + + + Development Build + + + + + Il2CppCodeGeneration.OptimizeSize + + + + + Profiling Funcs + + + + + WebGL2.0 + + + + + CustomNodePath + + diff --git a/Runtime/Plugins/SDK-Call-JS-Old.jslib b/Runtime/Plugins/SDK-Call-JS-Old.jslib index 0b318f3ce..6d658038c 100755 --- a/Runtime/Plugins/SDK-Call-JS-Old.jslib +++ b/Runtime/Plugins/SDK-Call-JS-Old.jslib @@ -1008,7 +1008,6 @@ mergeInto(LibraryManager.library, { var sdk = _WXPointer_stringify_adaptor(sdkName); var func = _WXPointer_stringify_adaptor(functionName); var formattedArgs = JSON.parse(_WXPointer_stringify_adaptor(args)); - console.log('!!!WX_CallJSFunction', sdk, func, formattedArgs); GameGlobal[sdk][func].apply(GameGlobal[sdk], formattedArgs); }, WX_CallJSFunctionWithReturn: function (sdkName, functionName, args) { diff --git a/Runtime/Plugins/WxPerfJsBridge.jslib b/Runtime/Plugins/WxPerfJsBridge.jslib index 828162dac..adb5ceac1 100644 --- a/Runtime/Plugins/WxPerfJsBridge.jslib +++ b/Runtime/Plugins/WxPerfJsBridge.jslib @@ -28,6 +28,22 @@ mergeInto(LibraryManager.library, { GameGlobal.unityNamespace.ProfileWebgl.stopRecord(); } }, + JSProfilerUploadBinary: function(dataPtr, bufSize, namePtr, dirPtr, id, inStartFrameIdx, inEndFrameIdx) { + //if (GameGlobal && GameGlobal.manager && GameGlobal.manager.profiler) { + const name = UTF8ToString(namePtr); + const dir = UTF8ToString(dirPtr); + const content = HEAPU8.slice(dataPtr, dataPtr+bufSize); + GameGlobal.manager.profiler.uploadBinary({ + 'data': content, + 'len': bufSize, + 'fileName': name, + 'uploadDir': dir, + 'id': id, + 'startFrameIndex': inStartFrameIdx, + 'endFrameIndex': inEndFrameIdx + }); + //} + }, JSProfilerUploadString: function(dataPtr, bufSize, namePtr, dirPtr, id, inStartFrameIdx, inEndFrameIdx) { //if (GameGlobal && GameGlobal.manager && GameGlobal.manager.profiler) { const name = UTF8ToString(namePtr); @@ -106,5 +122,12 @@ mergeInto(LibraryManager.library, { stringToUTF8(GameGlobal.unityNamespace.convertPluginVersion, stringOnWasmHeap, lengthBytes); return stringOnWasmHeap; + }, + + JSProfilerCanvasToFilepathSync: function(savePath) { + if (GameGlobal && GameGlobal.unityNamespace && GameGlobal.unityNamespace.ProfileWebgl && GameGlobal.unityNamespace.ProfileWebgl.stopRecord) { + const savePathJSStr = UTF8ToString(savePath); + GameGlobal.manager.profiler.canvasToFilepathSync(savePathJSStr); + } } -}); +}); \ No newline at end of file diff --git a/Runtime/Plugins/wx-perf.dll b/Runtime/Plugins/wx-perf.dll index 4074f5f32..47ce1238d 100644 Binary files a/Runtime/Plugins/wx-perf.dll and b/Runtime/Plugins/wx-perf.dll differ diff --git a/Runtime/Plugins/wx-perf.dll.meta b/Runtime/Plugins/wx-perf.dll.meta index 99b128da8..01f86625f 100644 --- a/Runtime/Plugins/wx-perf.dll.meta +++ b/Runtime/Plugins/wx-perf.dll.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: f0cbdcf50f6d52cea758f1ea825443c0 +guid: ffcf22f69c45d4919a04626e60e86c20 PluginImporter: externalObjects: {} serializedVersion: 2 @@ -7,68 +7,21 @@ PluginImporter: executionOrder: {} defineConstraints: [] isPreloaded: 0 - isOverridable: 1 + isOverridable: 0 isExplicitlyReferenced: 0 validateReferences: 1 platformData: - - first: - : Any - second: - enabled: 0 - settings: - Exclude Editor: 0 - Exclude Linux64: 1 - Exclude OSXUniversal: 1 - Exclude WebGL: 0 - Exclude Win: 1 - Exclude Win64: 1 - first: Any: second: - enabled: 0 + enabled: 1 settings: {} - first: Editor: Editor second: - enabled: 1 + enabled: 0 settings: - CPU: AnyCPU DefaultValueInitialized: true - OS: AnyOS - - first: - Standalone: Linux64 - second: - enabled: 0 - settings: - CPU: None - - first: - Standalone: OSXUniversal - second: - enabled: 0 - settings: - CPU: None - - first: - Standalone: Win - second: - enabled: 0 - settings: - CPU: None - - first: - Standalone: Win64 - second: - enabled: 0 - settings: - CPU: None - - first: - WebGL: WebGL - second: - enabled: 1 - settings: {} - - first: - WeixinMiniGame: WeixinMiniGame - second: - enabled: 1 - settings: {} - first: Windows Store Apps: WindowsStoreApps second: diff --git a/Runtime/Plugins/wx-perf.xml.meta b/Runtime/Plugins/wx-perf.xml.meta index f0d3a97e1..f871240eb 100644 --- a/Runtime/Plugins/wx-perf.xml.meta +++ b/Runtime/Plugins/wx-perf.xml.meta @@ -1,7 +1,7 @@ fileFormatVersion: 2 -guid: 8ea3a597042b1e09596b698c5fcfd06b -DefaultImporter: -externalObjects: {} -userData: -assetBundleName: -assetBundleVariant: \ No newline at end of file +guid: 94249136b4b39434dbb3ae3f5b41f47b +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Plugins/wx-runtime-editor.dll b/Runtime/Plugins/wx-runtime-editor.dll index ca961ff6c..bfc6b30ee 100644 Binary files a/Runtime/Plugins/wx-runtime-editor.dll and b/Runtime/Plugins/wx-runtime-editor.dll differ diff --git a/Runtime/Plugins/wx-runtime-editor.xml b/Runtime/Plugins/wx-runtime-editor.xml index e04592bfe..ccaca068c 100644 --- a/Runtime/Plugins/wx-runtime-editor.xml +++ b/Runtime/Plugins/wx-runtime-editor.xml @@ -3124,6 +3124,26 @@ 是否成功 + + +  是否结束 + + + + + 接口调用结束的回调函数(调用成功、失败都会执行) + + + + + 接口调用失败的回调函数 + + + + + 接口调用成功的回调函数 + + 一个表示控制器设备上存在的坐标轴的数组 (比如控制器摇杆)。 diff --git a/Runtime/Plugins/wx-runtime.dll b/Runtime/Plugins/wx-runtime.dll index ab572eae8..f030f6042 100644 Binary files a/Runtime/Plugins/wx-runtime.dll and b/Runtime/Plugins/wx-runtime.dll differ diff --git a/Runtime/Plugins/wx-runtime.xml b/Runtime/Plugins/wx-runtime.xml index 5f5e944c3..a73f981c2 100644 --- a/Runtime/Plugins/wx-runtime.xml +++ b/Runtime/Plugins/wx-runtime.xml @@ -3130,6 +3130,26 @@ 是否成功 + + +  是否结束 + + + + + 接口调用结束的回调函数(调用成功、失败都会执行) + + + + + 接口调用失败的回调函数 + + + + + 接口调用成功的回调函数 + + 一个表示控制器设备上存在的坐标轴的数组 (比如控制器摇杆)。 diff --git a/Runtime/Plugins/wx_perf_2021.a b/Runtime/Plugins/wx_perf_2021.a index 2748bc3a3..f54f35d8b 100644 Binary files a/Runtime/Plugins/wx_perf_2021.a and b/Runtime/Plugins/wx_perf_2021.a differ diff --git a/Runtime/Plugins/wx_perf_2022.a b/Runtime/Plugins/wx_perf_2022.a index e0a76f1a3..da0f2ff3f 100644 Binary files a/Runtime/Plugins/wx_perf_2022.a and b/Runtime/Plugins/wx_perf_2022.a differ diff --git a/Runtime/WX.cs b/Runtime/WX.cs index 7977a5a30..cbb9acb6f 100644 --- a/Runtime/WX.cs +++ b/Runtime/WX.cs @@ -2667,6 +2667,23 @@ namespace WeChatWASM WXSDKManagerHandler.Instance.RevokeBufferURL(url); } + /// + /// [wx.setStorageSync(string key, any data)](https://developers.weixin.qq.com/minigame/dev/api/storage/wx.setStorageSync.html) + /// 将数据存储在本地缓存中指定的 key 中。会覆盖掉原来该 key 对应的内容。除非用户主动删除或因存储空间原因被系统清理,否则数据都一直可用。单个 key 允许存储的最大数据长度为 1MB,所有数据存储上限为 10MB。 + /// **注意** + /// storage 应只用来进行数据的持久化存储,不应用于运行时的数据传递或全局状态管理。启动过程中过多的同步读写存储,会显著影响启动耗时。 + /// **示例代码** + /// ```js + /// try { + /// wx.setStorageSync('key', 'value') + /// } catch (e) { } + /// ``` + /// + public static void SetStorageSync(string key, T data) + { + WXSDKManagerHandler.Instance.SetStorageSync(key, data); + } + /// /// [wx.shareAppMessage(Object object)](https://developers.weixin.qq.com/minigame/dev/api/share/wx.shareAppMessage.html) /// 主动拉起转发,进入选择通讯录界面。 diff --git a/Runtime/WXBase.cs b/Runtime/WXBase.cs index eaefbe801..3daf90bc9 100644 --- a/Runtime/WXBase.cs +++ b/Runtime/WXBase.cs @@ -1117,6 +1117,16 @@ namespace WeChatWASM { WXSDKManagerHandler.Instance.ReserveChannelsLive(option); } +#region 试玩特有接口 + /// + /// 通知试玩结束 + /// + /// + public static void NotifyMiniProgramPlayableStatus(NotifyMiniProgramPlayableStatusOption option) + { + WXSDKManagerHandler.Instance.NotifyMiniProgramPlayableStatus(option); + } +#endregion } } #endif diff --git a/Runtime/playable-default.meta b/Runtime/playable-default.meta new file mode 100644 index 000000000..0654d88b6 --- /dev/null +++ b/Runtime/playable-default.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 260b24feb18b7455485a7bd2ed1d0a07 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/playable-default/check-version.js b/Runtime/playable-default/check-version.js new file mode 100644 index 000000000..cfd2d0bb5 --- /dev/null +++ b/Runtime/playable-default/check-version.js @@ -0,0 +1,164 @@ +/* eslint-disable no-multi-assign */ +/* eslint-disable @typescript-eslint/naming-convention */ +const { version, SDKVersion } = wx.getAppBaseInfo ? wx.getAppBaseInfo() : wx.getSystemInfoSync(); +const { platform, system } = wx.getDeviceInfo ? wx.getDeviceInfo() : wx.getSystemInfoSync(); +const accountInfo = wx.getAccountInfoSync(); +const envVersion = accountInfo?.miniProgram?.envVersion; +function compareVersion(v1, v2) { + if (!v1 || !v2) { + return false; + } + return (v1 + .split('.') + .map(v => v.padStart(2, '0')) + .join('') + >= v2 + .split('.') + .map(v => v.padStart(2, '0')) + .join('')); +} +export const isDebug = false; +export const isPc = platform === 'windows' || platform === 'mac'; +export const isIOS = platform === 'ios'; +export const isAndroid = platform === 'android'; +export const isDevtools = platform === 'devtools'; +export const isMobile = !isPc && !isDevtools; +export const isDevelop = envVersion === 'develop'; +// 是否禁止**开通了高性能模式**的小游戏在不支持的iOS设备上回退成普通模式,回退可能导致无法正常体验游戏 +// @ts-ignore +const disableHighPerformanceFallback = $DISABLE_HIGHPERFORMANCE_FALLBACK && isIOS; +// 是否iOS高性能模式 +export const isH5Renderer = GameGlobal.isIOSHighPerformanceMode; +// 操作系统版本号 +const systemVersionArr = system ? system.split(' ') : []; +const systemVersion = systemVersionArr.length ? systemVersionArr[systemVersionArr.length - 1] : ''; +// pc微信版本号不一致,需要>=3.3 +const isPcWeChatVersionValid = compareVersion(version, '3.3'); +// 支持unity小游戏,需要试玩基础库>=2.0.10 +const isLibVersionValid = compareVersion(SDKVersion, '2.0.10'); +// 如果是iOS高性能模式,基础库需要>=2.0.10 +const isH5LibVersionValid = compareVersion(SDKVersion, '2.0.10'); +// 压缩纹理需要iOS系统版本>=14.0,检测到不支持压缩纹理时会提示升级系统 +const isIOSH5SystemVersionValid = compareVersion(systemVersion, '14.0'); +// iOS系统版本>=15支持webgl2,高性能模式+无此系统要求 +const isIOSWebgl2SystemVersionValid = compareVersion(systemVersion, '15.0') || GameGlobal.isIOSHighPerformanceModePlus; +// Android客户端版本>=8.0.19支持webgl2 +const isAndroidWebGL2ClientVersionValid = compareVersion(version, '8.0.19'); +// 是否用了webgl2 +const isWebgl2 = () => GameGlobal.managerConfig.contextConfig.contextType === 2; +// 是否支持BufferURL +export const isSupportBufferURL = !isPc + && (isH5Renderer + ? compareVersion(SDKVersion, '2.0.10') && compareVersion(version, '8.0.30') + : typeof wx.createBufferURL === 'function'); +// 安卓innerAudio支持playbackRate +export const isSupportPlayBackRate = !isAndroid || compareVersion(version, '8.0.23'); +// IOS innerAudio支持复用时再次触发onCanplay +export const isSupportCacheAudio = !isIOS || compareVersion(version, '8.0.31'); +// // 安卓旧客户端版本innerAudio偶现会导致闪退,大于等于8.0.38才使用innerAudio减少内存 +export const isSupportInnerAudio = compareVersion(version, '8.0.38'); +// 检查是否支持brotli压缩,pc基础库>=2.29.2,真机基础库>=2.21.1 +// @ts-ignore +const isPcBrotliInvalid = isPc && !compareVersion(SDKVersion, $LOAD_DATA_FROM_SUBPACKAGE ? '2.29.2' : '2.32.3'); +const isMobileBrotliInvalid = isMobile && !compareVersion(SDKVersion, '2.0.10'); +// @ts-ignore +const isBrotliInvalid = $COMPRESS_DATA_PACKAGE && (isPcBrotliInvalid || isMobileBrotliInvalid); +// iOS系统版本>=17.5时,小游戏退后台会导致异常 +export const isIOS175 = compareVersion(systemVersion, '17.5') && isH5Renderer; +// 试玩无开放数据域 +export const isSupportSharedCanvasMode = false; +// 是否能以iOS高性能模式运行 +// 请勿修改GameGlobal.canUseH5Renderer赋值!!! +GameGlobal.canUseH5Renderer = isH5Renderer && isH5LibVersionValid; +// iOS高性能模式定期GC +GameGlobal.canUseiOSAutoGC = false; +// pc微信版本不满足要求 +const isPcInvalid = isPc && !isPcWeChatVersionValid; +// 移动设备基础库版本或客户端版本不支持运行unity小游戏 +const isMobileInvalid = isMobile && !isLibVersionValid; +// 基础库/客户端不支持iOS高性能模式 +const isIOSH5Invalid = (isH5Renderer && !isH5LibVersionValid) || (!isH5Renderer && disableHighPerformanceFallback); +// 是否支持VideoPlayer组件,注意:开发者工具需要1.06.2310312以上版本 +export const isSupportVideoPlayer = false; +// 视情况添加,没用到对应能力就不需要判断 +// 是否支持webgl2 +const isWebgl2SystemVersionInvalid = () => isWebgl2() && ((!isIOSWebgl2SystemVersionValid && isIOS) || (isAndroid && !isAndroidWebGL2ClientVersionValid)); +// IOS高性能模式2.25.3以上基础库需要手动启动webAudio +export const webAudioNeedResume = false; +// 满足iOS高性能条件,但未开通高性能模式 +const needToastEnableHpMode = isDevelop && isIOS && isH5LibVersionValid && isIOSH5SystemVersionValid && !isH5Renderer; +/** + * 判断环境是否可使用coverview + * coverview实际需要基础库版本>=2.16.1,但因为移动端要>=2.17.0才能运行,所以移动端基本都支持coverview + * + * @export + * @returns + */ +export function canUseCoverview() { + return isMobile || isDevtools; +} +if (needToastEnableHpMode) { + console.error('此AppID未开通高性能模式\n请前往mp后台-能力地图-开发提效包-高性能模式开通\n可大幅提升游戏运行性能'); + // setTimeout(() => { + // wx.showModal({ + // title: '[开发版提示]建议', + // content: '此AppID未开通高性能模式\n请前往mp后台-能力地图-开发提效包-高性能模式开通\n可大幅提升游戏运行性能', + // showCancel: false, + // }) + // }, 10000); +} +// @ts-ignore +if (isIOS && typeof $IOS_DEVICE_PIXEL_RATIO === 'number' && $IOS_DEVICE_PIXEL_RATIO > 0) { + // @ts-ignore + window.devicePixelRatio = $IOS_DEVICE_PIXEL_RATIO; +} +else if (isPc) { + try { + if (window.devicePixelRatio < 2) { + window.devicePixelRatio = 2; + } + } + catch (e) { + console.warn(e); + } +} +export default () => new Promise((resolve) => { + if (!isDevtools) { + if (isPcInvalid + || isMobileInvalid + || isIOSH5Invalid + || isWebgl2SystemVersionInvalid() + || isBrotliInvalid) { + let updateWechat = true; + let content = '当前微信版本过低\n请更新微信后进行游戏'; + if (isIOS) { + if (!isIOSH5SystemVersionValid || (isWebgl2SystemVersionInvalid() && isIOS)) { + content = '当前操作系统版本过低\n请更新iOS系统后进行游戏'; + updateWechat = false; + } + } + console.error('提示: ', content); + wx.showModal({ + title: '提示', + content, + showCancel: false, + confirmText: updateWechat ? '更新微信' : '确定', + success(res) { + if (res.confirm) { + const showUpdateWechat = updateWechat && typeof wx.createBufferURL === 'function'; + if (showUpdateWechat) { + wx.updateWeChatApp(); + } + else { + wx.exitMiniProgram({ + success: () => { }, + }); + } + } + }, + }); + return resolve(false); + } + } + return resolve(true); +}); diff --git a/Runtime/playable-default/check-version.js.meta b/Runtime/playable-default/check-version.js.meta new file mode 100644 index 000000000..765634fe0 --- /dev/null +++ b/Runtime/playable-default/check-version.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 0b834659d694cd75e401a0cfa054b4d1 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/data-package.meta b/Runtime/playable-default/data-package.meta new file mode 100644 index 000000000..efa165943 --- /dev/null +++ b/Runtime/playable-default/data-package.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: dd3038c26002d669138e7670dcf5db5b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/data-package/game.js b/Runtime/playable-default/data-package/game.js new file mode 100644 index 000000000..e69de29bb diff --git a/Runtime/playable-default/data-package/game.js.meta b/Runtime/playable-default/data-package/game.js.meta new file mode 100644 index 000000000..6bb7acd02 --- /dev/null +++ b/Runtime/playable-default/data-package/game.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 802204aad50cb079999b5d69a89b5440 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/events.js b/Runtime/playable-default/events.js new file mode 100644 index 000000000..c47db5f02 --- /dev/null +++ b/Runtime/playable-default/events.js @@ -0,0 +1,58 @@ +const events = []; +const EventsManager = { + /** + * 注册一个事件并持续监听 + * @param eventName 事件名称 + * @param callback 事件的触发函数 + */ + on(eventName, callback) { + events.push({ + eventName, + callback, + once: false, + }); + }, + /** + * 注册一个事件并最多只触发一次 + * @param eventName 事件名称 + * @param callback 事件的触发函数 + */ + once(eventName, callback) { + events.push({ + eventName, + callback, + once: true, + }); + }, + /** + * 卸载一个事件 + * @param eventName 事件名称 + * @param callback 事件句柄,若缺省将卸载所有同名事件 + */ + off(eventName, callback) { + events.forEach((item, index) => { + if (item.eventName === eventName) { + if (!callback || item.callback === callback) { + events.splice(index, 1); + } + } + }); + }, + emit(eventName, ...args) { + const res = []; + const indexs = []; + events.forEach((item, index) => { + if (item.eventName === eventName) { + res.push(item.callback(...args)); + if (item.once) { + indexs.unshift(index); + } + } + }); + indexs.forEach((value) => { + events.splice(value, 1); + }); + return res; + }, +}; +GameGlobal.events = EventsManager; diff --git a/Runtime/playable-default/events.js.meta b/Runtime/playable-default/events.js.meta new file mode 100644 index 000000000..436809750 --- /dev/null +++ b/Runtime/playable-default/events.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 4233e6a36b92f459850cf74914936862 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/game.js b/Runtime/playable-default/game.js new file mode 100644 index 000000000..da53b8829 --- /dev/null +++ b/Runtime/playable-default/game.js @@ -0,0 +1,187 @@ +// @ts-nocheck +import './playable-fix'; +import './weapp-adapter'; +import './events'; +import './texture-config'; +import unityNamespace from './unity-namespace'; +import '.$DOTNET_RUNTIME_FOLD/$GAME_NAME.wasm.framework.unityweb'; +import './unity-sdk/index'; +import checkVersion from './check-version'; +import { launchEventType, scaleMode } from './plugin-config'; +import UnityManager from './unity-playable-plugin/index'; +const managerConfig = { + DATA_FILE_MD5: '$DATA_MD5', + CODE_FILE_MD5: '$CODE_MD5', + GAME_NAME: '$GAME_NAME', + APPID: '$APP_ID', + DATA_FILE_SIZE: '$DATA_FILE_SIZE', + OPT_DATA_FILE_SIZE: '$OPT_DATA_FILE_SIZE', + DATA_CDN: '$DEPLOY_URL', + // 资源包是否作为小游戏分包加载 + loadDataPackageFromSubpackage: $LOAD_DATA_FROM_SUBPACKAGE, + // 资源包放小游戏分包加载时,是否br压缩 + compressDataPackage: $COMPRESS_DATA_PACKAGE, + // 需要在网络空闲时预加载的资源,支持如下形式的路径 + preloadDataList: [ + // 'DATA_CDN/StreamingAssets/WebGL/textures_8d265a9dfd6cb7669cdb8b726f0afb1e', + // '/WebGL/sounds_97cd953f8494c3375312e75a29c34fc2' + '$PRELOAD_LIST', + ], + contextConfig: { + contextType: $WEBGL_VERSION, // 1: webgl1 2: webgl2 + }, + PROFILER_UPLOAD_URL: '', +}; +GameGlobal.managerConfig = managerConfig; +// 版本检查 +checkVersion().then((enable) => { + if (enable) { + // eslint-disable-next-line @typescript-eslint/naming-convention + // let UnityManager; + // try { + // // @ts-ignore + // UnityManager = requirePlugin('UnityPlugin', { + // enableRequireHostModule: true, + // customEnv: { + // wx, + // unityNamespace, + // document, + // canvas, + // events: GameGlobal.events, + // WXWASMSDK: GameGlobal.WXWASMSDK, + // }, + // }).default; + // } catch (error) { + // GameGlobal.realtimeLogManager.error(error); + // // logManager不支持自动处理错误对象 + // GameGlobal.logmanager.warn(error.stack); + // console.error('requirePlugin:', error); + // if (error.message.indexOf('not defined') !== -1) { + // console.error('!!!插件需要申请才可使用\n请勿使用测试AppID,并登录 https://mp.weixin.qq.com/ 并前往:能力地图-开发提效包-快适配 开通\n阅读文档获取详情:https://github.com/wechat-miniprogram/minigame-unity-webgl-transform/blob/main/Design/Transform.md'); + // } + // } + // JS堆栈能显示更完整 + Error.stackTraceLimit = Infinity; + Object.assign(managerConfig, { + // callmain结束后立即隐藏封面视频 + hideAfterCallmain: $HIDE_AFTER_CALLMAIN, + loadingPageConfig: { + // 以下是默认值 + totalLaunchTime: 7000, + animationDuration: 100, + /** + * !!注意:修改设计宽高和缩放模式后,需要修改文字和进度条样式。默认设计尺寸为667*375 + */ + designWidth: 0, + designHeight: 0, + scaleMode: scaleMode.default, + // 以下配置的样式,尺寸相对设计宽高 + textConfig: { + firstStartText: '首次加载请耐心等待', + downloadingText: ['正在加载资源'], + compilingText: '编译中', + initText: '初始化中', + completeText: '开始游戏', + textDuration: 1500, + // 文字样式 + style: { + bottom: 64, + height: 24, + width: 240, + lineHeight: 24, + color: '#ffffff', + fontSize: 12, + }, + }, + // 进度条样式 + barConfig: { + style: { + width: 240, + height: 24, + padding: 2, + bottom: 64, + backgroundColor: '#07C160', + }, + }, + // 一般不修改,控制icon样式 + iconConfig: { + visible: true, + style: { + width: 64, + height: 23, + bottom: 20, + }, + }, + // 加载页的素材配置 + materialConfig: { + // 背景图或背景视频,两者都填时,先展示背景图,视频可播放后,播放视频 + backgroundImage: '$BACKGROUND_IMAGE', + backgroundVideo: '$LOADING_VIDEO_URL', + iconImage: 'images/unity_logo.png', // icon图片,一般不更换 + }, + }, + }); + GameGlobal.managerConfig = managerConfig; + // 显示启动封面 + const gameManager = new UnityManager(managerConfig); + gameManager.onLaunchProgress((e) => { + // interface LaunchEvent { + // type: LaunchEventType; + // data: { + // costTimeMs: number; // 阶段耗时 + // runTimeMs: number; // 总耗时 + // loadDataPackageFromSubpackage: boolean; // 首包资源是否通过小游戏分包加载 + // isVisible: boolean; // 当前是否处于前台,onShow/onHide + // useCodeSplit: boolean; // 是否使用代码分包 + // isHighPerformance: boolean; // 是否iOS高性能模式 + // needDownloadDataPackage: boolean; // 本次启动是否需要下载资源包 + // }; + // } + if (e.type === launchEventType.launchPlugin) { + } + if (e.type === launchEventType.loadWasm) { + } + if (e.type === launchEventType.compileWasm) { + } + if (e.type === launchEventType.loadAssets) { + } + if (e.type === launchEventType.readAssets) { + } + if (e.type === launchEventType.prepareGame) { + } + }); + gameManager.onModulePrepared(() => { + // eslint-disable-next-line no-restricted-syntax + for (const key in unityNamespace) { + // 动态修改DATA_CDN后,同步修改全局对象 + if (!GameGlobal.hasOwnProperty(key) || key === 'DATA_CDN') { + GameGlobal[key] = unityNamespace[key]; + } + else { + } + } + managerConfig.DATA_CDN = GameGlobal.DATA_CDN; + gameManager.assetPath = `${(managerConfig.DATA_CDN || '').replace(/\/$/, '')}/Assets`; + }); + // 插件捕获到引擎错误后,会通过此事件抛给游戏 + gameManager.onLogError = function (err) { + GameGlobal.realtimeLogManager.error(err); + const isErrorObj = err && err.stack; + GameGlobal.logmanager.warn(isErrorObj ? err.stack : err); + }; + // iOS高性能模式定期GC + if (GameGlobal.canUseiOSAutoGC && unityNamespace.iOSAutoGCInterval !== 0) { + setInterval(() => { + wx.triggerGC(); + }, unityNamespace.iOSAutoGCInterval); + } + // 开始执行游戏启动流程 + gameManager.startGame(); + GameGlobal.manager = gameManager; + GameGlobal.events.on('launchOperaPushMsgToWasm', (callback, args) => GameGlobal.WXWASMSDK.WXLaunchOperaBridgeToC(callback, args)); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + GameGlobal.events.on('createWorker', (worker) => { + // worker created + }); + } +}); diff --git a/Runtime/playable-default/game.js.meta b/Runtime/playable-default/game.js.meta new file mode 100644 index 000000000..ef7de9eff --- /dev/null +++ b/Runtime/playable-default/game.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 92b1828e8ecd1581ab1b5b98331dd8bd +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/game.json b/Runtime/playable-default/game.json new file mode 100644 index 000000000..53ea8d986 --- /dev/null +++ b/Runtime/playable-default/game.json @@ -0,0 +1,9 @@ +{ + "deviceOrientation": "$ORIENTATION", + "engine": { + "name": "unity" + }, + "features": [ + "api.fs.readCompressedFile" + ] +} diff --git a/Runtime/playable-default/game.json.meta b/Runtime/playable-default/game.json.meta new file mode 100644 index 000000000..e8f85033d --- /dev/null +++ b/Runtime/playable-default/game.json.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 92595fff12b705d2f9fac76dc507764b +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/playable-fix.js b/Runtime/playable-default/playable-fix.js new file mode 100644 index 000000000..0bed12bb3 --- /dev/null +++ b/Runtime/playable-default/playable-fix.js @@ -0,0 +1,42 @@ +/* eslint-disable */ +delete wx.getWindowInfo; +delete wx.getDeviceInfo; +delete wx.getAppBaseInfo; +wx.getPerformance = function () { + return { + now: function () { + return Date.now() * 1000; + }, + }; +}; +wx.getRealtimeLogManager = function () { + return { + info: function (...args) { + console.log.apply(console, args); + }, + warn: function (...args) { + console.warn.apply(console, args); + }, + error: function (...args) { + console.error.apply(console, args); + }, + setFilterMsg: function () { }, + addFilterMsg: function () { }, + }; +}; +wx.getLogManager = function () { + return { + info: function (...args) { + console.log.apply(console, args); + }, + warn: function (...args) { + console.warn.apply(console, args); + }, + log: function (...args) { + console.log.apply(console, args); + }, + debug: function (...args) { + console.log.apply(console, args); + }, + }; +}; diff --git a/Runtime/playable-default/playable-fix.js.meta b/Runtime/playable-default/playable-fix.js.meta new file mode 100644 index 000000000..45c78d2d7 --- /dev/null +++ b/Runtime/playable-default/playable-fix.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: f89a2faca43696d491ef1d0ec059c468 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/plugin-config.js b/Runtime/playable-default/plugin-config.js new file mode 100644 index 000000000..47220167e --- /dev/null +++ b/Runtime/playable-default/plugin-config.js @@ -0,0 +1,19 @@ +export const launchEventType = { + launchPlugin: 0, + loadWasm: 1, + compileWasm: 2, + loadAssets: 3, + readAssets: 5, + prepareGame: 6, // 初始化引擎 +}; +// https://docs.egret.com/engine/docs/screenAdaptation/zoomMode +export const scaleMode = { + default: '', + noBorder: 'NO_BORDER', + exactFit: 'EXACT_FIT', + fixedHeight: 'FIXED_HEIGHT', + fixedWidth: 'FIXED_WIDTH', + showAll: 'SHOW_ALL', + fixedNarrow: 'FIXED_NARROW', + fixedWide: 'FIXED_WIDE', +}; diff --git a/Runtime/playable-default/plugin-config.js.meta b/Runtime/playable-default/plugin-config.js.meta new file mode 100644 index 000000000..ddc6e53b5 --- /dev/null +++ b/Runtime/playable-default/plugin-config.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 42511f91d8aa1c98352de4a65d4ae80a +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/plugins.meta b/Runtime/playable-default/plugins.meta new file mode 100644 index 000000000..f7d8cedbc --- /dev/null +++ b/Runtime/playable-default/plugins.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 94fa8901a990d01a1fd0fb10518e125b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/plugins/check-update.js b/Runtime/playable-default/plugins/check-update.js new file mode 100644 index 000000000..51b013111 --- /dev/null +++ b/Runtime/playable-default/plugins/check-update.js @@ -0,0 +1,23 @@ +function checkUpdate() { + const updateManager = wx.getUpdateManager(); + updateManager.onCheckForUpdate(() => { + // 请求完新版本信息的回调 + // console.log(res.hasUpdate) + }); + updateManager.onUpdateReady(() => { + wx.showModal({ + title: '更新提示', + content: '新版本已经准备好,是否重启应用?', + success(res) { + if (res.confirm) { + // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 + updateManager.applyUpdate(); + } + }, + }); + }); + updateManager.onUpdateFailed(() => { + // 新版本下载失败 + }); +} +checkUpdate(); diff --git a/Runtime/playable-default/plugins/check-update.js.meta b/Runtime/playable-default/plugins/check-update.js.meta new file mode 100644 index 000000000..4983f83ff --- /dev/null +++ b/Runtime/playable-default/plugins/check-update.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 4b23648b7922fb86269f95d8dd15930b +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/plugins/screen-adapter.js b/Runtime/playable-default/plugins/screen-adapter.js new file mode 100644 index 000000000..71cf7c4dd --- /dev/null +++ b/Runtime/playable-default/plugins/screen-adapter.js @@ -0,0 +1,9 @@ +wx.onWindowResize((res) => { + window.innerWidth = res.windowWidth; + window.innerHeight = res.windowHeight; +}); +wx.onDeviceOrientationChange(() => { + const info = wx.getWindowInfo ? wx.getWindowInfo() : wx.getSystemInfoSync(); + window.innerWidth = info.screenWidth; + window.innerHeight = info.screenHeight; +}); diff --git a/Runtime/playable-default/plugins/screen-adapter.js.meta b/Runtime/playable-default/plugins/screen-adapter.js.meta new file mode 100644 index 000000000..3107c6c8c --- /dev/null +++ b/Runtime/playable-default/plugins/screen-adapter.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b0e22021b4d0dcaa5e97fc5c97afd4bb +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/project.config.json b/Runtime/playable-default/project.config.json new file mode 100644 index 000000000..dab2f3b3e --- /dev/null +++ b/Runtime/playable-default/project.config.json @@ -0,0 +1,71 @@ +{ + "description": "项目配置文件", + "setting": { + "urlCheck": false, + "es6": true, + "enhance": true, + "postcss": true, + "preloadBackgroundData": false, + "minified": true, + "newFeature": true, + "coverView": true, + "nodeModules": false, + "autoAudits": false, + "showShadowRootInWxmlPanel": true, + "scopeDataCheck": false, + "uglifyFileName": false, + "checkInvalidKey": true, + "checkSiteMap": true, + "uploadWithSourceMap": true, + "compileHotReLoad": false, + "useMultiFrameRuntime": true, + "useApiHook": false, + "disableUseStrict": false, + "babelSetting": { + "ignore": ["$GAME_NAME.wasm.framework.unityweb.js"], + "disablePlugins": [], + "outputPath": "" + }, + "useIsolateContext": true, + "useCompilerModule": true, + "userConfirmedUseCompilerModuleSwitch": false, + "packNpmManually": false, + "packNpmRelationList": [] + }, + "compileType": "game", + "libVersion": "3.5.1", + "appid": "$APP_ID", + "projectname": "$PROJECT_NAME", + "simulatorType": "wechat", + "simulatorPluginLibVersion": {}, + "packOptions": { + "ignore": [ + { + "type": "folder", + "value": ".plugincache" + }, + { + "type": "suffix", + "value": ".symbols.unityweb" + } + ] + }, + "condition": { + "search": { + "current": -1, + "list": [] + }, + "conversation": { + "current": -1, + "list": [] + }, + "game": { + "currentL": -1, + "list": [] + }, + "miniprogram": { + "current": -1, + "list": [] + } + } +} diff --git a/Runtime/playable-default/project.config.json.meta b/Runtime/playable-default/project.config.json.meta new file mode 100644 index 000000000..c8edd8b97 --- /dev/null +++ b/Runtime/playable-default/project.config.json.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: c0e0cd60162187de96432b08eaa48d00 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/texture-config.js b/Runtime/playable-default/texture-config.js new file mode 100644 index 000000000..4dba8c5e8 --- /dev/null +++ b/Runtime/playable-default/texture-config.js @@ -0,0 +1,3 @@ +GameGlobal.USED_TEXTURE_COMPRESSION = false; +GameGlobal.TEXTURE_PARALLEL_BUNDLE = false; +GameGlobal.TEXTURE_BUNDLES = ''; diff --git a/Runtime/playable-default/texture-config.js.meta b/Runtime/playable-default/texture-config.js.meta new file mode 100644 index 000000000..4abbf4d14 --- /dev/null +++ b/Runtime/playable-default/texture-config.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b23e9ecce85c0e0177990706d7c47721 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-namespace.js b/Runtime/playable-default/unity-namespace.js new file mode 100644 index 000000000..f0db49076 --- /dev/null +++ b/Runtime/playable-default/unity-namespace.js @@ -0,0 +1,194 @@ +// @ts-nocheck +const unityNamespace = { + canvas: GameGlobal.canvas, + // cache width + canvas_width: GameGlobal.canvas.width, + // cache height + canvas_height: GameGlobal.canvas.height, + navigator: GameGlobal.navigator, + XMLHttpRequest: GameGlobal.XMLHttpRequest, + // 是否显示耗时的弹框,默认开发版时显示弹出耗时弹框 + hideTimeLogModal: true, + // 是否打印详细日志 + enableDebugLog: false, + // 自定义bundle中的hash长度 + bundleHashLength: $BUNDLE_HASH_LENGTH, + // 单位Bytes, 1MB = 1024 KB = 1024*1024Bytes + releaseMemorySize: $DEFAULT_RELEASE_SIZE, + unityVersion: '$UNITY_VERSION', + // Color Space: Gamma、Linear、Uninitialized(未初始化的颜色空间) + unityColorSpace: '$UNITY_COLORSPACE', + convertPluginVersion: '$PLUGIN_VERSION', + // 拼在StreamingAssets前面的path,DATA_CDN + streamingUrlPrefixPath + StreamingAssets + streamingUrlPrefixPath: '', + // DATA_CDN + dataFileSubPrefix + datafilename + dataFileSubPrefix: '$DATA_FILE_SUB_PREFIX', + // 当前appid扩容后,通过本字段告知插件本地存储最大容量,单位MB + maxStorage: $MAX_STORAGE_SIZE, + // 纹理中的hash长度 + texturesHashLength: $TEXTURE_HASH_LENGTH, + // 纹理存放路径 + texturesPath: '$TEXTURES_PATH', + // 是否需要缓存纹理, + needCacheTextures: $NEED_CACHE_TEXTURES, + // AssetBundle在内存中的存活时间 + ttlAssetBundle: 5, + // 是否显示性能面板 + enableProfileStats: $ENABLE_PROFILE_STATS, + // 是否预载微信系统字体 + preloadWXFont: $PRELOAD_WXFONT, + // iOS高性能模式定期GC间隔 + iOSAutoGCInterval: $IOS_AUTO_GC_INTERVAL, + // 是否使用微信压缩纹理 + usedTextureCompression: GameGlobal.USED_TEXTURE_COMPRESSION, + // 是否使用autostreaming + usedAutoStreaming: $USED_AUTO_STREAMING, + // 是否显示渲染日志(dev only) + enableRenderAnalysisLog: $ENABLE_RENDER_ANALYSIS_LOG, + // 是否dotnet runtime + useDotnetRuntime: $USE_DOTNET_RUNTIME, + // 是否用了多线程brotli压缩 + useBrotliMT: $USE_BROTLI_MT, + // Boot config配置,包含例如wait-for-native-debugger、player-connection-ip等信息 + bootConfig: '$BOOT_CONFIG_INFO', + // 是否以Development Build构建 + isDevelopmentBuild: $Is_Development_Build, + // 是否以Profiling Build导出 + isProfilingBuild: $Is_Profiling_Build, + // 预留的堆内存 + unityHeapReservedMemory: $UnityHeapReservedMemory, +}; +// 最佳实践检测配置 +unityNamespace.monitorConfig = { + // 显示优化建议弹框 + showSuggestModal: $SHOW_SUGGEST_MODAL, + // 是否开启检测(只影响开发版/体验版,线上版本不会检测) + enableMonitor: true, + // 帧率低于此值的帧会被记录,用于分析长耗时帧,做了限帧的游戏应该适当调低 + fps: 10, + // 是否一直检测到游戏可交互完成 + showResultAfterLaunch: true, + // 仅当showResultAfterLaunch=false时有效, 在引擎初始化完成(即callmain)后多长时间停止检测 + monitorDuration: 30000, +}; +// 判断是否需要自动缓存的文件,返回true自动缓存;false不自动缓存 +unityNamespace.isCacheableFile = function (path) { + // 判定为下载bundle的路径标识符,此路径下的下载,会自动缓存 + const cacheableFileIdentifier = [$BUNDLE_PATH_IDENTIFIER]; + // 命中路径标识符的情况下,并不是所有文件都有必要缓存,过滤下不需要缓存的文件 + const excludeFileIdentifier = [$EXCLUDE_FILE_EXTENSIONS]; + if (cacheableFileIdentifier.some(identifier => path.includes(identifier) + && excludeFileIdentifier.every(excludeIdentifier => !path.includes(excludeIdentifier)))) { + return true; + } + return false; +}; +// 是否上报此条网络异常, 返回true则上报, 返回false则忽略 +unityNamespace.isReportableHttpError = function (_info) { + // const { url, error } = _info; + return true; +}; +// 判断是否是AssetBundle +unityNamespace.isWXAssetBundle = function (path) { + return unityNamespace.WXAssetBundles.has(unityNamespace.PathInFileOS(path)); +}; +unityNamespace.PathInFileOS = function (path) { + return path.replace(`${wx.env.USER_DATA_PATH}/__GAME_FILE_CACHE`, ''); +}; +unityNamespace.WXAssetBundles = new Map(); +// 清理缓存时是否可被自动清理;返回true可自动清理;返回false不可自动清理 +unityNamespace.isErasableFile = function (info) { + // 用于特定AssetBundle的缓存保持 + if (unityNamespace.WXAssetBundles.has(info.path)) { + return false; + } + // 达到缓存上限时,不会被自动清理的文件 + const inErasableIdentifier = []; + if (inErasableIdentifier.some(identifier => info.path.includes(identifier))) { + return false; + } + return true; +}; +GameGlobal.WebAssembly = GameGlobal.WXWebAssembly; +GameGlobal.unityNamespace = GameGlobal.unityNamespace || unityNamespace; +GameGlobal.realtimeLogManager = wx.getRealtimeLogManager(); +GameGlobal.logmanager = wx.getLogManager({ level: 0 }); +// 提前监听错误并打日志 +function bindGloblException() { + // 默认上报小游戏实时日志与用户反馈日志(所有error日志+小程序框架异常) + wx.onError((result) => { + // 若manager已初始化,则直接用manager打日志即可 + if (GameGlobal.manager) { + GameGlobal.manager.printErr(result.message); + } + else { + GameGlobal.realtimeLogManager.error(result); + const isErrorObj = result && result.stack; + GameGlobal.logmanager.warn(isErrorObj ? result.stack : result); + console.error('onError:', result); + } + }); + wx.onUnhandledRejection((result) => { + GameGlobal.realtimeLogManager.error(result); + const isErrorObj = result && result.reason && result.reason.stack; + GameGlobal.logmanager.warn(isErrorObj ? result.reason.stack : result.reason); + console.error('unhandledRejection:', result.reason); + }); + // 上报初始信息 + function printSystemInfo(appBaseInfo, deviceInfo) { + // eslint-disable-next-line @typescript-eslint/naming-convention + const { version, SDKVersion } = appBaseInfo; + const { platform, system } = deviceInfo; + unityNamespace.version = version; + unityNamespace.SDKVersion = SDKVersion; + unityNamespace.platform = platform; + unityNamespace.system = system; + unityNamespace.isPc = platform === 'windows' || platform === 'mac'; + unityNamespace.isDevtools = platform === 'devtools'; + unityNamespace.isMobile = !unityNamespace.isPc && !unityNamespace.isDevtools; + unityNamespace.isH5Renderer = GameGlobal.isIOSHighPerformanceMode; + unityNamespace.isIOS = platform === 'ios'; + unityNamespace.isAndroid = platform === 'android'; + const bootinfo = { + renderer: GameGlobal.isIOSHighPerformanceMode ? 'h5' : '', + isH5Plus: GameGlobal.isIOSHighPerformanceModePlus || false, + abi: deviceInfo.abi || '', + brand: deviceInfo.brand, + model: deviceInfo.model, + platform: deviceInfo.platform, + system: deviceInfo.system, + version: appBaseInfo.version, + SDKVersion: appBaseInfo.SDKVersion, + benchmarkLevel: deviceInfo.benchmarkLevel, + }; + GameGlobal.realtimeLogManager.info('game starting', bootinfo); + GameGlobal.logmanager.info('game starting', bootinfo); + console.info('game starting', bootinfo); + } + const appBaseInfo = wx.getAppBaseInfo ? wx.getAppBaseInfo() : wx.getSystemInfoSync(); + const deviceInfo = wx.getDeviceInfo ? wx.getDeviceInfo() : wx.getSystemInfoSync(); + printSystemInfo(appBaseInfo, deviceInfo); +} +bindGloblException(); +// eslint-disable-next-line no-multi-assign +GameGlobal.onCrash = GameGlobal.unityNamespace.onCrash = function () { + GameGlobal.manager.showAbort(); + const windowInfo = wx.getWindowInfo ? wx.getWindowInfo() : wx.getSystemInfoSync(); + wx.createFeedbackButton({ + type: 'text', + text: '提交反馈', + style: { + left: (windowInfo.screenWidth - 184) / 2, + top: windowInfo.screenHeight / 3 + 140, + width: 184, + height: 40, + lineHeight: 40, + backgroundColor: '#07C160', + color: '#ffffff', + textAlign: 'center', + fontSize: 16, + borderRadius: 4, + }, + }); +}; +export default GameGlobal.unityNamespace; diff --git a/Runtime/playable-default/unity-namespace.js.meta b/Runtime/playable-default/unity-namespace.js.meta new file mode 100644 index 000000000..ab948cb04 --- /dev/null +++ b/Runtime/playable-default/unity-namespace.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 20a9bb8d548a37bb4a486e10f2362080 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-playable-plugin.meta b/Runtime/playable-default/unity-playable-plugin.meta new file mode 100644 index 000000000..a0cca0926 --- /dev/null +++ b/Runtime/playable-default/unity-playable-plugin.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d7946ca9e9f0adbe8f187722a9aa2d59 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-playable-plugin/index.js b/Runtime/playable-default/unity-playable-plugin/index.js new file mode 100644 index 000000000..cb820449d --- /dev/null +++ b/Runtime/playable-default/unity-playable-plugin/index.js @@ -0,0 +1 @@ +(()=>{var e={7:(e,t,n)=>{"use strict";function s(){}function i(e=20,t){const n=(t?"":"!#%()*+,-./:;=?@[]^_`{|}~")+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",s=n.length,i=[];for(let t=0;ti)return 1;if(t{const r=(t=0)=>{e.apply(null,[...s,t]).then(i).catch((e=>{t>0?setTimeout((()=>{r(t-1)}),n):o(e)}))};r(t)}))}function c(e){return e.then((e=>[null,e])).catch((e=>[e,null]))}function l(e,t="yyyy-MM-dd"){if(!e)return"";let n=t;const s=10===String(e).toString().length?new Date(1e3*e):new Date(e),i={"y+":s.getFullYear(),"M+":s.getMonth()+1,"d+":s.getDate(),"h+":s.getHours(),"m+":s.getMinutes(),"s+":s.getSeconds(),"q+":Math.floor((s.getMonth()+3)/3),"S+":s.getMilliseconds()};for(const[e,t]of Object.entries(i)){const s=new RegExp(`(${e})`);if(s.test(n)){const[e]=n.match(s);n=n.replace(s,(()=>`00${t}`.slice(-`${e}`.length)))}}return n}function u(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return!e;if(e instanceof Error)return""===e.message;switch(Object.prototype.toString.call(e)){case"[object String]":case"[object Array]":return!e.length;case"[object File]":case"[object Map]":case"[object Set]":return!e.size;case"[object Object]":return!Object.keys(e).length}return!1}function h(e){return"[object String]"===Object.prototype.toString.call(e)}function d(e){return"[object Object]"===Object.prototype.toString.call(e)}function p(e){return e&&"[object Function]"===Object.prototype.toString.call(e)}function g(e){let t=e;try{"object"==typeof e&&(t="string"==typeof e.errMsg?e.errMsg:"string"==typeof e.errmsg?e.errmsg:"string"==typeof e.message?e.message:JSON.stringify(e))}catch(e){console.error(e)}return t}function m(e,t,n){if(!n)return e;let s=e;const i=new RegExp(`([?&])${t}=.*?(&|$)`,"i");if(s.match(i))return s.replace(i,`$1${t}=${n}$2`);const o=-1!==s.indexOf("?")?"&":"?",r=s.split("#");return s=`${r[0]+o+t}=${n}`,r[1]&&(s+=`#${r[1]}`),s}n.d(t,{Et:()=>r,Gm:()=>o,Gv:()=>d,Im:()=>u,Kg:()=>h,L8:()=>g,Ld:()=>i,Mx:()=>a,NW:()=>c,Q$:()=>m,Tn:()=>p,Yq:()=>l,dv:()=>s})},72:(e,t,n)=>{"use strict";var s,i,o,r,a;n.d(t,{OD:()=>s,aM:()=>o,jt:()=>r,rC:()=>a}),function(e){e.devtools="devtools",e.android="android",e.ios="ios",e.windows="windows",e.mac="mac"}(s||(s={})),function(e){e.portrait="portrait",e.landscape="landscape",e.landscapeLeft="landscapeLeft",e.landscapeRight="landscapeRight"}(i||(i={})),function(e){e.DEVELOP="develop",e.TRIAL="trial",e.RELEASE="release"}(o||(o={})),function(e){e[e.release=1]="release",e[e.develop=2]="develop",e[e.trial=3]="trial"}(r||(r={})),function(e){e[e.Android=0]="Android",e[e.IOSJscore=1]="IOSJscore",e[e.IOSWK=2]="IOSWK",e[e.UnKnow=3]="UnKnow",e[e.PC=4]="PC",e[e.Devtools=5]="Devtools",e[e.IPadJscore=6]="IPadJscore",e[e.IPadWK=7]="IPadWK",e[e.IOSWKPlus=8]="IOSWKPlus",e[e.IPadWKPlus=9]="IPadWKPlus"}(a||(a={}))},347:(e,t,n)=>{"use strict";n.d(t,{A:()=>Ie});var s={};n.r(s),n.d(s,{navigateToMiniProgram:()=>I});var i=n(7),o=n(72);function r(e){var t,s,i,r,a;const c=null===(t=e.platform)||void 0===t?void 0:t.toLocaleLowerCase();return c===o.OD.devtools?o.rC.Devtools:c===o.OD.ios?e.model&&e.model.indexOf("iPad")>-1?(null===(s=n.g)||void 0===s?void 0:s.isIOSHighPerformanceModePlus)?o.rC.IPadWKPlus:(null===(i=n.g)||void 0===i?void 0:i.isIOSHighPerformanceMode)?o.rC.IPadWK:o.rC.IPadJscore:(null===(r=n.g)||void 0===r?void 0:r.isIOSHighPerformanceModePlus)?o.rC.IOSWKPlus:(null===(a=n.g)||void 0===a?void 0:a.isIOSHighPerformanceMode)?o.rC.IOSWK:o.rC.IOSJscore:c===o.OD.android?o.rC.Android:c===o.OD.windows||c===o.OD.mac?o.rC.PC:o.rC.UnKnow}var a,c,l,u,h;const d="undefined"!=typeof mb&&void 0!==mb.env,p=!("undefined"==typeof pluginEnv),g=!d&&"undefined"!=typeof wx&&"undefined"!=typeof Page,m=!(d||"undefined"==typeof wx||g)||p,f={isMagicBrush:d,isMiniGamePlugin:p,isMiniGame:m,isMiniProgram:g,isIOS:!1,isAndroid:!1,isDevtools:!1,isWindows:!1,isMac:!1,isPC:!1,isWK:!1,isWKPlus:!1,isIPad:!1,systemInfo:{},accountInfo:{},wx:{},runtimeType:o.rC.UnKnow,pluginWx:{},pluginAppId:"",pluginVersion:""};function y(e){var t;if(f.systemInfo=e,f.systemInfo.screenWidth||f.systemInfo.screenWidth||(f.systemInfo.screenWidth=0,f.systemInfo.screenHeight=0),f.runtimeType=r(f.systemInfo),v(f.systemInfo),(0,i.Gm)(f.systemInfo.SDKVersion,"2.24.4")>=0&&(null===(t=f.pluginWx)||void 0===t?void 0:t.getAccountInfoSync))try{const e=f.pluginWx.getAccountInfoSync()||{},{plugin:t={}}=e;f.pluginAppId=t.appId,f.pluginVersion=t.version}catch(e){console.error(e)}}function v(e){var t;const s=null===(t=e.platform)||void 0===t?void 0:t.toLocaleLowerCase();s===o.OD.devtools?f.isDevtools=!0:s===o.OD.ios?(f.isIOS=!0,f.isWK=!!(null===n.g||void 0===n.g?void 0:n.g.isIOSHighPerformanceMode),f.isWKPlus=!!(null===n.g||void 0===n.g?void 0:n.g.isIOSHighPerformanceModePlus)):s===o.OD.android?f.isAndroid=!0:s===o.OD.windows?f.isWindows=!0:s===o.OD.mac?f.isMac=!0:void 0===s&&(f.isIOS=!0),(f.isWindows||f.isMac)&&(f.isPC=!0),e.model&&e.model.indexOf("iPad")>-1&&(f.isIPad=!0)}if(m||g){if(p){const{customEnv:e}=pluginEnv;e&&e.customEnv&&(pluginEnv.customEnv=e.customEnv),"undefined"!=typeof wx&&(f.pluginWx=wx),pluginEnv.customEnv?f.wx=pluginEnv.customEnv.wx?pluginEnv.customEnv.wx:f.pluginWx:f.wx=f.pluginWx}else f.wx=wx;if(f.wx){try{y(f.wx.getSystemInfoSync()),f.wx.getSystemInfo({success:e=>{y(e)}})}catch(e){console.error(e)}try{f.accountInfo=null!==(l=null===(c=(a=f.wx).getAccountInfoSync)||void 0===c?void 0:c.call(a))&&void 0!==l?l:{}}catch(e){console.error(e)}}}else d&&mb.JSBridge.invoke("getSystemInfoSync",{},(e=>{f.systemInfo=e,f.runtimeType=r(f.systemInfo),v(f.systemInfo)}));null===(h=(u=f.wx).onDeviceOrientationChange)||void 0===h||h.call(u,(()=>{f.wx.getSystemInfo({success:e=>{f.systemInfo=e||{}}})})),p&&(f.pluginEnv=pluginEnv);const S=f;function I(e){S.wx.navigateToMiniProgram&&(S.pluginEnv&&S.pluginEnv.navigateToMiniProgramDirectly?S.pluginEnv.navigateToMiniProgramDirectly({appId:e}):S.wx.navigateToMiniProgram({appId:e}))}const{parse:T,stringify:w}=JSON,{keys:b}=Object,E=String,M="string",P="object",R=(e,t)=>t,A=(e,t,n)=>{const s=E(t.push(n)-1);return e.set(n,s),s},L=(e,t,n)=>{const s=t&&typeof t===P?(e,n)=>""===e||-1{s.length>0&&(s+=this.delimiter);let t=e;"object"==typeof t&&(t=t instanceof TypeError?t.message:L(t)),s+=`${String(t).trim()}`}));const i=`[minigamefe${this.namespace}XLog]: ${JSON.stringify(Object.assign(Object.assign({},this.base),{type:e,content:s}))}`;return this.debug&&(null===(n=console[e])||void 0===n||n.call(console,i)),i}report(e,t){const{reportFunc:n}=this;if(!n)return void console.error(`[minigamefe${this.namespace}XLog]: 未传入上报函数。`);if(!n[e]||"function"!=typeof n[e])return void console.error(`[minigamefe${this.namespace}XLog]: 传入的上报函数格式不对。`);const s=this.getLogStr(e,t);s&&n[e](s)}}!function(e){e[e.Front=1]="Front",e[e.Background=2]="Background"}(O||(O={})),function(e){e[e.Default=0]="Default",e[e.GameTransfer=1]="GameTransfer",e[e.Request=2]="Request",e[e.DownloadFile=3]="DownloadFile",e[e.CgiSpeedMeasure=4]="CgiSpeedMeasure",e[e.BadJs=5]="BadJs",e[e.Init=6]="Init",e[e.CostTime=7]="CostTime",e[e.Error=8]="Error",e[e.UploadFile=9]="UploadFile",e[e.Login=10]="Login",e[e.WebTransfer=11]="WebTransfer"}(D||(D={})),function(e){e[e.Info=101]="Info",e[e.Warn=102]="Warn",e[e.Error=103]="Error"}(x||(x={})),function(e){e.GameTransferReport="GameTransferReport",e.KeyValueReport="KeyValueReport",e.WxRequestReport="WxRequestReport"}(N||(N={}));const G=Object.values(D).filter((e=>(0,i.Et)(e)));const F=new class{constructor(){this.options={debug:!1,logReport:!1,qualityReportType:N.KeyValueReport,pluginAppId:"",pluginVersion:"",xlogName:"minigamefe"}}set(e){Object.assign(this.options,e)}get(e){return this.options[e]}};class k{constructor(e){this.identifier=`${F.get("pluginAppId")||S.pluginAppId}/plugin.js`,this.quality=e,this.init()}init(){var e,t;null===(t=null===(e=S.wx)||void 0===e?void 0:e.onError)||void 0===t||t.call(e,(e=>{this.processError(e.message)}))}processError(e){var t;if(e.indexOf(this.identifier)>-1){const n=e.split("\n"),s=n[0],i=null===(t=n[2])||void 0===t?void 0:t.split(":")[0];this.quality.innerReport({Type:D.BadJs,Target:s,CostTime:0,Result:e,CustomKey1:i})}}}var W,U,$=n(504);!function(e){e.GAMETRANSFER_IS_NOT_EXIST="gameTransfer is not exist",e.REQUEST_IS_NOT_EXIST="request is not exist",e.UPLOADFILE_IS_NOT_EXIST="uploadFile is not exist",e.LOGIN_IS_NOT_EXIST="login is not exist",e.URL_IS_EMPTY="request url is empty.",e.HEADER_INVALID="request header is invalid",e.METHOD_IS_NOT_EXIST="method is not exist"}(W||(W={}));class j extends $.TinyEmitter{}!function(e){e.login="login",e.gameTransfer="gameTransfer",e.request="request",e.uploadFile="uploadFile",e.downloadFile="downloadFile",e.webTransfer="webTransfer"}(U||(U={}));const V={QualityReportType:N,RequestRejectType:W,ReportType:D,PluginReportType:x},q=8192;var B,K;!function(e){e.STRING="STRING",e.LONGLONG="LONGLONG",e.UINT="UINT",e.INT="INT"}(B||(B={})),function(e){e.SvrReport="SvrReport",e.KvStat="KvStat"}(K||(K={}));const H={[B.STRING]:e=>"string"==typeof e&&e.length<=q,[B.LONGLONG]:e=>"number"==typeof e&&Math.floor(e)===e,[B.UINT]:e=>"number"==typeof e&&Math.floor(e)===e&&e>=0,[B.INT]:e=>"number"==typeof e&&Math.floor(e)===e};class z{constructor({logid:e,schemas:t={},base:n,debug:s=!1,namespace:i="",skipValidateInProdEnv:o=!0}){this.debug=!1,this.base={},this.namespace="",this.skipValidateInProdEnv=!0,this.asyncGetBase=()=>Promise.resolve({}),this.logid=e,this.schemas=t,n&&this.setBase(n),this.debug=s,this.skipValidateInProdEnv=o,this.namespace=i?` ${i} `:" "}setBase(e){this.validate(e),this.base=Object.assign(Object.assign({},this.base),e)}validate(e){if((this.debug||!this.skipValidateInProdEnv)&&Object.keys(this.schemas).length)for(const[t,n]of Object.entries(e)){if(void 0===n)continue;const e=this.schemas[t];e?this.validateColumn(e,n)||console.error(`[minigamefe${this.namespace}SchemaValidator]: logid ${this.logid}: ${t} should be ${e}, but now ${n}`):console.warn(`[minigamefe${this.namespace}SchemaValidator]: logid${this.logid}: ${t} 缺少类型定义`)}}validateColumn(e,t){return H[e](t)}}let X="";class J extends z{constructor({reportFunc:e,logid:t,schemas:n={},base:s,reportType:i,asyncGetBase:o=()=>Promise.resolve({}),debug:r,namespace:a="",skipValidateInProdEnv:c=!0}){super({logid:t,schemas:n,base:s,debug:r,namespace:a,skipValidateInProdEnv:c}),this.reportType=K.SvrReport,this.asyncGetBase=o,e||console.error(`[minigamefe${this.namespace}GameTransferReport]: 未传入上报函数。`),this.reportFunc=e,void 0!==i&&(this.reportType=i)}setKvStatBase(e,t){if(this.reportType===K.KvStat){const n=(e.system||"").split(" ");Object.assign(this.schemas,{DeviceModel:B.STRING,DeviceBrand:B.STRING,OsName:B.STRING,OsVersion:B.STRING,LanguageVersion:B.STRING,Count:B.UINT,AppId:B.STRING,AppVersion:B.UINT,AppState:B.UINT}),this.setBase({DeviceModel:e.model||"",DeviceBrand:e.brand||"",OsName:n[0]||"",OsVersion:n[1]||"",LanguageVersion:e.language||"",Count:1}),(null==t?void 0:t.miniProgram)&&this.setBase({AppState:o.jt[t.miniProgram.envVersion]||o.jt.release,AppId:t.miniProgram.appId,AppVersion:0})}}send(e,t){if(!this.reportFunc||"function"!=typeof this.reportFunc)return void console.error("[minigamefe GameTransferReport]: 未传入上报函数!!!");const n=[],s=this.logid;let o;o=Array.isArray(e)?e:[e],this.asyncGetBase().then((e=>{this.setBase(e),o.forEach((e=>{const t=Object.assign(Object.assign({},this.base),e);if(t.ExternInfo&&"object"==typeof t.ExternInfo&&this.schemas.ExternInfo===B.STRING&&(t.ExternInfo=encodeURIComponent(JSON.stringify(t.ExternInfo))),this.validate(t),this.reportType===K.KvStat){const e=Math.floor(Date.now()/1e3);Object.assign(t,{StartTime:e,EndTime:e})}const i={log_id:this.logid,custom_data:t};n.push(i),this.debug&&console.log(`[minigamefe${this.namespace}GameTransferReport]: ${s},`,t)}));const r={report_list:n};this.reportFunc({req_path:"comm_datareport",json_data:JSON.stringify(r),success(){t&&t(s,JSON.stringify(r))},fail(e){console.error(e),t&&t(s,(0,i.L8)(e))}})}))}}const Y={19283:"GameComponent",19335:"GameWhatsNew",20285:"MidasFriendPayment",21494:"WXGameWASMLaunchClose",21493:"WXGameWASMLaunchException",21492:"WXGameWASMLaunchTime",21898:"GameLifeMiniGameCardAction",20267:"GameAdsSkipCard"};class Q extends z{constructor({reportFunc:e,logid:t,protocolParams:n,schemas:s,base:i,asyncGetBase:o=()=>Promise.resolve({}),debug:r,namespace:a="",skipValidateInProdEnv:c=!0}){let l=t;"number"==typeof t&&Y[t]&&(l=Y[t],r&&console.warn(`[minigamefe${a?` ${a} `:" "}KeyValueReporter]: logid ${t} auto map to ${l}!`)),super({logid:l,schemas:s,base:i,debug:r,namespace:a,skipValidateInProdEnv:c}),this.asyncGetBase=o,e||console.error(`[minigamefe${this.namespace}KeyValueReporter]: 未传入上报函数。`),this.reportFunc=e||function(){},this.protocolParams=n,this.sendCbk=null}setAppInfoBase(e){Object.assign(this.schemas,{AppId:B.STRING,AppVersion:B.UINT,AppState:B.UINT}),this.protocolParams.unshift("AppId","AppVersion","AppState"),this.setBase(e)}send(e,t){let n;n=Array.isArray(e)?e:[e],this.asyncGetBase().then((e=>{this.setBase(e),n.forEach((e=>{const n=Object.assign(Object.assign({},this.base),e);this.validate(n);const s=[];this.protocolParams.forEach((e=>{const t=void 0!==n[e]?n[e]:"";s.push(t)})),this.reportFunc({key:this.logid,value:s.map(encodeURIComponent).join(","),immediately:!0});const i=t||this.sendCbk;if(i&&i(this.logid,s.map(encodeURIComponent).join(",")),this.debug){(n.IsError?console.error:console.log)(`[minigamefe${this.namespace}keyValueReport]: ${this.logid}`,n)}}))}))}}const Z="https://game.weixin.qq.com",ee="minigamefe_session_id";class te extends z{constructor({reportFunc:e,logid:t,schemas:n={},base:s,debug:i,namespace:o,asyncGetBase:r=()=>Promise.resolve({}),reportType:a,skipValidateInProdEnv:c=!0}){super({logid:t,schemas:n,base:s,debug:i,namespace:o,skipValidateInProdEnv:c}),this.reportType=K.SvrReport,this.reportFunc=e,e||console.error(`[minigamefe${this.namespace}RequestReport]: 未传入上报函数。`),this.asyncGetBase=r,void 0!==a&&(this.reportType=a)}setKvStatBase(e,t){if(this.reportType===K.KvStat){const n=(e.system||"").split(" ");Object.assign(this.schemas,{DeviceModel:B.STRING,DeviceBrand:B.STRING,OsName:B.STRING,OsVersion:B.STRING,LanguageVersion:B.STRING,Count:B.UINT,AppId:B.STRING,AppVersion:B.UINT,AppState:B.UINT}),this.setBase({DeviceModel:e.model||"",DeviceBrand:e.brand||"",OsName:n[0]||"",OsVersion:n[1]||"",LanguageVersion:e.language||"",Count:1}),(null==t?void 0:t.miniProgram)&&this.setBase({AppState:o.jt[t.miniProgram.envVersion]||o.jt.release,AppId:t.miniProgram.appId,AppVersion:0})}}send(e,t){if(!this.reportFunc||"function"!=typeof this.reportFunc)return void console.error("[minigamefe RequestReport]: 未传入上报函数!!!");const n=[],s=this.logid;let o;o=Array.isArray(e)?e:[e],this.asyncGetBase().then((e=>{this.setBase(e),o.forEach((e=>{const t=Object.assign(Object.assign({},this.base),e);this.validate(t);const i={log_id:s,custom_data:t};n.push(i)}));const r=JSON.stringify({report_list:n});this.debug&&console.log(`[minigamefe${this.namespace}RequestReport]: ${s}`,...n),this.reportFunc({url:`${Z}/cgi-bin/comm/datareport`,method:"POST",header:{"content-type":"application/x-www-form-urlencoded"},data:r,success(){t&&t(s,JSON.stringify(r))},fail(e){console.error(e),t&&t(s,(0,i.L8)(e))}})}))}}const ne=["BenchmarkLevel","NetworkType","RuntimeType","PluginAppId","PluginVersion","Scene","SDKVersion","IsVisible","Type","Target","Params","Result","CostTime","ExternInfo","CustomKey1","CustomKey2","CustomKey3","IsError","FELibVersion","Query"],se={BenchmarkLevel:B.UINT,NetworkType:B.STRING,RuntimeType:B.UINT,PluginAppId:B.STRING,PluginVersion:B.STRING,Scene:B.UINT,SDKVersion:B.STRING,IsVisible:B.UINT,Type:B.UINT,Target:B.STRING,Params:B.STRING,Result:B.STRING,CostTime:B.UINT,ExternInfo:B.STRING,CustomKey1:B.STRING,CustomKey2:B.STRING,CustomKey3:B.STRING,IsError:B.UINT,FELibVersion:B.STRING,Query:B.STRING};function ie(e){const{type:t=N.KeyValueReport,reportKeyValue:n,debug:s,gameTransfer:i,systemInfo:o,accountInfo:r,getNetworkType:a,onNetworkStatusChange:c,request:l,namespace:u}=e;let h,d="";function p(){return new Promise((e=>{d?e({NetworkType:d}):a({success:t=>{d=t.networkType,e({NetworkType:d})},fail:()=>{d="unknown",e({NetworkType:d})}})}))}return t===N.KeyValueReport?h=new Q({reportFunc:n,logid:26340,schemas:se,protocolParams:ne,debug:s,namespace:u,asyncGetBase:p}):t===N.GameTransferReport?(h=new J({reportFunc:i,logid:26340,schemas:se,reportType:K.KvStat,debug:s,namespace:u,asyncGetBase:p}),h.setKvStatBase(o,r)):(console.warn("[minigamefe]: 当前选择 reqeust 进行质量上报, 请自行确保兼容性"),h=new te({reportFunc:l,logid:26340,schemas:se,debug:s,namespace:u,asyncGetBase:p,reportType:K.KvStat}),h.setKvStatBase(o,r)),t!==N.GameTransferReport&&t!==N.WxRequestReport||function(e,t,n){X?e&&e(X):(t({success:t=>{X=t.networkType,e&&e(X)}}),n((t=>{X=t.networkType,t.isConnected||(X="none"),e&&e(X)})))}((e=>{d=e,h.setBase({NetworkType:e})}),a,c),h}const oe="1.1.79";function re(e,t){let n=e||"";if((0,i.Gv)(n))try{n=JSON.stringify(n)}catch(e){console.error(`[minigamefe stringify error]: ${e}`),n=""}else n=String(n);return n.length&&n.length>=q&&(n=n.substr(0,q),console.warn(`[minigamefe stringify warning]: ${t} 上报长度超过8192, 已裁剪`)),n}class ae{constructor(e){var t,n,s;this.benchmarkLevel=0,this.network="",this.runtimeType=o.rC.UnKnow,this.sdkVersion="0.0.0",this.isVisible=O.Front,this.scene=0,this.query="",this.pluginAppId="",this.pluginVersion="",this.inited=!1;const{systemInfo:a,launchInfo:c,onShow:l,onHide:u,pluginAppId:h="",pluginVersion:d=""}=e;if(!l||!u)return console.error("[minigamefe stringify warning]: please inject QualityConfig correctly"),void(this.inited=!1);this.inited=!0,this.onShow=l,this.onHide=u,this.benchmarkLevel=(a.benchmarkLevel||1)+100,this.sdkVersion=a.SDKVersion||"0.0.0",this.launchInfo=c,this.scene=(null===(t=this.launchInfo)||void 0===t?void 0:t.scene)||0,(0,i.Im)(null===(n=this.launchInfo)||void 0===n?void 0:n.query)||(this.query=encodeURIComponent(JSON.stringify(null===(s=this.launchInfo)||void 0===s?void 0:s.query))),this.runtimeType=r(a),this.pluginAppId=h,this.pluginVersion=d,this.bindNativeEvent(),this.reporter=ie(e),this.reporter.setBase({BenchmarkLevel:this.benchmarkLevel,RuntimeType:this.runtimeType,Scene:+this.scene,SDKVersion:this.sdkVersion,IsVisible:this.isVisible,PluginAppId:h,PluginVersion:d,FELibVersion:oe,Query:this.query})}bindNativeEvent(){this.onHide((()=>{this.isVisible=O.Background,this.reporter.setBase({IsVisible:this.isVisible})})),this.onShow((e=>{(0,i.Im)(null==e?void 0:e.query)||(this.query=encodeURIComponent(JSON.stringify(e.query))),this.isVisible=O.Front,this.reporter.setBase({IsVisible:this.isVisible,Query:this.query})}))}innerReport(e){this.reporter.send(Object.assign(e,{CostTime:(0,i.Et)(e.CostTime)?e.CostTime:0,Params:re(e.Params,"Params"),Result:re(e.Result,"Result"),ExternInfo:re(e.ExternInfo,"ExternInfo")}))}report(e){G.indexOf(e.Type)>-1&&console.error(`[minigamefe quality report]: 若为自定义上报, Type 请不要使用内置枚举值 ${e.Type}, 内置枚举可见 mgp.consts.ReportType`),this.inited&&this.innerReport(e)}setCustomKey(e){this.inited&&this.reporter.setBase({CustomKey1:e.CustomKey1&&re(e.CustomKey1,"CustomKey1")||"",CustomKey2:e.CustomKey2&&re(e.CustomKey2,"CustomKey2")||"",CustomKey3:e.CustomKey3&&re(e.CustomKey3,"CustomKey3")||""})}clearCustomKey(){this.inited&&this.reporter.setBase({CustomKey1:"",CustomKey2:"",CustomKey3:""})}}class ce{constructor({debug:e=!1,quality:t,namespace:n}){this.namespace="",this.errCodeIgnoreList=[],this.debug=e,this.quality=t,this.namespace=n?` ${n} `:" "}innerRequest(e,t){return new Promise(((n,s)=>{const{Constructor:o,funcName:r,reportType:a}=t;if(r!==U.login&&!e.url)return void s(W.URL_IS_EMPTY);const c=new o(e);c.optionsFilter(e),c.on("success",(()=>{var t;this.debug&&!0!==e.silent&&console.log(`[minigamefe${this.namespace}Network]: ${r} end with success`,c.response);const{response:s,sourceResponse:o,costTime:l}=c;let{errcode:u}=s;const{errmsg:h}=s;let d=h;e.reduceErrmsgBeforeReport&&(0,i.Tn)(e.reduceErrmsgBeforeReport)&&(d=e.reduceErrmsgBeforeReport(s)),r!==U.login||s.code||(d=s.errMsg,u=9999),(0,i.Et)(u)&&0!==Number(u)&&!0!==e.silent&&-1===this.errCodeIgnoreList.indexOf(Number(u))&&(null===(t=this.quality)||void 0===t||t.innerReport({Type:a,Target:e.url||"",Params:e.data,CostTime:l,Result:{errcode:u,errmsg:d},IsError:1})),n([s,o])})),c.on("error",(t=>{var n;!0!==e.silent&&(this.debug&&console.error(`[minigamefe${this.namespace}Network]: ${r} end with error`,e,t),null===(n=this.quality)||void 0===n||n.innerReport({Type:a,Target:e.url||"",CostTime:c.costTime,Params:e.data,Result:(0,i.L8)(t),IsError:1})),s(t)})),c.on("complete",((t=0)=>{var n;!0!==e.silent&&Math.random()<.1&&(null===(n=this.quality)||void 0===n||n.innerReport({Type:D.CgiSpeedMeasure,Target:e.url||"",Params:e.data,CostTime:c.costTime,IsError:t}))})),this.debug&&!0!==e.silent&&console.log(`[minigamefe${this.namespace}Network]: ${r} start`,e),c.send()}))}addIgnoreErrCode(e){(Array.isArray(e)?e:[e]).forEach((e=>{-1===this.errCodeIgnoreList.indexOf(e)&&this.errCodeIgnoreList.push(e)}))}removeIgnoreErrCode(e){(Array.isArray(e)?e:[e]).forEach((e=>{this.errCodeIgnoreList.indexOf(e)>-1&&this.errCodeIgnoreList.splice(this.errCodeIgnoreList.indexOf(e),1)}))}setRequestQualityReporter(e){this.quality=e}}class le{constructor(e){this.sessionId="",this.login=e.login,this.request=e.request}getSessionId(e){return this.checkSession().catch((()=>this.loginWxGame(e)))}clearSessionId(){var e,t;this.sessionId="",null===(t=(e=S.wx).removeStorageSync)||void 0===t||t.call(e,ee)}checkSession(){return new Promise(((e,t)=>{var n,s,i,o;const r=this.sessionId||(null===(s=(n=S.wx).getStorageSync)||void 0===s?void 0:s.call(n,ee));r?null===(o=(i=S.wx).checkSession)||void 0===o||o.call(i,{success:()=>{e({sessionId:r})},fail:e=>{this.clearSessionId(),t(e)}}):t({errMsg:"尚未保存sessionId"})}))}loginWxGame(e){return this.isLoginPromise||(this.isLoginPromise=new Promise(((t,n)=>{this.login({}).then((([t])=>{const n={code:t.code};return e&&(n.appid=e),this.request({url:`${Z}/cgi-bin/gameweappauthwap/login`,data:n,method:"POST"})})).then((([e])=>{var s,i;e&&e.data?(S.isMiniGamePlugin||null===(i=(s=S.wx).setStorageSync)||void 0===i||i.call(s,ee,e.data.session_id),this.sessionId=e.data.session_id||"",t({sessionId:e.data.session_id})):n({errMsg:"登录出错"})})).catch((()=>{n({errMsg:"登录出错"})}))}))),this.isLoginPromise.finally((()=>{this.isLoginPromise=void 0}))}}function ue(e,t){var n,s;if(!e)return"";let o=e,r=t;return r||(r=null===(s=(n=S.wx).getStorageSync)||void 0===s?void 0:s.call(n,ee)),r&&(o=(0,i.Q$)(o,"session_id",r)),o}class he extends j{constructor(e,t){super(),this.startTime=0,this.costTime=0,this.resAsResponse=!1,this.options=e,this.requestFunc=t}optionsFilter(e){return e.sessionId&&(e.url=ue(e.url,e.sessionId)),e}send(){this.startTime=Date.now();const{options:e}=this,t=Object.assign(e,{success:e=>{this.sourceResponse=e,this.costTime=Date.now()-this.startTime;let t=(this.resAsResponse?e:e.data)||{};if((0,i.Kg)(t))try{t=JSON.parse(t)}catch(e){t={}}this.response=t,this.emit("success"),this.emit("complete",0)},fail:e=>{this.costTime=Date.now()-this.startTime,this.emit("error",e),this.emit("complete",1)}});this.requestFunc(t)}}class de extends he{constructor(e){super(e,S.isMiniGamePlugin?S.pluginWx.request:S.wx.request)}optionsFilter(e){return e.timeout=e.timeout||3e4,e.header&&(e.header=Object.assign({"content-type":"application/json; charset=utf-8"},e.header||{})),e.method=e.method?e.method.toUpperCase():"GET",e.sessionId&&(e.url=ue(e.url,e.sessionId)),e}}class pe extends he{constructor(e){super(e,S.isMiniGamePlugin?S.pluginWx.uploadFile:S.wx.uploadFile)}}class ge extends he{constructor(){super({},S.isMiniGamePlugin?S.pluginWx.login:S.wx.login),this.resAsResponse=!0}}class me extends he{constructor(e){super(e,S.isMiniGamePlugin?S.pluginWx.downloadFile:S.wx.downloadFile),this.resAsResponse=!0}}class fe extends ce{constructor(e){super(e),this.login=this.initWxMethod({funcName:U.login,Constructor:ge,reportType:D.Login}),this.request=this.initWxMethod({funcName:U.request,Constructor:de,reportType:D.Request}),this.uploadFile=this.initWxMethod({funcName:U.uploadFile,Constructor:pe,reportType:D.UploadFile}),this.downloadFile=this.initWxMethod({funcName:U.downloadFile,Constructor:me,reportType:D.DownloadFile}),this.session=new le({login:this.login,request:this.request});const{pluginAppId:t=""}=e;this.pluginAppId=t}initWxMethod({funcName:e,Constructor:t,reportType:n}){const s=S.isMiniGamePlugin?S.pluginWx:S.wx;if(void 0!==s&&s[e]){const s={Constructor:t,funcName:e,reportType:n},i=e=>this.innerRequest(e||{},s);return e===U.request||e===U.uploadFile?this.initMethodNeedSession(i):i}console.warn(`[minigamfe${this.namespace}]: 当前环境不支持 ${e}。`);return()=>new Promise(((e,t)=>{t(W.METHOD_IS_NOT_EXIST)}))}initMethodNeedSession(e){return t=>t.needSession?this.session.getSessionId(this.pluginAppId).then((n=>e(Object.assign(t,n)))).then((([n,s])=>{return 401===(null==s?void 0:s.statusCode)||("-1702220400"==`${i=n.errcode}`||"-1702220401"==`${i}`||"-1702220407"==`${i}`||"-1702220402"==`${i}`||"40001"==`${i}`)?(this.session.clearSessionId(),this.session.getSessionId(this.pluginAppId).then((n=>e(Object.assign(t,n))))):[n,s];var i})):e(t)}}class ye extends j{constructor(e){super(),this.startTime=0,this.costTime=0,this.isSupportNoStringifyReqData=!1,this.options=e,this.isSupportNoStringifyReqData=!!((0,i.Gm)(S.systemInfo.SDKVersion,"2.29.1")>=0)}optionsFilter(e){return e.sessionId&&e.data&&!e.data.session_id&&(e.data.session_id=e.sessionId),e.timeout=e.timeout||3e4,e}send(){this.startTime=Date.now();const{options:e}=this,{url:t,data:n,flat:s=!1,timeout:o}=e,r=n||{},a=r&&(0,i.Gv)(r);a&&(r[`requestTime_${(0,i.Ld)(10,!0)}`]=Date.now());let c={req_path:t,timeout:o,success:e=>{this.costTime=Date.now()-this.startTime,this.sourceResponse=e,this.response=function(e){const{rawData:t="",respData:n={}}=e,s=t||n.data||"";if(!s)return{};try{return JSON.parse(s)}catch(e){return{}}}(e),this.emit("success"),this.emit("complete",0)},fail:e=>{this.costTime=Date.now()-this.startTime,this.emit("error",e),this.emit("complete",1)}};if(!s){const e=a?JSON.stringify(r):r;this.isSupportNoStringifyReqData?(c.reqData={req_path:t,json_data:e},delete c.req_path):c.json_data=e}s&&a&&(this.isSupportNoStringifyReqData?(c.reqData=Object.assign({req_path:t},r),delete c.req_path):c=Object.assign(Object.assign({},r),c)),S.pluginEnv.gameTransfer(c)}}class ve extends fe{constructor(e){super(e),this.gameTransfer=this.initGameTransfer()}initGameTransfer(){if(S.pluginEnv.gameTransfer){const e={Constructor:ye,funcName:U.gameTransfer,reportType:D.GameTransfer},t=t=>this.innerRequest(t,e);return this.initMethodNeedSession(t)}console.warn(`[minigamfe${this.namespace}]: 当前插件不支持 gameTransfer。`);return()=>new Promise(((e,t)=>{t(W.GAMETRANSFER_IS_NOT_EXIST)}))}}const Se=Date.now();const Ie=new class{constructor(){this.version=oe,this.consts=V,this.env=S,this.util=s,this.config=F,this.reporter={GameTransferReport:J,KeyValueReporter:Q}}init(e){var t;if(console.log("[minigamefe mgp]: inited"),n.g.mgp=this,this.config.set(e),this.network=new ve({pluginAppId:this.config.get("pluginAppId")||S.pluginAppId||"",debug:this.config.get("debug")||!1,namespace:"mgp"}),!S.isMiniGamePlugin)return void console.warn("[minigamefe mgp]: please use mgp in minigame plugin");const{pluginEnv:s}=S;s.gameTransfer||s.reportKeyValue?(this.quality=new ae({debug:this.config.get("debug")&&this.config.get("logReport"),type:this.config.get("qualityReportType"),pluginAppId:this.config.get("pluginAppId")||S.pluginAppId||"",pluginVersion:this.config.get("pluginVersion")||S.pluginVersion||"",launchInfo:S.wx.getLaunchOptionsSync(),accountInfo:S.accountInfo,systemInfo:S.systemInfo,onShow:S.wx.onShow,onHide:S.wx.onHide,getNetworkType:S.wx.getNetworkType,onNetworkStatusChange:S.wx.onNetworkStatusChange,gameTransfer:null==S?void 0:S.pluginEnv.gameTransfer,reportKeyValue:null===(t=null==S?void 0:S.pluginEnv)||void 0===t?void 0:t.reportKeyValue,request:S.pluginWx.request,namespace:"mgp"}),this.network.setRequestQualityReporter(this.quality),this.quality.innerReport({Type:D.Default,Target:"init",CostTime:Date.now()-Se}),new k(this.quality)):(console.warn("[minigamefe mgp]: 当前环境不支持质量上报。"),this.quality={report:i.dv});const o=this.config.get("debug");s.getXLogManager?(this.xlog=new _({reportFunc:s.getXLogManager(),namespace:"mgp",base:{name:this.config.get("xlogName")},debug:o}),o&&console.info("[minigamefe mgp]: 当前插件已支持 xlog, 建议在关键操作打客户端日志。")):(this.xlog=console,o&&console.info("[minigamefe MGP]: 当前客户端不支持 xlog, 降级为 console。"))}}},228:e=>{"use strict";var t=Object.prototype.hasOwnProperty,n="~";function s(){}function i(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,s,o,r){if("function"!=typeof s)throw new TypeError("The listener must be a function");var a=new i(s,o||e,r),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function r(e,t){0==--e._eventsCount?e._events=new s:delete e._events[t]}function a(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,s,i=[];if(0===this._eventsCount)return i;for(s in e=this._events)t.call(e,s)&&i.push(n?s.slice(1):s);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},a.prototype.listeners=function(e){var t=n?n+e:e,s=this._events[t];if(!s)return[];if(s.fn)return[s.fn];for(var i=0,o=s.length,r=new Array(o);i{function t(){}t.prototype={on:function(e,t,n){var s=this.e||(this.e={});return(s[e]||(s[e]=[])).push({fn:t,ctx:n}),this},once:function(e,t,n){var s=this;function i(){s.off(e,i),t.apply(n,arguments)}return i._=t,this.on(e,i,n)},emit:function(e){for(var t=[].slice.call(arguments,1),n=((this.e||(this.e={}))[e]||[]).slice(),s=0,i=n.length;s{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};(()=>{"use strict";n.r(s),n.d(s,{default:()=>rt});var e=n(347).A;const{env:t}=e;let i,o,r,a,c,l,u,h,d,p,g,m,f,y,v,S,I,T,w,b,E,M,P,R;if(t.isMiniGamePlugin){const{pluginEnv:e}=t,{customEnv:n}=e;i=t.wx,o=t.pluginWx,r=n.unityNamespace,a=n.canvas,c=n.document,b=n.events,E=n.WXWASMSDK,l=e.reportKeyValue||function(){console.warn("当前环境没有reportKeyValue函数!!")},u=e.gameTransfer||function(){console.warn("当前环境没有gameTransfer函数")},I=e.instanceId||"",S=e.setFileSpaceStatistics,T=e.getPrivateFileSystemManager,h=e.coverview,w=e.getWxCommonFont,M=e.createScreenCanvas,P=e.PIXI,R=e.TWEEN,h?({Component:d,getPrivateThis:p,removePrivateThis:g,create:m,init:f,webviewLayout:y,xmlParser:v}=h):d=class{}}else i=wx,r=GameGlobal.unityNamespace,a=GameGlobal.canvas,c=GameGlobal.document,l=function(){},u=function(){},d=function(){},p=function(e){return e},I="";r.isCacheableFile=r.isCacheableFile||function(e){return e.includes("StreamingAssets")};var A=n(7),L=n(72);const{systemInfo:C,accountInfo:O}=t,{pixelRatio:D,platform:x,benchmarkLevel:N,screenHeight:_,screenWidth:G,enableDebug:F,SDKVersion:k,version:W}=C,{miniProgram:U}=O||{},{envVersion:$=L.aM.DEVELOP}=(i.getFileSystemManager(),U||{}),j=$===L.aM.RELEASE,V=(L.aM.DEVELOP,F),q=!!r.enableDebugLog,B=!!V||!!t.isDevtools,K=((0,A.Gm)(k,"2.21.2"),!!h),H=t.isAndroid&&0===(0,A.Gm)(W,"8.0.25"),z=!!i.reportScene&&(0,A.Gm)(W,"8.0.27")>-1;r.instantiateWasm,t.isAndroid&&(0,A.Gm)(W,"8.0.34")>-1||t.isIOS&&(0,A.Gm)(W,"8.0.39");var X,J;a.id="",a.style.width=G,a.style.height=_,a.width=G*D,a.height=_*D,a.widthNative=0,a.heightNative=0,r.eventLog=function(...e){B&&console.log("[PLUGIN LOG]",...e)},r.timeLog=function(...e){console.log("[PLUGIN TIME LOG] ",...e)},function(e){e[e.GAME_LAUNCH=0]="GAME_LAUNCH",e[e.LOAD_SUBPACKAGE=1]="LOAD_SUBPACKAGE",e[e.COMPILE_WASM=2]="COMPILE_WASM",e[e.LOAD_ASSETS=3]="LOAD_ASSETS",e[e.UNZIP_ASSETS=4]="UNZIP_ASSETS",e[e.READ_ASSETS=5]="READ_ASSETS",e[e.PREPARE_GAME=6]="PREPARE_GAME",e[e.GAME_START=7]="GAME_START",e[e.LOAD_ASSET_BUNDLE=8]="LOAD_ASSET_BUNDLE",e[e.FILE_SYSTEM_INIT=9]="FILE_SYSTEM_INIT",e[e.GET_CONTEXT=10]="GET_CONTEXT",e[e.LOAD_BACKGROUND_IMAGE=11]="LOAD_BACKGROUND_IMAGE",e[e.COVER_VIEW_INIT=12]="COVER_VIEW_INIT",e[e.LAUNCH_OPERA_FRAME_START=13]="LAUNCH_OPERA_FRAME_START",e[e.LAUNCH_OPERA_FRAME_END=14]="LAUNCH_OPERA_FRAME_END",e[e.LAUNCH_OPERA_FRAME_CHECKPOINT=15]="LAUNCH_OPERA_FRAME_CHECKPOINT",e[e.LAUNCH_OPERA_FRAME_CHECKPOINT_COUNT=16]="LAUNCH_OPERA_FRAME_CHECKPOINT_COUNT"}(X||(X={})),function(e){e[e.normal=0]="normal",e[e.codeSplit=1]="codeSplit"}(J||(J={}));const Y={1:"webgl",2:"webgl2"};var Q;!function(e){e[e.ON_ABORT=100]="ON_ABORT",e[e.WaitingRemoveDependencies=101]="WaitingRemoveDependencies",e[e.WxABReadEmptyContent=102]="WxABReadEmptyContent"}(Q||(Q={}));class Z{static getInstance(){return this.instance||(this.instance=new this),this.instance}}const ee=class extends Z{constructor(){super(...arguments),this.data={},this.launchData=new Map}setData(e){this.data=Object.assign(Object.assign({},this.data),e)}addLaunchData(e){this.launchData.set(e.type,e)}getLaunchData(e){return this.launchData.get(e)}getAllLaunchData(){return Array.from(this.launchData.values())}}.getInstance();var te=function(e,t,n,s){return new(n||(n=Promise))((function(i,o){function r(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((s=s.apply(e,t||[])).next())}))};const ne=class extends Z{init(e){this.unityManager=e,this.initConfig()}initConfig(){return te(this,void 0,void 0,(function*(){}))}}.getInstance();var se,ie;!function(e){e.Mismatch="mismatch data size"}(se||(se={})),function(e){e.launchPlugin="launchPlugin",e.loadWasm="loadWasm",e.compileWasm="compileWasm",e.loadAssets="loadAssets",e.readAssets="readAssets",e.prepareGame="prepareGame",e.launchOperaInit="launchOperaInit",e.launchOperaMsgBridgeFromWasm="launchOperaMsgBridgeFromWasm",e.launchOperaPushMsgToWasm="launchOperaPushMsgToWasm",e.CreateWorker="createWorker"}(ie||(ie={}));var oe=n(228),re=n.n(oe);const ae=new class{constructor(){this.namespaces=new Map}getEventManager(e){return this.namespaces.has(e)||this.namespaces.set(e,new(re())),this.namespaces.get(e)}};const ce=(le="lifecycle",ae.getEventManager(le));var le,ue;!function(e){e.PluginLaunch="onPluginLaunch",e.LoadingPageReady="onLoadingPageReady",e.ParallelLoading="onParallelLoading",e.ParallelLoaded="onParallelLoaded",e.WasmLoading="onWasmLoading",e.WasmLoaded="onWasmLoaded",e.AssetLoading="onAssetLoading",e.AssetLoaded="onAssetLoaded",e.AssetProcessed="onAssetProcessed",e.WasmInstantiated="onWasmInstantiated",e.CalledMain="onCalledMain",e.FileSystemReady="onFileSystemReady",e.FeatureFlagReady="onFeatureFlagReady",e.ReporterReady="onReporterReady",e.InstanceReady="onInstanceReady",e.ModulePrepared="onModulePrepared",e.LaunchProgress="onLaunchProgress"}(ue||(ue={}));const he={[X.GAME_LAUNCH]:ie.launchPlugin,[X.LOAD_SUBPACKAGE]:ie.loadWasm,[X.COMPILE_WASM]:ie.compileWasm,[X.LOAD_ASSETS]:ie.loadAssets,[X.READ_ASSETS]:ie.readAssets,[X.PREPARE_GAME]:ie.prepareGame};class de{static getInstance(){return de.instance||(de.instance=new de),de.instance}init(e){const t=e;this.unityManager=t,this.bindFunction()}triggerEvent(e,t){ce.emit(e,t),e===ue.LaunchProgress&&(null==t?void 0:t.type)&&he[t.type]&&(null==b||b.emit(he[t.type],t))}bindFunction(){Object.values(ue).forEach((e=>{e===ue.LaunchProgress?this.unityManager[e]=t=>{"function"==typeof t&&ce.on(e,t);const n=ee.getAllLaunchData();(null==n?void 0:n.length)&&n.forEach((t=>this.triggerEvent(e,t)))}:this.unityManager[e]=t=>{"function"==typeof t&&ce.on(e,t)}}))}}const pe=de.getInstance();class ge{constructor(e,...t){this.type=e,this.content=t}}class me extends oe.EventEmitter{constructor(e="default"){super(),this.tag=e,this.maxLogs=300,this.logItems=[],this.isSupport=!1,wx.getGameLogManager?this.isSupport=!0:(this.isSupport=!1,console.warn("wx.getGameLogManager is not support")),this.generateLogFunc()}getInstance(e){return this.instance||(this.instance=new me(e)),this.instance}init(e){return!this.logger&&this.isSupport&&(this.logger=wx.getGameLogManager({commonInfo:e}),this.logger=this.logger.tag(this.tag),this.logItems.length>0&&(this.logItems.forEach((e=>{this.logger[e.type](...e.content)})),this.logItems=[])),this.logger}generateLogFunc(){["info","warn","error","debug"].forEach((e=>{this[e]=(...t)=>{this.isSupport&&(this.logger?this.logger[e](...t):(this.logItems.push(new ge(e,...t)),this.logItems.length>this.maxLogs&&this.logItems.shift()))}}))}}const fe=new me("time"),ye=new me("trace"),ve=new me("error");const{pixelRatio:Se}=C;const Ie=function(){const e=[];return t=>"string"==typeof t&&(!!(t.includes("end of list")||t.includes("still waiting on run dependencies")||t.includes("dependency"))&&(!!e.includes(t)||(e.push(t),!1)))}();function Te(e){if(e instanceof Error)return`${e.message}\n${e.stack}`;if(e&&"string"==typeof e.stack&&"string"==typeof e.message)return`${e.message}\n${e.stack}`;switch(typeof e){case"bigint":case"boolean":case"function":case"number":case"symbol":return e.toString();case"string":return e;case"undefined":return"undefined";case"object":{let t;try{t=JSON.stringify(e)}catch(e){t="[对象含有循环引用]"}return t}default:return}}class we{static timeStart(e){if(!we.timeMap.has(e)){const t=Date.now();return we.timeMap.set(e,t),t}return 0}static printTime(e){const t=e.indexOf("callMain耗时")>-1&&r.DO_RUN_START,n=e.indexOf("wasm编译耗时")>-1&&r.WASM_BEGIN_TIME;if(we.timeMap.has(e)||n||t){const t=we.timeEnd(e,!1),n=`[PLUGIN TIME LOG ${(0,A.Yq)(Date.now(),"hh:mm.ss.SSS")}] ${e}: ${t}ms`;fe.info(n),console.log(n),we.timeStrList.push(n)}}static timeEnd(e,t=!0){const n=e.indexOf("callMain耗时")>-1&&r.DO_RUN_START,s=e.indexOf("wasm编译耗时")>-1&&r.WASM_BEGIN_TIME;if(we.timeMap.has(e)||n||s){const i=Date.now();let o=we.timeMap.get(e);return n&&(o=r.DO_RUN_START),s&&(o=r.WASM_BEGIN_TIME),t&&we.timeMap.delete(e),i-o}return 0}static getRuntime(e=!1){const t=Date.now()-we.logStartTime;return e?+(t/1e3).toFixed(2):t}static printRuntime(e){const t=`[PLUGIN TIME LOG ${(0,A.Yq)(Date.now(),"hh:mm.ss.SSS")}] ${e}: ${we.getRuntime()}ms`;console.log(t),t.indexOf("游戏启动耗时")>-1&&(we.timeStrList.push(t),r.hideTimeLogModal||!r.showTimeLogInAllVersion&&$!==L.aM.DEVELOP||(i.showModal({title:"timelog",content:we.timeStrList.join("\r\n")}),we.timeStrList=[]))}static storeTime(e){we.storeTimeMap.has(e)||we.storeTimeMap.set(e,{CostTimeMs:we.timeEnd(e),RunTimeMs:we.getRuntime()})}static popTime(e){if(we.storeTimeMap.has(e)){const t=we.storeTimeMap.get(e);return we.storeTimeMap.delete(e),t}return null}}we.logStartTime=Date.now(),we.timeMap=new Map,we.storeTimeMap=new Map,we.timeStrList=[];class be{static eventLog(...e){ye.info(Array.from(e).map(Te).join(" ")),B&&console.log(`[PLUGIN LOG ${(0,A.Yq)(Date.now(),"hh:mm.ss.SSS")}] `,...e)}static debugLog(...e){B&&q&&console.log(`[DEBUG LOG ${(0,A.Yq)(Date.now(),"hh:mm.ss.SSS")}] `,...e)}static debugWarn(...e){B&&q&&console.warn(`[DEBUG WARN ${(0,A.Yq)(Date.now(),"hh:mm.ss.SSS")}] `,...e)}static debugError(...e){B&&q&&console.error(`[DEBUG ERROR ${(0,A.Yq)(Date.now(),"hh:mm.ss.SSS")}] `,...e)}static pluginLog(...e){B&&q&&console.log(`[PLUGIN LOG ${(0,A.Yq)(Date.now(),"hh:mm.ss.SSS")}] `,...e)}static pluginWarn(...e){B&&console.warn(`[PLUGIN WARN ${(0,A.Yq)(Date.now(),"hh:mm.ss.SSS")}] `,...e)}static pluginError(...e){ve.error(Array.from(e).map(Te).join(" ")),B&&console.error(`[PLUGIN ERROR ${(0,A.Yq)(Date.now(),"hh:mm.ss.SSS")}] `,...e)}static monitorLog(...e){B&&console.log("[PLUGIN MONITOR] ",...e)}static monitorWarn(...e){B&&console.warn("[PLUGIN MONITOR] ",...e)}}function Ee(e,t,...n){return new e(t,...n)}class Me{constructor(e){this.isVisible=!0,this.useCodeSplit=!!e.codeType}}class Pe extends Me{constructor(e,t,n){super(e),this.type=t,this.data={costTimeMs:n,runTimeMs:we.getRuntime(),isVisible:this.isVisible,useCodeSplit:this.useCodeSplit},delete this.isVisible,delete this.useCodeSplit}}const Re=[Math.pow(216,3),Math.pow(216,2),216,1];const Ae=wx.getFileSystemManager();class Le{static readCompressedFile(e){return new Promise(((t,n)=>{Ae.readCompressedFile({filePath:e,compressionAlgorithm:"br",success:e=>t(e.data),fail:n})}))}static readCompressedFileSyncCatch(e){return new Promise(((t,n)=>{try{t(Ae.readCompressedFileSync({filePath:e,compressionAlgorithm:"br"}))}catch(e){n(e)}}))}static readFile(e,n=void 0,s=!1){return new Promise(((s,i)=>{Ae.readFile({filePath:e,encoding:n,success:e=>{if(t.isIOS&&!t.isWK){const[t]=function(e){const t=e.byteLength;if(e.slice(-8).every(((e,t)=>11+t===e))){let n=1;const s=12,i=e.slice(-12,-8).reduce(((e,t,n)=>e+t*Re[n]),0),o=6;for(;n<=i;){const i=t-s-n*o,r=e[i],a=e[i+1]+200,c=e[i+2],l=e[i+3],u=e[i+4],h=e[i+5],d=c*Re[0]+l*Re[1]+u*Re[2]+h;e[d]=r,e[d+1]=a,n+=1}const r=(e[t-s-(n-1)*o-1]<<8)+e[t-s-(n-1)*o-2];for(let i=1;i<=r;i++)if(0!==e[t-s-(n-1)*o-2-i])return[e.buffer,!1];return[e.slice(0,t-s-(n-1)*o-r-2).buffer,!0]}if(e.slice(-8).every(((e,t)=>21+t===e))){const n=(e[t-9]<<8)+e[t-10];for(let s=1;s<=n;s++)if(0!==e[t-10-s])return[e.buffer,!1];return[e.slice(0,t-8-n-2).buffer,!0]}return[e.buffer,!1]}(new Uint8Array(e.data));e.data=t}s(e.data)},fail:i})}))}}const Ce=/[^:]\/{2,}/gi,Oe=/\.[./]+/gi,De=/[<>]+/gi;function xe(...e){return(null==e?void 0:e.length)?function(e){if(!(null==e?void 0:e.trim()))return"";return e.replace(Oe,"").replace(De,"").replace(Ce,(e=>e.replace(/\/+/g,"/")))}(e.filter((e=>{var t;return!!(null===(t=null==e?void 0:e.trim)||void 0===t?void 0:t.call(e))})).join("/")):""}function Ne(e){const t=r.STREAMING_CDN||r.DATA_CDN,n=r.streamingUrlPrefixPath||"",s=e.match(/(http|https|ftp|file):\/\//);let i=e;return s||(i=xe(t,n,e)),i}const _e={send(e){console.log("report21492 send:",e)},setBase(e){console.log("report21492 setBase:",e)}},Ge={send(e){console.log("report21493 send:",e)},setBase(e){console.log("report21493 setBase:",e)}};var Fe;!function(e){e.False="0",e.True="1"}(Fe||(Fe={}));class ke{constructor(e){Object.keys(e).forEach((t=>{this[t]=e[t]}))}}const We=class extends Z{constructor(){super(...arguments),this.subWasmModuleName="wasmcode1",this.retryCount=1,this.retryDuration=1500,this.pendingDuration=6e4,this.unityModuleInited=!1,this.invokeLoadWasmCode=e=>new Promise(((e,t)=>{const{unityManager:n}=this;pe.triggerEvent(ue.WasmLoading,Ee(Me,n)),we.timeStart("下载wasm代码包"),be.eventLog("开始下载wasm代码包"),pe.triggerEvent(ue.WasmLoaded,Ee(Me,n)),we.printTime("下载wasm代码包");const s=we.timeEnd("下载wasm代码包");n.triggerLaunchProgress(X.LOAD_SUBPACKAGE,s),n.loadingCount-=1,setTimeout((()=>{e()}),0)})).then((()=>{const{unityManager:e}=this;be.eventLog("start invoke UnityModule"),r.useDotnetRuntime?(be.eventLog("invoke UnityModule for dotnet"),e.gameInstance.Module.preInit=[()=>{be.eventLog("UnityModule preInit"),this.unityModuleInited=!0,pe.triggerEvent(ue.ModulePrepared),$e.processRawData()}],r.UnityModule(e.gameInstance.Module)):(be.eventLog("invoke UnityModule for il2cpp"),r.UnityModule(e.gameInstance.Module),this.unityModuleInited=!0,pe.triggerEvent(ue.ModulePrepared),$e.processRawData())}))}init(e){this.unityManager=e,this.initConfig()}loadWasmCode(){return(0,A.Mx)(this.invokeLoadWasmCode,this.retryCount,this.retryDuration)}parallelFetchSubWasm(){return be.eventLog("loadSubPackage1"),new Promise(((e,t)=>{we.timeStart("subWasmLoad"),r._subWasmLoading=!0,r._subWasmLoading=!1,r._subWasmLoaded=!0,console.log("[PLUGIN TIME LOG]下载小游戏分包1: ",we.timeEnd("subWasmLoad",!1),"ms"),be.eventLog("下载代码分包1完毕"),e()}))}initConfig(){const{CODE_FILE_MD5:e,GAME_NAME:t}=r;this.moduleName="wasmcode",this.md5=e,this.filename=`${this.md5}.${t}.wasm.code.unityweb.wasm.br`,this.wasmPath=`${this.moduleName}/${this.filename}`,this.unityManager.gameInstance.Module.wasmPath=this.wasmPath,ee.setData({useCodeSplit:this.unityManager.codeType===J.codeSplit})}}.getInstance();var Ue=function(e,t,n,s){return new(n||(n=Promise))((function(i,o){function r(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((s=s.apply(e,t||[])).next())}))};const $e=class extends Z{constructor(){super(...arguments),this.loadDataPackageFromSubpackage=!1,this.compressDataPackage=!1,this.packageName="data-package",this.retryCount=1,this.retryDuration=1500,this.pendingDuration=6e4,this.dataPackageLoaded=!1,this.preloadDataProcessed=!1,this.releaseAblePaths=[],this.processRawData=()=>{var e;const{unityManager:t}=this;if(this.preloadDataProcessed||!this.dataPackageLoaded||!We.unityModuleInited)return;const n=t.gameInstance.Module.rawData,s=new Uint8Array(n),i=new DataView(n);let o=0,a="";if(n&&this.checkPackageSize(n.byteLength)||(a=se.Mismatch),r.customProcessRawData&&"function"==typeof r.customProcessRawData)r.customProcessRawData(t.gameInstance.Module);else{const t=["UnityWebData1.0\0","TuanjieWebData1.0\0"];let c="",l="";for(const e of t)if(l=String.fromCharCode.apply(null,s.subarray(o,o+e.length)),l===e){c=l;break}if(be.pluginLog("prefix",l),c||a||(a="unknown data format"),a.length)throw this.handleDataError({errMsg:a,byteLength:null==n?void 0:n.byteLength,defaultSize:this.defaultSize,prefix:l}),a;o+=c.length;const u=i.getUint32(o,!0);for(o+=4,we.timeStart("解析资源");o0;e=t,t=c.indexOf("/",e)+1)r.FS.createPath(c.substring(0,e),c.substring(e,t-1),!0,!0);(null===(e=null==c?void 0:c.includes)||void 0===e?void 0:e.call(c,"metadata.dat"))&&this.releaseAblePaths.push(c),r.FS.createDataFile(c,null,s.slice(t,t+n),!0,!0,!0)}}this.preloadDataProcessed=!0,t.gameInstance.Module.rawData=null,we.printTime("解析资源"),we.timeEnd("解析资源"),pe.triggerEvent(ue.AssetProcessed,Ee(Me,t)),t.gameInstance.Module.removeRunDependency("wasm-preloadAssets")},this.releaseDataPackage=()=>{this.releaseAblePaths.forEach((e=>{var t,n;try{null===(n=null==r?void 0:(t=r.FS).unlink)||void 0===n||n.call(t,e)}catch(e){be.pluginError(`删除首资源包meta段错误: ${e.message}`)}}))}}init(e,t){this.unityManager=e,this.initConfig(t)}loadDataPackage(){return Ue(this,void 0,void 0,(function*(){const{unityManager:e,downloadFilename:t}=this;try{pe.triggerEvent(ue.AssetLoading,Ee(Me,e)),this.loadDataPackageFromSubpackage?be.eventLog("通过小游戏分包加载资源",t,", 是否压缩=",this.compressDataPackage):be.eventLog("通过CDN加载资源",t);const n=`${this.packageName}/${t}`;return be.eventLog("从缓存加载首包资源"),be.pluginLog("加载路径: ",n),ee.setData({loadFromCache:!0}),e.loadingCount-=1,this.compressDataPackage?yield this.decompressPackage(n):yield this.readDataPackage(n),this.dataPackageLoaded=!0,ee.setData({assetContentLength:e.gameInstance.Module.rawData.byteLength}),pe.triggerEvent(ue.AssetLoaded,Ee(Me,e)),this.processRawData(),Promise.resolve()}catch(e){return be.pluginError("加载资源异常 ",e.errMsg||e.message,e),Promise.reject(e)}}))}readDataPackage(e){return Ue(this,void 0,void 0,(function*(){const{unityManager:t}=this;if(e){we.timeStart("读取资源文件");try{t.gameInstance.Module.rawData=yield Le.readFile(e,void 0,this.loadDataPackageFromSubpackage),we.printTime("读取资源文件"),this.printBufferContent(t.gameInstance.Module.rawData),t.triggerLaunchProgress(X.READ_ASSETS,we.timeEnd("读取资源文件",!1)),be.eventLog(`data content size=${t.gameInstance.Module.rawData.byteLength}`),_e.send(new ke({ReportType:X.READ_ASSETS,CostTimeMs:we.timeEnd("读取资源文件"),RunTimeMs:we.getRuntime(),ExternInfo:JSON.stringify({fileSize:t.gameInstance.Module.rawData.byteLength,defaultSize:this.defaultSize,optimalSize:this.optimalSize,compressDataPackage:this.compressDataPackage})}))}catch(e){let t=e;"number"==typeof e||"string"==typeof e||(t=e.errMsg||e.message),this.handleDataError({errMsg:t})}return Promise.resolve()}return Promise.reject("need asset path")}))}decompressPackage(e){return Ue(this,void 0,void 0,(function*(){const{unityManager:t}=this;we.timeStart("解压资源包耗时");const[n,s]=yield(0,A.NW)(Le.readCompressedFileSyncCatch(e));if(we.printTime("解压资源包耗时"),n||!(null==s?void 0:s.byteLength)){const e=(null==n?void 0:n.errMsg)||"empty content";return Ge.send({ReportType:X.UNZIP_ASSETS,ErrorMsg:e,RunTimeMs:we.getRuntime()}),be.pluginError(`解压资源失败, 加载方式: ${this.loadDataPackageFromSubpackage?"分包":"CDN"}, errMsg: `,e),Promise.reject(n||e)}return be.eventLog(`data decompressed size=${s.byteLength}`),t.triggerLaunchProgress(X.UNZIP_ASSETS,we.timeEnd("解压资源包耗时",!1)),_e.send(new ke({ReportType:X.UNZIP_ASSETS,CostTimeMs:we.timeEnd("解压资源包耗时"),RunTimeMs:we.getRuntime(),ExternInfo:JSON.stringify({fileSize:s.byteLength,defaultSize:this.defaultSize,optimalSize:this.optimalSize,compressDataPackage:this.compressDataPackage})})),t.gameInstance.Module.rawData=s,this.printBufferContent(s),Promise.resolve(s)}))}checkPackageSize(e){const t=!Number.isNaN(this.defaultSize)&&e===this.defaultSize,n=!Number.isNaN(this.optimalSize)&&e===this.optimalSize;return be.eventLog(`[datapackage] fileSize=${e}, defaultSize=${this.defaultSize}, optimalSize=${this.optimalSize}`),t||n}initConfig(e){const{loadDataPackageFromSubpackage:t,compressDataPackage:n}=e||{};this.loadDataPackageFromSubpackage=!!t,this.compressDataPackage=!!n;const{DATA_FILE_MD5:s,GAME_NAME:i,DATA_FILE_SIZE:o,OPT_DATA_FILE_SIZE:a}=r;this.md5=s,this.cacheFilename=`${this.md5}.${i}.data.unityweb.bin`;const c=r.dataFileSubPrefix||"";this.compressDataPackage?this.downloadFilename=`${this.cacheFilename}.br`:this.downloadFilename=`${this.cacheFilename}.txt`,this.unityManager.gameInstance.Module.preLoaDataPath=this.downloadFilename,this.cachePath=xe(c,this.cacheFilename),this.downloadPath=xe(c,this.downloadFilename),this.defaultSize=Number(o),this.optimalSize=Number(a)}handleDataError({errMsg:e,byteLength:t,defaultSize:n,optimalSize:s,prefix:i}){var o;null===(o=null==r?void 0:r.onCrash)||void 0===o||o.call(r),Ge.send(new ke({ReportType:X.READ_ASSETS,ErrorMsg:e,ExternInfo:JSON.stringify({byteLength:t,defaultSize:n,optimalSize:s,prefix:i,compressDataPackage:this.compressDataPackage})}))}printBufferContent(e){e&&be.eventLog("[datapackage] content=",new Uint8Array(e,0,64).toString())}}.getInstance();let je=0;function Ve(){return je}const qe=class extends Z{constructor(){super(...arguments),this.unityFsInited=!1,this.runDependencies=0,this.denpendencyIds=[],this.onAbort=e=>{var t;const{Module:n}=this.gameInstance,s=`abort(${e}) at ${(null===(t=null==e?void 0:e.stack)||void 0===t?void 0:t.toString)?e.stack.toString():n.stackTrace()}`;Ge.send(new ke({ReportType:Ve()||Q.ON_ABORT,ErrorMsg:`${s}`.slice(0,1024),RunTimeMs:we.getRuntime(),ExternInfo:JSON.stringify({isAbort:!0})})),ve.error(s)},this.wasmInstantiated=()=>{var e,t;const{unityManager:n}=this;pe.triggerEvent(ue.WasmInstantiated,Ee(Me,n)),we.printTime("wasm编译耗时"),n.triggerLaunchProgress(X.COMPILE_WASM,we.timeEnd("wasm编译耗时",!1)),_e.send(new ke({ReportType:X.COMPILE_WASM,CostTimeMs:we.timeEnd("wasm编译耗时"),RunTimeMs:we.getRuntime()}));const s=ot.getInstance();s&&s.wasmInited&&"function"==typeof s.wasmInited&&s.wasmInited(),n.codeType===J.codeSplit&&H&&(this.gameInstance.Module.addRunDependency("subWasmInstantiated"),null===(t=null===(e=null==r?void 0:r.compileSubWasm)||void 0===e?void 0:e.call(r))||void 0===t||t.then((()=>{this.gameInstance.Module.removeRunDependency("subWasmInstantiated")})))},this.calledMainCb=()=>{const{unityManager:e}=this;e.mainCalled=!0,pe.triggerEvent(ue.CalledMain,Ee(Me,e)),we.printTime("callMain耗时"),we.printRuntime("游戏启动耗时"),we.timeStart("游戏主场景耗时");const n=we.timeEnd("callMain耗时"),s=we.getRuntime();e.triggerLaunchProgress(X.PREPARE_GAME,n),ee.setData({callmainCost:n,launchTime:s}),_e.send(new ke({ReportType:X.PREPARE_GAME,CostTimeMs:n,RunTimeMs:s})),r.Browser&&(be.pluginLog("是默认启动页,callMain完成开始游戏主循环"),r.Browser.mainLoop.resume()),$e.releaseDataPackage(),t.isWK||setTimeout((()=>{var e;null===(e=null==r?void 0:r.compileSubWasm)||void 0===e||e.call(r)}),3e4),j||setTimeout((()=>{e.gameStarted||be.pluginError("[开发阶段提示 不影响线上版本]请使用自定义上报能力 WX.ReportGameStart, 便于分析数据做启动优化, 文档: \nhttps://github.com/wechat-miniprogram/minigame-unity-webgl-transform/blob/main/Design/ReportStartupStat.md")}),6e4)},this.unityFileSystemInit=()=>{const{Module:e}=this.gameInstance;e.indexedDB||be.pluginWarn("IndexedDB is not available. Data will not persist in cache and PlayerPrefs will not be saved."),r.FS.mkdir("/idbfs"),r.FS.mount(r.IDBFS,{},"/idbfs"),this.unityFsInited=!0,e.rawData&&e.processRawData()},this.printErr=e=>{const{unityManager:t}=this,n="string"==typeof e?e:e.message;!t.gameStarted&&we.getRuntime()<6e4&&(Ie(e)||Ge.send(new ke({ReportType:Ve(),ErrorMsg:`${n}`.slice(0,1024),RunTimeMs:we.getRuntime(),ExternInfo:JSON.stringify({mainCalled:t.mainCalled})}))),(null==t?void 0:t.onLogError)&&t.onLogError(n),console.error(e)},this.monitorRunDependencies=(e,t)=>{t&&(ee!==t)):this.denpendencyIds.push(t)),this.runDependencies=e,0===this.runDependencies&&be.eventLog("no dependencies, invoke run")}}init(e){this.unityManager=e,this.initInstance(),this.checkDependenciesRemoved(),e.printErr=this.printErr.bind(this)}checkDependenciesRemoved(){setTimeout((()=>{0!==this.runDependencies&&(be.pluginError("still waiting runDependencies, ids=",this.denpendencyIds),Ge.send(new ke({ReportType:Q.WaitingRemoveDependencies,ExternInfo:JSON.stringify({runDependencies:this.runDependencies,denpendencyIds:this.denpendencyIds})})))}),3e4)}initInstance(){this.gameInstance={gameInstance:this.gameInstance,onProgress:void 0,compatibilityCheck:void 0,Module:{IsWxGame:!0,preLoadDataPath:$e.downloadFilename,wasmPath:We.wasmPath,graphicsAPI:["WebGL 2.0","WebGL 1.0"],instantiateWasm:r.instantiateWasm,onAbort:this.onAbort.bind(this),monitorRunDependencies:this.monitorRunDependencies.bind(this),wasmInstantiated:this.wasmInstantiated.bind(this),onRuntimeInitialized(){},calledMainCb:this.calledMainCb.bind(this),unityFileSystemInit:this.unityFileSystemInit.bind(this),tuanjieFileSystemInit:this.unityFileSystemInit.bind(this),processRawData:$e.processRawData,preRun:[],postRun:[],print(e){console.log(e)},printErr:this.printErr.bind(this),Jobs:{},canvas:a,buildDownloadProgress:{},resolveBuildUrl:Ne,streamingAssetsUrl:()=>Ne("StreamingAssets"),pthreadMainPrefixURL:"Build/",webglContextAttributes:{premultipliedAlpha:1,preserveDrawingBuffer:1}},SetFullscreen:(...e)=>{if(this.gameInstance.Module.SetFullscreen)return this.gameInstance.Module.SetFullscreen.apply(this.gameInstance.Module,...e)},SendMessage:(...e)=>{if(this.gameInstance.Module.SendMessage)return this.gameInstance.Module.SendMessage.apply(this.gameInstance.Module,...e)},popup:(e,t)=>r.UnityLoader.Error.popup(this.gameInstance,e,t)},this.unityManager.gameInstance=this.gameInstance,r.Module=this.gameInstance.Module}}.getInstance();class Be{constructor(e){const t=e.getAllResponseHeaders(),n=new Map;t.trim().split(/[\r\n]+/).forEach((e=>{const t=e.split(": "),s=t.shift(),i=t.join(": ");n.set(s,i)})),this.headers=n,this.url=e.paramsCache.url,this.ok=!!(e.status>=200&&e.status<300),this.status=e.status,this.statusText=e.statusText,this.parsedBody=new Uint8Array(e.response),this.originXHR=e}}var Ke,He=n(347).A,ze=function(e,t,n,s){return new(n||(n=Promise))((function(i,o){function r(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((s=s.apply(e,t||[])).next())}))};!function(e){e[e.Fail=0]="Fail",e[e.Ok=1]="Ok"}(Ke||(Ke={}));class Xe{constructor(e){this.status=e.status,this.errMsg=e.errMsg,this.cachePath=e.xhrObj.cachePath,this.response=e.xhrObj.response,this.cacheable=e.xhrObj.cacheable,this.isReadFromCache=e.xhrObj.isReadFromCache}}class Je{constructor(){this.status=void 0,this.statusText=void 0,this.reqId="",this.cacheable=!1,this.isReadFromCache=!1,this.isFetchApi=!1,this.ignoreCallback=!1,this.skipOldCacheClean=!1,this.signal={aborted:!1},this.openAndSend=(e,t)=>(this.isFetchApi=!0,this.open(t.method,e,!0),this.responseType="arraybuffer",Object.keys(t.headers).forEach((e=>{this.setRequestHeader(e,t.headers[e])})),this.timeout=t.timeout,this.onprogress=t.onProgress,new Promise(((e,n)=>{this.onFetchResolve=()=>{e(new Be(this))},this.onFetchReject=e=>{const t=new Be(this);t.message=(null==e?void 0:e.errMsg)||(null==e?void 0:e.message)||"",n(t)},this.send(t.body)}))),this.send=(...e)=>ze(this,void 0,void 0,(function*(){console.warn("UnityWebRequest not supported")})),this.open=(e,t,n,...s)=>{this.paramsCache={method:e,url:t,async:n},this.originXhr.open(e,t,n,...s),this.onload=()=>{},this.onerror=()=>{},this.ontimeout=()=>{},this.onabort=()=>{},He.env.isPC&&this.setRequestHeader("Cache-Control","no-cache")},this.bindEvent=()=>{const e=["readyState","response","responseText","responseURL","responseXML","status","statusText"];["readyState","response","responseText","responseType","responseURL","responseXML","status","statusText","timeout","upload","withCredentials","onloadstart","onprogress","onabort","onerror","onload","ontimeout","onloadend","onreadystatechange"].forEach((t=>{Object.defineProperty(this,t,{get:()=>e.includes(t)&&this[`_${t}`]||this.originXhr[t],set:n=>{"onload"===t?this.originXhr[t]=e=>{this.isFetchApi?this.triggerEvent("FetchResolve"):n(e),this.triggerEvent("complete",new Xe({xhrObj:this,status:Ke.Ok}))}:"onerror"===t||"ontimeout"===t||"onabort"===t?this.originXhr[t]=e=>{this.isFetchApi?this.triggerEvent("FetchReject",e):n(e),this.triggerEvent("complete",new Xe({xhrObj:this,status:Ke.Fail,errMsg:`${t}_${this.statusText}`}))}:e.includes(t)?this[`_${t}`]=n:this.originXhr[t]=n}})})),["abort","getAllResponseHeaders","getResponseHeader","overrideMimeType","addEventListener","setRequestHeader"].forEach((e=>{Object.defineProperty(this,e,{value:(...t)=>{if("abort"===e&&(this.signal.aborted=!0),"setRequestHeader"===e){if("wechatminigame-preload"===t[0])return void(this.ignoreCallback="1"===t[1]);if("wechatminigame-skipclean"===t[0])return void(this.skipOldCacheClean="0"===t[1])}return this.originXhr[e](...t)}})}))},this.createResponse=({data:e,statusCode:t=200})=>{void 0!==t&&(this.status=t),e&&(this.response=e)},this.triggerEvent=(e,...t)=>{const n=this[`on${e}`];n&&n.apply(this,t||[])},this.originXhr=new r.XMLHttpRequest,this.paramsCache={},this.bindEvent(),this.reqId=function(e){const t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];let n="";for(let s=0;s{const n={sceneId:e,costTime:t,dimension:{useCodeSplit:this.codeType?Fe.True:Fe.False,needDownloadDataPackage:Fe.True}};this.baseReportScene(n)},this.baseReportScene=e=>{z&&wx.reportScene(e)},this.showAbort=()=>{console.warn("An error occurred")},ot.instance)return this;var t;t=e.language,et=t,pe.init(this),this.init(e),ne.init(this)}init(e){const{videoManager:n,finalPageVideoUrl:s,pageManager:i,loadingPageConfig:o,useCoverView:a,hideAfterCallmain:c,preloadDataList:l,loadDataPackageFromSubpackage:u=!1,compressDataPackage:h=!1,contextConfig:d={}}=e,p=it(e,["videoManager","finalPageVideoUrl","pageManager","loadingPageConfig","useCoverView","hideAfterCallmain","preloadDataList","loadDataPackageFromSubpackage","compressDataPackage","contextConfig"]);this.gameInstance=null,this.mainCalled=!1,this.gameStarted=!1,this.useCoverView=K,this.hideAfterCallmain=!!c,this.contextType=d.contextType||1,this.codeType=r.useWasmCodeSplit?J.codeSplit:J.normal,we.timeStart("getContext");if(r.globalGL=canvas.getContext(Y[this.contextType],{alpha:!0,stencil:!0,antialias:!1,powerPreference:"high-performance"}),we.storeTime("getContext"),!r.globalGL){const e=`${nt("不支持")}${Y[this.contextType]}, ${nt("请升级")}${t.isIOS?nt("系统"):nt("微信")}`;be.pluginError(e),wx.showModal({title:nt("提示"),content:e,showCancel:!1,success(){}}),setTimeout((()=>{throw new Error(e)}),0)}this.initGameGlobal(p),qe.init(this),$e.init(this,{loadDataPackageFromSubpackage:u,compressDataPackage:h}),We.init(this),ne.init(this),ot.instance=this}initGameGlobal(e={}){Object.entries(e).forEach((([e,t])=>{if(["STREAMING_CDN","DATA_CDN"].includes(e)&&t.includes("http")){const n=t.endsWith("/")?t:`${t}/`;r[e]=n}else r[e]=t})),r.UnityLoader={SystemInfo:{width:G,height:_,gpu:(()=>{const e=canvas.getContext(Y[this.contextType]);if(e){const t=e.getExtension("WEBGL_debug_renderer_info");if(t)return e.getParameter(t.UNMASKED_RENDERER_WEBGL)}return"unknown"})(),browser:"wx",browserVersion:"0.0",language:r.navigator.userLanguage||r.navigator.language,hasWebGL:this.contextType},UnityCache:{XMLHttpRequest:Ye}}}triggerLaunchProgress(e,t){const n=Ee(Pe,this,e,t);this.reportPluginLaunchScene(e,t),ee.addLaunchData(n),pe.triggerEvent(ue.LaunchProgress,n)}startGame(){return st(this,void 0,void 0,(function*(){if(this.mainCalled)return;pe.triggerEvent(ue.LoadingPageReady,Ee(Me,this)),this.startCheckIs32Wechat();const e=[We.loadWasmCode(),$e.loadDataPackage()];return pe.triggerEvent(ue.ParallelLoading,Ee(Me,this)),Promise.all(e).then((()=>{pe.triggerEvent(ue.ParallelLoaded,Ee(Me,this)),this.start()}))}))}start(){return st(this,void 0,void 0,(function*(){}))}startCheckIs32Wechat(){C.abi&&!C.abi.includes("64")&&setTimeout((()=>{this.mainCalled||(be.pluginError("当前是32位微信,请升级最新版本"),wx.showModal({title:nt("提示"),content:nt("当前微信为32位版本\n请升级最新版本"),showCancel:!1,confirmText:nt("确认升级"),success(){wx.updateWeChatApp()}}))}),3e4)}}const rt=ot})(),module.exports=s})(); \ No newline at end of file diff --git a/Runtime/playable-default/unity-playable-plugin/index.js.meta b/Runtime/playable-default/unity-playable-plugin/index.js.meta new file mode 100644 index 000000000..ce23bdc82 --- /dev/null +++ b/Runtime/playable-default/unity-playable-plugin/index.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 28f5abc76c1cce08e739315e9cf0f0c0 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk.meta b/Runtime/playable-default/unity-sdk.meta new file mode 100644 index 000000000..78a0f084a --- /dev/null +++ b/Runtime/playable-default/unity-sdk.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 355c2d58622d623c29791d8bc23be99e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/audio.meta b/Runtime/playable-default/unity-sdk/audio.meta new file mode 100644 index 000000000..28279c85b --- /dev/null +++ b/Runtime/playable-default/unity-sdk/audio.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 637595a7086f731a50c0b36daca86d57 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/audio/common.js b/Runtime/playable-default/unity-sdk/audio/common.js new file mode 100644 index 000000000..07447a793 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/audio/common.js @@ -0,0 +1,71 @@ +import { WEBAudio, audios, unityAudioVolume, innerAudioVolume } from './store'; +import { resumeWebAudio, mkCacheDir } from './utils'; + +mkCacheDir(); +export default { + WXGetAudioCount() { + return { + innerAudio: Object.keys(audios).length, + webAudio: WEBAudio.bufferSourceNodeLength, + buffer: WEBAudio.audioBufferLength, + }; + }, + WXSetAudioMute(value) { + if (typeof value !== 'boolean') { + return; + } + if (WEBAudio.isMute === value) { + return; + } + WEBAudio.isMute = value; + + for (const channelInstance of Object.keys(WEBAudio.audioInstances)) { + const channel = WEBAudio.audioInstances[+channelInstance]; + if (channel.source) { + channel.setVolume?.(value ? 0 : unityAudioVolume.get(channel) ?? 1); + } + } + + for (const innerAudio of Object.values(audios)) { + innerAudio.volume = value ? 0 : innerAudioVolume.get(innerAudio) ?? 1; + } + }, +}; + +const HandleInterruption = { + init() { + let INTERRUPT_LIST = {}; + wx.onHide(() => { + Object.keys(audios).forEach((key) => { + if (!audios[key].paused !== false) { + INTERRUPT_LIST[key] = true; + } + }); + }); + wx.onShow(() => { + Object.keys(audios).forEach((key) => { + if (audios[key].paused !== false && INTERRUPT_LIST[key]) { + audios[key].play(); + } + }); + INTERRUPT_LIST = {}; + }); + wx.onAudioInterruptionBegin(() => { + Object.keys(audios).forEach((key) => { + if (!audios[key].paused !== false) { + INTERRUPT_LIST[key] = true; + } + }); + }); + wx.onAudioInterruptionEnd(() => { + Object.keys(audios).forEach((key) => { + if (audios[key].paused !== false && INTERRUPT_LIST[key]) { + audios[key].play(); + } + }); + INTERRUPT_LIST = {}; + resumeWebAudio(); + }); + }, +}; +HandleInterruption.init(); diff --git a/Runtime/playable-default/unity-sdk/audio/common.js.meta b/Runtime/playable-default/unity-sdk/audio/common.js.meta new file mode 100644 index 000000000..cf13d1666 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/audio/common.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 14c59c99c9181f93a489279155724859 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/audio/const.js b/Runtime/playable-default/unity-sdk/audio/const.js new file mode 100644 index 000000000..e83356935 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/audio/const.js @@ -0,0 +1,3 @@ +export const INNER_AUDIO_UNDEFINED_MSG = 'InnerAudioContext does not exist!'; +export const IGNORE_ERROR_MSG = 'audio is playing, don\'t play again'; +export const TEMP_DIR_PATH = `${wx.env.USER_DATA_PATH}/__GAME_FILE_CACHE/audios`; diff --git a/Runtime/playable-default/unity-sdk/audio/const.js.meta b/Runtime/playable-default/unity-sdk/audio/const.js.meta new file mode 100644 index 000000000..bfc0dab12 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/audio/const.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: a668ba7c86b4c0afef675e87a649af10 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/audio/index.js b/Runtime/playable-default/unity-sdk/audio/index.js new file mode 100644 index 000000000..9e4cf5e54 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/audio/index.js @@ -0,0 +1,8 @@ +import innerAudio from './inner-audio'; +import unityAudio from './unity-audio'; +import common from './common'; +export default { + ...innerAudio, + ...unityAudio, + ...common, +}; diff --git a/Runtime/playable-default/unity-sdk/audio/index.js.meta b/Runtime/playable-default/unity-sdk/audio/index.js.meta new file mode 100644 index 000000000..755b7e334 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/audio/index.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 96e28a3b903bae246a13e94cfb90070c +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/audio/inner-audio.js b/Runtime/playable-default/unity-sdk/audio/inner-audio.js new file mode 100644 index 000000000..8c5471219 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/audio/inner-audio.js @@ -0,0 +1,382 @@ +/* eslint-disable no-param-reassign */ +import moduleHelper from '../module-helper'; +import { isSupportPlayBackRate } from '../../check-version'; +import { audios, localAudioMap, downloadingAudioMap, innerAudioVolume, WEBAudio } from './store'; +import { createInnerAudio, destroyInnerAudio, printErrMsg } from './utils'; +import { IGNORE_ERROR_MSG, INNER_AUDIO_UNDEFINED_MSG } from './const'; +const funs = { + + getFullUrl(v) { + if (!/^https?:\/\//.test(v) && !/^wxfile:\/\//.test(v)) { + const cdnPath = GameGlobal.manager.assetPath; + v = `${cdnPath.replace(/\/$/, '')}/${v.replace(/^\//, '').replace(/^Assets\//, '')}`; + } + return v; + }, + + downloadAudios(paths) { + const list = paths.split(','); + return Promise.all(list.map((v) => { + const src = funs.getFullUrl(v); + return new Promise((resolve, reject) => { + + if (!downloadingAudioMap[src]) { + downloadingAudioMap[src] = [ + { + resolve, + reject, + }, + ]; + if (funs.checkLocalFile(src)) { + funs.handleDownloadEnd(src, true); + } + else if (!GameGlobal.unityNamespace.isCacheableFile(src)) { + + wx.downloadFile({ + url: src, + success(res) { + if (res.statusCode === 200 && res.tempFilePath) { + localAudioMap[src] = res.tempFilePath; + funs.handleDownloadEnd(src, true); + } + else { + funs.handleDownloadEnd(src, false); + } + }, + fail(e) { + funs.handleDownloadEnd(src, false); + printErrMsg(e); + }, + }); + } + else { + const xmlhttp = new GameGlobal.unityNamespace.UnityLoader.UnityCache.XMLHttpRequest(); + xmlhttp.open('GET', src, true); + xmlhttp.responseType = 'arraybuffer'; + xmlhttp.onsave = () => { + localAudioMap[src] = GameGlobal.manager.getCachePath(src); + funs.handleDownloadEnd(src, true); + }; + xmlhttp.onsavefail = () => { + funs.handleDownloadEnd(src, false); + }; + xmlhttp.onerror = () => { + funs.handleDownloadEnd(src, false); + }; + xmlhttp.send(); + } + } + else { + downloadingAudioMap[src].push({ + resolve, + reject, + }); + } + }); + })); + }, + + handleDownloadEnd(src, succeeded) { + if (!downloadingAudioMap[src]) { + return; + } + while (downloadingAudioMap[src] && downloadingAudioMap[src].length > 0) { + const item = downloadingAudioMap[src].shift(); + if (!succeeded) { + item?.reject(); + } + else { + item?.resolve(''); + } + } + delete downloadingAudioMap[src]; + }, + // 是否存在本地文件 + checkLocalFile(src) { + if (localAudioMap[src]) { + return true; + } + const path = GameGlobal.manager.getCachePath(src); + if (path) { + localAudioMap[src] = path; + return true; + } + return false; + }, + // 设置路径 + setAudioSrc(audio, getSrc) { + return new Promise((resolve, reject) => { + const src = funs.getFullUrl(getSrc); + // 设置原始路径,后面用此路径作为key值 + audio.isLoading = src; + if (funs.checkLocalFile(src)) { + audio.src = localAudioMap[src]; + delete audio.isLoading; + funs.handleDownloadEnd(src, true); + resolve(localAudioMap[src]); + } + else if (audio.needDownload) { + funs + .downloadAudios(src) + .then(() => { + if (audio) { + audio.src = localAudioMap[src]; + delete audio.isLoading; + resolve(localAudioMap[src]); + } + else { + console.warn('资源已被删除:', src); + reject({ + errCode: -1, + errMsg: '资源已被删除', + }); + } + }) + .catch(() => { + console.warn('资源下载失败:', src); + if (audio) { + audio.src = src; + delete audio.isLoading; + } + reject({ + errCode: -1, + errMsg: '资源下载失败', + }); + }); + } + else { + // 不推荐这样处理,建议优先下载再使用,除非是需要立即播放的长音频文件或一次性播放音频 + // console.warn('建议优先下载再使用:', src); + audio.src = src; + delete audio.isLoading; + resolve(src); + } + }); + }, +}; +function checkHasAudio(id) { + if (audios[id]) { + return true; + } + console.error(INNER_AUDIO_UNDEFINED_MSG, id); + return false; +} +export default { + // 创建audio对象 + WXCreateInnerAudioContext(src, loop, startTime, autoplay, volume, playbackRate, needDownload) { + const { audio: getAudio, id } = createInnerAudio(); + getAudio.needDownload = needDownload; + if (src) { + // 设置原始src + funs.setAudioSrc(getAudio, src).catch((e) => { + moduleHelper.send('OnAudioCallback', JSON.stringify({ + callbackId: id, + errMsg: 'onError', + result: JSON.stringify(e), + })); + }); + } + if (loop) { + getAudio.loop = true; + } + if (autoplay) { + getAudio.autoplay = true; + } + if (typeof startTime === 'undefined') { + startTime = 0; + } + if (startTime > 0) { + getAudio.startTime = +startTime.toFixed(2); + } + + let volumeValue; + if (typeof volume === 'undefined') { + volumeValue = 1; + } + else { + volumeValue = +volume.toFixed(2); + } + innerAudioVolume.set(getAudio, volumeValue); + if (WEBAudio.isMute) { + volumeValue = 0; + } + if (volumeValue !== 1) { + getAudio.volume = volumeValue; + } + + if (!isSupportPlayBackRate) { + playbackRate = 1; + } + if (typeof playbackRate !== 'undefined' && playbackRate !== 1) { + getAudio.playbackRate = +playbackRate.toFixed(2); + } + return id; + }, + + WXInnerAudioContextSetBool(id, k, v) { + if (!checkHasAudio(id)) { + return; + } + audios[id][k] = Boolean(+v); + }, + + WXInnerAudioContextSetString(id, k, v) { + if (!checkHasAudio(id)) { + return; + } + + if (k === 'src') { + funs.setAudioSrc(audios[id], v); + } + else if (k === 'needDownload') { + audios[id].needDownload = !!v; + } + else { + audios[id][k] = v; + } + }, + + WXInnerAudioContextSetFloat(id, k, v) { + if (!checkHasAudio(id)) { + return; + } + let value = +v.toFixed(2); + if (k === 'volume') { + innerAudioVolume.set(audios[id], value); + if (WEBAudio.isMute) { + value = 0; + } + } + audios[id][k] = value; + }, + + WXInnerAudioContextGetFloat(id, k) { + if (!checkHasAudio(id)) { + return 0; + } + return audios[id][k]; + }, + + WXInnerAudioContextGetBool(id, k) { + if (!checkHasAudio(id)) { + return false; + } + return audios[id][k]; + }, + WXInnerAudioContextPlay(id) { + if (!checkHasAudio(id)) { + return; + } + + const url = audios[id].isLoading; + if (url) { + if (downloadingAudioMap[url]) { + downloadingAudioMap[url].push({ + resolve: () => { + if (typeof audios[id] !== 'undefined') { + audios[id].play(); + } + }, + reject: () => { }, + }); + } + else { + audios[id].src = url; + audios[id].play(); + } + } + else { + audios[id].play(); + } + }, + WXInnerAudioContextPause(id) { + if (!checkHasAudio(id)) { + return; + } + audios[id].pause(); + }, + WXInnerAudioContextStop(id) { + if (!checkHasAudio(id)) { + return; + } + audios[id].stop(); + }, + WXInnerAudioContextDestroy(id) { + if (!checkHasAudio(id)) { + return; + } + destroyInnerAudio(id, false); + }, + WXInnerAudioContextSeek(id, position) { + if (!checkHasAudio(id)) { + return; + } + audios[id].seek(+position.toFixed(3)); + }, + + WXInnerAudioContextAddListener(id, key) { + if (!checkHasAudio(id)) { + return; + } + if (key === 'onCanplay') { + audios[id][key](() => { + + // @ts-ignore + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { duration, buffered, referrerPolicy, volume } = audios[id]; + setTimeout(() => { + moduleHelper.send('OnAudioCallback', JSON.stringify({ + callbackId: id, + errMsg: key, + })); + }, 0); + }); + } + else if (key === 'onError') { + audios[id][key]((e) => { + if (key === 'onError') { + console.error(e); + + if (e.errMsg && e.errMsg.indexOf(IGNORE_ERROR_MSG) > -1) { + return; + } + } + moduleHelper.send('OnAudioCallback', JSON.stringify({ + callbackId: id, + errMsg: key, + result: JSON.stringify(e), + })); + }); + } + else { + audios[id][key](() => { + moduleHelper.send('OnAudioCallback', JSON.stringify({ + callbackId: id, + errMsg: key, + })); + }); + } + }, + WXInnerAudioContextRemoveListener(id, key) { + if (!checkHasAudio(id)) { + return; + } + audios[id][key](); + }, + WXPreDownloadAudios(paths, id) { + funs + .downloadAudios(paths) + .then(() => { + moduleHelper.send('WXPreDownloadAudiosCallback', JSON.stringify({ + callbackId: id.toString(), + errMsg: '0', + })); + }) + .catch(() => { + moduleHelper.send('WXPreDownloadAudiosCallback', JSON.stringify({ + callbackId: id.toString(), + errMsg: '1', + })); + }); + }, +}; diff --git a/Runtime/playable-default/unity-sdk/audio/inner-audio.js.meta b/Runtime/playable-default/unity-sdk/audio/inner-audio.js.meta new file mode 100644 index 000000000..a9bc00582 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/audio/inner-audio.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 9e2837ac842a293fb14f815cbb35acda +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/audio/store.js b/Runtime/playable-default/unity-sdk/audio/store.js new file mode 100644 index 000000000..f33b3e60a --- /dev/null +++ b/Runtime/playable-default/unity-sdk/audio/store.js @@ -0,0 +1,33 @@ + +export const WEBAudio = { + audioInstanceIdCounter: 0, + audioInstances: {}, + audioContext: null, + audioWebEnabled: 0, + audioCache: [], + lOrientation: { + x: 0, + y: 0, + z: 0, + xUp: 0, + yUp: 0, + zUp: 0, + }, + lPosition: { x: 0, y: 0, z: 0 }, + audio3DSupport: 0, + audioWebSupport: 0, + bufferSourceNodeLength: 0, + audioBufferLength: 0, + isMute: false, + FAKEMOD_SAMPLERATE: 44100, +}; + +export const audios = {}; + +export const localAudioMap = {}; + +export const downloadingAudioMap = {}; + +export const unityAudioVolume = new WeakMap(); + +export const innerAudioVolume = new WeakMap(); diff --git a/Runtime/playable-default/unity-sdk/audio/store.js.meta b/Runtime/playable-default/unity-sdk/audio/store.js.meta new file mode 100644 index 000000000..52cf66fe1 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/audio/store.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: ce1ee1f24f20b16bf6969a58f9679ba1 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/audio/unity-audio.js b/Runtime/playable-default/unity-sdk/audio/unity-audio.js new file mode 100644 index 000000000..bf675abc0 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/audio/unity-audio.js @@ -0,0 +1,1235 @@ +/* eslint-disable no-param-reassign */ +/* eslint-disable eqeqeq */ +/* eslint-disable no-plusplus */ +import { isAndroid, webAudioNeedResume, isSupportBufferURL, isSupportPlayBackRate, isIOS175, } from '../../check-version'; +import { WEBAudio, unityAudioVolume } from './store'; +import { TEMP_DIR_PATH } from './const'; +import { createInnerAudio, destroyInnerAudio, printErrMsg, resumeWebAudio } from './utils'; +import { debugLog } from '../utils'; + +const defaultSoundLength = 441000; + +const needGetLength = false; +function jsAudioCreateUncompressedSoundClip(buffer, error, length) { + const soundClip = { + buffer, + error, + release() { + this.buffer = null; + WEBAudio.audioBufferLength -= length; + }, + resetGain() { }, + getLength() { + if (!this.buffer) { + + return 0; + } + const sampleRateRatio = 44100 / this.buffer.sampleRate; + return this.buffer.length * sampleRateRatio; + }, + getData(ptr, length) { + if (!this.buffer) { + console.log('Trying to get data of sound which is not loaded.'); + return 0; + } + const startOutputBuffer = ptr >> 2; + const output = GameGlobal.unityNamespace.Module.HEAPF32.subarray(startOutputBuffer, startOutputBuffer + (length >> 2)); + const numMaxSamples = Math.floor((length >> 2) / this.buffer.numberOfChannels); + const numReadSamples = Math.min(this.buffer.length, numMaxSamples); + for (let i = 0; i < this.buffer.numberOfChannels; i++) { + const channelData = this.buffer.getChannelData(i).subarray(0, numReadSamples); + output.set(channelData, i * numReadSamples); + } + return numReadSamples * this.buffer.numberOfChannels * 4; + }, + getNumberOfChannels() { + if (!this.buffer) { + console.log('Trying to get metadata of sound which is not loaded.'); + return 0; + } + return this.buffer.numberOfChannels; + }, + getFrequency() { + if (!this.buffer) { + console.log('Trying to get metadata of sound which is not loaded.'); + return 0; + } + return this.buffer.sampleRate; + }, + }; + return soundClip; +} +function jsAudioCreateUncompressedSoundClipFromCompressedAudio(audioData, ptr, length) { + const soundClip = jsAudioCreateUncompressedSoundClip(null, false, length); + WEBAudio.audioContext?.decodeAudioData(audioData, (buffer) => { + soundClip.buffer = buffer; + WEBAudio.audioBufferLength += length; + }, (error) => { + soundClip.error = true; + console.log(`Decode error: ${error}`); + }); + return soundClip; +} +function jsAudioCreateCompressedSoundClip(audioData, ptr, length) { + const soundClip = { + error: false, + length: needGetLength ? 0 : defaultSoundLength, + url: undefined, + release() { + WEBAudio.audioBufferLength -= length; + if (isSupportBufferURL && this.url) { + wx.revokeBufferURL(this.url); + } + delete this.url; + }, + resetGain() { }, + getLength() { + return this.length || 0; + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getData(ptr, length) { + console.warn('getData() is not supported for compressed sound.'); + return 0; + }, + getNumberOfChannels() { + console.warn('getNumberOfChannels() is not supported for compressed sound.'); + return 0; + }, + getFrequency() { + console.warn('getFrequency() is not supported for compressed sound.'); + return 0; + }, + }; + if (isSupportBufferURL) { + const url = wx.createBufferURL(audioData); + soundClip.url = url; + WEBAudio.audioBufferLength += length; + } + else { + const tempFilePath = `${TEMP_DIR_PATH}/temp-audio${ptr + length}.mp3`; + if (GameGlobal.manager.getCachePath(tempFilePath)) { + soundClip.url = tempFilePath; + WEBAudio.audioBufferLength += length; + } + else { + GameGlobal.manager + .writeFile(tempFilePath, audioData) + .then(() => { + soundClip.url = tempFilePath; + WEBAudio.audioBufferLength += length; + }) + .catch((res) => { + soundClip.error = true; + printErrMsg(res); + }); + } + } + if (needGetLength && soundClip.url) { + const { audio: getAudio } = createInnerAudio(); + getAudio.src = soundClip.url; + getAudio.onCanplay(() => { + soundClip.length = getAudio.duration * 44100; + setTimeout(() => { + soundClip.length = getAudio.duration * 44100; + getAudio.destroy(); + }, 0); + }); + } + return soundClip; +} +function jsAudioCreateUncompressedSoundClipFromPCM(channels, length, sampleRate, ptr) { + if (WEBAudio.audioContext) { + const buffer = WEBAudio.audioContext.createBuffer(channels, length, sampleRate); + for (let i = 0; i < channels; i++) { + const offs = (ptr >> 2) + length * i; + const copyToChannel = buffer.copyToChannel + || function (source, channelNumber, startInChannel) { + const clipped = source.subarray(0, Math.min(source.length, buffer.length - (startInChannel | 0))); + buffer.getChannelData(channelNumber | 0).set(clipped, startInChannel | 0); + }; + copyToChannel.apply(buffer, [GameGlobal.unityNamespace.Module.HEAPF32.subarray(offs, offs + length), i, 0]); + } + return jsAudioCreateUncompressedSoundClip(buffer, false, length); + } + return jsAudioCreateUncompressedSoundClip(null, false, length); +} +export class AudioChannelInstance { + threeD = false; + source; + gain; + callback = 0; + userData = 0; + loop = false; + loopStart = 0; + loopEnd = 0; + deleyTime = 0; + deleyOffset = 0; + constructor(callback, userData) { + if (WEBAudio.audioContext) { + this.gain = WEBAudio.audioContext.createGain(); + this.gain?.connect(WEBAudio.audioContext.destination); + } + this.callback = callback; + this.userData = userData; + } + resetGain() { + if (WEBAudio.audioContext && this.gain) { + this.gain.disconnect(); + this.gain = WEBAudio.audioContext.createGain(); + this.gain?.connect(WEBAudio.audioContext.destination); + } + } + release() { + this.disconnectSource(); + if (this.gain) { + this.gain.disconnect(); + } + } + setLoop(loop) { + this.loop = loop; + if (!this.source || this.source.loop == loop) { + return; + } + this.source.loop = loop; + } + setLoopPoints(loopStart, loopEnd) { + this.loopStart = loopStart; + this.loopEnd = loopEnd; + if (!this.source) { + return; + } + if (this.source.loopStart !== loopStart) { + this.source.loopStart = loopStart; + } + if (this.source.loopEnd !== loopEnd) { + this.source.loopEnd = loopEnd; + } + } + playUrl(startTime, url, startOffset, volume, soundClip) { + debugLog('playUrl: ', url, startTime, startOffset, volume, soundClip); + try { + this.setup(url); + if (!this.source || !this.source.mediaElement) { + return; + } + if (typeof volume !== 'undefined') { + this.source.mediaElement.volume = volume; + } + if (WEBAudio.isMute) { + this.source.mediaElement.volume = 0; + } + this.source.mediaElement.onPlay(() => { + if (typeof this.source !== 'undefined') { + this.source.isPlaying = true; + if (!this.source.loop && this.source.mediaElement) { + const { duration } = this.source.mediaElement; + + if (duration > 0) { + if (this.source.stopTicker) { + clearTimeout(this.source.stopTicker); + this.source.stopTicker = undefined; + } + const time = Math.floor(duration * 1000) + 1000; + this.source.stopTicker = setTimeout(() => { + if (this.source && this.source.mediaElement) { + this.source.mediaElement.stop(); + } + }, time); + } + } + } + }); + this.source.mediaElement.onPause(() => { + debugLog('onPause'); + if (typeof this.source !== 'undefined') { + this.source.isPlaying = false; + if (this.source.stopTicker) { + clearTimeout(this.source.stopTicker); + this.source.stopTicker = undefined; + } + } + }); + this.source.mediaElement.onStop(() => { + debugLog('onStop'); + if (typeof this.source !== 'undefined') { + if (this.source.playAfterStop) { + this.source._reset(); + if (typeof this.source.mediaElement !== 'undefined') { + this.source.mediaElement.play(); + } + return; + } + this.source._reset(); + this.disconnectSource(); + } + if (this.callback) { + GameGlobal.unityNamespace.Module.dynCall_vi(this.callback, [this.userData]); + } + }); + this.source.mediaElement.onEnded(() => { + debugLog('onEnded'); + if (typeof this.source !== 'undefined') { + this.source._reset(); + this.disconnectSource(); + } + if (this.callback) { + GameGlobal.unityNamespace.Module.dynCall_vi(this.callback, [this.userData]); + } + }); + this.source.mediaElement.onError((e) => { + debugLog('onError', e); + printErrMsg(e); + const { errMsg } = e; + + if (errMsg && errMsg.indexOf('play audio fail') < 0) { + return; + } + + if (typeof this.source !== 'undefined' && this.source.mediaElement) { + this.source._reset(); + this.source.mediaElement.stop(); + } + }); + const fn = () => { + if (typeof this.source !== 'undefined' && this.source.mediaElement) { + // @ts-ignore + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { duration } = this.source.mediaElement; + setTimeout(() => { + if (soundClip && this.source && this.source.mediaElement) { + soundClip.length = Math.round(Math.max(this.source.mediaElement.duration, 0) * 44100); + } + }, 0); + } + }; + if (!this.source.canPlayFnList) { + this.source.canPlayFnList = []; + } + this.source.canPlayFnList.push(fn); + this.source.mediaElement.onCanplay(fn); + this.source.mediaElement.loop = this.loop; + this.deleyTime = startTime; + this.deleyOffset = startOffset; + this.source.start(startTime, startOffset); + this.source.playbackStartTime = startTime - startOffset / this.source.playbackRateValue; + } + catch (e) { + printErrMsg(`playUrl error. Exception: ${e}`); + } + } + playBuffer(startTime, buffer, startOffset, channel) { + try { + this.setup(); + if (!this.source) { + return; + } + this.source.buffer = buffer; + this.source.onended = () => { + this.disconnectSource(); + if (this.callback) { + GameGlobal.unityNamespace.Module.dynCall_vi(this.callback, [this.userData]); + } + }; + if (this.gain && channel) { + let volume; + if (WEBAudio.isMute) { + unityAudioVolume.set(channel, this.gain.gain.value || 1); + volume = 0; + } + else { + volume = unityAudioVolume.get(channel); + } + if (this.gain.gain.value !== volume && typeof volume === 'number') { + this.gain.gain.value = volume; + } + } + this.source.loop = this.loop; + this.source.loopStart = this.loopStart; + this.source.loopEnd = this.loopEnd; + this.source.start(startTime, startOffset); + this.source.playbackStartTime = startTime - startOffset / this.source.playbackRateValue; + } + catch (e) { + printErrMsg(`playBuffer error. Exception: ${e}`); + } + } + disconnectSource() { + if (this.source) { + if (this.source.mediaElement) { + if (this.source.stopTimeout) { + clearTimeout(this.source.stopTimeout); + delete this.source.stopTimeout; + } + destroyInnerAudio(this.source.instanceId, false); + delete this.source.mediaElement; + delete this.source; + } + else if (!this.source.isPausedMockNode) { + this.source.onended = null; + if (this.source.disconnect) { + this.source.disconnect(); + } + if (GameGlobal.isIOSHighPerformanceMode) { + this.source.buffer = null; + } + WEBAudio.bufferSourceNodeLength -= 1; + delete this.source; + } + else { + this.source.buffer = null; + } + } + } + stop(delay) { + if (!WEBAudio.audioContext) { + return; + } + if (this.source) { + if (this.source.buffer) { + try { + this.source.stop(WEBAudio.audioContext.currentTime + delay); + } + catch (e) { } + if (delay == 0) { + this.disconnectSource(); + } + } + else if (this.source.mediaElement) { + this.source.stop(delay); + } + } + } + isPaused() { + if (!this.source) { + return true; + } + if (this.source.isPausedMockNode) { + return true; + } + if (this.source.mediaElement) { + return (!this.source.isPlaying || this.source.pauseRequested) ?? true; + } + return false; + } + pause() { + const { source } = this; + if (!source) { + return; + } + if (source.mediaElement) { + source._pauseMediaElement?.(); + return; + } + if (source.isPausedMockNode) { + return; + } + const pausedSource = { + isPausedMockNode: true, + loop: this.loop, + loopStart: this.loopStart, + loopEnd: this.loopEnd, + buffer: source.buffer, + playbackRate: source.playbackRateValue, + playbackPausedAtPosition: source.estimatePlaybackPosition(), + setPitch(v) { + this.playbackRate = v; + }, + _reset() { }, + }; + this.stop(0); + this.disconnectSource(); + this.source = pausedSource; + } + resume() { + if (!WEBAudio.audioContext) { + return; + } + if (!this.source) { + return; + } + if (this.source.mediaElement) { + this.source.start(this.deleyTime, this.deleyOffset); + delete this.deleyTime; + delete this.deleyOffset; + return; + } + const pausedSource = this.source; + if (!pausedSource.isPausedMockNode) { + return; + } + delete this.source; + if (!pausedSource.buffer) { + return; + } + this.playBuffer(WEBAudio.audioContext.currentTime - Math.min(0, pausedSource.playbackPausedAtPosition), pausedSource.buffer, Math.max(0, pausedSource.playbackPausedAtPosition)); + const getSource = this.source; + if (getSource) { + getSource.loop = pausedSource.loop; + getSource.loopStart = pausedSource.loopStart; + getSource.loopEnd = pausedSource.loopEnd; + getSource.setPitch(pausedSource.playbackRate); + } + } + setVolume(volume, isDefault) { + if (!WEBAudio.audioContext) { + return; + } + if (WEBAudio.isMute) { + volume = 0; + } + + if (isDefault && volume == 1) { + return; + } + if (this.source) { + if (this.source.buffer && this.gain) { + + this.gain.gain.value = volume; + } + else if (this.source.mediaElement) { + this.source.mediaElement.volume = volume; + } + } + } + setup(url) { + if (!WEBAudio.audioContext) { + return; + } + if (this.source && !this.source.isPausedMockNode) { + if (!this.source.url) { + if (typeof url !== 'undefined') { + + this.stop(0); + } + else { + + } + } + else if (typeof url === 'undefined') { + if (typeof this.source !== 'undefined') { + + this.source._reset(); + } + this.disconnectSource(); + } + else { + + + this.source._reset(); + this.disconnectSource(); + } + } + if (!url) { + this.source = WEBAudio.audioContext.createBufferSource(); + WEBAudio.bufferSourceNodeLength += 1; + const { source } = this; + Object.defineProperty(this.source, 'playbackRateValue', { + get() { + return source?.playbackRate?.value ?? 0; + }, + set(v) { + if (!source) { + return; + } + if (typeof source.playbackRate === 'undefined') { + return; + } + source.playbackRate.value = v; + }, + }); + } + else { + const { audio: getAudio, id: instanceId } = createInnerAudio(); + getAudio.src = url; + const innerFixPlay = () => { + if (!this.source) { + return; + } + this.source.needCanPlay = true; + if (this.source.fixPlayTicker) { + + clearTimeout(this.source.fixPlayTicker); + delete this.source.fixPlayTicker; + } + + this.source.fixPlayTicker = setTimeout(() => { + if (this.source && this.source.mediaElement && this.source.needCanPlay && !this.source.isPlaying) { + this.source.mediaElement.play(); + } + }, 100); + }; + const innerPlay = (callback) => { + if (this.source && this.source.mediaElement) { + if (isSupportBufferURL && this.source.readyToPlay) { + if (this.source.stopCache) { + this.source.stopCache = false; + this.source.playAfterStop = true; + } + else if (!this.source.isPlaying) { + + if (isAndroid) { + innerFixPlay(); + } + this.source.mediaElement.play(); + callback?.(); + } + } + else { + const fn = () => { + if (!this.source) { + return; + } + this.source.needCanPlay = false; + this.source.readyToPlay = true; + if (typeof this.source.mediaElement !== 'undefined') { + // @ts-ignore + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { duration } = this.source.mediaElement; + + + this.source.canPlayFnList.forEach((fn) => { + this.source?.mediaElement?.offCanplay(fn); + }); + this.source.canPlayFnList = []; + } + if (this.source.stopCache) { + this.source.stopCache = false; + this.source.playAfterStop = true; + } + else if (!this.source.isPlaying) { + + if (isAndroid) { + innerFixPlay(); + } + if (typeof this.source.mediaElement !== 'undefined') { + this.source.mediaElement.play(); + callback?.(); + } + } + }; + if (!this.source.canPlayFnList) { + this.source.canPlayFnList = []; + } + this.source.canPlayFnList.push(fn); + this.source.mediaElement.onCanplay(fn); + innerFixPlay(); + } + } + }; + // eslint-disable-next-line @typescript-eslint/naming-convention + const _reset = () => { + if (!this.source) { + return; + } + this.source.readyToPlay = false; + this.source.isPlaying = false; + this.source.stopCache = false; + this.source.playAfterStop = false; + this.source.needCanPlay = false; + if (this.source.stopTicker) { + clearTimeout(this.source.stopTicker); + this.source.stopTicker = undefined; + } + }; + // eslint-disable-next-line @typescript-eslint/naming-convention + const _pauseMediaElement = () => { + if (typeof this.source === 'undefined') { + return; + } + if (this.source.playTimeout) { + this.source.pauseRequested = true; + } + else if (this.source.isPlaying && this.source.mediaElement) { + this.source.mediaElement.pause(); + } + }; + // eslint-disable-next-line @typescript-eslint/naming-convention + const _startPlayback = (offset) => { + if (typeof this.source === 'undefined' || !this.source.mediaElement) { + return; + } + if (this.source.playTimeout) { + this.source.mediaElement.seek(offset); + this.source.pauseRequested = false; + return; + } + innerPlay(() => { + + if (this.source && this.source.mediaElement) { + this.source.mediaElement.seek(offset); + } + }); + }; + const start = (startTime, offset) => { + if (typeof this.source === 'undefined') { + return; + } + if (typeof startTime === 'undefined' && typeof offset === 'undefined') { + innerPlay(); + return; + } + if (typeof startTime === 'undefined') { + startTime = 0; + } + if (typeof offset === 'undefined') { + offset = 0; + } + const startDelayThresholdMS = 4; + const startDelayMS = startTime * 1e3; + if (startDelayMS > startDelayThresholdMS) { + if (this.source.playTimeout) { + clearTimeout(this.source.playTimeout); + delete this.source.playTimeout; + } + this.source.playTimeout = setTimeout(() => { + if (typeof this.source !== 'undefined') { + delete this.source.playTimeout; + this.source._startPlayback?.(offset || 0); + } + }, startDelayMS); + } + else { + this.source._startPlayback?.(offset); + } + }; + const stop = (stopTime) => { + if (typeof this.source === 'undefined') { + return; + } + if (typeof stopTime === 'undefined') { + stopTime = 0; + } + const stopDelayThresholdMS = 4; + const stopDelayMS = stopTime * 1e3; + if (stopDelayMS > stopDelayThresholdMS) { + if (this.source.stopTimeout) { + clearTimeout(this.source.stopTimeout); + delete this.source.stopTimeout; + } + this.source.stopTimeout = setTimeout(() => { + if (this.source && this.source.mediaElement) { + this.source.stopCache = true; + this.source.mediaElement.stop(); + } + }, stopDelayMS); + } + else if (this.source.mediaElement) { + this.source.stopCache = true; + this.source.mediaElement.stop(); + } + }; + this.source = { + instanceId, + mediaElement: getAudio, + url, + playbackStartTime: 0, + playbackRate: 1, + pauseRequested: false, + _reset, + _pauseMediaElement, + _startPlayback, + start, + stop, + }; + // @ts-ignore + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { buffered, referrerPolicy, volume } = getAudio; + const { source } = this; + Object.defineProperty(this.source, 'loopStart', { + get() { + return 0; + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + set(v) { }, + }); + Object.defineProperty(source, 'loopEnd', { + get() { + return 0; + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + set(v) { }, + }); + Object.defineProperty(source, 'loop', { + get() { + return source?.mediaElement?.loop ?? false; + }, + set(v) { + if (!source || !source.mediaElement) { + return; + } + source.mediaElement.loop = v; + }, + }); + Object.defineProperty(source, 'playbackRateValue', { + get() { + + return source?.playbackRate ?? 1; + }, + set(v) { + if (!source || !source.mediaElement) { + return; + } + + if (!isSupportPlayBackRate) { + source.mediaElement.playbackRate = 1; + } + else { + source.playbackRate = v; + source.mediaElement.playbackRate = v; + } + }, + }); + Object.defineProperty(source, 'currentTime', { + get() { + return source?.mediaElement?.currentTime ?? 0; + }, + set(v) { + if (!source || !source.mediaElement) { + return; + } + if (typeof source.mediaElement.seek === 'function') { + source.mediaElement.seek(v); + } + else { + source.mediaElement.currentTime = v; + } + }, + }); + } + if (!this.source) { + return; + } + this.source.estimatePlaybackPosition = () => { + if (!this.source) { + return 0; + } + let t; + if (WEBAudio.audioContext) { + t = (WEBAudio.audioContext.currentTime - this.source.playbackStartTime) * this.source.playbackRateValue; + } + else { + t = -this.source.playbackStartTime * this.source.playbackRateValue; + } + if (typeof this.source.loopStart !== 'undefined' && typeof this.source.loopEnd !== 'undefined') { + if (this.source.loop && t >= this.source.loopStart) { + t = ((t - this.source.loopStart) % (this.source.loopEnd - this.source.loopStart)) + this.source.loopStart; + } + } + return t; + }; + this.source.setPitch = (newPitch) => { + if (!this.source) { + return 0; + } + const curPosition = this.source.estimatePlaybackPosition(); + if (curPosition >= 0) { + if (WEBAudio.audioContext) { + this.source.playbackStartTime = WEBAudio.audioContext.currentTime - curPosition / newPitch; + } + } + this.source.playbackRateValue = newPitch; + }; + this.setupPanning(); + } + setupPanning() { + if (typeof this.source === 'undefined') { + return; + } + if (this.source.isPausedMockNode) { + return; + } + if (this.source.disconnect && this.source.connect) { + this.source.disconnect(); + if (this.gain) { + this.source.connect(this.gain); + } + } + } + isStopped() { + return !this.source; + } +} +export default { + _JS_Sound_Create_Channel(callback, userData) { + if (!WEBAudio.audioContext || WEBAudio.audioWebEnabled === 0) { + return 0; + } + const channel = new AudioChannelInstance(callback, userData); + WEBAudio.audioInstances[++WEBAudio.audioInstanceIdCounter] = channel; + return WEBAudio.audioInstanceIdCounter; + }, + _JS_Sound_GetLength(bufferInstance) { + if (WEBAudio.audioWebEnabled === 0) { + return defaultSoundLength; + } + const soundClip = WEBAudio.audioInstances[bufferInstance]; + if (!soundClip) { + return defaultSoundLength; + } + const length = soundClip.getLength(); + return length; + }, + _JS_Sound_GetLoadState(bufferInstance) { + if (WEBAudio.audioWebEnabled === 0) { + return 2; + } + const soundClip = WEBAudio.audioInstances[bufferInstance]; + if (!soundClip || soundClip.error) { + return 2; + } + if (soundClip.buffer) { + return 0; + } + if (soundClip.url && soundClip.length) { + return 0; + } + return 1; + }, + _JS_Sound_Init() { + try { + if (wx && wx.createWebAudioContext) { + WEBAudio.audioContext = wx.createWebAudioContext(); + console.log('use wx WebAudio'); + } + if (!WEBAudio.audioContext) { + printErrMsg('Minigame Web Audio API not suppoted'); + return; + } + WEBAudio.audioWebSupport = 1; + WEBAudio.audioWebEnabled = 1; + let webAutoResumeTicker = null; + wx.onHide(() => { + if (webAutoResumeTicker) { + clearTimeout(webAutoResumeTicker); + webAutoResumeTicker = null; + } + WEBAudio.audioContext?.suspend(); + }); + wx.onShow(() => { + + if (isIOS175) { + WEBAudio.audioContext?.close(); + WEBAudio.audioContext = wx.createWebAudioContext(); + Object.values(WEBAudio.audioInstances).forEach(it => it.resetGain()); + } + else { + WEBAudio.audioContext?.resume(); + } + }); + if (webAudioNeedResume) { + + webAutoResumeTicker = setTimeout(() => { + resumeWebAudio(); + }, 2000); + } + } + catch (e) { + printErrMsg('Web Audio API is not supported in this browser'); + } + }, + _JS_Sound_IsStopped(channelInstance) { + if (WEBAudio.audioWebEnabled == 0) { + return true; + } + const channel = WEBAudio.audioInstances[channelInstance]; + if (!channel) { + return true; + } + return channel.isStopped(); + }, + _JS_Sound_Load(ptr, length, decompress) { + if (!WEBAudio.audioContext || WEBAudio.audioWebEnabled === 0) { + return 0; + } + const audioData = GameGlobal.unityNamespace.Module.HEAPU8.buffer.slice(ptr, ptr + length); + + + + + + + + + + + + + + + + decompress = 1; + let soundClip; + if (decompress && WEBAudio.audioWebSupport) { + soundClip = jsAudioCreateUncompressedSoundClipFromCompressedAudio(audioData, ptr, length); + } + else { + soundClip = jsAudioCreateCompressedSoundClip(audioData, ptr, length); + } + WEBAudio.audioInstances[++WEBAudio.audioInstanceIdCounter] = soundClip; + return WEBAudio.audioInstanceIdCounter; + }, + _JS_Sound_Load_PCM(channels, length, sampleRate, ptr) { + if (!WEBAudio.audioContext || WEBAudio.audioWebSupport === 0 || WEBAudio.audioWebEnabled === 0) { + return 0; + } + const sound = jsAudioCreateUncompressedSoundClipFromPCM(channels, length, sampleRate, ptr); + WEBAudio.audioInstances[++WEBAudio.audioInstanceIdCounter] = sound; + return WEBAudio.audioInstanceIdCounter; + }, + _JS_Sound_Play(bufferInstance, channelInstance, offset, delay) { + if (!WEBAudio.audioContext || WEBAudio.audioWebEnabled === 0) { + return; + } + debugLog('_JS_Sound_Play', bufferInstance, channelInstance, offset, delay); + WXWASMSDK._JS_Sound_Stop(channelInstance, 0); + const soundClip = WEBAudio.audioInstances[bufferInstance]; + const channel = WEBAudio.audioInstances[channelInstance]; + if (soundClip && soundClip.url) { + try { + channel.playUrl(delay, soundClip.url, offset, unityAudioVolume.get(channel), soundClip); + } + catch (e) { + printErrMsg(`playUrl error. Exception: ${e}`); + } + } + else if (soundClip && soundClip.buffer) { + try { + channel.playBuffer(WEBAudio.audioContext.currentTime + delay, soundClip.buffer, offset, channel); + } + catch (e) { + printErrMsg(`playBuffer error. Exception: ${e}`); + } + } + else { + console.log('Trying to play sound which is not loaded.'); + } + }, + _JS_Sound_ReleaseInstance(instance) { + if (WEBAudio.audioWebEnabled === 0) { + return; + } + const object = WEBAudio.audioInstances[instance]; + if (object) { + object.release(); + } + delete WEBAudio.audioInstances[instance]; + }, + _JS_Sound_ResumeIfNeeded() { + if (WEBAudio.audioWebSupport === 0 || WEBAudio.audioWebEnabled === 0) { + return; + } + resumeWebAudio(); + }, + _JS_Sound_Set3D(channelInstance, threeD) { + if (WEBAudio.audio3DSupport === 0 || WEBAudio.audioWebEnabled === 0) { + return; + } + const channel = WEBAudio.audioInstances[channelInstance]; + if (channel.threeD != threeD) { + channel.threeD = threeD; + if (!channel.source) { + channel.setup(); + } + channel.setupPanning(); + } + }, + _JS_Sound_SetListenerOrientation(x, y, z, xUp, yUp, zUp) { + if (!WEBAudio.audioContext + || WEBAudio.audio3DSupport === 0 + || WEBAudio.audioWebSupport === 0 + || WEBAudio.audioWebEnabled === 0) { + return; + } + x = x > 0 ? 0 : x; + y = y > 0 ? 0 : y; + z = z > 0 ? 0 : z; + xUp = xUp < 0 ? 0 : xUp; + yUp = yUp < 0 ? 0 : yUp; + zUp = zUp < 0 ? 0 : zUp; + if (x == WEBAudio.lOrientation.x + && y == WEBAudio.lOrientation.y + && z == WEBAudio.lOrientation.z + && xUp == WEBAudio.lOrientation.xUp + && yUp == WEBAudio.lOrientation.yUp + && zUp == WEBAudio.lOrientation.zUp) { + return; + } + WEBAudio.lOrientation.x = x; + WEBAudio.lOrientation.y = y; + WEBAudio.lOrientation.z = z; + WEBAudio.lOrientation.xUp = xUp; + WEBAudio.lOrientation.yUp = yUp; + WEBAudio.lOrientation.zUp = zUp; + if (WEBAudio.audioContext.listener.forwardX) { + WEBAudio.audioContext.listener.forwardX = -x; + WEBAudio.audioContext.listener.forwardY = -y; + WEBAudio.audioContext.listener.forwardZ = -z; + WEBAudio.audioContext.listener.upX = xUp; + WEBAudio.audioContext.listener.upY = yUp; + WEBAudio.audioContext.listener.upZ = zUp; + } + else { + WEBAudio.audioContext.listener.setOrientation(-x, -y, -z, xUp, yUp, zUp); + } + }, + _JS_Sound_SetListenerPosition(x, y, z) { + if (!WEBAudio.audioContext + || WEBAudio.audio3DSupport === 0 + || WEBAudio.audioWebSupport === 0 + || WEBAudio.audioWebEnabled === 0) { + return; + } + x = x < 0 ? 0 : x; + y = y < 0 ? 0 : y; + z = z < 0 ? 0 : z; + if (x == WEBAudio.lPosition.x && y == WEBAudio.lPosition.y && z == WEBAudio.lPosition.z) { + return; + } + WEBAudio.lPosition.x = x; + WEBAudio.lPosition.y = y; + WEBAudio.lPosition.z = z; + if (WEBAudio.audioContext.listener.positionX) { + WEBAudio.audioContext.listener.positionX = x; + WEBAudio.audioContext.listener.positionY = y; + WEBAudio.audioContext.listener.positionZ = z; + } + else { + WEBAudio.audioContext.listener.setPosition(x, y, z); + } + }, + _JS_Sound_SetLoop(channelInstance, loop) { + if (WEBAudio.audioWebEnabled === 0) { + return; + } + const channel = WEBAudio.audioInstances[channelInstance]; + if (!channel.source) { + channel.setup(); + } + if (!channel.source) { + return; + } + channel.setLoop(loop > 0); + }, + _JS_Sound_SetLoopPoints(channelInstance, loopStart, loopEnd) { + if (WEBAudio.audioWebEnabled === 0) { + return; + } + const channel = WEBAudio.audioInstances[channelInstance]; + if (!channel.source) { + channel.setup(); + } + if (!channel.source) { + return; + } + channel.setLoopPoints(loopStart, loopEnd); + }, + _JS_Sound_SetPaused(channelInstance, paused) { + if (WEBAudio.audioWebEnabled === 0) { + return; + } + const channel = WEBAudio.audioInstances[channelInstance]; + if (!!paused !== channel.isPaused()) { + if (paused) { + channel.pause(); + } + else { + channel.resume(); + } + } + }, + _JS_Sound_SetPitch(channelInstance, v) { + if (WEBAudio.audioWebSupport === 0 || WEBAudio.audioWebEnabled === 0) { + return; + } + try { + WEBAudio.audioInstances[channelInstance].source?.setPitch(v); + } + catch (e) { + printErrMsg(`Invalid audio pitch ${v} specified to WebAudio backend!`); + } + }, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _JS_Sound_SetPosition(channelInstance, x, y, z) { + if (WEBAudio.audio3DSupport === 0 || WEBAudio.audioWebSupport === 0 || WEBAudio.audioWebEnabled === 0) { + return; + } + console.error('不支持3d音效'); + }, + _JS_Sound_SetVolume(channelInstance, v) { + if (WEBAudio.audioWebEnabled === 0) { + return; + } + try { + const volume = Number(v.toFixed(2)); + const channel = WEBAudio.audioInstances[channelInstance]; + const cur = unityAudioVolume.get(channel); + if (cur === volume) { + return; + } + unityAudioVolume.set(channel, volume); + channel.setVolume(volume, cur == undefined); + } + catch (e) { + printErrMsg(`Invalid audio volume ${v} specified to WebAudio backend!`); + } + }, + _JS_Sound_Stop(channelInstance, delay) { + if (WEBAudio.audioWebEnabled === 0) { + return; + } + debugLog('_JS_Sound_Stop', channelInstance, delay); + const channel = WEBAudio.audioInstances[channelInstance]; + channel.stop(delay); + }, + _JS_Sound_GetData(bufferInstance, ptr, length) { + if (WEBAudio.audioWebEnabled === 0) { + return 0; + } + const soundClip = WEBAudio.audioInstances[bufferInstance]; + if (!soundClip) { + return 0; + } + return soundClip.getData(ptr, length) ?? 0; + }, + _JS_Sound_GetMetaData(buffer, bufferInstance, metaData) { + if (WEBAudio.audioWebEnabled === 0) { + buffer[metaData >> 2] = 0; + buffer[(metaData >> 2) + 1] = 0; + return false; + } + const soundClip = WEBAudio.audioInstances[bufferInstance]; + if (!soundClip) { + buffer[metaData >> 2] = 0; + buffer[(metaData >> 2) + 1] = 0; + return false; + } + buffer[metaData >> 2] = soundClip.getNumberOfChannels() ?? 0; + buffer[(metaData >> 2) + 1] = soundClip.getFrequency() ?? 0; + return true; + }, + _JS_Sound_GetAudioBufferSampleRate(soundInstance) { + if (WEBAudio.audioWebEnabled === 0) { + return WEBAudio.FAKEMOD_SAMPLERATE; + } + const audioInstance = WEBAudio.audioInstances[soundInstance]; + if (!audioInstance) { + return WEBAudio.FAKEMOD_SAMPLERATE; + } + // eslint-disable-next-line no-nested-ternary + const buffer = audioInstance.buffer + ? audioInstance.buffer + : audioInstance.source + ? audioInstance.source?.buffer + : null; + if (!buffer) { + return WEBAudio.FAKEMOD_SAMPLERATE; + } + return buffer.sampleRate; + }, + _JS_Sound_GetAudioContextSampleRate() { + if (WEBAudio.audioWebEnabled === 0 || !WEBAudio.audioContext) { + return WEBAudio.FAKEMOD_SAMPLERATE; + } + return WEBAudio.audioContext.sampleRate; + }, +}; diff --git a/Runtime/playable-default/unity-sdk/audio/unity-audio.js.meta b/Runtime/playable-default/unity-sdk/audio/unity-audio.js.meta new file mode 100644 index 000000000..ba879b2d0 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/audio/unity-audio.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 5d744ea7cf33148363e99bc0bd362a7d +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/audio/utils.js b/Runtime/playable-default/unity-sdk/audio/utils.js new file mode 100644 index 000000000..1a0e39b9e --- /dev/null +++ b/Runtime/playable-default/unity-sdk/audio/utils.js @@ -0,0 +1,77 @@ +import { uid } from '../utils'; +import { isSupportCacheAudio } from '../../check-version'; +import { WEBAudio, audios } from './store'; +import { TEMP_DIR_PATH } from './const'; +export const resumeWebAudio = () => { + + + + + + + WEBAudio.audioContext?.resume(); +}; +export const createInnerAudio = () => { + const id = uid(); + const audio = (isSupportCacheAudio && WEBAudio.audioCache.length ? WEBAudio.audioCache.shift() : wx.createInnerAudioContext()); + if (audio) { + audios[id] = audio; + } + return { + id, + audio, + }; +}; +export const destroyInnerAudio = (id, useCache) => { + if (!id) { + return; + } + if (!useCache || !isSupportCacheAudio || WEBAudio.audioCache.length > 32) { + audios[id].destroy(); + } + else { + + ['Play', 'Pause', 'Stop', 'Canplay', 'Error', 'Ended', 'Waiting', 'Seeking', 'Seeked', 'TimeUpdate'].forEach((eventName) => { + audios[id][`off${eventName}`](); + }); + const state = { + startTime: 0, + obeyMuteSwitch: true, + volume: 1, + autoplay: false, + loop: false, + referrerPolicy: '', + }; + Object.keys(state).forEach((key) => { + try { + + // @ts-ignore + audios[id][key] = state[key]; + } + catch (e) { } + }); + audios[id].stop(); + const cacheAudio = audios[id]; + + setTimeout(() => { + + WEBAudio.audioCache.push(cacheAudio); + }, 1000); + } + delete audios[id]; +}; +export const printErrMsg = (msg) => { + GameGlobal.manager.printErr(msg); +}; +export function mkCacheDir() { + const fs = wx.getFileSystemManager(); + fs.rmdir({ + dirPath: TEMP_DIR_PATH, + recursive: true, + complete: () => { + fs.mkdir({ + dirPath: TEMP_DIR_PATH, + }); + }, + }); +} diff --git a/Runtime/playable-default/unity-sdk/audio/utils.js.meta b/Runtime/playable-default/unity-sdk/audio/utils.js.meta new file mode 100644 index 000000000..3c170aa2e --- /dev/null +++ b/Runtime/playable-default/unity-sdk/audio/utils.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 4421437a0083958be4632b521ddb8905 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/canvas-context.js b/Runtime/playable-default/unity-sdk/canvas-context.js new file mode 100644 index 000000000..83a5364fa --- /dev/null +++ b/Runtime/playable-default/unity-sdk/canvas-context.js @@ -0,0 +1,16 @@ +const callbacks = []; +let isTriggered = false; +export default { + addCreatedListener(callback) { + if (isTriggered) { + callback(); + } + else { + callbacks.push(callback); + } + }, + _triggerCallback() { + isTriggered = true; + callbacks.forEach(v => v()); + }, +}; diff --git a/Runtime/playable-default/unity-sdk/canvas-context.js.meta b/Runtime/playable-default/unity-sdk/canvas-context.js.meta new file mode 100644 index 000000000..27b20758d --- /dev/null +++ b/Runtime/playable-default/unity-sdk/canvas-context.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 77fe45c0f03c7663002c75ca806452e2 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/canvas.js b/Runtime/playable-default/unity-sdk/canvas.js new file mode 100644 index 000000000..380a9ee28 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/canvas.js @@ -0,0 +1,24 @@ +import response from './response'; +import moduleHelper from './module-helper'; +import { getDefaultData } from './utils'; +export default { + WXToTempFilePathSync(conf) { + return canvas.toTempFilePathSync(getDefaultData(canvas, conf)); + }, + WXToTempFilePath(conf, s, f, c) { + if (conf) { + canvas.toTempFilePath({ + ...getDefaultData(canvas, conf), + ...response.handleText(s, f, c), + success: (res) => { + moduleHelper.send('ToTempFilePathCallback', JSON.stringify({ + callbackId: s, + errMsg: res.errMsg, + errCode: res.errCode || 0, + tempFilePath: res.tempFilePath, + })); + }, + }); + } + }, +}; diff --git a/Runtime/playable-default/unity-sdk/canvas.js.meta b/Runtime/playable-default/unity-sdk/canvas.js.meta new file mode 100644 index 000000000..b98f98d0e --- /dev/null +++ b/Runtime/playable-default/unity-sdk/canvas.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 91ed9cdb077eade6d28ac213af3a459e +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/conf.js b/Runtime/playable-default/unity-sdk/conf.js new file mode 100644 index 000000000..bdda06f7c --- /dev/null +++ b/Runtime/playable-default/unity-sdk/conf.js @@ -0,0 +1 @@ +export const MODULE_NAME = 'WXSDKManagerHandler'; diff --git a/Runtime/playable-default/unity-sdk/conf.js.meta b/Runtime/playable-default/unity-sdk/conf.js.meta new file mode 100644 index 000000000..15d41ea40 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/conf.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 3579e4c8f436f1af33f770da6ad12f7a +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/file-info.js b/Runtime/playable-default/unity-sdk/file-info.js new file mode 100644 index 000000000..38ce0d509 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/file-info.js @@ -0,0 +1,47 @@ +function getObjectSize(data) { + if (data && (typeof data === 'string' || data.byteLength)) { + return data.byteLength || data.length || 0; + } + return 0; +} +export const fileInfoHandler = { + addFileInfo(filePath, data) { + if (GameGlobal.manager.fs && GameGlobal.manager.fs.addFileInfo) { + GameGlobal.manager.fs.addFileInfo({ path: filePath, size: getObjectSize(data), erasable: false }); + } + }, + modifyFileInfo(filePath, data) { + if (GameGlobal.manager.fs && GameGlobal.manager.fs.modifyFileInfo) { + GameGlobal.manager.fs.modifyFileInfo({ path: filePath, size: getObjectSize(data) }); + } + }, + removeFileInfo(filePath) { + if (GameGlobal.manager.fs && GameGlobal.manager.fs.removeFileInfo) { + GameGlobal.manager.fs.removeFileInfo(filePath); + } + }, +}; +export const fileInfoType = { + add: 0, + remove: 1, + modify: 2, +}; +export function responseWrapper(responseHandler, info) { + const { filePath, data, type } = info; + return { + success(res) { + if (type === fileInfoType.add) { + fileInfoHandler.addFileInfo(filePath, data); + } + if (type === fileInfoType.remove) { + fileInfoHandler.removeFileInfo(filePath); + } + if (type === fileInfoType.modify) { + fileInfoHandler.modifyFileInfo(filePath, data); + } + responseHandler.success(res); + }, + fail: responseHandler.fail, + complete: responseHandler.complete, + }; +} diff --git a/Runtime/playable-default/unity-sdk/file-info.js.meta b/Runtime/playable-default/unity-sdk/file-info.js.meta new file mode 100644 index 000000000..4f61c2229 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/file-info.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: d0221b1711c3a28e71bdf13818e2e893 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/fix.js b/Runtime/playable-default/unity-sdk/fix.js new file mode 100644 index 000000000..b6e84c48e --- /dev/null +++ b/Runtime/playable-default/unity-sdk/fix.js @@ -0,0 +1,89 @@ +/* eslint-disable prefer-spread */ +/* eslint-disable prefer-rest-params */ + +export default { + init() { + this.fixTimer(); + }, + + fixTimer() { + const wm = {}; + const privateSetTimeout = window.setTimeout; + let id = 0; + const getId = function () { + id += 1; + if (id > 100000000) { + id = 0; + } + return id; + }; + // @ts-ignore + window.setTimeout = function (vCallback, nDelay) { + const aArgs = Array.prototype.slice.call(arguments, 2); + const id = getId(); + const t = privateSetTimeout(vCallback instanceof Function + ? () => { + // @ts-ignore + vCallback.apply(null, aArgs); + delete wm[id]; + } + : vCallback, nDelay); + wm[id] = t; + return id; + }; + const privateClearTimeout = window.clearTimeout; + // @ts-ignore + window.clearTimeout = function (id) { + if (id) { + const t = wm[id]; + if (t) { + privateClearTimeout(t); + delete wm[id]; + } + } + }; + const privateSetInterval = window.setInterval; + // @ts-ignore + window.setInterval = function (vCallback, nDelay) { + const aArgs = Array.prototype.slice.call(arguments, 2); + const id = getId(); + const t = privateSetInterval(vCallback instanceof Function + ? () => { + // @ts-ignore + vCallback.apply(null, aArgs); + } + : vCallback, nDelay); + wm[id] = t; + return id; + }; + const privateClearInterval = window.clearInterval; + // @ts-ignore + window.clearInterval = function (id) { + if (id) { + const t = wm[id]; + if (t) { + privateClearInterval(t); + delete wm[id]; + } + } + }; + const privateRequestAnimationFrame = window.requestAnimationFrame; + window.requestAnimationFrame = function (vCallback) { + const id = getId(); + const t = privateRequestAnimationFrame(() => { + vCallback(0); + delete wm[id]; + }); + wm[id] = t; + return id; + }; + const privateCancelAnimationFrame = window.cancelAnimationFrame; + window.cancelAnimationFrame = function (id) { + const t = wm[id]; + if (t) { + privateCancelAnimationFrame(t); + delete wm[id]; + } + }; + }, +}; diff --git a/Runtime/playable-default/unity-sdk/fix.js.meta b/Runtime/playable-default/unity-sdk/fix.js.meta new file mode 100644 index 000000000..5d18b1d89 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/fix.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 410deb7280bbde515c531b1122f865b4 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/fs.js b/Runtime/playable-default/unity-sdk/fs.js new file mode 100644 index 000000000..6ea13c491 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/fs.js @@ -0,0 +1,473 @@ +/* eslint-disable no-param-reassign */ +import response from './response'; +import moduleHelper from './module-helper'; +import { cacheArrayBuffer, formatJsonStr, formatResponse } from './utils'; +import { fileInfoHandler, fileInfoType, responseWrapper } from './file-info'; +function runMethod(method, option, callbackId, isString = false) { + try { + const fs = wx.getFileSystemManager(); + let config; + if (typeof option === 'string') { + config = formatJsonStr(option); + } + else { + config = option; + } + if (method === 'readZipEntry' && !config.encoding) { + config.encoding = 'utf-8'; + console.error('fs.readZipEntry不支持读取ArrayBuffer,已改为utf-8'); + } + + fs[method]({ + ...config, + success(res) { + let returnRes = ''; + if (method === 'read') { + cacheArrayBuffer(callbackId, res.arrayBuffer); + returnRes = JSON.stringify({ + bytesRead: res.bytesRead, + arrayBufferLength: res.arrayBuffer?.byteLength ?? 0, + }); + } + else if (method === 'readCompressedFile') { + cacheArrayBuffer(callbackId, res.data); + returnRes = JSON.stringify({ + arrayBufferLength: res.data?.byteLength ?? 0, + }); + } + else if (method === 'readFile') { + if (config.encoding) { + returnRes = JSON.stringify({ + stringData: res.data || '', + }); + } + else { + cacheArrayBuffer(callbackId, res.data); + returnRes = JSON.stringify({ + arrayBufferLength: res.data?.byteLength ?? 0, + }); + } + } + else { + returnRes = JSON.stringify(res); + } + // console.log(`fs.${method} success:`, res); + moduleHelper.send('FileSystemManagerCallback', JSON.stringify({ + callbackId, type: 'success', res: returnRes, method: isString ? `${method}_string` : method, + })); + }, + fail(res) { + + moduleHelper.send('FileSystemManagerCallback', JSON.stringify({ + callbackId, type: 'fail', res: JSON.stringify(res), method: isString ? `${method}_string` : method, + })); + }, + complete(res) { + moduleHelper.send('FileSystemManagerCallback', JSON.stringify({ + callbackId, type: 'complete', res: JSON.stringify(res), method: isString ? `${method}_string` : method, + })); + }, + }); + } + catch (e) { + moduleHelper.send('FileSystemManagerCallback', JSON.stringify({ + callbackId, type: 'complete', res: 'fail', method: isString ? `${method}_string` : method, + })); + } +} +export default { + WXGetUserDataPath() { + return wx.env.USER_DATA_PATH; + }, + WXWriteFileSync(filePath, data, encoding) { + try { + const fs = wx.getFileSystemManager(); + // @ts-ignore + fs.writeFileSync(filePath, data, encoding); + fileInfoHandler.addFileInfo(filePath, data); + } + catch (e) { + console.error(e); + if (e.message) { + return e.message; + } + return 'fail'; + } + return 'ok'; + }, + WXAccessFileSync(filePath) { + try { + const fs = wx.getFileSystemManager(); + fs.accessSync(filePath); + return 'access:ok'; + } + catch (e) { + + if (e.message) { + return e.message; + } + return 'fail'; + } + }, + WXAccessFile(path, s, f, c) { + const fs = wx.getFileSystemManager(); + fs.access({ + path, + ...response.handleText(s, f, c), + }); + }, + WXCopyFileSync(src, dst) { + try { + const fs = wx.getFileSystemManager(); + fs.copyFileSync(src, dst); + return 'copyFile:ok'; + } + catch (e) { + console.error(e); + if (e.message) { + return e.message; + } + return 'fail'; + } + }, + WXCopyFile(srcPath, destPath, s, f, c) { + const fs = wx.getFileSystemManager(); + fs.copyFile({ + srcPath, + destPath, + ...response.handleText(s, f, c), + }); + }, + WXUnlinkSync(filePath) { + try { + const fs = wx.getFileSystemManager(); + fs.unlinkSync(filePath); + fileInfoHandler.removeFileInfo(filePath); + return 'unlink:ok'; + } + catch (e) { + console.error(e); + if (e.message) { + return e.message; + } + return 'fail'; + } + }, + WXUnlink(filePath, s, f, c) { + const fs = wx.getFileSystemManager(); + fs.unlink({ + filePath, + ...responseWrapper(response.handleText(s, f, c), { filePath, type: fileInfoType.remove }), + }); + }, + WXWriteFile(filePath, data, encoding, s, f, c) { + const fs = wx.getFileSystemManager(); + fs.writeFile({ + filePath, + data: data.buffer, + encoding, + ...responseWrapper(response.handleTextLongBack(s, f, c), { filePath, data: data.buffer, type: fileInfoType.add }), + }); + }, + WXWriteStringFile(filePath, data, encoding, s, f, c) { + const fs = wx.getFileSystemManager(); + fs.writeFile({ + filePath, + data, + encoding, + ...responseWrapper(response.handleTextLongBack(s, f, c), { filePath, data, type: fileInfoType.add }), + }); + }, + WXAppendFile(filePath, data, encoding, s, f, c) { + const fs = wx.getFileSystemManager(); + fs.appendFile({ + filePath, + data: data.buffer, + encoding, + ...response.handleTextLongBack(s, f, c), + }); + }, + WXAppendStringFile(filePath, data, encoding, s, f, c) { + const fs = wx.getFileSystemManager(); + fs.appendFile({ + filePath, + data, + encoding, + ...response.handleTextLongBack(s, f, c), + }); + }, + WXWriteBinFileSync(filePath, data, encoding) { + const fs = wx.getFileSystemManager(); + try { + fs.writeFileSync(filePath, data.buffer, encoding); + fileInfoHandler.addFileInfo(filePath, data.buffer); + } + catch (e) { + console.error(e); + if (e.message) { + return e.message; + } + return 'fail'; + } + return 'ok'; + }, + WXReadFile(option, callbackId) { + runMethod('readFile', option, callbackId); + }, + WXReadFileSync(option) { + const fs = wx.getFileSystemManager(); + const config = formatJsonStr(option); + try { + const { filePath } = config; + const res = fs.readFileSync(config.filePath, config.encoding, config.position, config.length); + if (!config.encoding && typeof res !== 'string') { + cacheArrayBuffer(filePath, res); + return `${res.byteLength}`; + } + return res; + } + catch (e) { + console.error(e); + if (e.message) { + return e.message; + } + return 'fail'; + } + }, + WXMkdir(dirPath, recursive, s, f, c) { + const fs = wx.getFileSystemManager(); + fs.mkdir({ + dirPath, + recursive: Boolean(recursive), + ...response.handleText(s, f, c), + }); + }, + WXMkdirSync(dirPath, recursive) { + try { + const fs = wx.getFileSystemManager(); + fs.mkdirSync(dirPath, Boolean(recursive)); + return 'mkdir:ok'; + } + catch (e) { + console.error(e); + if (e.message) { + return e.message; + } + return 'fail'; + } + }, + WXRmdir(dirPath, recursive, s, f, c) { + const fs = wx.getFileSystemManager(); + fs.rmdir({ + dirPath, + recursive: Boolean(recursive), + ...response.handleText(s, f, c), + }); + }, + WXRmdirSync(dirPath, recursive) { + try { + const fs = wx.getFileSystemManager(); + fs.rmdirSync(dirPath, Boolean(recursive)); + return 'rmdirSync:ok'; + } + catch (e) { + console.error(e); + if (e.message) { + return e.message; + } + return 'fail'; + } + }, + WXStat(conf, callbackId) { + const config = formatJsonStr(conf); + wx.getFileSystemManager().stat({ + ...config, + success(res) { + if (!Array.isArray(res.stats)) { + // @ts-ignore C#中特殊处理 + res.one_stat = res.stats; + // @ts-ignore C#中特殊处理 + res.stats = null; + } + moduleHelper.send('StatCallback', JSON.stringify({ + callbackId, + type: 'success', + res: JSON.stringify(res), + })); + }, + fail(res) { + moduleHelper.send('StatCallback', JSON.stringify({ + callbackId, + type: 'fail', + res: JSON.stringify(res), + })); + }, + complete(res) { + // @ts-ignore C#中特殊处理 + if (!Array.isArray(res.stats)) { + // @ts-ignore C#中特殊处理 + res.one_stat = res.stats; + // @ts-ignore C#中特殊处理 + res.stats = null; + } + moduleHelper.send('StatCallback', JSON.stringify({ + callbackId, + type: 'complete', + res: JSON.stringify(res), + })); + }, + }); + }, + WX_FileSystemManagerClose(option, callbackId) { + runMethod('close', option, callbackId); + }, + WX_FileSystemManagerFstat(option, callbackId) { + runMethod('fstat', option, callbackId); + }, + WX_FileSystemManagerFtruncate(option, callbackId) { + runMethod('ftruncate', option, callbackId); + }, + WX_FileSystemManagerGetFileInfo(option, callbackId) { + runMethod('getFileInfo', option, callbackId); + }, + WX_FileSystemManagerGetSavedFileList(option, callbackId) { + runMethod('getSavedFileList', option, callbackId); + }, + WX_FileSystemManagerOpen(option, callbackId) { + runMethod('open', option, callbackId); + }, + WX_FileSystemManagerRead(option, data, callbackId) { + const config = formatJsonStr(option); + config.arrayBuffer = data.buffer; + runMethod('read', config, callbackId); + }, + WX_FileSystemManagerReadCompressedFile(option, callbackId) { + runMethod('readCompressedFile', option, callbackId); + }, + WX_FileSystemManagerReadZipEntry(option, callbackId) { + runMethod('readZipEntry', option, callbackId); + }, + WX_FileSystemManagerReadZipEntryString(option, callbackId) { + runMethod('readZipEntry', option, callbackId, true); + }, + WX_FileSystemManagerReaddir(option, callbackId) { + runMethod('readdir', option, callbackId); + }, + WX_FileSystemManagerRemoveSavedFile(option, callbackId) { + runMethod('removeSavedFile', option, callbackId); + }, + WX_FileSystemManagerRename(option, callbackId) { + runMethod('rename', option, callbackId); + }, + WX_FileSystemManagerSaveFile(option, callbackId) { + runMethod('saveFile', option, callbackId); + }, + WX_FileSystemManagerTruncate(option, callbackId) { + runMethod('truncate', option, callbackId); + }, + WX_FileSystemManagerUnzip(option, callbackId) { + runMethod('unzip', option, callbackId); + }, + WX_FileSystemManagerWrite(option, data, callbackId) { + const config = formatJsonStr(option); + config.data = data.buffer; + runMethod('write', config, callbackId); + }, + WX_FileSystemManagerWriteString(option, callbackId) { + runMethod('write', option, callbackId, true); + }, + WX_FileSystemManagerReaddirSync(dirPath) { + const fs = wx.getFileSystemManager(); + try { + + return JSON.stringify(fs.readdirSync(dirPath) || []); + } + catch (e) { + console.error(e); + return '[]'; + } + }, + WX_FileSystemManagerReadCompressedFileSync(option, callbackId) { + const fs = wx.getFileSystemManager(); + const res = fs.readCompressedFileSync(formatJsonStr(option)); + cacheArrayBuffer(callbackId, res); + return res.byteLength; + }, + WX_FileSystemManagerAppendFileStringSync(filePath, data, encoding) { + const fs = wx.getFileSystemManager(); + fs.appendFileSync(filePath, data, encoding); + }, + WX_FileSystemManagerAppendFileSync(filePath, data, encoding) { + const fs = wx.getFileSystemManager(); + fs.appendFileSync(filePath, data.buffer, encoding); + }, + WX_FileSystemManagerRenameSync(oldPath, newPath) { + const fs = wx.getFileSystemManager(); + fs.renameSync(oldPath, newPath); + return 'ok'; + }, + WX_FileSystemManagerReadSync(option, callbackId) { + const fs = wx.getFileSystemManager(); + const optionConfig = formatJsonStr(option); + optionConfig.arrayBuffer = new ArrayBuffer(optionConfig.arrayBuffer.length); + const res = fs.readSync(optionConfig); + cacheArrayBuffer(callbackId, res.arrayBuffer); + return JSON.stringify({ + bytesRead: res.bytesRead, + arrayBufferLength: res.arrayBuffer?.byteLength ?? 0, + }); + }, + WX_FileSystemManagerFstatSync(option) { + const fs = wx.getFileSystemManager(); + const res = fs.fstatSync(formatJsonStr(option)); + formatResponse('Stats', res); + return JSON.stringify(res); + }, + WX_FileSystemManagerStatSync(path, recursive) { + const fs = wx.getFileSystemManager(); + const res = fs.statSync(path, recursive); + let resArray; + if (Array.isArray(res)) { + resArray = res; + } + else { + resArray = [res]; + } + return JSON.stringify(resArray); + }, + WX_FileSystemManagerWriteSync(option, data) { + const fs = wx.getFileSystemManager(); + const optionConfig = formatJsonStr(option); + optionConfig.data = data.buffer; + const res = fs.writeSync(optionConfig); + return JSON.stringify(res); + }, + WX_FileSystemManagerWriteStringSync(option) { + const fs = wx.getFileSystemManager(); + const res = fs.writeSync(formatJsonStr(option)); + return JSON.stringify(res); + }, + WX_FileSystemManagerOpenSync(option) { + const fs = wx.getFileSystemManager(); + return fs.openSync(formatJsonStr(option)); + }, + WX_FileSystemManagerSaveFileSync(tempFilePath, filePath) { + const fs = wx.getFileSystemManager(); + return fs.saveFileSync(tempFilePath, filePath); + }, + WX_FileSystemManagerCloseSync(option) { + const fs = wx.getFileSystemManager(); + fs.closeSync(formatJsonStr(option)); + return 'ok'; + }, + WX_FileSystemManagerFtruncateSync(option) { + const fs = wx.getFileSystemManager(); + fs.ftruncateSync(formatJsonStr(option)); + return 'ok'; + }, + WX_FileSystemManagerTruncateSync(option) { + const fs = wx.getFileSystemManager(); + fs.truncateSync(formatJsonStr(option)); + return 'ok'; + }, +}; diff --git a/Runtime/playable-default/unity-sdk/fs.js.meta b/Runtime/playable-default/unity-sdk/fs.js.meta new file mode 100644 index 000000000..37cb2966f --- /dev/null +++ b/Runtime/playable-default/unity-sdk/fs.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 8b6f6d9e92f81197271065ac79715005 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/index.js b/Runtime/playable-default/unity-sdk/index.js new file mode 100644 index 000000000..0e206c917 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/index.js @@ -0,0 +1,80 @@ + +import moduleHelper from './module-helper'; +import canvasHelper from './canvas'; +import fs from './fs'; +import util from './util'; +import audio from './audio/index'; +import texture from './texture'; +import fix from './fix'; +import canvasContext from './canvas-context'; +import video from './video'; +import logger from './logger'; +import sdk from './sdk'; +import videoDecoder from './video/index'; +import mobileKeyboard from './mobileKeyboard/index'; +import touch from './touch/index'; +import specialCallbacks from './special-callbacks'; +const unityVersion = '$unityVersion$'; +GameGlobal.unityNamespace = GameGlobal.unityNamespace || {}; +GameGlobal.unityNamespace.unityVersion = unityVersion; +window._ScaleRate = 1; + +if (unityVersion && unityVersion.split('.').slice(0, 2) + .join('') < '20193') { + const width = window.innerWidth * window.devicePixelRatio; + const height = window.innerHeight * window.devicePixelRatio; + canvas.width = width; + canvas.height = height; + window._ScaleRate = window.devicePixelRatio; +} +Object.defineProperty(canvas, 'clientHeight', { + get() { + return window.innerHeight * window._ScaleRate; + }, + configurable: true, +}); +Object.defineProperty(canvas, 'clientWidth', { + get() { + return window.innerWidth * window._ScaleRate; + }, + configurable: true, +}); +Object.defineProperty(document.body, 'clientHeight', { + get() { + return window.innerHeight * window._ScaleRate; + }, + configurable: true, +}); +Object.defineProperty(document.body, 'clientWidth', { + get() { + return window.innerWidth * window._ScaleRate; + }, + configurable: true, +}); +Object.defineProperty(document, 'fullscreenEnabled', { + get() { + return true; + }, + configurable: true, +}); +fix.init(); +const WXWASMSDK = { + WXInitializeSDK() { + moduleHelper.init(); + moduleHelper.send('Inited', 200); + }, + ...canvasHelper, + ...fs, + ...util, + ...audio, + ...texture, + ...video, + ...logger, + canvasContext, + ...sdk, + ...videoDecoder, + ...mobileKeyboard, + ...touch, + ...specialCallbacks, +}; +GameGlobal.WXWASMSDK = WXWASMSDK; diff --git a/Runtime/playable-default/unity-sdk/index.js.meta b/Runtime/playable-default/unity-sdk/index.js.meta new file mode 100644 index 000000000..5544fcafb --- /dev/null +++ b/Runtime/playable-default/unity-sdk/index.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: f1e291e032cc749be6d2b0f7db843282 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/logger.js b/Runtime/playable-default/unity-sdk/logger.js new file mode 100644 index 000000000..b2939b43f --- /dev/null +++ b/Runtime/playable-default/unity-sdk/logger.js @@ -0,0 +1,27 @@ +let logger; +export default { + WXLogManagerDebug(str) { + if (!logger) { + logger = wx.getLogManager({ level: 0 }); + } + logger.debug(str); + }, + WXLogManagerInfo(str) { + if (!logger) { + logger = wx.getLogManager({ level: 0 }); + } + logger.info(str); + }, + WXLogManagerLog(str) { + if (!logger) { + logger = wx.getLogManager({ level: 0 }); + } + logger.log(str); + }, + WXLogManagerWarn(str) { + if (!logger) { + logger = wx.getLogManager({ level: 0 }); + } + logger.warn(str); + }, +}; diff --git a/Runtime/playable-default/unity-sdk/logger.js.meta b/Runtime/playable-default/unity-sdk/logger.js.meta new file mode 100644 index 000000000..42024403f --- /dev/null +++ b/Runtime/playable-default/unity-sdk/logger.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: acb8386409f823458dea82af2ad09ba3 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/mobileKeyboard.meta b/Runtime/playable-default/unity-sdk/mobileKeyboard.meta new file mode 100644 index 000000000..e529a087b --- /dev/null +++ b/Runtime/playable-default/unity-sdk/mobileKeyboard.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f19e6105a634ac8e2358239d66f08d0a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/mobileKeyboard/index.js b/Runtime/playable-default/unity-sdk/mobileKeyboard/index.js new file mode 100644 index 000000000..55cc9d874 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/mobileKeyboard/index.js @@ -0,0 +1,137 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +let FrameworkData = null; +const keyboardSetting = { + value: '', + maxLength: 140, + multiple: false, + confirmHold: false, + confirmType: 'done', +}; +const keyboardInputlistener = function (res) { + keyboardSetting.value = res.value; +}; +const keyboardConfirmlistener = function (res) { + keyboardSetting.value = res.value; + _JS_MobileKeyboard_Hide(false); +}; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +const keyboardCompletelistener = function (res) { + removeKeyboardListeners(); +}; +let hasExistingMobileInput = false; +let mobile_input_hide_delay = null; +let mobile_input_ignore_blur_event = false; +function _JS_MobileKeybard_GetIgnoreBlurEvent() { + + + + return mobile_input_ignore_blur_event; +} +function _JS_MobileKeyboard_GetKeyboardStatus() { + const kKeyboardStatusVisible = 0; + const kKeyboardStatusDone = 1; + + + if (!hasExistingMobileInput) { + return kKeyboardStatusDone; + } + return kKeyboardStatusVisible; +} +function _JS_MobileKeyboard_GetText(buffer, bufferSize) { + if (buffer) { + FrameworkData.stringToUTF8(keyboardSetting.value, buffer, bufferSize); + } + return FrameworkData.lengthBytesUTF8(keyboardSetting.value); +} +function _JS_MobileKeyboard_GetTextSelection(outStart, outLength) { + + const n = keyboardSetting.value.length; + FrameworkData.HEAP32[outStart >> 2] = n; + FrameworkData.HEAP32[outLength >> 2] = 0; +} +function _JS_MobileKeyboard_Hide(delay) { + if (mobile_input_hide_delay) { + return; + } + mobile_input_ignore_blur_event = true; + function hideMobileKeyboard() { + if (hasExistingMobileInput) { + wx.hideKeyboard(); + } + hasExistingMobileInput = false; + mobile_input_hide_delay = null; + + + + + setTimeout(() => { + mobile_input_ignore_blur_event = false; + }, 100); + } + if (delay) { + + + + + const hideDelay = 200; + mobile_input_hide_delay = setTimeout(hideMobileKeyboard, hideDelay); + } + else { + hideMobileKeyboard(); + } +} +function _JS_MobileKeyboard_SetCharacterLimit(limit) { + keyboardSetting.maxLength = limit; +} +function _JS_MobileKeyboard_SetText(text) { + if (!hasExistingMobileInput) { + return; + } + keyboardSetting.value = FrameworkData.UTF8ToString(text); +} +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function _JS_MobileKeyboard_SetTextSelection(start, length) { + +} +function _JS_MobileKeyboard_Show(text, keyboardType, autocorrection, multiline, secure, alert, placeholder, characterLimit, data) { + if (FrameworkData === null) { + FrameworkData = data; + } + if (mobile_input_hide_delay) { + clearTimeout(mobile_input_hide_delay); + mobile_input_hide_delay = null; + } + if (hasExistingMobileInput) { + if (keyboardSetting.multiple !== !!multiline) { + _JS_MobileKeyboard_Hide(false); + return; + } + } + keyboardSetting.value = FrameworkData.UTF8ToString(text); + keyboardSetting.maxLength = characterLimit > 0 ? characterLimit : 524288; + keyboardSetting.multiple = !!multiline; + wx.showKeyboard({ defaultValue: keyboardSetting.value, maxLength: keyboardSetting.maxLength, multiple: keyboardSetting.multiple, confirmHold: keyboardSetting.confirmHold, confirmType: keyboardSetting.confirmType }); + addKeyboardListeners(); + hasExistingMobileInput = true; +} +function addKeyboardListeners() { + wx.onKeyboardInput(keyboardInputlistener); + wx.onKeyboardConfirm(keyboardConfirmlistener); + wx.onKeyboardComplete(keyboardCompletelistener); +} +function removeKeyboardListeners() { + wx.offKeyboardInput(keyboardInputlistener); + wx.offKeyboardConfirm(keyboardConfirmlistener); + wx.offKeyboardComplete(keyboardCompletelistener); +} +export default { + _JS_MobileKeybard_GetIgnoreBlurEvent, + _JS_MobileKeyboard_GetKeyboardStatus, + _JS_MobileKeyboard_GetText, + _JS_MobileKeyboard_GetTextSelection, + _JS_MobileKeyboard_Hide, + _JS_MobileKeyboard_SetCharacterLimit, + _JS_MobileKeyboard_SetText, + _JS_MobileKeyboard_SetTextSelection, + _JS_MobileKeyboard_Show, +}; diff --git a/Runtime/playable-default/unity-sdk/mobileKeyboard/index.js.meta b/Runtime/playable-default/unity-sdk/mobileKeyboard/index.js.meta new file mode 100644 index 000000000..ad075e6a7 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/mobileKeyboard/index.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: ee2ae2d99a13f9f0cfdca93ba7f25463 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/module-helper.js b/Runtime/playable-default/unity-sdk/module-helper.js new file mode 100644 index 000000000..9af0cfa2f --- /dev/null +++ b/Runtime/playable-default/unity-sdk/module-helper.js @@ -0,0 +1,15 @@ +/* eslint-disable no-underscore-dangle */ +import { MODULE_NAME } from './conf'; +export default { + _send: null, + init() { + this._send = GameGlobal.Module.SendMessage; + }, + send(method, str = '') { + if (!this._send) { + this.init(); + } + // @ts-ignore + this._send(MODULE_NAME, method, str); + }, +}; diff --git a/Runtime/playable-default/unity-sdk/module-helper.js.meta b/Runtime/playable-default/unity-sdk/module-helper.js.meta new file mode 100644 index 000000000..06dbdee42 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/module-helper.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: fceaac0eeaf70b3aa091b66849002cf9 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/recorder.js b/Runtime/playable-default/unity-sdk/recorder.js new file mode 100644 index 000000000..54d2d15c5 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/recorder.js @@ -0,0 +1,156 @@ +import moduleHelper from './module-helper'; +import { formatJsonStr, cacheArrayBuffer, getListObject, uid } from './utils'; +const recorderManagerList = {}; +const getObject = getListObject(recorderManagerList, 'video'); +export default { + WX_GetRecorderManager() { + const id = uid(); + recorderManagerList[id] = wx.getRecorderManager(); + return id; + }, + WX_OnRecorderError(id) { + const obj = getObject(id); + if (!obj) { + return; + } + const callback = (res) => { + const resStr = JSON.stringify({ + callbackId: id, + res: JSON.stringify(res), + }); + moduleHelper.send('_OnRecorderErrorCallback', resStr); + }; + obj.onError(callback); + }, + WX_OnRecorderFrameRecorded(id) { + const obj = getObject(id); + if (!obj) { + return; + } + const callback = (res) => { + cacheArrayBuffer(id, res.frameBuffer); + const resStr = JSON.stringify({ + callbackId: id, + res: JSON.stringify({ + frameBufferLength: res.frameBuffer.byteLength, + isLastFrame: res.isLastFrame, + }), + }); + moduleHelper.send('_OnRecorderFrameRecordedCallback', resStr); + }; + obj.onFrameRecorded(callback); + }, + WX_OnRecorderInterruptionBegin(id) { + const obj = getObject(id); + if (!obj) { + return; + } + const callback = (res) => { + const resStr = JSON.stringify({ + callbackId: id, + res: JSON.stringify(res), + }); + moduleHelper.send('_OnRecorderInterruptionBeginCallback', resStr); + }; + obj.onInterruptionBegin(callback); + }, + WX_OnRecorderInterruptionEnd(id) { + const obj = getObject(id); + if (!obj) { + return; + } + const callback = (res) => { + const resStr = JSON.stringify({ + callbackId: id, + res: JSON.stringify(res), + }); + moduleHelper.send('_OnRecorderInterruptionEndCallback', resStr); + }; + obj.onInterruptionEnd(callback); + }, + WX_OnRecorderPause(id) { + const obj = getObject(id); + if (!obj) { + return; + } + const callback = (res) => { + const resStr = JSON.stringify({ + callbackId: id, + res: JSON.stringify(res), + }); + moduleHelper.send('_OnRecorderPauseCallback', resStr); + }; + obj.onPause(callback); + }, + WX_OnRecorderResume(id) { + const obj = getObject(id); + if (!obj) { + return; + } + const callback = (res) => { + const resStr = JSON.stringify({ + callbackId: id, + res: JSON.stringify(res), + }); + moduleHelper.send('_OnRecorderResumeCallback', resStr); + }; + obj.onResume(callback); + }, + WX_OnRecorderStart(id) { + const obj = getObject(id); + if (!obj) { + return; + } + const callback = (res) => { + const resStr = JSON.stringify({ + callbackId: id, + res: JSON.stringify(res), + }); + moduleHelper.send('_OnRecorderStartCallback', resStr); + }; + obj.onStart(callback); + }, + WX_OnRecorderStop(id) { + const obj = getObject(id); + if (!obj) { + return; + } + const callback = (res) => { + const resStr = JSON.stringify({ + callbackId: id, + res: JSON.stringify(res), + }); + moduleHelper.send('_OnRecorderStopCallback', resStr); + }; + obj.onStop(callback); + }, + WX_RecorderPause(id) { + const obj = getObject(id); + if (!obj) { + return; + } + obj.pause(); + }, + WX_RecorderResume(id) { + const obj = getObject(id); + if (!obj) { + return; + } + obj.resume(); + }, + WX_RecorderStart(id, option) { + const obj = getObject(id); + if (!obj) { + return; + } + const conf = formatJsonStr(option); + obj.start(conf); + }, + WX_RecorderStop(id) { + const obj = getObject(id); + if (!obj) { + return; + } + obj.stop(); + }, +}; diff --git a/Runtime/playable-default/unity-sdk/recorder.js.meta b/Runtime/playable-default/unity-sdk/recorder.js.meta new file mode 100644 index 000000000..57a4c0c3d --- /dev/null +++ b/Runtime/playable-default/unity-sdk/recorder.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: dc21bb274355e700fd0b79da2507fad9 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/resType.js b/Runtime/playable-default/unity-sdk/resType.js new file mode 100644 index 000000000..e81a85770 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/resType.js @@ -0,0 +1,1016 @@ +export const ResType = { + AccountInfo: { + miniProgram: 'MiniProgram', + plugin: 'Plugin', + }, + MiniProgram: { + appId: 'string', + envVersion: 'string', + version: 'string', + }, + Plugin: { + appId: 'string', + version: 'string', + }, + AppAuthorizeSetting: { + albumAuthorized: 'string', + bluetoothAuthorized: 'string', + cameraAuthorized: 'string', + locationAuthorized: 'string', + locationReducedAccuracy: 'bool', + microphoneAuthorized: 'string', + notificationAlertAuthorized: 'string', + notificationAuthorized: 'string', + notificationBadgeAuthorized: 'string', + notificationSoundAuthorized: 'string', + phoneCalendarAuthorized: 'string', + }, + AppBaseInfo: { + SDKVersion: 'string', + enableDebug: 'bool', + fontSizeScaleFactor: 'number', + fontSizeSetting: 'number', + host: 'AppBaseInfoHost', + language: 'string', + version: 'string', + theme: 'string', + }, + AppBaseInfoHost: { + appId: 'string', + }, + GetBatteryInfoSyncResult: { + isCharging: 'bool', + isLowPowerModeEnabled: 'bool', + level: 'number', + }, + DeviceInfo: { + abi: 'string', + benchmarkLevel: 'number', + brand: 'string', + cpuType: 'string', + deviceAbi: 'string', + memorySize: 'string', + model: 'string', + platform: 'string', + system: 'string', + }, + EnterOptionsGame: { + apiCategory: 'string', + query: 'object', + referrerInfo: 'EnterOptionsGameReferrerInfo', + scene: 'number', + chatType: 'number', + shareTicket: 'string', + }, + EnterOptionsGameReferrerInfo: { + appId: 'string', + extraData: 'object', + gameLiveInfo: 'GameLiveInfo', + }, + GameLiveInfo: { + streamerOpenId: 'string', + feedId: 'string', + }, + LaunchOptionsGame: { + query: 'object', + referrerInfo: 'EnterOptionsGameReferrerInfo', + scene: 'number', + chatType: 'number', + shareTicket: 'string', + }, + ClientRect: { + bottom: 'number', + height: 'number', + left: 'number', + right: 'number', + top: 'number', + width: 'number', + }, + GetStorageInfoSyncOption: { + currentSize: 'number', + keys: 'string[]', + limitSize: 'number', + }, + SystemInfo: { + SDKVersion: 'string', + albumAuthorized: 'bool', + benchmarkLevel: 'number', + bluetoothEnabled: 'bool', + brand: 'string', + cameraAuthorized: 'bool', + deviceOrientation: 'string', + enableDebug: 'bool', + fontSizeSetting: 'number', + host: 'SystemInfoHost', + language: 'string', + locationAuthorized: 'bool', + locationEnabled: 'bool', + locationReducedAccuracy: 'bool', + microphoneAuthorized: 'bool', + model: 'string', + notificationAlertAuthorized: 'bool', + notificationAuthorized: 'bool', + notificationBadgeAuthorized: 'bool', + notificationSoundAuthorized: 'bool', + phoneCalendarAuthorized: 'bool', + pixelRatio: 'number', + platform: 'string', + safeArea: 'SafeArea', + screenHeight: 'number', + screenWidth: 'number', + statusBarHeight: 'number', + system: 'string', + version: 'string', + wifiEnabled: 'bool', + windowHeight: 'number', + windowWidth: 'number', + theme: 'string', + }, + SystemInfoHost: { + appId: 'string', + }, + SafeArea: { + bottom: 'number', + height: 'number', + left: 'number', + right: 'number', + top: 'number', + width: 'number', + }, + SystemSetting: { + bluetoothEnabled: 'bool', + deviceOrientation: 'string', + locationEnabled: 'bool', + wifiEnabled: 'bool', + }, + WindowInfo: { + pixelRatio: 'number', + safeArea: 'SafeArea', + screenHeight: 'number', + screenTop: 'number', + screenWidth: 'number', + statusBarHeight: 'number', + windowHeight: 'number', + windowWidth: 'number', + }, + GeneralCallbackResult: { + errMsg: 'string', + }, + DownloadFileSuccessCallbackResult: { + filePath: 'string', + profile: 'RequestProfile', + statusCode: 'number', + tempFilePath: 'string', + errMsg: 'string', + }, + RequestProfile: { + SSLconnectionEnd: 'number', + SSLconnectionStart: 'number', + connectEnd: 'number', + connectStart: 'number', + domainLookUpEnd: 'number', + domainLookUpStart: 'number', + downstreamThroughputKbpsEstimate: 'number', + estimate_nettype: 'number', + fetchStart: 'number', + httpRttEstimate: 'number', + peerIP: 'string', + port: 'number', + protocol: 'string', + receivedBytedCount: 'number', + redirectEnd: 'number', + redirectStart: 'number', + requestEnd: 'number', + requestStart: 'number', + responseEnd: 'number', + responseStart: 'number', + rtt: 'number', + sendBytesCount: 'number', + socketReused: 'bool', + throughputKbps: 'number', + transportRttEstimate: 'number', + usingHighPerformanceMode: 'bool', + }, + DownloadTaskOnHeadersReceivedListenerResult: { + header: 'object', + }, + DownloadTaskOnProgressUpdateListenerResult: { + progress: 'number', + totalBytesExpectedToWrite: 'number', + totalBytesWritten: 'number', + }, + CreateOpenSettingButtonOption: { + style: 'OptionStyle', + type: 'string', + image: 'string', + text: 'string', + }, + OptionStyle: { + backgroundColor: 'string', + height: 'number', + left: 'number', + top: 'number', + width: 'number', + borderColor: 'string', + borderRadius: 'number', + borderWidth: 'number', + color: 'string', + fontSize: 'number', + lineHeight: 'number', + textAlign: 'string', + }, + ImageData: { + height: 'number', + width: 'number', + }, + GetLogManagerOption: { + level: 'number', + }, + Path2D: {}, + OnCheckForUpdateListenerResult: { + hasUpdate: 'bool', + }, + VideoDecoderStartOption: { + source: 'string', + abortAudio: 'bool', + abortVideo: 'bool', + mode: 'number', + }, + SetMessageToFriendQueryOption: { + query: 'string', + shareMessageToFriendScene: 'number', + }, + AddCardRequestInfo: { + cardExt: 'string', + cardId: 'string', + }, + AddCardSuccessCallbackResult: { + cardList: 'AddCardResponseInfo[]', + errMsg: 'string', + }, + AddCardResponseInfo: { + cardExt: 'string', + cardId: 'string', + code: 'string', + isSuccess: 'bool', + }, + AuthPrivateMessageSuccessCallbackResult: { + encryptedData: 'string', + errMsg: 'string', + iv: 'string', + valid: 'bool', + }, + CheckIsAddedToMyMiniProgramSuccessCallbackResult: { + added: 'bool', + errMsg: 'string', + }, + ChooseImageSuccessCallbackResult: { + tempFilePaths: 'string[]', + tempFiles: 'ImageFile[]', + errMsg: 'string', + }, + ImageFile: { + path: 'string', + size: 'number', + }, + ChooseMediaSuccessCallbackResult: { + tempFiles: 'MediaFile[]', + type: 'string', + errMsg: 'string', + }, + MediaFile: { + duration: 'number', + fileType: 'string', + height: 'number', + size: 'number', + tempFilePath: 'string', + thumbTempFilePath: 'string', + width: 'number', + }, + ChooseMessageFileSuccessCallbackResult: { + tempFiles: 'ChooseFile[]', + errMsg: 'string', + }, + ChooseFile: { + name: 'string', + path: 'string', + size: 'number', + time: 'number', + type: 'string', + }, + BluetoothError: { + errMsg: 'string', + errCode: 'number', + }, + CompressImageSuccessCallbackResult: { + tempFilePath: 'string', + errMsg: 'string', + }, + CreateBLEPeripheralServerSuccessCallbackResult: { + server: 'BLEPeripheralServer', + errMsg: 'string', + }, + BLEPeripheralService: { + characteristics: 'Characteristic[]', + uuid: 'string', + }, + Characteristic: { + uuid: 'string', + descriptors: 'Descriptor[]', + permission: 'CharacteristicPermission', + properties: 'CharacteristicProperties', + value: 'arrayBuffer', + arrayBufferLength: 'number', + }, + Descriptor: { + uuid: 'string', + permission: 'DescriptorPermission', + value: 'arrayBuffer', + arrayBufferLength: 'number', + }, + DescriptorPermission: { + read: 'bool', + write: 'bool', + }, + CharacteristicPermission: { + readEncryptionRequired: 'bool', + readable: 'bool', + writeEncryptionRequired: 'bool', + writeable: 'bool', + }, + CharacteristicProperties: { + indicate: 'bool', + notify: 'bool', + read: 'bool', + write: 'bool', + writeNoResponse: 'bool', + }, + OnCharacteristicReadRequestListenerResult: { + callbackId: 'number', + characteristicId: 'string', + serviceId: 'string', + }, + OnCharacteristicSubscribedListenerResult: { + characteristicId: 'string', + serviceId: 'string', + }, + OnCharacteristicWriteRequestListenerResult: { + callbackId: 'number', + characteristicId: 'string', + serviceId: 'string', + value: 'arrayBuffer', + arrayBufferLength: 'number', + }, + AdvertiseReqObj: { + beacon: 'BeaconInfoObj', + connectable: 'bool', + deviceName: 'string', + manufacturerData: 'ManufacturerData[]', + serviceUuids: 'string[]', + }, + BeaconInfoObj: { + major: 'number', + minor: 'number', + uuid: 'string', + measuredPower: 'number', + }, + ManufacturerData: { + manufacturerId: 'string', + manufacturerSpecificData: 'arrayBuffer', + arrayBufferLength: 'number', + }, + FaceDetectSuccessCallbackResult: { + angleArray: 'FaceAngel', + confArray: 'FaceConf', + detectRect: 'object', + faceInfo: 'IAnyObject[]', + pointArray: 'IAnyObject[]', + x: 'number', + y: 'number', + errMsg: 'string', + }, + FaceAngel: { + pitch: 'number', + roll: 'number', + yaw: 'number', + }, + FaceConf: { + global: 'number', + leftEye: 'number', + mouth: 'number', + nose: 'number', + rightEye: 'number', + }, + GetAvailableAudioSourcesSuccessCallbackResult: { + errMsg: 'string', + }, + GetBLEDeviceCharacteristicsSuccessCallbackResult: { + characteristics: 'BLECharacteristic[]', + errMsg: 'string', + }, + BLECharacteristic: { + properties: 'BLECharacteristicProperties', + uuid: 'string', + }, + BLECharacteristicProperties: { + indicate: 'bool', + notify: 'bool', + read: 'bool', + write: 'bool', + writeDefault: 'bool', + writeNoResponse: 'bool', + }, + GetBLEDeviceRSSISuccessCallbackResult: { + RSSI: 'number', + errMsg: 'string', + }, + GetBLEDeviceServicesSuccessCallbackResult: { + services: 'BLEService[]', + errMsg: 'string', + }, + BLEService: { + isPrimary: 'bool', + uuid: 'string', + }, + GetBLEMTUSuccessCallbackResult: { + mtu: 'number', + errMsg: 'string', + }, + GetBackgroundFetchDataSuccessCallbackResult: { + fetchedData: 'string', + path: 'string', + query: 'string', + scene: 'number', + timeStamp: 'long', + errMsg: 'string', + }, + GetBackgroundFetchTokenSuccessCallbackResult: { + errMsg: 'string', + token: 'string', + }, + GetBatteryInfoSuccessCallbackResult: { + isCharging: 'bool', + isLowPowerModeEnabled: 'bool', + level: 'number', + errMsg: 'string', + }, + BeaconError: { + errMsg: 'string', + errCode: 'number', + }, + GetBeaconsSuccessCallbackResult: { + beacons: 'BeaconInfo[]', + errMsg: 'string', + }, + BeaconInfo: { + accuracy: 'number', + major: 'number', + minor: 'number', + proximity: 'number', + rssi: 'number', + uuid: 'string', + }, + GetBluetoothAdapterStateSuccessCallbackResult: { + available: 'bool', + discovering: 'bool', + errMsg: 'string', + }, + GetBluetoothDevicesSuccessCallbackResult: { + devices: 'BlueToothDevice[]', + errMsg: 'string', + }, + BlueToothDevice: { + RSSI: 'number', + advertisData: 'arrayBuffer', + arrayBufferLength: 'number', + advertisServiceUUIDs: 'string[]', + connectable: 'bool', + deviceId: 'string', + localName: 'string', + name: 'string', + serviceData: 'object', + }, + GetChannelsLiveInfoSuccessCallbackResult: { + description: 'string', + feedId: 'string', + headUrl: 'string', + nickname: 'string', + nonceId: 'string', + otherInfos: 'AnyKeyword[]', + replayStatus: 'number', + status: 'number', + errMsg: 'string', + }, + GetChannelsLiveNoticeInfoSuccessCallbackResult: { + headUrl: 'string', + nickname: 'string', + noticeId: 'string', + otherInfos: 'AnyKeyword[]', + reservable: 'bool', + startTime: 'string', + status: 'number', + errMsg: 'string', + }, + GetClipboardDataSuccessCallbackOption: { + data: 'string', + errMsg: 'string', + }, + GetConnectedBluetoothDevicesSuccessCallbackResult: { + devices: 'BluetoothDeviceInfo[]', + errMsg: 'string', + }, + BluetoothDeviceInfo: { + deviceId: 'string', + name: 'string', + }, + GetDeviceBenchmarkInfoSuccessCallbackResult: { + benchmarkLevel: 'number', + modelLevel: 'number', + errMsg: 'string', + }, + GetExtConfigSuccessCallbackResult: { + extConfig: 'object', + errMsg: 'string', + }, + GetFuzzyLocationSuccessCallbackResult: { + latitude: 'number', + longitude: 'number', + errMsg: 'string', + }, + DataType: { + type: 'number', + subKey: 'string', + }, + GetGameClubDataSuccessCallbackResult: { + cloudID: 'string', + encryptedData: 'string', + iv: 'string', + signature: 'string', + errMsg: 'string', + }, + GetGroupEnterInfoError: { + errMsg: 'string', + errCode: 'number', + }, + GetGroupEnterInfoSuccessCallbackResult: { + cloudID: 'string', + encryptedData: 'string', + errMsg: 'string', + iv: 'string', + }, + GetInferenceEnvInfoSuccessCallbackResult: { + ver: 'string', + errMsg: 'string', + }, + GetLocalIPAddressSuccessCallbackResult: { + errMsg: 'string', + localip: 'string', + netmask: 'string', + }, + GetNetworkTypeSuccessCallbackResult: { + hasSystemProxy: 'bool', + networkType: 'string', + signalStrength: 'number', + weakNet: 'bool', + errMsg: 'string', + }, + GetPrivacySettingSuccessCallbackResult: { + needAuthorization: 'bool', + privacyContractName: 'string', + errMsg: 'string', + }, + GetScreenBrightnessSuccessCallbackOption: { + value: 'number', + errMsg: 'string', + }, + GetScreenRecordingStateSuccessCallbackResult: { + state: 'string', + errMsg: 'string', + }, + GetSettingSuccessCallbackResult: { + authSetting: 'AuthSetting', + subscriptionsSetting: 'SubscriptionsSetting', + miniprogramAuthSetting: 'AuthSetting', + errMsg: 'string', + }, + AuthSetting: {}, + SubscriptionsSetting: { + mainSwitch: 'bool', + itemSettings: 'object', + }, + GetStorageInfoSuccessCallbackOption: { + currentSize: 'number', + keys: 'string[]', + limitSize: 'number', + errMsg: 'string', + }, + GetUserInfoSuccessCallbackResult: { + cloudID: 'string', + encryptedData: 'string', + iv: 'string', + rawData: 'string', + signature: 'string', + userInfo: 'UserInfo', + errMsg: 'string', + }, + UserInfo: { + avatarUrl: 'string', + city: 'string', + country: 'string', + gender: 'number', + language: 'string', + nickName: 'string', + province: 'string', + }, + GetUserInteractiveStorageFailCallbackResult: { + errCode: 'number', + errMsg: 'string', + }, + GetUserInteractiveStorageSuccessCallbackResult: { + cloudID: 'string', + encryptedData: 'string', + iv: 'string', + errMsg: 'string', + }, + GetWeRunDataSuccessCallbackResult: { + cloudID: 'string', + encryptedData: 'string', + iv: 'string', + errMsg: 'string', + }, + JoinVoIPChatError: { + errMsg: 'string', + errCode: 'number', + }, + MuteConfig: { + muteEarphone: 'bool', + muteMicrophone: 'bool', + }, + JoinVoIPChatSuccessCallbackResult: { + errCode: 'number', + errMsg: 'string', + openIdList: 'string[]', + }, + RequestFailCallbackErr: { + errMsg: 'string', + errno: 'number', + }, + LoginSuccessCallbackResult: { + code: 'string', + errMsg: 'string', + }, + OnAccelerometerChangeListenerResult: { + x: 'number', + y: 'number', + z: 'number', + }, + OnAddToFavoritesListenerResult: { + disableForward: 'bool', + imageUrl: 'string', + query: 'string', + title: 'string', + }, + OnBLEConnectionStateChangeListenerResult: { + connected: 'bool', + deviceId: 'string', + }, + OnBLEMTUChangeListenerResult: { + deviceId: 'string', + mtu: 'number', + }, + OnBLEPeripheralConnectionStateChangedListenerResult: { + connected: 'bool', + deviceId: 'string', + serverId: 'string', + }, + OnBackgroundFetchDataListenerResult: { + fetchType: 'string', + fetchedData: 'string', + path: 'string', + query: 'string', + scene: 'number', + timeStamp: 'long', + }, + OnBeaconServiceChangeListenerResult: { + available: 'bool', + discovering: 'bool', + }, + OnBeaconUpdateListenerResult: { + beacons: 'BeaconInfo[]', + }, + OnBluetoothAdapterStateChangeListenerResult: { + available: 'bool', + discovering: 'bool', + }, + OnBluetoothDeviceFoundListenerResult: { + devices: 'BlueToothDevice[]', + }, + OnCompassChangeListenerResult: { + accuracy: 'string', + direction: 'number', + }, + OnCopyUrlListenerResult: { + query: 'string', + }, + OnDeviceMotionChangeListenerResult: { + alpha: 'number', + beta: 'number', + gamma: 'number', + }, + OnDeviceOrientationChangeListenerResult: { + value: 'string', + }, + Error: { + message: 'string', + stack: 'string', + }, + OnHandoffListenerResult: { + query: 'string', + }, + OnKeyDownListenerResult: { + code: 'string', + key: 'string', + timeStamp: 'long', + }, + OnKeyboardInputListenerResult: { + value: 'string', + }, + OnKeyboardHeightChangeListenerResult: { + height: 'number', + }, + OnMemoryWarningListenerResult: { + level: 'number', + }, + OnMenuButtonBoundingClientRectWeightChangeListenerResult: { + bottom: 'number', + height: 'number', + left: 'number', + right: 'number', + top: 'number', + width: 'number', + }, + OnMouseDownListenerResult: { + button: 'number', + timeStamp: 'long', + x: 'number', + y: 'number', + }, + OnMouseMoveListenerResult: { + movementX: 'number', + movementY: 'number', + timeStamp: 'long', + x: 'number', + y: 'number', + }, + OnNetworkStatusChangeListenerResult: { + isConnected: 'bool', + networkType: 'string', + }, + OnNetworkWeakChangeListenerResult: { + networkType: 'string', + weakNet: 'bool', + }, + OnScreenRecordingStateChangedListenerResult: { + state: 'string', + }, + OnShareTimelineListenerResult: { + imageUrl: 'string', + imagePreviewUrl: 'string', + imagePreviewUrlId: 'string', + imageUrlId: 'string', + path: 'string', + query: 'string', + title: 'string', + }, + OnShowListenerResult: { + query: 'object', + referrerInfo: 'ResultReferrerInfo', + scene: 'number', + chatType: 'number', + shareTicket: 'string', + }, + ResultReferrerInfo: { + appId: 'string', + extraData: 'object', + }, + OnUnhandledRejectionListenerResult: { + promise: 'string', + reason: 'string', + }, + OnUserCaptureScreenListenerResult: { + query: 'string', + }, + OnVoIPChatInterruptedListenerResult: { + errCode: 'number', + errMsg: 'string', + }, + OnVoIPChatMembersChangedListenerResult: { + errCode: 'number', + errMsg: 'string', + openIdList: 'string[]', + }, + OnVoIPChatSpeakersChangedListenerResult: { + errCode: 'number', + errMsg: 'string', + openIdList: 'string[]', + }, + OnVoIPChatStateChangedListenerResult: { + code: 'number', + data: 'object', + errCode: 'number', + errMsg: 'string', + }, + OnWheelListenerResult: { + deltaX: 'number', + deltaY: 'number', + deltaZ: 'number', + timeStamp: 'long', + x: 'number', + y: 'number', + }, + OnWindowResizeListenerResult: { + windowHeight: 'number', + windowWidth: 'number', + }, + OpenCardRequestInfo: { + cardId: 'string', + code: 'string', + }, + ExtInfoOption: { + url: 'string', + }, + OpenCustomerServiceConversationSuccessCallbackResult: { + path: 'string', + query: 'object', + errMsg: 'string', + }, + OpenSettingSuccessCallbackResult: { + authSetting: 'AuthSetting', + subscriptionsSetting: 'SubscriptionsSetting', + errMsg: 'string', + }, + OperateGameRecorderVideoOption: { + atempo: 'number', + audioMix: 'bool', + bgm: 'string', + desc: 'string', + path: 'string', + query: 'string', + timeRange: 'number[]', + title: 'string', + volume: 'number', + }, + MediaSource: { + url: 'string', + poster: 'string', + type: 'string', + }, + ReportSceneError: { + errMsg: 'string', + errCode: 'number', + }, + ReportSceneFailCallbackErr: { + data: 'object', + errMsg: 'string', + }, + ReportSceneSuccessCallbackResult: { + data: 'object', + errMsg: 'string', + }, + ReportUserBehaviorBranchAnalyticsOption: { + branchId: 'string', + eventType: 'number', + branchDim: 'string', + }, + MidasFriendPaymentError: { + errMsg: 'string', + errCode: 'number', + }, + RequestMidasFriendPaymentSuccessCallbackResult: { + cloudID: 'string', + encryptedData: 'string', + errMsg: 'string', + iv: 'string', + }, + MidasPaymentError: { + errMsg: 'string', + errCode: 'number', + }, + RequestMidasPaymentFailCallbackErr: { + errCode: 'number', + errMsg: 'string', + errno: 'number', + }, + RequestMidasPaymentSuccessCallbackResult: { + errMsg: 'string', + }, + SignData1: { + buyQuantity: 'number', + currencyType: 'string', + goodsPrice: 'number', + mode: 'string', + offerId: 'string', + outTradeNo: 'string', + productId: 'string', + attach: 'string', + env: 'number', + platform: 'string', + zoneId: 'string', + }, + RequestSubscribeMessageFailCallbackResult: { + errCode: 'number', + errMsg: 'string', + }, + RequestSubscribeMessageSuccessCallbackResult: { + anyKeyWord: 'string', + errMsg: 'string', + }, + RequestSubscribeSystemMessageSuccessCallbackResult: { + anyKeyWord: 'string', + errMsg: 'string', + }, + ScanCodeSuccessCallbackResult: { + charSet: 'string', + path: 'string', + rawData: 'string', + result: 'string', + scanType: 'string', + errMsg: 'string', + }, + SetBLEMTUFailCallbackResult: { + mtu: 'number', + }, + SetBLEMTUSuccessCallbackResult: { + mtu: 'number', + errMsg: 'string', + }, + KVData: { + key: 'string', + value: 'string', + }, + ShareAppMessageOption: { + imageUrl: 'string', + imageUrlId: 'string', + path: 'string', + query: 'string', + title: 'string', + toCurrentGroup: 'bool', + }, + ShowActionSheetSuccessCallbackResult: { + tapIndex: 'number', + errMsg: 'string', + }, + ShowModalSuccessCallbackResult: { + cancel: 'bool', + confirm: 'bool', + content: 'string', + errMsg: 'string', + }, + UpdatableMessageFrontEndTemplateInfo: { + parameterList: 'UpdatableMessageFrontEndParameter[]', + templateId: 'string', + }, + UpdatableMessageFrontEndParameter: { + name: 'string', + value: 'string', + }, + VibrateShortFailCallbackResult: { + errMsg: 'string', + }, + CheckGameLiveEnabledSuccessCallbackOption: { + errMsg: 'string', + isEnabled: 'bool', + }, + OnGameLiveStateChangeCallbackResult: { + state: 'string', + feedId: 'string', + }, + OnGameLiveStateChangeCallbackResponse: { + query: 'string', + }, + GameLiveState: { + isLive: 'bool', + }, + GetUserCurrentGameliveInfoSuccessCallbackOption: { + feedIdList: 'string[]', + }, + GetUserGameLiveDetailsSuccessCallbackOption: { + encryptedData: 'string', + iv: 'string', + cloudID: 'string', + feedIdList: 'string[]', + errMsg: 'string', + }, + RequestSubscribeLiveActivitySuccessCallbackResult: { + code: 'string', + errMsg: 'string', + }, + FrameDataOptions: { + data: 'arrayBuffer', + arrayBufferLength: 'number', + height: 'number', + pkDts: 'number', + pkPts: 'number', + width: 'number', + }, +}; diff --git a/Runtime/playable-default/unity-sdk/resType.js.meta b/Runtime/playable-default/unity-sdk/resType.js.meta new file mode 100644 index 000000000..9d8f791f6 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/resType.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: f16aadaf319f3a51483a769f979e776d +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/resTypeOther.js b/Runtime/playable-default/unity-sdk/resTypeOther.js new file mode 100644 index 000000000..9ca8b5a42 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/resTypeOther.js @@ -0,0 +1,89 @@ +export const ResTypeOther = { + Stats: { + lastAccessedTime: 'number', + lastModifiedTime: 'number', + mode: 'number', + size: 'number', + }, + TCPSocketOnMessageListenerResult: { + localInfo: 'LocalInfo', + message: 'arrayBuffer', + remoteInfo: 'RemoteInfo', + }, + LocalInfo: { + address: 'string', + family: 'string', + port: 'number', + }, + RemoteInfo: { + address: 'string', + family: 'string', + port: 'number', + }, + UDPSocketConnectOption: { + address: 'string', + port: 'number', + }, + UDPSocketOnMessageListenerResult: { + localInfo: 'LocalInfo', + message: 'arrayBuffer', + remoteInfo: 'RemoteInfo', + }, + UDPSocketSendOption: { + address: 'string', + message: 'string|arrayBuffer', + port: 'number', + length: 'number', + offset: 'number', + setBroadcast: 'bool', + }, + UDPSocketSendParam: { + address: 'string', + port: 'number', + length: 'number', + offset: 'number', + setBroadcast: 'bool', + }, + CallFunctionResult: { + result: 'string', + requestID: 'string', + errMsg: 'string', + }, + CallContainerResult: { + data: 'string', + statusCode: 'number', + header: 'object', + callID: 'string', + errMsg: 'string', + }, + UploadFileResult: { + fileID: 'string', + statusCode: 'number', + errMsg: 'string', + }, + DownloadFileResult: { + tempFilePath: 'string', + statusCode: 'number', + errMsg: 'string', + }, + GetTempFileURLResult: { + fileList: 'GetTempFileURLResultItem[]', + errMsg: 'string', + }, + GetTempFileURLResultItem: { + fileID: 'string', + tempFileURL: 'string', + maxAge: 'number', + status: 'number', + errMsg: 'string', + }, + DeleteFileResult: { + fileList: 'DeleteFileResultItem[]', + errMsg: 'string', + }, + DeleteFileResultItem: { + fileID: 'string', + status: 'number', + errMsg: 'string', + }, +}; diff --git a/Runtime/playable-default/unity-sdk/resTypeOther.js.meta b/Runtime/playable-default/unity-sdk/resTypeOther.js.meta new file mode 100644 index 000000000..81980d539 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/resTypeOther.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 935a8a2cc706964770dd203b9bc9bcbb +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/response.js b/Runtime/playable-default/unity-sdk/response.js new file mode 100644 index 000000000..f5febd7b7 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/response.js @@ -0,0 +1,74 @@ +/* eslint-disable @typescript-eslint/no-this-alias */ +import moduleHelper from './module-helper'; +export default { + handleText(s, f, c) { + const self = this; + return { + success(res) { + self.textFormat(s, res); + }, + fail(res) { + self.textFormat(f, res); + }, + complete(res) { + self.textFormat(c, res); + }, + }; + }, + handleTextLongBack(s, f, c) { + const self = this; + return { + success(res) { + self.textFormatLongBack(s, res); + }, + fail(res) { + self.textFormatLongBack(f, res); + }, + complete(res) { + self.textFormatLongBack(c, res); + }, + }; + }, + textFormat(id, res) { + if (!id) { + return false; + } + moduleHelper.send('TextResponseCallback', JSON.stringify({ + callbackId: id, + errMsg: res.errMsg, + errCode: res.errCode, + })); + }, + textFormatLongBack(id, res) { + if (!id) { + return false; + } + moduleHelper.send('TextResponseLongCallback', JSON.stringify({ + callbackId: id, + errMsg: res.errMsg, + errCode: res.errCode, + })); + }, + handle(formatFunc, s, f, c) { + return { + success(res) { + if (!s) { + return false; + } + formatFunc(s, res); + }, + fail(res) { + if (!f) { + return false; + } + formatFunc(f, res); + }, + complete(res) { + if (!c) { + return false; + } + formatFunc(c, res); + }, + }; + }, +}; diff --git a/Runtime/playable-default/unity-sdk/response.js.meta b/Runtime/playable-default/unity-sdk/response.js.meta new file mode 100644 index 000000000..2fac099d2 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/response.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 434ae200e2a9a4754ceaa847f34c731a +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/sdk.js b/Runtime/playable-default/unity-sdk/sdk.js new file mode 100644 index 000000000..d1230f719 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/sdk.js @@ -0,0 +1,402 @@ + +import moduleHelper from './module-helper'; +import { uid, formatResponse, formatJsonStr, stringifyRes } from './utils'; +const onEventLists = {}; +let wxOnAddToFavoritesResolveConf; +let wxOnCopyUrlResolveConf; +let wxOnHandoffResolveConf; +let wxOnShareTimelineResolveConf; +let wxOnGameLiveStateChangeResolveConf; +const ClassLists = {}; +const ClassOnEventLists = {}; +function getClassObject(className, id) { + if (!ClassLists[className]) { + ClassLists[className] = {}; + } + const obj = ClassLists[className][id]; + if (!obj) { + console.error(`${className} 不存在:`, id); + } + return obj; +} +; + +// eslint-disable-next-line @typescript-eslint/naming-convention +function WX_OneWayNoFunction(functionName, ...params) { + wx[functionName.replace(/^\w/, a => a.toLowerCase())](...params); +} + + +const onlyReadyResponse = [ + 'getSystemSetting', + 'getAppAuthorizeSetting', +]; +// eslint-disable-next-line @typescript-eslint/naming-convention +function WX_SyncFunction(functionName, ...params) { + return wx[functionName.replace(/^\w/, a => a.toLowerCase())](...params); +} + +// eslint-disable-next-line @typescript-eslint/naming-convention +function WX_ClassOneWayNoFunction(className, functionName, id, ...params) { + const obj = getClassObject(className, id); + if (!obj) { + return; + } + obj[functionName.replace(/^\w/, a => a.toLowerCase())](...params); +} +export default { + WX_OneWayFunction(functionName, successType, failType, completeType, conf, callbackId) { + const lowerFunctionName = functionName.replace(/^\w/, a => a.toLowerCase()); + const config = formatJsonStr(conf); + + if (lowerFunctionName === 'login') { + if (!config.timeout) { + delete config.timeout; + } + } + else if (lowerFunctionName === 'reportScene') { + if (GameGlobal.manager && GameGlobal.manager.setGameStage) { + GameGlobal.manager.setGameStage(config.sceneId); + } + } + wx[lowerFunctionName]({ + ...config, + success(res) { + formatResponse(successType, res); + moduleHelper.send(`${functionName}Callback`, JSON.stringify({ + callbackId, type: 'success', res: JSON.stringify(res), + })); + }, + fail(res) { + formatResponse(failType, res); + moduleHelper.send(`${functionName}Callback`, JSON.stringify({ + callbackId, type: 'fail', res: JSON.stringify(res), + })); + }, + complete(res) { + formatResponse(completeType, res); + moduleHelper.send(`${functionName}Callback`, JSON.stringify({ + callbackId, type: 'complete', res: JSON.stringify(res), + })); + }, + }); + }, + WX_OneWayNoFunction_v(functionName) { + WX_OneWayNoFunction(functionName); + }, + WX_OneWayNoFunction_vs(functionName, param1) { + WX_OneWayNoFunction(functionName, param1); + }, + WX_OneWayNoFunction_vt(functionName, param1) { + const formatParam1 = formatJsonStr(param1); + WX_OneWayNoFunction(functionName, formatParam1); + }, + WX_OneWayNoFunction_vst(functionName, param1, param2) { + const formatParam2 = formatJsonStr(param2); + WX_OneWayNoFunction(functionName, param1, formatParam2); + }, + WX_OneWayNoFunction_vsn(functionName, param1, param2) { + WX_OneWayNoFunction(functionName, param1, param2); + }, + WX_OneWayNoFunction_vnns(functionName, param1, param2, param3) { + WX_OneWayNoFunction(functionName, param1, param2, param3); + }, + WX_OnEventRegister(functionName, resType) { + if (!onEventLists[functionName]) { + onEventLists[functionName] = []; + } + const callback = (res) => { + formatResponse(resType, res); + const resStr = stringifyRes(res); + moduleHelper.send(`_${functionName}Callback`, resStr); + }; + onEventLists[functionName].push(callback); + wx[functionName.replace(/^\w/, a => a.toLowerCase())](callback); + }, + WX_OffEventRegister(functionName) { + (onEventLists[functionName] || []).forEach((v) => { + wx[functionName.replace(/^On/, 'off')](v); + }); + }, + WX_OnAddToFavorites() { + const callback = (res) => { + const resStr = stringifyRes(res); + moduleHelper.send('_OnAddToFavoritesCallback', resStr); + return wxOnAddToFavoritesResolveConf; + }; + wx.onAddToFavorites(callback); + }, + WX_OnAddToFavorites_Resolve(conf) { + try { + wxOnAddToFavoritesResolveConf = formatJsonStr(conf); + return; + } + catch (e) { + } + wxOnAddToFavoritesResolveConf = {}; + }, + WX_OffAddToFavorites() { + wx.offAddToFavorites(); + }, + WX_OnCopyUrl() { + const callback = (res) => { + const resStr = stringifyRes(res); + moduleHelper.send('_OnCopyUrlCallback', resStr); + return wxOnCopyUrlResolveConf; + }; + wx.onCopyUrl(callback); + }, + WX_OnCopyUrl_Resolve(conf) { + try { + wxOnCopyUrlResolveConf = formatJsonStr(conf); + return; + } + catch (e) { + } + wxOnCopyUrlResolveConf = {}; + }, + WX_OffCopyUrl() { + wx.offCopyUrl(); + }, + WX_OnHandoff() { + const callback = (res) => { + const resStr = stringifyRes(res); + moduleHelper.send('_OnHandoffCallback', resStr); + return wxOnHandoffResolveConf; + }; + wx.onHandoff(callback); + }, + WX_OnHandoff_Resolve(conf) { + try { + wxOnHandoffResolveConf = formatJsonStr(conf); + return; + } + catch (e) { + } + wxOnHandoffResolveConf = {}; + }, + WX_OffHandoff() { + wx.offHandoff(); + }, + WX_OnShareTimeline() { + const callback = (res) => { + const resStr = stringifyRes(res); + moduleHelper.send('_OnShareTimelineCallback', resStr); + return wxOnShareTimelineResolveConf; + }; + wx.onShareTimeline(callback); + }, + WX_OnShareTimeline_Resolve(conf) { + try { + wxOnShareTimelineResolveConf = formatJsonStr(conf); + return; + } + catch (e) { + } + wxOnShareTimelineResolveConf = {}; + }, + WX_OffShareTimeline() { + wx.offShareTimeline(); + }, + WX_OnGameLiveStateChange() { + const callback = (res) => { + formatResponse('OnGameLiveStateChangeCallbackResult', res); + const resStr = stringifyRes(res); + moduleHelper.send('_OnGameLiveStateChangeCallback', resStr); + return wxOnGameLiveStateChangeResolveConf; + }; + wx.onGameLiveStateChange(callback); + }, + WX_OnGameLiveStateChange_Resolve(conf) { + try { + wxOnGameLiveStateChangeResolveConf = formatJsonStr(conf); + return; + } + catch (e) { + } + wxOnGameLiveStateChangeResolveConf = {}; + }, + WX_OffGameLiveStateChange() { + wx.offGameLiveStateChange(); + }, + WX_SyncFunction_bs(functionName, param1) { + const res = WX_SyncFunction(functionName, param1); + return res; + }, + WX_SyncFunction_t(functionName, returnType) { + const res = WX_SyncFunction(functionName); + if (onlyReadyResponse.includes(functionName.replace(/^\w/, a => a.toLowerCase()))) { + formatResponse(returnType, JSON.parse(JSON.stringify(res))); + return JSON.stringify(res); + } + formatResponse(returnType, res); + return JSON.stringify(res); + }, + WX_SyncFunction_tt(functionName, returnType, param1) { + const res = WX_SyncFunction(functionName, formatJsonStr(param1)); + formatResponse(returnType, res); + return JSON.stringify(res); + }, + WX_SyncFunction_b(functionName) { + const res = WX_SyncFunction(functionName); + return res; + }, + WX_SyncFunction_bsnn(functionName, param1, param2, param3) { + const res = WX_SyncFunction(functionName, param1, param2, param3); + return res; + }, + WX_SyncFunction_bt(functionName, param1) { + const res = WX_SyncFunction(functionName, formatJsonStr(param1)); + return res; + }, + WX_SyncFunction_nt(functionName, param1) { + const res = WX_SyncFunction(functionName, formatJsonStr(param1)); + return res; + }, + WX_SyncFunction_ss(functionName, param1) { + const res = WX_SyncFunction(functionName, param1); + return res; + }, + WX_SyncFunction_tnn(functionName, returnType, param1, param2) { + const res = WX_SyncFunction(functionName, param1, param2); + formatResponse(returnType, res); + return JSON.stringify(res); + }, + WX_ClassOneWayFunction(functionName, returnType, successType, failType, completeType, conf) { + const config = formatJsonStr(conf); + const callbackId = uid(); + const obj = wx[functionName.replace(/^\w/, a => a.toLowerCase())]({ + ...config, + success(res) { + formatResponse(successType, res); + moduleHelper.send(`${functionName}Callback`, JSON.stringify({ + callbackId, type: 'success', res: JSON.stringify(res), + })); + }, + fail(res) { + formatResponse(failType, res); + moduleHelper.send(`${functionName}Callback`, JSON.stringify({ + callbackId, type: 'fail', res: JSON.stringify(res), + })); + }, + complete(res) { + formatResponse(completeType, res); + moduleHelper.send(`${functionName}Callback`, JSON.stringify({ + callbackId, type: 'complete', res: JSON.stringify(res), + })); + }, + }); + if (!ClassLists[returnType]) { + ClassLists[returnType] = {}; + } + ClassLists[returnType][callbackId] = obj; + return callbackId; + }, + WX_ClassFunction(functionName, returnType, option) { + const obj = wx[functionName.replace(/^\w/, a => a.toLowerCase())](formatJsonStr(option)); + const id = uid(); + if (!ClassLists[returnType]) { + ClassLists[returnType] = {}; + } + ClassLists[returnType][id] = obj; + return id; + }, + WX_ClassSetProperty(className, id, key, value) { + const obj = getClassObject(className, id); + if (!obj) { + return; + } + if (/^\s*(\{.*\}|\[.*\])\s*$/.test(value)) { + try { + const jsonValue = JSON.parse(value); + Object.assign(obj[key], jsonValue); + } + catch (e) { + obj[key] = value; + } + } + else { + obj[key] = value; + } + }, + WX_ClassOnEventFunction(className, functionName, returnType, id, eventName) { + const obj = getClassObject(className, id); + if (!obj) { + return; + } + if (!ClassOnEventLists[className + functionName]) { + ClassOnEventLists[className + functionName] = {}; + } + const callback = (res) => { + if (returnType !== 'string') { + formatResponse(returnType, res); + } + if (!eventName) { + // eslint-disable-next-line no-param-reassign + eventName = ''; + } + const resStr = JSON.stringify({ + callbackId: id + eventName, + res: JSON.stringify(res), + }); + moduleHelper.send(`_${className}${functionName}Callback`, resStr); + }; + if (!ClassOnEventLists[className + functionName][id + eventName]) { + ClassOnEventLists[className + functionName][id + eventName] = []; + } + ClassOnEventLists[className + functionName][id + eventName].push(callback); + // WXVideoDecoder OnEvent 不规范 特殊处理 + if (className === 'WXVideoDecoder') { + obj[functionName.replace(/^\w/, a => a.toLowerCase())](eventName, callback); + } + else { + obj[functionName.replace(/^\w/, a => a.toLowerCase())](callback); + } + }, + WX_ClassOffEventFunction(className, functionName, id, eventName) { + const obj = getClassObject(className, id); + if (!obj) { + return; + } + if (!eventName) { + // eslint-disable-next-line no-param-reassign + eventName = ''; + } + // eslint-disable-next-line no-param-reassign + functionName = functionName.replace(/Off/, 'On'); + if (!ClassOnEventLists[className + functionName][id + eventName]) { + return; + } + ClassOnEventLists[className + functionName][id + eventName].forEach((v) => { + + if (className === 'WXVideoDecoder') { + obj[functionName.replace(/^\w/, (a) => a.toLowerCase())](eventName, v); + } + else { + obj[functionName.replace(/^\w/, (a) => a.toLowerCase())](v); + } + }); + delete ClassOnEventLists[className + functionName][id + eventName]; + }, + WX_ClassOneWayNoFunction_v(className, functionName, id) { + WX_ClassOneWayNoFunction(className, functionName, id); + }, + WX_ClassOneWayNoFunction_vs(className, functionName, id, param1) { + WX_ClassOneWayNoFunction(className, functionName, id, param1); + }, + WX_ClassOneWayNoFunction_t(className, functionName, returnType, id) { + const obj = getClassObject(className, id); + if (!obj) { + return JSON.stringify(formatResponse(returnType)); + } + const res = obj[functionName.replace(/^\w/, a => a.toLowerCase())](); + return JSON.stringify(formatResponse(returnType, res, id)); + }, + WX_ClassOneWayNoFunction_vt(className, functionName, id, param1) { + const formatParam1 = formatJsonStr(param1); + WX_ClassOneWayNoFunction(className, functionName, id, formatParam1); + }, + WX_ClassOneWayNoFunction_vn(className, functionName, id, param1) { + WX_ClassOneWayNoFunction(className, functionName, id, param1); + }, +}; diff --git a/Runtime/playable-default/unity-sdk/sdk.js.meta b/Runtime/playable-default/unity-sdk/sdk.js.meta new file mode 100644 index 000000000..c1fa02a12 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/sdk.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 18bb5483043b48f0ee2ca881daec2cac +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/special-callbacks.js b/Runtime/playable-default/unity-sdk/special-callbacks.js new file mode 100644 index 000000000..770fdee4c --- /dev/null +++ b/Runtime/playable-default/unity-sdk/special-callbacks.js @@ -0,0 +1,41 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +function WX_RegisterUDPSocketOnMessageCallback(_callback) { } +function WX_RegisterTCPSocketOnMessageCallback(_callback) { } +function WX_RegisterOnBLECharacteristicValueChangeCallback(_callback) { } +function WX_RegisterStartGyroscopeCallback(_callback) { } +function WX_RegisterStopGyroscopeCallback(_callback) { } +function WX_RegisterOnGyroscopeChangeCallback(_callback) { } +function WXStorageGetIntSync() { + return 0; +} +function WXStorageSetIntSync() { } +function WXStorageGetFloatSync() { + return 0; +} +function WXStorageSetFloatSync() { } +function WXStorageGetStringSync() { + return ''; +} +function WXStorageSetStringSync() { } +function WXStorageDeleteAllSync() { } +function WXStorageDeleteKeySync() { } +function WXStorageHasKeySync() { + return false; +} +export default { + WX_RegisterUDPSocketOnMessageCallback, + WX_RegisterTCPSocketOnMessageCallback, + WX_RegisterOnBLECharacteristicValueChangeCallback, + WX_RegisterStartGyroscopeCallback, + WX_RegisterStopGyroscopeCallback, + WX_RegisterOnGyroscopeChangeCallback, + WXStorageGetIntSync, + WXStorageSetIntSync, + WXStorageGetFloatSync, + WXStorageSetFloatSync, + WXStorageGetStringSync, + WXStorageSetStringSync, + WXStorageDeleteAllSync, + WXStorageDeleteKeySync, + WXStorageHasKeySync, +}; diff --git a/Runtime/playable-default/unity-sdk/special-callbacks.js.meta b/Runtime/playable-default/unity-sdk/special-callbacks.js.meta new file mode 100644 index 000000000..066c93924 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/special-callbacks.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 0999062082dd208d604173a202d662c6 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/texture.js b/Runtime/playable-default/unity-sdk/texture.js new file mode 100644 index 000000000..ad06d3ebd --- /dev/null +++ b/Runtime/playable-default/unity-sdk/texture.js @@ -0,0 +1,276 @@ +/* eslint-disable no-param-reassign */ +/* eslint-disable no-restricted-properties */ +/* eslint-disable no-plusplus */ +import canvasContext from './canvas-context'; +const downloadedTextures = {}; +const downloadingTextures = {}; +const downloadFailedTextures = {}; +let hasCheckSupportedExtensions = false; + +if (typeof window !== 'undefined' && window.indexedDB) { + Object.defineProperty(window, 'indexedDB', { + get() { + return undefined; + }, + set() { }, + enumerable: true, + configurable: true, + }); +} +const PotList = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]; +const UseDXT5 = '$UseDXT5$'; +const pngPath = GameGlobal.unityNamespace.unityColorSpace && GameGlobal.unityNamespace.unityColorSpace === 'Linear' ? 'lpng' : 'png'; +let isStopDownloadTexture = false; +const cachedDownloadTask = []; +wx.stopDownloadTexture = function () { + isStopDownloadTexture = true; +}; +wx.starDownloadTexture = function () { + isStopDownloadTexture = false; + while (cachedDownloadTask.length > 0) { + const task = cachedDownloadTask.shift(); + if (task) { + mod.WXDownloadTexture(task.path, task.width, task.height, task.callback, task.limitType); + } + } +}; +const mod = { + getSupportedExtensions() { + if (hasCheckSupportedExtensions) { + return GameGlobal.TextureCompressedFormat; + } + const list = canvas + .getContext(GameGlobal.managerConfig.contextConfig.contextType === 2 ? 'webgl2' : 'webgl') + .getSupportedExtensions(); + const noneLimitSupportedTextures = ['']; // 兜底采用png + GameGlobal.TextureCompressedFormat = ''; + if (list.indexOf('WEBGL_compressed_texture_s3tc') !== -1 && UseDXT5) { + GameGlobal.TextureCompressedFormat = 'dds'; + } + if (list.indexOf('WEBGL_compressed_texture_pvrtc') !== -1) { + GameGlobal.TexturePVRTCSupported = true; + GameGlobal.TextureCompressedFormat = 'pvr'; + } + if (list.indexOf('WEBGL_compressed_texture_etc') !== -1) { + GameGlobal.TextureEtc2Supported = true; + noneLimitSupportedTextures.push('etc2'); + GameGlobal.TextureCompressedFormat = 'etc2'; + } + if (list.indexOf('WEBGL_compressed_texture_astc') !== -1) { + noneLimitSupportedTextures.push('astc'); + GameGlobal.TextureCompressedFormat = 'astc'; + } + hasCheckSupportedExtensions = true; + GameGlobal.NoneLimitSupportedTexture = noneLimitSupportedTextures.pop(); + return GameGlobal.TextureCompressedFormat; + }, + getRemoteImageFile(path, width, height, limitType) { + let textureFormat = GameGlobal.TextureCompressedFormat; + if (textureFormat && limitType) { + textureFormat = GameGlobal.NoneLimitSupportedTexture; + } + if (!textureFormat + || (textureFormat === 'pvr' && (width !== height || PotList.indexOf(width) === -1)) + || (textureFormat === 'dds' && (width % 4 !== 0 || height % 4 !== 0))) { + mod.downloadFile(path, width, height); + } + else { + mod.requestFile(path, width, height, textureFormat, limitType); + } + }, + reTryRemoteImageFile(path, width, height, limitType = false) { + const cid = path; + if (!downloadFailedTextures[cid]) { + downloadFailedTextures[cid] = { + count: 0, + path, + width, + height, + limitType, + }; + } + if (downloadFailedTextures[cid].count > 4) { + return; + } + setTimeout(() => { + mod.getRemoteImageFile(path, width, height, limitType); + }, Math.pow(2, downloadFailedTextures[cid].count) * 250); + downloadFailedTextures[cid].count++; + }, + requestFile(path, width, height, format, limitType) { + const cid = path; + const url = `${GameGlobal.manager.assetPath.replace(/\/$/, '')}/Textures/${format}/${width}/${path}.txt`; + const xmlhttp = new GameGlobal.unityNamespace.UnityLoader.UnityCache.XMLHttpRequest(); + xmlhttp.responseType = 'arraybuffer'; + xmlhttp.open('GET', url, true); + xmlhttp.onload = function () { + const res = xmlhttp; + if (res.status === 200) { + downloadedTextures[cid] = { + data: res.response, + tmpFile: '', + }; + downloadingTextures[cid].forEach(v => v()); + delete downloadingTextures[cid]; + delete downloadFailedTextures[cid]; + delete downloadedTextures[cid].data; + } + else { + // err("压缩纹理下载失败!url:"+url); + mod.reTryRemoteImageFile(path, width, height, limitType); + } + }; + xmlhttp.onerror = function () { + // err("压缩纹理下载失败!url:"+url); + mod.reTryRemoteImageFile(path, width, height, limitType); + }; + xmlhttp.setRequestHeader('wechatminigame-skipclean', '1'); + xmlhttp.send(null); + }, + callbackPngFile(path, cid) { + const image = wx.createImage(); + image.crossOrigin = ''; + image.src = path; + image.onload = function () { + downloadedTextures[cid] = { + data: image, + tmpFile: '', + }; + downloadingTextures[cid].forEach(v => v()); + delete downloadingTextures[cid]; + delete downloadFailedTextures[cid]; + delete downloadedTextures[cid]; + }; + }, + downloadFile(path, width, height) { + const url = `${GameGlobal.manager.assetPath.replace(/\/$/, '')}/Textures/${pngPath}/${width}/${path}.png`; + const cid = path; + const cache = GameGlobal.manager.getCachePath(url); + if (cache) { + mod.callbackPngFile(cache, cid); + } + else { + if (GameGlobal.unityNamespace.needCacheTextures) { + const xmlhttp = new GameGlobal.unityNamespace.UnityLoader.UnityCache.XMLHttpRequest(); + xmlhttp.responseType = 'arraybuffer'; + xmlhttp.open('GET', url, true); + xmlhttp.onsave = function (path) { + mod.callbackPngFile(path, cid); + }; + xmlhttp.onerror = function () { + mod.reTryRemoteImageFile(path, width, height); + }; + xmlhttp.setRequestHeader('wechatminigame-skipclean', '1'); + xmlhttp.send(null); + } + else { + const image = wx.createImage(); + image.crossOrigin = ''; + image.src = url; + image.onload = function () { + downloadedTextures[cid] = { + data: image, + tmpFile: '', + }; + downloadingTextures[cid].forEach(v => v()); + delete downloadingTextures[cid]; + delete downloadFailedTextures[cid]; + delete downloadedTextures[cid]; + }; + image.onerror = function () { + mod.reTryRemoteImageFile(path, width, height); + }; + } + } + }, + WXDownloadTexture(path, width, height, callback, limitType = false) { + const width4m = width % 4; + if (width4m !== 0) { + width += 4 - width4m; + } + if (!hasCheckSupportedExtensions) { + mod.getSupportedExtensions(); + } + const cid = path; + if (!cid) { // 可能由于瘦身资源发起的下载此处将直接忽略 + return; + } + /* + if(downloadedTextures[cid]){ + if(downloadedTextures[cid].data){ + callback(); + }else{ + mod.readFile(id,type,callback,width,height); + } + }else */ + if (isStopDownloadTexture) { + cachedDownloadTask.push({ + path, + width, + height, + callback, + limitType, + }); + return; + } + if (downloadingTextures[cid]) { + downloadingTextures[cid].push(callback); + } + else { + downloadingTextures[cid] = [callback]; + mod.getRemoteImageFile(path, width, height, limitType); + } + }, +}; +GameGlobal.DownloadedTextures = downloadedTextures; +GameGlobal.TextureCompressedFormat = ''; // 支持的压缩格式 +GameGlobal.ParalleLDownloadTexture = function (filename) { + filename = filename.replace(GameGlobal.managerConfig.DATA_CDN, '').replace(/^\//, ''); + filename = `/${filename}`; + if (GameGlobal.TEXTURE_BUNDLES[filename]) { + GameGlobal.TEXTURE_BUNDLES[filename].forEach((v) => { + const f = GameGlobal.TextureCompressedFormat; + if (!f) { + const p = `${GameGlobal.manager.assetPath}/Textures/png/${v.w}/${v.p}.png`; + const image = wx.createImage(); + image.crossOrigin = ''; + image.src = p; + } + else if (f !== 'pvr') { + const http = new GameGlobal.unityNamespace.UnityLoader.UnityCache.XMLHttpRequest(); + const p = `${GameGlobal.manager.assetPath}/Textures/${f}/${v.w}/${v.p}.txt`; + http.open('GET', p, true); + http.responseType = 'arraybuffer'; + http.setRequestHeader('wechatminigame-skipclean', '1'); + http.send(); + } + }); + } +}; +export default { + WXDownloadTexture: mod.WXDownloadTexture, +}; +canvasContext.addCreatedListener(() => { + if (GameGlobal.USED_TEXTURE_COMPRESSION) { + mod.getSupportedExtensions(); + if (GameGlobal.TextureCompressedFormat === '' || GameGlobal.TextureCompressedFormat === 'pvr') { + const { platform } = wx.getDeviceInfo ? wx.getDeviceInfo() : wx.getSystemInfoSync(); + if (platform === 'ios') { + wx.showModal({ + title: '提示', + content: '当前操作系统版本过低,建议您升级至最新版本。', + }); + } + } + } + wx.onNetworkStatusChange((res) => { + if (res.isConnected) { + Object.keys(downloadFailedTextures).forEach((key) => { + const v = downloadFailedTextures[key]; + if (v.count > 4) { + mod.getRemoteImageFile(v.path, v.width, v.height, v.limitType); + } + }); + } + }); +}); diff --git a/Runtime/playable-default/unity-sdk/texture.js.meta b/Runtime/playable-default/unity-sdk/texture.js.meta new file mode 100644 index 000000000..34a0cd24d --- /dev/null +++ b/Runtime/playable-default/unity-sdk/texture.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 3e0ab2c180831a037b20c3af33f39d99 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/touch.meta b/Runtime/playable-default/unity-sdk/touch.meta new file mode 100644 index 000000000..352bce930 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/touch.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 78834150e231cd72967e6f36ec76923a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/touch/index.js b/Runtime/playable-default/unity-sdk/touch/index.js new file mode 100644 index 000000000..352e3a0f5 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/touch/index.js @@ -0,0 +1,77 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +import { formatTouchEvent, convertOnTouchStartListenerResultToPointer } from '../utils'; +let wxOnTouchCancelCallback; +let wxOnTouchEndCallback; +let wxOnTouchMoveCallback; +let wxOnTouchStartCallback; +function handleTouchEvent(res, callback) { + const dataPtr = convertOnTouchStartListenerResultToPointer({ + touches: res.touches.map(v => formatTouchEvent(v, res.type)), + changedTouches: res.changedTouches.map(v => formatTouchEvent(v, res.type, 1)), + timeStamp: parseInt(res.timeStamp.toString(), 10), + }); + GameGlobal.Module.dynCall_viii(callback, dataPtr, res.touches.length, res.changedTouches.length); + GameGlobal.Module._free(dataPtr); +} +const OnTouchCancel = (res) => { + handleTouchEvent(res, wxOnTouchCancelCallback); +}; +const OnTouchEnd = (res) => { + handleTouchEvent(res, wxOnTouchEndCallback); +}; +const OnTouchMove = (res) => { + handleTouchEvent(res, wxOnTouchMoveCallback); +}; +const OnTouchStart = (res) => { + handleTouchEvent(res, wxOnTouchStartCallback); +}; +function WX_OnTouchCancel() { + wx.onTouchCancel(OnTouchCancel); +} +function WX_OffTouchCancel() { + wx.offTouchCancel(OnTouchCancel); +} +function WX_OnTouchEnd() { + wx.onTouchEnd(OnTouchEnd); +} +function WX_OffTouchEnd() { + wx.offTouchEnd(OnTouchEnd); +} +function WX_OnTouchMove() { + wx.onTouchMove(OnTouchMove); +} +function WX_OffTouchMove() { + wx.offTouchMove(OnTouchMove); +} +function WX_OnTouchStart() { + wx.onTouchStart(OnTouchStart); +} +function WX_OffTouchStart() { + wx.offTouchStart(OnTouchStart); +} +function WX_RegisterOnTouchCancelCallback(callback) { + wxOnTouchCancelCallback = callback; +} +function WX_RegisterOnTouchEndCallback(callback) { + wxOnTouchEndCallback = callback; +} +function WX_RegisterOnTouchMoveCallback(callback) { + wxOnTouchMoveCallback = callback; +} +function WX_RegisterOnTouchStartCallback(callback) { + wxOnTouchStartCallback = callback; +} +export default { + WX_OnTouchCancel, + WX_OffTouchCancel, + WX_OnTouchEnd, + WX_OffTouchEnd, + WX_OnTouchMove, + WX_OffTouchMove, + WX_OnTouchStart, + WX_OffTouchStart, + WX_RegisterOnTouchCancelCallback, + WX_RegisterOnTouchEndCallback, + WX_RegisterOnTouchMoveCallback, + WX_RegisterOnTouchStartCallback, +}; diff --git a/Runtime/playable-default/unity-sdk/touch/index.js.meta b/Runtime/playable-default/unity-sdk/touch/index.js.meta new file mode 100644 index 000000000..60129c659 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/touch/index.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 055f82055e596db2c328e5826dd1cfd3 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/util.js b/Runtime/playable-default/unity-sdk/util.js new file mode 100644 index 000000000..3108ab050 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/util.js @@ -0,0 +1,177 @@ +import moduleHelper from './module-helper'; +import { launchEventType } from '../plugin-config'; +import { setArrayBuffer, uid } from './utils'; +import '../events'; +export default { + WXReportGameStart() { + GameGlobal.manager.reportCustomLaunchInfo(); + }, + WXReportGameSceneError(sceneId, errorType, errStr, extInfo) { + if (GameGlobal.manager && GameGlobal.manager.reportGameSceneError) { + GameGlobal.manager.reportGameSceneError(sceneId, errorType, errStr, extInfo); + } + }, + WXWriteLog(str) { + if (GameGlobal.manager && GameGlobal.manager.writeLog) { + GameGlobal.manager.writeLog(str); + } + }, + WXWriteWarn(str) { + if (GameGlobal.manager && GameGlobal.manager.writeWarn) { + GameGlobal.manager.writeWarn(str); + } + }, + WXHideLoadingPage() { + if (GameGlobal.manager && GameGlobal.manager.hideLoadingPage) { + GameGlobal.manager.hideLoadingPage(); + } + }, + WXReportUserBehaviorBranchAnalytics(branchId, branchDim, eventType) { + wx.reportUserBehaviorBranchAnalytics({ branchId, branchDim, eventType }); + }, + WXPreloadConcurrent(count) { + if (GameGlobal.manager && GameGlobal.manager.setConcurrent) { + GameGlobal.manager.setConcurrent(count); + } + }, + WXIsCloudTest() { + if (typeof GameGlobal.isTest !== 'undefined' && GameGlobal.isTest) { + return true; + } + return false; + }, + WXUncaughtException(needAbort) { + function currentStackTrace() { + const err = new Error('WXUncaughtException'); + return err; + } + const err = currentStackTrace(); + let fullTrace = err.stack?.toString(); + if (fullTrace) { + const posOfThisFunc = fullTrace.indexOf('WXUncaughtException'); + if (posOfThisFunc !== -1) { + fullTrace = fullTrace.substr(posOfThisFunc); + } + const posOfRaf = fullTrace.lastIndexOf('browserIterationFunc'); + if (posOfRaf !== -1) { + fullTrace = fullTrace.substr(0, posOfRaf); + } + } + const realTimelog = wx.getRealtimeLogManager(); + realTimelog.error(fullTrace); + const logmanager = wx.getLogManager({ level: 0 }); + logmanager.warn(fullTrace); + if (needAbort === true) { + GameGlobal.onCrash(err); + throw err; + } + else { + setTimeout(() => { + throw err; + }, 0); + } + }, + WXCleanAllFileCache() { + if (GameGlobal.manager && GameGlobal.manager.cleanCache) { + const key = uid(); + GameGlobal.manager.cleanAllCache().then((res) => { + moduleHelper.send('CleanAllFileCacheCallback', JSON.stringify({ + callbackId: key, + result: res, + })); + }); + return key; + } + return ''; + }, + WXCleanFileCache(fileSize) { + if (GameGlobal.manager && GameGlobal.manager.cleanCache) { + const key = uid(); + GameGlobal.manager.cleanCache(fileSize).then((res) => { + moduleHelper.send('CleanFileCacheCallback', JSON.stringify({ + callbackId: key, + result: res, + })); + }); + return key; + } + return ''; + }, + WXRemoveFile(path) { + if (GameGlobal.manager && GameGlobal.manager.removeFile && path) { + const key = uid(); + GameGlobal.manager.removeFile(path).then((res) => { + moduleHelper.send('RemoveFileCallback', JSON.stringify({ + callbackId: key, + result: res, + })); + }); + return key; + } + return ''; + }, + WXGetCachePath(url) { + if (GameGlobal.manager && GameGlobal.manager.getCachePath) { + return GameGlobal.manager.getCachePath(url); + } + }, + WXGetPluginCachePath() { + if (GameGlobal.manager && GameGlobal.manager.PLUGIN_CACHE_PATH) { + return GameGlobal.manager.PLUGIN_CACHE_PATH; + } + }, + WXOnLaunchProgress() { + if (GameGlobal.manager && GameGlobal.manager.onLaunchProgress) { + const key = uid(); + // 异步执行,保证C#已经记录这个回调ID + setTimeout(() => { + GameGlobal.manager.onLaunchProgress((e) => { + moduleHelper.send('OnLaunchProgressCallback', JSON.stringify({ + callbackId: key, + res: JSON.stringify(Object.assign({}, e.data, { + type: e.type, + })), + })); + + if (e.type === launchEventType.prepareGame) { + moduleHelper.send('RemoveLaunchProgressCallback', JSON.stringify({ + callbackId: key, + })); + } + }); + }, 0); + return key; + } + return ''; + }, + WXSetDataCDN(path) { + if (GameGlobal.manager && GameGlobal.manager.setDataCDN) { + GameGlobal.manager.setDataCDN(path); + } + }, + WXSetPreloadList(paths) { + if (GameGlobal.manager && GameGlobal.manager.setPreloadList) { + const list = (paths || '').split(',').filter(str => !!str && !!str.trim()); + GameGlobal.manager.setPreloadList(list); + } + }, + WXSetArrayBuffer(buffer, offset, callbackId) { + setArrayBuffer(buffer, offset, callbackId); + }, + WXLaunchOperaBridge(args) { + const res = GameGlobal.events.emit('launchOperaMsgBridgeFromWasm', args); + if (Array.isArray(res) && res.length > 0) { + return res[0]; + } + return null; + }, + WXLaunchOperaBridgeToC(callback, args) { + moduleHelper.send('WXLaunchOperaBridgeToC', JSON.stringify({ + callback, + args, + })); + }, + WX_SetPreferredFramesPerSecond(fps) { + wx.setPreferredFramesPerSecond(fps); + }, +}; diff --git a/Runtime/playable-default/unity-sdk/util.js.meta b/Runtime/playable-default/unity-sdk/util.js.meta new file mode 100644 index 000000000..66d131082 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/util.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: ff7098c0197cca45a9c950d3f05b791b +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/utils.js b/Runtime/playable-default/unity-sdk/utils.js new file mode 100644 index 000000000..1d47e36d0 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/utils.js @@ -0,0 +1,408 @@ +/* eslint-disable no-param-reassign */ +import moduleHelper from './module-helper'; +import { ResType } from './resType'; +import { ResTypeOther } from './resTypeOther'; +Object.assign(ResType, ResTypeOther); +function realUid(length = 20, char = true) { + const soup = `${char ? '' : '!#%()*+,-./:;=?@[]^_`{|}~'}ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`; + const soupLength = soup.length; + const id = []; + for (let i = 0; i < length; i++) { + id[i] = soup.charAt(Math.random() * soupLength); + } + return id.join(''); +} +// 用于调试js代码 +const isDebug = false; +const identifierCache = []; +const clearIdTicker = {}; +const tempCacheObj = {}; +const typeMap = { + array: [], + arrayBuffer: [], + string: '', + number: 0, + bool: false, + object: {}, +}; +const interfaceTypeMap = { + array: 'object', + arrayBuffer: 'object', + string: 'string', + number: 'number', + bool: 'boolean', + object: 'object', +}; +export const uid = () => realUid(20, true); +export function formatIdentifier(identifier, eventType, changed) { + if (changed && clearIdTicker[identifier]) { + clearTimeout(clearIdTicker[identifier]); + delete clearIdTicker[identifier]; + } + let id = identifierCache.indexOf(identifier); + if (id <= -1) { + for (let key = 0; key < identifierCache.length; key++) { + if (identifierCache[key] === null) { + identifierCache[key] = identifier; + id = key; + break; + } + } + } + if (id <= -1) { + identifierCache.push(identifier); + id = identifierCache.length - 1; + } + if (changed && (eventType === 'touchend' || eventType === 'touchcancel')) { + clearIdTicker[identifier] = setTimeout(() => { + identifierCache[id] = null; + delete clearIdTicker[identifier]; + }, 50); + } + return id; +} +export function formatTouchEvent(v, type, changed) { + return { + clientX: v.clientX * window.devicePixelRatio, + clientY: (window.innerHeight - v.clientY) * window.devicePixelRatio, + force: v.force, + identifier: formatIdentifier(v.identifier, type, changed), + pageX: v.pageX * window.devicePixelRatio, + pageY: (window.innerHeight - v.pageY) * window.devicePixelRatio, + }; +} +export function formatResponse(type, data, id) { + if (!data) { + data = {}; + } + if (typeof data !== 'object') { + return {}; + } + const conf = ResType[type]; + if (!conf) { + return data; + } + + Object.keys(conf).forEach((key) => { + if (data[key] === null || typeof data[key] === 'undefined') { + if (typeof typeMap[conf[key]] === 'undefined') { + if (conf[key].indexOf('[]') > -1) { + data[key] = []; + } + else { + data[key] = {}; + if (ResType[conf[key]]) { + formatResponse(conf[key], data[key]); + } + } + } + else { + data[key] = typeMap[conf[key]]; + } + } + else if (conf[key] === 'long') { + data[key] = parseInt(data[key], 10); + } + else if (conf[key] === 'number' && typeof data[key] === 'string') { + data[key] = Number(data[key]); + } + else if (conf[key] === 'string' && typeof data[key] === 'number') { + data[key] = `${data[key]}`; + } + else if (conf[key] === 'string' && typeof data[key] === 'object') { + data[key] = JSON.stringify(data[key]); + } + else if (conf[key] === 'bool' && (typeof data[key] === 'number' || typeof data[key] === 'string')) { + data[key] = !!data[key]; + } + else if (conf[key] === 'arrayBuffer') { + if (id) { + + cacheArrayBuffer(id, data[key]); + data.arrayBufferLength = data[key].byteLength; + data[key] = []; + } + else if (data[key] instanceof ArrayBuffer) { + data[key] = new Uint8Array(data[key]); + data[key] = Array.from(data[key]); + } + else { + data[key] = []; + } + } + else if (typeof data[key] === 'object' && conf[key] === 'object') { + Object.keys(data[key]).forEach((v) => { + if (typeof data[key][v] === 'object') { + data[key][v] = JSON.stringify(data[key][v]); + } + else { + data[key][v] += ''; + } + }); + } + else if (typeof data[key] === 'object' && conf[key]) { + + const array = conf[key].match(/(.+)\[\]/); + if (array) { + for (const itemKey of Object.keys(data[key])) { + if (array[1] === 'string') { + data[key][itemKey] = `${data[key][itemKey]}`; + } + else if (array[1] === 'number') { + data[key][itemKey] = Number(data[key][itemKey]); + } + else { + formatResponse(array[1], data[key][itemKey]); + } + } + } + else { + formatResponse(conf[key], data[key]); + } + } + }); + + if (conf.anyKeyWord) { + return data; + } + + Object.keys(data).forEach((key) => { + if (typeof conf[key] === 'undefined') { + delete data[key]; + } + else { + const getType = interfaceTypeMap[conf[key]]; + if (getType && getType !== typeof data[key]) { + data[key] = typeMap[conf[key]]; + } + } + }); + if ((type === 'SystemInfo' || type === 'WindowInfo') && data.pixelRatio) { + data.pixelRatio = window.devicePixelRatio; + } + return data; +} +export function formatJsonStr(str, type) { + if (!str) { + return {}; + } + if (type === 'string|arrayBuffer') { + return convertBase64ToData(str); + } + try { + const data = JSON.parse(str); + Object.keys(data).forEach((v) => { + if (data[v] === null) { + delete data[v]; + } + }); + if (type) { + const conf = ResType[type]; + if (!conf) { + return data; + } + Object.keys(conf).forEach((key) => { + if (data[key]) { + if (conf[key] === 'arrayBuffer') { + data[key] = new Uint8Array(data[key]).buffer; + } + else if (conf[key] === 'string|arrayBuffer') { + data[key] = convertBase64ToData(data[key]); + } + } + }); + } + return data; + } + catch (e) { + return str; + } +} +function isBase64(str) { + const base64Pattern = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; + return base64Pattern.test(str); +} +function base64ToArrayBuffer(base64) { + const binaryString = atob(base64); + const len = binaryString.length; + const bytes = new Uint8Array(len); + for (let i = 0; i < len; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes.buffer; +} +function convertBase64ToData(input) { + if (isBase64(input)) { + return base64ToArrayBuffer(input); + } + return input; +} +export function cacheArrayBuffer(callbackId, data) { + if (!callbackId || !data) { + return; + } + tempCacheObj[callbackId] = data; +} +export function setArrayBuffer(buffer, offset, callbackId) { + buffer.set(new Uint8Array(tempCacheObj[callbackId]), offset); + delete tempCacheObj[callbackId]; +} +export function getListObject(list, name) { + return (id) => { + if (!list) { + list = {}; + } + const obj = list[id]; + if (!obj) { + console.error(`${name} 不存在:`, id); + } + return obj; + }; +} +export function onEventCallback(list, eventName, id, callbackId) { + if (!list[id]) { + list[id] = []; + } + const callback = (res) => { + const resStr = JSON.stringify({ + callbackId: callbackId || id, + res: JSON.stringify(res), + }); + moduleHelper.send(eventName, resStr); + }; + list[id].push(callback); + return callback; +} +export function offEventCallback(list, callback, id) { + if (!list || !list[id]) { + return; + } + list[id].forEach(callback); + delete list[id]; +} +function allocateAndSet(byteArray) { + const ptr = GameGlobal.Module._malloc(byteArray.length); + GameGlobal.Module.HEAPU8.set(byteArray, ptr); + return ptr; +} + +function convertNumberToPointer(num, ArrayType = Float64Array) { + const byteArray = numberToUint8Array(num, ArrayType); + return allocateAndSet(byteArray); +} +function convertArrayBufferToPointer(arrayBuffer) { + const byteArray = new Uint8Array(arrayBuffer); + return allocateAndSet(byteArray); +} +function convertStringToPointer(str) { + const byteArray = GameGlobal.Module.lengthBytesUTF8(str) + 1; + const ptr = GameGlobal.Module._malloc(byteArray); + GameGlobal.Module.stringToUTF8(str, ptr, byteArray); + return ptr; +} +export function convertDataToPointer(data) { + if (typeof data === 'number') { + return convertNumberToPointer(data); + } + if (typeof data === 'string') { + return convertStringToPointer(data); + } + if (data instanceof ArrayBuffer || typeof data === 'object') { + return convertArrayBufferToPointer(data); + } + return 0; +} + +function numberToUint8Array(num, ArrayType = Float64Array) { + return new Uint8Array(new ArrayType([num]).buffer); +} +function stringToUint8ArrayWithLength(str) { + const strPtr = convertStringToPointer(str); + const strBytesLength = GameGlobal.Module.lengthBytesUTF8(str); + const strBytes = new Uint8Array(GameGlobal.Module.HEAPU8.buffer, strPtr, strBytesLength); + const lengthBytes = new Uint8Array(4); + new DataView(lengthBytes.buffer).setUint32(0, strBytes.length, true); + const result = new Uint8Array(4 + strBytes.length); + result.set(lengthBytes); + result.set(strBytes, 4); + GameGlobal.Module._free(strPtr); + return result; +} +function createUint8ArrayFromByteArrays(byteArrays) { + const totalLength = byteArrays.reduce((sum, byteArray) => sum + byteArray.length, 0); + const result = new Uint8Array(totalLength); + let offset = 0; + byteArrays.forEach((byteArray) => { + result.set(byteArray, offset); + offset += byteArray.length; + }); + return result; +} + +function touchToUint8Array(touch) { + return createUint8ArrayFromByteArrays([ + numberToUint8Array(touch.clientX, Float32Array), + numberToUint8Array(touch.clientY, Float32Array), + numberToUint8Array(touch.force), + numberToUint8Array(touch.identifier, Uint32Array), + numberToUint8Array(touch.pageX, Float32Array), + numberToUint8Array(touch.pageY, Float32Array), + ]); +} +function touchesToUint8Array(touches) { + return createUint8ArrayFromByteArrays(touches.map(touchToUint8Array)); +} +function onTouchStartListenerResultToUint8Array(result) { + return createUint8ArrayFromByteArrays([ + touchesToUint8Array(result.touches), + touchesToUint8Array(result.changedTouches), + numberToUint8Array(result.timeStamp, Uint32Array), + ]); +} +export function convertOnTouchStartListenerResultToPointer(result) { + return allocateAndSet(onTouchStartListenerResultToUint8Array(result)); +} + +function infoToUint8Array(info) { + return createUint8ArrayFromByteArrays([ + stringToUint8ArrayWithLength(info.address), + stringToUint8ArrayWithLength(info.family), + numberToUint8Array(info.port, Uint32Array) + ]); +} +export function convertInfoToPointer(info) { + return allocateAndSet(infoToUint8Array(info)); +} +export function stringifyRes(obj) { + if (!obj) { + return '{}'; + } + return JSON.stringify(obj); +} +export function getDefaultData(canvas, conf) { + const config = formatJsonStr(conf); + if (typeof config.x === 'undefined') { + config.x = 0; + } + if (typeof config.y === 'undefined') { + config.y = 0; + } + if (typeof config.width === 'undefined' || config.width === 0) { + config.width = canvas.width; + } + if (typeof config.height === 'undefined' || config.height === 0) { + config.height = canvas.height; + } + if (typeof config.destWidth === 'undefined' || config.destWidth === 0) { + config.destWidth = canvas.width; + } + if (typeof config.destHeight === 'undefined' || config.destHeight === 0) { + config.destHeight = canvas.height; + } + return config; +} +export function debugLog(...args) { + if (isDebug) { + console.log('[debug]', ...args); + } +} diff --git a/Runtime/playable-default/unity-sdk/utils.js.meta b/Runtime/playable-default/unity-sdk/utils.js.meta new file mode 100644 index 000000000..a4527c7dc --- /dev/null +++ b/Runtime/playable-default/unity-sdk/utils.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 3b5eb5f13f59b0ac80506c438bac4350 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/video.js b/Runtime/playable-default/unity-sdk/video.js new file mode 100644 index 000000000..e81be2bbe --- /dev/null +++ b/Runtime/playable-default/unity-sdk/video.js @@ -0,0 +1,104 @@ +import moduleHelper from './module-helper'; +import { formatJsonStr, getListObject, uid } from './utils'; +const videoList = {}; +const getObject = getListObject(videoList, 'video'); +export default { + WXCreateVideo(conf) { + const id = uid(); + const params = formatJsonStr(conf); + + if (params.underGameView) { + GameGlobal.enableTransparentCanvas = true; + } + videoList[id] = wx.createVideo(params); + return id; + }, + WXVideoSetProperty(id, key, value) { + const obj = getObject(id); + if (!obj) { + return; + } + if (key === 'x' || key === 'y' || key === 'width' || key === 'height') { + obj[key] = +value; + } + else if (key === 'src' || key === 'poster') { + obj[key] = value; + } + }, + WXVideoPlay(id) { + const obj = getObject(id); + if (!obj) { + return; + } + obj.play(); + }, + WXVideoAddListener(id, key) { + const obj = getObject(id); + if (!obj) { + return; + } + obj[key]((e) => { + moduleHelper.send('OnVideoCallback', JSON.stringify({ + callbackId: id, + errMsg: key, + position: e && e.position, + buffered: e && e.buffered, + duration: e && e.duration, + })); + if (key === 'onError') { + GameGlobal.enableTransparentCanvas = false; + console.error(e); + } + }); + }, + WXVideoDestroy(id) { + const obj = getObject(id); + if (!obj) { + return; + } + obj.destroy(); + GameGlobal.enableTransparentCanvas = false; + }, + WXVideoExitFullScreen(id) { + const obj = getObject(id); + if (!obj) { + return; + } + obj.exitFullScreen(); + }, + WXVideoPause(id) { + const obj = getObject(id); + if (!obj) { + return; + } + obj.pause(); + }, + WXVideoRequestFullScreen(id, direction) { + const obj = getObject(id); + if (!obj) { + return; + } + obj.requestFullScreen(direction); + }, + WXVideoSeek(id, time) { + const obj = getObject(id); + if (!obj) { + return; + } + obj.seek(time); + }, + WXVideoStop(id) { + const obj = getObject(id); + if (!obj) { + return; + } + obj.stop(); + }, + WXVideoRemoveListener(id, key) { + const obj = getObject(id); + if (!obj) { + return; + } + obj[key](); + }, +}; diff --git a/Runtime/playable-default/unity-sdk/video.js.meta b/Runtime/playable-default/unity-sdk/video.js.meta new file mode 100644 index 000000000..0871fa296 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/video.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 327a33667f15a37e01905b6455cdf141 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/video.meta b/Runtime/playable-default/unity-sdk/video.meta new file mode 100644 index 000000000..70d2274b9 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/video.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a1557ae769fbd05e5c7cd167be2e460c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/unity-sdk/video/index.js b/Runtime/playable-default/unity-sdk/video/index.js new file mode 100644 index 000000000..c94034672 --- /dev/null +++ b/Runtime/playable-default/unity-sdk/video/index.js @@ -0,0 +1,480 @@ +/* eslint-disable @typescript-eslint/prefer-for-of */ +/* eslint-disable @typescript-eslint/naming-convention */ +import { isH5Renderer, isSupportVideoPlayer, isPc, isDevtools } from '../../check-version'; +import { debugLog } from '../utils'; +let FrameworkData = null; + +const isWebVideo = (isH5Renderer && !GameGlobal.isIOSHighPerformanceModePlus) || isPc || isDevtools; +const needCache = true; +const cacheVideoDecoder = []; +const supportVideoFrame = !!GameGlobal.isIOSHighPerformanceModePlus; +const videoInstances = {}; +function _JS_Video_CanPlayFormat(format, data) { + + + FrameworkData = data; + return !!isSupportVideoPlayer; +} +let videoInstanceIdCounter = 0; +function dynCall_vi(...args) { + if (FrameworkData) { + FrameworkData.dynCall_vi(...args); + } +} +function dynCall_vii(...args) { + if (FrameworkData) { + FrameworkData.dynCall_vii(...args); + } +} +function jsVideoEnded() { + debugLog('jsVideoEnded'); + // @ts-ignore + if (this.onendedCallback) { + // @ts-ignore + dynCall_vi(this.onendedCallback, this.onendedRef); + } +} +function _JS_Video_Create(url) { + let source = ''; + if (FrameworkData) { + source = FrameworkData.UTF8ToString(url); + } + debugLog('_JS_Video_Create', source); + if (isWebVideo) { + // @ts-ignore + const video = GameGlobal.manager.createWKVideo(source, FrameworkData.GLctx); + // eslint-disable-next-line no-plusplus + videoInstances[++videoInstanceIdCounter] = video; + } + else { + let videoDecoder; + if (cacheVideoDecoder.length > 0) { + videoDecoder = cacheVideoDecoder.pop(); + } + else { + // @ts-ignore 8.0.38客户端+3.0.0基础库,才能正常使用type参数 + videoDecoder = wx.createVideoDecoder({ + type: 'wemedia', + }); + } + // eslint-disable-next-line no-plusplus + const videoInstance = { + videoDecoder, + videoWidth: 0, + videoHeight: 0, + isReady: false, + stoped: false, + paused: false, + ended: false, + seeking: false, + duration: 1, + }; + // eslint-disable-next-line no-plusplus + videoInstances[++videoInstanceIdCounter] = videoInstance; + + videoDecoder.remove(); + videoDecoder.on('start', (res) => { + debugLog('wxVideoDecoder start:', res); + videoInstance.paused = false; + videoInstance.stoped = false; + if (!videoInstance.isReady) { + if (res.video && res.video.duration) { + videoInstance.duration = res.video.duration / 1000; + } + videoInstance.videoWidth = res.width ?? 0; + videoInstance.videoHeight = res.height ?? 0; + videoInstance.isReady = true; + videoDecoder.stop(); + } + }); + videoDecoder.on('stop', (res) => { + debugLog('wxVideoDecoder stop:', res); + videoInstance.stoped = true; + }); + videoDecoder.on('bufferchange', (res) => { + debugLog('wxVideoDecoder bufferchange:', res); + }); + videoDecoder.on('ended', (res) => { + debugLog('wxVideoDecoder ended:', res); + if (videoInstance.loop) { + videoInstance.seek(0); + } + else { + videoInstance.ended = true; + videoInstance.onended?.(); + } + }); + // @ts-ignore + videoDecoder.on('frame', (res) => { + // @ts-ignore + videoInstance.currentTime = res.pts / 1000; + + if (supportVideoFrame) { + + videoInstance.frameData?.close?.(); + } + videoInstance.frameData = res; + }); + const startOption = { + source, + }; + if (supportVideoFrame) { + startOption.videoDataType = 2; + } + videoInstance.play = () => { + if (videoInstance.seeking) { + videoInstance.seeking = false; + } + if (videoInstance.paused) { + videoInstance.paused = false; + videoDecoder.wait(false); + } + else { + videoDecoder.start(startOption); + } + }; + videoInstance.pause = () => { + videoDecoder.wait(true); + videoInstance.paused = true; + }; + videoInstance.seek = (time) => { + // @ts-ignore + videoDecoder.avSync.seek({ stamp: time }); + videoInstance.seeking = true; + videoDecoder.emitter.emit('seek', {}); + }; + videoInstance.play(); + videoInstance.destroy = () => { + if (needCache) { + videoDecoder.stop(); + cacheVideoDecoder.push(videoDecoder); + } + else { + videoDecoder.remove(); + } + if (videoInstance.loopEndPollInterval) { + clearInterval(videoInstance.loopEndPollInterval); + } + delete videoInstance.videoDecoder; + delete videoInstance.onendedCallback; + delete videoInstance.frameData; + videoInstance.stoped = false; + videoInstance.paused = false; + videoInstance.ended = false; + videoInstance.seeking = false; + videoInstance.currentTime = 0; + videoInstance.onended = null; + }; + } + return videoInstanceIdCounter; +} +function _JS_Video_Destroy(video) { + debugLog('_JS_Video_Destroy', video); + videoInstances[video].destroy(); + delete videoInstances[video]; +} +function _JS_Video_Duration(video) { + return videoInstances[video].duration; +} +function _JS_Video_EnableAudioTrack(video, trackIndex, enabled) { + const v = videoInstances[video]; + + if (!v.enabledTracks) { + v.enabledTracks = []; + } + while (v.enabledTracks.length <= trackIndex) { + v.enabledTracks.push(true); + } + v.enabledTracks[trackIndex] = enabled; + const tracks = v.audioTracks; + if (!tracks) { + return; + } + const track = tracks[trackIndex]; + if (track) { + track.enabled = !!enabled; + } +} +function _JS_Video_GetAudioLanguageCode(video, trackIndex) { + + const tracks = videoInstances[video].audioTracks; + if (!tracks) { + return ''; + } + const track = tracks[trackIndex]; + return track ? track.language : ''; +} +function _JS_Video_GetNumAudioTracks(video) { + const tracks = videoInstances[video].audioTracks; + // console.log('_JS_Video_GetNumAudioTracks', tracks); + return tracks ? tracks.length : 1; +} +function _JS_Video_Height(video) { + return videoInstances[video].videoHeight; +} +function _JS_Video_IsPlaying(video) { + if (isWebVideo) { + const v = videoInstances[video]; + return v.isPlaying; + } + const v = videoInstances[video]; + return v.isReady && !v.stoped && !v.paused && !v.ended; +} +function _JS_Video_IsReady(video) { + const v = videoInstances[video]; + return !!v.isReady; +} +function _JS_Video_IsSeeking(video) { + const v = videoInstances[video]; + return !!v.seeking; +} +function _JS_Video_Pause(video) { + debugLog('_JS_Video_Pause'); + const v = videoInstances[video]; + if (v.loopEndPollInterval) { + clearInterval(v.loopEndPollInterval); + } + v.pause(); +} +function _JS_Video_SetLoop(video, loop = false) { + debugLog('_JS_Video_SetLoop', video, loop); + const v = videoInstances[video]; + if (v.loopEndPollInterval) { + clearInterval(v.loopEndPollInterval); + } + v.loop = loop; + if (loop) { + + v.loopEndPollInterval = setInterval(() => { + if (typeof v.currentTime !== 'undefined' && typeof v.lastSeenPlaybackTime !== 'undefined') { + const cur = Math.floor(v.currentTime); + const last = Math.floor(v.lastSeenPlaybackTime); + if (cur < last) { + const dur = v.duration; + const margin = 0.2; + const closeToBegin = margin * dur; + const closeToEnd = dur - closeToBegin; + if (cur < closeToBegin && last > closeToEnd) { + jsVideoEnded.apply(v); + } + } + } + v.lastSeenPlaybackTime = v.currentTime; + }, 1e3 / 30); + v.lastSeenPlaybackTime = v.currentTime; + v.onended = null; + } + else { + v.onended = jsVideoEnded; + } +} +function jsVideoAllAudioTracksAreDisabled(v) { + debugLog('jsVideoAllAudioTracksAreDisabled'); + if (!v.enabledTracks) { + return false; + } + for (let i = 0; i < v.enabledTracks.length; ++i) { + if (v.enabledTracks[i]) { + return false; + } + } + return true; +} +function _JS_Video_Play(video, muted) { + debugLog('_JS_Video_Play', video, muted); + const v = videoInstances[video]; + v.muted = muted || jsVideoAllAudioTracksAreDisabled(v); + v.play(); + _JS_Video_SetLoop(video, v.loop); +} +function _JS_Video_Seek(video, time) { + debugLog('_JS_Video_Seek', video, time); + const v = videoInstances[video]; + v.seek(time); +} +function _JS_Video_SetEndedHandler(video, ref, onended) { + debugLog('_JS_Video_SetEndedHandler', video, ref, onended); + const v = videoInstances[video]; + v.onendedCallback = onended; + v.onendedRef = ref; +} +function _JS_Video_SetErrorHandler(video, ref, onerror) { + debugLog('_JS_Video_SetErrorHandler', video, ref, onerror); + if (isWebVideo) { + videoInstances[video].on('error', (errMsg) => { + debugLog('video error:', errMsg); + dynCall_vii(onerror, ref, errMsg); + }); + } +} +function _JS_Video_SetMute(video, muted) { + debugLog('_JS_Video_SetMute', video, muted); + const v = videoInstances[video]; + v.muted = muted || jsVideoAllAudioTracksAreDisabled(v); +} +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function _JS_Video_SetPlaybackRate(video, rate) { + + + + + + + return; + + +} +function _JS_Video_SetReadyHandler(video, ref, onready) { + debugLog('_JS_Video_SetReadyHandler', video, ref, onready); + const v = videoInstances[video]; + if (isWebVideo) { + v.on('canplay', () => { + dynCall_vi(onready, ref); + }); + } + else { + const fn = () => { + console.log('_JS_Video_SetReadyHandler onCanPlay'); + dynCall_vi(onready, ref); + v.videoDecoder?.off('bufferchange', fn); + }; + v.videoDecoder?.on('bufferchange', fn); + } +} +function _JS_Video_SetSeekedOnceHandler(video, ref, onseeked) { + debugLog('_JS_Video_SetSeekedOnceHandler', video, ref, onseeked); + const v = videoInstances[video]; + if (isWebVideo) { + v.on('seek', () => { + dynCall_vi(onseeked, ref); + }); + } + else { + v.videoDecoder?.on('seek', () => { + dynCall_vi(onseeked, ref); + }); + } +} +function _JS_Video_SetVolume(video, volume) { + debugLog('_JS_Video_SetVolume'); + videoInstances[video].volume = volume; +} +function _JS_Video_Time(video) { + return videoInstances[video].currentTime; +} +function _JS_Video_UpdateToTexture(video, tex) { + + const v = videoInstances[video]; + if (!(v.videoWidth > 0 && v.videoHeight > 0)) { + return false; + } + if (v.lastUpdateTextureTime === v.currentTime) { + return false; + } + v.lastUpdateTextureTime = v.currentTime; + if (!FrameworkData) { + return false; + } + const { GL, GLctx } = FrameworkData; + GLctx.pixelStorei(GLctx.UNPACK_FLIP_Y_WEBGL, true); + + + const internalFormat = GLctx.RGBA; + const format = GLctx.RGBA; + const width = v.videoWidth; + const height = v.videoHeight; + if (v.previousUploadedWidth !== width || v.previousUploadedHeight !== height) { + GLctx.deleteTexture(GL.textures[tex]); + const t = GLctx.createTexture(); + t.name = tex; + GL.textures[tex] = t; + GLctx.bindTexture(GLctx.TEXTURE_2D, t); + GLctx.texParameteri(GLctx.TEXTURE_2D, GLctx.TEXTURE_WRAP_S, GLctx.CLAMP_TO_EDGE); + GLctx.texParameteri(GLctx.TEXTURE_2D, GLctx.TEXTURE_WRAP_T, GLctx.CLAMP_TO_EDGE); + GLctx.texParameteri(GLctx.TEXTURE_2D, GLctx.TEXTURE_MIN_FILTER, GLctx.LINEAR); + if (isWebVideo) { + v.render(); + } + else { + + const data = v.frameData?.data; + const source = supportVideoFrame ? data : new Uint8ClampedArray(data); + + if (supportVideoFrame) { + GLctx.texImage2D(GLctx.TEXTURE_2D, 0, internalFormat, format, GLctx.UNSIGNED_BYTE, source); + } + else { + GLctx.texImage2D(GLctx.TEXTURE_2D, 0, internalFormat, v.videoWidth, v.videoHeight, 0, format, GLctx.UNSIGNED_BYTE, source); + } + } + v.previousUploadedWidth = width; + v.previousUploadedHeight = height; + } + else { + GLctx.bindTexture(GLctx.TEXTURE_2D, GL.textures[tex]); + if (isWebVideo) { + v.render(); + } + else { + const data = v.frameData?.data; + const source = supportVideoFrame ? data : new Uint8ClampedArray(data); + + if (supportVideoFrame) { + GLctx.texImage2D(GLctx.TEXTURE_2D, 0, internalFormat, format, GLctx.UNSIGNED_BYTE, source); + } + else { + GLctx.texImage2D(GLctx.TEXTURE_2D, 0, internalFormat, v.videoWidth, v.videoHeight, 0, format, GLctx.UNSIGNED_BYTE, source); + } + } + } + GLctx.pixelStorei(GLctx.UNPACK_FLIP_Y_WEBGL, false); + return true; +} +function _JS_Video_Width(video) { + return videoInstances[video].videoWidth; +} +function _JS_Video_SetSeekedHandler(video, ref, onseeked) { + const v = videoInstances[video]; + if (isWebVideo) { + v.on('seek', () => { + dynCall_vi(onseeked, ref); + }); + } + else { + v.videoDecoder?.on('seek', () => { + dynCall_vi(onseeked, ref); + }); + } +} +function _JS_Video_GetPlaybackRate(video) { + return videoInstances[video].playbackRate; +} +export default { + _JS_Video_CanPlayFormat, + _JS_Video_Create, + _JS_Video_Destroy, + _JS_Video_Duration, + _JS_Video_EnableAudioTrack, + _JS_Video_GetAudioLanguageCode, + _JS_Video_GetNumAudioTracks, + _JS_Video_Height, + _JS_Video_IsPlaying, + _JS_Video_IsReady, + _JS_Video_IsSeeking, + _JS_Video_Pause, + _JS_Video_SetLoop, + _JS_Video_Play, + _JS_Video_Seek, + _JS_Video_SetEndedHandler, + _JS_Video_SetErrorHandler, + _JS_Video_SetMute, + _JS_Video_SetPlaybackRate, + _JS_Video_SetReadyHandler, + _JS_Video_SetSeekedOnceHandler, + _JS_Video_SetVolume, + _JS_Video_Time, + _JS_Video_UpdateToTexture, + _JS_Video_Width, + _JS_Video_SetSeekedHandler, + _JS_Video_GetPlaybackRate, +}; diff --git a/Runtime/playable-default/unity-sdk/video/index.js.meta b/Runtime/playable-default/unity-sdk/video/index.js.meta new file mode 100644 index 000000000..9eee9e94e --- /dev/null +++ b/Runtime/playable-default/unity-sdk/video/index.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 7f00b8e4052c34818798ac576ec9ea72 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/wasmcode.meta b/Runtime/playable-default/wasmcode.meta new file mode 100644 index 000000000..90bc888c7 --- /dev/null +++ b/Runtime/playable-default/wasmcode.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ef98c0255e2b715fe9875b5f26216aaf +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/wasmcode/game.js b/Runtime/playable-default/wasmcode/game.js new file mode 100644 index 000000000..e69de29bb diff --git a/Runtime/playable-default/wasmcode/game.js.meta b/Runtime/playable-default/wasmcode/game.js.meta new file mode 100644 index 000000000..51579d243 --- /dev/null +++ b/Runtime/playable-default/wasmcode/game.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b008f789bb8a47a8022207c331fd3aa9 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/playable-default/weapp-adapter.js b/Runtime/playable-default/weapp-adapter.js new file mode 100644 index 000000000..1ad847b95 --- /dev/null +++ b/Runtime/playable-default/weapp-adapter.js @@ -0,0 +1,1650 @@ +// @ts-nocheck +import { formatIdentifier } from './unity-sdk/utils'; +/* eslint-disable */ +const isWK = false; +// try{ +// isWK = wx.getSystemInfoSync().renderer == 'h5'; +// }catch(e){ +// isWK = typeof(window)!='undefined' && window.XMLHttpRequest; +// } +/** ****/ (function (modules) { + /** ****/ // The module cache + /** ****/ const installedModules = {}; + /** ****/ // The require function + /** ****/ function __webpack_require__(moduleId) { + /** ****/ // Check if module is in cache + /** ****/ if (installedModules[moduleId]) + /** ****/ return installedModules[moduleId].exports; + /** ****/ // Create a new module (and put it into the cache) + /** ****/ const module = installedModules[moduleId] = { + /** ****/ exports: {}, + /** ****/ id: moduleId, + /** ****/ loaded: false, + /** ****/ + }; + /** ****/ // Execute the module function + /** ****/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + /** ****/ // Flag the module as loaded + /** ****/ module.loaded = true; + /** ****/ // Return the exports of the module + /** ****/ return module.exports; + /** ****/ + } + /** ****/ // expose the modules object (__webpack_modules__) + /** ****/ __webpack_require__.m = modules; + /** ****/ // expose the module cache + /** ****/ __webpack_require__.c = installedModules; + /** ****/ // __webpack_public_path__ + /** ****/ __webpack_require__.p = ''; + /** ****/ // Load entry module and return exports + /** ****/ return __webpack_require__(0); + /** ****/ +}([ + /* 0 */ + /***/ (function (module, exports, __webpack_require__) { + 'use strict'; + const _window2 = __webpack_require__(1); + const _window = _interopRequireWildcard(_window2); + const _HTMLElement = __webpack_require__(5); + const _HTMLElement2 = _interopRequireDefault(_HTMLElement); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + const newObj = {}; + if (obj != null) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) + newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + const global = GameGlobal; + function inject() { + _window.addEventListener = function (type, listener) { + _window.document.addEventListener(type, listener); + }; + _window.removeEventListener = function (type, listener) { + _window.document.removeEventListener(type, listener); + }; + if (_window.canvas) { + _window.canvas.addEventListener = _window.addEventListener; + _window.canvas.removeEventListener = _window.removeEventListener; + } + const { platform } = wx.getDeviceInfo ? wx.getDeviceInfo() : wx.getSystemInfoSync(); + // 开发者工具无法重定义 window + if (platform === 'devtools') { + for (const key in _window) { + const descriptor = Object.getOwnPropertyDescriptor(global, key); + if (!descriptor || descriptor.configurable === true) { + Object.defineProperty(window, key, { + value: _window[key], + }); + } + } + for (const _key in _window.document) { + const _descriptor = Object.getOwnPropertyDescriptor(global.document, _key); + if (!_descriptor || _descriptor.configurable === true) { + Object.defineProperty(global.document, _key, { + value: _window.document[_key], + }); + } + } + window.parent = window; + } + else { + for (const _key2 in _window) { + global[_key2] = _window[_key2]; + } + global.window = _window; + window = global; + window.top = window.parent = window; + } + } + if (!GameGlobal.__isAdapterInjected) { + GameGlobal.__isAdapterInjected = true; + inject(); + } + /***/ + }), + /* 1 */ + /***/ (function (module, exports, __webpack_require__) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + exports.cancelAnimationFrame = exports.requestAnimationFrame = exports.clearInterval = exports.clearTimeout = exports.setInterval = exports.setTimeout = exports.canvas = exports.location = exports.localStorage = exports.HTMLElement = exports.FileReader = exports.Audio = exports.Image = exports.WebSocket = /* exports.XMLHttpRequest =*/ exports.navigator = exports.document = undefined; + if (!isWK) { + exports.XMLHttpRequest = undefined; + } + const _WindowProperties = __webpack_require__(2); + Object.keys(_WindowProperties).forEach((key) => { + if (key === 'default' || key === '__esModule') + return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _WindowProperties[key]; + }, + }); + }); + const _constructor = __webpack_require__(4); + Object.keys(_constructor).forEach((key) => { + if (key === 'default' || key === '__esModule') + return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _constructor[key]; + }, + }); + }); + const _Canvas = __webpack_require__(10); + const _Canvas2 = _interopRequireDefault(_Canvas); + const _document2 = __webpack_require__(11); + const _document3 = _interopRequireDefault(_document2); + const _navigator2 = __webpack_require__(18); + const _navigator3 = _interopRequireDefault(_navigator2); + const _XMLHttpRequest2 = __webpack_require__(19); + const _XMLHttpRequest3 = _interopRequireDefault(_XMLHttpRequest2); + const _WebSocket2 = __webpack_require__(20); + const _WebSocket3 = _interopRequireDefault(_WebSocket2); + const _Image2 = __webpack_require__(12); + const _Image3 = _interopRequireDefault(_Image2); + const _Audio2 = __webpack_require__(13); + const _Audio3 = _interopRequireDefault(_Audio2); + const _FileReader2 = __webpack_require__(21); + const _FileReader3 = _interopRequireDefault(_FileReader2); + const _HTMLElement2 = __webpack_require__(5); + const _HTMLElement3 = _interopRequireDefault(_HTMLElement2); + const _localStorage2 = __webpack_require__(22); + const _localStorage3 = _interopRequireDefault(_localStorage2); + const _location2 = __webpack_require__(23); + const _location3 = _interopRequireDefault(_location2); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + exports.document = _document3.default; + exports.navigator = _navigator3.default; + if (!isWK) { + exports.XMLHttpRequest = _XMLHttpRequest3.default; + } + // exports.XMLHttpRequest = _XMLHttpRequest3.default; + exports.WebSocket = _WebSocket3.default; + exports.Image = _Image3.default; + exports.Audio = _Audio3.default; + exports.FileReader = _FileReader3.default; + exports.HTMLElement = _HTMLElement3.default; + exports.localStorage = _localStorage3.default; + exports.location = _location3.default; + // 模拟web中的CustomEvent接口 + function CustomEvent(event, params) { + params = params || { + bubbles: false, + cancelable: false, + detail: undefined, + }; + const evt = { + type: event, + bubbles: params.bubbles, + cancelable: params.cancelable, + detail: params.detail, + }; + return evt; + } + ; + exports.CustomEvent = CustomEvent; + // 暴露全局的 canvas + const canvas = new _Canvas2.default(); + exports.canvas = canvas; + exports.setTimeout = setTimeout; + exports.setInterval = setInterval; + exports.clearTimeout = clearTimeout; + exports.clearInterval = clearInterval; + exports.requestAnimationFrame = requestAnimationFrame; + exports.cancelAnimationFrame = cancelAnimationFrame; + /***/ + }), + /* 2 */ + /***/ (function (module, exports, __webpack_require__) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + exports.performance = exports.ontouchend = exports.ontouchmove = exports.ontouchstart = exports.screen = exports.devicePixelRatio = exports.innerHeight = exports.innerWidth = undefined; + const _performance2 = __webpack_require__(3); + const _performance3 = _interopRequireDefault(_performance2); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + const { screenWidth, screenHeight, pixelRatio } = wx.getWindowInfo ? wx.getWindowInfo() : wx.getSystemInfoSync(); + const innerWidth = exports.innerWidth = screenWidth; + const innerHeight = exports.innerHeight = screenHeight; + exports.devicePixelRatio = pixelRatio; + const screen = exports.screen = { + availWidth: innerWidth, + availHeight: innerHeight, + }; + const ontouchstart = exports.ontouchstart = null; + const ontouchmove = exports.ontouchmove = null; + const ontouchend = exports.ontouchend = null; + exports.performance = _performance3.default; + /***/ + }), + /* 3 */ + /***/ (function (module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + let performance = void 0; + let ori_performance = wx.getPerformance(); + const initTime = Date.now(); + const ori_initTime = ori_performance.now(); + const clientPerfAdapter = Object.assign({}, { + now: function now() { + if (GameGlobal.unityNamespace.isDevelopmentBuild + && GameGlobal.unityNamespace.isProfilingBuild + && !GameGlobal.unityNamespace.isDevtools + && !GameGlobal.isIOSHighPerformanceMode) { + // 由于wx.getPerformance()获取到的是微秒级,因此这里需要/1000.0,进行单位的统一 + return (ori_performance.now() - ori_initTime) * 0.001; + } + return (Date.now() - initTime); + }, + }); + performance = clientPerfAdapter; + exports.default = performance; + /***/ + }), + /* 4 */ + /***/ (function (module, exports, __webpack_require__) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + exports.HTMLCanvasElement = exports.HTMLImageElement = undefined; + const _HTMLElement3 = __webpack_require__(5); + const _HTMLElement4 = _interopRequireDefault(_HTMLElement3); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return call && (typeof call === 'object' || typeof call === 'function') ? call : self; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError(`Super expression must either be null or a function, not ${typeof superClass}`); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); + if (superClass) + Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + const HTMLImageElement = exports.HTMLImageElement = (function (_HTMLElement) { + _inherits(HTMLImageElement, _HTMLElement); + function HTMLImageElement() { + _classCallCheck(this, HTMLImageElement); + return _possibleConstructorReturn(this, (HTMLImageElement.__proto__ || Object.getPrototypeOf(HTMLImageElement)).call(this, 'img')); + } + return HTMLImageElement; + }(_HTMLElement4.default)); + const HTMLCanvasElement = exports.HTMLCanvasElement = (function (_HTMLElement2) { + _inherits(HTMLCanvasElement, _HTMLElement2); + function HTMLCanvasElement() { + _classCallCheck(this, HTMLCanvasElement); + return _possibleConstructorReturn(this, (HTMLCanvasElement.__proto__ || Object.getPrototypeOf(HTMLCanvasElement)).call(this, 'canvas')); + } + return HTMLCanvasElement; + }(_HTMLElement4.default)); + /***/ + }), + /* 5 */ + /***/ (function (module, exports, __webpack_require__) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + const _createClass = (function () { + function defineProperties(target, props) { + for (let i = 0; i < props.length; i++) { + const descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) + descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + return function (Constructor, protoProps, staticProps) { + if (protoProps) + defineProperties(Constructor.prototype, protoProps); + if (staticProps) + defineProperties(Constructor, staticProps); + return Constructor; + }; + }()); + const _Element2 = __webpack_require__(6); + const _Element3 = _interopRequireDefault(_Element2); + const _util = __webpack_require__(9); + const _WindowProperties = __webpack_require__(2); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return call && (typeof call === 'object' || typeof call === 'function') ? call : self; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError(`Super expression must either be null or a function, not ${typeof superClass}`); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); + if (superClass) + Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + const HTMLElement = (function (_Element) { + _inherits(HTMLElement, _Element); + function HTMLElement() { + const tagName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + _classCallCheck(this, HTMLElement); + const _this = _possibleConstructorReturn(this, (HTMLElement.__proto__ || Object.getPrototypeOf(HTMLElement)).call(this)); + _this.className = ''; + _this.childern = []; + _this.style = { + width: `${_WindowProperties.innerWidth}px`, + height: `${_WindowProperties.innerHeight}px`, + }; + _this.insertBefore = _util.noop; + _this.innerHTML = ''; + _this.tagName = tagName.toUpperCase(); + return _this; + } + _createClass(HTMLElement, [{ + key: 'setAttribute', + value: function setAttribute(name, value) { + this[name] = value; + }, + }, { + key: 'getAttribute', + value: function getAttribute(name) { + return this[name]; + }, + }, { + key: 'getBoundingClientRect', + value: function getBoundingClientRect() { + return { + top: 0, + left: 0, + width: _WindowProperties.innerWidth, + height: _WindowProperties.innerHeight, + }; + }, + }, { + key: 'focus', + value: function focus() { }, + }, { + key: 'clientWidth', + get: function get() { + const ret = parseInt(this.style.fontSize, 10) * this.innerHTML.length; + return Number.isNaN(ret) ? 0 : ret; + }, + }, { + key: 'clientHeight', + get: function get() { + const ret = parseInt(this.style.fontSize, 10); + return Number.isNaN(ret) ? 0 : ret; + }, + }]); + return HTMLElement; + }(_Element3.default)); + exports.default = HTMLElement; + /***/ + }), + /* 6 */ + /***/ (function (module, exports, __webpack_require__) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + const _Node2 = __webpack_require__(7); + const _Node3 = _interopRequireDefault(_Node2); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return call && (typeof call === 'object' || typeof call === 'function') ? call : self; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError(`Super expression must either be null or a function, not ${typeof superClass}`); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); + if (superClass) + Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + const ELement = (function (_Node) { + _inherits(ELement, _Node); + function ELement() { + _classCallCheck(this, ELement); + const _this = _possibleConstructorReturn(this, (ELement.__proto__ || Object.getPrototypeOf(ELement)).call(this)); + _this.className = ''; + _this.children = []; + return _this; + } + return ELement; + }(_Node3.default)); + exports.default = ELement; + /***/ + }), + /* 7 */ + /***/ (function (module, exports, __webpack_require__) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + const _createClass = (function () { + function defineProperties(target, props) { + for (let i = 0; i < props.length; i++) { + const descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) + descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + return function (Constructor, protoProps, staticProps) { + if (protoProps) + defineProperties(Constructor.prototype, protoProps); + if (staticProps) + defineProperties(Constructor, staticProps); + return Constructor; + }; + }()); + const _EventTarget2 = __webpack_require__(8); + const _EventTarget3 = _interopRequireDefault(_EventTarget2); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return call && (typeof call === 'object' || typeof call === 'function') ? call : self; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError(`Super expression must either be null or a function, not ${typeof superClass}`); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); + if (superClass) + Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + const Node = (function (_EventTarget) { + _inherits(Node, _EventTarget); + function Node() { + _classCallCheck(this, Node); + const _this = _possibleConstructorReturn(this, (Node.__proto__ || Object.getPrototypeOf(Node)).call(this)); + _this.childNodes = []; + return _this; + } + _createClass(Node, [{ + key: 'appendChild', + value: function appendChild(node) { + if (node instanceof Node) { + this.childNodes.push(node); + } + else { + throw new TypeError('Failed to executed \'appendChild\' on \'Node\': parameter 1 is not of type \'Node\'.'); + } + }, + }, { + key: 'cloneNode', + value: function cloneNode() { + const copyNode = Object.create(this); + Object.assign(copyNode, this); + return copyNode; + }, + }, { + key: 'removeChild', + value: function removeChild(node) { + const index = this.childNodes.findIndex(child => child === node); + if (index > -1) { + return this.childNodes.splice(index, 1); + } + return null; + }, + }]); + return Node; + }(_EventTarget3.default)); + exports.default = Node; + /***/ + }), + /* 8 */ + /***/ (function (module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + const _createClass = (function () { + function defineProperties(target, props) { + for (let i = 0; i < props.length; i++) { + const descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) + descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + return function (Constructor, protoProps, staticProps) { + if (protoProps) + defineProperties(Constructor.prototype, protoProps); + if (staticProps) + defineProperties(Constructor, staticProps); + return Constructor; + }; + }()); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + const _events = new WeakMap(); + const EventTarget = (function () { + function EventTarget() { + _classCallCheck(this, EventTarget); + _events.set(this, {}); + } + _createClass(EventTarget, [{ + key: 'addEventListener', + value: function addEventListener(type, listener) { + const options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + let events = _events.get(this); + if (!events) { + events = {}; + _events.set(this, events); + } + if (!events[type]) { + events[type] = []; + } + events[type].push(listener); + if (options.capture) { + console.warn('EventTarget.addEventListener: options.capture is not implemented.'); + } + if (options.once) { + console.warn('EventTarget.addEventListener: options.once is not implemented.'); + } + if (options.passive) { + console.warn('EventTarget.addEventListener: options.passive is not implemented.'); + } + }, + }, { + key: 'removeEventListener', + value: function removeEventListener(type, listener) { + const listeners = _events.get(this)[type]; + if (listeners && listeners.length > 0) { + for (let i = listeners.length; i--; i > 0) { + if (listeners[i] === listener) { + listeners.splice(i, 1); + break; + } + } + } + }, + }, { + key: 'dispatchEvent', + value: function dispatchEvent() { + const event = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + const listeners = _events.get(this)[event.type]; + if (listeners) { + for (let i = 0; i < listeners.length; i++) { + listeners[i](event); + } + } + }, + }]); + return EventTarget; + }()); + exports.default = EventTarget; + /***/ + }), + /* 9 */ + /***/ (function (module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + exports.noop = noop; + function noop() { } + /***/ + }), + /* 10 */ + /***/ (function (module, exports, __webpack_require__) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + exports.default = Canvas; + const _constructor = __webpack_require__(4); + const _HTMLElement = __webpack_require__(5); + const _HTMLElement2 = _interopRequireDefault(_HTMLElement); + const _document = __webpack_require__(11); + const _document2 = _interopRequireDefault(_document); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + const hasModifiedCanvasPrototype = false; + const hasInit2DContextConstructor = false; + const hasInitWebGLContextConstructor = false; + function Canvas() { + const canvas = wx.createCanvas(); + canvas.type = 'canvas'; + canvas.__proto__.__proto__ = new _HTMLElement2.default('canvas'); + const _getContext = canvas.getContext; + canvas.getBoundingClientRect = function () { + const ret = { + top: 0, + left: 0, + width: window.innerWidth, + height: window.innerHeight, + }; + return ret; + }; + return canvas; + } + /***/ + }), + /* 11 */ + /***/ (function (module, exports, __webpack_require__) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + const _window = __webpack_require__(1); + const window = _interopRequireWildcard(_window); + const _HTMLElement = __webpack_require__(5); + const _HTMLElement2 = _interopRequireDefault(_HTMLElement); + const _Image = __webpack_require__(12); + const _Image2 = _interopRequireDefault(_Image); + const _Audio = __webpack_require__(13); + const _Audio2 = _interopRequireDefault(_Audio); + const _Canvas = __webpack_require__(10); + const _Canvas2 = _interopRequireDefault(_Canvas); + __webpack_require__(16); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + const newObj = {}; + if (obj != null) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) + newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + const events = {}; + var document = { + readyState: 'complete', + visibilityState: 'visible', + documentElement: window, + hidden: false, + style: {}, + location: window.location, + ontouchstart: null, + ontouchmove: null, + ontouchend: null, + head: new _HTMLElement2.default('head'), + body: new _HTMLElement2.default('body'), + createElement: function createElement(tagName) { + if (tagName === 'canvas') { + return new _Canvas2.default(); + } + if (tagName === 'audio') { + return new _Audio2.default(); + } + if (tagName === 'img') { + return new _Image2.default(); + } + return new _HTMLElement2.default(tagName); + }, + getElementById: function getElementById(id) { + if (id === window.canvas.id) { + return window.canvas; + } + return null; + }, + getElementsByTagName: function getElementsByTagName(tagName) { + if (tagName === 'head') { + return [document.head]; + } + if (tagName === 'body') { + return [document.body]; + } + if (tagName === 'canvas') { + return [window.canvas]; + } + return []; + }, + getElementsByName: function getElementsByName(tagName) { + if (tagName === 'head') { + return [document.head]; + } + if (tagName === 'body') { + return [document.body]; + } + if (tagName === 'canvas') { + return [window.canvas]; + } + return []; + }, + querySelector: function querySelector(query) { + if (query === 'head') { + return document.head; + } + if (query === 'body') { + return document.body; + } + if (query === 'canvas') { + return window.canvas; + } + if (query === `#${window.canvas.id}`) { + return window.canvas; + } + return null; + }, + querySelectorAll: function querySelectorAll(query) { + if (query === 'head') { + return [document.head]; + } + if (query === 'body') { + return [document.body]; + } + if (query === 'canvas') { + return [window.canvas]; + } + return []; + }, + addEventListener: function addEventListener(type, listener) { + if (!events[type]) { + events[type] = []; + } + events[type].push(listener); + }, + removeEventListener: function removeEventListener(type, listener) { + const listeners = events[type]; + if (listeners && listeners.length > 0) { + for (let i = listeners.length; i--; i > 0) { + if (listeners[i] === listener) { + listeners.splice(i, 1); + break; + } + } + } + }, + dispatchEvent: function dispatchEvent(event) { + const listeners = events[event.type]; + if (listeners) { + for (let i = 0; i < listeners.length; i++) { + listeners[i](event); + } + } + }, + }; + exports.default = document; + /***/ + }), + /* 12 */ + /***/ (function (module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + exports.default = Image; + function Image() { + const image = wx.createImage(); + return image; + } + /***/ + }), + /* 13 */ + /***/ (function (module, exports, __webpack_require__) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + const _createClass = (function () { + function defineProperties(target, props) { + for (let i = 0; i < props.length; i++) { + const descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) + descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + return function (Constructor, protoProps, staticProps) { + if (protoProps) + defineProperties(Constructor.prototype, protoProps); + if (staticProps) + defineProperties(Constructor, staticProps); + return Constructor; + }; + }()); + const _HTMLAudioElement2 = __webpack_require__(14); + const _HTMLAudioElement3 = _interopRequireDefault(_HTMLAudioElement2); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return call && (typeof call === 'object' || typeof call === 'function') ? call : self; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError(`Super expression must either be null or a function, not ${typeof superClass}`); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); + if (superClass) + Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + const HAVE_NOTHING = 0; + const HAVE_METADATA = 1; + const HAVE_CURRENT_DATA = 2; + const HAVE_FUTURE_DATA = 3; + const HAVE_ENOUGH_DATA = 4; + const _innerAudioContext = new WeakMap(); + const _src = new WeakMap(); + const _loop = new WeakMap(); + const _autoplay = new WeakMap(); + const Audio = (function (_HTMLAudioElement) { + _inherits(Audio, _HTMLAudioElement); + function Audio(url) { + _classCallCheck(this, Audio); + const _this = _possibleConstructorReturn(this, (Audio.__proto__ || Object.getPrototypeOf(Audio)).call(this)); + _this.HAVE_NOTHING = HAVE_NOTHING; + _this.HAVE_METADATA = HAVE_METADATA; + _this.HAVE_CURRENT_DATA = HAVE_CURRENT_DATA; + _this.HAVE_FUTURE_DATA = HAVE_FUTURE_DATA; + _this.HAVE_ENOUGH_DATA = HAVE_ENOUGH_DATA; + _this.readyState = HAVE_NOTHING; + _src.set(_this, ''); + const innerAudioContext = wx.createInnerAudioContext(); + _innerAudioContext.set(_this, innerAudioContext); + innerAudioContext.onCanplay(() => { + _this.dispatchEvent({ type: 'load' }); + _this.dispatchEvent({ type: 'loadend' }); + _this.dispatchEvent({ type: 'canplay' }); + _this.dispatchEvent({ type: 'canplaythrough' }); + _this.dispatchEvent({ type: 'loadedmetadata' }); + _this.readyState = HAVE_CURRENT_DATA; + }); + innerAudioContext.onPlay(() => { + _this.dispatchEvent({ type: 'play' }); + }); + innerAudioContext.onPause(() => { + _this.dispatchEvent({ type: 'pause' }); + }); + innerAudioContext.onEnded(() => { + _this.dispatchEvent({ type: 'ended' }); + _this.readyState = HAVE_ENOUGH_DATA; + }); + innerAudioContext.onError(() => { + _this.dispatchEvent({ type: 'error' }); + }); + if (url) { + _innerAudioContext.get(_this).src = url; + } + return _this; + } + _createClass(Audio, [{ + key: 'load', + value: function load() { + console.warn('HTMLAudioElement.load() is not implemented.'); + }, + }, { + key: 'play', + value: function play() { + _innerAudioContext.get(this).play(); + }, + }, { + key: 'pause', + value: function pause() { + _innerAudioContext.get(this).pause(); + }, + }, { + key: 'canPlayType', + value: function canPlayType() { + const mediaType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + if (typeof mediaType !== 'string') { + return ''; + } + if (mediaType.indexOf('audio/mpeg') > -1 || mediaType.indexOf('audio/mp4')) { + return 'probably'; + } + return ''; + }, + }, { + key: 'cloneNode', + value: function cloneNode() { + const newAudio = new Audio(); + newAudio.loop = _innerAudioContext.get(this).loop; + newAudio.autoplay = _innerAudioContext.get(this).autoplay; + newAudio.src = this.src; + return newAudio; + }, + }, { + key: 'currentTime', + get: function get() { + return _innerAudioContext.get(this).currentTime; + }, + set: function set(value) { + _innerAudioContext.get(this).seek(value); + }, + }, { + key: 'src', + get: function get() { + return _src.get(this); + }, + set: function set(value) { + _src.set(this, value); + _innerAudioContext.get(this).src = value; + }, + }, { + key: 'loop', + get: function get() { + return _innerAudioContext.get(this).loop; + }, + set: function set(value) { + _innerAudioContext.get(this).loop = value; + }, + }, { + key: 'autoplay', + get: function get() { + return _innerAudioContext.get(this).autoplay; + }, + set: function set(value) { + _innerAudioContext.get(this).autoplay = value; + }, + }, { + key: 'paused', + get: function get() { + return _innerAudioContext.get(this).paused; + }, + }]); + return Audio; + }(_HTMLAudioElement3.default)); + exports.default = Audio; + /***/ + }), + /* 14 */ + /***/ (function (module, exports, __webpack_require__) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + const _HTMLMediaElement2 = __webpack_require__(15); + const _HTMLMediaElement3 = _interopRequireDefault(_HTMLMediaElement2); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return call && (typeof call === 'object' || typeof call === 'function') ? call : self; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError(`Super expression must either be null or a function, not ${typeof superClass}`); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); + if (superClass) + Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + const HTMLAudioElement = (function (_HTMLMediaElement) { + _inherits(HTMLAudioElement, _HTMLMediaElement); + function HTMLAudioElement() { + _classCallCheck(this, HTMLAudioElement); + return _possibleConstructorReturn(this, (HTMLAudioElement.__proto__ || Object.getPrototypeOf(HTMLAudioElement)).call(this, 'audio')); + } + return HTMLAudioElement; + }(_HTMLMediaElement3.default)); + exports.default = HTMLAudioElement; + /***/ + }), + /* 15 */ + /***/ (function (module, exports, __webpack_require__) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + const _createClass = (function () { + function defineProperties(target, props) { + for (let i = 0; i < props.length; i++) { + const descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) + descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + return function (Constructor, protoProps, staticProps) { + if (protoProps) + defineProperties(Constructor.prototype, protoProps); + if (staticProps) + defineProperties(Constructor, staticProps); + return Constructor; + }; + }()); + const _HTMLElement2 = __webpack_require__(5); + const _HTMLElement3 = _interopRequireDefault(_HTMLElement2); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return call && (typeof call === 'object' || typeof call === 'function') ? call : self; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== 'function' && superClass !== null) { + throw new TypeError(`Super expression must either be null or a function, not ${typeof superClass}`); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); + if (superClass) + Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + const HTMLMediaElement = (function (_HTMLElement) { + _inherits(HTMLMediaElement, _HTMLElement); + function HTMLMediaElement(type) { + _classCallCheck(this, HTMLMediaElement); + return _possibleConstructorReturn(this, (HTMLMediaElement.__proto__ || Object.getPrototypeOf(HTMLMediaElement)).call(this, type)); + } + _createClass(HTMLMediaElement, [{ + key: 'addTextTrack', + value: function addTextTrack() { }, + }, { + key: 'captureStream', + value: function captureStream() { }, + }, { + key: 'fastSeek', + value: function fastSeek() { }, + }, { + key: 'load', + value: function load() { }, + }, { + key: 'pause', + value: function pause() { }, + }, { + key: 'play', + value: function play() { }, + }]); + return HTMLMediaElement; + }(_HTMLElement3.default)); + exports.default = HTMLMediaElement; + /***/ + }), + /* 16 */ + /***/ (function (module, exports, __webpack_require__) { + 'use strict'; + __webpack_require__(17); + /***/ + }), + /* 17 */ + /***/ (function (module, exports, __webpack_require__) { + 'use strict'; + const _window = __webpack_require__(1); + const window = _interopRequireWildcard(_window); + const _document = __webpack_require__(11); + const _document2 = _interopRequireDefault(_document); + const _util = __webpack_require__(9); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + const newObj = {}; + if (obj != null) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) + newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + const TouchEvent = function TouchEvent(type) { + _classCallCheck(this, TouchEvent); + this.target = window.canvas; + this.currentTarget = window.canvas; + this.touches = []; + this.targetTouches = []; + this.changedTouches = []; + this.preventDefault = _util.noop; + this.stopPropagation = _util.noop; + this.type = type; + }; + function formatTouchEvent(v, type, changed) { + return { + ...v, + identifier: formatIdentifier(v.identifier, type, changed) + }; + } + function touchEventHandlerFactory(type) { + return function (event) { + const touchEvent = new TouchEvent(type); + touchEvent.touches = event.touches.map(v => formatTouchEvent(v, event.type)); + touchEvent.targetTouches = Array.prototype.slice.call(event.touches).map(v => formatTouchEvent(v, event.type)); + touchEvent.changedTouches = event.changedTouches.map(v => formatTouchEvent(v, event.type, 1)); + touchEvent.timeStamp = event.timeStamp; + _document2.default.dispatchEvent(touchEvent); + }; + } + wx.onTouchStart(touchEventHandlerFactory('touchstart')); + wx.onTouchMove(touchEventHandlerFactory('touchmove')); + wx.onTouchEnd(touchEventHandlerFactory('touchend')); + wx.onTouchCancel(touchEventHandlerFactory('touchcancel')); + /***/ + }), + /* 18 */ + /***/ (function (module, exports, __webpack_require__) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + const _util = __webpack_require__(9); + // TODO 需要 wx.getSystemInfo 获取更详细信息 + const { platform } = wx.getDeviceInfo ? wx.getDeviceInfo() : wx.getSystemInfoSync(); + const navigator = { + platform, + language: 'zh-cn', + appVersion: '5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1', + userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E8301 MicroMessenger/6.6.0 MiniGame NetType/WIFI Language/zh_CN', + onLine: true, + // TODO 用 wx.getLocation 来封装 geolocation + geolocation: { + getCurrentPosition: _util.noop, + watchPosition: _util.noop, + clearWatch: _util.noop, + }, + }; + exports.default = navigator; + /***/ + }), + /* 19 */ + /***/ (function (module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + const _createClass = (function () { + function defineProperties(target, props) { + for (let i = 0; i < props.length; i++) { + const descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) + descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + return function (Constructor, protoProps, staticProps) { + if (protoProps) + defineProperties(Constructor.prototype, protoProps); + if (staticProps) + defineProperties(Constructor, staticProps); + return Constructor; + }; + }()); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + const _url = new WeakMap(); + const _method = new WeakMap(); + const _requestHeader = new WeakMap(); + const _responseHeader = new WeakMap(); + const _requestTask = new WeakMap(); + function _triggerEvent(type) { + if (typeof this[`on${type}`] === 'function') { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + this[`on${type}`].apply(this, args); + } + } + function _changeReadyState(readyState) { + this.readyState = readyState; + _triggerEvent.call(this, 'readystatechange'); + } + const XMLHttpRequest = (function () { + // TODO 没法模拟 HEADERS_RECEIVED 和 LOADING 两个状态 + function XMLHttpRequest() { + _classCallCheck(this, XMLHttpRequest); + this.onabort = null; + this.onerror = null; + this.onload = null; + this.onloadstart = null; + this.onprogress = null; + this.ontimeout = null; + this.onloadend = null; + this.onreadystatechange = null; + this.readyState = 0; + this.response = null; + this.responseText = null; + this.responseType = ''; + this.responseXML = null; + this.status = 0; + this.statusText = ''; + this.upload = {}; + this.withCredentials = false; + this.timeout = 60000; + _requestHeader.set(this, { + 'content-type': 'application/x-www-form-urlencoded', + }); + _responseHeader.set(this, {}); + } + /* + * TODO 这一批事件应该是在 XMLHttpRequestEventTarget.prototype 上面的 + */ + _createClass(XMLHttpRequest, [{ + key: 'abort', + value: function abort() { + const myRequestTask = _requestTask.get(this); + if (myRequestTask) { + myRequestTask.abort(); + } + }, + }, { + key: 'getAllResponseHeaders', + value: function getAllResponseHeaders() { + const responseHeader = _responseHeader.get(this); + return Object.keys(responseHeader).map(header => `${header}: ${responseHeader[header]}`) + .join('\n'); + }, + }, { + key: 'getResponseHeader', + value: function getResponseHeader(header) { + return _responseHeader.get(this)[header]; + }, + }, { + key: 'open', + value: function open(method, url /* async, user, password 这几个参数在小程序内不支持*/) { + _method.set(this, method); + _url.set(this, url); + _changeReadyState.call(this, XMLHttpRequest.OPENED); + }, + }, { + key: 'overrideMimeType', + value: function overrideMimeType() { }, + }, { + key: 'send', + value: function send() { + const _this = this; + let data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + if (this.readyState !== XMLHttpRequest.OPENED) { + throw new Error('Failed to execute \'send\' on \'XMLHttpRequest\': The object\'s state must be OPENED.'); + } + else { + if (data instanceof Uint8Array) { + // unity 过来的请求会出现Uint8Array的数组,而客户端这里处理有问题,先这样兼容 + data = Uint8Array.from(data).buffer; + } + const { responseType } = this; + wx.request({ + data, + url: _url.get(this), + method: _method.get(this), + header: _requestHeader.get(this), + responseType: this.responseType, + enableHttp2: true, + enableQuic: true, + timeout: this.timeout ? this.timeout : 60000, + success: function success(_ref) { + let { data } = _ref; + const { statusCode } = _ref; + const { header } = _ref; + if (typeof data !== 'string' && !(data instanceof ArrayBuffer)) { + try { + data = JSON.stringify(data); + } + catch (e) { + data = data; + } + } + _this.status = statusCode; + _responseHeader.set(_this, header); + _triggerEvent.call(_this, 'loadstart'); + _changeReadyState.call(_this, XMLHttpRequest.HEADERS_RECEIVED); + _changeReadyState.call(_this, XMLHttpRequest.LOADING); + _this.response = data; + _this.profile = _ref.profile; + if (responseType === 'text') { + if (data instanceof ArrayBuffer) { + _this.responseText = ''; + const bytes = new Uint8Array(data); + const len = bytes.byteLength; + for (let i = 0; i < len; i++) { + _this.responseText += String.fromCharCode(bytes[i]); + } + } + else { + _this.responseText = data; + } + } + _changeReadyState.call(_this, XMLHttpRequest.DONE); + _triggerEvent.call(_this, 'load'); + _triggerEvent.call(_this, 'loadend'); + }, + fail: function fail(_ref2) { + const { errMsg } = _ref2; + // TODO 规范错误 + if (errMsg.indexOf('abort') !== -1) { + _triggerEvent.call(_this, 'abort'); + } + else { + _triggerEvent.call(_this, 'error', errMsg); + } + _triggerEvent.call(_this, 'loadend'); + }, + }); + } + }, + }, { + key: 'setRequestHeader', + value: function setRequestHeader(header, value) { + const myHeader = _requestHeader.get(this); + myHeader[header] = value; + _requestHeader.set(this, myHeader); + }, + }]); + return XMLHttpRequest; + }()); + XMLHttpRequest.UNSEND = 0; + XMLHttpRequest.OPENED = 1; + XMLHttpRequest.HEADERS_RECEIVED = 2; + XMLHttpRequest.LOADING = 3; + XMLHttpRequest.DONE = 4; + if (!isWK) { + exports.default = XMLHttpRequest; + } + /***/ + }), + /* 20 */ + /***/ (function (module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + const _createClass = (function () { + function defineProperties(target, props) { + for (let i = 0; i < props.length; i++) { + const descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) + descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + return function (Constructor, protoProps, staticProps) { + if (protoProps) + defineProperties(Constructor.prototype, protoProps); + if (staticProps) + defineProperties(Constructor, staticProps); + return Constructor; + }; + }()); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + const _socketTask = new WeakMap(); + const WebSocket = (function () { + // TODO 更新 binaryType + // The connection is in the process of closing. + // The connection is not yet open. + function WebSocket(url) { + const _this = this; + const protocols = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + _classCallCheck(this, WebSocket); + this.binaryType = ''; + this.bufferedAmount = 0; + this.extensions = ''; + this.onclose = null; + this.onerror = null; + this.onmessage = null; + this.onopen = null; + this.protocol = ''; + this.readyState = 3; + if (typeof url !== 'string' || !/(^ws:\/\/)|(^wss:\/\/)/.test(url)) { + throw new TypeError(`Failed to construct 'WebSocket': The URL '${url}' is invalid`); + } + this.url = url; + this.readyState = WebSocket.CONNECTING; + const socketTask = wx.connectSocket({ + url, + protocols: Array.isArray(protocols) ? protocols : [protocols], + }); + _socketTask.set(this, socketTask); + socketTask.onClose((res) => { + _this.readyState = WebSocket.CLOSED; + if (typeof _this.onclose === 'function') { + _this.onclose(res); + } + }); + socketTask.onMessage((res) => { + if (typeof _this.onmessage === 'function') { + _this.onmessage(res); + } + }); + socketTask.onOpen(() => { + _this.readyState = WebSocket.OPEN; + if (typeof _this.onopen === 'function') { + _this.onopen(); + } + }); + socketTask.onError((res) => { + if (typeof _this.onerror === 'function') { + _this.onerror(new Error(res.errMsg)); + } + }); + return this; + } // TODO 小程序内目前获取不到,实际上需要根据服务器选择的 sub-protocol 返回 + // TODO 更新 bufferedAmount + // The connection is closed or couldn't be opened. + // The connection is open and ready to communicate. + _createClass(WebSocket, [{ + key: 'close', + value: function close(code, reason) { + this.readyState = WebSocket.CLOSING; + const socketTask = _socketTask.get(this); + socketTask.close({ + code, + reason, + }); + }, + }, { + key: 'send', + value: function send(data) { + if (typeof data !== 'string' && !(data instanceof ArrayBuffer) && !((typeof data) === 'object')) { + throw new TypeError(`Failed to send message: The data ${data} is invalid`); + } + const socketTask = _socketTask.get(this); + socketTask.send({ + data, + }); + }, + }]); + return WebSocket; + }()); + WebSocket.CONNECTING = 0; + WebSocket.OPEN = 1; + WebSocket.CLOSING = 2; + WebSocket.CLOSED = 3; + exports.default = WebSocket; + /***/ + }), + /* 21 */ + /***/ (function (module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + const _createClass = (function () { + function defineProperties(target, props) { + for (let i = 0; i < props.length; i++) { + const descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) + descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + return function (Constructor, protoProps, staticProps) { + if (protoProps) + defineProperties(Constructor.prototype, protoProps); + if (staticProps) + defineProperties(Constructor, staticProps); + return Constructor; + }; + }()); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } + } + /* + * TODO 使用 wx.readFile 来封装 FileReader + */ + const FileReader = (function () { + function FileReader() { + _classCallCheck(this, FileReader); + } + _createClass(FileReader, [{ + key: 'construct', + value: function construct() { }, + }]); + return FileReader; + }()); + exports.default = FileReader; + /***/ + }), + /* 22 */ + /***/ (function (module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + const localStorage = { + get length() { + const _wx$getStorageInfoSyn = wx.getStorageInfoSync(); + const { keys } = _wx$getStorageInfoSyn; + return keys.length; + }, + key: function key(n) { + const _wx$getStorageInfoSyn2 = wx.getStorageInfoSync(); + const { keys } = _wx$getStorageInfoSyn2; + return keys[n]; + }, + getItem: function getItem(key) { + return wx.getStorageSync(key); + }, + setItem: function setItem(key, value) { + return wx.setStorageSync(key, value); + }, + removeItem: function removeItem(key) { + wx.removeStorageSync(key); + }, + clear: function clear() { + wx.clearStorageSync(); + }, + }; + exports.default = localStorage; + /***/ + }), + /* 23 */ + /***/ (function (module, exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true, + }); + const location = { + href: 'game.js', + reload: function reload() { }, + }; + exports.default = location; + /***/ + }), + /** ****/ +])); diff --git a/Runtime/playable-default/weapp-adapter.js.meta b/Runtime/playable-default/weapp-adapter.js.meta new file mode 100644 index 000000000..766f73430 --- /dev/null +++ b/Runtime/playable-default/weapp-adapter.js.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 7aa6b4017a18f4a45964659d3b86c0e3 +DefaultImporter: +externalObjects: {} +userData: +assetBundleName: +assetBundleVariant: \ No newline at end of file diff --git a/Runtime/wechat-default/check-version.js.meta b/Runtime/wechat-default/check-version.js.meta index c6b5a2f25..4ba25df78 100644 --- a/Runtime/wechat-default/check-version.js.meta +++ b/Runtime/wechat-default/check-version.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: f5bbedd327ca4d453dc693e0eec93f0a +guid: b995d292ffc4eb0a88f485f0f7c18433 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/data-package/game.js.meta b/Runtime/wechat-default/data-package/game.js.meta index 4db3a214f..a1d243a7a 100644 --- a/Runtime/wechat-default/data-package/game.js.meta +++ b/Runtime/wechat-default/data-package/game.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 4dc9fc4325c0d2d284155ba7dca22a6e +guid: 6eec49e0e51a40a6385e0c423fcb4763 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/events.js.meta b/Runtime/wechat-default/events.js.meta index d2402396c..2675284f9 100644 --- a/Runtime/wechat-default/events.js.meta +++ b/Runtime/wechat-default/events.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: dd4d2a77c91d8c85cd875bfc9a004e3c +guid: a47b5ed4892fbcd979010f4ff34b3898 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/game.js.meta b/Runtime/wechat-default/game.js.meta index a41b01ab8..8cbe35bb4 100644 --- a/Runtime/wechat-default/game.js.meta +++ b/Runtime/wechat-default/game.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 599452cb9207cd3ab8657e0862b49d49 +guid: bfae7618cd2d30e41081e2b9cff36b7f DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/game.json b/Runtime/wechat-default/game.json index 4e6877d02..22b682158 100644 --- a/Runtime/wechat-default/game.json +++ b/Runtime/wechat-default/game.json @@ -23,7 +23,7 @@ ], "plugins": { "UnityPlugin": { - "version": "1.2.72", + "version": "1.2.74", "provider": "wxe5a48f1ed5f544b7", "contexts": [ { @@ -51,4 +51,4 @@ } }, "workers": "workers" -} +} \ No newline at end of file diff --git a/Runtime/wechat-default/game.json.meta b/Runtime/wechat-default/game.json.meta index e44dfdf77..e679ba9ba 100644 --- a/Runtime/wechat-default/game.json.meta +++ b/Runtime/wechat-default/game.json.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 45ce9756a440dd72f6ca1374e2081c3f +guid: c50108627e852f5a2586b9357e6b9ae1 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/images/background.jpg.meta b/Runtime/wechat-default/images/background.jpg.meta index ec89570ae..0e3e0bbeb 100644 --- a/Runtime/wechat-default/images/background.jpg.meta +++ b/Runtime/wechat-default/images/background.jpg.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 1c7f4f320cabcdf3a328509648b1805e +guid: b5ea5da8df58a386eee9d1f98c0fed1d DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/images/unity_logo.png.meta b/Runtime/wechat-default/images/unity_logo.png.meta index 687276000..16127a3a9 100644 --- a/Runtime/wechat-default/images/unity_logo.png.meta +++ b/Runtime/wechat-default/images/unity_logo.png.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 89728d328850333146cfeb7523e57965 +guid: 9f000212ce34f53ad7e1465793fdcf9d DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/data/index.js.meta b/Runtime/wechat-default/open-data/data/index.js.meta index 37b32ef77..d7c44e74b 100644 --- a/Runtime/wechat-default/open-data/data/index.js.meta +++ b/Runtime/wechat-default/open-data/data/index.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 2b3478f37747dc014aa38eab6a967415 +guid: fd12f4ef0ea6534509bd9586dec6ac44 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/data/utils.js.meta b/Runtime/wechat-default/open-data/data/utils.js.meta index 35d99bba0..7349b58a2 100644 --- a/Runtime/wechat-default/open-data/data/utils.js.meta +++ b/Runtime/wechat-default/open-data/data/utils.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c66500ff3c20972e6556e2c4ba4d5cfe +guid: faeb0a51a7466850ad29bb4c5a863e21 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/index.js.meta b/Runtime/wechat-default/open-data/index.js.meta index f588b1a8d..1d49f705a 100644 --- a/Runtime/wechat-default/open-data/index.js.meta +++ b/Runtime/wechat-default/open-data/index.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: b89084c80bee844d81419056298bc0ce +guid: 8ba31e44cc68b8dadb41761ac9ec5225 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/loading.js.meta b/Runtime/wechat-default/open-data/loading.js.meta index bfee17d50..a106348b0 100644 --- a/Runtime/wechat-default/open-data/loading.js.meta +++ b/Runtime/wechat-default/open-data/loading.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: bfebde84e2fd88a58a6810586b6f6cc6 +guid: f1e530d3b4822756aa12dd242cdead03 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/render/image/avatar.png.meta b/Runtime/wechat-default/open-data/render/image/avatar.png.meta index 6f7fc64d3..0db2c6195 100644 --- a/Runtime/wechat-default/open-data/render/image/avatar.png.meta +++ b/Runtime/wechat-default/open-data/render/image/avatar.png.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 640ba1eec9d43c5c024b5aeb87d2cfeb +guid: 519106d32b6d382a4d06e77c62ebdfff DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/render/image/button1.png.meta b/Runtime/wechat-default/open-data/render/image/button1.png.meta index fb228a3dc..a1a83f352 100644 --- a/Runtime/wechat-default/open-data/render/image/button1.png.meta +++ b/Runtime/wechat-default/open-data/render/image/button1.png.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: ea016d2813f4be01a2ecc83740a0682b +guid: 928d4612ff56b956c96655b59c9bd58b DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/render/image/button2.png.meta b/Runtime/wechat-default/open-data/render/image/button2.png.meta index a64bd39b8..4b7e7ff22 100644 --- a/Runtime/wechat-default/open-data/render/image/button2.png.meta +++ b/Runtime/wechat-default/open-data/render/image/button2.png.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: ca63ffbee01ed6541166ac58c9bf4a2b +guid: 78d7ee93aba1069ba132424e9cc53504 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/render/image/button3.png.meta b/Runtime/wechat-default/open-data/render/image/button3.png.meta index 0d872bba9..a4cdb9e12 100644 --- a/Runtime/wechat-default/open-data/render/image/button3.png.meta +++ b/Runtime/wechat-default/open-data/render/image/button3.png.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 6213428642573b3838e1a981c21f1df2 +guid: 923d13827d11ac62b5af22e5bb604e87 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/render/image/loading.png.meta b/Runtime/wechat-default/open-data/render/image/loading.png.meta index 7fe203d89..18cbb92d2 100644 --- a/Runtime/wechat-default/open-data/render/image/loading.png.meta +++ b/Runtime/wechat-default/open-data/render/image/loading.png.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 77300a23453e71c1334025c7bcebe69d +guid: 3df8425da07725ca135aba3bc3239f43 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/render/image/nameBg.png.meta b/Runtime/wechat-default/open-data/render/image/nameBg.png.meta index 3eaaf8fea..67fbf5062 100644 --- a/Runtime/wechat-default/open-data/render/image/nameBg.png.meta +++ b/Runtime/wechat-default/open-data/render/image/nameBg.png.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 371f2d1949813934266ce550e94c6839 +guid: 600cb4175de418e46d526f51ba488318 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/render/image/rankAvatar.png.meta b/Runtime/wechat-default/open-data/render/image/rankAvatar.png.meta index 1b4e4d9f0..162f6bdd8 100644 --- a/Runtime/wechat-default/open-data/render/image/rankAvatar.png.meta +++ b/Runtime/wechat-default/open-data/render/image/rankAvatar.png.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 06a24c2a970aaa28991597d76913c9b8 +guid: 3ecc59927dca963cc07df1b96156a4a6 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/render/image/rankBg.png.meta b/Runtime/wechat-default/open-data/render/image/rankBg.png.meta index 97826f292..bda0bd61b 100644 --- a/Runtime/wechat-default/open-data/render/image/rankBg.png.meta +++ b/Runtime/wechat-default/open-data/render/image/rankBg.png.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 024f68d89cbbcb2b7d2a449efeb05c09 +guid: b43a80abd4b666bbb1e2171c954824e8 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/render/image/shareBg.png.meta b/Runtime/wechat-default/open-data/render/image/shareBg.png.meta index db1f3222d..dfad230c4 100644 --- a/Runtime/wechat-default/open-data/render/image/shareBg.png.meta +++ b/Runtime/wechat-default/open-data/render/image/shareBg.png.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 7c427d76aed0d933bfd634a1df796a67 +guid: 936f1709e2bdb10b77540661271e9b62 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/render/image/shareBg2.png.meta b/Runtime/wechat-default/open-data/render/image/shareBg2.png.meta index 85605f24e..c8e5245c9 100644 --- a/Runtime/wechat-default/open-data/render/image/shareBg2.png.meta +++ b/Runtime/wechat-default/open-data/render/image/shareBg2.png.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 10af17eda5936f2ce157d288d52dea59 +guid: 12282a33ea47d4b3038c662ad64ef8b1 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/render/styles/friendRank.js.meta b/Runtime/wechat-default/open-data/render/styles/friendRank.js.meta index c4d523545..1c33ae4a6 100644 --- a/Runtime/wechat-default/open-data/render/styles/friendRank.js.meta +++ b/Runtime/wechat-default/open-data/render/styles/friendRank.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 9a3302d93b2e1a3fdd3536258d01f83d +guid: 700249430495078e7fac4d6454f782e4 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/render/styles/tips.js.meta b/Runtime/wechat-default/open-data/render/styles/tips.js.meta index 3bb7aac74..5cab5bf14 100644 --- a/Runtime/wechat-default/open-data/render/styles/tips.js.meta +++ b/Runtime/wechat-default/open-data/render/styles/tips.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: f93250b42acf947f93919bd4531c8bb9 +guid: 9a3e88f39cb64fe0957130457381b399 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/render/tpls/friendRank.js.meta b/Runtime/wechat-default/open-data/render/tpls/friendRank.js.meta index 7a2f372a5..5869b829b 100644 --- a/Runtime/wechat-default/open-data/render/tpls/friendRank.js.meta +++ b/Runtime/wechat-default/open-data/render/tpls/friendRank.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 5824baea9c65ccbc4995adbfb25e0d71 +guid: 3e0045fa9b8dec4b551c3150291ab778 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/open-data/render/tpls/tips.js.meta b/Runtime/wechat-default/open-data/render/tpls/tips.js.meta index 71add50d6..5b6186df0 100644 --- a/Runtime/wechat-default/open-data/render/tpls/tips.js.meta +++ b/Runtime/wechat-default/open-data/render/tpls/tips.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 97b3ad2b595e8aa7d998575ffd297784 +guid: b9985302619cb4e2151aa29360c597ee DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/plugin-config.js.meta b/Runtime/wechat-default/plugin-config.js.meta index 38c4d5d60..402743209 100644 --- a/Runtime/wechat-default/plugin-config.js.meta +++ b/Runtime/wechat-default/plugin-config.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: f294cff5531d36144a68512c7aed2195 +guid: 3b6412792d3294ad37d966e909ae3b71 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/plugins/check-update.js.meta b/Runtime/wechat-default/plugins/check-update.js.meta index c93c4e179..79f473f84 100644 --- a/Runtime/wechat-default/plugins/check-update.js.meta +++ b/Runtime/wechat-default/plugins/check-update.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: d8809338f937180c3f27ec32a7db00e5 +guid: 887557c30a04466d4d1a0a6c5d52bd88 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/plugins/screen-adapter.js.meta b/Runtime/wechat-default/plugins/screen-adapter.js.meta index a834d13f6..e69674294 100644 --- a/Runtime/wechat-default/plugins/screen-adapter.js.meta +++ b/Runtime/wechat-default/plugins/screen-adapter.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 1299702628a955c3cb4ff3e5a23309cf +guid: cecfddcfb1a2649d043650e7d9d56aa5 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/project.config.json.meta b/Runtime/wechat-default/project.config.json.meta index ac93e270d..d15e9a974 100644 --- a/Runtime/wechat-default/project.config.json.meta +++ b/Runtime/wechat-default/project.config.json.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: ab69992b759090dbca36bd280c87dbd0 +guid: d41ee28ff99a97a882c252e1ee24e9c3 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/texture-config.js.meta b/Runtime/wechat-default/texture-config.js.meta index 51abf0081..ab60ea087 100644 --- a/Runtime/wechat-default/texture-config.js.meta +++ b/Runtime/wechat-default/texture-config.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 8e08bb7708434d67ac9bd388dd0740fe +guid: 36196b0956154b5cd9839ca98f93ad16 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-namespace.js.meta b/Runtime/wechat-default/unity-namespace.js.meta index 799808d96..6eaa0049e 100644 --- a/Runtime/wechat-default/unity-namespace.js.meta +++ b/Runtime/wechat-default/unity-namespace.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 4095c88cab533cdfe1a256b37a1d9238 +guid: b718f054566670885069fcb167827124 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/TCPSocket/index.js.meta b/Runtime/wechat-default/unity-sdk/TCPSocket/index.js.meta index dfc26748f..fb4cb8bce 100644 --- a/Runtime/wechat-default/unity-sdk/TCPSocket/index.js.meta +++ b/Runtime/wechat-default/unity-sdk/TCPSocket/index.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 0a9aa05b0098345c58e0e315e56dab5b +guid: b4d1d50f2066ad2aa1444a226841d071 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/UDPSocket/index.js.meta b/Runtime/wechat-default/unity-sdk/UDPSocket/index.js.meta index 1234ad777..00440861b 100644 --- a/Runtime/wechat-default/unity-sdk/UDPSocket/index.js.meta +++ b/Runtime/wechat-default/unity-sdk/UDPSocket/index.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: efb677617699481f8b37449834a97817 +guid: 2b2227e52675d84aa656714e0b457154 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/ad.js.meta b/Runtime/wechat-default/unity-sdk/ad.js.meta index 8e901854d..8e8b04d84 100644 --- a/Runtime/wechat-default/unity-sdk/ad.js.meta +++ b/Runtime/wechat-default/unity-sdk/ad.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 75d7183d6861ab9205cfe65aac42200b +guid: 4c5765ff0ac95c4bf787bac08a722c50 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/audio/common.js.meta b/Runtime/wechat-default/unity-sdk/audio/common.js.meta index 73a69b8c1..83d46db3f 100644 --- a/Runtime/wechat-default/unity-sdk/audio/common.js.meta +++ b/Runtime/wechat-default/unity-sdk/audio/common.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c469495c25f2aa32bf329ea4d27d6b78 +guid: 3272c418c47fa3b5649f12f5217a04b1 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/audio/const.js.meta b/Runtime/wechat-default/unity-sdk/audio/const.js.meta index 8a2feb8cc..5c5bcdcdd 100644 --- a/Runtime/wechat-default/unity-sdk/audio/const.js.meta +++ b/Runtime/wechat-default/unity-sdk/audio/const.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 14c3fb0a7c888e669203241affa83799 +guid: 4a83de69eb6a33e54e9cec8584741868 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/audio/index.js.meta b/Runtime/wechat-default/unity-sdk/audio/index.js.meta index 0da8719af..637b7b09d 100644 --- a/Runtime/wechat-default/unity-sdk/audio/index.js.meta +++ b/Runtime/wechat-default/unity-sdk/audio/index.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 4a73210f3528121111cb7a446f4fc65d +guid: 0b3877df98ffb6cc90e6fa97c78df13c DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/audio/inner-audio.js.meta b/Runtime/wechat-default/unity-sdk/audio/inner-audio.js.meta index 0a70d1a3d..510ecb63c 100644 --- a/Runtime/wechat-default/unity-sdk/audio/inner-audio.js.meta +++ b/Runtime/wechat-default/unity-sdk/audio/inner-audio.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 156ee288be94269bae6720995e0551a2 +guid: 32ca7c5d14e05c5e0e2ef05bd41bd312 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/audio/store.js.meta b/Runtime/wechat-default/unity-sdk/audio/store.js.meta index 0cb2bced9..8510cceeb 100644 --- a/Runtime/wechat-default/unity-sdk/audio/store.js.meta +++ b/Runtime/wechat-default/unity-sdk/audio/store.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: fea716d7e82de6ddec4d1e3971658ffc +guid: 50382da8d8cab118957715abe25794af DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/audio/unity-audio.js.meta b/Runtime/wechat-default/unity-sdk/audio/unity-audio.js.meta index 27e757673..81cdfac5d 100644 --- a/Runtime/wechat-default/unity-sdk/audio/unity-audio.js.meta +++ b/Runtime/wechat-default/unity-sdk/audio/unity-audio.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 377b442115a64588dfb4de4d72c82401 +guid: 817f29c0723d2a9a7d9327d97e593dcc DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/audio/utils.js.meta b/Runtime/wechat-default/unity-sdk/audio/utils.js.meta index ed7fc5016..28555aac3 100644 --- a/Runtime/wechat-default/unity-sdk/audio/utils.js.meta +++ b/Runtime/wechat-default/unity-sdk/audio/utils.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 9b0976170efd11aad1de64f2e3a177eb +guid: bdb30dd8b868ec66f5fd3cde9b85e661 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/authorize.js.meta b/Runtime/wechat-default/unity-sdk/authorize.js.meta index 91b20ff7a..5139f0dff 100644 --- a/Runtime/wechat-default/unity-sdk/authorize.js.meta +++ b/Runtime/wechat-default/unity-sdk/authorize.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 2084f84ad52f4d737572cf75334def99 +guid: eb76fcebf1dc37faafbef82e7ab7c893 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/bluetooth/index.js.meta b/Runtime/wechat-default/unity-sdk/bluetooth/index.js.meta index f7376712b..8e3a9e8cd 100644 --- a/Runtime/wechat-default/unity-sdk/bluetooth/index.js.meta +++ b/Runtime/wechat-default/unity-sdk/bluetooth/index.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 991e938a520c8629f8b1bb446c1eba32 +guid: ed84123662e17b3473457b43f838cdf7 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/camera.js.meta b/Runtime/wechat-default/unity-sdk/camera.js.meta index c89c5cabf..a3ee52ecb 100644 --- a/Runtime/wechat-default/unity-sdk/camera.js.meta +++ b/Runtime/wechat-default/unity-sdk/camera.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 2f3e0d471989b3e64b2d3a7d81235264 +guid: d6d39fbd6c57737edf507821b5195440 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/canvas-context.js.meta b/Runtime/wechat-default/unity-sdk/canvas-context.js.meta index be11cd3f7..1b113ea49 100644 --- a/Runtime/wechat-default/unity-sdk/canvas-context.js.meta +++ b/Runtime/wechat-default/unity-sdk/canvas-context.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 98ccbccc80be38055fd35346b80cb47f +guid: ed81eedf0ab67ca2d1193517abf9061e DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/canvas.js.meta b/Runtime/wechat-default/unity-sdk/canvas.js.meta index 02befc46d..678093918 100644 --- a/Runtime/wechat-default/unity-sdk/canvas.js.meta +++ b/Runtime/wechat-default/unity-sdk/canvas.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 6566290a0fe5fd774341339eebfcdac9 +guid: a2652221264679bb000c8c6e62893071 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/chat.js.meta b/Runtime/wechat-default/unity-sdk/chat.js.meta index 92a7f89e3..6120de255 100644 --- a/Runtime/wechat-default/unity-sdk/chat.js.meta +++ b/Runtime/wechat-default/unity-sdk/chat.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: a56382186744cf31395c6cedb874370b +guid: ee4f4b03ba225329405190316ae99f81 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/cloud.js.meta b/Runtime/wechat-default/unity-sdk/cloud.js.meta index e1a03f67b..60fff0f87 100644 --- a/Runtime/wechat-default/unity-sdk/cloud.js.meta +++ b/Runtime/wechat-default/unity-sdk/cloud.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 8a2009830f64f24c4b6f16f6f3eff8b4 +guid: 1d1282814dec8e7ebe982a951ca46043 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/conf.js.meta b/Runtime/wechat-default/unity-sdk/conf.js.meta index 145bb037d..72f697f51 100644 --- a/Runtime/wechat-default/unity-sdk/conf.js.meta +++ b/Runtime/wechat-default/unity-sdk/conf.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: e64172a0c4c384c895f13bd3b36461d5 +guid: 78e9b5885569188973b6ab129163b6c4 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/file-info.js.meta b/Runtime/wechat-default/unity-sdk/file-info.js.meta index e917dce0d..a55a736bb 100644 --- a/Runtime/wechat-default/unity-sdk/file-info.js.meta +++ b/Runtime/wechat-default/unity-sdk/file-info.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 621683693092751e2f6a215818b30572 +guid: a306749fd203464926de1b5dbe1ae6ce DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/fix.js.meta b/Runtime/wechat-default/unity-sdk/fix.js.meta index c81c3c473..75baabf0a 100644 --- a/Runtime/wechat-default/unity-sdk/fix.js.meta +++ b/Runtime/wechat-default/unity-sdk/fix.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 0c83329525cff78a75e18c31eab86a00 +guid: b7fdf6ca82b5600aecb0adee0d157104 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/font/fix-cmap.js.meta b/Runtime/wechat-default/unity-sdk/font/fix-cmap.js.meta index d740212cd..123d50ef8 100644 --- a/Runtime/wechat-default/unity-sdk/font/fix-cmap.js.meta +++ b/Runtime/wechat-default/unity-sdk/font/fix-cmap.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 8220ca4d8f2a2f5cfdc766d52f555e27 +guid: de1a29f790b40030210286e5fb08e06e DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/font/index.js.meta b/Runtime/wechat-default/unity-sdk/font/index.js.meta index 9b5ee4cda..2ca212c2a 100644 --- a/Runtime/wechat-default/unity-sdk/font/index.js.meta +++ b/Runtime/wechat-default/unity-sdk/font/index.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c8eff552608bf6b2b56d7d9a0436b919 +guid: 30ba9a5a0c6222ae63b4cbee2ab81db0 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/font/read-metrics.js.meta b/Runtime/wechat-default/unity-sdk/font/read-metrics.js.meta index bc3fc416b..67cfc89a8 100644 --- a/Runtime/wechat-default/unity-sdk/font/read-metrics.js.meta +++ b/Runtime/wechat-default/unity-sdk/font/read-metrics.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 628a6b413e409a75e1ac999d659d178c +guid: fa43dc9a7397cab04781b89a46f573ca DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/font/split-sc.js.meta b/Runtime/wechat-default/unity-sdk/font/split-sc.js.meta index de9e756c0..accab4652 100644 --- a/Runtime/wechat-default/unity-sdk/font/split-sc.js.meta +++ b/Runtime/wechat-default/unity-sdk/font/split-sc.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 1500478f1918bec52a22dff02753b91d +guid: a400f8c37af47843adec664d1e6f1a73 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/font/util.js.meta b/Runtime/wechat-default/unity-sdk/font/util.js.meta index d0b4722c3..e6556eec3 100644 --- a/Runtime/wechat-default/unity-sdk/font/util.js.meta +++ b/Runtime/wechat-default/unity-sdk/font/util.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 2d40d4c846ba6a82b91969e02605547d +guid: 9956f785a41022f2b16063e512b42fa0 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/fs.js.meta b/Runtime/wechat-default/unity-sdk/fs.js.meta index 2aa0c4470..d6d398623 100644 --- a/Runtime/wechat-default/unity-sdk/fs.js.meta +++ b/Runtime/wechat-default/unity-sdk/fs.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: a74ee9c0aa9898add673f63bf4942a47 +guid: 4639c72a3413b5c110585a96091422f1 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/game-club.js.meta b/Runtime/wechat-default/unity-sdk/game-club.js.meta index 90fa1e51e..40753c901 100644 --- a/Runtime/wechat-default/unity-sdk/game-club.js.meta +++ b/Runtime/wechat-default/unity-sdk/game-club.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 4258c9c76fada289f422e0f8a001c504 +guid: 81e11319d20d7de6da73257e39ceda07 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/game-recorder.js.meta b/Runtime/wechat-default/unity-sdk/game-recorder.js.meta index 3498992ea..5277d4dd1 100644 --- a/Runtime/wechat-default/unity-sdk/game-recorder.js.meta +++ b/Runtime/wechat-default/unity-sdk/game-recorder.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 8bf928ef581712eff834881e68325041 +guid: 894a636560b49491067ac09a089305bb DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/gyroscope/index.js.meta b/Runtime/wechat-default/unity-sdk/gyroscope/index.js.meta index 1c29f84a6..155505c3d 100644 --- a/Runtime/wechat-default/unity-sdk/gyroscope/index.js.meta +++ b/Runtime/wechat-default/unity-sdk/gyroscope/index.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: df65a0703839a5072443b9fc2d203cdf +guid: 70bd0d4dfae7edc098fac3d9eb736444 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/index.js.meta b/Runtime/wechat-default/unity-sdk/index.js.meta index 3950b5154..add444d47 100644 --- a/Runtime/wechat-default/unity-sdk/index.js.meta +++ b/Runtime/wechat-default/unity-sdk/index.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 45bf7d6b8111e3e5a3c7574eefc725c2 +guid: dc21ce996e9ed1d6f47f4e52f6e0cd0d DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/logger.js.meta b/Runtime/wechat-default/unity-sdk/logger.js.meta index 2afb7787c..1dc8fff14 100644 --- a/Runtime/wechat-default/unity-sdk/logger.js.meta +++ b/Runtime/wechat-default/unity-sdk/logger.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 8161adcd3920b1954ec441ac0deab0b8 +guid: 9317b0aa9d010bd002d52059198765b5 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/mobileKeyboard/index.js.meta b/Runtime/wechat-default/unity-sdk/mobileKeyboard/index.js.meta index 9a3aa699d..771389a23 100644 --- a/Runtime/wechat-default/unity-sdk/mobileKeyboard/index.js.meta +++ b/Runtime/wechat-default/unity-sdk/mobileKeyboard/index.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 6e1977684d3e909449ebdcee8e3ebea2 +guid: a506168ffbd63f760a4646b334f88081 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/module-helper.js.meta b/Runtime/wechat-default/unity-sdk/module-helper.js.meta index 949eae827..d98c4cf8f 100644 --- a/Runtime/wechat-default/unity-sdk/module-helper.js.meta +++ b/Runtime/wechat-default/unity-sdk/module-helper.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 38dbfa0bdc1fcf879b68d9b0b8ac52e8 +guid: a9505c882e69197f537c7647329f8410 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/open-data.js.meta b/Runtime/wechat-default/unity-sdk/open-data.js.meta index 362cf8b0e..d29a39b48 100644 --- a/Runtime/wechat-default/unity-sdk/open-data.js.meta +++ b/Runtime/wechat-default/unity-sdk/open-data.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c83b5b340f112baab39d01670df3d236 +guid: db811ea5f73a1d4036a57546542a35aa DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/recorder.js.meta b/Runtime/wechat-default/unity-sdk/recorder.js.meta index f695079e4..12915a434 100644 --- a/Runtime/wechat-default/unity-sdk/recorder.js.meta +++ b/Runtime/wechat-default/unity-sdk/recorder.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: a07cf0aa5fcdbdc2da59ea8f6daf6aac +guid: c4621e88dfc0dd08bd8ec3226d212a66 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/resType.js.meta b/Runtime/wechat-default/unity-sdk/resType.js.meta index 01fb75407..891b86660 100644 --- a/Runtime/wechat-default/unity-sdk/resType.js.meta +++ b/Runtime/wechat-default/unity-sdk/resType.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 1789e77da34fa0b89b0612d2fd45aef5 +guid: ff8b401d128dd238e76bf7f5a7182e7e DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/resTypeOther.js.meta b/Runtime/wechat-default/unity-sdk/resTypeOther.js.meta index 77d2adff1..0412fa7df 100644 --- a/Runtime/wechat-default/unity-sdk/resTypeOther.js.meta +++ b/Runtime/wechat-default/unity-sdk/resTypeOther.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 29b85f7b9842cdc0af584fca47934b06 +guid: aa0cac44d2f9e9f1ac8c838fe4698a94 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/response.js.meta b/Runtime/wechat-default/unity-sdk/response.js.meta index c20595a98..f8b6b4e71 100644 --- a/Runtime/wechat-default/unity-sdk/response.js.meta +++ b/Runtime/wechat-default/unity-sdk/response.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c04ae875f798c1f4f6414b2d57effd5f +guid: 512034dd477a64f4caba5ec19aff2581 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/sdk.js.meta b/Runtime/wechat-default/unity-sdk/sdk.js.meta index b9f18b89b..b86e6b3fa 100644 --- a/Runtime/wechat-default/unity-sdk/sdk.js.meta +++ b/Runtime/wechat-default/unity-sdk/sdk.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 4c3246639a83f7ccd1b764558a739d52 +guid: 03bee59c66d704fc43f9b5f886015c22 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/share.js.meta b/Runtime/wechat-default/unity-sdk/share.js.meta index 14e9f11b9..d3df36492 100644 --- a/Runtime/wechat-default/unity-sdk/share.js.meta +++ b/Runtime/wechat-default/unity-sdk/share.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 9fd389fee1c0701c2f3e2b4535b9420a +guid: 68271b9849539db013d95b663122adde DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/storage.js.meta b/Runtime/wechat-default/unity-sdk/storage.js.meta index 49f92d62e..3c164cf3b 100644 --- a/Runtime/wechat-default/unity-sdk/storage.js.meta +++ b/Runtime/wechat-default/unity-sdk/storage.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 7feb1d0a7ddf038455d3ac47805d676c +guid: 580a20961fc0e6a8c28d19bcc9207e52 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/texture.js.meta b/Runtime/wechat-default/unity-sdk/texture.js.meta index 823c6157e..cf2ae511e 100644 --- a/Runtime/wechat-default/unity-sdk/texture.js.meta +++ b/Runtime/wechat-default/unity-sdk/texture.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 233478922069e367c50cb786c1d53668 +guid: 9a277fa9cd8d4b8e30b1ff2385af4469 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/touch/index.js.meta b/Runtime/wechat-default/unity-sdk/touch/index.js.meta index 203fc824a..a451e2bf2 100644 --- a/Runtime/wechat-default/unity-sdk/touch/index.js.meta +++ b/Runtime/wechat-default/unity-sdk/touch/index.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: a0f0df4db83c3863068f00d50b5d51d9 +guid: 3ce4400b2e11bfee16243eca4f16864b DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/upload-file.js.meta b/Runtime/wechat-default/unity-sdk/upload-file.js.meta index bbc2238db..af629187a 100644 --- a/Runtime/wechat-default/unity-sdk/upload-file.js.meta +++ b/Runtime/wechat-default/unity-sdk/upload-file.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 0a716dd02c3ba2d37379b3f911f7b8c4 +guid: d0504e0f2399c239e68c83b4e3a46d75 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/userinfo.js.meta b/Runtime/wechat-default/unity-sdk/userinfo.js.meta index b0d27377d..693c107f0 100644 --- a/Runtime/wechat-default/unity-sdk/userinfo.js.meta +++ b/Runtime/wechat-default/unity-sdk/userinfo.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 8efe90c24815d539c362cd8350b6d0f6 +guid: 39b2ed1acdf730836b8ac14780cb913c DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/util.js.meta b/Runtime/wechat-default/unity-sdk/util.js.meta index 7d4e4e207..9dc989278 100644 --- a/Runtime/wechat-default/unity-sdk/util.js.meta +++ b/Runtime/wechat-default/unity-sdk/util.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c141311a86eb12850002df4e04430f1e +guid: e43fa8c4da948e79f1d17a93593bf94d DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/utils.js.meta b/Runtime/wechat-default/unity-sdk/utils.js.meta index c2ca3dad5..31f6769aa 100644 --- a/Runtime/wechat-default/unity-sdk/utils.js.meta +++ b/Runtime/wechat-default/unity-sdk/utils.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 3d53f875f478136496d5de225cfbea21 +guid: 7c258e23a620de61e310140ffda20f8b DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/video.js.meta b/Runtime/wechat-default/unity-sdk/video.js.meta index 000432ee4..db0f38452 100644 --- a/Runtime/wechat-default/unity-sdk/video.js.meta +++ b/Runtime/wechat-default/unity-sdk/video.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 95f7e07e318c8dadea93b70b7c2b2009 +guid: 71d20b5ae2c4c29f215de587cb2f90fe DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/unity-sdk/video/index.js.meta b/Runtime/wechat-default/unity-sdk/video/index.js.meta index 84da204f1..29ca331a2 100644 --- a/Runtime/wechat-default/unity-sdk/video/index.js.meta +++ b/Runtime/wechat-default/unity-sdk/video/index.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: de851da3584a727475ca46eb52a42695 +guid: faba0c650c3d38061cf2c1a4489ac8cf DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/wasmcode/game.js.meta b/Runtime/wechat-default/wasmcode/game.js.meta index a63ccad32..6e87d15b4 100644 --- a/Runtime/wechat-default/wasmcode/game.js.meta +++ b/Runtime/wechat-default/wasmcode/game.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 40ce1e5992ecf8b562c3419c7c144f73 +guid: a1c75c45997dfc8ca269c67e7408139e DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/weapp-adapter.js.meta b/Runtime/wechat-default/weapp-adapter.js.meta index e3ac0a867..1f56c73cc 100644 --- a/Runtime/wechat-default/weapp-adapter.js.meta +++ b/Runtime/wechat-default/weapp-adapter.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 35f60381826b934ef26c1dc37ab71509 +guid: 7f2338ad6c58c4bac02d6f4b14738f84 DefaultImporter: externalObjects: {} userData: diff --git a/Runtime/wechat-default/workers/response/index.js.meta b/Runtime/wechat-default/workers/response/index.js.meta index 15006c576..92ae9b011 100644 --- a/Runtime/wechat-default/workers/response/index.js.meta +++ b/Runtime/wechat-default/workers/response/index.js.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: b0b7b24adc9e5cc6890eebfed1cc641d +guid: b91b43e5cc146c0dd78c6b34068325a2 DefaultImporter: externalObjects: {} userData: