From e2bd8238328b11a4f16cfb7e07883c3033488b8f Mon Sep 17 00:00:00 2001 From: Johannes Deml Date: Wed, 11 Dec 2024 19:39:22 +0100 Subject: [PATCH 1/9] Add some more commands to test memory limits --- .../Plugins/WebGL/WebBridge/CommonCommands.cs | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs b/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs index 1e4408a8..0c64ed34 100644 --- a/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs +++ b/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs @@ -21,6 +21,11 @@ namespace Supyrb /// public class CommonCommands : WebCommands { + /// + /// List that stores allocated byte arrays to prevent them from being garbage collected + /// + private List byteArrayMemory = new List(); + /// /// Disable capturing all keyboard input, e.g. for using native html input fields /// Browser Usage: unityGame.SendMessage("WebGL","DisableCaptureAllKeyboardInput"); @@ -58,6 +63,41 @@ public void LogMemory() WebToolPlugins.LogMemory(); } + /// + /// Allocate memory to test memory usage and limits + /// The memory will be stored in a list to prevent it from being garbage collected + /// + /// MB to allocate + [WebCommand(Description = "Allocate memory to test memory usage and limits")] + public void AllocateByteArrayMemory(int mb) + { + byte[] memory = new byte[mb * 1024 * 1024]; + byteArrayMemory.Add(memory); + Debug.Log($"Allocated {mb} MB of memory, total memory usage: {WebToolPlugins.GetTotalMemorySize():0.00}MB"); + } + + /// + /// Release all allocated byte array memory + /// + [WebCommand(Description = "Release all allocated byte array memory")] + [ContextMenu(nameof(ReleaseByteArrayMemory))] + public void ReleaseByteArrayMemory() + { + byteArrayMemory.Clear(); + Debug.Log("Released all allocated byte array memory, it can now be garbage collected"); + } + + /// + /// Trigger garbage collection + /// + [WebCommand(Description = "Trigger garbage collection")] + [ContextMenu(nameof(TriggerGarbageCollection))] + public void TriggerGarbageCollection() + { + GC.Collect(); + Debug.Log("Garbage collection triggered"); + } + /// /// Unloads all unused assets /// Browser Usage: unityGame.SendMessage("WebGL","UnloadUnusedAssets"); @@ -67,6 +107,7 @@ public void LogMemory() public void UnloadUnusedAssets() { Resources.UnloadUnusedAssets(); + Debug.Log("Unloaded unused assets"); } /// @@ -79,6 +120,7 @@ public void UnloadUnusedAssets() public void SetApplicationRunInBackground(int runInBackground) { Application.runInBackground = runInBackground == 1; + Debug.Log($"Application.runInBackground: {Application.runInBackground}"); } /// @@ -90,6 +132,7 @@ public void SetApplicationRunInBackground(int runInBackground) public void SetApplicationTargetFrameRate(int targetFrameRate) { Application.targetFrameRate = targetFrameRate; + Debug.Log($"Application.targetFrameRate: {Application.targetFrameRate}"); } /// @@ -101,6 +144,7 @@ public void SetApplicationTargetFrameRate(int targetFrameRate) public void SetTimeFixedDeltaTime(float fixedDeltaTime) { Time.fixedDeltaTime = fixedDeltaTime; + Debug.Log($"Time.fixedDeltaTime: {Time.fixedDeltaTime}"); } /// @@ -113,6 +157,7 @@ public void SetTimeFixedDeltaTime(float fixedDeltaTime) public void SetTimeTimeScale(float timeScale) { Time.timeScale = timeScale; + Debug.Log($"Time.timeScale: {Time.timeScale}"); } /// @@ -214,6 +259,7 @@ public void LogTextureSupport() public void DeleteAllPlayerPrefs() { PlayerPrefs.DeleteAll(); + Debug.Log("Deleted all player prefs"); } /// @@ -226,6 +272,7 @@ public void DeleteAllPlayerPrefs() public void LogShaderCompilation(int enabled) { GraphicsSettings.logWhenShaderIsCompiled = enabled == 1; + Debug.Log($"GraphicsSettings.logWhenShaderIsCompiled: {GraphicsSettings.logWhenShaderIsCompiled}"); } } } \ No newline at end of file From 9e03c3a43c61ea94c840dc5c00ae5ab9c54b4642 Mon Sep 17 00:00:00 2001 From: Johannes Deml Date: Mon, 16 Dec 2024 20:43:00 +0100 Subject: [PATCH 2/9] Change support newer variables from unity for memory information --- .../WebGL/WebTools/WebToolPlugins.jslib | 28 +++++++++++++------ 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib b/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib index 3140d6e8..893777d5 100644 --- a/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib +++ b/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib @@ -88,41 +88,53 @@ var WebGlPlugins = _GetTotalMemorySize: function() { - if(typeof TOTAL_MEMORY !== 'undefined') { + if(typeof HEAP8 !== 'undefined') { + return HEAP8.length; + } + if(typeof TOTAL_MEMORY !== 'undefined') { // Legacy support return TOTAL_MEMORY; } - console.warn("Problem with retrieving unity value. TOTAL_MEMORY: " + typeof TOTAL_MEMORY); + console.warn("Problem with retrieving total memory size"); return -1; }, _GetTotalStackSize: function() { - if(typeof TOTAL_STACK !== 'undefined') { + if(typeof Module !== 'undefined' && typeof Module.STACK_SIZE !== 'undefined') { + return Module.STACK_SIZE; + } + if(typeof TOTAL_STACK !== 'undefined') { // Legacy support return TOTAL_STACK; } - console.warn("Problem with retrieving unity value. TOTAL_STACK: " + typeof TOTAL_STACK); + console.warn("Problem with retrieving stack size"); return -1; }, _GetStaticMemorySize: function() { - if(typeof STATICTOP !== 'undefined' && typeof STATIC_BASE !== 'undefined') { + if(typeof Module !== 'undefined' && typeof Module.staticAlloc !== 'undefined') { + return Module.staticAlloc; + } + if(typeof STATICTOP !== 'undefined' && typeof STATIC_BASE !== 'undefined') { // Legacy support return STATICTOP - STATIC_BASE; } - console.warn("Problem with retrieving unity value. STATICTOP: " + typeof STATICTOP + ", STATIC_BASE: " + typeof STATIC_BASE); + console.warn("Problem with retrieving static memory size"); return -1; }, _GetDynamicMemorySize: function() { - if(typeof HEAP32 !== 'undefined' && typeof DYNAMICTOP_PTR !== 'undefined' && typeof DYNAMIC_BASE !== 'undefined') { + if(typeof Module !== 'undefined' && typeof Module.dynamicAlloc !== 'undefined') { + return Module.dynamicAlloc; + } + if(typeof HEAP32 !== 'undefined' && typeof DYNAMICTOP_PTR !== 'undefined' && typeof DYNAMIC_BASE !== 'undefined') { // Legacy support return HEAP32[DYNAMICTOP_PTR >> 2] - DYNAMIC_BASE; } - console.warn("Problem with retrieving unity value. HEAP32: " + typeof HEAP32 + ", DYNAMICTOP_PTR: " + typeof DYNAMICTOP_PTR + ", DYNAMIC_BASE: " + typeof DYNAMIC_BASE); + console.warn("Problem with retrieving dynamic memory size"); return -1; } }; From f41f47dc36c45ef431214d5fd625e6b6092e29fe Mon Sep 17 00:00:00 2001 From: Johannes Deml Date: Mon, 16 Dec 2024 21:41:34 +0100 Subject: [PATCH 3/9] Remove memory calls that are not really supported anymore --- .../Plugins/WebGL/WebTools/WebToolPlugins.cs | 65 ++----------------- .../WebGL/WebTools/WebToolPlugins.jslib | 41 +----------- 2 files changed, 6 insertions(+), 100 deletions(-) diff --git a/Assets/Plugins/WebGL/WebTools/WebToolPlugins.cs b/Assets/Plugins/WebGL/WebTools/WebToolPlugins.cs index 8b3c0cd4..e83a8e1e 100644 --- a/Assets/Plugins/WebGL/WebTools/WebToolPlugins.cs +++ b/Assets/Plugins/WebGL/WebTools/WebToolPlugins.cs @@ -34,10 +34,6 @@ public static class WebToolPlugins private static extern string _GetUserAgent(); [DllImport("__Internal")] private static extern uint _GetTotalMemorySize(); - [DllImport("__Internal")] - private static extern uint _GetStaticMemorySize(); - [DllImport("__Internal")] - private static extern uint _GetDynamicMemorySize(); #endif private static bool _infoPanelVisible = false; @@ -154,23 +150,6 @@ public static bool IsMobileDevice() userAgent.Contains("Android"); } - /// - /// Get the total memory size used by the application in MB - /// - /// Size in MB - public static float GetTotalMemorySize() - { -#if UNITY_WEBGL && !UNITY_EDITOR - var bytes = _GetTotalMemorySize(); - return GetMegaBytes(bytes); -#elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS - Debug.Log($"{nameof(WebToolPlugins)}.{nameof(GetTotalMemorySize)} called"); - return -1f; -#else - return -1f; -#endif - } - /// /// Log all current memory data in MB /// @@ -178,58 +157,24 @@ public static void LogMemory() { #if UNITY_WEBGL && !UNITY_EDITOR var managed = GetManagedMemorySize(); - var native = GetNativeMemorySize(); var total = GetTotalMemorySize(); - Debug.Log($"Memory stats:\nManaged: {managed:0.00}MB\nNative: {native:0.00}MB\nTotal: {total:0.00}MB"); + Debug.Log($"Memory stats:\nManaged: {managed:0.00}MB\nTotal: {total:0.00}MB"); #elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS Debug.Log($"{nameof(WebToolPlugins)}.{nameof(LogMemory)} called"); #endif } /// - /// Get the static memory size used by the application in MB - /// - /// Size in MB - public static float GetStaticMemorySize() - { -#if UNITY_WEBGL && !UNITY_EDITOR - var bytes = _GetStaticMemorySize(); - return GetMegaBytes(bytes); -#elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS - Debug.Log($"{nameof(WebToolPlugins)}.{nameof(GetStaticMemorySize)} called"); - return -1f; -#else - return -1f; -#endif - } - - /// - /// Get the dynamic memory size used by the application in MB + /// Get the total memory size used by the application in MB /// /// Size in MB - public static float GetDynamicMemorySize() + public static float GetTotalMemorySize() { #if UNITY_WEBGL && !UNITY_EDITOR - var bytes = _GetStaticMemorySize(); + var bytes = _GetTotalMemorySize(); return GetMegaBytes(bytes); #elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS - Debug.Log($"{nameof(WebToolPlugins)}.{nameof(GetDynamicMemorySize)} called"); - return -1f; -#else - return -1f; -#endif - } - - /// - /// Get the native memory size used by the application in MB (Static + Dynamic memory) - /// - /// Size in MB - public static float GetNativeMemorySize() - { -#if UNITY_WEBGL && !UNITY_EDITOR - return GetDynamicMemorySize() + GetStaticMemorySize(); -#elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS - Debug.Log($"{nameof(WebToolPlugins)}.{nameof(GetNativeMemorySize)} called"); + Debug.Log($"{nameof(WebToolPlugins)}.{nameof(GetTotalMemorySize)} called"); return -1f; #else return -1f; diff --git a/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib b/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib index 893777d5..67bbd1ed 100644 --- a/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib +++ b/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib @@ -46,7 +46,7 @@ var WebGlPlugins = } var currentTimeRounded = currentTime.toFixed(2); - console.log('Time tracker event ' +eventNameText +': ' + currentTimeRounded + 'ms'); + console.log('Time tracker event ' + eventNameText + ': ' + currentTimeRounded + 'ms'); }, _AddFpsTrackingEvent: function(fps) { @@ -97,45 +97,6 @@ var WebGlPlugins = console.warn("Problem with retrieving total memory size"); return -1; - }, - - _GetTotalStackSize: function() - { - if(typeof Module !== 'undefined' && typeof Module.STACK_SIZE !== 'undefined') { - return Module.STACK_SIZE; - } - if(typeof TOTAL_STACK !== 'undefined') { // Legacy support - return TOTAL_STACK; - } - - console.warn("Problem with retrieving stack size"); - return -1; - }, - - _GetStaticMemorySize: function() - { - if(typeof Module !== 'undefined' && typeof Module.staticAlloc !== 'undefined') { - return Module.staticAlloc; - } - if(typeof STATICTOP !== 'undefined' && typeof STATIC_BASE !== 'undefined') { // Legacy support - return STATICTOP - STATIC_BASE; - } - - console.warn("Problem with retrieving static memory size"); - return -1; - }, - - _GetDynamicMemorySize: function() - { - if(typeof Module !== 'undefined' && typeof Module.dynamicAlloc !== 'undefined') { - return Module.dynamicAlloc; - } - if(typeof HEAP32 !== 'undefined' && typeof DYNAMICTOP_PTR !== 'undefined' && typeof DYNAMIC_BASE !== 'undefined') { // Legacy support - return HEAP32[DYNAMICTOP_PTR >> 2] - DYNAMIC_BASE; - } - - console.warn("Problem with retrieving dynamic memory size"); - return -1; } }; From 04efb17d6cd6761de69eedf22f5d8d47714f91d7 Mon Sep 17 00:00:00 2001 From: Johannes Deml Date: Mon, 16 Dec 2024 21:42:01 +0100 Subject: [PATCH 4/9] Add clipboard and download methods to bridge and commands --- .../Plugins/WebGL/WebBridge/CommonCommands.cs | 83 ++++++++++++++ .../Plugins/WebGL/WebTools/WebToolPlugins.cs | 101 ++++++++++++++++++ .../WebGL/WebTools/WebToolPlugins.jslib | 67 ++++++++++++ 3 files changed, 251 insertions(+) diff --git a/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs b/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs index 0c64ed34..fab7f7b6 100644 --- a/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs +++ b/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs @@ -274,5 +274,88 @@ public void LogShaderCompilation(int enabled) GraphicsSettings.logWhenShaderIsCompiled = enabled == 1; Debug.Log($"GraphicsSettings.logWhenShaderIsCompiled: {GraphicsSettings.logWhenShaderIsCompiled}"); } + + /// + /// Copy text to clipboard using the browser's clipboard API + /// + /// Text to copy to clipboard + [WebCommand(Description = "Copy text to clipboard")] + public void CopyToClipboard(string text) + { + bool success = WebToolPlugins.CopyToClipboard(text); + Debug.Log($"Copy to clipboard {(success ? "successful" : "failed")}: {text}"); + } + + /// + /// Get current clipboard content using the browser's clipboard API + /// Note: Requires clipboard-read permission in modern browsers + /// + [WebCommand(Description = "Get current clipboard content")] + public void GetClipboardContent() + { + string content = WebToolPlugins.GetClipboardContent(); + Debug.Log($"Clipboard content: {content}"); + } + + /// + /// Check if the browser has an internet connection + /// + [WebCommand(Description = "Check if browser is online")] + public void CheckOnlineStatus() + { + bool isOnline = WebToolPlugins.IsOnline(); + Debug.Log($"Online Status: {(isOnline ? "Connected" : "Disconnected")}"); + } + + /// + /// Captures the current screen and saves it as a PNG file. + /// + [WebCommand(Description = "Save current screen as PNG")] + public void SaveScreenshot() + { + SaveScreenshot(1); + } + + /// + /// Captures the current screen and saves it as a PNG file. + /// + /// 1 for normal size, 2 for double size, 4 for quadruple size + [WebCommand(Description = "Save current screen as PNG with variable super size")] + public void SaveScreenshot(int superSize) + { + string filename = "screenshot.png"; + try + { + // Capture the screen + var screenshot = ScreenCapture.CaptureScreenshotAsTexture(superSize); + + try + { + // Convert to PNG + byte[] pngData = screenshot.EncodeToPNG(); + + // Download through browser + WebToolPlugins.DownloadBinaryFile(filename, pngData, "image/png"); + + Debug.Log($"Screenshot saved as {filename}"); + } + finally + { + // Clean up the texture + if (Application.isPlaying) + { + Destroy(screenshot); + } + else + { + DestroyImmediate(screenshot); + } + } + } + catch (System.Exception e) + { + Debug.LogError($"Failed to save screenshot: {e.Message}"); + } + } } } \ No newline at end of file diff --git a/Assets/Plugins/WebGL/WebTools/WebToolPlugins.cs b/Assets/Plugins/WebGL/WebTools/WebToolPlugins.cs index e83a8e1e..ae7689df 100644 --- a/Assets/Plugins/WebGL/WebTools/WebToolPlugins.cs +++ b/Assets/Plugins/WebGL/WebTools/WebToolPlugins.cs @@ -34,6 +34,17 @@ public static class WebToolPlugins private static extern string _GetUserAgent(); [DllImport("__Internal")] private static extern uint _GetTotalMemorySize(); + [DllImport("__Internal")] + private static extern bool _CopyToClipboard(string text); + [DllImport("__Internal")] + private static extern string _GetClipboardContent(); + [DllImport("__Internal")] + private static extern int _IsOnline(); + [DllImport("__Internal")] + private static extern void _DownloadFile(string filename, string content); + [DllImport("__Internal")] + private static extern void _DownloadBlob(string filename, byte[] byteArray, int byteLength, string mimeType); + #endif private static bool _infoPanelVisible = false; @@ -200,5 +211,95 @@ private static float GetMegaBytes(uint bytes) { return (float)bytes / (1024 * 1024); } + + /// + /// Copies the specified text to the system clipboard using the browser's clipboard API. + /// Only works in WebGL builds and requires clipboard-write permission in modern browsers. + /// + /// The text to copy to the clipboard + /// True if the copy operation was successful, false otherwise + public static bool CopyToClipboard(string text) + { + #if UNITY_WEBGL && !UNITY_EDITOR + return _CopyToClipboard(text); + #elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS + Debug.Log($"{nameof(WebToolPlugins)}.{nameof(CopyToClipboard)} called with: {text}"); + return false; + #else + return false; + #endif + } + + /// + /// Retrieves the current content from the system clipboard using the browser's clipboard API. + /// Only works in WebGL builds and requires clipboard-read permission in modern browsers. + /// + /// The clipboard content as string, or empty string if clipboard is empty or access was denied + public static string GetClipboardContent() + { + #if UNITY_WEBGL && !UNITY_EDITOR + return _GetClipboardContent(); + #elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS + Debug.Log($"{nameof(WebToolPlugins)}.{nameof(GetClipboardContent)} called"); + return string.Empty; + #else + return string.Empty; + #endif + } + + /// + /// Checks if the browser currently has an internet connection using the navigator.onLine property. + /// + /// True if the browser is online, false if it's offline + public static bool IsOnline() + { + #if UNITY_WEBGL && !UNITY_EDITOR + return _IsOnline() == 1; + #elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS + Debug.Log($"{nameof(WebToolPlugins)}.{nameof(IsOnline)} called"); + return true; + #else + return true; + #endif + } + + /// + /// Downloads a text file through the browser with the specified filename and content. + /// Creates a temporary anchor element to trigger the download. + /// + /// The name of the file to be downloaded + /// The text content to be saved in the file + public static void DownloadTextFile(string filename, string content) + { + #if UNITY_WEBGL && !UNITY_EDITOR + _DownloadFile(filename, content); + #elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS + Debug.Log($"{nameof(WebToolPlugins)}.{nameof(DownloadTextFile)} called with filename: {filename}"); + #endif + } + + /// + /// Downloads a binary file through the browser with the specified filename and data. + /// Creates a Blob with the specified MIME type and triggers the download. + /// + /// The name of the file to be downloaded + /// The binary data to be saved in the file + /// The MIME type of the file (defaults to "application/octet-stream") + /// + /// + /// // Example: Save a Texture2D as PNG + /// Texture2D texture; + /// byte[] pngData = texture.EncodeToPNG(); + /// WebToolPlugins.DownloadBinaryFile("texture.png", pngData, "image/png"); + /// + /// + public static void DownloadBinaryFile(string filename, byte[] data, string mimeType = "application/octet-stream") + { + #if UNITY_WEBGL && !UNITY_EDITOR + _DownloadBlob(filename, data, data.Length, mimeType); + #elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS + Debug.Log($"{nameof(WebToolPlugins)}.{nameof(DownloadBinaryFile)} called with filename: {filename}"); + #endif + } } } \ No newline at end of file diff --git a/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib b/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib index 67bbd1ed..2cb864af 100644 --- a/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib +++ b/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib @@ -97,6 +97,73 @@ var WebGlPlugins = console.warn("Problem with retrieving total memory size"); return -1; + }, + + _CopyToClipboard: function(text) { + var str = UTF8ToString(text); + navigator.clipboard.writeText(str) + .then(function() { + console.log('Text copied to clipboard'); + return true; + }) + .catch(function(err) { + console.error('Failed to copy text: ', err); + return false; + }); + }, + + _GetClipboardContent: function() { + // Note: This requires clipboard-read permission + navigator.clipboard.readText() + .then(function(text) { + var bufferSize = lengthBytesUTF8(text) + 1; + var buffer = _malloc(bufferSize); + stringToUTF8(text, buffer, bufferSize); + return buffer; + }) + .catch(function(err) { + console.error('Failed to read clipboard: ', err); + return null; + }); + }, + + _IsOnline: function() { + return navigator.onLine ? 1 : 0; + }, + + _DownloadFile: function(filename, content) { + var filenameStr = UTF8ToString(filename); + var contentStr = UTF8ToString(content); + + var element = document.createElement('a'); + element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(contentStr)); + element.setAttribute('download', filenameStr); + element.style.display = 'none'; + document.body.appendChild(element); + element.click(); + document.body.removeChild(element); + }, + + _DownloadBlob: function(filename, byteArray, byteLength, mimeType) { + var filenameStr = UTF8ToString(filename); + var mimeTypeStr = UTF8ToString(mimeType); + + var data = new Uint8Array(byteLength); + for (var i = 0; i < byteLength; i++) { + data[i] = HEAPU8[byteArray + i]; + } + + var blob = new Blob([data], { type: mimeTypeStr }); + var url = URL.createObjectURL(blob); + + var element = document.createElement('a'); + element.setAttribute('href', url); + element.setAttribute('download', filenameStr); + element.style.display = 'none'; + document.body.appendChild(element); + element.click(); + document.body.removeChild(element); + URL.revokeObjectURL(url); } }; From db371b9f00c728a8a6cc656ef081ee9b252bc1f7 Mon Sep 17 00:00:00 2001 From: Johannes Deml Date: Mon, 16 Dec 2024 22:11:08 +0100 Subject: [PATCH 5/9] Change cleanup output for supported commands --- Assets/Plugins/WebGL/WebBridge/WebBridge.cs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/Assets/Plugins/WebGL/WebBridge/WebBridge.cs b/Assets/Plugins/WebGL/WebBridge/WebBridge.cs index 0bca0b6a..4ca27a17 100644 --- a/Assets/Plugins/WebGL/WebBridge/WebBridge.cs +++ b/Assets/Plugins/WebGL/WebBridge/WebBridge.cs @@ -109,6 +109,7 @@ public void Help() { sb.AppendLine($"---{webCommand.GetType().Name}---"); MethodInfo[] methods = webCommand.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance); + Array.Sort(methods, (a, b) => string.Compare(a.Name, b.Name)); for (int i = 0; i < methods.Length; i++) { @@ -123,11 +124,11 @@ public void Help() var parameter = parameters[j]; if (parameter.ParameterType == typeof(string)) { - sb.Append($", \"{parameter.ParameterType} {parameter.Name}\""); + sb.Append($", \"{GetFriendlyTypeName(parameter.ParameterType)} {parameter.Name}\""); } else { - sb.Append($", {parameter.ParameterType} {parameter.Name}"); + sb.Append($", {GetFriendlyTypeName(parameter.ParameterType)} {parameter.Name}"); } } @@ -140,5 +141,16 @@ public void Help() sb.AppendLine($"\nRun a command with 'runUnityCommand(\"COMMAND_NAME\",PARAMETER);'"); Debug.Log(sb.ToString()); } + + private string GetFriendlyTypeName(Type type) + { + if (type == typeof(int)) return "int"; + if (type == typeof(long)) return "long"; + if (type == typeof(float)) return "float"; + if (type == typeof(double)) return "double"; + if (type == typeof(bool)) return "bool"; + if (type == typeof(string)) return "string"; + return type.Name; + } } } \ No newline at end of file From 8995ad3bf6254cf53fe50830a971ade019ff898f Mon Sep 17 00:00:00 2001 From: Johannes Deml Date: Mon, 16 Dec 2024 22:11:55 +0100 Subject: [PATCH 6/9] Update bundle version to 1.4.0 --- ProjectSettings/ProjectSettings.asset | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ProjectSettings/ProjectSettings.asset b/ProjectSettings/ProjectSettings.asset index 42f4f36c..e0305a2f 100644 --- a/ProjectSettings/ProjectSettings.asset +++ b/ProjectSettings/ProjectSettings.asset @@ -139,7 +139,7 @@ PlayerSettings: loadStoreDebugModeEnabled: 0 visionOSBundleVersion: 1.0 tvOSBundleVersion: 1.0 - bundleVersion: 1.3.0 + bundleVersion: 1.4.0 preloadedAssets: [] metroInputSource: 0 wsaTransparentSwapchain: 0 From eb449aef1cc789a177e3c9e3003a97d186bb1367 Mon Sep 17 00:00:00 2001 From: Johannes Deml Date: Mon, 16 Dec 2024 22:23:16 +0100 Subject: [PATCH 7/9] Add logic to also always build when pushing to master to check if everything is correct there --- .github/workflows/release.yml | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9139e86a..1a08d576 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,6 +5,8 @@ on: push: tags: - '*' + branches: + - master jobs: variables: @@ -28,7 +30,12 @@ jobs: - name: Set tag id: set_tag - run: echo "VERSION=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_OUTPUT + run: | + if [[ $GITHUB_REF == refs/tags/* ]]; then + echo "VERSION=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_OUTPUT + else + echo "VERSION=${{ steps.set_unity_version.outputs.VERSION }}-webgl2-master" >> $GITHUB_OUTPUT + fi - name: Set target name id: set_build_name @@ -62,8 +69,8 @@ jobs: buildProject: name: Create Unity WebGL Build 🏗 - # only build with additional parameters, the tag alone should only create a release draft - if: ${{ needs.variables.outputs.TAG != needs.variables.outputs.UNITY_VERSION }} + # Build if it's a master push or if the tag is not just the unity version + if: ${{ github.ref == 'refs/heads/master' || needs.variables.outputs.TAG != needs.variables.outputs.UNITY_VERSION }} needs: [ variables ] runs-on: ubuntu-latest strategy: @@ -112,7 +119,7 @@ jobs: createRelease: name: Create Github release 🐙 # only run for the pure tag without build parameters - if: ${{ needs.variables.outputs.TAG == needs.variables.outputs.UNITY_VERSION }} + if: ${{ github.ref_type == 'tag' && needs.variables.outputs.TAG == needs.variables.outputs.UNITY_VERSION }} needs: [ variables ] runs-on: ubuntu-latest steps: From d97c3d64ff9a3c46f61e11f6c56b990005054472 Mon Sep 17 00:00:00 2001 From: Johannes Deml Date: Mon, 16 Dec 2024 23:02:00 +0100 Subject: [PATCH 8/9] Try to fix CopyToClipboard and SaveScreenshot --- .../Plugins/WebGL/WebBridge/CommonCommands.cs | 23 +++++++--------- .../Plugins/WebGL/WebTools/WebToolPlugins.cs | 26 ++----------------- .../WebGL/WebTools/WebToolPlugins.jslib | 18 ------------- 3 files changed, 12 insertions(+), 55 deletions(-) diff --git a/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs b/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs index fab7f7b6..bdd20225 100644 --- a/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs +++ b/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs @@ -9,6 +9,7 @@ // -------------------------------------------------------------------------------------------------------------------- using System; +using System.Collections; using System.Collections.Generic; using Supyrb.Attributes; using UnityEngine; @@ -282,19 +283,7 @@ public void LogShaderCompilation(int enabled) [WebCommand(Description = "Copy text to clipboard")] public void CopyToClipboard(string text) { - bool success = WebToolPlugins.CopyToClipboard(text); - Debug.Log($"Copy to clipboard {(success ? "successful" : "failed")}: {text}"); - } - - /// - /// Get current clipboard content using the browser's clipboard API - /// Note: Requires clipboard-read permission in modern browsers - /// - [WebCommand(Description = "Get current clipboard content")] - public void GetClipboardContent() - { - string content = WebToolPlugins.GetClipboardContent(); - Debug.Log($"Clipboard content: {content}"); + WebToolPlugins.CopyToClipboard(text); } /// @@ -323,6 +312,14 @@ public void SaveScreenshot() [WebCommand(Description = "Save current screen as PNG with variable super size")] public void SaveScreenshot(int superSize) { + StartCoroutine(CaptureScreenshot(superSize)); + } + + private IEnumerator CaptureScreenshot(int superSize) + { + // Wait for the end of frame to ensure everything is rendered + yield return new WaitForEndOfFrame(); + string filename = "screenshot.png"; try { diff --git a/Assets/Plugins/WebGL/WebTools/WebToolPlugins.cs b/Assets/Plugins/WebGL/WebTools/WebToolPlugins.cs index ae7689df..b79af50b 100644 --- a/Assets/Plugins/WebGL/WebTools/WebToolPlugins.cs +++ b/Assets/Plugins/WebGL/WebTools/WebToolPlugins.cs @@ -37,8 +37,6 @@ public static class WebToolPlugins [DllImport("__Internal")] private static extern bool _CopyToClipboard(string text); [DllImport("__Internal")] - private static extern string _GetClipboardContent(); - [DllImport("__Internal")] private static extern int _IsOnline(); [DllImport("__Internal")] private static extern void _DownloadFile(string filename, string content); @@ -218,32 +216,12 @@ private static float GetMegaBytes(uint bytes) /// /// The text to copy to the clipboard /// True if the copy operation was successful, false otherwise - public static bool CopyToClipboard(string text) + public static void CopyToClipboard(string text) { #if UNITY_WEBGL && !UNITY_EDITOR - return _CopyToClipboard(text); + _CopyToClipboard(text); #elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS Debug.Log($"{nameof(WebToolPlugins)}.{nameof(CopyToClipboard)} called with: {text}"); - return false; - #else - return false; - #endif - } - - /// - /// Retrieves the current content from the system clipboard using the browser's clipboard API. - /// Only works in WebGL builds and requires clipboard-read permission in modern browsers. - /// - /// The clipboard content as string, or empty string if clipboard is empty or access was denied - public static string GetClipboardContent() - { - #if UNITY_WEBGL && !UNITY_EDITOR - return _GetClipboardContent(); - #elif UNITY_EDITOR && WEBTOOLS_LOG_CALLS - Debug.Log($"{nameof(WebToolPlugins)}.{nameof(GetClipboardContent)} called"); - return string.Empty; - #else - return string.Empty; #endif } diff --git a/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib b/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib index 2cb864af..637e9216 100644 --- a/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib +++ b/Assets/Plugins/WebGL/WebTools/WebToolPlugins.jslib @@ -103,27 +103,9 @@ var WebGlPlugins = var str = UTF8ToString(text); navigator.clipboard.writeText(str) .then(function() { - console.log('Text copied to clipboard'); - return true; }) .catch(function(err) { console.error('Failed to copy text: ', err); - return false; - }); - }, - - _GetClipboardContent: function() { - // Note: This requires clipboard-read permission - navigator.clipboard.readText() - .then(function(text) { - var bufferSize = lengthBytesUTF8(text) + 1; - var buffer = _malloc(bufferSize); - stringToUTF8(text, buffer, bufferSize); - return buffer; - }) - .catch(function(err) { - console.error('Failed to read clipboard: ', err); - return null; }); }, From 6d068571a46ad7b7962988bcd80be9642febdb83 Mon Sep 17 00:00:00 2001 From: Johannes Deml Date: Mon, 16 Dec 2024 23:14:46 +0100 Subject: [PATCH 9/9] Change don't try to do overloads of method names --- Assets/Plugins/WebGL/WebBridge/CommonCommands.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs b/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs index bdd20225..d4d48e2d 100644 --- a/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs +++ b/Assets/Plugins/WebGL/WebBridge/CommonCommands.cs @@ -302,7 +302,7 @@ public void CheckOnlineStatus() [WebCommand(Description = "Save current screen as PNG")] public void SaveScreenshot() { - SaveScreenshot(1); + SaveScreenshotSuperSize(1); } /// @@ -310,7 +310,7 @@ public void SaveScreenshot() /// /// 1 for normal size, 2 for double size, 4 for quadruple size [WebCommand(Description = "Save current screen as PNG with variable super size")] - public void SaveScreenshot(int superSize) + public void SaveScreenshotSuperSize(int superSize) { StartCoroutine(CaptureScreenshot(superSize)); } @@ -324,7 +324,7 @@ private IEnumerator CaptureScreenshot(int superSize) try { // Capture the screen - var screenshot = ScreenCapture.CaptureScreenshotAsTexture(superSize); + Texture2D screenshot = ScreenCapture.CaptureScreenshotAsTexture(superSize); try { @@ -334,7 +334,7 @@ private IEnumerator CaptureScreenshot(int superSize) // Download through browser WebToolPlugins.DownloadBinaryFile(filename, pngData, "image/png"); - Debug.Log($"Screenshot saved as {filename}"); + Debug.Log($"Screenshot saved as {filename} ({screenshot.width}x{screenshot.height}) with size {pngData.Length} bytes"); } finally {