diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 82ef1c676..efb9cb783 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,7 +14,7 @@ on: jobs: build_and_deploy_job: env: - DIST_PATH: src/Uno.Wasm.Sample.RayTracer/bin/Release/net6.0/publish/wwwroot + DIST_PATH: src/Uno.Wasm.Sample.RayTracer/bin/Release/net9.0/publish/wwwroot if: (github.event_name == 'pull_request' && github.event.action != 'closed') runs-on: ubuntu-latest @@ -38,15 +38,34 @@ jobs: useConfigFile: true configFilePath: gitversion.yml - - name: Setup dotnet 8.0.100 + # Daily builds install + # - run: | + # wget https://dot.net/v1/dotnet-install.sh + # chmod +x dotnet-install.sh + # ./dotnet-install.sh -c 9.0 -q daily + # echo ~/.dotnet >> $GITHUB_PATH + # + # name: Setup .NET + # + + - name: Setup .NET uses: actions/setup-dotnet@v1.7.2 with: - dotnet-version: '8.0.100' + dotnet-version: '9.0.100-rc.1.24452.12' include-prerelease: true + + - run: | + cd src + dotnet workload install wasm-tools + + name: Setup Workloads + + - run: | + dotnet build -c Release src/Uno.Wasm.Bootstrap/Uno.Wasm.Bootstrap.csproj /bl:./artifacts-logs/build.binlog + name: Build Bootstrap - run: | - dotnet publish -c Release /p:DISABLE_CLIHOST_NET6=true src/Uno.Wasm.Bootstrap/Uno.Wasm.Bootstrap.csproj /bl:./artifacts-logs/build.binlog - dotnet publish -c Release /p:DISABLE_CLIHOST_NET6=true src/Uno.Wasm.Sample.RayTracer/Uno.Wasm.Sample.RayTracer.csproj /bl:./artifacts-logs/build-sample.binlog + dotnet publish -c Release src/Uno.Wasm.Sample.RayTracer/Uno.Wasm.Sample.RayTracer.csproj /bl:./artifacts-logs/build-sample.binlog name: Build WebAssembly app - uses: actions/upload-artifact@v4 @@ -55,6 +74,7 @@ jobs: path: ${{ env.DIST_PATH }} - uses: actions/upload-artifact@v4 + if: always() with: name: logs path: artifacts-logs diff --git a/.gitignore b/.gitignore index 3f5a127b3..1d85e161a 100644 --- a/.gitignore +++ b/.gitignore @@ -267,5 +267,7 @@ launchSettings.json # Directory Cache files .DS_Store thumbs.db +/src/Uno.Wasm.Bootstrap/tools /src/Uno.Wasm.Bootstrap/build/packager /src/Uno.Wasm.Bootstrap/build/wasm-tuner + diff --git a/.vsts-ci.yml b/.vsts-ci.yml index 1f925c2d7..1b20c8ee0 100644 --- a/.vsts-ci.yml +++ b/.vsts-ci.yml @@ -54,4 +54,3 @@ stages: parameters: jobName: macOS_Tests vmImage: macOS-12 - - template: build/ci/stage-build-wsl-tests.yml diff --git a/Readme.md b/Readme.md index 8bb41bc72..985ac2d11 100644 --- a/Readme.md +++ b/Readme.md @@ -2,15 +2,11 @@ [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/unoplatform/Uno.Wasm.Bootstrap) -Uno.Wasm.Bootstrap provides a simple way to package C# .NET code, and run it from a compatible browser environment. +The Uno.Wasm.Bootstrap package provides a runtime bootstrapper of the `Microsoft.NET.Sdk.WebAssembly` SDK from .NET 9. -It is a standalone .NET Web Assembly (Wasm) sdk bootstrapper taking the form of a nuget package. +This package only provides the bootstrapping features to run a .NET assembly and write to the JavaScript console, through `Console.WriteLine`. To write an app that provides UI functionalities, make sur to check out https://aka.platform.uno/get-started. -Installing it on a .NET project (5, 6, 7, 8 or .NET Standard 2.0) with an entry point allows to publish it as part of a Wasm distribution folder, along with CSS, JavaScript and content files. - -This package only provides the bootstrapping features to run a .NET assembly and write to the JavaScript console, through `Console.WriteLine`. - -This package is based on the excellent work from @praeclarum's [OOui Wasm MSBuild task](https://github.com/praeclarum/Ooui). +This work is based on the excellent work from @praeclarum's [OOui Wasm MSBuild task](https://github.com/praeclarum/Ooui). ## Documentation @@ -28,15 +24,11 @@ This package is based on the excellent work from @praeclarum's [OOui Wasm MSBuil - [Splash screen](doc/features-splash-screen.md) - [Threading](doc/features-threading.md) - [Deep linking](doc/features-deep-linking.md) - - [Pre-compression](doc/features-pre-compression.md) - [Embedded mode](doc/features-embedded.mode.md) - [Native Linker Optimization](doc/features-linker-opts.md) - [Memory troubleshooting](doc/features-memory-corruption-troubleshooting.md) - [Module Linking](doc/features-module-linking.md) - [Profiling](doc/features-profiling.md) - - [Node JS](doc/features-node-js.md) - - [Nuget package overrides](doc/features-nuget-package-overrides.md) - - [Prefetching](doc/features-prefetch.md) - [PWA Support](doc/features-pwa.md) - [4GB Support](doc/features-4gb.md) - [HttpRequestMessage Extensions](doc/features-httprequestmessage-extensions.md) @@ -45,3 +37,9 @@ This package is based on the excellent work from @praeclarum's [OOui Wasm MSBuil - [Uno Version Checker](doc/features-version-checker.md) - [Contributing](doc/contributing.md) - [Release procedure](doc/release-procedure.md) + +## Previous releases documentation + +- [8.0.x](https://github.com/unoplatform/Uno.Wasm.Bootstrap/tree/release/stable/8.0/doc) +- [7.0.x](https://github.com/unoplatform/Uno.Wasm.Bootstrap/tree/release/stable/7.0/doc) +- [3.x](https://github.com/unoplatform/Uno.Wasm.Bootstrap/tree/release/stable/3.3/doc) diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt new file mode 100644 index 000000000..4bac042ff --- /dev/null +++ b/THIRD-PARTY-NOTICES.txt @@ -0,0 +1,59 @@ +The Uno Platform uses third-party libraries and resources that may be +distributed under licenses different from the Uno Platform software. + +In the event of accidental failure to list a required notice, please +bring it to our attention. Post an issue at : + + https://github.com/unoplatform/uno/issues + +The attached notices are provided for information only. + +License notice for .NET Core +---------------------------- + +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for ProtoBufJsonConverter +---------------------------- + +Copyright(c) 2023 Stef Heyenrath + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/build/ci/cspell.json b/build/ci/cspell.json index 4358070e9..e41eed86e 100644 --- a/build/ci/cspell.json +++ b/build/ci/cspell.json @@ -205,6 +205,6 @@ "Multi-line code blocks" ], "ignorePaths": [ - "../doc/index.md" + "../doc/index.md", ] } \ No newline at end of file diff --git a/build/ci/dotnet-install.yml b/build/ci/dotnet-install.yml index 50543fdb6..70f263f0f 100644 --- a/build/ci/dotnet-install.yml +++ b/build/ci/dotnet-install.yml @@ -1,10 +1,40 @@ parameters: - DotNetVersion: '7.0.200' + DotNetVersion: '9.0.100-rc.1.24452.12' steps: - task: UseDotNet@2 - displayName: 'Use .NET 6 SDK' + displayName: 'Use .NET SDK' inputs: version: ${{ parameters.DotNetVersion }} includePreviewVersions: true + + # Daily builds install + # - pwsh: | + # $DotNetRoot = "C:\hostedtoolcache\windows\dotnet" + # Invoke-WebRequest "https://dot.net/v1/dotnet-install.ps1" -OutFile "./build/installcli.ps1" + # & ./build/installcli.ps1 -c 9.0 -q daily -InstallDir $DotNetRoot + + # condition: and(succeeded(), eq( variables['Agent.OS'], 'Windows_NT' )) + # displayName: 'Setup .NET (Windows)' + + # - pwsh: | + # wget https://dot.net/v1/dotnet-install.sh + # chmod +x dotnet-install.sh + # ./dotnet-install.sh -c 9.0 -q daily + # echo "[task.setvariable variable=PATH;]${env:PATH}:$env:HOME/.dotnet" + # echo "[task.setvariable variable=DOTNET_ROOT;]$env:HOME/.dotnet" + + # echo "##vso[task.setvariable variable=PATH;]$env:HOME/.dotnet:${env:PATH}" + # echo "##vso[task.setvariable variable=DOTNET_ROOT;]$env:HOME/.dotnet" + + # condition: and(succeeded(), ne( variables['Agent.OS'], 'Windows_NT' )) + # displayName: 'Setup .NET (Linux/macOS)' + + - pwsh: | + cd src + dotnet --version + dotnet --list-sdks + dotnet workload install wasm-tools + + displayName: Setup Workloads diff --git a/build/ci/stage-build-linux-tests.yml b/build/ci/stage-build-linux-tests.yml index 4f1813746..380ec5ac8 100644 --- a/build/ci/stage-build-linux-tests.yml +++ b/build/ci/stage-build-linux-tests.yml @@ -17,6 +17,7 @@ jobs: variables: NUGET_PACKAGES: $(build.sourcesdirectory)/.nuget + WasmCachePath: $(Agent.TempDirectory)/emsdk-cache steps: - checkout: self @@ -25,26 +26,19 @@ jobs: - template: gitversion.yml - template: dotnet-install.yml - - task: UseDotNet@2 - displayName: 'Use .NET SDK' - inputs: - packageType: sdk - version: 8.0.100 - includePreviewVersions: true - - bash: | cd $(build.sourcesdirectory)/src/Uno.Wasm.Bootstrap - dotnet msbuild /r /p:Configuration=Release /p:DISABLE_CLIHOST_NET6=true + dotnet msbuild /r /p:Configuration=Release displayName: Build bootstrap - bash: | cd $(build.sourcesdirectory)/src - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true Uno.Wasm.Bootstrap-netcore-only.slnf /bl:$(build.artifactstagingdirectory)/SampleNet5.binlog + dotnet publish -c Release /m:1 Uno.Wasm.Bootstrap-netcore-only.slnf /bl:$(build.artifactstagingdirectory)/SampleNet5.binlog displayName: Build NetCore-Wasm Sample - task: CopyFiles@2 inputs: - SourceFolder: $(build.sourcesdirectory)/src/Uno.Wasm.Sample.RayTracer/bin/Release/net6.0/publish + SourceFolder: $(build.sourcesdirectory)/src/Uno.Wasm.Sample.RayTracer/bin/Release/net9.0/publish/wwwroot Contents: '**/*.*' TargetFolder: $(build.artifactstagingdirectory)/Uno.Wasm.Sample.RayTracer CleanTargetFolder: false @@ -54,7 +48,7 @@ jobs: ## Raytracer validation - bash: | $(build.sourcesdirectory)/build/scripts/run-tests.sh \ - "$(build.sourcesdirectory)/src/Uno.Wasm.Sample.RayTracer/bin/Release/net6.0/dist" \ + "$(build.sourcesdirectory)/src/Uno.Wasm.Sample.RayTracer/bin/Release/net9.0/publish/wwwroot" \ "$(build.sourcesdirectory)/src/WasmAot.UITests" "http://localhost:8000/" displayName: Raytracer UI Tests Net5 env: @@ -63,43 +57,45 @@ jobs: ## Threads Interp validation - bash: | cd $(build.sourcesdirectory)/src/Uno.Wasm.Threads - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true "/p:WasmShellWebAppBasePath=/" + dotnet clean -c Release + dotnet publish -c Release /m:1 "/p:WasmShellWebAppBasePath=/" displayName: Build Threads test - bash: | $(build.sourcesdirectory)/build/scripts/run-tests.sh \ - "$(build.sourcesdirectory)/src/Uno.Wasm.Threads/bin/Release/net8.0/dist" \ + "$(build.sourcesdirectory)/src/Uno.Wasm.Threads/bin/Release/net9.0/publish/wwwroot" \ "$(build.sourcesdirectory)/src/Uno.Wasm.Threading.UITests" "http://localhost:8000/" displayName: Threading UI Tests + condition: eq( variables['THREAD_TESTING'], 'true' ) env: BUILD_SOURCESDIRECTORY: "$(build.sourcesdirectory)" ### Threads AOT validation - bash: | cd $(build.sourcesdirectory)/src/Uno.Wasm.Threads.Aot - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true "/p:WasmShellWebAppBasePath=/" + dotnet clean -c Release + dotnet publish -c Release /m:1 "/p:WasmShellWebAppBasePath=/" displayName: Build Threads AOT test - bash: | $(build.sourcesdirectory)/build/scripts/run-tests.sh \ - "$(build.sourcesdirectory)/src/Uno.Wasm.Threads.Aot/bin/Release/net6.0/dist" \ + "$(build.sourcesdirectory)/src/Uno.Wasm.Threads.Aot/bin/Release/net9.0/publish/wwwroot" \ "$(build.sourcesdirectory)/src/Uno.Wasm.Threading.UITests" "http://localhost:8000/" displayName: Threading AOT UI Tests + condition: eq( variables['THREAD_TESTING'], 'true' ) env: BUILD_SOURCESDIRECTORY: "$(build.sourcesdirectory)" ## SWA sub-path validation - bash: | cd $(build.sourcesdirectory)/src/Uno.Wasm.Sample.RayTracer - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true "/p:WasmShellWebAppBasePath=/" + dotnet clean -c Release + dotnet publish -c Release /m:1 "/p:WasmShellWebAppBasePath=/" displayName: Build RayTracer with sub-path - task: CopyFiles@2 inputs: - SourceFolder: $(build.sourcesdirectory)/src/Uno.Wasm.Sample.RayTracer/bin/Release/net6.0/publish + SourceFolder: $(build.sourcesdirectory)/src/Uno.Wasm.Sample.RayTracer/bin/Release/net9.0/publish/wwwroot Contents: '**/*.*' TargetFolder: $(build.artifactstagingdirectory)/subpath-override CleanTargetFolder: false @@ -108,7 +104,7 @@ jobs: - bash: | $(build.sourcesdirectory)/build/scripts/run-tests-swa.sh \ - "$(build.sourcesdirectory)/src/Uno.Wasm.Sample.RayTracer/bin/Release/net6.0/dist" \ + "$(build.sourcesdirectory)/src/Uno.Wasm.Sample.RayTracer/bin/Release/net9.0/publish/wwwroot" \ "$(build.sourcesdirectory)/src/WasmAot.UITests" "http://localhost:8000/test/inner" displayName: Raytracer UI Tests Net5 (SWA) env: @@ -117,7 +113,7 @@ jobs: ## Static linking validation - bash: | $(build.sourcesdirectory)/build/scripts/run-tests.sh \ - "$(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Aot.Net6/bin/Release/net6.0/dist" \ + "$(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Aot.Net6/bin/Release/net9.0/publish/wwwroot" \ "$(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Aot.UITests" "http://localhost:8000/" displayName: StaticLinking.Aot Tests net5 env: @@ -126,7 +122,7 @@ jobs: ## Static linking validation (net7) - bash: | $(build.sourcesdirectory)/build/scripts/run-tests.sh \ - "$(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.net7/bin/Release/net7.0/dist" \ + "$(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.net7/bin/Release/net9.0/publish/wwwroot" \ "$(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Aot.UITests" "http://localhost:8000/" displayName: StaticLinking.Aot Tests net7 env: @@ -142,7 +138,7 @@ jobs: ## Static linking validation (net7) - bash: | $(build.sourcesdirectory)/build/scripts/run-tests-csp.sh \ - "$(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.net7/bin/Release/net7.0/dist" \ + "$(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.net7/bin/Release/net9.0/publish/wwwroot" \ "$(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Aot.UITests" "http://localhost:8000/" displayName: StaticLinking.Aot Tests net7 (CSP Enabled) env: @@ -160,7 +156,7 @@ jobs: - task: CopyFiles@2 condition: always() inputs: - SourceFolder: $(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Server.net7/bin/Release/net7.0 + SourceFolder: $(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Server.net7/bin/Release/net9.0 Contents: '**/*.*' TargetFolder: $(build.artifactstagingdirectory)/Uno.Wasm.StaticLinking.Server.net7 CleanTargetFolder: false @@ -170,8 +166,8 @@ jobs: # Interpreter debug for symbols copy issue - bash: | cd $(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Interpreter - dotnet clean -c Debug /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Debug /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/sample.debug-interpreter-linux-debug.binlog + dotnet clean -c Debug + dotnet publish -c Debug /m:1 /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/sample.debug-interpreter-linux-debug.binlog displayName: Build Debug Interpreter with linking Sample - task: PublishBuildArtifacts@1 diff --git a/build/ci/stage-build-macos-tests.yml b/build/ci/stage-build-macos-tests.yml index d6badf5bd..a90fc0e08 100644 --- a/build/ci/stage-build-macos-tests.yml +++ b/build/ci/stage-build-macos-tests.yml @@ -16,40 +16,14 @@ jobs: - template: gitversion.yml - template: dotnet-install.yml - - task: UseDotNet@2 - displayName: 'Use .NET SDK' - inputs: - packageType: sdk - version: 8.0.100 - includePreviewVersions: true - - - bash: brew install ninja - displayName: 'Install Ninja' - - # - bash: | - # source ~/emsdk/emsdk_env.sh - # export PATH=$PATH:$(Agent.WorkFolder)/ninja-mac - # msbuild /r /t:Publish /p:Configuration=Release src/Uno.Wasm.Bootstrap.sln - # - # displayName: MSBuild Validation - - # - task: CopyFiles@2 - # inputs: - # SourceFolder: $(build.sourcesdirectory)/src/Uno.Wasm.AotTests/bin/Release/netstandard2.0/dist - # Contents: '**/*.*' - # TargetFolder: $(build.artifactstagingdirectory) - # CleanTargetFolder: false - # OverWrite: false - # flattenFolders: false - - bash: | cd $(build.sourcesdirectory)/src/Uno.Wasm.Bootstrap dotnet msbuild /r /p:Configuration=Release displayName: Build bootstrap - bash: | - cd $(build.sourcesdirectory)/src/Uno.Wasm.SampleNet6 - dotnet build -m:1 /bl:$(build.artifactstagingdirectory)/SampleNet6-mac.binlog + cd $(build.sourcesdirectory)/src/Uno.Wasm.SampleNet7 + dotnet build -m:1 /bl:$(build.artifactstagingdirectory)/SampleNet7-mac.binlog displayName: Build NetCore-Wasm Sample # Static linking test (net5) without the linker @@ -61,7 +35,7 @@ jobs: - bash: | $(build.sourcesdirectory)/build/scripts/run-tests.sh \ - "$(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Interpreter/bin/Release/net5.0/dist" \ + "$(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Interpreter/bin/Release/net9.0/publish/wwwroot" \ "$(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Aot.UITests" "http://localhost:8000/" displayName: StaticLinking Interpreter Test env: diff --git a/build/ci/stage-build-packages.yml b/build/ci/stage-build-packages.yml index b8aeb9b09..d9cee758d 100644 --- a/build/ci/stage-build-packages.yml +++ b/build/ci/stage-build-packages.yml @@ -2,7 +2,7 @@ jobs: - job: Windows pool: - vmImage: 'windows-2019' + vmImage: 'windows-2022' variables: NUGET_PACKAGES: $(Agent.WorkFolder)\.nuget @@ -11,13 +11,6 @@ jobs: - checkout: self clean: true - - task: UseDotNet@2 - displayName: 'Use .NET SDK' - inputs: - packageType: sdk - version: 8.0.100 - includePreviewVersions: true - - template: gitversion.yml - template: dotnet-install.yml @@ -42,7 +35,7 @@ jobs: - script: | cd $(build.sourcesdirectory)\src - dotnet msbuild Uno.Wasm.Bootstrap-paclages-only.slnf /r /p:Configuration=Release /p:InformationalVersion=$(GITVERSION.INFORMATIONALVERSION) /p:PackageReleaseNotesFile=$(Build.SourcesDirectory)/build/CHANGELOG.md /p:PackageVersion=$(GITVERSION.FullSemVer) /p:PackageOutputPath=$(build.sourcesdirectory)\build\nuget /bl:$(build.artifactstagingdirectory)/win-packages.binlog + dotnet msbuild Uno.Wasm.Bootstrap-packages-only.slnf /r /p:Configuration=Release /p:InformationalVersion=$(GITVERSION.INFORMATIONALVERSION) /p:PackageReleaseNotesFile=$(Build.SourcesDirectory)/build/CHANGELOG.md /p:PackageVersion=$(GITVERSION.FullSemVer) /p:PackageOutputPath=$(build.sourcesdirectory)\build\nuget /bl:$(build.artifactstagingdirectory)/win-packages.binlog displayName: Build packages - script: | diff --git a/build/ci/stage-build-windows-tests.yml b/build/ci/stage-build-windows-tests.yml index a037ef209..d73463285 100644 --- a/build/ci/stage-build-windows-tests.yml +++ b/build/ci/stage-build-windows-tests.yml @@ -14,6 +14,7 @@ jobs: variables: NUGET_PACKAGES: $(build.sourcesdirectory)/.nuget NETCORE_VERSION: ${{ parameters.netcore_version }} + # EMCC_DEBUG: 1 steps: - checkout: self @@ -22,45 +23,31 @@ jobs: - template: gitversion.yml - template: dotnet-install.yml - - task: UseDotNet@2 - displayName: 'Use .NET SDK' - inputs: - packageType: sdk - version: 8.0.100 - includePreviewVersions: true - - pwsh: | attrib +r "$(build.sourcesdirectory)/src" /s /d displayName: Set all repo files as readonly - pwsh: | cd $(build.sourcesdirectory)/src/Uno.Wasm.Bootstrap - dotnet msbuild /r /p:Configuration=Release /p:DISABLE_CLIHOST_NET6=true - displayName: Build bootstrap - - - pwsh: | - cd $(build.sourcesdirectory)/src/Uno.Wasm.Bootstrap - dotnet msbuild /r /p:Configuration=Release /p:DISABLE_CLIHOST_NET6=true + dotnet msbuild /r /p:Configuration=Release displayName: Build bootstrap - pwsh: | - cd $(build.sourcesdirectory)/src/Uno.Wasm.SampleNet6 - $customMonoTempPath="$env:temp\with a space\test" - mkdir $customMonoTempPath - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish /p:Configuration=Release /m:1 "/p:WasmShellMonoTempFolder=$customMonoTempPath" /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/SampleNet6-win-temp-with-space.binlog + cd $(build.sourcesdirectory)/src/Uno.Wasm.SampleNet7 + dotnet clean -c Release + dotnet publish /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/SampleNet7-win-temp-with-space.binlog displayName: Build Raytracer Sample with Spaces # Standalone Server publish - pwsh: | cd $(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Server.net7 - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/SampleServerNet7-win.binlog + dotnet clean -c Release + dotnet publish -c Release /m:1 /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/SampleServerNet7-win.binlog displayName: Build Standalone Server publish (net5) - pwsh: | $(build.sourcesdirectory)\build\scripts\run-tests-windows-server.ps1 ` - "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Server.net7\bin\Release\net7.0\publish" ` + "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Server.net7\bin\Release\net9.0\publish" ` "Uno.Wasm.StaticLinking.Server.net7.exe" ` "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.UITests" ` "http://localhost:8000/" @@ -73,21 +60,19 @@ jobs: - pwsh: | cd $(build.sourcesdirectory)/src/Uno.Wasm.Sample.RayTracer - $customMonoTempPath="$env:temp\with a space\test2" - mkdir $customMonoTempPath dotnet clean -c Release - dotnet publish -c Release /m:1 "/p:WasmShellMonoTempFolder=$customMonoTempPath" /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/aottest-win-temp-with-space.binlog + dotnet publish -c Release /m:1 "/p:WasmShellMonoTempFolder=$customMonoTempPath" /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/aottest-win-temp-with-space.binlog displayName: Build Raytracer Sample with Spaces - pwsh: | cd $(build.sourcesdirectory)/src/Uno.Wasm.Sample.RayTracer - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/SampleNet5-win.binlog + dotnet clean -c Release + dotnet publish -c Release /m:1 /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/SampleNet5-win.binlog displayName: Build Raytracer Sample - pwsh: | $(build.sourcesdirectory)\build\scripts\run-tests-windows.ps1 ` - "$(build.sourcesdirectory)\src\Uno.Wasm.Sample.RayTracer\bin\Release\net6.0\publish\wwwroot" ` + "$(build.sourcesdirectory)\src\Uno.Wasm.Sample.RayTracer\bin\Release\net9.0\publish\wwwroot" ` "$(build.sourcesdirectory)\src\WasmAot.UITests" ` "http://localhost:8000/" @@ -98,8 +83,8 @@ jobs: # Static linking test (net5) without the linker - pwsh: | cd $(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Interpreter - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /p:WasmShellILLinkerEnabled=false /bl:$(build.artifactstagingdirectory)/SampleNet5-nolinker-win.binlog + dotnet clean -c Release + dotnet publish -c Release /m:1 /p:WasmShellEmccLinkOptimization=false /p:WasmShellILLinkerEnabled=false /bl:$(build.artifactstagingdirectory)/SampleNet5-nolinker-win.binlog displayName: Build StaticLinking.Interpreter Sample (net5 without linker) # Static linking test (net5) emsdk path with space test @@ -107,20 +92,20 @@ jobs: cd $(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Interpreter mkdir "emsdk test" $env:WASMSHELL_WSLEMSDK="$(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Interpreter/emsdk test" - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /p:WasmShellILLinkerEnabled=false /bl:$(build.artifactstagingdirectory)/SampleNet5-emsdk-space.binlog + dotnet clean -c Release + dotnet publish -c Release /m:1 /p:WasmShellEmccLinkOptimization=false /p:WasmShellILLinkerEnabled=false /bl:$(build.artifactstagingdirectory)/SampleNet5-emsdk-space.binlog displayName: Build StaticLinking.Interpreter Sample (emsdk path with space test) # Static linking test with obsfucation enabled - pwsh: | cd $(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Aot.Net6 - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /p:WasmShellObfuscateAssemblies=true /bl:$(build.artifactstagingdirectory)/SampleNet6-nolinker-win.binlog + dotnet clean -c Release + dotnet publish -c Release /m:1 /p:WasmShellEmccLinkOptimization=false /p:WasmShellObfuscateAssemblies=true /bl:$(build.artifactstagingdirectory)/SampleNet6-nolinker-win.binlog displayName: Build StaticLinking.StaticLinking.Aot.Net6 Sample (net6 with obfuscation) - pwsh: | $(build.sourcesdirectory)\build\scripts\run-tests-windows.ps1 ` - "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.Net6\bin\Release\net6.0\dist" ` + "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.Net6\bin\Release\net9.0\publish\wwwroot" ` "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.UITests" ` "http://localhost:8000/" @@ -131,13 +116,13 @@ jobs: # Static linking test with file name obsfucation enabled - pwsh: | cd $(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Aot.Net6 - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /p:WasmShellAssembliesFileNameObfuscationMode=NoDots /bl:$(build.artifactstagingdirectory)/SampleNet5-nolinker-win.binlog + dotnet clean -c Release + dotnet publish -c Release /m:1 /p:WasmShellEmccLinkOptimization=false /p:WasmShellAssembliesFileNameObfuscationMode=NoDots /bl:$(build.artifactstagingdirectory)/SampleNet5-nolinker-win.binlog displayName: Build StaticLinking.StaticLinking.Aot.Net5 Sample (net5 with file name obfuscation) - pwsh: | $(build.sourcesdirectory)\build\scripts\run-tests-windows.ps1 ` - "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.Net6\bin\Release\net6.0\dist" ` + "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.Net6\bin\Release\net9.0\publish\wwwroot" ` "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.UITests" ` "http://localhost:8000/" @@ -147,7 +132,7 @@ jobs: - pwsh: | $(build.sourcesdirectory)\build\scripts\run-tests-windows.ps1 ` - "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.Net6\bin\Release\net6.0\dist" ` + "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.Net6\bin\Release\net9.0\publish\wwwroot" ` "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.UITests" ` "http://127.0.0.1:8000/" @@ -158,13 +143,13 @@ jobs: # Static linking test with dual obfuscation enabled - pwsh: | cd $(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Aot.Net6 - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /p:WasmShellObfuscateAssemblies=true /p:WasmShellAssembliesFileNameObfuscationMode=NoDots /bl:$(build.artifactstagingdirectory)/SampleNet6-dual-win.binlog + dotnet clean -c Release + dotnet publish -c Release /m:1 /p:WasmShellEmccLinkOptimization=false /p:WasmShellObfuscateAssemblies=true /p:WasmShellAssembliesFileNameObfuscationMode=NoDots /bl:$(build.artifactstagingdirectory)/SampleNet6-dual-win.binlog displayName: Build StaticLinking.Aot.Net6 Sample (dual obfuscation) - pwsh: | $(build.sourcesdirectory)\build\scripts\run-tests-windows.ps1 ` - "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.Net6\bin\Release\net6.0\dist" ` + "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.Net6\bin\Release\net9.0\publish\wwwroot" ` "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.UITests" ` "http://localhost:8000/" @@ -175,13 +160,13 @@ jobs: # Static linking test (net5) - pwsh: | cd $(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Aot.Net6 - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/SampleNet5-win.binlog + dotnet clean -c Release + dotnet publish -c Release /m:1 /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/SampleNet5-win.binlog displayName: Build StaticLinking.Aot Sample (net5) - pwsh: | $(build.sourcesdirectory)\build\scripts\run-tests-windows.ps1 ` - "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.Net6\bin\Release\net6.0\dist" ` + "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.Net6\bin\Release\net9.0\publish\wwwroot" ` "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.UITests" ` "http://localhost:8000/" @@ -192,13 +177,13 @@ jobs: # Static linking test (net7) - pwsh: | cd $(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.net7 - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/SampleNet7-win.binlog + dotnet clean -c Release + dotnet publish -c Release /m:1 /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/SampleNet7-win.binlog displayName: Build StaticLinking.Aot Sample (net7) - pwsh: | $(build.sourcesdirectory)\build\scripts\run-tests-windows.ps1 ` - "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Net7\bin\Release\net7.0\dist" ` + "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Net7\bin\Release\net9.0\publish\wwwroot" ` "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.UITests" ` "http://localhost:8000/" @@ -214,20 +199,20 @@ jobs: rm $(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.net7/obj -r -force cd $(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.net7 - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/SampleNet7-win-nuget-space.binlog + dotnet clean -c Release + dotnet publish -c Release /m:1 /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/SampleNet7-win-nuget-space.binlog displayName: Build StaticLinking with nuget space # Embedded mode test (net6) - pwsh: | cd $(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.Embedded - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/SampleEmbedded-win.binlog + dotnet clean -c Release + dotnet publish -c Release /m:1 /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/SampleEmbedded-win.binlog displayName: Build StaticLinking.Embedded Sample (net6) - pwsh: | $(build.sourcesdirectory)\build\scripts\run-tests-windows.ps1 ` - "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Embedded\bin\Release\net6.0\dist" ` + "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Embedded\bin\Release\net9.0\publish\wwwroot" ` "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.UITests" ` "http://localhost:8000/" @@ -238,40 +223,42 @@ jobs: # Thread test Debug build for emscripten LTO issue - pwsh: | cd $(build.sourcesdirectory)/src/Uno.Wasm.Threads - dotnet clean -c Debug /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Debug /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/sample.threads-win-debug.binlog + dotnet clean -c Debug + dotnet publish -c Debug /m:1 /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/sample.threads-win-debug.binlog displayName: Build Threading Sample # Thread test - pwsh: | cd $(build.sourcesdirectory)/src/Uno.Wasm.Threads - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/sample.threads-win-release.binlog + dotnet clean -c Release + dotnet publish -c Release /m:1 /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/sample.threads-win-release.binlog displayName: Build Threading Sample - pwsh: | $(build.sourcesdirectory)\build\scripts\run-tests-windows.ps1 ` - "$(build.sourcesdirectory)\src\Uno.Wasm.Threads\bin\Release\net8.0\dist" ` + "$(build.sourcesdirectory)\src\Uno.Wasm.Threads\bin\Release\net9.0\publish\wwwroot" ` "$(build.sourcesdirectory)\src\Uno.Wasm.Threading.UITests" ` "http://localhost:8000/" displayName: Threading Tests + condition: eq( variables['THREAD_TESTING'], 'true' ) env: BUILD_SOURCESDIRECTORY: "$(build.sourcesdirectory)" # Thread AOT test - pwsh: | cd $(build.sourcesdirectory)/src/Uno.Wasm.Threads.Aot - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/sample.threads-win.binlog + dotnet clean -c Release + dotnet publish -c Release /m:1 /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/sample.threads-win.binlog displayName: Build Threading AOT Sample - pwsh: | $(build.sourcesdirectory)\build\scripts\run-tests-windows.ps1 ` - "$(build.sourcesdirectory)\src\Uno.Wasm.Threads.Aot\bin\Release\net6.0\dist" ` + "$(build.sourcesdirectory)\src\Uno.Wasm.Threads.Aot\bin\Release\net9.0\publish\wwwroot" ` "$(build.sourcesdirectory)\src\Uno.Wasm.Threading.UITests" ` "http://localhost:8000/" displayName: Threading AOT Tests + condition: eq( variables['THREAD_TESTING'], 'true' ) env: BUILD_SOURCESDIRECTORY: "$(build.sourcesdirectory)" diff --git a/build/ci/stage-build-wsl-tests.yml b/build/ci/stage-build-wsl-tests.yml deleted file mode 100644 index 134f42ba4..000000000 --- a/build/ci/stage-build-wsl-tests.yml +++ /dev/null @@ -1,115 +0,0 @@ -parameters: - jobName: '' - -jobs: -- job: WSL_Tests - timeoutInMinutes: 90 - - pool: - vmImage: 'windows-2022' - - workspace: - clean: all - - steps: - - checkout: self - clean: true - - - pwsh: | - # Set-PSDebug -Trace 1 - - # Workaround from https://github.com/actions/runner-images/issues/6844#issuecomment-1367225048 - # At the time of this comment (30-12-2022) this only works on Azure DevOps hosted - # agents and doesn't work on 1ES images - Write-Host "wsl --update --web-download" - wsl --update --web-download | Out-String - - Write-Host "wsl --version" - wsl --version - - write-host "WSL install of ubuntu." - # wsl --install -d Ubuntu-22.04 --web-download # Similar to https://github.com/Azure/azure-sdk-for-cpp/issues/4397 - - # - # Manual installation of Ubuntu 20.04 - # - $url = "https://aka.ms/wslubuntu2004" # URL of the file to download - $appxInstaller = "$env:TEMP\appx-install" # Folder where the uncompressed files will be saved - $distroInstaller = "$env:TEMP\wsl-install" # Folder for the inner - - mkdir $appxInstaller - mkdir $distroInstaller - - # Download the file - Invoke-WebRequest $url -OutFile "$appxInstaller\distro.zip" - - # Uncompress the file - Expand-Archive -Path "$appxInstaller\distro.zip" -DestinationPath $appxInstaller - - Expand-Archive -Path "$appxInstaller\Ubuntu*_x64.appx" -DestinationPath $distroInstaller - - & $distroInstaller\ubuntu.exe install --root - - # - # End Manual install - # - - write-host "Launch WSL." - $wsl = wsl -l -v | out-string - - write-host $wsl - - # workaround for encoding issue: https://github.com/microsoft/terminal/issues/110 - while ($wsl -notmatch "R`0u`0n`0n`0i`0n`0g") { - start-sleep -seconds 1 - $wsl = wsl -l -v | out-string - write-host $wsl - } - write-host "Ubuntu installed." - - displayName: Install WSL - - - pwsh: | - wsl wget https://packages.microsoft.com/config/ubuntu/22.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb - wsl sudo dpkg -i packages-microsoft-prod.deb - wsl rm packages-microsoft-prod.deb - wsl sudo apt-get update - wsl sudo apt-get install -y ninja-build lbzip2 - wsl sudo apt-get install -y dotnet-sdk-7.0 - displayName: Install WSL dependencies - - - task: UseDotNet@2 - displayName: 'Use .NET SDK' - inputs: - packageType: sdk - version: 8.0.100 - includePreviewVersions: true - - - pwsh: | - cd $(build.sourcesdirectory)/src/Uno.Wasm.Bootstrap - dotnet msbuild /r /p:Configuration=Release /p:DISABLE_CLIHOST_NET6=true - displayName: Build bootstrap - - # Static linking test (WSL Forced) - - pwsh: | - cd $(build.sourcesdirectory)/src/Uno.Wasm.StaticLinking.net7 - dotnet clean -c Release /p:DISABLE_CLIHOST_NET6=true - dotnet publish -c Release /m:1 /p:DISABLE_CLIHOST_NET6=true /p:WasmShellEnableEmscriptenWindows=false /p:WasmShellEmccLinkOptimization=false /bl:$(build.artifactstagingdirectory)/SampleNet7-win-wsl.binlog - displayName: Build StaticLinking.Aot Sample (net7 WSL Forced) - - - pwsh: | - $(build.sourcesdirectory)\build\scripts\run-tests-windows.ps1 ` - "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Net7\bin\Release\net7.0\dist" ` - "$(build.sourcesdirectory)\src\Uno.Wasm.StaticLinking.Aot.UITests" ` - "http://localhost:8000/" - - displayName: StaticLinking.Aot Tests net7 - env: - BUILD_SOURCESDIRECTORY: "$(build.sourcesdirectory)" - - - task: PublishBuildArtifacts@1 - condition: always() - inputs: - PathtoPublish: $(build.artifactstagingdirectory) - ArtifactName: uno-wasm-bootstrap-windows-test - ArtifactType: Container diff --git a/doc/debugger-support.md b/doc/debugger-support.md index e24c06203..2008d0119 100644 --- a/doc/debugger-support.md +++ b/doc/debugger-support.md @@ -4,75 +4,11 @@ uid: UnoWasmBootstrap.Features.Debugger # .NET for WebAssembly Debugger Support -Debugging is supported through the integration of a .NET Core CLI component, which acts as a static files server, as well as a debugger proxy for Chrome (other browsers are not supported). +Debugging is support is provided by .NET, using the WasmApp host. -## Enable the Debugger support +## AOT Debugging and mono tracing -In order to debug an **Uno.Wasm.Bootstrap** enabled project, the Mono runtime debugger must be enabled: - -```xml - - true - -``` - -Debug symbols need to be emitted and be of the type `portable`: - -```xml - - portable - true - -``` - -Finally, the `DEBUG` constant must be defined - -```xml - - $(DefineConstants);TRACE;DEBUG - -``` - -Doing so will enable the deployment of `pdb` files to the browser, and allow for the mono debugger proxy to use them. - -For the time being, you will also need to make sure that mscorlib is disabled in the Linker configuration file: - -```xml - - - -``` - -.NET for WebAssembly now has integrated **preliminary** support for in-browser debugging. Refer to -[this document for up-to-date information](https://github.com/dotnet/runtime/blob/main/docs/workflow/debugging/mono/wasm-debugging.md) on how to set up the debugging. - -## How to use the Browser debugger - -The bootstrapper also supports debugging directly in the browser debugging tools. - -In Visual Studio: - -- Make your project the startup project (right-click **set as startup**) -- In the debugging toolbar: - - Select **IIS Express** as the debugging target - - Select **Chrome** as the Web Browser - - Make sure script debugging is disabled -- Start the debugging session using F5 (or Start Debug) -- Once your application has started, press `Alt+Shift+D` -- Follow the instructions on the web page -- You may need to refresh the original tab if you want to debug the entry point (Main) of your application. - -## Debugger troubleshooting - -The debugger is still under development, and here are a few things to look for: - -- Breakpoints set sometimes disappear when the debugged page is reloaded -- If none of your assemblies appear in the debugger window, it's generally caused -by the debugger caching previously loaded files. Make sure to hit Ctrl+Shit+R to force reload the debugged page. - -## AOT Debugging and mono tracing (.NET 5 only) - -When running with PG-AOT, exceptions generally do not provide stack traces, as WebAssembly as of the MVP does not yet support stack walking. +When running with AOT or Profiled AOT, exceptions generally do not provide complete stack traces, as WebAssembly as of the MVP does not yet support stack walking. For the time being, it's still possible to view browser stack traces in the log by enabling mono tracing. diff --git a/doc/deploy-and-publish.md b/doc/deploy-and-publish.md index 1bbd278f3..414b06a98 100644 --- a/doc/deploy-and-publish.md +++ b/doc/deploy-and-publish.md @@ -6,9 +6,23 @@ uid: UnoWasmBootstrap.Features.Publish The easiest way to publish the build results is to use the Visual Studio publish menu on your project. This will allow to use all the features provided by the standard experience, as described in the [Deploy to Azure App Service](https://docs.microsoft.com/en-us/visualstudio/deployment/quickstart-deploy-to-azure?view=vs-2017). -The publication of the application must be done in .NET Framework hosting (and not .NET Core), as the app uses the `web.config` file for the server configuration, and to enable the use of pre-compression. +In the command line, to publish the app, use the following: -For deeper integration in the publishing pipeline, the `WasmShellOutputPackagePath` property is defined by the bootstrapper after the `BuildDist` target, which contains the path to the generated `package_XXX` content. +```bash +dotnet publish +``` + +The app will be located in the `bin/Release/net9.0/publish/wwwroot` folder. More information about `dotnet publish` can be [found in the Microsoft docs](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-publish). + +## Localization publishing + +By default, the .NET runtime does not load all resource assemblies, but if you want to load all resources regardless of the user's culture, you can add the following to your project file: + +```xml + + true + +``` ## Integration with ASP.NET Core @@ -29,18 +43,3 @@ In order to host an Uno Platform App, you'll need to the following: - Add a project reference to the `Wasm` project - Build and deploy `MyApp.Server` - -## Serve the Wasm app through Windows Linux Subsystem - -Using Windows 10/11, serving the app through a small Web Server is done through WSL. - -Here's how to install it: - -- Search for Ubuntu in the Microsoft Store: https://apps.microsoft.com/store/search/ubuntu -- Install Ubuntu 18.04 or later, and follow the instructions during the first run - - If you have another distribution installed make sure that the 18.04 is the default using `wslconfig /s "Ubuntu-20.04"`. You can list your active distributions with `wslconfig /l` - - Note that WSL 2 is considerably slower than WSL 1 for the bootstrapper scenario. You will need to set your distribution to version 1 using `wsl --set-version "Ubuntu-20.04" 1`. -- Once you've built your project, you should see a path to the project dll -- In the Ubuntu shell, type ``cd `wslpath "[the_path_to_your_bin_folder]\dist"` `` -- Type `python3 server.py` - - If this command does not exist, run the following `sudo apt-get install python3` diff --git a/doc/features-additional-files.md b/doc/features-additional-files.md index 2f393143d..0c0763f05 100644 --- a/doc/features-additional-files.md +++ b/doc/features-additional-files.md @@ -56,7 +56,7 @@ Exclusions: ``` -Asset files: `dist/package_XXXX/uno-assets.txt` contains the package relative paths of the content files that were copied to the `dist/package_XXXX` folder. It can be used to identify which assets are packaged with the application at runtime and avoid costly probing operations. Important: Will only contain files deployed in `UnoDeploy="Package"` mode. +Asset files: `wwwroot/uno-assets.txt` contains the package relative paths of the content files that were copied to the `wwwroot` folder. It can be used to identify which assets are packaged with the application at runtime and avoid costly probing operations. Important: Will only contain files deployed in `UnoDeploy="Package"` mode. A few files extensions are excluded (`UnoDeploy="None")`by default such as `*.a`, `*.bc`. `.html` files are those named `web.config` will default to `UnoDeploy="Root"`. diff --git a/doc/features-interop.md b/doc/features-interop.md index 4491e4461..d9d9a3567 100644 --- a/doc/features-interop.md +++ b/doc/features-interop.md @@ -13,8 +13,6 @@ Two techniques are available: ## Invoking C# code from Javascript -### [**.NET 7 JSExport**](#tab/net7) - .NET 7 introduces the [`[JSExportAttribute]`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.javascript.jsexportattribute?view=net-7.0) which allows for Javascript to invoke C# static methods in a memory, threading and performance efficient way. > [!IMPORTANT] @@ -46,42 +44,9 @@ async function invokeCSMethod() { invokeCSMethod(); ``` -### [**.NET 6 `mono_bind_static_method`**](#tab/jseval) - -In your C# project (named `MyApp` for this example), add the following class: - -```csharp -namespace MyNamespace; - -public static partial class Exports -{ - public static string MyExportedMethod() - { - return $"Invoked"; - } -} -``` - -Then in your Javascript, add the following: - -```js -var myExportedMethod = Module.mono_bind_static_method("[MyApp] MyNamespace.Exports:MyExportedMethod"); -var result = myExportedMethod(); -``` - -> [!IMPORTANT] -> The interop infrastructure only supports primitive types for parameters and return value. -> -> [!IMPORTANT] -> This type of interop is not compatible with [strict CSP](xref:Uno.Wasm.Bootstrap.Security). - ---- - ## Invoking Javascript code from C# -### [**.NET 7 JSImport**](#tab/net7) - Invoking JS functions from C# can be done through [`[JSImportAttribute]`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.javascript.jsimportattribute?view=net-7.0). > [!IMPORTANT] @@ -108,36 +73,3 @@ function myJSMethod(){ ``` In the C# code, call `Imports.MyJSMethod();` as you would any other method. - -### [**.NET 6 JSEval**](#tab/jseval) - -If you're not using Uno.UI, you'll need to define the following in the global namespace: - -```csharp -internal sealed class Interop -{ - internal sealed class Runtime - { - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern string InvokeJS(string str, out int exceptional_result); - } -} -``` - -Then in your Javascript, add the following: - -```js -function myJSMethod(){ - console.log("myJSMethod invoked!"); -} -``` - -And can be used from C# with: - -```cs -InvokeJS("myJSMethod()"); -``` - -Note that the interop only supports strings as the returned value, and parameters must formatted in the string passed to `InvokeJS`. - ---- diff --git a/doc/features-module-linking.md b/doc/features-module-linking.md index be62560cb..7ea7a7fe5 100644 --- a/doc/features-module-linking.md +++ b/doc/features-module-linking.md @@ -21,6 +21,8 @@ This allowing for p/invoke to be functional when resolving methods from the load ``` +The .NET SDK [`NativeFileReference`](https://learn.microsoft.com/en-us/aspnet/core/blazor/webassembly-native-dependencies) is also supported. + ## WebAssembly Exceptions support As of version 7.0 and later, WebAssembly Exceptions support is now required. @@ -113,6 +115,8 @@ The file is provided as-is to `emcc` and its resulting object file is linked wit This feature is meant to be used for small additions of native code. If more is needed (e.g. adding header directories, defines, options, etc...) it is best to use the emcc tooling directly. +The .NET SDK [`NativeFileReference`](https://learn.microsoft.com/en-us/aspnet/core/blazor/webassembly-native-dependencies) is also supported to include C/C++ source files. + ### Example Here's an example of file: diff --git a/doc/features-node-js.md b/doc/features-node-js.md deleted file mode 100644 index 6bf0b60ab..000000000 --- a/doc/features-node-js.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -uid: UnoWasmBootstrap.NodeJS ---- - -# Node.js support - -The bootstrapper supports having a project loaded as part of a node application. To do so: - -- Create a Wasm bootstrapper project, named `MyApp.Wasm` -- Create a Node.js TypeScript project in Visual Studio, named `MyApp.Runner` -- In bootstrapper project, add the following : - - ```xml - ../MyApp.Runner/app - node - ``` - -- In the `app.ts`, add the following: - - ```js - require("./app/mono"); - ``` - -Run the application and the main method of the `MyApp.Wasm` will be executed. - -The parameters of the node command line are provided to the app's main method when running the app as follows: - -```shell -node app param1 param2 -``` diff --git a/doc/features-nuget-package-overrides.md b/doc/features-nuget-package-overrides.md deleted file mode 100644 index 597811afd..000000000 --- a/doc/features-nuget-package-overrides.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -uid: UnoWasmBootstrap.PackageOverrides ---- - -# Nuget package runtime overrides - -By default, when presented with an assembly present in both the runtime and a nuget package, the bootstrapper will favor the runtime's version of the assembly. This is generally required to avoid internal consistency errors with the runtime. - -In some rare cases though, it may still be required to override the runtime's version. To do this, you'll need to add the following to your csproj: - -```xml - - - - -``` - -This will ensure that the System.Text.Json.dll assembly coming from an explicit `PackageReference` will be favored over the runtime version. diff --git a/doc/features-obfuscation.md b/doc/features-obfuscation.md deleted file mode 100644 index d72791a32..000000000 --- a/doc/features-obfuscation.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -uid: UnoWasmBootstrap.Features.Obfuscation ---- - -# Assemblies obfuscation - -The Bootstrapper provides a way to obfuscate served assemblies in order to avoid incorrect flagging by anti-virus and firewalls. - -## Description - -Assemblies currently a critical part of the behavior of .NET, [even when using AOT](runtime-execution-modes.md). Original assemblies are still required for metadata (Reflection) and non-AOTable pieces of code (as of .NET 7, part of try/catch/finally blocks). - -The Uno bootstrapper packages .NET assemblies as part of the final generated web content. Those files are fetched the application directly and the default extension used by the bootstrapper for these files are `.clr` as a minimal attempt to avoid blocking. - -## Changing the assemblies extensions - -This feature allows to change the `.clr` extension for another extension. Add the following to your `csproj` file: - -```xml - - .custom - -``` - -> [!NOTE] -> Changing this extension requires the adjustment of `web.config` or `staticwebapp.config.json` to provide the proper `application/octet-stream` mime type. -> -> [!NOTE] -> As of Bootstrapper 7.0, changing the extension does not permit local Visual Studio debugging and serving. Using [dotnet-serve](https://github.com/natemcmaster/dotnet-serve) is required. - -## Extension-less mode for assemblies - -This feature allows to remove the extension from the assemblies URI, by removing all `.` from the assembly file names. - -Add the following to your `csproj` file: - -```xml - - NoDots - -``` - -Note that serving extension-less files requires a special fallback in servers: - -- For IIS: - - ```xml - - ... - - - ``` - -- For ASP.NET Core, using a [`StaticFileOptions`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.staticfileoptions?view=aspnetcore-7.0) - - ```csharp - app.UseStaticFiles(new StaticFileOptions - { - ... - DefaultContentType = MediaTypeNames.Application.Octet, - ServeUnknownFileTypes = true - }); - ``` - -## Obfuscating the contents of assemblies - -This feature allows to change the contents of the files using a simple XOR transformation applied to the generated site. - -> [!WARNING] -> Ensure that enabling this feature is conforming to the requirements of the deployment environment, commonly defined by an IT department. - -To use this feature, add the following to your `csproj` file: - -```xml - - true - -``` - -> [!WARNING] -> Enabling this feature has an impact on the startup time of the application, as additional process is required to de-obfuscate the downloaded assemblies. diff --git a/doc/features-pre-compression.md b/doc/features-pre-compression.md index 7892ef07e..3d9930f15 100644 --- a/doc/features-pre-compression.md +++ b/doc/features-pre-compression.md @@ -4,42 +4,4 @@ uid: UnoWasmBootstrap.Features.PreCompression # Pre-Compression support -Pre-compression has two modes: - -- In-place, where Brotli compressed files are placed next to original files -- Legacy, where a `web.config` file url rewriter rule is used - -The parameters for the pre-compression are as follows: - -- `WasmShellGenerateCompressedFiles` which can be `true` or `false`. This property is ignored when building `MonoRuntimeDebuggerEnabled` is set to `true`, and `true` by default when the `Configuration` property is set to `Release` -- `WasmShellCompressedExtension` is an item group which specifies which files to compress. By default, the `wasm`, `clr`, `js`, `json`, `css`, `html`, `dat`, `ttf`, and `txt` files are pre-compressed. More files can be added as follows: - - ```xml - - - - ``` - -- `WasmShellBrotliCompressionQuality` which controls the compression quality used to pre-compress the files. Possible values are in the range from `0` to `11`. The default value is `7`. - - > [!WARNING] - > Two-digit compression quality values (`10` and higher) are intended for extra-intensive CPU usage and can significantly slow down build time. - -- `WasmShellCompressionLayoutMode` which can be set to `InPlace` or `Legacy`. If not set and for backward compatibility reasons, `Legacy` is automatically selected if a `web.config` file is detected in the layout, and contains the `_compressed_br` string. - -## Support for in-place compression - -This mode is to be preferred for web servers that support `accept-encoding` header file rewriting. In the case of [**Azure Static WebApps**](https://docs.microsoft.com/en-us/azure/static-web-apps/get-started-portal), if a file next to the original one is suffixed with `.br`, and the client requested for brotli compressed files, the in-place compressed file will be served. -> [!NOTE] -> To achieve the same behavior in a standalone ASP.NET Core application the [CompressedStaticFiles](https://github.com/AnderssonPeter/CompressedStaticFiles) third-party library can be used. - -## Support for IIS / Azure WebApp GZip/Brotli pre-compression - -The IIS compression support has too many knobs for the size of generated WebAssembly files, which -makes the serving of static files inefficient. - -The Bootstrapper tooling will generate two folders `_compressed_gz` and `_compressed_br` which contain compressed versions of the main files. A set IIS rewriting rules are used to redirect the queries to the requested pre-compressed files, with a preference for Brotli. - -When building an application, place [the following file](src/Uno.Wasm.SampleNet6/wwwroot/web.config) in the `wwwroot` folder to automatically enable the use of pre-compressed files. - -Note that the pre-compressed files are optional, and if the rewriting rules are removed or not used (because the site is served without IIS), the original files are available at their normal locations. +Pre-compression support is provided by the .NET SDK, using the `EnableDefaultCompressedItems` feature. diff --git a/doc/features-prefetch.md b/doc/features-prefetch.md deleted file mode 100644 index 956479320..000000000 --- a/doc/features-prefetch.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -uid: UnoWasmBootstrap.Features.Prefetch ---- - -# Support for Content prefetching - -The `WashShellGeneratePrefetchHeaders` controls the generation of `` nodes in the index.html header. - -It is disabled by default and allows for the browser to efficiently fetch the applications WebAssembly and .NET assemblies files, while the JavaScript and WebAssembly runtimes are being initialized. - -This prefetching feature is particularly useful if the HTTP server supports HTTP/2.0. diff --git a/doc/features-security.md b/doc/features-security.md index a58675a41..7c7bb34d8 100644 --- a/doc/features-security.md +++ b/doc/features-security.md @@ -33,7 +33,7 @@ Enabling CSP support can be done in three ways: > [!IMPORTANT] > The Uno.Wasm.Bootstrap package uses WebAssembly, it is required to provide the [`wasm-unsafe-eval`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#unsafe_webassembly_execution) directive in the CSP configuration. -Enabling CSP without `unsafe-eval` implies that the application will not be able to use [Runtime.JSInvoke](xref:Uno.Wasm.Bootstrap.JSInterop), and [JSImport/JSExport](xref:Uno.Wasm.Bootstrap.JSInterop) must be used instead. +Enabling CSP without `unsafe-eval` implies that the application will not be able to use JavaScript's `eval()`, and [JSImport/JSExport](xref:Uno.Wasm.Bootstrap.JSInterop) must be used instead. ### Validation diff --git a/doc/features-simd.md b/doc/features-simd.md index fd190ed44..bc8b325b9 100644 --- a/doc/features-simd.md +++ b/doc/features-simd.md @@ -20,6 +20,8 @@ With .NET 8, SIMD support is enabled by default and can be disabled using: ``` +The .NET SDK [`WasmEnableSIMD`](https://learn.microsoft.com/en-us/aspnet/core/blazor/webassembly-build-tools-and-aot?view=aspnetcore-8.0#single-instruction-multiple-data-simd) property is also supported. + [WebAssembly Support for SIMD](https://github.com/webassembly/simd) enables faster execution for specialized pieces of code, and .NET increasingly uses those instructions to make applications run faster. You can take a look at [this article](https://platform.uno/blog/safari-16-4-support-for-webassembly-fixed-width-simd-how-to-use-it-with-c/) for more information. diff --git a/doc/linker-configuration.md b/doc/linker-configuration.md index 9fd68bf27..2a00b62a1 100644 --- a/doc/linker-configuration.md +++ b/doc/linker-configuration.md @@ -40,7 +40,9 @@ It is also possible to provide the linker file as an embedded resource, which is ``` -The Linker can be disabled completely by setting the `WasmShellILLinkerEnabled` property to false. This property has no effect when building with AOT enabled. +The Linker can be disabled completely by setting the `WasmShellILLinkerEnabled` or `PublishTrimmed` property to false. This property has no effect when building with AOT enabled. + +The .NET SDK configuration [options are also supported](https://learn.microsoft.com/en-us/dotnet/core/deploying/trimming/trim-self-contained). ## .NET 5 Feature Linker Configuration diff --git a/doc/runtime-execution-modes.md b/doc/runtime-execution-modes.md index dbd312fec..e220b410f 100644 --- a/doc/runtime-execution-modes.md +++ b/doc/runtime-execution-modes.md @@ -4,7 +4,7 @@ uid: Uno.Wasm.Bootstrap.Runtime.Execution # Runtime Execution Modes -The mono for WebAssembly runtime provides three execution modes, Interpreter, AOT (Ahead of Time), and Mixed Mode Interpreter/AOT. +The mono for WebAssembly runtime provides three execution modes, Interpreter, and Mixed Mode Interpreter/AOT (Ahead of Time). The execution mode can be set as follows: @@ -17,8 +17,6 @@ The possible values are: - `Interpreter` (the default mode) - `InterpreterAndAOT` -To setup your machine to use AOT modes on Windows, you will need to install [Python from Windows Store](https://www.microsoft.com/store/productId/9P7QFQMJRFP7), or manually through [Python's official site](https://www.python.org/downloads/). - ## Interpreter mode This mode is the slowest but allows for great flexibility and debugging, as well as an efficient payload size. @@ -51,17 +49,20 @@ Finally, runtime statistics are maintained by the jiterpreter and can be display This mode enables AOT compilation for most of the assemblies, with [some specific exceptions](https://github.com/dotnet/runtime/issues/50609). -> [!IMPORTANT] -> This mode is not supported on macOS. You'll need to use a [Linux container](https://hub.docker.com/r/unoplatform/wasm-build) to build with AOT, see below for more details. +By default, this mode is only enabled when running `dotnet publish`. + +To enable AOT compilation on normal builds, use the following: + +```xml + + true + +``` ### Required configuration for Mixed AOT Mode or static linking on Linux -- Ubuntu 18.04+ or a [container](https://hub.docker.com/r/unoplatform/wasm-build) -- A [stable build of mono](https://www.mono-project.com/download/stable/#download-lin) +- Ubuntu 20.04+ or a [container](https://hub.docker.com/r/unoplatform/wasm-build) - A [.NET SDK](https://docs.microsoft.com/en-us/dotnet/core/install/linux-ubuntu) >= 6.0 -- ninja: `apt-get install ninja-build` - -The easiest is to build using the environment provided by the [unoplatform/wasm-build docker image](https://hub.docker.com/r/unoplatform/wasm-build). ## Profile Guided AOT @@ -69,7 +70,7 @@ This mode allows for the AOT engine to selectively optimize methods to WebAssemb This feature is used in two passes: -- The first pass needs the creation of a profiled interpreter build, which records any methods invoked during the profiling session. +- The first pass needs the creation of a profiled interpreted build, which records any methods invoked during the profiling session. - The second pass rebuilds the application using the Mixed AOT/Interpreter mode augmented by the recording created during the first pass. This mode gives very good results, where the RayTracer sample of this repository goes from an uncompressed size of 5.5MB to 2.9MB. @@ -82,12 +83,6 @@ To create a profiled build: true ``` -- In your `LinkerConfig.xml` file, add the following: - - ```xml - - ``` - - Run the application once, without the debugger (e.g. Ctrl+F5) - Navigate throughout the application in high-usage places. - Once done, either: @@ -187,59 +182,3 @@ In order to fix this, you'll need to set the [`INITIAL_MEMORY`](https://emscript ``` which will set the initial memory size accordingly. Note that setting this value to a sufficiently large value (based on your app's usual memory consumption) can improve the startup performance. - -## Required configuration for AOT, Mixed Mode, or external bitcode support compilation on Windows 10 - -### Native windows tooling - -This is the default mode on Windows. It requires installing [Python from Windows Store](https://www.microsoft.com/store/productId/9P7QFQMJRFP7), or manually through [Python's official site](https://www.python.org/downloads/). - -This mode is compatible with CI servers that have Python installed by default, such as [Azure Devops Hosted Agents](https://docs.microsoft.com/en-us/azure/devops/pipelines/agents/hosted?view=azure-devops). - -#### Powershell setup - -The bootstrapper needs to use PowerShell, and configuration is needed. - -You'll need to run the following command in an elevated (administrator) PowerShell prompt: - -```pwsh -Set-ExecutionPolicy RemoteSigned -Force -``` - -You may also need to enable the developer mode for Windows 10 and 11 by using **Control panel** / **System** / **Privacy & Security** / **For developers** / **PowerShell** and setting **Change execution policy to allow local scripts to run without signing** to **On**. - -### Using Windows Subsystem for Linux - -This mode can be enabled by adding this property to the `csproj`: - -```xml - - false - -``` - -Requirements: - -- A Windows 10 machine with [WSL 1 or 2 with Ubuntu 20.04](https://docs.microsoft.com/en-us/windows/wsl/install-win10) installed. -- A [stable build of mono](https://www.mono-project.com/download/stable/#download-lin) -- A [.NET SDK](https://docs.microsoft.com/en-us/dotnet/core/install/linux-ubuntu) >= 3.1 -- ninja: `apt-get install ninja-build` in WSL - -If you have another distribution installed make sure that the 20.04 is the default using `wslconfig /s "Ubuntu-20.04"`. You can list your active distributions with `wslconfig /l` -Note that WSL 2 is considerably slower than WSL 1 for the bootstrapper scenario. You will need to set your distribution to version 1 using `wsl --set-version "Ubuntu-20.04" 1`. - -During the first use of WSL, if the environment is not properly setup, you will be guided to run the [`dotnet-setup.sh`](xref:dotnet-setup.sh) script that will install Mono, .NET Core and some additional dependencies. - -The emscripten installation is automatically done as part of the build. - -The bootstrapper uses its own installation of emscripten, installed by default in `$HOME/.uno/emsdk` in the WSL filesystem. This can be globally overridden by setting the `WASMSHELL_WSLEMSDK` environment variable. - -### WSL Integration for Windows 10 - -The integration with WSL provides a way to use AOT, Mixed mode, or external bitcode support using Windows 10. - -This feature is active only if one of those condition is true: - -- The `WasmShellMonoRuntimeExecutionMode` property is `InterpreterAndAOT` -- There is a `*.bc` or `*.a` file in the `Content` item group -- The `WasmShellForceUseWSL` is set to `true` diff --git a/doc/toc.yml b/doc/toc.yml index c3e525294..4c22f5107 100644 --- a/doc/toc.yml +++ b/doc/toc.yml @@ -9,8 +9,6 @@ items: href: linker-configuration.md - name: Runtime Execution Modes href: runtime-execution-modes.md -- name: Troubleshooting - href: troubleshooting.md - name: Features items: @@ -44,20 +42,12 @@ items: href: features-simd.md - name: Profiling href: features-profiling.md - - name: Node JS - href: features-node-js.md - - name: Nuget package overrides - href: features-nuget-package-overrides.md - - name: Prefetching - href: features-prefetch.md - name: PWA Support href: features-pwa.md - name: 4GB Support href: features-4gb.md - name: HttpRequestMessage Extensions href: features-httprequestmessage-extensions.md - - name: Assemblies obfuscation - href: features-obfuscation.md - name: Tools items: diff --git a/doc/troubleshooting.md b/doc/troubleshooting.md deleted file mode 100644 index fa32a07d9..000000000 --- a/doc/troubleshooting.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -uid: UnoWasmBootstrap.Features.Troubleshooting ---- - -# Windows Long Path support - -The bootstrapper supports Windows 10 long paths by default, but there may be cases where the `\\?\` [path format](https://web.archive.org/web/20160818035729/https://blogs.msdn.microsoft.com/jeremykuhne/2016/06/21/more-on-new-net-path-handling/) may not be supported. - -In such a case, setting the `false` in the project file can disable this feature. diff --git a/doc/using-the-bootstrapper.md b/doc/using-the-bootstrapper.md index 0d625a891..b939c4a3c 100644 --- a/doc/using-the-bootstrapper.md +++ b/doc/using-the-bootstrapper.md @@ -4,32 +4,34 @@ uid: UnoWasmBootstrap.Overview # Using the bootstrapper -Uno.Wasm.Bootstrap provides a simple way to package C# .NET code, and run it from a compatible browser environment. +The Uno.Wasm.Bootstrap package provides a runtime bootstrapper of the `Microsoft.NET.Sdk.WebAssembly` SDK from .NET 9. -It is a standalone .NET Web Assembly (Wasm) sdk bootstrapper taking the form of a nuget package. +This package only provides the bootstrapping features to run a .NET assembly and write to the javascript console, through `Console.WriteLine`. To write an app that provides UI functionalities, make sur to check out https://aka.platform.uno/get-started. -Installing it on a .NET project (5, 6 or .NET Standard 2.0) with an entry point allows to publish it as part of a Wasm distribution folder, along with CSS, Javascript and content files. +This work is based on the excellent work from @praeclarum's [OOui Wasm MSBuild task](https://github.com/praeclarum/Ooui). -This package only provides the bootstrapping features to run a .NET assembly and write to the javascript console, through `Console.WriteLine`. +## Prepare your machine -This package is based on the excellent work from @praeclarum's [OOui Wasm MSBuild task](https://github.com/praeclarum/Ooui). +On the command line, type the following to install the WebAssembly workload: -## How to use the bootstrapper with .NET 5 and later +```bash +dotnet workload install wasm-tools +``` + +## How to use the Bootstrapper with .NET 9 and later -- Create a .NET 5 Console Application, and update it with the following basic definition: +- Create a .NET 9 Console Application, and update it with the following basic definition: ```xml - + Exe - net5.0 - true + net9.0 - - + @@ -47,15 +49,13 @@ This package is based on the excellent work from @praeclarum's [OOui Wasm MSBuil } ``` -- In Visual Studio 2019, press `Ctrl+F5` to start without the debugger (this will create the `launchSettings.json` needed below for debugging) +- In Visual Studio 2022, press `F5` to start with the debugger - A browser window will appear with your application - The output of the Console.WriteLine will appear in the javascript debugging console -## How to use the Visual Studio 2019/2022 Debugger +## How to use the Visual Studio 2022 Debugger -Starting from **Visual Studio 2019 16.6**, it is possible to debug a WebAssembly app. - -To enable the debugging, add the following line to your `launchSettings.json` file: +To enable the debugging, make sure that the following line is present in your `Properties/launchSettings.json` file: ```json "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}" @@ -77,30 +77,51 @@ Once installed, launch the server by using the following command: ```bash cd MyApp.Wasm -dotnet serve -d bin\Debug\net5.0\dist -p 8000 +dotnet publish -c Debug +dotnet serve -d bin\Debug\net9.0\publish\wwwroot -p 8000 ``` You application will be available `http://localhost:8000`. ## Upgrading from previous versions of the Uno.Wasm.Bootstrap package -Previously, the suggested project structure was a .NET Standard 2.0 project using the non-web projects SDK. To enable debugging and easier deployment, the support for `Microsoft.NET.Sdk.Web` has been added. - -To upgrade a project from 1.1 to 1.2: +Moving from version 8.x to 9.x may require changing the used MSBuild SDK for your project. -- If you had a `` line, remove it -- Add the `` item in the same item group as the other nuget packages. +- If your project contains `Sdk="Uno.Sdk"`, you will need to update the Uno.Sdk to 5.5 or later. +- If your project contains `Sdk="Microsoft.NET.Sdk.Web"`, you'll need to change it to `Sdk="Microsoft.NET.Sdk.WebAssembly"`. -To upgrade a project from 1.0 to 1.1: +Once done, make sure to install the WebAssembly tools from .NET: -- Change `Microsoft.NET.Sdk` to `Microsoft.NET.Sdk.Web` in the Sdk attribute of your project -- Add the `` item in the same item group as the other nuget packages. +```bash +dotnet workload install wasm-tools +``` -## Changing the .NET SDKs install location +By default, the .NET runtime does not load all resource assemblies, but if you want to load all resources regardless of the user's culture, you can add the following to your project file: -The SDKs are installed under `Path.GetTempPath()` by default, you may change this by setting the following msbuild property(or environment variable): `WasmShellMonoTempFolder`. +```xml + + true + +``` -For example, on Windows, setting `WasmShellMonoTempFolder` to `C:\MonoWasmSDKs`, the `mono-wasm-e351637985e` sdk would be installed under `C:\MonoWasmSDKs\mono-wasm-e351637985e` +### Deprecated APIs + +- The `Uno.Wasm.Boostrap.DevServer` package is not needed anymore and can be removed +- `WasmShellOutputPackagePath` has been removed. Use `$(PublishDir)` +- `WasmShellOutputDistPath` has been removed. Use `$(PublishDir)` +- `WasmShellBrotliCompressionQuality`, `WasmShellCompressedExtension` and `WasmShellGenerateCompressedFiles` have been removed, the compression is done by the .NET SDK +- `WasmShellEnableAotGSharedVT` has been removed. +- `WasmShellEnableEmscriptenWindows` has been removed, the .NET SDK manages emscripten +- `WasmShellEnableLongPathSupport` has been removed, the .NET SDK manages the build +- `WasmShellEnableNetCoreICU`has been removed, the .NET SDK manages localization +- `WasmShellForceDisableWSL` and `WasmShellForceUseWSL` have been removed, Windows and Linux are supported natively by the .NET SDK. +- `WashShellGeneratePrefetchHeaders` has been removed. +- `WasmShellNinjaAdditionalParameters` has been removed, the .NET SDK manages the build +- `WasmShellObfuscateAssemblies`, `WasmShellAssembliesExtension` and `AssembliesFileNameObfuscationMode` have been removed, the .NET SDK uses WebCIL to achieve the same result. +- `WasmShellPrintAOTSkippedMethods` has been removed +- `WasmShellPThreadsPoolSize` has been removed in favor of the official .NET SDK parameters +- `MonoRuntimeDebuggerEnabled` has been removed, the .NET SDK manages the debugger +- `WashShellUseFileIntegrity` has been removed, the .NET SDK manages the assets integrity ## Bootstrapper versions and .NET runtimes @@ -109,10 +130,17 @@ Each major version of the bootstrapper targets a different version of the .NET R - 2.x: Mono runtime (https://github.com/mono/mono) - 3.x: .NET 6 (https://github.com/dotnet/runtime/commits/release/6.0) - 7.x: .NET 7 (https://github.com/dotnet/runtime/commits/release/7.0) -- 8.x-dev: .NET 8 (https://github.com/dotnet/runtime/commits/main) +- 8.0: .NET 8 (https://github.com/dotnet/runtime/commits/release/8.0) +- 9.0: .NET 9 (https://github.com/dotnet/runtime/commits/release/9.0) > [!NOTE] -> Starting from version 3.x, the bootstrapper uses a custom build of the runtime, maintained here: https://github.com/unoplatform/Uno.DotnetRuntime.WebAssembly +> Between version 3.x and 8.x, the bootstrapper is using custom builds of the runtime, maintained here: https://github.com/unoplatform/Uno.DotnetRuntime.WebAssembly > > [!NOTE] > Bootstrapper builds version 4.x-dev were based on developments builds of .NET 7 and were later versioned 7.x-dev to match the appropriate runtime. + +## Previous releases documentation + +- [8.0.x](https://github.com/unoplatform/Uno.Wasm.Bootstrap/tree/release/stable/8.0/doc) +- [7.0.x](https://github.com/unoplatform/Uno.Wasm.Bootstrap/tree/release/stable/7.0/doc) +- [3.x](https://github.com/unoplatform/Uno.Wasm.Bootstrap/tree/release/stable/3.3/doc) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 589a3f199..680dfc8fb 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -17,7 +17,7 @@ $(AssemblyName) ($(TargetFramework)) en-US - 11.0 + 12.0 diff --git a/src/LongPathTest/Uno.Wasm.LongPath.csproj b/src/LongPathTest/Uno.Wasm.LongPath.csproj index 8a270b687..1e5b58718 100644 --- a/src/LongPathTest/Uno.Wasm.LongPath.csproj +++ b/src/LongPathTest/Uno.Wasm.LongPath.csproj @@ -1,7 +1,7 @@ - + - net5.0 + net9.0 Exe false @@ -10,19 +10,14 @@ - - - + + + false true TargetFramework - - false - true - TargetFramework - diff --git a/src/Uno.Wasm.AotProfiler/AotProfilerSupport.cs b/src/Uno.Wasm.AotProfiler/AotProfilerSupport.cs index adb377079..1f0db7f08 100644 --- a/src/Uno.Wasm.AotProfiler/AotProfilerSupport.cs +++ b/src/Uno.Wasm.AotProfiler/AotProfilerSupport.cs @@ -1,33 +1,16 @@ using System; -using System.Collections.Generic; using System.Runtime.CompilerServices; -using System.Text; -using WebAssembly; namespace Uno { - public static class AotProfilerSupport + public static partial class AotProfilerSupport { - public static void Initialize() - => Console.WriteLine("Profiler support initialized"); - // // Can be called by the app to stop profilings // [MethodImpl(MethodImplOptions.NoInlining)] + [System.Runtime.InteropServices.JavaScript.JSExport()] public static void StopProfile() - { - } - - // Called by the AOT profiler to save profile data into Module.aot_profile_data - [MethodImpl(MethodImplOptions.NoInlining)] - public unsafe static void DumpAotProfileData(ref byte buf, int len, string s) - { - // Based on https://github.com/jeromelaban/runtime/blob/69e7d87aef627e5e0241123b3d4b5b1d598f8c21/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Interop/JavaScriptExports.cs#L224-L225 - fixed (void* p = &buf) - { - Runtime.InvokeJS($"Module.aot_profile_data = Module.HEAPU8.slice({(long)p}, {(long)p} + {len});"); - } - } + => Console.WriteLine("Stopping AOT profile"); } } diff --git a/src/Uno.Wasm.AotProfiler/Runtime.cs b/src/Uno.Wasm.AotProfiler/Runtime.cs deleted file mode 100644 index 4ef0a2268..000000000 --- a/src/Uno.Wasm.AotProfiler/Runtime.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.Runtime.CompilerServices; - -namespace WebAssembly -{ - internal sealed class Runtime - { - /// - /// Mono specific internal call. - /// - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern string InvokeJS(string str, out int exceptional_result); - - // Disable inlining to avoid the interpreter to evaluate an internal call that may not be available - [MethodImpl(MethodImplOptions.NoInlining)] - private static string MonoInvokeJS(string str, out int exceptionResult) => InvokeJS(str, out exceptionResult); - - // Disable inlining to avoid the interpreter to evaluate an internal call that may not be available - [MethodImpl(MethodImplOptions.NoInlining)] - private static string NetCoreInvokeJS(string str, out int exceptionResult) - => Interop.Runtime.InvokeJS(str, out exceptionResult); - - /// - /// Invokes Javascript code in the hosting environment - /// - internal static string InvokeJS(string str) - { - var r = IsNetCore - ? NetCoreInvokeJS(str, out var exceptionResult) - : MonoInvokeJS(str, out exceptionResult); - - if (exceptionResult != 0) - { - Console.Error.WriteLine($"Error #{exceptionResult} \"{r}\" executing javascript: \"{str}\""); - } - return r; - } - - internal static bool IsNetCore { get; } = Type.GetType("System.Runtime.Loader.AssemblyLoadContext") != null; - } -} - -internal sealed class Interop -{ - internal sealed class Runtime - { - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern string InvokeJS(string str, out int exceptional_result); - } -} diff --git a/src/Uno.Wasm.Bootstrap-msbuild-only.slnf b/src/Uno.Wasm.Bootstrap-msbuild-only.slnf index 51523cb69..1334f78c8 100644 --- a/src/Uno.Wasm.Bootstrap-msbuild-only.slnf +++ b/src/Uno.Wasm.Bootstrap-msbuild-only.slnf @@ -3,8 +3,6 @@ "path": "Uno.Wasm.Bootstrap.sln", "projects": [ "LongPathTest\\Uno.Wasm.LongPath.csproj", - "Uno.Wasm.Bootstrap.Cli\\Uno.Wasm.Bootstrap.Cli.csproj", - "Uno.Wasm.Bootstrap.DevServer\\Uno.Wasm.Bootstrap.DevServer.csproj", "Uno.Wasm.Bootstrap.Server\\Uno.Wasm.Bootstrap.Server.csproj", "Uno.Wasm.Bootstrap.UnitTests\\Uno.Wasm.Bootstrap.UnitTests.csproj", "Uno.Wasm.Bootstrap\\Uno.Wasm.Bootstrap.csproj", @@ -26,4 +24,4 @@ "WasmAot.UITests\\WasmAot.UITests.njsproj" ] } -} +} \ No newline at end of file diff --git a/src/Uno.Wasm.Bootstrap-netcore-only.slnf b/src/Uno.Wasm.Bootstrap-netcore-only.slnf index da4281992..e68815783 100644 --- a/src/Uno.Wasm.Bootstrap-netcore-only.slnf +++ b/src/Uno.Wasm.Bootstrap-netcore-only.slnf @@ -3,19 +3,14 @@ "path": "Uno.Wasm.Bootstrap.sln", "projects": [ "LongPathTest\\Uno.Wasm.LongPath.csproj", - "Uno.Wasm.Sample.RayTracer.Shared\\Uno.Wasm.Sample.RayTracer.Shared.shproj", - "Uno.Wasm.Sample.RayTracer\\Uno.Wasm.Sample.RayTracer.csproj", - "Uno.Wasm.Bootstrap.Cli\\Uno.Wasm.Bootstrap.Cli.csproj", - "Uno.Wasm.Bootstrap.DevServer\\Uno.Wasm.Bootstrap.DevServer.csproj", "Uno.Wasm.Bootstrap\\Uno.Wasm.Bootstrap.csproj", "Uno.Wasm.MixedModeRoslynSample\\Uno.Wasm.MixedModeRoslynSample.csproj", "Uno.Wasm.MixedModeSample\\Uno.Wasm.MixedModeSample.csproj", "Uno.Wasm.Node.Sample\\Uno.Wasm.Node.Sample.csproj", + "Uno.Wasm.Sample.RayTracer.Shared\\Uno.Wasm.Sample.RayTracer.Shared.shproj", + "Uno.Wasm.Sample.RayTracer\\Uno.Wasm.Sample.RayTracer.csproj", "Uno.Wasm.Sample.Server.Net7\\Uno.Wasm.Sample.Server.Net7.csproj", "Uno.Wasm.SampleNet6.Aot\\Uno.Wasm.SampleNet6.Aot.csproj", - "Uno.Wasm.SampleNet6\\Uno.Wasm.SampleNet6.csproj", - "Uno.Wasm.SampleNet6.LogProfiler\\Uno.Wasm.SampleNet6.LogProfiler.csproj", - "Uno.Wasm.SampleNet6\\Uno.Wasm.SampleNet6.csproj", "Uno.Wasm.SampleNet7\\Uno.Wasm.SampleNet7.csproj", "Uno.Wasm.Sample\\Uno.Wasm.Sample.shproj", "Uno.Wasm.Static Linking\\Uno.Wasm.StaticLinking.csproj", @@ -27,10 +22,10 @@ "Uno.Wasm.StaticLinking.Shared\\Uno.Wasm.StaticLinking.Shared.shproj", "Uno.Wasm.StaticLinking.Simd.net7\\Uno.Wasm.StaticLinking.Simd.net7.csproj", "Uno.Wasm.StaticLinking.net7\\Uno.Wasm.StaticLinking.net7.csproj", + "Uno.Wasm.Tests.AbsoluteIntermediate\\Uno.Wasm.Tests.AbsoluteIntermediate.csproj", "Uno.Wasm.Tests.Electron\\Uno.Wasm.Tests.Electron.csproj", "Uno.Wasm.Tests.Empty\\Uno.Wasm.Test.Empty.csproj", "Uno.Wasm.Tests.Shared\\Uno.Wasm.Tests.Shared.shproj", - "Uno.Wasm.Tests.AbsoluteIntermediate\\Uno.Wasm.Tests.AbsoluteIntermediate.csproj", "Uno.Wasm.Tests.TypeScript\\Uno.Wasm.Tests.TypeScript.csproj", "Uno.Wasm.Threads.Aot\\Uno.Wasm.Threads.Aot.csproj", "Uno.Wasm.Threads.Shared\\Uno.Wasm.Threads.Shared.shproj", @@ -39,4 +34,4 @@ "Uno.WasmSample WithSpace\\Uno.WasmSample.WithSpace.csproj" ] } -} +} \ No newline at end of file diff --git a/src/Uno.Wasm.Bootstrap-paclages-only.slnf b/src/Uno.Wasm.Bootstrap-packages-only.slnf similarity index 79% rename from src/Uno.Wasm.Bootstrap-paclages-only.slnf rename to src/Uno.Wasm.Bootstrap-packages-only.slnf index ac3b2ab4d..478e601a0 100644 --- a/src/Uno.Wasm.Bootstrap-paclages-only.slnf +++ b/src/Uno.Wasm.Bootstrap-packages-only.slnf @@ -2,18 +2,16 @@ "solution": { "path": "Uno.Wasm.Bootstrap.sln", "projects": [ - "Uno.Wasm.VersionChecker\\Uno.Wasm.VersionChecker.csproj", "Uno.Wasm.AotProfiler\\Uno.Wasm.AotProfiler.csproj", - "Uno.Wasm.Bootstrap.Cli\\Uno.Wasm.Bootstrap.Cli.csproj", - "Uno.Wasm.Bootstrap.DevServer\\Uno.Wasm.Bootstrap.DevServer.csproj", + "Uno.Wasm.Bootstrap.DevServer\\Uno.Wasm.Bootstrap.DevServer.csproj.csproj", "Uno.Wasm.Bootstrap.Server\\Uno.Wasm.Bootstrap.Server.csproj", "Uno.Wasm.Bootstrap.UnitTests\\Uno.Wasm.Bootstrap.UnitTests.csproj", "Uno.Wasm.Bootstrap\\Uno.Wasm.Bootstrap.csproj", "Uno.Wasm.HttpRequestMessageExtensions\\Uno.Wasm.HttpRequestMessageExtensions.csproj", "Uno.Wasm.LogProfiler\\Uno.Wasm.LogProfiler.csproj", "Uno.Wasm.MetadataUpdater\\Uno.Wasm.MetadataUpdater.csproj", - "Uno.Wasm.Packager\\Uno.Wasm.Packager.csproj", - "Uno.Wasm.Tuner\\Uno.Wasm.Tuner.csproj" + "Uno.Wasm.VersionChecker\\Uno.Wasm.VersionChecker.csproj", + "Uno.Wasm.WebCIL\\Uno.Wasm.WebCIL.csproj" ] } -} +} \ No newline at end of file diff --git a/src/Uno.Wasm.Bootstrap.Cli/Commands/Serve.cs b/src/Uno.Wasm.Bootstrap.Cli/Commands/Serve.cs deleted file mode 100644 index 14db59610..000000000 --- a/src/Uno.Wasm.Bootstrap.Cli/Commands/Serve.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -// -// Imported from https://github.com/aspnet/Blazor/tree/release/0.7.0 -// -// History: -// - 2019-01-14: update for Uno support -// - -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.CommandLineUtils; -using System.Threading.Tasks; - -namespace Uno.Wasm.Bootstrap.Cli.Commands -{ - internal class ServeCommand : CommandLineApplication - { - public ServeCommand(CommandLineApplication parent) - - // We pass arbitrary arguments through to the ASP.NET Core configuration - : base(throwOnUnexpectedArg: false) - { - Parent = parent; - - Name = "serve"; - Description = "Serve requests to an Uno WebAssembly application"; - - HelpOption("-?|-h|--help"); - - OnExecute(() => Execute()); - } - - private int Execute() - { - Server.Program.BuildWebHost(RemainingArguments.ToArray()).Run(); - return 0; - } - } -} \ No newline at end of file diff --git a/src/Uno.Wasm.Bootstrap.Cli/DebuggingProxy/DebugHostExtensions.cs b/src/Uno.Wasm.Bootstrap.Cli/DebuggingProxy/DebugHostExtensions.cs deleted file mode 100644 index afac4b2f7..000000000 --- a/src/Uno.Wasm.Bootstrap.Cli/DebuggingProxy/DebugHostExtensions.cs +++ /dev/null @@ -1,70 +0,0 @@ -#nullable enable - -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -// -// Based on https://github.com/dotnet/aspnetcore/blob/7a3f9fe66b641c7667e9122cbab5e6052525d030/src/Components/WebAssembly/Server/src/WebAssemblyNetDebugProxyAppBuilderExtensions.cs -// - -using System; -using System.Net; -using System.Web; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Configuration; - -#if NET6_0_OR_GREATER -using _RequestDelegate = Microsoft.AspNetCore.Http.RequestDelegate; -#else -using _RequestDelegate = System.Func; -#endif - -namespace Uno.Wasm.Bootstrap.Cli.DebuggingProxy -{ - internal static class DebuggerHostExtensions - { - /// - /// Adds middleware needed for debugging Blazor WebAssembly applications - /// inside Chromium dev tools. - /// - public static void UseWebAssemblyDebugging(this IApplicationBuilder app, IConfiguration configuration) - => app.Map("/_framework/debug", app => - { - app.Use(async (HttpContext context, _RequestDelegate next) => - { - var queryParams = HttpUtility.ParseQueryString(context.Request.QueryString.Value!); - var browserParam = queryParams.Get("browser"); - Uri? browserUrl = null; - var devToolsHost = "http://localhost:9222"; - if (browserParam != null) - { - browserUrl = new Uri(browserParam); - devToolsHost = $"http://{browserUrl.Host}:{browserUrl.Port}"; - } - - var debugProxyBaseUrl = await DebugProxyLauncher.EnsureLaunchedAndGetUrl(context.RequestServices, configuration, devToolsHost, browserUrl); - var requestPath = context.Request.Path.ToString(); - if (requestPath == string.Empty) - { - requestPath = "/"; - } - - switch (requestPath) - { - case "/": - var targetPickerUi = new TargetPickerUi(debugProxyBaseUrl, devToolsHost); - await targetPickerUi.Display(context); - break; - case "/ws-proxy": - context.Response.Redirect($"{debugProxyBaseUrl}{browserUrl!.PathAndQuery}"); - break; - default: - context.Response.StatusCode = (int)HttpStatusCode.NotFound; - break; - } - }); - }); - } - -} diff --git a/src/Uno.Wasm.Bootstrap.Cli/DebuggingProxy/DebugProxyLauncher.cs b/src/Uno.Wasm.Bootstrap.Cli/DebuggingProxy/DebugProxyLauncher.cs deleted file mode 100644 index 37848ea4a..000000000 --- a/src/Uno.Wasm.Bootstrap.Cli/DebuggingProxy/DebugProxyLauncher.cs +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -// -// Based on https://github.com/dotnet/aspnetcore/blob/52eff90fbcfca39b7eb58baad597df6a99a542b0/src/Components/WebAssembly/Server/src/DebugProxyLauncher.cs -// -#nullable enable - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Net.Http; -using System.Net.WebSockets; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.CommandLineUtils; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace Uno.Wasm.Bootstrap.Cli -{ - internal static class DebugProxyLauncher - { - private static readonly TimeSpan DebugProxyLaunchTimeout; - private static Task? LaunchedDebugProxyUrl; - private static SemaphoreSlim LaunchLock = new SemaphoreSlim(1); - private static readonly Regex NowListeningRegex = new Regex(@"^\s*Now listening on: (?.*)$", RegexOptions.None, TimeSpan.FromSeconds(10)); - private static readonly Regex ApplicationStartedRegex = new Regex(@"^\s*Application started\. Press Ctrl\+C to shut down\.$", RegexOptions.None, TimeSpan.FromSeconds(10)); - - private static Process? _debugProxyProcess; - private static string? _devToolsHost; - private static readonly HttpClient _aliveCheckClient; - - static DebugProxyLauncher() - { - if(!TimeSpan.TryParse(Environment.GetEnvironmentVariable("WASMSHELL_DEBUG_KEEPALIVE_TIMEOUT"), out var timespan)) - { - timespan = TimeSpan.FromSeconds(10); - } - - _aliveCheckClient = new HttpClient() - { - Timeout = timespan - }; - - if (!TimeSpan.TryParse(Environment.GetEnvironmentVariable("WASMSHELL_DEBUG_KEEPALIVE_TIMEOUT"), out DebugProxyLaunchTimeout)) - { - DebugProxyLaunchTimeout = TimeSpan.FromSeconds(10); - } - } - - public static async Task EnsureLaunchedAndGetUrl(IServiceProvider serviceProvider, IConfiguration configuration, string devToolsHost, Uri? browserUrl) - { - try - { - await LaunchLock.WaitAsync(); - - if (LaunchedDebugProxyUrl == null - || (_debugProxyProcess?.HasExited ?? false) - || (!await IsAlive())) - { - LaunchedDebugProxyUrl = LaunchAndGetUrl(serviceProvider, configuration, devToolsHost, browserUrl); - } - - return await LaunchedDebugProxyUrl; - } - finally - { - LaunchLock.Release(); - } - } - - /// - /// Determines if the target host is available. - /// - /// - private static async Task IsAlive() - { - if (_devToolsHost == null) - { - return false; - } - - try - { - _ = await _aliveCheckClient.GetByteArrayAsync($"{_devToolsHost}"); - return true; - } - catch - { - return false; - } - } - - private static async Task LaunchAndGetUrl(IServiceProvider serviceProvider, IConfiguration configuration, string devToolsHost, Uri? browserUrl) - { - var tcs = new TaskCompletionSource(); - - var environment = serviceProvider.GetRequiredService(); - var executablePath = LocateDebugProxyExecutable(environment, configuration); - var muxerPath = DotNetMuxer.MuxerPathOrDefault(); - var ownerPid = Process.GetCurrentProcess().Id; - - var processStartInfo = new ProcessStartInfo - { - FileName = muxerPath, - Arguments = $"exec \"{executablePath}\" --OwnerPid {ownerPid} --DevToolsUrl {devToolsHost}", - UseShellExecute = false, - RedirectStandardOutput = true, - }; - RemoveUnwantedEnvironmentVariables(processStartInfo.Environment); - - _devToolsHost = devToolsHost; - - if(_debugProxyProcess != null && !_debugProxyProcess.HasExited) - { - _debugProxyProcess.Kill(); - } - - _debugProxyProcess = Process.Start(processStartInfo); - if (_debugProxyProcess is null) - { - tcs.TrySetException(new InvalidOperationException("Unable to start debug proxy process.")); - } - else - { - PassThroughConsoleOutputAndError(_debugProxyProcess); - CompleteTaskWhenServerIsReady(_debugProxyProcess, tcs); - - new CancellationTokenSource(DebugProxyLaunchTimeout).Token.Register(() => - { - tcs.TrySetException(new TimeoutException($"Failed to start the debug proxy within the timeout period of {DebugProxyLaunchTimeout.TotalSeconds} seconds.")); - }); - } - - return await tcs.Task; - } - - private static void RemoveUnwantedEnvironmentVariables(IDictionary environment) - { - // Generally we expect to pass through most environment variables, since dotnet might - // need them for arbitrary reasons to function correctly. However, we specifically don't - // want to pass through any ASP.NET Core hosting related ones, since the child process - // shouldn't be trying to use the same port numbers, etc. In particular we need to break - // the association with IISExpress and the MS-ASPNETCORE-TOKEN check. - // For more context on this, see https://github.com/dotnet/aspnetcore/issues/20308. - var keysToRemove = environment.Keys.Where(key => key.StartsWith("ASPNETCORE_", StringComparison.Ordinal)).ToList(); - foreach (var key in keysToRemove) - { - environment.Remove(key); - } - } - - private static string LocateDebugProxyExecutable(IWebHostEnvironment environment, IConfiguration configuration) - { - var platform = configuration.GetValue("platform") ?? ""; - var buildConfiguration = configuration.GetValue("configuration") ?? ""; - var targetFramework = configuration.GetValue("targetframework") ?? ""; - var intermediatePath = configuration.GetValue("intermediateoutputpath") ?? ""; - - var contentRoot = environment.ContentRootPath; - var debuggerInfoRoot = intermediatePath is { Length: > 0 } - // This is defined in when the bootstrapper is referenced through nuget - ? Path.Combine(contentRoot, intermediatePath, "wasm-debugger") - // Used as a fallback inside the bootstrapper solution - : Path.Combine(contentRoot, "obj", platform, buildConfiguration, targetFramework, "wasm-debugger"); - - var debuggerInfoFile = Path.Combine(debuggerInfoRoot, ".debuggerinfo"); - if (!File.Exists(debuggerInfoFile)) - { - throw new FileNotFoundException( - $"Cannot start debug proxy because its path cannot be determined."); - } - - var debugProxyPath = Path.Combine( - File.ReadAllText(debuggerInfoFile), - "BrowserDebugHost.dll"); - - if (!File.Exists(debugProxyPath)) - { - throw new FileNotFoundException( - $"Cannot start debug proxy because it cannot be found at '{debugProxyPath}'"); - } - - return debugProxyPath; - } - - private static void PassThroughConsoleOutputAndError(Process process) - { - process.OutputDataReceived += - (sender, eventArgs) => Console.WriteLine(eventArgs.Data); - - process.ErrorDataReceived += - (sender, eventArgs) => Console.WriteLine("[DebuggerHost-ERROR] " + eventArgs.Data); - } - - private static void CompleteTaskWhenServerIsReady(Process aspNetProcess, TaskCompletionSource taskCompletionSource) - { - string? capturedUrl = null; - aspNetProcess.OutputDataReceived += OnOutputDataReceived; - aspNetProcess.BeginOutputReadLine(); - - void OnOutputDataReceived(object sender, DataReceivedEventArgs eventArgs) - { - if (string.IsNullOrEmpty(eventArgs.Data)) - { - taskCompletionSource.TrySetException(new InvalidOperationException( - "No output has been recevied from the application.")); - return; - } - - if (ApplicationStartedRegex.IsMatch(eventArgs.Data)) - { - aspNetProcess.OutputDataReceived -= OnOutputDataReceived; - if (!string.IsNullOrEmpty(capturedUrl)) - { - taskCompletionSource.TrySetResult(capturedUrl); - } - else - { - taskCompletionSource.TrySetException(new InvalidOperationException( - "The application started listening without first advertising a URL")); - } - } - else - { - var match = NowListeningRegex.Match(eventArgs.Data); - if (match.Success) - { - capturedUrl = match.Groups["url"].Value; - } - } - } - } - } -} diff --git a/src/Uno.Wasm.Bootstrap.Cli/DebuggingProxy/DotNetMuxer.cs b/src/Uno.Wasm.Bootstrap.Cli/DebuggingProxy/DotNetMuxer.cs deleted file mode 100644 index b0dfca370..000000000 --- a/src/Uno.Wasm.Bootstrap.Cli/DebuggingProxy/DotNetMuxer.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -// -// Based on https://github.com/dotnet/aspnetcore/blob/db4ef86f34815a992d79f02109983c3d9d4bdbf1/src/Shared/CommandLineUtils/Utilities/DotNetMuxer.cs -// - -#nullable enable - -using System; -using System.Diagnostics; -using System.IO; -using System.Runtime.InteropServices; - -namespace Uno.Wasm.Bootstrap.Cli -{ - /// - /// Utilities for finding the "dotnet.exe" file from the currently running .NET Core application - /// - internal static class DotNetMuxer - { - private const string MuxerName = "dotnet"; - - static DotNetMuxer() - { - MuxerPath = TryFindMuxerPath(Process.GetCurrentProcess().MainModule?.FileName); - } - - /// - /// The full filepath to the .NET Core muxer. - /// - public static string? MuxerPath { get; } - - /// - /// Finds the full filepath to the .NET Core muxer, - /// or returns a string containing the default name of the .NET Core muxer ('dotnet'). - /// - /// The path or a string named 'dotnet'. - public static string MuxerPathOrDefault() - => MuxerPath ?? MuxerName; - - internal static string? TryFindMuxerPath(string? mainModule) - { - var fileName = MuxerName; - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - fileName += ".exe"; - } - - if (!string.IsNullOrEmpty(mainModule) - && string.Equals(Path.GetFileName(mainModule!), fileName, StringComparison.OrdinalIgnoreCase)) - { - return mainModule; - } - - return null; - } - } -} - - diff --git a/src/Uno.Wasm.Bootstrap.Cli/DebuggingProxy/TargetPickerUi.cs b/src/Uno.Wasm.Bootstrap.Cli/DebuggingProxy/TargetPickerUi.cs deleted file mode 100644 index 75f77925b..000000000 --- a/src/Uno.Wasm.Bootstrap.Cli/DebuggingProxy/TargetPickerUi.cs +++ /dev/null @@ -1,245 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -// -// Based on https://github.com/dotnet/aspnetcore/blob/bc5960e878140bc90484be799123ea1f25af0ba2/src/Components/WebAssembly/Server/src/TargetPickerUi.cs -// - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Runtime.InteropServices; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; - -namespace Uno.Wasm.Bootstrap.Cli.DebuggingProxy -{ - /// - /// Class for the target picker ui. - /// - public class TargetPickerUi - { - private static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions - { - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - PropertyNameCaseInsensitive = true, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull - }; - - private string _browserHost; - private string _debugProxyUrl; - - /// - /// Initialize a new instance of . - /// - /// The debug proxy url. - /// The dev tools host. - public TargetPickerUi(string debugProxyUrl, string devToolsHost) - { - _debugProxyUrl = debugProxyUrl; - _browserHost = devToolsHost; - } - - /// - /// Display the ui. - /// - /// The . - /// The . - public async Task Display(HttpContext context) - { - context.Response.ContentType = "text/html"; - - var request = context.Request; - var targetApplicationUrl = request.Query["url"]; - - var debuggerTabsListUrl = $"{_browserHost}/json"; - IEnumerable availableTabs; - - try - { - availableTabs = await GetOpenedBrowserTabs(); - } - catch (Exception ex) - { - await context.Response.WriteAsync($@" -

Unable to find debuggable browser tab

-

- Could not get a list of browser tabs from {debuggerTabsListUrl}. - Ensure your browser is running with debugging enabled. -

-

Resolution

-

-

If you are using Google Chrome for your development, follow these instructions:

- {GetLaunchChromeInstructions(targetApplicationUrl)} -

-

-

If you are using Microsoft Edge (80+) for your development, follow these instructions:

- {GetLaunchEdgeInstructions(targetApplicationUrl)} -

-This should launch a new browser window with debugging enabled..

-

Underlying exception:

-
{ex}
- "); - - return; - } - - var matchingTabs = string.IsNullOrEmpty(targetApplicationUrl) - ? availableTabs.ToList() - : availableTabs.Where(t => t.Url.Equals(targetApplicationUrl, StringComparison.Ordinal)).ToList(); - - if (matchingTabs.Count == 1) - { - // We know uniquely which tab to debug, so just redirect - var devToolsUrlWithProxy = GetDevToolsUrlWithProxy(request, matchingTabs.Single()); - context.Response.Redirect(devToolsUrlWithProxy); - } - else if (matchingTabs.Count == 0) - { - await context.Response.WriteAsync("

No inspectable pages found

"); - - var suffix = string.IsNullOrEmpty(targetApplicationUrl) - ? string.Empty - : $" matching the URL {WebUtility.HtmlEncode(targetApplicationUrl)}"; - await context.Response.WriteAsync($"

The list of targets returned by {WebUtility.HtmlEncode(debuggerTabsListUrl)} contains no entries{suffix}.

"); - await context.Response.WriteAsync("

Make sure your browser is displaying the target application.

"); - } - else - { - await context.Response.WriteAsync("

Inspectable pages

"); - await context.Response.WriteAsync(@" - - "); - - foreach (var tab in matchingTabs) - { - var devToolsUrlWithProxy = GetDevToolsUrlWithProxy(request, tab); - await context.Response.WriteAsync( - $"" - + $"

{WebUtility.HtmlEncode(tab.Title)}

{WebUtility.HtmlEncode(tab.Url)}" - + $"
"); - } - } - } - - private string GetDevToolsUrlWithProxy(HttpRequest request, BrowserTab tabToDebug) - { - var underlyingV8Endpoint = new Uri(tabToDebug.WebSocketDebuggerUrl); - var proxyEndpoint = new Uri(_debugProxyUrl); - var devToolsUrlAbsolute = new Uri(_browserHost + tabToDebug.DevtoolsFrontendUrl); - var devToolsUrlWithProxy = $"{devToolsUrlAbsolute.Scheme}://{devToolsUrlAbsolute.Authority}{devToolsUrlAbsolute.AbsolutePath}?{underlyingV8Endpoint.Scheme}={proxyEndpoint.Authority}{underlyingV8Endpoint.PathAndQuery}"; - return devToolsUrlWithProxy; - } - - private string GetLaunchChromeInstructions(string targetApplicationUrl) - { - var profilePath = Path.Combine(Path.GetTempPath(), "blazor-chrome-debug"); - var debuggerPort = new Uri(_browserHost).Port; - - if (OperatingSystem.IsWindows()) - { - return $@"

Press Win+R and enter the following:

-

chrome --remote-debugging-port={debuggerPort} --user-data-dir=""{profilePath}"" {targetApplicationUrl}

"; - } - else if (OperatingSystem.IsLinux()) - { - return $@"

In a terminal window execute the following:

-

google-chrome --remote-debugging-port={debuggerPort} --user-data-dir={profilePath} {targetApplicationUrl}

"; - } - else if (OperatingSystem.IsMacOS()) - { - return $@"

Execute the following:

-

open -n /Applications/Google\ Chrome.app --args --remote-debugging-port={debuggerPort} --user-data-dir={profilePath} {targetApplicationUrl}

"; - } - else - { - throw new InvalidOperationException("Unknown OS platform"); - } - } - - private string GetLaunchEdgeInstructions(string targetApplicationUrl) - { - var profilePath = Path.Combine(Path.GetTempPath(), "blazor-edge-debug"); - var debuggerPort = new Uri(_browserHost).Port; - - if (OperatingSystem.IsWindows()) - { - return $@"

Press Win+R and enter the following:

-

msedge --remote-debugging-port={debuggerPort} --user-data-dir=""{profilePath}"" --no-first-run {targetApplicationUrl}

"; - } - else if (OperatingSystem.IsMacOS()) - { - return $@"

In a terminal window execute the following:

-

open -n /Applications/Microsoft\ Edge.app --args --remote-debugging-port={debuggerPort} --user-data-dir={profilePath} {targetApplicationUrl}

"; - } - else - { - return $@"

Edge is not current supported on your platform

"; - } - } - - private static Uri GetProxyEndpoint(HttpRequest incomingRequest, string browserEndpoint) - { - var builder = new UriBuilder( - schemeName: incomingRequest.IsHttps ? "wss" : "ws", - hostName: incomingRequest.Host.Host) - { - Path = $"{incomingRequest.PathBase}/ws-proxy", - Query = $"browser={WebUtility.UrlEncode(browserEndpoint)}" - }; - - if (incomingRequest.Host.Port.HasValue) - { - builder.Port = incomingRequest.Host.Port.Value; - } - - return builder.Uri; - } - - private async Task> GetOpenedBrowserTabs() - { - using var httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) }; - var jsonResponse = await httpClient.GetStringAsync($"{_browserHost}/json"); - return JsonSerializer.Deserialize(jsonResponse, JsonOptions)!; - } - - public class BrowserTab - { - public string Id { get; set; } - public string Type { get; set; } - public string Url { get; set; } - public string Title { get; set; } - public string DevtoolsFrontendUrl { get; set; } - public string WebSocketDebuggerUrl { get; set; } - }; - } -} diff --git a/src/Uno.Wasm.Bootstrap.Cli/Program.cs b/src/Uno.Wasm.Bootstrap.Cli/Program.cs deleted file mode 100644 index 42952bb5f..000000000 --- a/src/Uno.Wasm.Bootstrap.Cli/Program.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Microsoft.Extensions.CommandLineUtils; -using System; -using Uno.Wasm.Bootstrap.Cli.Commands; - -namespace Uno.Wasm.Bootstrap.Cli -{ - class Program - { - static int Main(string[] args) - { - var app = new CommandLineApplication(throwOnUnexpectedArg: false) - { - Name = "unowasm-cli" - }; - app.HelpOption("-?|-h|--help"); - - app.Commands.Add(new ServeCommand(app)); - - app.OnExecute(() => - { - app.ShowHelp(); - return 0; - }); - - try - { - return app.Execute(args); - } - catch (CommandParsingException cex) - { - app.Error.WriteLine(cex.Message); - app.ShowHelp(); - return 1; - } - } - } -} diff --git a/src/Uno.Wasm.Bootstrap.Cli/Server/Program.cs b/src/Uno.Wasm.Bootstrap.Cli/Server/Program.cs deleted file mode 100644 index 69fdd230b..000000000 --- a/src/Uno.Wasm.Bootstrap.Cli/Server/Program.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Microsoft.AspNetCore; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Uno.Wasm.Bootstrap.Cli.Server -{ - class Program - { - public static IWebHost BuildWebHost(string[] args) - { - var initialData = new Dictionary() - { - [WebHostDefaults.EnvironmentKey] = "Development", - ["Logging:LogLevel:Microsoft"] = "Warning", - ["Logging:LogLevel:Microsoft.Hosting.Lifetime"] = "Information", - }; - - return WebHost.CreateDefaultBuilder(args) - .UseConfiguration(new ConfigurationBuilder() - .AddCommandLine(args) - .AddInMemoryCollection(initialData) - .Build()) - .UseStartup() - .Build(); - } - } -} diff --git a/src/Uno.Wasm.Bootstrap.Cli/Server/Startup.cs b/src/Uno.Wasm.Bootstrap.Cli/Server/Startup.cs deleted file mode 100644 index 13c473c5d..000000000 --- a/src/Uno.Wasm.Bootstrap.Cli/Server/Startup.cs +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -// -// Imported from https://github.com/aspnet/Blazor/tree/release/0.7.0 -// -// History: -// 2019-01-14: Adjustments to make the debugger imported. -// - -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Features; -using Microsoft.AspNetCore.ResponseCompression; -using Microsoft.AspNetCore.StaticFiles; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.FileProviders; -using Microsoft.Extensions.Hosting; -using Microsoft.Net.Http.Headers; -using System; -using System.IO; -using System.Linq; -using System.Net.Mime; -using System.Threading.Tasks; -using Uno.Wasm.Bootstrap.Cli.DebuggingProxy; - -namespace Uno.Wasm.Bootstrap.Cli.Server -{ - class Startup - { - private readonly char OtherDirectorySeparatorChar = Path.DirectorySeparatorChar == '/' ? '\\' : '/'; - - public void ConfigureServices(IServiceCollection services) - { - services.AddRouting(); - services.AddResponseCompression(options => - { - options.EnableForHttps = true; - options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[] - { - MediaTypeNames.Application.Octet - }); - }); - } - - public void Configure(IApplicationBuilder app, IConfiguration configuration) - { - - var webHostEnvironment = app.ApplicationServices.GetRequiredService(); - - var useSecureMode = ShouldUseSecureMode(webHostEnvironment, configuration); - var isDebugBuild = IsDebugBuild(configuration); - - if (!isDebugBuild) - { - app.UseResponseCompression(); - } - - app.UseDeveloperExceptionPage(); - - app.Use(async (context, next) => - { - context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); - context.Response.Headers.Add("Access-Control-Allow-Methods", "*"); - context.Response.Headers.Add("Access-Control-Allow-Headers", "*"); - - if (useSecureMode) - { - // Required for SharedArrayBuffer: https://developer.chrome.com/blog/enabling-shared-array-buffer/ - context.Response.Headers.Add("Cross-Origin-Embedder-Policy", "require-corp"); - context.Response.Headers.Add("Cross-Origin-Opener-Policy", "same-origin"); - } - - await next(); - }); - - var pathBase = FixupPath(configuration.GetValue("pathbase")); - - app.UseStaticFiles(new StaticFileOptions - { - ContentTypeProvider = CreateContentTypeProvider(true), - FileProvider = new PhysicalFileProvider(pathBase), - HttpsCompression = isDebugBuild ? HttpsCompressionMode.DoNotCompress : HttpsCompressionMode.Compress, - OnPrepareResponse = SetCacheHeaders, - DefaultContentType = MediaTypeNames.Application.Octet, - ServeUnknownFileTypes = true - }); - - app.UseWebAssemblyDebugging(configuration); - - // foreach(DictionaryEntry entry in Environment.GetEnvironmentVariables()) - // { - // Console.WriteLine($"Env: {entry.Key}={entry.Value}"); - // } - - app.MapWhen( - ctx => ctx.Request.Path.StartsWithSegments("/_framework/unohotreload"), - subBuilder => - { - subBuilder.Use(async (HttpContext context, Func next) => - { - context.Response.Headers.Append("Uno-Environment", webHostEnvironment.EnvironmentName); - - if (webHostEnvironment.IsDevelopment()) - { - // DOTNET_MODIFIABLE_ASSEMBLIES is used by the runtime to initialize hot-reload specific environment variables and is configured - // by the launching process (dotnet-watch / Visual Studio). - // In Development, we'll transmit the environment variable to WebAssembly as a HTTP header. The bootstrapping code will read the header - // and configure it as env variable for the wasm app. - if (Environment.GetEnvironmentVariable("DOTNET_MODIFIABLE_ASSEMBLIES") is string dotnetModifiableAssemblies) - { - context.Response.Headers.Append("DOTNET-MODIFIABLE-ASSEMBLIES", dotnetModifiableAssemblies); - } - - // See https://github.com/dotnet/aspnetcore/issues/37357#issuecomment-941237000 - // Translate the _ASPNETCORE_BROWSER_TOOLS environment configured by the browser tools agent in to a HTTP response header. - if (Environment.GetEnvironmentVariable("__ASPNETCORE_BROWSER_TOOLS") is string browserTools) - { - context.Response.Headers.Append("ASPNETCORE-BROWSER-TOOLS", browserTools); - } - } - - context.Response.StatusCode = 200; - await context.Response.WriteAsync(""); - }); - }); - - // Use SPA fallback routing (serve default page for anything else, - // excluding /_framework/*) - app.MapWhen(IsNotFrameworkDir, childAppBuilder => - { - var indexHtmlPath = FindIndexHtmlFile(pathBase); - var indexHtmlStaticFileOptions = string.IsNullOrEmpty(indexHtmlPath) - ? null : new StaticFileOptions - { - FileProvider = new PhysicalFileProvider(Path.GetDirectoryName(indexHtmlPath)), - HttpsCompression = isDebugBuild ? HttpsCompressionMode.DoNotCompress : HttpsCompressionMode.Compress, - OnPrepareResponse = SetCacheHeaders - }; - - childAppBuilder.UseSpa(spa => - { - spa.Options.DefaultPageStaticFileOptions = indexHtmlStaticFileOptions; - }); - }); - } - - private static bool IsDebugBuild(IConfiguration configuration) - { - var buildConfiguration = configuration.GetValue("configuration") ?? ""; - - return buildConfiguration.Equals("Debug", StringComparison.OrdinalIgnoreCase); - } - - private static bool ShouldUseSecureMode(IWebHostEnvironment environment, IConfiguration configuration) - { - var platform = configuration.GetValue("platform") ?? ""; - var buildConfiguration = configuration.GetValue("configuration") ?? ""; - var targetFramework = configuration.GetValue("targetframework") ?? ""; - - var contentRoot = environment.ContentRootPath; - var debuggerInfoRoot = Path.Combine(contentRoot, "obj", platform, buildConfiguration, targetFramework); - - var featuresInfoFile = Path.Combine(debuggerInfoRoot, ".unoappfeatures"); - if (File.Exists(featuresInfoFile)) - { - var featuresRaw = File.ReadAllText(featuresInfoFile); - - return featuresRaw.Contains("threads", StringComparison.Ordinal); - } - - return false; - } - - private static string FindIndexHtmlFile(string basePath) - { - var distIndexHtmlPath = Path.Combine(basePath, "index.html"); - if (File.Exists(distIndexHtmlPath)) - { - return distIndexHtmlPath; - } - - // Since there's no index.html, we'll use the default DefaultPageStaticFileOptions, - // hence we'll look for index.html in the host server app's wwwroot. - return null; - } - - private static bool IsNotFrameworkDir(HttpContext context) - => !context.Request.Path.StartsWithSegments("/_framework"); - - private static IContentTypeProvider CreateContentTypeProvider(bool enableDebugging) - { - var result = new FileExtensionContentTypeProvider(); - result.Mappings.Add(".blat", MediaTypeNames.Application.Octet); - result.Mappings.Add(".br", MediaTypeNames.Application.Octet); - result.Mappings.Add(".clr", MediaTypeNames.Application.Octet); - result.Mappings.Add(".dat", MediaTypeNames.Application.Octet); - - if (enableDebugging) - { - result.Mappings.Add(".pdb", MediaTypeNames.Application.Octet); - } - - return result; - } - - private static void SetCacheHeaders(StaticFileResponseContext ctx) - { - // By setting "Cache-Control: no-cache", we're allowing the browser to store - // a cached copy of the response, but telling it that it must check with the - // server for modifications (based on Etag) before using that cached copy. - // Longer term, we should generate URLs based on content hashes (at least - // for published apps) so that the browser doesn't need to make any requests - // for unchanged files. - var headers = ctx.Context.Response.GetTypedHeaders(); - if (headers.CacheControl == null) - { - headers.CacheControl = new CacheControlHeaderValue - { - NoCache = true - }; - } - } - - /// - /// Align paths to fix issues with mixed path - /// - string FixupPath(string path) - => path.Replace(OtherDirectorySeparatorChar, Path.DirectorySeparatorChar); - } -} diff --git a/src/Uno.Wasm.Bootstrap.Cli/Uno - Backup.Wasm.Bootstrap.Cli.csproj b/src/Uno.Wasm.Bootstrap.Cli/Uno - Backup.Wasm.Bootstrap.Cli.csproj deleted file mode 100644 index 8840689d8..000000000 --- a/src/Uno.Wasm.Bootstrap.Cli/Uno - Backup.Wasm.Bootstrap.Cli.csproj +++ /dev/null @@ -1,41 +0,0 @@ - - - - Exe - Uno.Wasm.Bootstrap.Cli.Program - netcoreapp3.1;net5 - dotnet-unowasm - false - - - - - - - - - - - - - - External\Mono.Cecil.dll - false - - - External\netcoreapp3.1\Mono.WebAssembly.DebuggerProxy.dll - false - - - External\net5\BrowserDebugProxy.dll - false - - - - - - diff --git a/src/Uno.Wasm.Bootstrap.Cli/Uno.Wasm.Bootstrap.Cli.csproj b/src/Uno.Wasm.Bootstrap.Cli/Uno.Wasm.Bootstrap.Cli.csproj deleted file mode 100644 index df99967b4..000000000 --- a/src/Uno.Wasm.Bootstrap.Cli/Uno.Wasm.Bootstrap.Cli.csproj +++ /dev/null @@ -1,41 +0,0 @@ - - - - Exe - Uno.Wasm.Bootstrap.Cli.Program - dotnet-unowasm - false - - - Major - - - - net5;net6;net7.0 - - - - - - net7.0 - - - - - - - - - - - - - - diff --git a/src/Uno.Wasm.Bootstrap.DevServer/Uno.Wasm.Bootstrap.DevServer.csproj b/src/Uno.Wasm.Bootstrap.DevServer/Uno.Wasm.Bootstrap.DevServer.csproj deleted file mode 100644 index f2a99bf72..000000000 --- a/src/Uno.Wasm.Bootstrap.DevServer/Uno.Wasm.Bootstrap.DevServer.csproj +++ /dev/null @@ -1,50 +0,0 @@ - - - - netstandard2.0 - 1701;1702;1705;649 - Uno.Wasm.Bootstrap.DevServer - true - false - true - - - - This package provides the development server and debugger support for Wasm bootstrap projects - - - - - - - build - true - - - tools\server\net5 - true - - - tools\server\net6 - true - - - tools\server\net7.0 - true - - - - - - - - - - - false - true - TargetFramework - - - - diff --git a/src/Uno.Wasm.Bootstrap.DevServer/Uno.Wasm.Bootstrap.DevServer.csproj.csproj b/src/Uno.Wasm.Bootstrap.DevServer/Uno.Wasm.Bootstrap.DevServer.csproj.csproj new file mode 100644 index 000000000..de3cb00ff --- /dev/null +++ b/src/Uno.Wasm.Bootstrap.DevServer/Uno.Wasm.Bootstrap.DevServer.csproj.csproj @@ -0,0 +1,15 @@ + + + + netstandard2.0 + Uno.Wasm.Bootstrap.DevServer + true + false + true + + + + [Deprecated] This package is not needed anymore and can be removed + + + diff --git a/src/Uno.Wasm.Bootstrap.DevServer/build/Uno.Wasm.Bootstrap.DevServer.targets b/src/Uno.Wasm.Bootstrap.DevServer/build/Uno.Wasm.Bootstrap.DevServer.targets deleted file mode 100644 index a7cc42e9f..000000000 --- a/src/Uno.Wasm.Bootstrap.DevServer/build/Uno.Wasm.Bootstrap.DevServer.targets +++ /dev/null @@ -1,40 +0,0 @@ - - - - - dotnet - - - <_unoBinArgs>unowasm serve - - <_UnoDevServerBasePath Condition="'$(TargetFramework)'=='netstandard2.0'">netcoreapp3.1 - <_UnoDevServerBasePath Condition="'$(TargetFramework.substring(0,3))'=='net' and '$(TargetFramework)'!='netstandard2.0'">net5 - <_UnoDevServerBasePath Condition="'$([MSBuild]::GetTargetFrameworkVersion($(TargetFramework)))' > 5">net6 - <_UnoDevServerBasePath Condition="'$([MSBuild]::GetTargetFrameworkVersion($(TargetFramework)))' > 6">net7.0 - - <_UnoBootstrapIsDevelopment>false - <_UnoBootstrapIsDevelopment Condition="exists('$(MSBuildThisFileDirectory)../../Uno.Wasm.Bootstrap.Cli')">true - - - <_unoBinArgs Condition="$(_UnoBootstrapIsDevelopment)">exec "$(MSBuildThisFileDirectory)../../Uno.Wasm.Bootstrap.Cli/bin/$(Configuration)/$(_UnoDevServerBasePath)/dotnet-unowasm.dll" serve $(_unoRunArgs) - <_unoBinArgs Condition="!$(_UnoBootstrapIsDevelopment)">"$(MSBuildThisFileDirectory)../tools/server/$(_UnoDevServerBasePath)/dotnet-unowasm.dll" serve $(_unoRunArgs) - - - <_UnoRunBasePath Condition="!$(_UnoBootstrapIsDevelopment) and '$(OutputPath)'!='' and !$([System.IO.Path]::IsPathRooted($(OutputPath)))">$(MSBuildProjectDirectory)/$(OutputPath) - <_UnoRunBasePath Condition="!$(_UnoBootstrapIsDevelopment) and '$(OutputPath)'!='' and $([System.IO.Path]::IsPathRooted($(OutputPath)))">$(OutputPath) - - - - <_UnoMaybePlatform> - <_UnoMaybePlatform Condition="'$(Platform)' != 'AnyCPU'">$(Platform) - - <_UnoBasePathMaybePlatform> - <_UnoBasePathMaybePlatform Condition="'$(AppendPlatformToOutputPath)' == 'true' and '$(Platform)' != 'AnyCPU'">$(Platform)/ - - <_UnoRunBasePath Condition="$(_UnoBootstrapIsDevelopment) and '$(OutputPath)'==''">$(MSBuildProjectDirectory)/bin/$(_UnoBasePathMaybePlatform)$(Configuration)/$(TargetFramework)/ - <_UnoRunBasePath Condition="$(_UnoBootstrapIsDevelopment) and '$(OutputPath)'!='' and $([System.IO.Path]::IsPathRooted($(OutputPath)))">$(OutputPath) - - $(_unoBinArgs) $(_unoRunArgs) --pathbase "$(_UnoRunBasePath)dist" --platform "$(_UnoMaybePlatform)" --configuration "$(Configuration)" --targetframework "$(TargetFramework)" --intermediateoutputpath "$(IntermediateOutputPath)/" $(AdditionalRunArguments) - - - diff --git a/src/Uno.Wasm.Bootstrap.sln b/src/Uno.Wasm.Bootstrap.sln index aa8c2acb8..a8cb82d91 100644 --- a/src/Uno.Wasm.Bootstrap.sln +++ b/src/Uno.Wasm.Bootstrap.sln @@ -7,8 +7,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.Bootstrap", "Uno.W EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.Test.Empty", "Uno.Wasm.Tests.Empty\Uno.Wasm.Test.Empty.csproj", "{2DFA7173-E4AD-44C6-B25A-2A455CB513FD}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.Bootstrap.Cli", "Uno.Wasm.Bootstrap.Cli\Uno.Wasm.Bootstrap.Cli.csproj", "{AA1C47D5-53C6-4BD6-9206-FDD812D67C13}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.MixedModeSample", "Uno.Wasm.MixedModeSample\Uno.Wasm.MixedModeSample.csproj", "{DF5FF703-BAC7-427B-BAEA-2E49B65DBF6E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.MixedModeRoslynSample", "Uno.Wasm.MixedModeRoslynSample\Uno.Wasm.MixedModeRoslynSample.csproj", "{15C3F459-5FE5-48F2-A33C-A7864969FEA4}" @@ -40,8 +38,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.Threads", "Uno.Was EndProject Project("{9092AA53-FB77-4645-B42D-1CCCA6BD08BD}") = "Uno.Wasm.Threading.UITests", "Uno.Wasm.Threading.UITests\Uno.Wasm.Threading.UITests.njsproj", "{3D59ACEE-12BF-4B69-AEF7-893514C0BA7D}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.Bootstrap.DevServer", "Uno.Wasm.Bootstrap.DevServer\Uno.Wasm.Bootstrap.DevServer.csproj", "{6ACB62AD-0DFF-4593-A7EC-5A4E21DA4ABE}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.StaticLinking", "Uno.Wasm.Static Linking\Uno.Wasm.StaticLinking.csproj", "{EBCB3142-593E-4815-915D-3B88B75161C1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.WasmSample.WithSpace.Aot", "Uno.WasmSample WithSpace Aot\Uno.WasmSample.WithSpace.Aot.csproj", "{359A63C4-C5D0-4011-8C39-89D23190B22F}" @@ -76,15 +72,12 @@ Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Uno.Wasm.Threads.Shared", " EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.Bootstrap.UnitTests", "Uno.Wasm.Bootstrap.UnitTests\Uno.Wasm.Bootstrap.UnitTests.csproj", "{E1458920-4A5A-4D54-882D-304A46359BEC}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.Packager", "Uno.Wasm.Packager\Uno.Wasm.Packager.csproj", "{5A0392DE-9D69-4183-9BD9-84D5723AFB76}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.Tuner", "Uno.Wasm.Tuner\Uno.Wasm.Tuner.csproj", "{13C116EE-6907-45D4-9CB2-F1E905C71387}" -EndProject Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Uno.Wasm.Sample", "Uno.Wasm.Sample\Uno.Wasm.Sample.shproj", "{ADEFF1C4-A1B5-4FE8-9EB0-A1D81B65B995}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.SampleNet6", "Uno.Wasm.SampleNet6\Uno.Wasm.SampleNet6.csproj", "{2477F160-939B-4B9F-B9CD-9100FCD24E34}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Embedded", "Embedded", "{DF5C402A-5CB7-4692-BDB3-93F734E214FA}" + ProjectSection(SolutionItems) = preProject + Uno.Wasm.SampleNet7\web.config = Uno.Wasm.SampleNet7\web.config + EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.Embedded.Host", "Uno.Wasm.Embedded.Host\Uno.Wasm.Embedded.Host.csproj", "{EF3A95B2-32EE-4CAA-8235-B2AD6C540389}" EndProject @@ -94,10 +87,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.MetadataUpdater", EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.StaticLinking.PgAot.ProfileGen.Net6", "Uno.Wasm.StaticLinking.PgAot.ProfileGen.Net6\Uno.Wasm.StaticLinking.PgAot.ProfileGen.Net6.csproj", "{2DF55561-12DD-4325-BDBF-F42AC72FC284}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.SampleNet6.LogProfiler", "Uno.Wasm.SampleNet6.LogProfiler\Uno.Wasm.SampleNet6.LogProfiler.csproj", "{92B22005-5A7B-4B38-8D09-68D7240EBE8C}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.LogProfiler", "Uno.Wasm.LogProfiler\Uno.Wasm.LogProfiler.csproj", "{3C2B9F04-972E-4A9F-AA08-545A67C7C455}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.Threads.Aot", "Uno.Wasm.Threads.Aot\Uno.Wasm.Threads.Aot.csproj", "{1CA3AA29-A8FC-4CB3-8803-5BD739F2BEC7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.SampleNet7", "Uno.Wasm.SampleNet7\Uno.Wasm.SampleNet7.csproj", "{D348EE61-E4D1-4DAF-A84F-086BA6AD659B}" @@ -120,12 +109,17 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.VersionChecker", " EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_Root", "_Root", "{70AAFC96-05F5-43A3-959A-95FB32CDE202}" ProjectSection(SolutionItems) = preProject - ..\.vsts-ci-linux.yml = ..\.vsts-ci-linux.yml - ..\.vsts-ci-macos.yml = ..\.vsts-ci-macos.yml - ..\.vsts-ci-windows-tests.yml = ..\.vsts-ci-windows-tests.yml - ..\.vsts-ci-wsl-tests.yml = ..\.vsts-ci-wsl-tests.yml - ..\.vsts-ci.yml = ..\.vsts-ci.yml + ..\build\ci\.markdownlint.json = ..\build\ci\.markdownlint.json + ..\build\ci\cspell.json = ..\build\ci\cspell.json + ..\build\ci\dotnet-install.yml = ..\build\ci\dotnet-install.yml + ..\build\ci\gitversion.yml = ..\build\ci\gitversion.yml ..\Readme.md = ..\Readme.md + ..\build\ci\stage-build-linux-tests.yml = ..\build\ci\stage-build-linux-tests.yml + ..\build\ci\stage-build-macos-tests.yml = ..\build\ci\stage-build-macos-tests.yml + ..\build\ci\stage-build-packages.yml = ..\build\ci\stage-build-packages.yml + ..\build\ci\stage-build-windows-tests.yml = ..\build\ci\stage-build-windows-tests.yml + ..\build\ci\stage-determine-changes.yml = ..\build\ci\stage-determine-changes.yml + ..\build\ci\stage-docs-validations.yml = ..\build\ci\stage-docs-validations.yml EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.Tests.AbsoluteIntermediate", "Uno.Wasm.Tests.AbsoluteIntermediate\Uno.Wasm.Tests.AbsoluteIntermediate.csproj", "{6584CC1B-2628-4872-851A-E85C0E572D39}" @@ -145,6 +139,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{D9443716 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Uno.Wasm.Sample.Library", "Uno.Wasm.Sample.Library\Uno.Wasm.Sample.Library.csproj", "{42FC5421-72BC-41EA-A1C4-FF88A2DC820A}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Uno.Wasm.Bootstrap.DevServer.csproj", "Uno.Wasm.Bootstrap.DevServer\Uno.Wasm.Bootstrap.DevServer.csproj.csproj", "{E12B8472-7C20-42FA-843D-7E12F523CD36}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Uno.Wasm.LogProfiler", "Uno.Wasm.LogProfiler\Uno.Wasm.LogProfiler.csproj", "{39AAD91B-9927-49F1-A186-9C710862E2FB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Uno.Wasm.WebCIL", "Uno.Wasm.WebCIL\Uno.Wasm.WebCIL.csproj", "{49124779-05D7-4611-A116-C0086F24DE9A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -159,10 +159,6 @@ Global {2DFA7173-E4AD-44C6-B25A-2A455CB513FD}.Debug|Any CPU.Build.0 = Debug|Any CPU {2DFA7173-E4AD-44C6-B25A-2A455CB513FD}.Release|Any CPU.ActiveCfg = Release|Any CPU {2DFA7173-E4AD-44C6-B25A-2A455CB513FD}.Release|Any CPU.Build.0 = Release|Any CPU - {AA1C47D5-53C6-4BD6-9206-FDD812D67C13}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AA1C47D5-53C6-4BD6-9206-FDD812D67C13}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AA1C47D5-53C6-4BD6-9206-FDD812D67C13}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AA1C47D5-53C6-4BD6-9206-FDD812D67C13}.Release|Any CPU.Build.0 = Release|Any CPU {DF5FF703-BAC7-427B-BAEA-2E49B65DBF6E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DF5FF703-BAC7-427B-BAEA-2E49B65DBF6E}.Debug|Any CPU.Build.0 = Debug|Any CPU {DF5FF703-BAC7-427B-BAEA-2E49B65DBF6E}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -211,10 +207,6 @@ Global {3D59ACEE-12BF-4B69-AEF7-893514C0BA7D}.Debug|Any CPU.Build.0 = Debug|Any CPU {3D59ACEE-12BF-4B69-AEF7-893514C0BA7D}.Release|Any CPU.ActiveCfg = Release|Any CPU {3D59ACEE-12BF-4B69-AEF7-893514C0BA7D}.Release|Any CPU.Build.0 = Release|Any CPU - {6ACB62AD-0DFF-4593-A7EC-5A4E21DA4ABE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6ACB62AD-0DFF-4593-A7EC-5A4E21DA4ABE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6ACB62AD-0DFF-4593-A7EC-5A4E21DA4ABE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6ACB62AD-0DFF-4593-A7EC-5A4E21DA4ABE}.Release|Any CPU.Build.0 = Release|Any CPU {EBCB3142-593E-4815-915D-3B88B75161C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EBCB3142-593E-4815-915D-3B88B75161C1}.Debug|Any CPU.Build.0 = Debug|Any CPU {EBCB3142-593E-4815-915D-3B88B75161C1}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -251,18 +243,6 @@ Global {E1458920-4A5A-4D54-882D-304A46359BEC}.Debug|Any CPU.Build.0 = Debug|Any CPU {E1458920-4A5A-4D54-882D-304A46359BEC}.Release|Any CPU.ActiveCfg = Release|Any CPU {E1458920-4A5A-4D54-882D-304A46359BEC}.Release|Any CPU.Build.0 = Release|Any CPU - {5A0392DE-9D69-4183-9BD9-84D5723AFB76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5A0392DE-9D69-4183-9BD9-84D5723AFB76}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5A0392DE-9D69-4183-9BD9-84D5723AFB76}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5A0392DE-9D69-4183-9BD9-84D5723AFB76}.Release|Any CPU.Build.0 = Release|Any CPU - {13C116EE-6907-45D4-9CB2-F1E905C71387}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {13C116EE-6907-45D4-9CB2-F1E905C71387}.Debug|Any CPU.Build.0 = Debug|Any CPU - {13C116EE-6907-45D4-9CB2-F1E905C71387}.Release|Any CPU.ActiveCfg = Release|Any CPU - {13C116EE-6907-45D4-9CB2-F1E905C71387}.Release|Any CPU.Build.0 = Release|Any CPU - {2477F160-939B-4B9F-B9CD-9100FCD24E34}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2477F160-939B-4B9F-B9CD-9100FCD24E34}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2477F160-939B-4B9F-B9CD-9100FCD24E34}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2477F160-939B-4B9F-B9CD-9100FCD24E34}.Release|Any CPU.Build.0 = Release|Any CPU {EF3A95B2-32EE-4CAA-8235-B2AD6C540389}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EF3A95B2-32EE-4CAA-8235-B2AD6C540389}.Debug|Any CPU.Build.0 = Debug|Any CPU {EF3A95B2-32EE-4CAA-8235-B2AD6C540389}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -279,14 +259,6 @@ Global {2DF55561-12DD-4325-BDBF-F42AC72FC284}.Debug|Any CPU.Build.0 = Debug|Any CPU {2DF55561-12DD-4325-BDBF-F42AC72FC284}.Release|Any CPU.ActiveCfg = Release|Any CPU {2DF55561-12DD-4325-BDBF-F42AC72FC284}.Release|Any CPU.Build.0 = Release|Any CPU - {92B22005-5A7B-4B38-8D09-68D7240EBE8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {92B22005-5A7B-4B38-8D09-68D7240EBE8C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {92B22005-5A7B-4B38-8D09-68D7240EBE8C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {92B22005-5A7B-4B38-8D09-68D7240EBE8C}.Release|Any CPU.Build.0 = Release|Any CPU - {3C2B9F04-972E-4A9F-AA08-545A67C7C455}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3C2B9F04-972E-4A9F-AA08-545A67C7C455}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3C2B9F04-972E-4A9F-AA08-545A67C7C455}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3C2B9F04-972E-4A9F-AA08-545A67C7C455}.Release|Any CPU.Build.0 = Release|Any CPU {1CA3AA29-A8FC-4CB3-8803-5BD739F2BEC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1CA3AA29-A8FC-4CB3-8803-5BD739F2BEC7}.Debug|Any CPU.Build.0 = Debug|Any CPU {1CA3AA29-A8FC-4CB3-8803-5BD739F2BEC7}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -335,6 +307,18 @@ Global {42FC5421-72BC-41EA-A1C4-FF88A2DC820A}.Debug|Any CPU.Build.0 = Debug|Any CPU {42FC5421-72BC-41EA-A1C4-FF88A2DC820A}.Release|Any CPU.ActiveCfg = Release|Any CPU {42FC5421-72BC-41EA-A1C4-FF88A2DC820A}.Release|Any CPU.Build.0 = Release|Any CPU + {E12B8472-7C20-42FA-843D-7E12F523CD36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E12B8472-7C20-42FA-843D-7E12F523CD36}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E12B8472-7C20-42FA-843D-7E12F523CD36}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E12B8472-7C20-42FA-843D-7E12F523CD36}.Release|Any CPU.Build.0 = Release|Any CPU + {39AAD91B-9927-49F1-A186-9C710862E2FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {39AAD91B-9927-49F1-A186-9C710862E2FB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {39AAD91B-9927-49F1-A186-9C710862E2FB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {39AAD91B-9927-49F1-A186-9C710862E2FB}.Release|Any CPU.Build.0 = Release|Any CPU + {49124779-05D7-4611-A116-C0086F24DE9A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {49124779-05D7-4611-A116-C0086F24DE9A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {49124779-05D7-4611-A116-C0086F24DE9A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {49124779-05D7-4611-A116-C0086F24DE9A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -369,12 +353,10 @@ Global {B27FC2DE-70CA-4287-9FC1-D108F115D8AA} = {35E84E5F-1C9B-4168-8333-216B456C12DF} {B474457D-DBCD-4795-A2AB-EC3F09E53198} = {B27FC2DE-70CA-4287-9FC1-D108F115D8AA} {ADEFF1C4-A1B5-4FE8-9EB0-A1D81B65B995} = {00F3A4D2-5534-44AF-B655-6209355E32A9} - {2477F160-939B-4B9F-B9CD-9100FCD24E34} = {00F3A4D2-5534-44AF-B655-6209355E32A9} {DF5C402A-5CB7-4692-BDB3-93F734E214FA} = {35E84E5F-1C9B-4168-8333-216B456C12DF} {EF3A95B2-32EE-4CAA-8235-B2AD6C540389} = {DF5C402A-5CB7-4692-BDB3-93F734E214FA} {B401928C-600E-4450-ADFF-20EADC7CE3EC} = {DF5C402A-5CB7-4692-BDB3-93F734E214FA} {2DF55561-12DD-4325-BDBF-F42AC72FC284} = {5F914B7D-AFA2-4145-9548-B1B3A16D77AE} - {92B22005-5A7B-4B38-8D09-68D7240EBE8C} = {00F3A4D2-5534-44AF-B655-6209355E32A9} {1CA3AA29-A8FC-4CB3-8803-5BD739F2BEC7} = {B27FC2DE-70CA-4287-9FC1-D108F115D8AA} {D348EE61-E4D1-4DAF-A84F-086BA6AD659B} = {00F3A4D2-5534-44AF-B655-6209355E32A9} {09FAA8FC-54FE-4602-A4A3-37CD98C99F74} = {5F914B7D-AFA2-4145-9548-B1B3A16D77AE} @@ -382,6 +364,7 @@ Global {2829B1BF-47C7-4284-9EAF-DEB48C4A0209} = {00F3A4D2-5534-44AF-B655-6209355E32A9} {227B4962-4978-4712-8C52-630E2371A869} = {5F914B7D-AFA2-4145-9548-B1B3A16D77AE} {A7F3B4BF-A73D-4769-A78D-5F3CAC362AAF} = {84D19B91-8728-4EBD-A6B2-D51F3B0EAB31} + {70AAFC96-05F5-43A3-959A-95FB32CDE202} = {35E84E5F-1C9B-4168-8333-216B456C12DF} {6584CC1B-2628-4872-851A-E85C0E572D39} = {35E84E5F-1C9B-4168-8333-216B456C12DF} {B7270680-8BCF-4246-834C-0F7CAF48FBB9} = {5F914B7D-AFA2-4145-9548-B1B3A16D77AE} {D9443716-A385-4210-80A3-06B8688EDD96} = {70AAFC96-05F5-43A3-959A-95FB32CDE202} @@ -396,13 +379,11 @@ Global Uno.Wasm.Tests.Shared\Uno.Wasm.Tests.Shared.projitems*{1ca3aa29-a8fc-4cb3-8803-5bd739f2bec7}*SharedItemsImports = 5 Uno.Wasm.Threads.Shared\Uno.Wasm.Threads.Shared.projitems*{1ca3aa29-a8fc-4cb3-8803-5bd739f2bec7}*SharedItemsImports = 5 Uno.Wasm.Tests.Shared\Uno.Wasm.Tests.Shared.projitems*{237820d2-9ebd-4e55-b5c3-9b50e628b8d3}*SharedItemsImports = 13 - Uno.Wasm.Sample\Uno.Wasm.Sample.projitems*{2477f160-939b-4b9f-b9cd-9100fcd24e34}*SharedItemsImports = 5 Uno.Wasm.Sample.RayTracer.Shared\Uno.Wasm.Sample.RayTracer.Shared.projitems*{286b5778-da8b-4965-9fc6-bc6f4258e155}*SharedItemsImports = 13 Uno.Wasm.StaticLinking.Shared\Uno.Wasm.StaticLinking.Shared.projitems*{2df55561-12dd-4325-bdbf-f42ac72fc284}*SharedItemsImports = 5 Uno.Wasm.Tests.Shared\Uno.Wasm.Tests.Shared.projitems*{2df55561-12dd-4325-bdbf-f42ac72fc284}*SharedItemsImports = 5 Uno.Wasm.Sample.RayTracer.Shared\Uno.Wasm.Sample.RayTracer.Shared.projitems*{7ee991bb-c93d-4720-854c-1e708b652ef1}*SharedItemsImports = 5 Uno.Wasm.Tests.Shared\Uno.Wasm.Tests.Shared.projitems*{7ee991bb-c93d-4720-854c-1e708b652ef1}*SharedItemsImports = 5 - Uno.Wasm.Sample\Uno.Wasm.Sample.projitems*{92b22005-5a7b-4b38-8d09-68d7240ebe8c}*SharedItemsImports = 5 Uno.Wasm.StaticLinking.Shared\Uno.Wasm.StaticLinking.Shared.projitems*{97e9b56a-be43-4590-a009-9ac135b371be}*SharedItemsImports = 5 Uno.Wasm.Tests.Shared\Uno.Wasm.Tests.Shared.projitems*{97e9b56a-be43-4590-a009-9ac135b371be}*SharedItemsImports = 5 Uno.Wasm.StaticLinking.Shared\Uno.Wasm.StaticLinking.Shared.projitems*{9fff339e-bd09-4d1c-a756-92ae3625eafd}*SharedItemsImports = 5 diff --git a/src/Uno.Wasm.Bootstrap/Constants.cs b/src/Uno.Wasm.Bootstrap/Constants.cs deleted file mode 100644 index ed1e1702a..000000000 --- a/src/Uno.Wasm.Bootstrap/Constants.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Uno.Wasm.Bootstrap -{ - internal class Constants - { - public const string DefaultDotnetRuntimeSdkUrl = "https://unowasmbootstrap.azureedge.net/runtime/" - + "dotnet-runtime-wasm-linux-498e18e-7331dcb60e0-8790049905-Release.zip"; - - /// - /// Min version of the emscripten SDK. Must be aligned with dotnet/runtime SDK build in . - /// - /// - /// The emscripten version use by dotnet/runtime can be found here: - /// https://github.com/dotnet/runtime/blob/f9bb1673708ca840da0e71f9a9444ea9b0d31911/src/mono/wasm/Makefile#L32 - /// - public static Version DotnetRuntimeEmscriptenVersion { get; } = new Version("3.1.34"); - } -} diff --git a/src/Uno.Wasm.Bootstrap/Extensions/RuntimeHelpers.cs b/src/Uno.Wasm.Bootstrap/Extensions/RuntimeHelpers.cs deleted file mode 100644 index ac0cc2e7f..000000000 --- a/src/Uno.Wasm.Bootstrap/Extensions/RuntimeHelpers.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Uno.Wasm.Bootstrap -{ - class RuntimeHelpers - { - public static bool IsNetCore => Type.GetType("System.Runtime.Loader.AssemblyLoadContext", false) != null; - - public static bool IsMono => Type.GetType("Mono.Runtime") != null; - } -} diff --git a/src/Uno.Wasm.Bootstrap/Extensions/ZipExtensions.cs b/src/Uno.Wasm.Bootstrap/Extensions/ZipExtensions.cs deleted file mode 100644 index c23b98c12..000000000 --- a/src/Uno.Wasm.Bootstrap/Extensions/ZipExtensions.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.IO.Compression; -using System.Text; - -namespace Uno.Wasm.Bootstrap.Extensions -{ - public static class ZipExtensions - { - internal static void ExtractRelativeToDirectory(this ZipArchiveEntry source, string destinationDirectoryName, bool overwrite) - { - // Note that this will give us a good DirectoryInfo even if destinationDirectoryName exists: - DirectoryInfo di = Directory.CreateDirectory(destinationDirectoryName); - string destinationDirectoryFullPath = di.FullName; - if (!destinationDirectoryFullPath.EndsWith(new string(Path.DirectorySeparatorChar, 1))) - { - destinationDirectoryFullPath += Path.DirectorySeparatorChar; - } - - string fileDestinationPath = Path.GetFullPath(Path.Combine(destinationDirectoryFullPath, source.FullName)); - - if (!fileDestinationPath.StartsWith(destinationDirectoryFullPath)) - { - throw new IOException("ExtractingResultsInOutside"); - } - - if (Path.GetFileName(fileDestinationPath).Length == 0) - { - // If it is a directory: - - if (source.Length != 0) - { - throw new IOException("DirectoryNameWithData"); - } - - Directory.CreateDirectory(fileDestinationPath); - } - else - { - // If it is a file: - // Create containing directory: - Directory.CreateDirectory(Path.GetDirectoryName(fileDestinationPath)); - source.ExtractToFile(fileDestinationPath, overwrite: overwrite); - } - } - - } -} diff --git a/src/Uno.Wasm.Bootstrap/FileNameObfuscationMode.cs b/src/Uno.Wasm.Bootstrap/FileNameObfuscationMode.cs deleted file mode 100644 index bd0b177e9..000000000 --- a/src/Uno.Wasm.Bootstrap/FileNameObfuscationMode.cs +++ /dev/null @@ -1,27 +0,0 @@ -// ****************************************************************** -// Copyright � 2015-2022 Uno Platform inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// ****************************************************************** -// -// This file is based on the work from https://github.com/praeclarum/Ooui -// -namespace Uno.Wasm.Bootstrap -{ - internal enum FileNameObfuscationMode - { - Original, - NoDots - } -} diff --git a/src/Uno.Wasm.Bootstrap/LinkOptimizationLevel.cs b/src/Uno.Wasm.Bootstrap/LinkOptimizationLevel.cs deleted file mode 100644 index 62bad1382..000000000 --- a/src/Uno.Wasm.Bootstrap/LinkOptimizationLevel.cs +++ /dev/null @@ -1,31 +0,0 @@ -// ****************************************************************** -// Copyright � 2015-2022 Uno Platform inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// ****************************************************************** -// -// This file is based on the work from https://github.com/praeclarum/Ooui -// - -namespace Uno.Wasm.Bootstrap -{ - enum LinkOptimizationLevel - { - None, - Level1, - Level2, - Level3, - Maximum, - } -} diff --git a/src/Uno.Wasm.Bootstrap/MetadataKeys.cs b/src/Uno.Wasm.Bootstrap/MetadataKeys.cs new file mode 100644 index 000000000..d51f84f06 --- /dev/null +++ b/src/Uno.Wasm.Bootstrap/MetadataKeys.cs @@ -0,0 +1,142 @@ +// Extracted from https://github.com/dotnet/sdk/blob/10803eca35eef6e685924886ba74caf0bd9439ad/src/Tasks/Common/MetadataKeys.cs#L6 + +namespace Uno.Wasm.Bootstrap +{ + internal static class MetadataKeys + { + // General Metadata + public const string Name = "Name"; + public const string Type = "Type"; + public const string Version = "Version"; + public const string FileGroup = "FileGroup"; + public const string Path = "Path"; + public const string ResolvedPath = "ResolvedPath"; + public const string IsImplicitlyDefined = "IsImplicitlyDefined"; + public const string IsTopLevelDependency = "IsTopLevelDependency"; + public const string AllowExplicitVersion = "AllowExplicitVersion"; + public const string RelativePath = "RelativePath"; + public const string DiagnosticLevel = "DiagnosticLevel"; + public const string Implementation = "Implementation"; // Metadata on WinMD references + + // Target Metadata + public const string RuntimeIdentifier = "RuntimeIdentifier"; + public const string TargetFrameworkMoniker = "TargetFrameworkMoniker"; + public const string TargetFramework = "TargetFramework"; + public const string FrameworkName = "FrameworkName"; + public const string FrameworkVersion = "FrameworkVersion"; + public const string IsTrimmable = "IsTrimmable"; + public const string RuntimeFrameworkName = "RuntimeFrameworkName"; + + // SDK Metadata + public const string SDKPackageItemSpec = "SDKPackageItemSpec"; + public const string OriginalItemSpec = "OriginalItemSpec"; + public const string SDKRootFolder = "SDKRootFolder"; + public const string ShimRuntimeIdentifier = "ShimRuntimeIdentifier"; + public const string RuntimePackAlwaysCopyLocal = "RuntimePackAlwaysCopyLocal"; + + // Foreign Keys + public const string ParentTarget = "ParentTarget"; + public const string ParentTargetLibrary = "ParentTargetLibrary"; + public const string ParentPackage = "ParentPackage"; + + // Tags + public const string Analyzer = "Analyzer"; + public const string AnalyzerLanguage = "AnalyzerLanguage"; + public const string TransitiveProjectReference = "TransitiveProjectReference"; + + // Diagnostics + public const string DiagnosticCode = "DiagnosticCode"; + public const string Message = "Message"; + public const string FilePath = "FilePath"; + public const string Severity = "Severity"; + public const string StartLine = "StartLine"; + public const string StartColumn = "StartColumn"; + public const string EndLine = "EndLine"; + public const string EndColumn = "EndColumn"; + + // Publish Target Manifest + public const string RuntimeStoreManifestNames = "RuntimeStoreManifestNames"; + + // Conflict Resolution + public const string OverriddenPackages = "OverriddenPackages"; + + // Package assets + public const string NuGetIsFrameworkReference = "NuGetIsFrameworkReference"; + public const string NuGetPackageId = "NuGetPackageId"; + public const string NuGetPackageVersion = "NuGetPackageVersion"; + public const string NuGetSourceType = "NuGetSourceType"; + public const string PathInPackage = "PathInPackage"; + public const string PackageDirectory = "PackageDirectory"; + public const string Publish = "Publish"; + + // References + public const string ExternallyResolved = "ExternallyResolved"; + public const string HintPath = "HintPath"; + public const string MSBuildSourceProjectFile = "MSBuildSourceProjectFile"; + public const string Private = "Private"; + public const string Pack = "Pack"; + public const string ReferenceSourceTarget = "ReferenceSourceTarget"; + public const string TargetPath = "TargetPath"; + public const string CopyLocal = "CopyLocal"; + + // Targeting packs + public const string PackageConflictPreferredPackages = "PackageConflictPreferredPackages"; + public const string RuntimePackRuntimeIdentifiers = "RuntimePackRuntimeIdentifiers"; + public const string RuntimePackExcludedRuntimeIdentifiers = "RuntimePackExcludedRuntimeIdentifiers"; + + // Runtime packs + public const string DropFromSingleFile = "DropFromSingleFile"; + public const string RuntimePackLabels = "RuntimePackLabels"; + public const string AdditionalFrameworkReferences = "AdditionalFrameworkReferences"; + + // Apphost packs + public const string ExcludedRuntimeIdentifiers = "ExcludedRuntimeIdentifiers"; + + // Content files + public const string PPOutputPath = "PPOutputPath"; + public const string CodeLanguage = "CodeLanguage"; + public const string CopyToOutput = "CopyToOutput"; + public const string BuildAction = "BuildAction"; + public const string OutputPath = "OutputPath"; + public const string CopyToPublishDirectory = "CopyToPublishDirectory"; + public const string ExcludeFromSingleFile = "ExcludeFromSingleFile"; + + // Resource assemblies + public const string Culture = "Culture"; + // The DestinationSubDirectory is the directory containing the asset, relative to the destination folder. + public const string DestinationSubDirectory = "DestinationSubDirectory"; + + // Copy local assets + // The DestinationSubPath is the path to the asset, relative to the destination folder. + public const string DestinationSubPath = "DestinationSubPath"; + public const string AssetType = "AssetType"; + + public const string ReferenceOnly = "ReferenceOnly"; + + public const string Aliases = "Aliases"; + + // ReadyToRun + public const string DotNetHostPath = "DotNetHostPath"; + public const string JitPath = "JitPath"; + public const string TargetOS = "TargetOS"; + public const string TargetArch = "TargetArch"; + public const string DiaSymReader = "DiaSymReader"; + public const string CreatePDBCommand = "CreatePDBCommand"; + public const string OutputR2RImage = "OutputR2RImage"; + public const string OutputPDBImage = "OutputPDBImage"; + public const string EmitSymbols = "EmitSymbols"; + public const string IsVersion5 = "IsVersion5"; + public const string CreateCompositeImage = "CreateCompositeImage"; + public const string PerfmapFormatVersion = "PerfmapFormatVersion"; + + // Debug symbols + public const string RelatedProperty = "related"; + public const string XmlExtension = ".xml"; + public const string XmlFilePath = "XmlFilePath"; + public const string PdbExtension = ".pdb"; + public const string PdbFilePath = "PdbFilePath"; + + // Dependencies design time + public const string Resolved = "Resolved"; + } +} diff --git a/src/Uno.Wasm.Bootstrap/ShellTask.AOTProfile.cs b/src/Uno.Wasm.Bootstrap/ShellTask.AOTProfile.cs index 67228c8ef..1cf6a311c 100644 --- a/src/Uno.Wasm.Bootstrap/ShellTask.AOTProfile.cs +++ b/src/Uno.Wasm.Bootstrap/ShellTask.AOTProfile.cs @@ -47,7 +47,7 @@ public partial class ShellTask_v0 /// private string? TransformAOTProfile() { - var profilePath = AotProfile?.FirstOrDefault()?.GetMetadata("FullPath"); + var profilePath = AotProfile; if (profilePath != null) { @@ -125,7 +125,7 @@ private void TryDumpProfileMethods(Mono.Profiler.Aot.ProfileData profile, string foreach (var method in profile.Methods) { - var genericParameters = string.Join("|", method.GenericInst?.Types.Select(t => t.ToString()) ?? new string[0]); + var genericParameters = string.Join("|", method.GenericInst?.Types.Select(t => t.ToString()) ?? []); sb.AppendLine($"{method.Type.Module.Name};{method.Type.FullName}.{method.Name};{method.GenericInst?.Id};{genericParameters}"); } diff --git a/src/Uno.Wasm.Bootstrap/ShellTask.cs b/src/Uno.Wasm.Bootstrap/ShellTask.cs index 6d1b29cfc..ececf6965 100644 --- a/src/Uno.Wasm.Bootstrap/ShellTask.cs +++ b/src/Uno.Wasm.Bootstrap/ShellTask.cs @@ -26,13 +26,16 @@ using System.Linq; using System.Net; using System.Net.Http.Headers; +using System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Transactions; +using System.Xml.Linq; using Microsoft.Build.Framework; +using Microsoft.Build.Utilities; using Microsoft.Win32.SafeHandles; using Mono.Cecil; using Mono.CompilerServices.SymbolWriter; @@ -42,1712 +45,165 @@ namespace Uno.Wasm.Bootstrap { - public partial class ShellTask_v0 : Microsoft.Build.Utilities.Task + public partial class ShellTask_v0 : Task { private const string WasmScriptsFolder = "WasmScripts"; - private const string ServiceWorkerFileName = "service-worker.js"; private const string DeployMetadataName = "UnoDeploy"; - private static readonly string _wwwwroot = "wwwroot" + Path.DirectorySeparatorChar; - - private string _distPath = ""; - private string _workDistPath = ""; - private string _workDistRootPath = ""; - private string _managedPath = ""; - private string _bclPath = ""; - private string[]? _bitcodeFilesCache; - private List _referencedAssemblies = new List(); - private Dictionary? _bclAssemblies; - private readonly List _dependencies = new List(); - private string[]? _additionalStyles; - private List? _resourceSearchList; - private RuntimeExecutionMode _runtimeExecutionMode; - private ShellMode _shellMode; - private CompressionLayoutMode _compressionLayoutMode; - private string _linkerBinPath = ""; - private string _finalPackagePath = ""; - private string _remoteBasePackagePath = ""; - private string[]? _contentExtensionsToExclude; - - private static readonly SHA384Managed _sha384 = new SHA384Managed(); - private UTF8Encoding _utf8Encoding = new UTF8Encoding(false); - private byte[] _obfuscationKey = Array.Empty(); - private FileNameObfuscationMode _assembliesFileNameObfuscationMode - = FileNameObfuscationMode.Original; - - [Microsoft.Build.Framework.Required] - public string CurrentProjectPath { get; set; } = ""; - - [Microsoft.Build.Framework.Required] - public string BuildTaskBasePath { get; set; } = ""; - - [Microsoft.Build.Framework.Required] - public string Assembly { get; set; } = ""; - - [Microsoft.Build.Framework.Required] - public string DistPath { get; set; } = ""; - - [Microsoft.Build.Framework.Required] - public string IntermediateOutputPath { get; set; } = ""; - [Microsoft.Build.Framework.Required] - public string ProjectDir { get; set; } = ""; - - [Microsoft.Build.Framework.Required] - public string MonoWasmSDKPath { get; set; } = ""; - - public string? PackagerBinPath { get; set; } - - public bool UseFileIntegrity { get; set; } = true; - - /// - /// Disabled until browsers get smarted about fetch vs. prefetch invocations. - /// e.g. Chrome downloads files twice. - /// - public bool GeneratePrefetchHeaders { get; set; } = false; - - public Microsoft.Build.Framework.ITaskItem[]? ReferencePath { get; set; } - - public Microsoft.Build.Framework.ITaskItem[]? MonoEnvironment { get; set; } - - public Microsoft.Build.Framework.ITaskItem[]? RuntimeCopyExclude { get; set; } - - [Microsoft.Build.Framework.Required] - public string TargetFrameworkIdentifier { get; set; } = ""; - - public string TargetFramework { get; set; } = ""; - - public string TargetFrameworkVersion { get; set; } = "0.0"; - - [Microsoft.Build.Framework.Required] - public string IndexHtmlPath { get; set; } = ""; - - public string WebAppBasePath { get; set; } = "./"; - - [Required] - public string WasmShellMode { get; set; } = ""; - - [Microsoft.Build.Framework.Required] - public string MonoRuntimeExecutionMode { get; set; } = ""; - - [Microsoft.Build.Framework.Required] - public bool MonoILLinker { get; set; } - - public bool InvariantGlobalization { get; set; } = false; - - public string CSPConfiguration { get; set; } = ""; - - public bool EnableJiterpreter { get; set; } = false; - - public string RuntimeOptions { get; set; } = ""; - - public bool EmccLinkOptimization { get; set; } - - public string? EmccLinkOptimizationLevel { get; set; } - - public bool EnableLogProfiler { get; set; } - - public string LogProfilerOptions { get; set; } = "log:alloc,output=output.mlpd"; - - public string AssembliesFileExtension { get; set; } = ".clr"; - - public string AssembliesFileNameObfuscationMode { get; set; } = nameof(FileNameObfuscationMode.Original); - - public bool ObfuscateAssemblies { get; set; } = false; - - public Microsoft.Build.Framework.ITaskItem[]? Assets { get; set; } - - public string? ContentExtensionsToExclude { get; set; } - - public Microsoft.Build.Framework.ITaskItem[]? AotProfile { get; set; } - - public Microsoft.Build.Framework.ITaskItem[]? LinkerDescriptors { get; set; } - - public Microsoft.Build.Framework.ITaskItem[]? MixedModeExcludedAssembly { get; set; } - - public string AOTProfileExcludedMethods { get; set; } = ""; - - public bool GenerateAOTProfileDebugList { get; set; } = false; - - public bool PrintAOTSkippedMethods { get; set; } = false; - - public Microsoft.Build.Framework.ITaskItem[]? CompressedExtensions { get; set; } - - public Microsoft.Build.Framework.ITaskItem[]? ExtraEmccFlags { get; set; } - - public Microsoft.Build.Framework.ITaskItem[]? RuntimeHostConfigurationOption { get; set; } - - public Microsoft.Build.Framework.ITaskItem[]? AdditionalPInvokeLibraries { get; set; } - - public Microsoft.Build.Framework.ITaskItem[]? NativeCompile { get; set; } - - public Microsoft.Build.Framework.ITaskItem[]? EmccExportedRuntimeMethods { get; set; } - - public bool GenerateCompressedFiles { get; set; } - - public string? DistCompressionLayoutMode { get; set; } - - public bool ForceUseWSL { get; set; } - - public bool EnableEmscriptenWindows { get; set; } = true; - - public bool ForceDisableWSL { get; set; } - - public bool SkipPowershellExecutionPolicyValidation { get; set; } = false; - - [Microsoft.Build.Framework.Required] - public string RuntimeConfiguration { get; set; } = ""; - - [Microsoft.Build.Framework.Required] - public bool EnableThreads { get; set; } - - public int PThreadsPoolSize { get; set; } = 4; - - [Microsoft.Build.Framework.Required] - public bool EnableSimd { get; set; } - - [Microsoft.Build.Framework.Required] - public bool RuntimeDebuggerEnabled { get; set; } - - public int BrotliCompressionQuality { get; set; } = 7; - - public string? CustomDebuggerPath { get; set; } - - public string? CustomLinkerPath { get; set; } - - public string? WasmTunerBinPath { get; set; } - - public string? PWAManifestFile { get; set; } - - public bool EnableLongPathSupport { get; set; } = true; - - public bool EnableEmccProfiling { get; set; } = false; - - public bool EnableNetCoreICU { get; set; } = true; - - public bool EnableAOTDeduplication { get; set; } = true; - - public bool EnableAotGSharedVT { get; set; } = false; - - public string? AotCompilerOptions { get; set; } - - public bool GenerateAOTProfile { get; set; } = false; - - public string? NinjaAdditionalParameters { get; set; } - - [Output] - public string? OutputPackagePath { get; private set; } - - [Output] - public string? OutputDistPath { get; private set; } - - private Version ActualTargetFrameworkVersion - => Version.TryParse(TargetFrameworkVersion.Substring(1), out var v) ? v : new Version("0.0"); - - public override bool Execute() - { - try - { - if (string.IsNullOrEmpty(TargetFramework)) - { - throw new InvalidOperationException($"The TargetFramework task parameter must be defined."); - } - - if(TargetFrameworkIdentifier == ".NETCoreApp" && ActualTargetFrameworkVersion < new Version("5.0")) - { - throw new InvalidOperationException($"The TargetFramework version must be above 5.0 (found {TargetFrameworkVersion})"); - } - - // Debugger.Launch(); - - PreloadAssemblies(); - ValidateEmscriptenWindowsAvailability(); - TryGenerateObfuscationKey(); - TryEnableLongPathAware(); - ParseProperties(); - GetBcl(); - CreateDist(); - CopyContent(); - CopyRuntime(); - RunPackager(); - TryDeployDebuggerProxy(); - GenerateServerAppFeaturesInfo(); - ExtractAdditionalJS(); - ExtractAdditionalCSS(); - CleanupDist(); - PrepareFinalDist(); - TouchServiceWorker(); - GenerateConfig(); - MergeConfig(); - GenerateIndexHtml(); - GenerateEmbeddedJs(); - TryCompressDist(); - - return true; - } - catch (Exception ex) - { - Log.LogError(ex.ToString(), false, true, null); - return false; - } - } - - private void TryGenerateObfuscationKey() - { - if (ObfuscateAssemblies) - { - _obfuscationKey = Encoding.ASCII.GetBytes(Guid.NewGuid().ToString().Split('-')[0]); - } - } - - private void PreloadAssemblies() - { - // Under some circumstances, the assemblies bundled with the bootstrapper do not - // get loaded properly by .NET Core. This is method forces the loading of those - // assemblies in order to let the loading find them automatically. - - var path = Path.GetDirectoryName(new Uri(GetType().Assembly.GetName().CodeBase).LocalPath); - - foreach (var file in Directory.GetFiles(path, "*.dll")) - { - _ = System.Reflection.Assembly.LoadFile(Path.Combine(path, file)); - } - } - - private void TryEnableLongPathAware() - { - if (EnableLongPathSupport) - { - // In some cases, particularly when using the Azure publish task - // long paths using the "\\?\" prefix is not supported. Fallback on - // standard paths in such cases. - - try - { - var path = TryConvertLongPath(Path.GetFullPath(DistPath)); - - DirectoryCreateDirectory(path); - } - catch (ArgumentException e) - { - Log.LogMessage($"Long path format use failed, falling back to standard path (Error: {e.Message})"); - EnableLongPathSupport = false; - } - } - - IntermediateOutputPath = TryConvertLongPath(IntermediateOutputPath); - - if (!Path.IsPathRooted(IntermediateOutputPath)) - { - IntermediateOutputPath = TryConvertLongPath(Path.Combine(ProjectDir, IntermediateOutputPath)); - } - - DistPath = TryConvertLongPath(DistPath); - CurrentProjectPath = TryConvertLongPath(CurrentProjectPath); - CustomDebuggerPath = TryConvertLongPath(CustomDebuggerPath!); - } - - private void ValidateEmscriptenWindowsAvailability() - { - if (EnableEmscriptenWindows && Environment.OSVersion.Platform != PlatformID.Win32NT) - { - EnableEmscriptenWindows = false; - } - } - - - private void TouchServiceWorker() - { - // The service worker file must change to be reloaded properly, add the dist digest - // as cache trasher. - var workerFilePath = Path.Combine(_finalPackagePath, ServiceWorkerFileName); - var workerBody = File.ReadAllText(workerFilePath); - - workerBody = workerBody.Replace("$(CACHE_KEY)", Path.GetFileName(_remoteBasePackagePath)); - workerBody = workerBody.Replace("$(REMOTE_BASE_PATH)", _remoteBasePackagePath); - workerBody = workerBody.Replace("$(REMOTE_WEBAPP_PATH)", WebAppBasePath); - workerBody += $"\r\n\r\n// {Path.GetFileName(_managedPath)}"; - - File.WriteAllText(workerFilePath, workerBody); - - // The service worker file must be placed at the root in order to specify the - // "./" scope to include index.html in the worker. Otherwise, offline mode cannot - // work if index.html is not cached. - MoveFileSafe(workerFilePath, Path.Combine(_distPath, ServiceWorkerFileName)); - } - - private void FileCopy(string source, string dest, bool overwrite = false) - { - var sourceFileName = PathHelper.FixupPath(source); - var destFileName = PathHelper.FixupPath(dest); - - try - { - File.Copy(sourceFileName, destFileName, overwrite); - } - catch (Exception ex) - { - Log.LogError($"Failed to copy {sourceFileName} to {destFileName}: {ex.Message}"); - throw; - } - } - - private void DirectoryCreateDirectory(string directory) - { - var directoryName = PathHelper.FixupPath(directory); - - try - { - Directory.CreateDirectory(directoryName); - } - catch (Exception /*e*/) - { - Log.LogError($"Failed to create directory [{directoryName}][{directory}]"); - throw; - } - } - - private void CleanupDist() - { - var unusedFiles = new[] { - "*.wast", - "*.bc", - "*.a", - "*.rsp", - "*.c", - "*.h", - "package.json", - }; - - foreach (var unusedFile in unusedFiles) - { - foreach (var file in Directory.EnumerateFiles(_workDistPath, unusedFile)) - { - Log.LogMessage(MessageImportance.Low, $"Removing unused file {file}"); - File.Delete(file); - } - } - } - - private void TryCompressDist() - { - var hasCompressedExtensions = (CompressedExtensions?.Any() ?? false); - - if ( - !RuntimeDebuggerEnabled - && GenerateCompressedFiles - && hasCompressedExtensions - ) - { - TryParseDistCompressionLayoutMode(); - - var compressibleExtensions = CompressedExtensions - .Select(e => e.ItemSpec); - - Log.LogMessage(MessageImportance.Low, $"Compressing {string.Join(", ", compressibleExtensions)}"); - - var filesToCompress = compressibleExtensions - .Select(e => { - if (_assembliesFileNameObfuscationMode == FileNameObfuscationMode.NoDots) - { - e = e.Replace(".", "_"); - } - return e; - }) - .SelectMany(e => Directory.GetFiles(_finalPackagePath, "*" + e, SearchOption.AllDirectories)) - .Where(f => !Path.GetDirectoryName(f).Contains("_compressed_")) - .Distinct() - .ToArray(); - - if (_compressionLayoutMode == CompressionLayoutMode.Legacy) - { - CompressFiles(filesToCompress, "gz", GzipCompress); - } - - CompressFiles(filesToCompress, "br", BrotliCompress); - } - else - { - Log.LogMessage(MessageImportance.Low, - $"Compression is disabled (RuntimeDebuggerEnabled:{RuntimeDebuggerEnabled}, " + - $"GenerateCompressedFiles:{GenerateCompressedFiles}, " + - $"hasCompressedExtensions:{hasCompressedExtensions})"); - } - } - - private void TryParseDistCompressionLayoutMode() - { - if (string.IsNullOrEmpty(DistCompressionLayoutMode)) - { - var webConfigPath = Directory.GetFiles(_distPath, "web.config").FirstOrDefault(); - - if (!string.IsNullOrEmpty(webConfigPath) - && File.ReadAllText(webConfigPath).Contains("_compressed_br")) - { - _compressionLayoutMode = CompressionLayoutMode.Legacy; - } - else - { - _compressionLayoutMode = CompressionLayoutMode.InPlace; - } - } - else - { - ParseEnumProperty(nameof(CompressionLayoutMode), DistCompressionLayoutMode!, out _compressionLayoutMode); - } - } - - private void CompressFiles(string[] filesToCompress, string method, Action compressHandler) - => filesToCompress - .AsParallel() - .Select(fileName => - { - var compressedPathBase = _compressionLayoutMode switch - { - CompressionLayoutMode.InPlace => _distPath, - CompressionLayoutMode.Legacy => Path.Combine(_distPath, "_compressed_" + method), - _ => throw new NotSupportedException($"CompressionLayoutMode {_compressionLayoutMode} is not supported") - }; - - var compressedFileName = fileName; - compressedFileName = compressedFileName.Replace(_distPath, compressedPathBase); - - if (_compressionLayoutMode == CompressionLayoutMode.InPlace) - { - compressedFileName += "." + method; - } - - DirectoryCreateDirectory(Path.GetDirectoryName(compressedFileName)); - - if (File.Exists(compressedFileName)) - { - if (File.GetCreationTime(compressedFileName) < File.GetCreationTime(fileName)) - { - Log.LogMessage(MessageImportance.Low, $"Deleting {compressedFileName} as the source has changed"); - File.Delete(compressedFileName); - } - } - - Log.LogMessage($"Compressing {fileName}->{compressedFileName}"); - - compressHandler(fileName, compressedFileName); - - return true; - }) - .ToArray(); - - private void GzipCompress(string source, string destination) - { - using var inStream = File.Open(source, FileMode.Open, FileAccess.Read, FileShare.Read); - using var compressedFileStream = File.Create(destination); - using var compressionStream = new GZipStream(compressedFileStream, CompressionLevel.Optimal); - - inStream.CopyTo(compressionStream); - } - - private void BrotliCompress(string source, string destination) - { - using var input = File.Open(source, FileMode.Open, FileAccess.Read, FileShare.Read); - using var output = File.Create(destination); - using var bs = new BrotliSharpLib.BrotliStream(output, CompressionMode.Compress); - - // By default, BrotliSharpLib uses a quality value of 1 and window size of 22 if the methods are not called. - bs.SetQuality(BrotliCompressionQuality); - /** bs.SetWindow(windowSize); **/ - /** bs.SetCustomDictionary(customDict); **/ - input.CopyTo(bs); - - /* IMPORTANT: Only use the destination stream after closing/disposing the BrotliStream - as the BrotliStream must be closed in order to signal that no more blocks are being written - for the final block to be flushed out - */ - bs.Dispose(); - } - - private bool IsWSLRequired => - Environment.OSVersion.Platform == PlatformID.Win32NT - && !EnableEmscriptenWindows - && (GetBitcodeFilesParams().Any() || _runtimeExecutionMode != RuntimeExecutionMode.Interpreter || ForceUseWSL || GenerateAOTProfile || UseAotProfile); - - private bool UseAotProfile => (AotProfile?.Any() ?? false) && _runtimeExecutionMode == RuntimeExecutionMode.InterpreterAndAOT; - - public Version CurrentEmscriptenVersion => Constants.DotnetRuntimeEmscriptenVersion; - - public bool HasAdditionalPInvokeLibraries => AdditionalPInvokeLibraries is { } libs && libs.Length != 0; - - public bool HasNativeCompile => NativeCompile is { } nativeCompile && nativeCompile.Length != 0; - - private (int exitCode, string output, string error) RunProcess( - string executable, - string parameters, - string? workingDirectory = null, - (string variable, string value)[]? environmentVariables = null) - { - if (IsWSLRequired - && !ForceDisableWSL - && !EnableEmscriptenWindows - && !executable.EndsWith("bash.exe", StringComparison.OrdinalIgnoreCase)) - { - var unixPath = AlignPath(executable, escape: true); - var dotnetRuntimePath = Path.GetExtension(executable).ToLowerInvariant() - switch - { - ".exe" => "mono", - ".dll" => "dotnet", - _ => "" - }; - - var cwd = workingDirectory != null ? $"cd \\\"{AlignPath(workingDirectory, escape: true)}\\\" && " : ""; - - parameters = $"-c \" {cwd} {dotnetRuntimePath} {unixPath} " + parameters.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""; - - executable = GetWSLBashExecutable(); - } - else if (RuntimeHelpers.IsNetCore - && (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) - || RuntimeInformation.IsOSPlatform(OSPlatform.Linux) - ) - ) - { - if (executable.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) - { - parameters = $"\"{executable}\" {parameters}"; - executable = "mono"; - } - - if (executable.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) - { - parameters = $"\"{executable}\" {parameters}"; - executable = "dotnet"; - } - } - else - { - if (executable.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) - { - parameters = $"\"{executable}\" {parameters}"; - executable = "dotnet"; - } - } - - var p = new Process - { - StartInfo = - { - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - FileName = executable, - Arguments = parameters - } - }; - - if(environmentVariables is not null) - { - foreach (var envVar in environmentVariables) - { - p.StartInfo.Environment.Add(envVar.variable, envVar.value); - } - } - - if (workingDirectory != null) - { - p.StartInfo.WorkingDirectory = workingDirectory; - } - - Log.LogMessage($"Running [{p.StartInfo.WorkingDirectory}]: {p.StartInfo.FileName} {p.StartInfo.Arguments}"); - - var output = new StringBuilder(); - var error = new StringBuilder(); - var elapsed = Stopwatch.StartNew(); - p.OutputDataReceived += (s, e) => { if (e.Data != null) { Log.LogMessage($"[{elapsed.Elapsed}] {e.Data}"); output.Append(e.Data); } }; - p.ErrorDataReceived += (s, e) => { if (e.Data != null) { Log.LogError($"[{elapsed.Elapsed}] {e.Data}"); error.Append(e.Data); } }; - - if (p.Start()) - { - p.BeginOutputReadLine(); - p.BeginErrorReadLine(); - p.WaitForExit(); - var exitCore = p.ExitCode; - p.Close(); - - return (exitCore, output.ToString(), error.ToString()); - } - else - { - throw new Exception($"Failed to start [{executable}]"); - } - } - - private static string GetWSLBashExecutable() - { - string executable; - var basePaths = new[] { - Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), "sysnative"), // 32 bits process - Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), "System32"), // 64 bits process - }; - - var fullPaths = basePaths.Select(p => Path.Combine(p, "bash.exe")); - - executable = fullPaths.FirstOrDefault(f => File.Exists(f)); - - if (string.IsNullOrEmpty(executable)) - { - var allPaths = string.Join(";", fullPaths); - - throw new InvalidOperationException( - $"WSL is required for this build but could not be found (Searched for [{allPaths}]). " + - $"WSL use may be explicitly disabled for CI Windows builds, see more details here: https://github.com/unoplatform/Uno.Wasm.Bootstrap#special-considerations-for-ci-servers-github-actions-azure-devops"); - } - - return executable; - } - - private string AlignPath(string path, bool escape = false) - { - var trimmedPath = path.Replace("\\\\?\\", ""); - - string convertPath() - { - if(IsWSLRequired && !ForceDisableWSL && Path.IsPathRooted(path)) - { - - var drive = trimmedPath.Substring(0, 1).ToLowerInvariant(); - var remainder = trimmedPath.Substring(3).Replace("\\", "/"); - - var r = $"/mnt/{drive}/{remainder}"; - - Log.LogMessage(MessageImportance.High, $"{path} -> {r}"); - return r; - } - else - { - return trimmedPath; - } - } - - var output = convertPath(); - - if (escape) - { - output = output.Replace("\"", "\\\""); - } - - return output; - } - - private void TryDeployDebuggerProxy() - { - var sdkName = Path.GetFileName(MonoWasmSDKPath); - - if (!string.IsNullOrEmpty(CustomDebuggerPath)) - { - CustomDebuggerPath = PathHelper.FixupPath(CustomDebuggerPath!); - } - - var wasmDebuggerRootPath = Path.Combine(IntermediateOutputPath, "wasm-debugger"); - DirectoryCreateDirectory(wasmDebuggerRootPath); - - var debuggerBinBasePaths = new[] { - Path.Combine(MonoWasmSDKPath, "dbg-proxy", TargetFramework.ToLower()), // Compatibility with previous runtime packages - Path.Combine(MonoWasmSDKPath, "dbg-proxy", "net5", "Release"), // Compatibility with previous runtime packages - Path.Combine(MonoWasmSDKPath, "dbg-proxy", "net5"), - Path.Combine(MonoWasmSDKPath, "dbg-proxy", "net7.0") - }; - - var proxyBasePath = debuggerBinBasePaths.First(Directory.Exists); - - // Write down the debugger file path so the static file server can find it - File.WriteAllText(Path.Combine(wasmDebuggerRootPath, ".debuggerinfo"), proxyBasePath); - } - - private void GenerateServerAppFeaturesInfo() - // Write down an info file so the static file server can find it - => File.WriteAllText(Path.Combine(IntermediateOutputPath, ".unoappfeatures"), BuildRuntimeFeatures()); - - private void RunPackager() - { - BuildReferencedAssembliesList(); - - var workAotPath = Path.Combine(IntermediateOutputPath, "workAot"); - - if (Directory.Exists(workAotPath)) - { - DirectoryDelete(workAotPath); - } - - DirectoryCreateDirectory(workAotPath); - - var referencePathsParameter = string.Join( - " " - , _referencedAssemblies.Select(Path.GetDirectoryName).Distinct().Select(r => $"--search-path=\"{AlignPath(r)}\"")); - - var referenceAssembliesParameter = string.Join( - " " - , _referencedAssemblies.Distinct().Select(r => $"--asm-ref=\"{AlignPath(r)}\"")); - - var metadataUpdaterPath = Path.Combine(BuildTaskBasePath, "..", "tools", "support", "Uno.Wasm.MetadataUpdater.dll"); - - if (RuntimeDebuggerEnabled) - { - referencePathsParameter += $" \"{AlignPath(metadataUpdaterPath)}\""; - } - - var debugOption = RuntimeDebuggerEnabled ? "--debug" : ""; - string packagerBinPath = string.IsNullOrWhiteSpace(PackagerBinPath) ? Path.Combine(MonoWasmSDKPath, "packager.exe") : PackagerBinPath!; - var appDirParm = $"--appdir=\"{AlignPath(_workDistPath)}\" "; - - // Determines if the packager needs to be used. - var useFullPackager = - !ForceDisableWSL - && (IsRuntimeAOT() - || GetBitcodeFilesParams().Any() - || IsWSLRequired - || HasAdditionalPInvokeLibraries - || HasNativeCompile - || GenerateAOTProfile - || EnableLogProfiler); - - var emsdkPath = useFullPackager ? ValidateEmscripten() : ""; - - ValidateDotnet(); - LinkerSetup(); - - var runtimeConfigurationParam = $"--runtime-config={RuntimeConfiguration.ToLowerInvariant()}" - + (EnableThreads ? "-threads" : "") + " " - + (EnableSimd ? "-simd" : "") + " " - + (EnableJiterpreter ? "-jiterpreter" : "") + " " - + (PrintAOTSkippedMethods ? "-print-skipped-aot-methods" : "") + " " - + (string.IsNullOrWhiteSpace(RuntimeOptions) ? "" : $"--runtime-options \"{RuntimeOptions}\" ") - - // Disable icalls generation on macOS, as it's using the cross-compiler that is not available - + (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "--no-link-icalls" : ""); - - if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && IsRuntimeAOT()) - { - throw new Exception("Building with AOT is not supported on macOS"); - } - - var pthreadPoolSizeParam = $"--pthread-pool-size={PThreadsPoolSize}"; - - var enableICUParam = EnableNetCoreICU ? "--icu" : ""; - var monovmparams = $"--framework=net5 --runtimepack-dir=\"{AlignPath(MonoWasmSDKPath)}\" {enableICUParam} {pthreadPoolSizeParam} --illinker-path=\"{_linkerBinPath}\""; - var pass1ResponseContent = $"{runtimeConfigurationParam} {appDirParm} {monovmparams} --zlib {debugOption} {referenceAssembliesParameter} {referencePathsParameter} \"{AlignPath(TryConvertLongPath(Path.GetFullPath(Assembly)))}\""; - - var packagerPass1ResponseFile = Path.Combine(workAotPath, "packager-pass1.rsp"); - File.WriteAllText(packagerPass1ResponseFile, pass1ResponseContent); - - Log.LogMessage(MessageImportance.Low, $"Response file: {pass1ResponseContent}"); - - // - // Run the packager to create the original layout. The AOT will optionally run over this pass. - // - var packagerResults = RunProcess(packagerBinPath, $"\"@{AlignPath(packagerPass1ResponseFile)}\"", _workDistPath); - - if (packagerResults.exitCode != 0) - { - throw new Exception("Failed to generate wasm layout (More details are available in diagnostics mode or using the MSBuild /bl switch)"); - } - - if (useFullPackager) - { - var extraEmccFlags = (ExtraEmccFlags?.Select(f => f.ItemSpec) ?? new string[0]).ToList(); - var extraLinkerFlags = GetLinkerFeatureConfiguration(); - - var packagerParams = new List(); - - var mixedModeExcluded = MixedModeExcludedAssembly - ?.Select(a => a.ItemSpec) - .ToArray() ?? Array.Empty(); - - var useAotProfile = !GenerateAOTProfile && UseAotProfile; - var aotProfileFilePath = TransformAOTProfile(); - - var mixedModeAotAssembliesParam = mixedModeExcluded.Any() && !useAotProfile ? "--skip-aot-assemblies=" + string.Join(",", mixedModeExcluded) : ""; - var aotProfile = useAotProfile ? $"\"--aot-profile={AlignPath(aotProfileFilePath!)}\"" : ""; - - var dynamicLibraries = GetDynamicLibrariesParams(); - var dynamicLibraryParams = dynamicLibraries.Any() ? "--pinvoke-libs=" + string.Join(",", dynamicLibraries) : ""; - - var bitcodeFiles = GetBitcodeFilesParams(); - var bitcodeFilesParams = dynamicLibraries.Any() ? string.Join(" ", bitcodeFiles.Select(f => $"\"--native-lib={AlignPath(f)}\"")) : ""; - - var additionalNativeCompile = HasNativeCompile - ? string.Join(" ", NativeCompile.Select(f => $"\"--native-compile={AlignPath(GetFilePaths(f).fullPath)}\"")) - : ""; - - var emccExportedRuntimeMethodsParams = - string.Join(" ", GetEmccExportedRuntimeMethods().Select(f => $"\"--emcc-exported-runtime-method={f}\"")); - - if (_runtimeExecutionMode != RuntimeExecutionMode.Interpreter && GenerateAOTProfile) - { - Log.LogMessage($"Forcing Interpreter mode because GenerateAOTProfile is set"); - _runtimeExecutionMode = RuntimeExecutionMode.Interpreter; - } - - var aotMode = _runtimeExecutionMode switch - { - RuntimeExecutionMode.FullAOT => throw new NotSupportedException("FullAOT mode is not supported by this version of the .NET Runtime"), // "--aot", - RuntimeExecutionMode.InterpreterAndAOT => $"--aot-interp {mixedModeAotAssembliesParam}", - RuntimeExecutionMode.Interpreter => "", - _ => throw new NotSupportedException($"Mode {_runtimeExecutionMode} is not supported"), - }; - - var dedupOption = !EnableAOTDeduplication ? "--no-dedup" : ""; - - var aotOptions = $"{aotMode} {dedupOption} {dynamicLibraryParams} {bitcodeFilesParams} {additionalNativeCompile} {emccExportedRuntimeMethodsParams} --emscripten-sdkdir=\"{emsdkPath}\" --builddir=\"{AlignPath(workAotPath)}\""; - - if (EnableEmccProfiling) - { - extraEmccFlags.Add("--profiling"); - } - - packagerParams.Add("--wasm-exceptions"); - - if (GenerateAOTProfile) - { - var aotProfilerSupport = Path.Combine(BuildTaskBasePath, "..", "tools", "support", "Uno.Wasm.AotProfiler.dll"); - referencePathsParameter += $" \"{AlignPath(aotProfilerSupport)}\""; - } - - if(string.IsNullOrEmpty(AotCompilerOptions) && EnableAotGSharedVT) - { - AotCompilerOptions = $"-O=gsharedvt"; - } - - if (EnableLogProfiler) - { - var logProfilerSupport = Path.Combine(BuildTaskBasePath, "..", "tools", "support", "Uno.Wasm.LogProfiler.dll"); - referencePathsParameter += $" \"{AlignPath(logProfilerSupport)}\""; - } - - var extraEmccFlagsPararm = string.Join(" ", extraEmccFlags).Replace("\\", "\\\\"); - - // Handle the `net8.0-browserwasm` case. The target framework is only - // used to generate the temporary aot classes, so the base TF is enough. - var baseTargetFramework = GetBaseTargetFramework(); - - packagerParams.Add(appDirParm); - packagerParams.Add(debugOption); - packagerParams.Add(monovmparams); - packagerParams.Add("--zlib"); - packagerParams.Add($"--illinker-path=\"{_linkerBinPath}\""); - packagerParams.Add($"--target-framework=\"{baseTargetFramework}\""); - packagerParams.Add("--enable-fs "); - packagerParams.Add($"--extra-emccflags=\"{extraEmccFlagsPararm} -l idbfs.js\" "); - packagerParams.Add($"--extra-linkerflags=\"{extraLinkerFlags}\""); - packagerParams.Add(runtimeConfigurationParam); - packagerParams.Add(aotOptions); - packagerParams.Add(aotProfile); - packagerParams.Add($"--aot-compiler-opts=\"{AotCompilerOptions}\""); - packagerParams.Add(EmccLinkOptimization ? "--emcc-link-optimization" : ""); - packagerParams.Add(MonoILLinker ? "--linker --link-mode=all" : ""); - packagerParams.Add(referencePathsParameter); - packagerParams.Add(referenceAssembliesParameter); - packagerParams.Add(GenerateAOTProfile ? "--profile=aot" : ""); - packagerParams.Add(EnableLogProfiler ? "--profile=log" : ""); - packagerParams.Add(!string.IsNullOrEmpty(WasmTunerBinPath) ? $"\"--wasm-tuner-path={AlignPath(Path.GetFullPath(WasmTunerBinPath))}\"" : ""); - packagerParams.Add($"\"--linker-optimization-level={GetEmccLinkerOptimizationLevel()}\""); - packagerParams.Add($"\"{AlignPath(Path.GetFullPath(Assembly))}\""); - - if (InvariantGlobalization) - { - packagerParams.Add("--invariant-globalization"); - } - - var packagerResponseFile = Path.Combine(workAotPath, "packager.rsp"); - File.WriteAllLines(packagerResponseFile, packagerParams.Select(p => p.Replace("\\", "/"))); - - Log.LogMessage(MessageImportance.Low, $"Response file: {File.ReadAllText(packagerResponseFile)}"); - - var aotPackagerResult = RunProcess(packagerBinPath, $"@\"{AlignPath(packagerResponseFile)}\"", _workDistPath); - - if (aotPackagerResult.exitCode != 0) - { - throw new Exception("Failed to generate wasm layout (More details are available in diagnostics mode or using the MSBuild /bl switch)"); - } - - var ninjaPath = Path.Combine(MonoWasmSDKPath, "tools", "ninja.exe"); - - var environmentVariables = default((string, string)[]); - if (GenerateAOTProfile) - { - // https://github.com/dotnet/runtime/blob/21f07e17b0874a898c660afc07261c70a2cb867d/src/mono/wasm/build/WasmApp.Native.targets#L278 - environmentVariables = new[] { ("ENABLE_AOT_PROFILER", "1"), ("ENABLE_BROWSER_PROFILER", "1") }; - } - - var ninjaResult = EnableEmscriptenWindows - ? RunProcess("cmd", $"/c call \"{emsdkPath}\\emsdk_env.bat\" 2>&1 && {ninjaPath} {NinjaAdditionalParameters} -v", workAotPath, environmentVariables) - : RunProcess("ninja", $"{NinjaAdditionalParameters} -v", workAotPath, environmentVariables); - - if (ninjaResult.exitCode != 0) - { - throw new Exception("Failed to run emscripten. More details are available in diagnostics logging mode or using the MSBuild /bl switch, see https://aka.platform.uno/msbuild-troubleshoot."); - } - - CleanupLinkerRemovedFiles(workAotPath); - } - else - { - if (ForceDisableWSL) - { - Log.LogWarning( - "WARNING: WebAssembly emscripten packaging has been explicitly disabled through" + - " WasmShellForceDisableWSL, the resulting compilation may not run properly."); - } - - // - // Run the IL Linker on the interpreter based output, as the packager does not yet do it. - // - if ( - MonoILLinker - ) - { - var linkerInput = Path.Combine(IntermediateOutputPath, "linker-in"); - var linkerResponse = Path.Combine(linkerInput, "linker.rsp"); - var linkerParams = new List(); - - if (Directory.Exists(linkerInput)) - { - DirectoryDelete(linkerInput); - } - - Directory.Move(_managedPath, linkerInput); - DirectoryCreateDirectory(_managedPath); - - var assemblyPath = Path.Combine(linkerInput, Path.GetFileName(Assembly)); - - // Use explicit assemby references first - var referenceAssemblyPaths = _referencedAssemblies.Distinct().Select(p => $"-reference \"{p}\" "); - linkerParams.AddRange(referenceAssemblyPaths); - - // Then search for other known paths - var linkerSearchPaths = _referencedAssemblies.Select(Path.GetDirectoryName).Distinct().Select(p => $"-d \"{p}\" "); - linkerParams.AddRange(linkerSearchPaths); - linkerParams.Add($"-d \"{_bclPath}\""); - - var frameworkBindings = new List - { - }; - - var bindingsPath = frameworkBindings.Select(a => $"-a \"{Path.Combine(linkerInput, a)}\""); - linkerParams.AddRange(bindingsPath); - - if (RuntimeDebuggerEnabled) - { - linkerParams.Add($" -a \"{metadataUpdaterPath}\""); - } - - // Opts should be aligned with the monolinker call in packager.cs, validate for linker_args as well - linkerParams.Add($"--deterministic --disable-opt unreachablebodies "); - - // disabled to align with the .NET SDK default behavior (https://github.com/dotnet/runtime/issues/90745) - // linkerParams.Add($"--used-attrs-only true "); - - // Metadata linking https://github.com/mono/linker/commit/fafb6cf6a385a8c753faa174b9ab7c3600a9d494 - linkerParams.Add("--keep-metadata all "); - - linkerParams.Add(GetLinkerFeatureConfiguration()); - linkerParams.Add($"--verbose -b true -a \"{assemblyPath}\" entrypoint -d \"{_managedPath}\""); - linkerParams.Add($"-out \"{_managedPath}\""); - - File.WriteAllLines(linkerResponse, linkerParams); - - Log.LogMessage(MessageImportance.Low, $"Response file: {File.ReadAllText(linkerResponse)}"); - - var linkerResults = RunProcess( - Path.Combine(_linkerBinPath, "illink.dll"), - $"\"@{linkerResponse}\"", - _managedPath - ); - - if (linkerResults.exitCode != 0) - { - throw new Exception("Failed to execute the linker"); - } - - // - // The linker removes files after the mono-config.json file has been - // generated by the packager. Synchronize the list with the actual list. - // - var deletedFiles = Directory - .GetFiles(linkerInput, "*.*", SearchOption.AllDirectories) - .Select(Path.GetFileName) - .Except(Directory - .GetFiles(_managedPath, "*.*", SearchOption.AllDirectories) - .Select(Path.GetFileName) - ); - - AdjustMonoConfigJson(deletedFiles); - } - } - } - - private string GetBaseTargetFramework() - { - var platformIndex = TargetFramework.IndexOf("-"); - var baseTargetFramework = platformIndex > -1 - ? TargetFramework.Substring(0, platformIndex) - : TargetFramework; - - return baseTargetFramework; - } - - private void CleanupLinkerRemovedFiles(string workAotPath) - { - // Debugger.Launch(); - - var linkerOut = Path.Combine(workAotPath, "linker-out"); - - if (MonoILLinker) - { - // - // Additional assemblies are created as part of the packager processing - // remove those files so they're not part of the final payload. - // - var temporaryFilesToDelete = Directory - .GetFiles(linkerOut, "*.aot-only") - .SelectMany(f => new[] { - Path.ChangeExtension(Path.GetFileName(f), ".dll"), - Path.ChangeExtension(Path.GetFileName(f), ".pdb") - }) - .ToList(); - - AdjustMonoConfigJson(temporaryFilesToDelete); - - temporaryFilesToDelete.ForEach(f => File.Delete(Path.Combine(_workDistPath, "managed", f))); - } - } - - private void AdjustMonoConfigJson(IEnumerable deletedFiles) - { - var monoConfigFilePath = Path.Combine(_workDistPath, "mono-config.json"); - - if (JsonConvert.DeserializeObject(File.ReadAllText(monoConfigFilePath)) is JObject monoConfig) - { - if (monoConfig["assets"] is JArray assetsArray) - { - // Cleanup the assets list for deleted files - var assetsDoDelete = assetsArray - .Where(asset => deletedFiles.Contains(asset["virtualPath"]?.Value())) - .ToList(); - - assetsDoDelete.ForEach(a => assetsArray.Remove(a)); - - foreach (var asset in assetsArray) - { - var originalUrl = asset["name"]?.Value(); - - if (originalUrl is not null) - { - if (originalUrl.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) - { - var newUrl = originalUrl.Substring(0, originalUrl.Length - "dll".Length - 1) + AssembliesFileExtension; - - if (_assembliesFileNameObfuscationMode == FileNameObfuscationMode.NoDots) - { - var lastSlashIndex = newUrl.LastIndexOf('/'); - newUrl = newUrl.Substring(0, lastSlashIndex + 1) + newUrl.Substring(lastSlashIndex + 1).Replace(".", "_"); - } - - asset["name"] = newUrl; - } - } - } - } - - File.WriteAllText(monoConfigFilePath, JsonConvert.SerializeObject(monoConfig, Formatting.Indented)); - } - } - - private string GetLinkerFeatureConfiguration() - { - if (RuntimeHostConfigurationOption != null) - { - var builder = new StringBuilder(); - - foreach (var featureSetting in RuntimeHostConfigurationOption) - { - var feature = featureSetting.ItemSpec; - var featureValue = featureSetting.GetMetadata("Value"); - if (String.IsNullOrEmpty(featureValue)) - { - throw new ArgumentException("feature settings require \"Value\" metadata"); - } - - builder.Append($"--feature {feature} {featureValue} "); - } - - if ( - ActualTargetFrameworkVersion < new Version("6.0") - && !RuntimeHostConfigurationOption.Any(c => c.ItemSpec == "System.Globalization.Invariant") - ) - { - // When using .NET 5, the System.Globalization.Invariant feature is not - // defined, so we assume that it's enabled. - - builder.Append($"--feature System.Globalization.Invariant false "); - } - - return builder.ToString(); - } - else - { - return ""; - } - } - - private string GetEmccLinkerOptimizationLevel() - { - if (Enum.TryParse(EmccLinkOptimizationLevel, out var level)) - { - return level switch - { - LinkOptimizationLevel.None => "-O0", - LinkOptimizationLevel.Level1 => "-O1", - LinkOptimizationLevel.Level2 => "-O2", - LinkOptimizationLevel.Level3 => "-O3", - LinkOptimizationLevel.Maximum => "-Oz", - _ => throw new ArgumentException("Unknown LinkOptimizationLevel") - }; - } - else - { - return EmccLinkOptimizationLevel ?? "-O3"; - } - } - private void LinkerSetup() - { - var embeddedLinker = Path.Combine(MonoWasmSDKPath, "tools"); - - // Use the embedded linker always when running with WSL, as the local windows binary - // is not compatible with Linux. - var linkerPath = (IsWSLRequired || CustomLinkerPath is null) - ? embeddedLinker - : CustomLinkerPath; - - _linkerBinPath = AlignPath(linkerPath); - } - - private bool IsRuntimeAOT() - => _runtimeExecutionMode == RuntimeExecutionMode.FullAOT || _runtimeExecutionMode == RuntimeExecutionMode.InterpreterAndAOT; - - private string TryConvertLongPath (string path) - => Environment.OSVersion.Platform == PlatformID.Win32NT - && !string.IsNullOrEmpty(path) - && !path.StartsWith(@"\\?\") - && Path.IsPathRooted(path) - && EnableLongPathSupport - && !EnableEmscriptenWindows // ninja does not support "\\?\" normalized paths - && FileInfoExtensions.PlatformRequiresLongPathNormalization - ? @"\\?\" + path - : path; - - private void ValidateDotnet() - { - int GetDotnetMajorVersion() - { - var (exitCode, output, error) = RunProcess("dotnet", "--version"); - if (exitCode != 0) - { - throw new InvalidOperationException($"Unable to read the .NET SDK version"); - } - else - { - if (Regex.Match(output, @"(\d+)\.\d+") is { Success: true, Groups.Count: > 0 } match - && int.TryParse(match.Groups[1].Value, out var majorVersion)) - { - return majorVersion; - } - else - { - throw new InvalidOperationException($"Unable to parse the .NET SDK version (Got {output})"); - } - } - } - - var majorVersion = GetDotnetMajorVersion(); - - if (majorVersion < 6) - { - throw new InvalidOperationException($".NET SDK Version must be 6.0 or greater"); - } - - Log.LogMessage($"Found .NET SDK {majorVersion}"); - } - - private string ValidateEmscripten() - { - if (Environment.OSVersion.Platform == PlatformID.Win32NT) - { - if (EnableEmscriptenWindows) - { - ValidatPowershellExecutionPolicy(); - - var emsdkHostFolder = Environment.GetEnvironmentVariable("WASMSHELL_WSLEMSDK") - ?? Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), ".uno", "emsdk"); - - var emsdkBaseFolder = Path.Combine(emsdkHostFolder, $"emsdk-{CurrentEmscriptenVersion}"); - - var emscriptenSetupScript = Path.Combine(BuildTaskBasePath, "scripts", "emscripten-setup.cmd"); - - var result = RunProcess( - emscriptenSetupScript, - $"\"{emsdkHostFolder.Replace("\\\\?\\", "").TrimEnd('\\')}\" {CurrentEmscriptenVersion}"); - - if (result.exitCode == 0) - { - return Path.Combine(emsdkBaseFolder, "emsdk"); - } - - throw new InvalidOperationException($"Failed to setup emscripten environment."); - } - else - { - var homePath = GetWSLHomePath(); + private static readonly string _wwwroot = "wwwroot" + Path.DirectorySeparatorChar; - var emsdkHostFolder = Environment.GetEnvironmentVariable("WASMSHELL_WSLEMSDK") ?? $"{homePath}/.uno/emsdk"; - var emsdkBaseFolder = emsdkHostFolder + $"/emsdk-{CurrentEmscriptenVersion}"; - - var emscriptenSetupScript = Path.Combine(BuildTaskBasePath, "scripts", "emscripten-setup.sh"); - - // Adjust line endings - AdjustFileLineEndings(emscriptenSetupScript); - - var result = RunProcess( - emscriptenSetupScript, - $"\"{emsdkHostFolder.Replace("\\\\?\\", "").TrimEnd('\\')}\" {CurrentEmscriptenVersion}"); - - if (result.exitCode == 0) - { - return emsdkBaseFolder + $"/emsdk"; - } - - var dotnetSetupScript = Path.Combine(BuildTaskBasePath, "scripts", "dotnet-setup.sh"); - AdjustFileLineEndings(dotnetSetupScript); - - Log.LogError( - $"The Windows Subsystem for Linux dotnet environment may not be properly setup, and you may need to run " + - $"the environment setup script. Open an Ubuntu WSL shell and run:\n\nbash -c `wslpath \"{dotnetSetupScript}\"`\n\n"); - - throw new InvalidOperationException($"Failed to setup WSL environment."); - } - } - else if (Environment.OSVersion.Platform == PlatformID.Unix) - { - var home = Environment.GetEnvironmentVariable("HOME"); - var emsdkHostFolder = Environment.GetEnvironmentVariable("WASMSHELL_WSLEMSDK") ?? $"{home}/.uno/emsdk"; - var emscriptenSetupScript = Path.Combine(BuildTaskBasePath, "scripts", "emscripten-setup.sh"); - var emsdkBaseFolder = emsdkHostFolder + $"/emsdk-{CurrentEmscriptenVersion}"; + private ShellMode _shellMode; + private UTF8Encoding _utf8Encoding = new UTF8Encoding(false); + private readonly List _dependencies = new List(); + private List? _resourceSearchList; + private List _referencedAssemblies = new List(); + private string[]? _additionalStyles; + private string _intermediateAssetsPath = ""; + private string[]? _contentExtensionsToExclude; + private RuntimeExecutionMode _runtimeExecutionMode; - // Adjust line endings - AdjustFileLineEndings(emscriptenSetupScript); + [Required] + public string AssemblyName { get; private set; } = ""; - var result = RunProcess( - "bash", - $"-c \"chmod +x \"{emscriptenSetupScript}\"; \"{emscriptenSetupScript}\" \\\"{emsdkHostFolder}\\\" {CurrentEmscriptenVersion}\""); + [Required] + public string IndexHtmlPath { get; set; } = ""; - if (result.exitCode == 0) - { - return emsdkBaseFolder + $"/emsdk"; - } + [Required] + public string Assembly { get; set; } = ""; - throw new NotSupportedException($"Failed to install emscripten"); - } - else - { - throw new NotSupportedException($"Unsupported platform"); - } - } + [Required] + public string CurrentProjectPath { get; set; } = ""; - private (int exitCode, string output, string error) ValidatPowershellExecutionPolicy() - { - var result = RunProcess( - "powershell", - "Get-ExecutionPolicy", - environmentVariables: new[] { - // Workaround for https://github.com/PowerShell/PowerShell/issues/18530#issuecomment-1325691850 - ("PSModulePath", "") - }); + public ITaskItem[]? Assets { get; set; } - if (result.exitCode != 0) - { - throw new Exception($"Failed to determine the powershell execution policy."); - } + [Required] + public string WasmShellMode { get; set; } = ""; - // https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-7.2 - if (!result.output.Equals("unrestricted", StringComparison.OrdinalIgnoreCase) - && !result.output.Equals("remotesigned", StringComparison.OrdinalIgnoreCase) - && !result.output.Equals("bypass", StringComparison.OrdinalIgnoreCase) - && !SkipPowershellExecutionPolicyValidation) - { - throw new InvalidOperationException($"The current PowerShell Execution policy is [{result.output}]. For more information see https://aka.platform.uno/bootstrapper-powershell"); - } - return result; - } + public ITaskItem[] EmbeddedResources { get; set; } = []; - private object GetWSLHomePath() - { - var p = RunProcess(GetWSLBashExecutable(), "-c \"echo $HOME\""); + [Required] + public string IntermediateOutputPath { get; set; } = ""; + public ITaskItem[]? MonoEnvironment { get; set; } - if(p.exitCode != 0) - { - throw new InvalidOperationException($"Failed to read WSL $HOME path"); - } + public string? PWAManifestFile { get; set; } - return p.output; - } + public string EmscriptenVersion { get; set; } = ""; - private static void AdjustFileLineEndings(string emscriptenSetupScript) - => File.WriteAllText(emscriptenSetupScript, File.ReadAllText(emscriptenSetupScript).Replace("\r\n", "\n")); + public ITaskItem[]? EmccFlags { get; set; } - private IEnumerable GetDynamicLibrariesParams() - { - foreach(var file in GetBitcodeFilesParams().Select(Path.GetFileNameWithoutExtension)) - { - yield return file; - } + public ITaskItem[]? EmccExportedRuntimeMethod { get; set; } - // For now, use this until __Internal is properly supported: - // https://github.com/dotnet/runtime/blob/dbe6447aa29b14150b7c6dd43072cc75f0cdf013/src/mono/mono/metadata/native-library.c#L781 - yield return "__Native"; + public string? ContentExtensionsToExclude { get; set; } - if (AdditionalPInvokeLibraries != null) - { - foreach (var pInvokeLibrary in AdditionalPInvokeLibraries) - { - yield return pInvokeLibrary.ItemSpec; - } + public string CSPConfiguration { get; set; } = ""; - // In the case of libc, the resolution differs when running - // with or without AOT being enabled, so we add both entries. - // https://github.dev/dotnet/runtime/blob/58f5c95085b2eb56800b87f466183b1448d33b3d/src/mono/mono/utils/mono-dl.c#L158 - var containsLibc = AdditionalPInvokeLibraries.Any(i => i.ItemSpec == "libc"); - var containsLibcSo = AdditionalPInvokeLibraries.Any(i => i.ItemSpec == "libc.so"); + public bool Optimize { get; set; } - if (containsLibc && !containsLibcSo) - { - yield return "libc.so"; - } + public bool EnableTracing { get; set; } - if(containsLibcSo && !containsLibc) - { - yield return "libc"; - } - } - } + public bool LoadAllSatelliteResources { get; set; } - private IEnumerable GetEmccExportedRuntimeMethods() - => (EmccExportedRuntimeMethods ?? Array.Empty()).Select(m => m.ItemSpec); + public string AotProfile { get; set; } = ""; - private IEnumerable GetBitcodeFilesParams() - { - if (_bitcodeFilesCache == null) - { - _bitcodeFilesCache = Assets - ?.Where(a => a.ItemSpec.EndsWith(".bc") || a.ItemSpec.EndsWith(".a")) - .Where(a => !bool.TryParse(a.GetMetadata("UnoAotCompile"), out var compile) || compile) - .Select(a => GetFilePaths(a).fullPath) - .ToArray() - ?? new string[0]; - - List features = new() - { - EnableThreads ? "mt" : "st" - }; + public bool RunAOTCompilation { get; set; } - if (EnableSimd) - { - features.Add("simd"); - } + public string? RuntimeOptions { get; set; } - Log.LogMessage(MessageImportance.Low, $"Bitcode files features lookup filter: {string.Join(",", features)}"); + public string AOTProfileExcludedMethods { get; set; } = ""; - _bitcodeFilesCache = BitcodeFilesSelector.Filter(CurrentEmscriptenVersion, features.ToArray(), _bitcodeFilesCache); - } + public bool GenerateAOTProfileDebugList { get; set; } = false; - return _bitcodeFilesCache; - } + public Microsoft.Build.Framework.ITaskItem[]? MixedModeExcludedAssembly { get; set; } - private void ParseProperties() - { - ParseEnumProperty(nameof(WasmShellMode), WasmShellMode, out _shellMode); - ParseEnumProperty(nameof(MonoRuntimeExecutionMode), MonoRuntimeExecutionMode, out _runtimeExecutionMode); - ParseEnumProperty(nameof(AssembliesFileNameObfuscationMode), AssembliesFileNameObfuscationMode, out _assembliesFileNameObfuscationMode); - AotProfile ??= new ITaskItem[0]; - _contentExtensionsToExclude = - ContentExtensionsToExclude - ?.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries) - ?? new string[0]; + public bool WasmBuildNative { get; set; } - Log.LogMessage($"Ignoring content files with following extensions:\n\t{string.Join("\n\t", _contentExtensionsToExclude)}"); + public bool PublishTrimmed { get; set; } - if (!WebAppBasePath.EndsWith("/")) - { - throw new InvalidOperationException($"The WasmShellWebAppBasePath property must end with a trailing \"/\" (got [{WebAppBasePath}] instead)"); - } + public bool RunILLink { get; set; } - if (!AssembliesFileExtension.StartsWith(".")) - { - throw new InvalidOperationException($"The WasmShellAssembliesFileExtension property must start with a '.'"); - } + public bool EnableLogProfiler { get; set; } - if(GenerateAOTProfile && MonoILLinker) - { - // Unknown failure based on the use of the AOT profiler and the linker. - // See https://github.com/unoplatform/Uno.Wasm.Bootstrap/issues/724 - // - // EXCEPTION handling: System.InvalidProgramException: - // "" tid=0x1 this=0xa690420 , thread handle : 0x1c032f8, state : not waiting - // at <0xffffffff> - // at Interop/Sys..cctor () [0x00000] in :0 - // at (wrapper runtime-invoke) object.runtime_invoke_direct_void (object,intptr,intptr,intptr) [0x0002d] in :0 - // at <0x00000> - // at <0xffffffff> - // at System.Threading.Thread.GetCurrentProcessorNumber () [0x00000] in :0 - // at System.Threading.ProcessorIdCache.ProcessorNumberSpeedCheck () [0x0001a] in :0 - // at System.Threading.Thread..cctor () [0x00000] in :0 - // at (wrapper runtime-invoke) object.runtime_invoke_direct_void (object,intptr,intptr,intptr) [0x0002d] in : - // at <0x00000> - // at <0xffffffff> - // at System.Threading.ObjectHeader.TryEnterFast (object) [0x00023] in :0 - // at System.Threading.Monitor.ReliableEnterTimeout (object,int,bool&) [0x00021] in :0 - // - throw new InvalidOperationException($"Generating an AOT profile is not supported when the linker is enabled"); - } - } + public string LogProfilerOptions { get; set; } = "log:alloc,output=output.mlpd"; - private void BuildReferencedAssembliesList() - { - if (ReferencePath != null) - { - _bclAssemblies = _bclAssemblies ?? throw new Exception("_bclAssemblies is not yet defined"); + public string WebAppBasePath { get; set; } = "./"; - var runtimeCopyExclusions = RuntimeCopyExclude - ?.Select(e => e.ItemSpec.ToLowerInvariant()) - .ToArray() - ?? Array.Empty(); + public bool GenerateAOTProfile { get; set; } - foreach (var referencePath in ReferencePath) - { - var isReferenceAssembly = referencePath.GetMetadata("PathInPackage")?.StartsWith("ref/", StringComparison.OrdinalIgnoreCase) ?? false; - var hasConcreteAssembly = isReferenceAssembly && ReferencePath.Any(innerReference => HasConcreteAssemblyForReferenceAssembly(innerReference, referencePath)); + public bool EnableThreads { get; set; } - if (isReferenceAssembly && hasConcreteAssembly) - { - // Reference assemblies may be present along with the actual assemblies. - // Filter out those assemblies as they cannot be used at runtime. - continue; - } + public ITaskItem[]? ReferencePath { get; set; } - var name = Path.GetFileName(referencePath.ItemSpec); - if ( - _bclAssemblies.ContainsKey(name) + [Output] + public ITaskItem[]? StaticWebContent { get; set; } = []; - // Potential manual exclusions for packages provided explicitly - // by the user (e.g. System.Text.Json) which is also included in the runtime. - && !runtimeCopyExclusions.Contains(name) - ) - { - _referencedAssemblies.Add(_bclAssemblies[name]); - } - else - { - _referencedAssemblies.Add(referencePath.ItemSpec); - } - } - } - } + [Output] + public ITaskItem[]? NativeFileReference { get; set; } = []; - private static bool HasConcreteAssemblyForReferenceAssembly(ITaskItem other, ITaskItem referenceAssembly) - => Path.GetFileName(other.ItemSpec) == Path.GetFileName(referenceAssembly.ItemSpec) && (other.GetMetadata("PathInPackage")?.StartsWith("lib/", StringComparison.OrdinalIgnoreCase) ?? false); + [Output] + public string? FilteredAotProfile { get; set; } = ""; - private void PrepareFinalDist() + public override bool Execute() { - IEnumerable ComputeHash(string file) - { - using var hashFunction = SHA1.Create(); - using var s = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); - return hashFunction.ComputeHash(s); - } - - var allBytes = Directory.GetFiles(_workDistPath, "*.*", SearchOption.AllDirectories) - .AsParallel() - .OrderBy(s => s) - .Select(ComputeHash) - .SelectMany(h => h) - .ToArray(); - - using var hashFunction = SHA1.Create(); - var hash = string.Join("", hashFunction.ComputeHash(allBytes).Select(b => b.ToString("x2"))); - - OutputDistPath = _distPath; - - if (_shellMode == ShellMode.Node) - { - _remoteBasePackagePath = "app"; - _finalPackagePath = _distPath; - OutputPackagePath = _distPath; - } - else - { - _remoteBasePackagePath = $"package_{hash}"; - _finalPackagePath = TryConvertLongPath(Path.Combine(_distPath, _remoteBasePackagePath)); - OutputPackagePath = _finalPackagePath.Replace(@"\\?\", ""); - } - - // Move ICU files to the managed folder to avoid multiple lookups in start_asset_download_sources - // implied by having multiple sources (https://github.com/dotnet/runtime/blob/ae0f0d8fec21eb69088c970ad58af75cca429651/src/mono/wasm/runtime/loader/assets.ts#L513) - // move all *.icu files from ditFolder to _managedPath - var icuFiles = Directory.GetFiles(_workDistPath, "icudt*.dat"); - foreach (var icuFile in icuFiles) - { - var icuFileName = Path.GetFileName(icuFile); - var icuFileDestination = Path.Combine(_managedPath, icuFileName); - File.Move(icuFile, icuFileDestination); - } - - // Create the path if it does not exist (particularly if the path is - // not in a set of folder that exists) - Directory.CreateDirectory(_finalPackagePath); - - if (Directory.Exists(_distPath)) - { - DirectoryDelete(_distPath); - } - - try - { - Directory.Move(_workDistRootPath, _distPath); - } - catch (Exception ex) - { - throw new ApplicationException($"Unable to move ROOT DIST {_workDistRootPath} to {_distPath}: {ex}", ex); - } + IntermediateOutputPath = TryConvertLongPath(IntermediateOutputPath); + _intermediateAssetsPath = Path.Combine(IntermediateOutputPath, "unowwwrootassets"); + Directory.CreateDirectory(_intermediateAssetsPath); try { - if (!_workDistRootPath.Equals(_workDistPath)) - { - Directory.Move(_workDistPath, _finalPackagePath); - } - } - catch (Exception ex) - { - throw new ApplicationException($"Unable to move PACKAGE DIST {_workDistPath} to {_finalPackagePath}: {ex}", ex); + ParseProperties(); + BuildReferencedAssembliesList(); + CopyContent(); + GenerateBitcodeFiles(); + ExtractAdditionalJS(); + ExtractAdditionalCSS(); + GeneratedAOTProfile(); + GenerateIndexHtml(); + GenerateEmbeddedJs(); + GenerateConfig(); } - - TryObfuscateAssemblies(Path.Combine(_finalPackagePath, Path.GetFileName(_managedPath))); - } - - private void DirectoryDelete(string path) - => PathHelper.DeleteDirectory(path); - - private static void MoveFileSafe(string source, string target) - { - if (File.Exists(source) && source != target) + finally { - if (File.Exists(target)) - { - File.Delete(target); - } - - File.Move(source, target); + Cleanup(); } - } - - /// - /// Renames the files to avoid quarantine by antivirus software such as Symantec, - /// which are quite present in the enterprise space. - /// - /// The extension to rename - private void TryObfuscateAssemblies(string path) - { - foreach (var dllFile in Directory.GetFiles(path, "*.dll", SearchOption.AllDirectories)) - { - var destFileName = Path.GetFileNameWithoutExtension(dllFile) + AssembliesFileExtension; - - if(_assembliesFileNameObfuscationMode == FileNameObfuscationMode.NoDots) - { - destFileName = destFileName.Replace(".", "_"); - } - var destDirName = Path.Combine(Path.GetDirectoryName(dllFile), destFileName); - - Log.LogMessage($"Renaming {dllFile} to {destDirName}"); - Directory.Move(dllFile, destDirName); - - if (ObfuscateAssemblies) - { - Log.LogMessage($"Obfuscating {destDirName}"); - ObfuscateAssembly(destDirName); - } - } + return true; } - private void ObfuscateAssembly(string file) + private void GeneratedAOTProfile() { - var data = File.ReadAllBytes(file); + var useAotProfile = !GenerateAOTProfile && UseAotProfile; - for (var i = 0; i < data.Length; i++) + if (useAotProfile) { - data[i] ^= _obfuscationKey[i % _obfuscationKey.Length]; + // If the profile was transformed, we need to use the transformed profile + FilteredAotProfile = TransformAOTProfile(); } - - File.WriteAllBytes(file, data); } - private void GetBcl() + private void ParseProperties() { - _bclPath = Path.Combine(MonoWasmSDKPath, "runtimes", "browser-wasm", "lib"); - - var subDirectories = Directory.GetDirectories(_bclPath); - if(subDirectories.Length != 1) - { - throw new InvalidDataException("The lib directory structure must have exactly one target framework"); - } - - _bclPath = Path.Combine(_bclPath, subDirectories.First()); - - var reals = Directory.GetFiles(_bclPath, "*.dll", SearchOption.AllDirectories); - _bclAssemblies = reals.ToDictionary(x => Path.GetFileName(x)); - } + ParseEnumProperty(nameof(WasmShellMode), WasmShellMode, out _shellMode); - private void CreateDist() - { - _distPath = TryConvertLongPath(Path.GetFullPath(DistPath)); - _workDistPath = TryConvertLongPath(Path.Combine(IntermediateOutputPath, "dist_work")); - _workDistRootPath = - _shellMode == ShellMode.Node - ? _workDistPath - : TryConvertLongPath(Path.Combine(IntermediateOutputPath, "dist_root_work")); - _managedPath = Path.Combine(_workDistPath, "managed"); - - if (Directory.Exists(_workDistPath)) - { - DirectoryDelete(_workDistPath); - } + _runtimeExecutionMode + = WasmBuildNative && RunAOTCompilation ? RuntimeExecutionMode.InterpreterAndAOT : RuntimeExecutionMode.Interpreter; - if (Directory.Exists(_workDistRootPath)) - { - DirectoryDelete(_workDistRootPath); - } + _contentExtensionsToExclude = + ContentExtensionsToExclude + ?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) + ?? []; - Log.LogMessage($"Creating managed path {_managedPath}"); - DirectoryCreateDirectory(_managedPath); + Log.LogMessage($"Ignoring content files with following extensions:\n\t{string.Join("\n\t", _contentExtensionsToExclude)}"); } - private void CopyRuntime() + private void Cleanup() { - DirectoryCreateDirectory(_workDistRootPath); - - var runtimePath = Path.Combine(MonoWasmSDKPath, "runtimes", "browser-wasm", "native"); - - foreach (var sourceFile in Directory.EnumerateFiles(runtimePath)) + if (_resourceSearchList is not null) { - var dest = Path.Combine(_workDistPath, Path.GetFileName(sourceFile)); - Log.LogMessage($"Runtime: {sourceFile} -> {dest}"); - FileCopy(sourceFile, dest, true); + foreach (var res in _resourceSearchList) + { + res.Dispose(); + } } } @@ -1756,7 +212,14 @@ private void CopyRuntime() // This is for project-local defined content var baseSourceFile = item.GetMetadata("DefiningProjectDirectory"); - if (item.GetMetadata("Link") is { } link && !string.IsNullOrEmpty(link)) + if (item.GetMetadata("TargetPath") is { } targetPath && !string.IsNullOrEmpty(targetPath)) + { + var fullPath = Path.IsPathRooted(item.ItemSpec) ? item.ItemSpec : Path.Combine(baseSourceFile, item.ItemSpec); + + // This is used for item remapping + return (fullPath, targetPath); + } + else if (item.GetMetadata("Link") is { } link && !string.IsNullOrEmpty(link)) { var fullPath = Path.IsPathRooted(item.ItemSpec) ? item.ItemSpec : Path.Combine(baseSourceFile, item.ItemSpec); @@ -1791,11 +254,10 @@ private void CopyContent() { foreach (var sourceFile in Assets) { - var (fullSourcePath, relativePath) = GetFilePaths(sourceFile); // Files in "wwwroot" folder will get deployed to root by default - var defaultDeployMode = relativePath.Contains(_wwwwroot) ? DeployMode.Root : DeployMode.Package; + var defaultDeployMode = relativePath.Contains(_wwwroot) ? DeployMode.None : DeployMode.Package; var deployModeSource = "Default"; var matchedExtension = _contentExtensionsToExclude @@ -1806,7 +268,7 @@ private void CopyContent() deployModeSource = "Excluded extension"; } - relativePath = PathHelper.FixupPath(relativePath).Replace(_wwwwroot, ""); + relativePath = PathHelper.FixupPath(relativePath).Replace(_wwwroot, ""); if (relativePath.StartsWith(WasmScriptsFolder)) { @@ -1827,74 +289,129 @@ private void CopyContent() deployMode = defaultDeployMode; } - if (deployMode == DeployMode.Package) + var dest = Path.Combine(_intermediateAssetsPath, relativePath); + + if (deployMode != DeployMode.None) { // Add the file to the package assets manifest assets.Add(relativePath.Replace(Path.DirectorySeparatorChar, '/')); + + AddStaticAsset(relativePath, fullSourcePath); } - var dest = deployMode - switch - { - DeployMode.Package => Path.Combine(_workDistPath, relativePath), - DeployMode.Root => Path.Combine(_workDistRootPath, relativePath), - _ => default // None or unknown mode - }; + Log.LogMessage($"ContentFile {fullSourcePath} -> {dest ?? ""} [Mode={deployMode} / by {deployModeSource}, ]"); + } + } + var assetsFilePath = Path.Combine(_intermediateAssetsPath, "uno-assets.txt"); + File.WriteAllLines(assetsFilePath, assets); + AddStaticAsset(Path.GetFileName(assetsFilePath), assetsFilePath); + } - Log.LogMessage($"ContentFile {fullSourcePath} -> {dest ?? ""} [Mode={deployMode} / by {deployModeSource}]"); + private void ExtractAdditionalJS() + { + BuildResourceSearchList(); - if (dest != null) - { - DirectoryCreateDirectory(Path.GetDirectoryName(dest)); + var q = EnumerateResources("js", "WasmDist") + .Concat(EnumerateResources("js", WasmScriptsFolder)); - FileCopy(fullSourcePath, dest, true); - } + foreach (var (name, source, resource) in q) + { + if (source.Name.Name != Path.GetFileNameWithoutExtension(Assembly)) + { + _dependencies.Add(name); + + CopyResourceToOutput(name, resource); + + Log.LogMessage($"Additional JS {name}"); + } + } + + foreach (var projectResource in EmbeddedResources) + { + var (fullSourcePath, relativePath) = GetFilePaths(projectResource); + + if (relativePath.Contains("WasmScripts")) + { + var scriptName = Path.GetFileName(relativePath); + + Log.LogMessage($"Embedded resources JS {scriptName}"); + + _dependencies.Add(scriptName); + AddStaticAsset(scriptName, fullSourcePath); } } - - File.WriteAllLines(Path.Combine(_workDistPath, "uno-assets.txt"), assets); } - private void ExtractAdditionalJS() + private void ExtractAdditionalCSS() { BuildResourceSearchList(); - var q = EnumerateResources("js", "WasmDist") - .Concat(EnumerateResources("js", WasmScriptsFolder)); + var additionalStyles = new List(); - foreach (var (name, source, resource) in q) + foreach (var (name, source, resource) in EnumerateResources("css", "WasmCSS")) { - if (source.Name.Name != GetType().Assembly.GetName().Name) + if (source.Name.Name != Path.GetFileNameWithoutExtension(Assembly)) { - _dependencies.Add(name); + using (var srcs = resource.GetResourceStream()) + { + additionalStyles.Add(name); + + CopyResourceToOutput(name, resource); + + Log.LogMessage($"Additional CSS {name}"); + } } + } + + foreach (var projectResource in EmbeddedResources) + { + var (fullSourcePath, relativePath) = GetFilePaths(projectResource); + + if (relativePath.Contains("WasmCSS")) + { + var cssName = Path.GetFileName(relativePath); - CopyResourceToOutput(name, resource); + Log.LogMessage($"Embedded CSS {cssName}"); - Log.LogMessage($"Additional JS {name}"); + additionalStyles.Add(cssName); + AddStaticAsset(cssName, fullSourcePath); + } } + + _additionalStyles = additionalStyles.ToArray(); } - private void ExtractAdditionalCSS() + private void CopyResourceToOutput(string name, EmbeddedResource resource) { - BuildResourceSearchList(); - - var q = EnumerateResources("css", "WasmCSS"); + var dest = Path.Combine(_intermediateAssetsPath, name); - foreach (var (name, source, resource) in q) + using (var srcs = resource.GetResourceStream()) { - using (var srcs = resource.GetResourceStream()) + using (var dests = new FileStream(dest, FileMode.Create, FileAccess.Write)) { - CopyResourceToOutput(name, resource); - - Log.LogMessage($"Additional CSS {name}"); + srcs.CopyTo(dests); } } - _additionalStyles = q - .Select(res => res.name) - .ToArray(); + AddStaticAsset(name, dest); + } + + private void AddStaticAsset(string targetPath, string filePath) + { + var contentRoot = targetPath.StartsWith(_intermediateAssetsPath) + ? _intermediateAssetsPath + : Path.GetDirectoryName(filePath); + + TaskItem indexMetadata = new( + filePath, new Dictionary + { + ["CopyToOutputDirectory"] = "PreserveNewest", + ["ContentRoot"] = contentRoot, + ["Link"] = "wwwroot/" + targetPath, + }); + + StaticWebContent = StaticWebContent.Concat([indexMetadata]).ToArray(); } private void BuildResourceSearchList() @@ -1933,19 +450,6 @@ select asm } } - private void CopyResourceToOutput(string name, EmbeddedResource resource) - { - var dest = Path.Combine(_workDistPath, name); - - using (var srcs = resource.GetResourceStream()) - { - using (var dests = new FileStream(dest, FileMode.Create, FileAccess.Write)) - { - srcs.CopyTo(dests); - } - } - } - private IEnumerable<(string name, AssemblyDefinition source, EmbeddedResource resource)> EnumerateResources(string extension, string folder) { var fullExtension = "." + extension; @@ -1962,67 +466,71 @@ where res.Name.Contains(fullFolder) ); } - private MethodDefinition DiscoverEntryPoint() + private void BuildReferencedAssembliesList() { - var asm = AssemblyDefinition.ReadAssembly(Assembly); - - if (asm?.EntryPoint is MethodDefinition def) + if (ReferencePath != null) { - return def; + foreach (var referencePath in ReferencePath) + { + _referencedAssemblies.Add(referencePath.ItemSpec); + } } - - throw new Exception($"{Path.GetFileName(Assembly)} is missing an entry point. Add Exe in the project file and a static main."); } + static string BuildDependencyPath(string dep, string baseLookup) + => baseLookup.StartsWith("/") + ? $"\"{baseLookup}{Path.GetFileName(dep)}\"" + : $"\"{baseLookup}{Path.GetFileNameWithoutExtension(dep)}\""; + private void GenerateConfig() { - var unoConfigJsPath = Path.Combine(_finalPackagePath, "uno-config.js"); + var unoConfigJsPath = Path.Combine(_intermediateAssetsPath, "uno-config.js"); using (var w = new StreamWriter(unoConfigJsPath, false, _utf8Encoding)) { - var baseLookup = _shellMode == ShellMode.Node ? "" : $"{WebAppBasePath}{_remoteBasePackagePath}/"; - var dependencies = string.Join(", ", _dependencies.Select(dep => BuildDependencyPath(dep, baseLookup))); - var entryPoint = DiscoverEntryPoint(); + var baseLookup = _shellMode == ShellMode.Node ? "" : $"{WebAppBasePath}"; + var dependencies = string.Join(", ", _dependencies + .Where(d => + !d.EndsWith("require.js") + && !d.EndsWith("uno-bootstrap.js") + && !d.EndsWith("service-worker.js")) + .Select(dep => BuildDependencyPath(dep, baseLookup))); var config = new StringBuilder(); - var (monoWasmFileName, monoWasmSize, totalAssembliesSize, assemblyFiles, filesIntegrity) = GetFilesDetails(); - var assembliesSize = string.Join( - ",", - assemblyFiles.Select(ass => $"\"{ass.fileName}\":{ass.length}")); - var filesIntegrityStr = string.Join( - ",", - filesIntegrity.Select(f => $"\"{f.fileName}\":\"{f.integrity}\"")); - var enablePWA = !string.IsNullOrEmpty(PWAManifestFile); - var offlineFiles = enablePWA ? string.Join(", ", GetPWACacheableFiles().Select(f => $"\".{f}\"")) : ""; + //var offlineFiles = enablePWA ? string.Join(", ", GetPWACacheableFiles().Select(f => $"\".{f}\"")) : ""; var emccExportedRuntimeMethodsParams = string.Join( ",", GetEmccExportedRuntimeMethods().Select(f => $"\'{f}\'")); + var runtimeOptionsSet = string.Join(",", (RuntimeOptions?.Split(' ') ?? []).Select(f => $"\'{f}\'")); + config.AppendLine($"let config = {{}};"); - config.AppendLine($"config.uno_remote_managedpath = \"{ Path.GetFileName(_managedPath) }\";"); - config.AppendLine($"config.uno_app_base = \"{WebAppBasePath}{_remoteBasePackagePath}\";"); + config.AppendLine($"config.uno_remote_managedpath = \"_framework\";"); + + // unoAppBase must not finish with a `/` to be backward + // compatible. + var unoAppBase = WebAppBasePath switch + { + "" => ".", + "./" => ".", + "/" => "/.", + _ => WebAppBasePath.TrimEnd('/') + "/." + }; + + config.AppendLine($"config.uno_app_base = \"{unoAppBase}\";"); config.AppendLine($"config.uno_dependencies = [{dependencies}];"); - config.AppendLine($"config.uno_main = \"{entryPoint.DeclaringType.Module.Assembly.Name.Name}\";"); - config.AppendLine($"config.assemblyFileExtension = \"{AssembliesFileExtension}\";"); - config.AppendLine($"config.assemblyFileNameObfuscationMode = \"{_assembliesFileNameObfuscationMode}\";"); - config.AppendLine($"config.mono_wasm_runtime = \"{monoWasmFileName}\";"); - config.AppendLine($"config.mono_wasm_runtime_size = {monoWasmSize};"); - config.AppendLine($"config.assemblies_with_size = {{{assembliesSize}}};"); - config.AppendLine($"config.files_integrity = {{{filesIntegrityStr}}};"); - config.AppendLine($"config.total_assemblies_size = {totalAssembliesSize};"); + config.AppendLine($"config.uno_runtime_options = [{runtimeOptionsSet}];"); config.AppendLine($"config.enable_pwa = {enablePWA.ToString().ToLowerInvariant()};"); - config.AppendLine($"config.offline_files = ['{WebAppBasePath}', {offlineFiles}];"); + //config.AppendLine($"config.offline_files = ['{WebAppBasePath}', {offlineFiles}];"); config.AppendLine($"config.uno_shell_mode = \"{_shellMode}\";"); + config.AppendLine($"config.uno_debugging_enabled = {(!Optimize).ToString().ToLowerInvariant()};"); + config.AppendLine($"config.uno_enable_tracing = {EnableTracing.ToString().ToLowerInvariant()};"); + config.AppendLine($"config.uno_load_all_satellite_resources = {LoadAllSatelliteResources.ToString().ToLowerInvariant()};"); config.AppendLine($"config.emcc_exported_runtime_methods = [{emccExportedRuntimeMethodsParams}];"); - if (ObfuscateAssemblies) - { - config.AppendLine($"config.assemblyObfuscationKey = \"{Encoding.ASCII.GetString(_obfuscationKey)}\";"); - } - if (GenerateAOTProfile) { config.AppendLine($"config.generate_aot_profile = true;"); @@ -2044,19 +552,14 @@ private void GenerateConfig() AddEnvironmentVariable("UNO_BOOTSTRAP_MONO_RUNTIME_MODE", _runtimeExecutionMode.ToString()); AddEnvironmentVariable("UNO_BOOTSTRAP_MONO_PROFILED_AOT", isProfiledAOT.ToString()); - AddEnvironmentVariable("UNO_BOOTSTRAP_LINKER_ENABLED", MonoILLinker.ToString()); - AddEnvironmentVariable("UNO_BOOTSTRAP_DEBUGGER_ENABLED", RuntimeDebuggerEnabled.ToString()); - AddEnvironmentVariable("UNO_BOOTSTRAP_MONO_RUNTIME_CONFIGURATION", RuntimeConfiguration); + AddEnvironmentVariable("UNO_BOOTSTRAP_LINKER_ENABLED", (PublishTrimmed && RunILLink).ToString()); + AddEnvironmentVariable("UNO_BOOTSTRAP_DEBUGGER_ENABLED", (!Optimize).ToString()); + AddEnvironmentVariable("UNO_BOOTSTRAP_MONO_RUNTIME_CONFIGURATION", "Release"); AddEnvironmentVariable("UNO_BOOTSTRAP_MONO_RUNTIME_FEATURES", BuildRuntimeFeatures()); - AddEnvironmentVariable("UNO_BOOTSTRAP_APP_BASE", _remoteBasePackagePath); + AddEnvironmentVariable("UNO_BOOTSTRAP_APP_BASE", "./"); AddEnvironmentVariable("UNO_BOOTSTRAP_WEBAPP_BASE_PATH", WebAppBasePath); - if (EnableThreads) - { - AddEnvironmentVariable("UNO_BOOTSTRAP_MAX_THREADS", PThreadsPoolSize.ToString()); - } - - if (ExtraEmccFlags?.Any(f => f.ItemSpec?.Contains("MAXIMUM_MEMORY=4GB") ?? false) ?? false) + if (EmccFlags?.Any(f => f.ItemSpec?.Contains("MAXIMUM_MEMORY=4GB") ?? false) ?? false) { // Detects the use of the 4GB flag: https://v8.dev/blog/4gb-wasm-memory AddEnvironmentVariable("UNO_BOOTSTRAP_EMSCRIPTEN_MAXIMUM_MEMORY", "4GB"); @@ -2070,121 +573,17 @@ private void GenerateConfig() config.AppendLine("export { config };"); w.Write(config.ToString()); - } - } - - private string BuildRuntimeFeatures() - => EnableThreads ? "threads" : ""; - - private void GenerateAppInfo() - { - var unoAppInfoPath = Path.Combine(_distPath, "uno-appinfo.json"); - using var w = new StreamWriter(unoAppInfoPath, append: false, encoding: _utf8Encoding); - - var appInfo = new AppInfo(WebAppBasePath, _remoteBasePackagePath); - } - - static string BuildDependencyPath(string dep, string baseLookup) - => baseLookup.StartsWith("/") - ? $"\"{baseLookup}{Path.GetFileName(dep)}\"" - : $"\"{baseLookup}{Path.GetFileNameWithoutExtension(dep)}\""; - - private void MergeConfig() - { - if(_shellMode == ShellMode.Node) - { - var tempFile = Path.GetTempFileName(); - try - { - var monoJsPath = Path.Combine(_finalPackagePath, "dotnet.native.js"); - - using (var fs = new StreamWriter(tempFile)) - { - fs.Write(File.ReadAllText(Path.Combine(_finalPackagePath, "mono-config.json"))); - fs.Write(File.ReadAllText(Path.Combine(_finalPackagePath, "uno-config.js"))); - fs.Write(File.ReadAllText(Path.Combine(_finalPackagePath, "uno-bootstrap.js"))); - fs.Write(File.ReadAllText(monoJsPath)); - } - - File.Delete(monoJsPath); - File.Move(tempFile, monoJsPath); - Log.LogMessage($"Merged config files with dotnet.native.js"); - } - finally - { - try - { - if (File.Exists(tempFile)) - { - File.Delete(tempFile); - } - } - catch(Exception e) + TaskItem indexMetadata = new( + unoConfigJsPath, new Dictionary { - Console.WriteLine($"Failed to delete temporary file: {e}"); - } - } - } - } - - private IEnumerable GetPWACacheableFiles() - => from file in Directory.EnumerateFiles(_finalPackagePath, "*.*", SearchOption.AllDirectories) - where !file.EndsWith("web.config", StringComparison.OrdinalIgnoreCase) - select file.Replace(_distPath, "").Replace("\\", "/"); - - private (string monoWasmFileName, long monoWasmSize, long totalAssembliesSize, (string fileName, long length)[] assemblyFiles, (string fileName, string integrity)[] filesIntegrity) GetFilesDetails() - { - const string monoWasmFileName = "dotnet.native.wasm"; - - var monoWasmFilePathAndName = Path.Combine(_finalPackagePath, monoWasmFileName); - var monoWasmSize = new FileInfo(monoWasmFilePathAndName).Length; - - var assemblyPathAndFiles = Directory - .EnumerateFiles(Path.Combine(_finalPackagePath, "managed"), "*", SearchOption.TopDirectoryOnly) - .ToArray(); - - var assemblyFiles = assemblyPathAndFiles - .Select(f => - { - var fi = new FileInfo(f); - return (fileName: fi.Name, length: fi.Length); - }) - .ToArray(); + ["CopyToOutputDirectory"] = "PreserveNewest", + ["ContentRoot"] = _intermediateAssetsPath, + ["Link"] = "wwwroot/" + Path.GetFileName(unoConfigJsPath), + }); - var totalAssembliesSize = assemblyFiles.Sum(fi => fi.length); - - (string fileName, string integrity)[] filesIntegrity; - if (UseFileIntegrity) - { - var integrities = new List<(string fileName, string integrity)>(); - - void AddFileIntegrity(string filePath) - { - var bytes = File.ReadAllBytes(filePath); - var hash = _sha384.ComputeHash(bytes); - var integrity = Convert.ToBase64String(hash); - var path = filePath.Replace(_distPath, "").Replace("\\", "/"); - - integrities.Add(($".{path}", $"sha384-{integrity}")); - } - - AddFileIntegrity(monoWasmFilePathAndName); - - foreach (var f in assemblyPathAndFiles) - { - AddFileIntegrity(f); - } - - - filesIntegrity = integrities.ToArray(); + StaticWebContent = StaticWebContent.Concat([indexMetadata]).ToArray(); } - else - { - filesIntegrity = Array.Empty<(string fileName, string integrity)>(); - } - - return ($"{WebAppBasePath}{_remoteBasePackagePath}/" + monoWasmFileName, monoWasmSize, totalAssembliesSize, assemblyFiles, filesIntegrity); } private void GenerateIndexHtml() @@ -2194,9 +593,9 @@ private void GenerateIndexHtml() return; } - var htmlPath = Path.Combine(_distPath, "index.html"); + var indexHtmlOutputPath = Path.Combine(_intermediateAssetsPath, "index.html"); - using var w = new StreamWriter(htmlPath, false, _utf8Encoding); + using var w = new StreamWriter(indexHtmlOutputPath, false, _utf8Encoding); using var reader = new StreamReader(IndexHtmlPath); var html = reader.ReadToEnd(); @@ -2205,7 +604,6 @@ private void GenerateIndexHtml() var extraBuilder = new StringBuilder(); GeneratePWAContent(extraBuilder); - GeneratePrefetchHeaderContent(extraBuilder); GenerateCSPMeta(extraBuilder); html = html.Replace("$(ADDITIONAL_HEAD)", extraBuilder.ToString()); @@ -2214,15 +612,76 @@ private void GenerateIndexHtml() html = html.Replace("mono.js\"", "dotnet.js\""); if (WebAppBasePath != "./") { - html = html.Replace($"\"{WebAppBasePath}", $"\"{WebAppBasePath}{_remoteBasePackagePath}/"); + html = html.Replace($"\"{WebAppBasePath}", $"\"{WebAppBasePath}"); } - html = html.Replace($"\"./", $"\"{WebAppBasePath}{_remoteBasePackagePath}/"); + html = html.Replace($"\"./", $"\"{WebAppBasePath}"); html = html.Replace("$(WEB_MANIFEST)", $"{WebAppBasePath}{Path.GetFileName(PWAManifestFile)}"); w.Write(html); - Log.LogMessage($"HTML {htmlPath}"); + TaskItem indexMetadata = new( + indexHtmlOutputPath, new Dictionary + { + ["CopyToOutputDirectory"] = "PreserveNewest", + ["ContentRoot"] = _intermediateAssetsPath, + ["Link"] = "wwwroot/index.html", + }); + + StaticWebContent = StaticWebContent.Concat([indexMetadata]).ToArray(); + + Log.LogMessage($"HTML {indexHtmlOutputPath}"); + } + + private void GeneratePWAContent(StringBuilder extraBuilder) + { + if (_shellMode != ShellMode.Browser) + { + return; + } + + if (!string.IsNullOrWhiteSpace(PWAManifestFile)) + { + var manifestDocument = JObject.Parse(File.ReadAllText(PWAManifestFile)); + + extraBuilder.AppendLine($""); + + // See https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html + extraBuilder.AppendLine($""); + + if (manifestDocument["icons"] is JArray array + && array.Where(v => v["sizes"]?.Value() == "1024x1024").FirstOrDefault() is JToken img) + { + extraBuilder.AppendLine($""); + } + + if (manifestDocument["theme_color"]?.Value() is string color) + { + extraBuilder.AppendLine($""); + } + else + { + extraBuilder.AppendLine($""); + } + + // Transform the PWA assets + if (manifestDocument["icons"] is JArray icons) + { + foreach (var icon in icons) + { + var originalSource = icon["src"]?.Value(); + + icon["src"] = originalSource switch + { + string s when s.StartsWith("./") => $"{WebAppBasePath}/" + s.Substring(2), + string s => $"./" + s, + _ => originalSource + }; + } + } + + AddStaticAsset(Path.GetFileName(PWAManifestFile), PWAManifestFile!); + } } private void GenerateCSPMeta(StringBuilder extraBuilder) @@ -2234,6 +693,41 @@ private void GenerateCSPMeta(StringBuilder extraBuilder) } } + private void GenerateBitcodeFiles() + { + var bitcodeFiles = Assets + ?.Where(a => a.ItemSpec.EndsWith(".bc") || a.ItemSpec.EndsWith(".a")) + .Where(a => !bool.TryParse(a.GetMetadata("UnoAotCompile"), out var compile) || compile) + .Select(a => GetFilePaths(a).fullPath) + .ToArray() + ?? []; + + List features = new() + { + EnableThreads ? "mt" : "st", + "simd" + }; + + Log.LogMessage(MessageImportance.Low, $"Bitcode files features lookup filter: {string.Join(",", features)}"); + + if (Version.TryParse(EmscriptenVersion, out var emsdkVersion)) + { + var list = BitcodeFilesSelector.Filter(emsdkVersion, features.ToArray(), bitcodeFiles); + + NativeFileReference = list.Select(i => new TaskItem(i)).ToArray(); + } + else + { + Log.LogMessage(MessageImportance.Low, $"EmscriptenVersion is not set, skipping native assets"); + } + } + + private IEnumerable GetEmccExportedRuntimeMethods() + => (EmccExportedRuntimeMethod ?? Array.Empty()).Select(m => m.ItemSpec); + + private bool UseAotProfile + => !string.IsNullOrEmpty(AotProfile) && _runtimeExecutionMode == RuntimeExecutionMode.InterpreterAndAOT; + private void GenerateEmbeddedJs() { if (_shellMode != ShellMode.BrowserEmbedded) @@ -2241,161 +735,106 @@ private void GenerateEmbeddedJs() return; } - var scriptPath = Path.Combine(_distPath, "embedded.js"); + var scriptPath = Path.Combine(IntermediateOutputPath, "shell-embedded.js"); using var w = new StreamWriter(scriptPath, append: false, _utf8Encoding); - const string javascriptTemplate = @" -(async function () { + const string javascriptTemplate = + """ + (async function () { + + const executingScript = document.currentScript; + if(!executingScript) { + console.err("embedded.js MUST be run using a \n"; w2.Write(html); w2.Flush(); - } - private void GeneratePrefetchHeaderContent(StringBuilder extraBuilder) - { - if (_shellMode == ShellMode.Browser && GeneratePrefetchHeaders) - { - extraBuilder.AppendLine($""); - extraBuilder.AppendLine($""); - extraBuilder.AppendLine($""); - extraBuilder.AppendLine($""); - extraBuilder.AppendLine($""); - extraBuilder.AppendLine($""); - - var distName = Path.GetFileName(_managedPath); - foreach (var file in Directory.GetFiles(_managedPath, "*.clr", SearchOption.AllDirectories)) - { - extraBuilder.AppendLine($""); - } - } + AddStaticAsset("embedded.js", scriptPath); + AddStaticAsset("index.html", htmlPath); } - private void GeneratePWAContent(StringBuilder extraBuilder) - { - if (_shellMode != ShellMode.Browser) - { - return; - } - - if (!string.IsNullOrWhiteSpace(PWAManifestFile)) - { - var manifestDocument = JObject.Parse(File.ReadAllText(PWAManifestFile)); - - extraBuilder.AppendLine($""); - - // See https://stackoverflow.com/a/27951414 - extraBuilder.AppendLine($""); - - if (manifestDocument["icons"] is JArray array - && array.Where(v => v["sizes"]?.Value() == "1024x1024").FirstOrDefault() is JToken img) - { - extraBuilder.AppendLine($""); - } - - if (manifestDocument["theme_color"]?.Value() is string color) - { - extraBuilder.AppendLine($""); - } - else - { - extraBuilder.AppendLine($""); - } - - // Transform the PWA assets - if(manifestDocument["icons"] is JArray icons && !string.IsNullOrWhiteSpace(_remoteBasePackagePath)) - { - foreach(var icon in icons) - { - var originalSource = icon["src"]?.Value(); - - icon["src"] = originalSource switch - { - string s when s.StartsWith("./") => $"{WebAppBasePath}{_remoteBasePackagePath}/" + s.Substring(2), - string s => $"{_remoteBasePackagePath}/" + s, - _ => originalSource - }; - } - } + private string TryConvertLongPath(string path) + => Environment.OSVersion.Platform == PlatformID.Win32NT + && !string.IsNullOrEmpty(path) + && !path.StartsWith(@"\\?\") + && Path.IsPathRooted(path) + && FileInfoExtensions.PlatformRequiresLongPathNormalization + ? @"\\?\" + path + : path; - File.WriteAllText(Path.Combine(_distPath, Path.GetFileName(PWAManifestFile)), manifestDocument.ToString()); - } - } + private string BuildRuntimeFeatures() + => EnableThreads ? "threads" : ""; private void ParseEnumProperty(string name, string stringValue, out TEnum value) where TEnum : struct { - if (Enum.TryParse(stringValue, true, out value)) + if (Enum.TryParse(stringValue, true, out value)) { Log.LogMessage(MessageImportance.Low, $"{name}={value}"); } @@ -2404,7 +843,5 @@ private void ParseEnumProperty(string name, string stringValue, out TEnum throw new NotSupportedException($"The {name} {stringValue} is not supported"); } } - - internal record AppInfo(string BasePath, string PackagePath); } } diff --git a/src/Uno.Wasm.Bootstrap/StaticWebAssetsResolverTask.cs b/src/Uno.Wasm.Bootstrap/StaticWebAssetsResolverTask.cs index 724ac49e0..0f8e9d318 100644 --- a/src/Uno.Wasm.Bootstrap/StaticWebAssetsResolverTask.cs +++ b/src/Uno.Wasm.Bootstrap/StaticWebAssetsResolverTask.cs @@ -24,6 +24,7 @@ using System.IO; using System.Linq; using System.Numerics; +using System.Runtime.InteropServices; using System.Security.Cryptography; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; @@ -31,110 +32,36 @@ namespace Uno.Wasm.Bootstrap; -public class StaticWebAssetsResolverTask_v0 : Microsoft.Build.Utilities.Task +public class ValidateStaticAssets_v0 : Microsoft.Build.Utilities.Task { - public string? WebAppBasePath { get; set; } - [Required] - public string AssemblyName { get; private set; } = ""; + public ITaskItem[] CandidateAssets { get; set; } = []; [Required] - public string DistPath { get; private set; } = ""; + public ITaskItem[] ExistingEndpoints { get; set; } = []; [Required] - public string ProjectDirectory { get; private set; } = ""; - - [Output] - public ITaskItem[]? StaticWebAsset { get; private set; } + public ITaskItem[] ContentTypeMappings { get; set; } = []; public override bool Execute() { - var fixedDistPath = PathHelper.FixupPath(DistPath); - var projectDirectory = PathHelper.FixupPath(ProjectDirectory); - - if (Directory.Exists(fixedDistPath)) - { - var wwwRootBasePath = Path.Combine(projectDirectory, "wwwroot"); - - var distFiles = Directory.EnumerateFiles(fixedDistPath, "*.*", SearchOption.AllDirectories).ToArray(); - var wwwRootAssets = Directory.Exists(wwwRootBasePath) - ? Directory.EnumerateFiles(wwwRootBasePath, "*.*", SearchOption.AllDirectories) - : Enumerable.Empty(); - - Log.LogMessage(MessageImportance.Low, $"Found {distFiles.Length} assets"); - - var filteredAssets = distFiles - .Where(a => !wwwRootAssets - .Select(wa => wa.Replace(wwwRootBasePath, "")) - .Any(wa => a.Replace(fixedDistPath, "") == wa)) - .ToArray() - ; - - Log.LogMessage(MessageImportance.Low, $"Found {filteredAssets.Length} filtered assets"); - - StaticWebAsset = - filteredAssets.Select(asset => new TaskItem(asset, GetMetadata(asset, fixedDistPath))) - .ToArray(); - } - else - { - Log.LogMessage(MessageImportance.Low, $"The folder {fixedDistPath} does not exist, skipping StaticAssets generation"); - } - + var staticWebAssets = CandidateAssets.ToDictionary(a => a.GetMetadata("FullPath")); + var existingEndpoints = ExistingEndpoints; + var existingEndpointsByAssetFile = existingEndpoints + .GroupBy(e => e.GetMetadata("AssetFile"), OSPath.PathComparer) + .ToDictionary(g => g.Key); + return true; } - private Dictionary GetMetadata(string asset, string fixedDistPath) + internal static class OSPath { - var dict = new Dictionary - { - ["SourceType"] = "Discovered", - ["SourceId"] = AssemblyName, - ["ContentRoot"] = fixedDistPath, - ["RelativePath"] = asset.Replace(fixedDistPath, ""), - ["BasePath"] = WebAppBasePath is { Length: > 0 } ? WebAppBasePath : "/", - ["AssetKind"] = "All", - ["AssetMode"] = "All", - ["AssetRole"] = "Primary", - ["OriginalItemSpec"] = asset, - }; - - var (fingerprint, integrity) = ComputeFingerprintAndIntegrity(asset, asset); - dict.Add("Fingerprint", fingerprint); - dict.Add("Integrity", integrity); - return dict; - } - - // https://github.com/dotnet/sdk/blob/cc17704acfbee4b2ef49a82aa6f65aaa9cafffef/src/StaticWebAssetsSdk/Tasks/Data/StaticWebAsset.cs#L233-L248 - private static (string fingerprint, string integrity) ComputeFingerprintAndIntegrity(string identity, string originalItemSpec) - { - using var file = File.Exists(identity) ? - File.OpenRead(identity) : - (File.Exists(originalItemSpec) ? - File.OpenRead(originalItemSpec) : - throw new InvalidOperationException($"No file exists for the asset at either location '{identity}' or '{originalItemSpec}'.")); - -#if NET6_0_OR_GREATER - var hash = SHA256.HashData(file); -#else - using var sha = SHA256.Create(); - var hash = sha.ComputeHash(file); -#endif - return (ToBase36(hash), Convert.ToBase64String(hash)); - } - - private static string ToBase36(byte[] hash) - { - const string chars = "0123456789abcdefghijklmnopqrstuvwxyz"; - - var result = new char[10]; - var dividend = BigInteger.Abs(new BigInteger(hash.AsSpan().Slice(0, 9).ToArray())); - for (var i = 0; i < 10; i++) - { - dividend = BigInteger.DivRem(dividend, 36, out var remainder); - result[i] = chars[(int)remainder]; - } + public static StringComparer PathComparer { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) + ? StringComparer.OrdinalIgnoreCase : + StringComparer.Ordinal; - return new string(result); + public static StringComparison PathComparison { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) + ? StringComparison.OrdinalIgnoreCase : + StringComparison.Ordinal; } } diff --git a/src/Uno.Wasm.Bootstrap/Uno.Wasm.Bootstrap.csproj b/src/Uno.Wasm.Bootstrap/Uno.Wasm.Bootstrap.csproj index 00d0c26fc..9b9feeb00 100644 --- a/src/Uno.Wasm.Bootstrap/Uno.Wasm.Bootstrap.csproj +++ b/src/Uno.Wasm.Bootstrap/Uno.Wasm.Bootstrap.csproj @@ -3,18 +3,18 @@ netstandard2.0 NET_CORE - 1701;1702;1705;649;NU5128 + 1701;1702;1705;649;NU5128;NU1903 Uno.Wasm.Bootstrap.v0 Uno.Wasm.Bootstrap.v0 Uno.Wasm.Bootstrap true 2.0.1-test.8 true - 10.0 enable - true + true + false - + Uno.Wasm.Bootstrap.v$(GitVersion_Sha) Uno.Wasm.Bootstrap.v$(GitVersion_Sha) @@ -41,76 +41,46 @@ - + true build - - + + true build - - - true - build/CustomDebuggerProxy - - - true - build/linker - - - true - build/cilstrip - - + + true build/scripts - - + + true tools/templates - - - true - tools - PreserveNewest - false - - - true - tools - PreserveNewest - false - - - true - tools - false - PreserveNewest - false - - - true - tools - false - PreserveNewest - false - - - true - tools - false - PreserveNewest - false - - + + + true tools false - PreserveNewest false - + + + + + + <_UnoTaskDependencies Include="$(NuGetPackageRoot)/mono.cecil/0.11.4/lib/netstandard2.0/*.dll" /> + + + + @@ -122,19 +92,14 @@ - + - + - - false - true - TargetFramework - false true @@ -150,44 +115,8 @@ true TargetFramework - - false - true - TargetFramework - - - false - true - TargetFramework - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -204,31 +133,36 @@ + + + - + - <_PackagerNet5Files Include="../Uno.Wasm.Packager/bin/$(Configuration)/net5.0/packager.*" /> - <_TunerNet5Files Include="../Uno.Wasm.Tuner/bin/$(Configuration)/net5.0/wasm-tuner.*" /> - <_TunerNet5Files Include="../Uno.Wasm.Tuner/bin/$(Configuration)/net5.0/Mono.Cecil.*" /> - <_TunerNet5Files Include="../Uno.Wasm.Tuner/bin/$(Configuration)/net5.0/System.Json.dll" /> - <_TunerNet5Files Include="../Uno.Wasm.Tuner/bin/$(Configuration)/net5.0/System.Reflection.MetadataLoadContext.dll" /> + - - + + + + + - + - - - true - build/packager - - - true - build/wasm-tuner - + <_IntermediateGeneratedJavascript Include="@(GeneratedJavascript->'$(IntermediateOutputPath)%(FileName)%(Extension)')" /> + + + + + + + + + + + @@ -241,6 +175,7 @@ <_Sha1Replace Include="ShellTask*.cs" /> <_Sha1Replace Include="*Task.cs" /> + <_Sha1Replace Include="build\Uno.Wasm.Bootstrap.props" /> <_Sha1Replace Include="build\Uno.Wasm.Bootstrap.targets" /> @@ -261,8 +196,9 @@ if(!output.Contains(SHAVersion)) { - Log.LogMessage("Updating : " + FilePath); + Log.LogMessage("Updating " + FilePath + " with " + SHAVersion); File.WriteAllText(FilePath, output.Replace("v0", SHAVersion)); + Log.LogMessage(File.ReadAllText(FilePath)); } else { @@ -272,4 +208,37 @@ + + + + + + + + + + + + + + + + + +
diff --git a/src/Uno.Wasm.Bootstrap/UnoInstallSDKTask.cs b/src/Uno.Wasm.Bootstrap/UnoInstallSDKTask.cs deleted file mode 100644 index 092d13dbf..000000000 --- a/src/Uno.Wasm.Bootstrap/UnoInstallSDKTask.cs +++ /dev/null @@ -1,408 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.IO.Compression; -using System.Linq; -using System.Net; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Build.Framework; -using Uno.Wasm.Bootstrap.Extensions; - -namespace Uno.Wasm.Bootstrap -{ - public class UnoInstallSDKTask_v0 : Microsoft.Build.Utilities.Task, ICancelableTask - { - private readonly CancellationTokenSource _cts = new(); - - private static readonly TimeSpan _SDKFolderLockTimeout = TimeSpan.FromMinutes(2); - private static readonly TimeSpan _SDKLockRetryDelay = TimeSpan.FromSeconds(10); - - public string? NetCoreWasmSDKUri { get; set; } - - public string? MonoTempFolder { get; set; } - - [Microsoft.Build.Framework.Required] - public string TargetFrameworkIdentifier { get; set; } = ""; - - public string TargetFramework { get; set; } = ""; - - public string TargetFrameworkVersion { get; set; } = "0.0"; - - [Required] - public string RuntimeConfiguration { get; set; } = ""; - - [Required] - public string PackagerOverrideFolderPath { get; set; } = ""; - - [Required] - public string CilStripOverrideFolderPath { get; set; } = ""; - - [Required] - public bool IsOSUnixLike { get; set; } - - [Microsoft.Build.Framework.Required] - public bool EnableThreads { get; set; } - - [Microsoft.Build.Framework.Required] - public bool EnableSimd { get; set; } - - public bool EnableEmscriptenWindows { get; set; } = true; - - [Microsoft.Build.Framework.Required] - public string MonoRuntimeExecutionMode { get; set; } = ""; - - [Microsoft.Build.Framework.Required] - public Microsoft.Build.Framework.ITaskItem[]? Assets { get; set; } - - public bool GenerateAOTProfile { get; set; } = false; - - public bool DisableSDKCheckSumValidation { get; set; } = false; - - public bool DebugSDKChecksum { get; set; } = false; - - [Output] - public string? SdkPath { get; set; } - - [Output] - public string? PackagerBinPath { get; set; } - - [Output] - public string? PackagerProjectFile { get; private set; } - - public override bool Execute() - => ExecuteAsync(_cts.Token).Result; - - private async Task ExecuteAsync(CancellationToken ct) - { - if(TargetFramework == "netstandard2.0") - { - Log.LogError($"netstandard2.0 is not supported by this version of the bootstrapper. Update to net5.0 or later."); - return false; - } - - if (EnableEmscriptenWindows && Environment.OSVersion.Platform != PlatformID.Win32NT) - { - EnableEmscriptenWindows = false; - } - - await InstallNetCoreWasmSdk(ct); - - return true; - } - - private Version ActualTargetFrameworkVersion => Version.TryParse(TargetFrameworkVersion.Substring(1), out var v) ? v : new Version("0.0"); - - private async Task InstallNetCoreWasmSdk(CancellationToken ct) - { - var sdkUri = string.IsNullOrWhiteSpace(NetCoreWasmSDKUri) ? Constants.DefaultDotnetRuntimeSdkUrl : NetCoreWasmSDKUri!; - - if (EnableEmscriptenWindows) - { - sdkUri = sdkUri.Replace("linux", "windows"); - } - - if (EnableThreads) - { - sdkUri = sdkUri.Replace(".zip", "-threads.zip"); - } - - if (EnableSimd) - { - sdkUri = sdkUri.Replace(".zip", "-simd.zip"); - } - - var sdkName = Path.GetFileNameWithoutExtension(new Uri(sdkUri).AbsolutePath.Replace('/', Path.DirectorySeparatorChar)); - Log.LogMessage("NetCore-Wasm SDK: " + sdkName); - SdkPath = Path.Combine(GetMonoTempPath(), sdkName); - Log.LogMessage("NetCore-Wasm SDK Path: " + SdkPath); - - SetupPackagerOutput(); - - var writeChecksum = false; - - try - { - void WriteTools() - { - WriteCilStrip(); - } - - if (!await ValidateSDKCheckSum(ct, "NetCore-Wasm", SdkPath)) - { - var zipPath = SdkPath + ".zip"; - Log.LogMessage($"Using NetCore-Wasm SDK {sdkUri}"); - - zipPath = await RetreiveSDKFile(ct, sdkName, sdkUri, zipPath); - - ZipFile.ExtractToDirectory(zipPath, SdkPath); - Log.LogMessage($"Extracted {sdkName} to {SdkPath}"); - - MarkSDKExecutable(); - - WriteTools(); - - writeChecksum = true; - } - - if (DisableSDKCheckSumValidation) - { - // If the validation is disabled, it's generally for troubleshooting of tooling - // Overwrite the tools when checksum validation is disabled. - WriteTools(); - } - - - if (writeChecksum) - { - WriteChecksum(SdkPath); - Log.LogMessage($"Wrote checksum to {SdkPath}"); - } - } - finally - { - UnlockSDKPath(SdkPath); - } - } - - private void SetupPackagerOutput() - { - var packagerName = "packager.dll"; - PackagerBinPath = Path.Combine(PackagerOverrideFolderPath, packagerName); - } - - private void UnlockSDKPath(string sdkPath) - { - try - { - File.Delete(Path.Combine(sdkPath, ".lock")); - } - catch (Exception ex) - { - Log.LogMessage($"Failed to delete SDK lock file ({ex.Message})"); - } - finally - { - Log.LogMessage(MessageImportance.Low, "Released SDK Folder lock"); - } - } - - private static void LockSDKPath(string sdkPath) - { - var lockFilePath = Path.Combine(sdkPath, ".lock"); - Directory.CreateDirectory(sdkPath); - File.WriteAllText(path: lockFilePath, Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture)); - } - - private async Task ValidateSDKCheckSum(CancellationToken ct, string sdkName, string sdkPath) - { - var result = Directory.Exists(sdkPath); - - await WaitForLockFile(sdkPath, ct); - - if (!DisableSDKCheckSumValidation && Directory.Exists(sdkPath) && !VerifyChecksum(sdkPath)) - { - // SDK folder was tampered with (e.g. StorageSense, User, etc.) - Log.LogMessage($"Removing invalid {sdkName} SDK: {sdkPath}"); - - var destination = $"{sdkPath}.{Guid.NewGuid():N}"; - - Directory.Move(sdkPath, destination); - Directory.Delete(destination, true); - - result = false; - } - - LockSDKPath(sdkPath); - - return result; - } - - private async Task WaitForLockFile(string sdkPath, CancellationToken ct) - { - var lockFilePath = Path.Combine(sdkPath, ".lock"); - var sw = Stopwatch.StartNew(); - - while (sw.Elapsed < _SDKFolderLockTimeout) - { - if (File.Exists(lockFilePath)) - { - if (int.TryParse(File.ReadAllText(lockFilePath), NumberStyles.Integer, CultureInfo.CurrentCulture, out var pid) && Process.GetCurrentProcess().Id == pid) - { - break; - } - else - { - Log.LogMessage(/*MessageImportance.Low, */"SDK Folder is locked, waiting..."); - - await Task.Delay(_SDKLockRetryDelay, ct); - } - } - else - { - break; - } - } - - Log.LogMessage(/*MessageImportance.Low, */"Got SDK Folder lock"); - } - - private void MarkSDKExecutable() - { - if (IsOSUnixLike) - { - Process.Start("chmod", $"-R +x \"{SdkPath}\""); - } - } - - private void WriteCilStrip() - { - if (!string.IsNullOrEmpty(CilStripOverrideFolderPath)) - { - var basePath = Path.Combine(SdkPath, "tools"); - Directory.CreateDirectory(basePath); - - foreach (var file in Directory.EnumerateFiles(CilStripOverrideFolderPath)) - { - var destFileName = Path.Combine(basePath, Path.GetFileName(file)); - Log.LogMessage($"Copy cil-strip {file} to {destFileName}"); - File.Copy(file, destFileName, true); - } - } - } - static readonly string[] BitCodeExtensions = new string[] { ".bc", ".a" }; - - private bool HasBitcodeAssets() - => Assets.Any(asset => BitCodeExtensions.Any(ext => asset.ItemSpec.EndsWith(ext, StringComparison.OrdinalIgnoreCase))); - - private async Task RetreiveSDKFile(CancellationToken ct, string sdkName, string sdkUri, string zipPath) - { - var tries = 3; - - while (--tries > 0) - { - try - { - var uri = new Uri(sdkUri); - - if (!uri.IsFile) - { - var client = new WebClient(); - var wp = WebRequest.DefaultWebProxy; - wp.Credentials = CredentialCache.DefaultCredentials; - client.Proxy = wp; - - Log.LogMessage(Microsoft.Build.Framework.MessageImportance.High, $"Downloading {sdkName} to {zipPath}"); - - using (ct.Register(() => client.CancelAsync())) - { - await client.DownloadFileTaskAsync(sdkUri, zipPath); - } - - return zipPath; - } - else - { - return uri.LocalPath; - } - } - catch(Exception e) - { - Log.LogWarning($"Failed to download Downloading {sdkName} to {zipPath}. Retrying... ({e.Message})"); - } - } - - throw new Exception($"Failed to download {sdkName} to {zipPath}"); - } - - private const string ChecksumFilename = "UNO_WASM_SDK.CHECKSUM"; - - private int ComputeChecksum(string path) - { - var exclusions = new[] - { - Path.Combine(path, ".lock"), - Path.Combine(path, ChecksumFilename), - Path.Combine(path, Path.Combine("wasm-bcl", "wasm_tools", "monolinker.exe.config")) - }; - - var files = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories) - .Where(f => !exclusions.Contains(f)); - - if (DebugSDKChecksum) - { - var raw = string.Join("\r\n", files.Select(f => $"{f}: {new FileInfo(f).Length}")); - Log.LogMessage($"SDK Files Checksum: {raw}"); - } - - return files - .Sum(f => f.Length); - } - - private bool VerifyChecksum(string path) - { - try - { - var checksum = int.Parse(File.ReadAllText(Path.Combine(path, ChecksumFilename))); - - return ComputeChecksum(path) == checksum; - } - catch - { - return false; - } - } - - private void WriteChecksum(string path) - { - var file = Path.Combine(path, ChecksumFilename); - - File.WriteAllText(file, $"{ComputeChecksum(path)}"); - } - - private string GetMonoTempPath() - { - var path = string.IsNullOrWhiteSpace(MonoTempFolder) ? Path.GetTempPath() : MonoTempFolder!; - - // Workaround for https://github.com/unoplatform/Uno.Wasm.Bootstrap/issues/418 - if(path.Trim().Contains(" ")) - { - if (EnableEmscriptenWindows) - { - path = Path.Combine(Environment.GetEnvironmentVariable("ProgramData"), "UnoPlatform"); - } - else - { - throw new InvalidOperationException("The MSBuild property WasmShellMonoTempFolder (MonoTempFolder task parameter) must not contain spaces"); - } - } - - Directory.CreateDirectory(path); - - return path; - } - - private RuntimeExecutionMode ParseRuntimeExecutionMode() - { - if (Enum.TryParse(MonoRuntimeExecutionMode, out var runtimeExecutionMode)) - { - Log.LogMessage(MessageImportance.Low, $"MonoRuntimeExecutionMode={MonoRuntimeExecutionMode}"); - } - else - { - throw new NotSupportedException($"The MonoRuntimeExecutionMode {MonoRuntimeExecutionMode} is not supported"); - } - - return runtimeExecutionMode; - } - - public void Cancel() - => _cts.Cancel(); - } -} diff --git a/src/Uno.Wasm.Bootstrap/build/CustomDebuggerProxy/Mono.Cecil.Mdb.dll b/src/Uno.Wasm.Bootstrap/build/CustomDebuggerProxy/Mono.Cecil.Mdb.dll deleted file mode 100644 index 4fcaa4131..000000000 Binary files a/src/Uno.Wasm.Bootstrap/build/CustomDebuggerProxy/Mono.Cecil.Mdb.dll and /dev/null differ diff --git a/src/Uno.Wasm.Bootstrap/build/CustomDebuggerProxy/Mono.Cecil.Pdb.dll b/src/Uno.Wasm.Bootstrap/build/CustomDebuggerProxy/Mono.Cecil.Pdb.dll deleted file mode 100644 index 9b68872c8..000000000 Binary files a/src/Uno.Wasm.Bootstrap/build/CustomDebuggerProxy/Mono.Cecil.Pdb.dll and /dev/null differ diff --git a/src/Uno.Wasm.Bootstrap/build/CustomDebuggerProxy/Mono.Cecil.Rocks.dll b/src/Uno.Wasm.Bootstrap/build/CustomDebuggerProxy/Mono.Cecil.Rocks.dll deleted file mode 100644 index becd68533..000000000 Binary files a/src/Uno.Wasm.Bootstrap/build/CustomDebuggerProxy/Mono.Cecil.Rocks.dll and /dev/null differ diff --git a/src/Uno.Wasm.Bootstrap/build/CustomDebuggerProxy/Mono.Cecil.dll b/src/Uno.Wasm.Bootstrap/build/CustomDebuggerProxy/Mono.Cecil.dll deleted file mode 100644 index 58dddaa32..000000000 Binary files a/src/Uno.Wasm.Bootstrap/build/CustomDebuggerProxy/Mono.Cecil.dll and /dev/null differ diff --git a/src/Uno.Wasm.Bootstrap/build/CustomDebuggerProxy/Mono.WebAssembly.DebuggerProxy.dll b/src/Uno.Wasm.Bootstrap/build/CustomDebuggerProxy/Mono.WebAssembly.DebuggerProxy.dll deleted file mode 100644 index 2ec873716..000000000 Binary files a/src/Uno.Wasm.Bootstrap/build/CustomDebuggerProxy/Mono.WebAssembly.DebuggerProxy.dll and /dev/null differ diff --git a/src/Uno.Wasm.Bootstrap/build/Uno.Wasm.Bootstrap.Publish.targets b/src/Uno.Wasm.Bootstrap/build/Uno.Wasm.Bootstrap.Publish.targets index 5455eeabf..a05b12bfe 100644 --- a/src/Uno.Wasm.Bootstrap/build/Uno.Wasm.Bootstrap.Publish.targets +++ b/src/Uno.Wasm.Bootstrap/build/Uno.Wasm.Bootstrap.Publish.targets @@ -1,33 +1,5 @@  - - - - - <_ResolvedCopyLocalPublishAssets Remove="@(_ResolvedCopyLocalPublishAssets)" /> - - - - - - - - - - - <_UnoWasmDistFiles Include="$(OutputPath)dist/**"/> - <_UnoWasmDist Include="@(_UnoWasmDistFiles)"> - $([System.String]::Copy('%(Identity)').Replace('$(OutputPath)dist$([System.IO.Path]::DirectorySeparatorChar)', 'wwwroot/')) - - - - %(TargetPath) - PreserveNewest - - - diff --git a/src/Uno.Wasm.Bootstrap/build/Uno.Wasm.Bootstrap.props b/src/Uno.Wasm.Bootstrap/build/Uno.Wasm.Bootstrap.props index 6748b30cf..eb2f351ab 100644 --- a/src/Uno.Wasm.Bootstrap/build/Uno.Wasm.Bootstrap.props +++ b/src/Uno.Wasm.Bootstrap/build/Uno.Wasm.Bootstrap.props @@ -1,19 +1,4 @@ - - true - - - browser-wasm - - - false - - - false - @@ -23,8 +8,4 @@ - - - - diff --git a/src/Uno.Wasm.Bootstrap/build/Uno.Wasm.Bootstrap.targets b/src/Uno.Wasm.Bootstrap/build/Uno.Wasm.Bootstrap.targets index eb328cdbb..c9b9772e3 100644 --- a/src/Uno.Wasm.Bootstrap/build/Uno.Wasm.Bootstrap.targets +++ b/src/Uno.Wasm.Bootstrap/build/Uno.Wasm.Bootstrap.targets @@ -1,196 +1,244 @@ - - <_packageBinaryPath>$(MSBuildThisFileDirectory)../tools/Uno.Wasm.Bootstrap.v0.dll + <_UnoBootstrapTaskBinary>$(MSBuildThisFileDirectory)../tools/Uno.Wasm.Bootstrap.v0.dll <_WasmShellTasksPathIsDevMode>false - <_WasmShellTasksPathIsDevMode Condition="!Exists('$(_packageBinaryPath)')">true + <_WasmShellTasksPathIsDevMode Condition="!Exists('$(_UnoBootstrapTaskBinary)')">true $(MSBuildThisFileDirectory)../bin/$(Configuration)/netstandard2.0 ../tools - $(MSBuildThisFileDirectory)../Templates/index.html - $(MSBuildThisFileDirectory)../tools/templates/index.html + $(MSBuildThisFileDirectory)../Templates/index.html + $(MSBuildThisFileDirectory)../tools/templates/index.html .a;.bc;.o - .clr + true browser - Release - false - true - false - true - 7 - true - false - true - false - - - true - - - true - - - false - false - false - false - false - true - - - - <_RequiresILLinkPack Condition="'$(TargetFrameworkVersion)'!='' and '$(TargetFrameworkVersion.Substring(1))'>='8.0'">true - - $(AssemblyName)/dist/ - - - Interpreter - - - FullAOT - - - false - false - true - false - false - $(MonoRuntimeDebuggerEnabled) - - - <_WasmBootstrapOriginalPublishDir>$(PublishDir) + + false - + + + + $(WasmProfilers);aot; + + + true + + + false + + + true + + + false - - false + + + + + $(WasmProfilers);log; - - - - - - - $([System.IO.Path]::GetDirectoryName($(ILLinkTasksAssembly)))\..\net$(TargetFrameworkVersion.Substring(1)) - - - - - $([System.IO.Path]::GetDirectoryName($(ILLinkTasksAssembly)))\..\net7.0 - - - - - - - - - - <_WasmShellIsNetCore Condition="'$(TargetFrameworkIdentifier)'=='.NETCoreApp' and '$(TargetFrameworkVersion.Substring(1))'>='5.0'">true - true - + + true + + + false + + + true - - - - + + false + + + + true + true + + + + + + - - - - - - - - - - - - - - - - - - - - - - + + + + + + - - - - + + + + + + - - - - - - + + + + <_emsdkOriginalPackagePath>$([System.IO.Path]::GetFullPath('$(EmscriptenSdkToolsPath)..')) + <_targetEMSDKPath>$(USERPROFILE)\.uno\emsdk\$([System.IO.Path]::GetFileName('$(_emsdkOriginalPackagePath)')) + + + + + + + + $(_targetEMSDKPath)\ + $(EmscriptenSdkToolsPath)bin\ + $(EmscriptenSdkToolsPath)emscripten\ + - + + + - + + + - - $(AssemblyName).xml - false - + + <_WasmPInvokeModules Include="__Native" /> + <_WasmPInvokeModules Include="__Internal" /> + <_WasmPInvokeModules Include="@(WasmShellAdditionalPInvokeLibrary)" /> + + + + + + + + <_NativeAssetsFiltered Include="@(Assets)" Condition=" '%(Extension)'=='.a' OR '%(Extension)'=='.o' OR '%(Extension)'=='.bc' " /> + + + + <_AOT_InternalForceInterpretAssemblies Include="@(MonoRuntimeMixedModeExcludedAssembly->'%(Filename).dll')" /> - + + + $(WasmShellEnableSimd) + + + $(WasmShellEnableAOTDeduplication) + + + -O0 + -O1 + -O2 + -O3 + -Oz + + -O0 + + + $(WasmShellEnableJiterpreter) + + + $(EmccFlags);@(WasmShellExtraEmccFlags) + + $(EmccFlags);--profiling + + + true + + + <_WasmPThreadPoolInitialSize Condition=" '$(WasmShellPThreadsPoolSize)' == 'true' ">true + + + true + + + true + + + + + + $([System.IO.Path]::GetFullPath('$(IntermediateOutputPath)emsdk-cache')) + + + $(TMP)\emsdk-cache + + + + + + + <_NativeAssetsFiltered Remove="@(_NativeAssetsFiltered)" /> + - - - BuildDist; - $(StaticWebAssetsPrepareForRunDependsOn) - - + + + + + + + + + - + + + + + @@ -199,172 +247,56 @@ Condition="'%(Extension)' == '.dll'" /> - - - - - $([System.IO.Path]::Combine('$(OutputPath)', 'dist')) - <_WasmShellIsNetCore Condition="'$(TargetFrameworkIdentifier)'=='.NETCoreApp' and '$(TargetFrameworkVersion.Substring(1))'>='5.0'">true - - <_WasmShellToolSuffix Condition="'$(_WasmShellIsNetCore)'!='true'">net462 - <_WasmShellToolSuffix Condition="'$(_WasmShellIsNetCore)'=='true'">net5.0 - + + <_UnoWasmCopyToOutputAssets + Include="@(_AllChildProjectItemsWithTargetPath)" + Condition=" '%(_AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest' OR '%(_AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'Always' " /> - - - - - + + - - + > + + + - - - - - - - - - - - - - - - - - - - - - - $(OutputPath)/dist - - - - - - - - <_CliToolRefs>@(DotNetCliToolReference) + + + $(_FilteredAotProfile) - - - - - - - - - - + - diff --git a/src/Uno.Wasm.Bootstrap/build/cilstrip/mono-cil-strip.exe b/src/Uno.Wasm.Bootstrap/build/cilstrip/mono-cil-strip.exe deleted file mode 100644 index badf776c9..000000000 Binary files a/src/Uno.Wasm.Bootstrap/build/cilstrip/mono-cil-strip.exe and /dev/null differ diff --git a/src/Uno.Wasm.Bootstrap/build/cilstrip/mono-cil-strip.pdb b/src/Uno.Wasm.Bootstrap/build/cilstrip/mono-cil-strip.pdb deleted file mode 100644 index d894dbf5b..000000000 Binary files a/src/Uno.Wasm.Bootstrap/build/cilstrip/mono-cil-strip.pdb and /dev/null differ diff --git a/src/Uno.Wasm.Bootstrap/build/linker/Mono.Cecil.dll b/src/Uno.Wasm.Bootstrap/build/linker/Mono.Cecil.dll deleted file mode 100644 index 9b78a39f1..000000000 Binary files a/src/Uno.Wasm.Bootstrap/build/linker/Mono.Cecil.dll and /dev/null differ diff --git a/src/Uno.Wasm.Bootstrap/build/linker/monolinker.exe b/src/Uno.Wasm.Bootstrap/build/linker/monolinker.exe deleted file mode 100644 index 4e4f7adcd..000000000 Binary files a/src/Uno.Wasm.Bootstrap/build/linker/monolinker.exe and /dev/null differ diff --git a/src/Uno.Wasm.Bootstrap/tools/support/.gitignore b/src/Uno.Wasm.Bootstrap/tools/support/.gitignore deleted file mode 100644 index f0daeb894..000000000 --- a/src/Uno.Wasm.Bootstrap/tools/support/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -*.dll -*.pdb -*.json \ No newline at end of file diff --git a/src/Uno.Wasm.Bootstrap/ts/Uno/WebAssembly/AotProfilerSupport.ts b/src/Uno.Wasm.Bootstrap/ts/Uno/WebAssembly/AotProfilerSupport.ts index d98c82368..b4386be1b 100644 --- a/src/Uno.Wasm.Bootstrap/ts/Uno/WebAssembly/AotProfilerSupport.ts +++ b/src/Uno.Wasm.Bootstrap/ts/Uno/WebAssembly/AotProfilerSupport.ts @@ -3,6 +3,7 @@ export class AotProfilerSupport { private _context?: DotnetPublicAPI; + private _aotProfilerExports?: any; private _unoConfig: UnoConfig; @@ -13,16 +14,10 @@ // This will fail when CSP is enabled, but initialization of the profiler // cannot happen asynchronously. Until this is fixed by the runtime, we'll need // to keep using bind_static_method. - var initializeProfile = this._context.BINDING.bind_static_method("[Uno.Wasm.AotProfiler] Uno.AotProfilerSupport:Initialize"); - if (initializeProfile) { - initializeProfile(); - this.attachProfilerHotKey(); - } - else { - throw `Unable to find AOT Profiler initialization method`; - } + this.attachProfilerHotKey(); } + public static initialize(context: DotnetPublicAPI, unoConfig: Uno.WebAssembly.Bootstrap.UnoConfig): AotProfilerSupport { if (Bootstrapper.ENVIRONMENT_IS_WEB && unoConfig.generate_aot_profile) { return new AotProfilerSupport(context, unoConfig); @@ -45,13 +40,25 @@ }); } - public saveAotProfile() { - var stopProfile = this._context.BINDING.bind_static_method("[Uno.Wasm.AotProfiler] Uno.AotProfilerSupport:StopProfile"); - stopProfile(); + private async initializeProfile() { + let anyContext = this._context; + + if (anyContext.getAssemblyExports !== undefined) { + this._aotProfilerExports = await anyContext.getAssemblyExports("Uno.Wasm.AotProfiler"); + } + else { + throw `Unable to find getAssemblyExports`; + } + } + + public async saveAotProfile() { + await this.initializeProfile(); + + this._aotProfilerExports.Uno.AotProfilerSupport.StopProfile(); // Export the file var a = window.document.createElement('a'); - var blob = new Blob([(this._context.Module).aot_profile_data]); + var blob = new Blob([(this._context.INTERNAL).aotProfileData]); a.href = window.URL.createObjectURL(blob); a.download = "aot.profile"; diff --git a/src/Uno.Wasm.Bootstrap/ts/Uno/WebAssembly/Bootstrapper.ts b/src/Uno.Wasm.Bootstrap/ts/Uno/WebAssembly/Bootstrapper.ts index 502f1f684..ec4bccb50 100644 --- a/src/Uno.Wasm.Bootstrap/ts/Uno/WebAssembly/Bootstrapper.ts +++ b/src/Uno.Wasm.Bootstrap/ts/Uno/WebAssembly/Bootstrapper.ts @@ -1,6 +1,5 @@ /// /// -/// /// namespace Uno.WebAssembly.Bootstrap { @@ -48,15 +47,18 @@ namespace Uno.WebAssembly.Bootstrap { this._appBase = this._unoConfig.environmentVariables["UNO_BOOTSTRAP_APP_BASE"]; this.disableDotnet6Compatibility = false; - this.configSrc = `mono-config.json`; + this.configSrc = `blazor.boot.json`; this.onConfigLoaded = config => this.configLoaded(config); this.onDotnetReady = () => this.RuntimeReady(); - this.onAbort = () => this.runtimeAbort(); // Register this instance of the Uno namespace globally globalThis.Uno = Uno; } + public static invokeJS(value: string) { + return eval(value); + } + public static async bootstrap(): Promise { try { @@ -82,7 +84,7 @@ namespace Uno.WebAssembly.Bootstrap { //@ts-ignore var config = await import('./uno-config.js'); - if(document && (document as any).uno_app_base_override) { + if (document && (document as any).uno_app_base_override) { config.config.uno_app_base = (document as any).uno_app_base_override; } @@ -93,10 +95,14 @@ namespace Uno.WebAssembly.Bootstrap { } //@ts-ignore - var m = await import(`./dotnet.js`); + var m = await import(`./_framework/dotnet.js`); - // Change the global loadBootResource - m.dotnet.withResourceLoader(bootstrapper.loadResource.bind(bootstrapper)); + m.dotnet + .withModuleConfig({ + preRun: () => bootstrapper.wasmRuntimePreRun(), + }) + .withRuntimeOptions(config.config.uno_runtime_options) + .withConfig({ loadAllSatelliteResources: config.config.uno_loadAllSatelliteResources }); const dotnetRuntime = await m.default( (context: DotnetPublicAPI) => { @@ -105,6 +111,10 @@ namespace Uno.WebAssembly.Bootstrap { } ); + // Capture the module instance and publish to globalThis. + bootstrapper._context.Module = dotnetRuntime.Module; + (globalThis).Module = bootstrapper._context.Module; + bootstrapper._runMain = dotnetRuntime.runMain; bootstrapper.setupExports(dotnetRuntime); } @@ -116,33 +126,26 @@ namespace Uno.WebAssembly.Bootstrap { private setupExports(dotnetRuntime: any) { this._getAssemblyExports = dotnetRuntime.getAssemblyExports; (this._context.Module).getAssemblyExports = dotnetRuntime.getAssemblyExports; - } + (globalThis.Module).getAssemblyExports = dotnetRuntime.getAssemblyExports; + } public asDotnetConfig(): DotnetModuleConfig { return { disableDotnet6Compatibility: this.disableDotnet6Compatibility, configSrc: this.configSrc, - baseUrl: this._unoConfig.uno_app_base + "/", - mainScriptPath: "dotnet.js", + baseUrl: this._unoConfig.uno_app_base, + mainScriptPath: "_framework/dotnet.js", onConfigLoaded: this.onConfigLoaded, onDotnetReady: this.onDotnetReady, onAbort: this.onAbort, exports: ["IDBFS", "FS"].concat(this._unoConfig.emcc_exported_runtime_methods), + onDownloadResourceProgress: (resourcesLoaded: number, totalResources: number) => this.reportDownloadResourceProgress(resourcesLoaded, totalResources), }; } public configure(context: DotnetPublicAPI) { this._context = context; - // Module may not be initialized yet (.NET 8 and later) - (this._context).Module = this._context.Module || {}; - - this.setupRequire(); - this.setupEmscriptenPreRun(); - - // Module is not exposed in the context in net8+ - (globalThis).Module = this._context.Module; - // Required for hot reload (browser-link provided javascript file) (globalThis).BINDING = this._context.BINDING; } @@ -155,16 +158,6 @@ namespace Uno.WebAssembly.Bootstrap { } } - private setupEmscriptenPreRun() { - if (!this._context.preRun) { - this._context.preRun = []; - } - else if (typeof this._context.preRun === "function") { - this._context.preRun = []; - } - (this._context.preRun).push(() => this.wasmRuntimePreRun()); - } - /** * Setup the global require.js library * @@ -178,67 +171,65 @@ namespace Uno.WebAssembly.Bootstrap { } private wasmRuntimePreRun() { - - if (this._unoConfig.environmentVariables) { - for (let key in this._unoConfig.environmentVariables) { - if (this._unoConfig.environmentVariables.hasOwnProperty(key)) { - if (this._monoConfig.debugLevel) console.log(`Setting ${key}=${this._unoConfig.environmentVariables[key]}`); - this._monoConfig.environmentVariables[key] = this._unoConfig.environmentVariables[key]; - } - } - } - - this.timezonePreSetup(); - if (LogProfilerSupport.initializeLogProfiler(this._unoConfig)) { this._logProfiler = new LogProfilerSupport(this._context, this._unoConfig); } } - private timezonePreSetup() { - let timeZone = 'UTC'; - try { - timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; - // eslint-disable-next-line no-empty - } catch { } - this._monoConfig.environmentVariables['TZ'] = timeZone || 'UTC'; - } - private RuntimeReady() { - MonoRuntimeCompatibility.initialize(); - this.configureGlobal(); + this.setupRequire(); this.initializeRequire(); this._aotProfiler = AotProfilerSupport.initialize(this._context, this._unoConfig); - this._logProfiler?.postInitializeLogProfiler(); } private configureGlobal() { var thatGlobal = (globalThis); thatGlobal.config = this._unoConfig; - thatGlobal.MonoRuntime = MonoRuntimeCompatibility; + + // The module instance is modified by the runtime, merge the changes + thatGlobal.Module = this._context.Module; // global exports from emscripten that are not exposed // as .NET is initialized in a module // List of possible exports: https://github.com/emscripten-core/emscripten/blob/c834ef7d69ccb4100239eeba0b0f6573fed063bc/src/modules.js#L391 // Needs to be aligned with exports in https://github.com/unoplatform/Uno.DotnetRuntime.WebAssembly/blob/f7294fe410705bc220e63fc51d44bdffe4093a5d/patches/fix-additional-emscripten-exports.patch#L19 // And in the packager's list of exports. - thatGlobal.lengthBytesUTF8 = (this._context.Module).lengthBytesUTF8; - thatGlobal.stringToUTF8 = (this._context.Module).stringToUTF8; - thatGlobal.UTF8ToString = (this._context.Module).UTF8ToString; - thatGlobal.UTF8ArrayToString = (this._context.Module).UTF8ArrayToString; + let anyModule = this._context.Module; + thatGlobal.lengthBytesUTF8 = anyModule.lengthBytesUTF8; + thatGlobal.UTF8ToString = anyModule.UTF8ToString; + thatGlobal.UTF8ArrayToString = anyModule.UTF8ArrayToString; + + thatGlobal.IDBFS = anyModule.IDBFS; + thatGlobal.FS = anyModule.FS; + + // copy properties from this._unoConfig.emcc_exported_runtime_methods into globalThis + if (this._unoConfig.emcc_exported_runtime_methods) { + this._unoConfig.emcc_exported_runtime_methods.forEach((name: string) => { + thatGlobal[name] = anyModule[name]; + }); + } } // This is called during emscripten `preInit` event, after we fetched config. private configLoaded(config: MonoConfig) { this._monoConfig = config; + if (this._unoConfig.environmentVariables) { + for (let key in this._unoConfig.environmentVariables) { + if (this._unoConfig.environmentVariables.hasOwnProperty(key)) { + if (this._monoConfig.debugLevel) console.log(`Setting ${key}=${this._unoConfig.environmentVariables[key]}`); + this._monoConfig.environmentVariables[key] = this._unoConfig.environmentVariables[key]; + } + } + } + if (this._unoConfig.generate_aot_profile) { this._monoConfig.aotProfilerOptions = { writeAt: "Uno.AotProfilerSupport::StopProfile", - sendTo: "Uno.AotProfilerSupport::DumpAotProfileData" + sendTo: "System.Runtime.InteropServices.JavaScript.JavaScriptExports::DumpAotProfileData" }; } @@ -250,10 +241,6 @@ namespace Uno.WebAssembly.Bootstrap { } } - private runtimeAbort() { - // set_exit_code(1, error); - } - public preInit() { this.body = document.getElementById("uno-body"); @@ -263,6 +250,7 @@ namespace Uno.WebAssembly.Bootstrap { private async mainInit(): Promise { try { this.attachDebuggerHotkey(); + await this.setupHotReload(); if (this._hotReloadSupport) { @@ -290,14 +278,18 @@ namespace Uno.WebAssembly.Bootstrap { } } + private reportDownloadResourceProgress(resourcesLoaded: number, totalResources: number) { + + this.progress.max = totalResources; + (this.progress).value = resourcesLoaded; + } + private initProgress() { this.loader = this.body.querySelector(".uno-loader"); if (this.loader) { this.loader.id = "loading"; - const totalBytesToDownload = this._unoConfig.mono_wasm_runtime_size + this._unoConfig.total_assemblies_size; const progress = this.loader.querySelector("progress"); - progress.max = totalBytesToDownload; (progress).value = ""; // indeterminate this.progress = progress; @@ -371,206 +363,6 @@ namespace Uno.WebAssembly.Bootstrap { } } - private reportProgressWasmLoading(loaded: number) { - if (this.progress) { - this.progress.value = loaded; - } - } - - private reportAssemblyLoading(adding: number) { - if (this.progress) { - this.progress.value += adding; - } - } - - private raiseLoadingError(err: any) { - this.loader.setAttribute("loading-alert", "error"); - - const alert = this.loader.querySelector(".alert"); - - let title = alert.getAttribute("title"); - if (title) { - title += `\n${err}`; - } else { - title = `${err}`; - } - alert.setAttribute("title", title); - } - - private raiseLoadingWarning(msg: string) { - if (this.loader.getAttribute("loading-alert") !== "error") { - this.loader.setAttribute("loading-alert", "warning"); - } - - const alert = this.loader.querySelector(".alert"); - - let title = alert.getAttribute("title"); - if (title) { - title += `\n${msg}`; - } else { - title = `${msg}`; - } - alert.setAttribute("title", title); - } - - private getFetchInit(url: string): RequestInit { - const fileName = url.substring(url.lastIndexOf("/") + 1); - - const init: RequestInit = { credentials: "same-origin" }; - - if (this._unoConfig.files_integrity.hasOwnProperty(fileName)) { - init.integrity = this._unoConfig.files_integrity[fileName]; - } - - return init; - } - - private loadResource(type: WebAssemblyBootResourceType, name: string, defaultUri: string, integrity: string, behavior: AssetBehaviors): - string | Promise | null | undefined { - - if (type == "dotnetjs") { - return defaultUri; - } - - return this.deobfuscateFile(name, this.fetchFile(defaultUri)); - } - - private async deobfuscateFile(asset: string, response: Promise): Promise { - const assemblyFileSuffix = this._unoConfig.assemblyFileNameObfuscationMode !== "NoDots" ? - this._unoConfig.assemblyFileExtension : - this._unoConfig.assemblyFileExtension.replace(".", "_"); - - if (this._unoConfig.assemblyObfuscationKey && asset.endsWith(assemblyFileSuffix)) { - const responseValue = await response; - - if (responseValue) { - var data = new Uint8Array(await responseValue.arrayBuffer()); - var key = this._unoConfig.assemblyObfuscationKey; - - for (var i = 0; i < data.length; i++) { - data[i] ^= key.charCodeAt(i % key.length); - } - - return new Response(data, { "status": 200, headers: responseValue.headers }); - } - } - - return response; - } - - private fetchWithProgress(url: string, progressCallback: Function) : Promise { - - if (!this.loader) { - // No active loader, simply use the fetch API directly... - return fetch(url, this.getFetchInit(url)); - } - - return fetch(url, this.getFetchInit(url)) - .then(response => { - if (!response.ok) { - throw Error(`${response.status} ${response.statusText}`); - } - - try { - let loaded = 0; - - // Wrap original stream with another one, while reporting progress. - const stream = new ReadableStream({ - start(ctl) { - const reader = response.body.getReader(); - - read(); - - function read() { - reader.read() - .then( - ({ done, value }) => { - if (done) { - ctl.close(); - return; - } - loaded += value.byteLength; - progressCallback(loaded, value.byteLength); - ctl.enqueue(value); - read(); - }) - .catch(error => { - console.error(error); - ctl.error(error); - }); - } - } - }); - - // We copy the previous response to keep original headers. - // Not only the WebAssembly will require the right content-type, - // but we also need it for streaming optimizations: - // https://bugs.chromium.org/p/chromium/issues/detail?id=719172#c28 - return new Response(stream, response); - } - catch (ex) { - // ReadableStream may not be supported (Edge as of 42.17134.1.0) - return response; - } - }) - .catch(err => this.raiseLoadingError(err)); - } - - private fetchFile(asset: string) : Promise { - - if (asset.lastIndexOf(".dll") !== -1) { - asset = asset.replace(".dll", this._unoConfig.assemblyFileExtension); - - if (this._unoConfig.assemblyFileNameObfuscationMode == "NoDots") { - asset = asset.replace(/\/([^\/]*)$/, function (match, p1) { - return "/" + p1.replace(/\./g, "_"); - }); - } - } - - if (asset.startsWith("icudt") && asset.endsWith(".dat")) { - asset = `${this._unoConfig.uno_app_base}/${asset}`; - } - - asset = asset.replace("/managed/", `/${this._unoConfig.uno_remote_managedpath}/`); - - if (Bootstrapper.ENVIRONMENT_IS_NODE) { - var fs = require('fs'); - - console.log('Loading... ' + asset); - var binary = fs.readFileSync(asset); - var resolve_func2 = function (resolve: any, reject: any) { - resolve(new Uint8Array(binary)); - }; - var resolve_func1 = function (resolve: any, reject: any) { - var response = { - ok: true, - url: asset, - arrayBuffer: function () { - return new Promise(resolve_func2); - } - }; - resolve(response); - }; - return new Promise(resolve_func1); - } else { - if (!this._unoConfig.enable_debugging) { - // Assembly fetch streaming is disabled during debug, it seems to - // interfere with the ability for mono or the chrome debugger to - // initialize the debugging session properly. Streaming in debug is - // not particularly interesting, so we can skip it. - - const assemblyName = asset.substring(asset.lastIndexOf("/") + 1); - if (this._unoConfig.assemblies_with_size.hasOwnProperty(assemblyName)) { - return this - .fetchWithProgress(asset, (loaded: any, adding: any) => this.reportAssemblyLoading(adding)); - } - } - - return fetch(asset, {credentials: "same-origin"}); - } - } - private isElectron() { return navigator.userAgent.indexOf('Electron') !== -1; } @@ -581,21 +373,21 @@ namespace Uno.WebAssembly.Bootstrap { // But when run with NodeJS or Electron, it's using CommonJS instead of AMD this._isUsingCommonJS = this._unoConfig.uno_shell_mode !== "BrowserEmbedded" && (Bootstrapper.ENVIRONMENT_IS_NODE || this.isElectron()); - if (this._unoConfig.enable_debugging) console.log("Done loading the BCL"); + if (this._unoConfig.uno_enable_tracing) console.log("Done loading the BCL"); if (this._unoConfig.uno_dependencies && this._unoConfig.uno_dependencies.length !== 0) { let pending = this._unoConfig.uno_dependencies.length; const checkDone = (dependency: string) => { --pending; - if (this._unoConfig.enable_debugging) console.log(`Loaded dependency (${dependency}) - remains ${pending} other(s).`); + if (this._unoConfig.uno_enable_tracing) console.log(`Loaded dependency (${dependency}) - remains ${pending} other(s).`); if (pending === 0) { this.mainInit(); } }; this._unoConfig.uno_dependencies.forEach((dependency) => { - if (this._unoConfig.enable_debugging) console.log(`Loading dependency (${dependency})`); + if (this._unoConfig.uno_enable_tracing) console.log(`Loading dependency (${dependency})`); let processDependency = (instance: any) => { @@ -604,7 +396,7 @@ namespace Uno.WebAssembly.Bootstrap { const existingInitializer = instance.onRuntimeInitialized; - if (this._unoConfig.enable_debugging) console.log(`Waiting for dependency (${dependency}) initialization`); + if (this._unoConfig.uno_enable_tracing) console.log(`Waiting for dependency (${dependency}) initialization`); instance.onRuntimeInitialized = () => { checkDone(dependency); @@ -649,7 +441,7 @@ namespace Uno.WebAssembly.Bootstrap { } private hasDebuggingEnabled() { - return this._hasReferencedPdbs && this._currentBrowserIsChrome; + return this._unoConfig.uno_debugging_enabled && this._currentBrowserIsChrome; } private attachDebuggerHotkey() { diff --git a/src/Uno.Wasm.Bootstrap/ts/Uno/WebAssembly/MonoRuntimeCompatibility.ts b/src/Uno.Wasm.Bootstrap/ts/Uno/WebAssembly/MonoRuntimeCompatibility.ts deleted file mode 100644 index 3c2e37046..000000000 --- a/src/Uno.Wasm.Bootstrap/ts/Uno/WebAssembly/MonoRuntimeCompatibility.ts +++ /dev/null @@ -1,63 +0,0 @@ -/// -/// -/// -/// - -namespace Uno.WebAssembly.Bootstrap { - - /** - * This block is present for backward compatibility when "MonoRuntime" was provided by mono-wasm. - * */ - export class MonoRuntimeCompatibility { - static load_runtime: any; - static assembly_load: any; - static find_class: any; - static find_method: any; - static invoke_method: any; - static mono_string_get_utf8: any; - static mono_wasm_obj_array_new: any; - static mono_string: any; - static mono_wasm_obj_array_set: any; - - public static initialize() { - MonoRuntimeCompatibility.load_runtime = Module.cwrap("mono_wasm_load_runtime", null, ["string", "number"]); - MonoRuntimeCompatibility.assembly_load = Module.cwrap("mono_wasm_assembly_load", "number", ["string"]); - MonoRuntimeCompatibility.find_class = Module.cwrap("mono_wasm_assembly_find_class", "number", ["number", "string", "string"]); - MonoRuntimeCompatibility.find_method = Module.cwrap("mono_wasm_assembly_find_method", "number", ["number", "string", "number"]); - MonoRuntimeCompatibility.invoke_method = Module.cwrap("mono_wasm_invoke_method", "number", ["number", "number", "number"]); - MonoRuntimeCompatibility.mono_string_get_utf8 = Module.cwrap("mono_wasm_string_get_utf8", "number", ["number"]); - MonoRuntimeCompatibility.mono_string = Module.cwrap("mono_wasm_string_from_js", "number", ["string"]); - MonoRuntimeCompatibility.mono_wasm_obj_array_new = Module.cwrap("mono_wasm_obj_array_new", "number", ["number"]); - MonoRuntimeCompatibility.mono_wasm_obj_array_set = Module.cwrap("mono_wasm_obj_array_set", null, ["number", "number", "number"]); - } - - public static conv_string(mono_obj: any) { - if (mono_obj === 0) - return null; - - return BINDING.conv_string(mono_obj); - } - - public static call_method(method: any, this_arg: any, args: any) { - const args_mem = Module._malloc(args.length * 4); - const eh_throw = Module._malloc(4); - for (let i = 0; i < args.length; ++i) - Module.setValue(args_mem + i * 4, args[i], "i32"); - Module.setValue(eh_throw, 0, "i32"); - - const res = MonoRuntimeCompatibility.invoke_method(method, this_arg, args_mem, eh_throw); - - const eh_res = Module.getValue(eh_throw, "i32"); - - Module._free(args_mem); - Module._free(eh_throw); - - if (eh_res !== 0) { - const msg = MonoRuntimeCompatibility.conv_string(res); - throw new Error(msg); - } - - return res; - } - } -} diff --git a/src/Uno.Wasm.Bootstrap/ts/Uno/WebAssembly/UnoConfig.ts b/src/Uno.Wasm.Bootstrap/ts/Uno/WebAssembly/UnoConfig.ts index b430198f0..786b0cb9d 100644 --- a/src/Uno.Wasm.Bootstrap/ts/Uno/WebAssembly/UnoConfig.ts +++ b/src/Uno.Wasm.Bootstrap/ts/Uno/WebAssembly/UnoConfig.ts @@ -13,20 +13,6 @@ assemblyFileNameObfuscationMode: string; - mono_wasm_runtime: string; - - mono_wasm_runtime_size?: number; - - assemblies_with_size?: { - [i: string]: number; - }; - - files_integrity?: { - [i: string]: string; - }; - - total_assemblies_size?: number; - enable_pwa: boolean; offline_files: string[]; @@ -40,8 +26,13 @@ }; generate_aot_profile?: boolean; - enable_debugging?: boolean; - - assemblyObfuscationKey?: string; + + uno_enable_tracing?: boolean; + + uno_debugging_enabled?: boolean; + + uno_runtime_options?: string[]; + + uno_load_all_satellite_resources?: string[]; } } diff --git a/src/Uno.Wasm.Embedded.App/Uno.Wasm.Embedded.App.csproj b/src/Uno.Wasm.Embedded.App/Uno.Wasm.Embedded.App.csproj index ba233ed31..c82dd4910 100644 --- a/src/Uno.Wasm.Embedded.App/Uno.Wasm.Embedded.App.csproj +++ b/src/Uno.Wasm.Embedded.App/Uno.Wasm.Embedded.App.csproj @@ -1,7 +1,7 @@ - + - net6.0 + net9.0 Exe false Uno.Wasm.Sample.Program @@ -13,7 +13,6 @@ - diff --git a/src/Uno.Wasm.HttpRequestMessageExtensions/Uno.Wasm.HttpRequestMessageExtensions.csproj b/src/Uno.Wasm.HttpRequestMessageExtensions/Uno.Wasm.HttpRequestMessageExtensions.csproj index 44335e4d7..c41bdd168 100644 --- a/src/Uno.Wasm.HttpRequestMessageExtensions/Uno.Wasm.HttpRequestMessageExtensions.csproj +++ b/src/Uno.Wasm.HttpRequestMessageExtensions/Uno.Wasm.HttpRequestMessageExtensions.csproj @@ -5,7 +5,6 @@ 1701;1702;1705;649 Uno.Wasm.HttpRequestMessageExtensions true - 11.0 diff --git a/src/Uno.Wasm.MetadataUpdater/Runtime.cs b/src/Uno.Wasm.MetadataUpdater/Runtime.cs index 4ef0a2268..245943fa0 100644 --- a/src/Uno.Wasm.MetadataUpdater/Runtime.cs +++ b/src/Uno.Wasm.MetadataUpdater/Runtime.cs @@ -1,50 +1,23 @@ using System; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Runtime.InteropServices.JavaScript; namespace WebAssembly { internal sealed class Runtime { - /// - /// Mono specific internal call. - /// - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern string InvokeJS(string str, out int exceptional_result); - - // Disable inlining to avoid the interpreter to evaluate an internal call that may not be available - [MethodImpl(MethodImplOptions.NoInlining)] - private static string MonoInvokeJS(string str, out int exceptionResult) => InvokeJS(str, out exceptionResult); - - // Disable inlining to avoid the interpreter to evaluate an internal call that may not be available - [MethodImpl(MethodImplOptions.NoInlining)] - private static string NetCoreInvokeJS(string str, out int exceptionResult) - => Interop.Runtime.InvokeJS(str, out exceptionResult); - /// /// Invokes Javascript code in the hosting environment /// internal static string InvokeJS(string str) - { - var r = IsNetCore - ? NetCoreInvokeJS(str, out var exceptionResult) - : MonoInvokeJS(str, out exceptionResult); - - if (exceptionResult != 0) - { - Console.Error.WriteLine($"Error #{exceptionResult} \"{r}\" executing javascript: \"{str}\""); - } - return r; - } - - internal static bool IsNetCore { get; } = Type.GetType("System.Runtime.Loader.AssemblyLoadContext") != null; + => Interop.InvokeJS(str); } -} -internal sealed class Interop -{ - internal sealed class Runtime + internal static partial class Interop { - [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern string InvokeJS(string str, out int exceptional_result); + [JSImport("globalThis.Uno.WebAssembly.Bootstrap.Bootstrapper.invokeJS")] + public static partial string InvokeJS(string value); } } diff --git a/src/Uno.Wasm.MixedModeRoslynSample/Uno.Wasm.MixedModeRoslynSample.csproj b/src/Uno.Wasm.MixedModeRoslynSample/Uno.Wasm.MixedModeRoslynSample.csproj index 34b8ac7fc..db3be73d1 100644 --- a/src/Uno.Wasm.MixedModeRoslynSample/Uno.Wasm.MixedModeRoslynSample.csproj +++ b/src/Uno.Wasm.MixedModeRoslynSample/Uno.Wasm.MixedModeRoslynSample.csproj @@ -1,7 +1,7 @@ - + - net5.0 + net9.0 Exe false Uno.Wasm.Sample.Program @@ -23,8 +23,8 @@ + - diff --git a/src/Uno.Wasm.MixedModeSample/Uno.Wasm.MixedModeSample.csproj b/src/Uno.Wasm.MixedModeSample/Uno.Wasm.MixedModeSample.csproj index 1251e1073..5331fcf43 100644 --- a/src/Uno.Wasm.MixedModeSample/Uno.Wasm.MixedModeSample.csproj +++ b/src/Uno.Wasm.MixedModeSample/Uno.Wasm.MixedModeSample.csproj @@ -1,7 +1,7 @@ - + - net5.0 + net9.0 Exe false Uno.Wasm.Sample.Program @@ -19,8 +19,8 @@ + - diff --git a/src/Uno.Wasm.Node.Sample/Uno.Wasm.Node.Sample.csproj b/src/Uno.Wasm.Node.Sample/Uno.Wasm.Node.Sample.csproj index 84d18b8cb..7490f2c17 100644 --- a/src/Uno.Wasm.Node.Sample/Uno.Wasm.Node.Sample.csproj +++ b/src/Uno.Wasm.Node.Sample/Uno.Wasm.Node.Sample.csproj @@ -1,7 +1,7 @@ - + - net5.0 + net9.0 Exe false true @@ -14,8 +14,8 @@ + - @@ -43,15 +43,5 @@ true TargetFramework - - false - true - TargetFramework - - - false - true - TargetFramework - diff --git a/src/Uno.Wasm.Packager/CapturingAssemblyResolver.cs b/src/Uno.Wasm.Packager/CapturingAssemblyResolver.cs deleted file mode 100644 index 5d45f9776..000000000 --- a/src/Uno.Wasm.Packager/CapturingAssemblyResolver.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Mono.Cecil; - -/// -/// An IAssemblyResolver which assumes the files list will not change, to perform faster lookups. -/// -class CapturingAssemblyResolver : DefaultAssemblyResolver -{ - private List> _files; - private List _assembly_references; - - public CapturingAssemblyResolver(List assembly_references) - { - _assembly_references = assembly_references; - } - - protected override AssemblyDefinition SearchDirectory(AssemblyNameReference name, IEnumerable directories, ReaderParameters parameters) - { - if (_files == null) - { - // Create a cache of the files found in search directories to avoid - // paying the cost of File.Exists - - _files = new List>(); - - // Fill all the known references first, so they get resolved - // using compilation paths. - var explicitAssembliesPaths = new Dictionary(); - foreach (var asmReferencePath in _assembly_references) - { - if (Path.GetFileNameWithoutExtension(asmReferencePath) is { } asmName) - { - if (!explicitAssembliesPaths.ContainsKey(asmName)) - { - explicitAssembliesPaths.Add(asmName, asmReferencePath); - } - } - } - - _files.Add(explicitAssembliesPaths); - - // Use all other search paths - string[] extensions = new[] { ".winmd", ".dll", ".exe", ".dll" }; - - foreach (var directory in directories.Where(Directory.Exists)) - { - var map = new Dictionary(); - - foreach (var file in Directory.GetFiles(directory)) - { - if (extensions.Any(e => file.EndsWith(e, StringComparison.OrdinalIgnoreCase))) - { - if (Path.GetFileNameWithoutExtension(file) is { } asmName) - { - if (!map.ContainsKey(asmName)) - { - map.Add(asmName, file); - } - } - } - } - - _files.Add(map); - } - } - - foreach (var directory in _files) - { - if (directory.TryGetValue(name.Name, out var filePath)) - { - try - { - return GetAssembly(filePath, parameters); - } - catch (System.BadImageFormatException) - { - continue; - } - } - } - - return null; - } - - AssemblyDefinition GetAssembly(string file, ReaderParameters parameters) - { - if (parameters.AssemblyResolver == null) - { - parameters.AssemblyResolver = this; - } - - return ModuleDefinition.ReadModule(file, parameters).Assembly; - } -} diff --git a/src/Uno.Wasm.Packager/Mono.Cecil.dll b/src/Uno.Wasm.Packager/Mono.Cecil.dll deleted file mode 100644 index 1a0b93a20..000000000 Binary files a/src/Uno.Wasm.Packager/Mono.Cecil.dll and /dev/null differ diff --git a/src/Uno.Wasm.Packager/Options.cs b/src/Uno.Wasm.Packager/Options.cs deleted file mode 100644 index 4c8f670ab..000000000 --- a/src/Uno.Wasm.Packager/Options.cs +++ /dev/null @@ -1,2006 +0,0 @@ -// -// Options.cs -// -// Authors: -// Jonathan Pryor , -// Federico Di Gregorio -// Rolf Bjarne Kvinge -// -// Copyright (C) 2008 Novell (http://www.novell.com) -// Copyright (C) 2009 Federico Di Gregorio. -// Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com) -// Copyright (C) 2017 Microsoft Corporation (http://www.microsoft.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -// Compile With: -// mcs -debug+ -r:System.Core Options.cs -o:Mono.Options.dll -t:library -// mcs -debug+ -d:LINQ -r:System.Core Options.cs -o:Mono.Options.dll -t:library -// -// The LINQ version just changes the implementation of -// OptionSet.Parse(IEnumerable), and confers no semantic changes. - -// -// A Getopt::Long-inspired option parsing library for C#. -// -// Mono.Options.OptionSet is built upon a key/value table, where the -// key is a option format string and the value is a delegate that is -// invoked when the format string is matched. -// -// Option format strings: -// Regex-like BNF Grammar: -// name: .+ -// type: [=:] -// sep: ( [^{}]+ | '{' .+ '}' )? -// aliases: ( name type sep ) ( '|' name type sep )* -// -// Each '|'-delimited name is an alias for the associated action. If the -// format string ends in a '=', it has a required value. If the format -// string ends in a ':', it has an optional value. If neither '=' or ':' -// is present, no value is supported. `=' or `:' need only be defined on one -// alias, but if they are provided on more than one they must be consistent. -// -// Each alias portion may also end with a "key/value separator", which is used -// to split option values if the option accepts > 1 value. If not specified, -// it defaults to '=' and ':'. If specified, it can be any character except -// '{' and '}' OR the *string* between '{' and '}'. If no separator should be -// used (i.e. the separate values should be distinct arguments), then "{}" -// should be used as the separator. -// -// Options are extracted either from the current option by looking for -// the option name followed by an '=' or ':', or is taken from the -// following option IFF: -// - The current option does not contain a '=' or a ':' -// - The current option requires a value (i.e. not a Option type of ':') -// -// The `name' used in the option format string does NOT include any leading -// option indicator, such as '-', '--', or '/'. All three of these are -// permitted/required on any named option. -// -// Option bundling is permitted so long as: -// - '-' is used to start the option group -// - all of the bundled options are a single character -// - at most one of the bundled options accepts a value, and the value -// provided starts from the next character to the end of the string. -// -// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' -// as '-Dname=value'. -// -// Option processing is disabled by specifying "--". All options after "--" -// are returned by OptionSet.Parse() unchanged and unprocessed. -// -// Unprocessed options are returned from OptionSet.Parse(). -// -// Examples: -// int verbose = 0; -// OptionSet p = new OptionSet () -// .Add ("v", v => ++verbose) -// .Add ("name=|value=", v => Console.WriteLine (v)); -// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); -// -// The above would parse the argument string array, and would invoke the -// lambda expression three times, setting `verbose' to 3 when complete. -// It would also print out "A" and "B" to standard output. -// The returned array would contain the string "extra". -// -// C# 3.0 collection initializers are supported and encouraged: -// var p = new OptionSet () { -// { "h|?|help", v => ShowHelp () }, -// }; -// -// System.ComponentModel.TypeConverter is also supported, allowing the use of -// custom data types in the callback type; TypeConverter.ConvertFromString() -// is used to convert the value option to an instance of the specified -// type: -// -// var p = new OptionSet () { -// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, -// }; -// -// Random other tidbits: -// - Boolean options (those w/o '=' or ':' in the option format string) -// are explicitly enabled if they are followed with '+', and explicitly -// disabled if they are followed with '-': -// string a = null; -// var p = new OptionSet () { -// { "a", s => a = s }, -// }; -// p.Parse (new string[]{"-a"}); // sets v != null -// p.Parse (new string[]{"-a+"}); // sets v != null -// p.Parse (new string[]{"-a-"}); // sets v == null -// - -// -// Mono.Options.CommandSet allows easily having separate commands and -// associated command options, allowing creation of a *suite* along the -// lines of **git**(1), **svn**(1), etc. -// -// CommandSet allows intermixing plain text strings for `--help` output, -// Option values -- as supported by OptionSet -- and Command instances, -// which have a name, optional help text, and an optional OptionSet. -// -// var suite = new CommandSet ("suite-name") { -// // Use strings and option values, as with OptionSet -// "usage: suite-name COMMAND [OPTIONS]+", -// { "v:", "verbosity", (int? v) => Verbosity = v.HasValue ? v.Value : Verbosity+1 }, -// // Commands may also be specified -// new Command ("command-name", "command help") { -// Options = new OptionSet {/*...*/}, -// Run = args => { /*...*/}, -// }, -// new MyCommandSubclass (), -// }; -// return suite.Run (new string[]{...}); -// -// CommandSet provides a `help` command, and forwards `help COMMAND` -// to the registered Command instance by invoking Command.Invoke() -// with `--help` as an option. -// - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Globalization; -using System.IO; -#if PCL -using System.Reflection; -#else -using System.Runtime.Serialization; -using System.Security.Permissions; -#endif -using System.Text; -using System.Text.RegularExpressions; - -#if LINQ -using System.Linq; -#endif - -#if TEST -using NDesk.Options; -#endif - -#if PCL -using MessageLocalizerConverter = System.Func; -#else -using MessageLocalizerConverter = System.Converter; -#endif - -#if NDESK_OPTIONS -namespace NDesk.Options -#else -namespace Mono.Options -#endif -{ - static class StringCoda { - - public static IEnumerable WrappedLines (string self, params int[] widths) - { - IEnumerable w = widths; - return WrappedLines (self, w); - } - - public static IEnumerable WrappedLines (string self, IEnumerable widths) - { - if (widths == null) - throw new ArgumentNullException ("widths"); - return CreateWrappedLinesIterator (self, widths); - } - - private static IEnumerable CreateWrappedLinesIterator (string self, IEnumerable widths) - { - if (string.IsNullOrEmpty (self)) { - yield return string.Empty; - yield break; - } - using (IEnumerator ewidths = widths.GetEnumerator ()) { - bool? hw = null; - int width = GetNextWidth (ewidths, int.MaxValue, ref hw); - int start = 0, end; - do { - end = GetLineEnd (start, width, self); - // endCorrection is 1 if the line end is '\n', and might be 2 if the line end is '\r\n'. - int endCorrection = 1; - if (end >= 2 && self.Substring (end - 2, 2).Equals ("\r\n")) - endCorrection = 2; - char c = self [end - endCorrection]; - if (char.IsWhiteSpace (c)) - end -= endCorrection; - bool needContinuation = end != self.Length && !IsEolChar (c); - string continuation = ""; - if (needContinuation) { - --end; - continuation = "-"; - } - string line = self.Substring (start, end - start) + continuation; - yield return line; - start = end; - if (char.IsWhiteSpace (c)) - start += endCorrection; - width = GetNextWidth (ewidths, width, ref hw); - } while (start < self.Length); - } - } - - private static int GetNextWidth (IEnumerator ewidths, int curWidth, ref bool? eValid) - { - if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) { - curWidth = (eValid = ewidths.MoveNext ()).Value ? ewidths.Current : curWidth; - // '.' is any character, - is for a continuation - const string minWidth = ".-"; - if (curWidth < minWidth.Length) - throw new ArgumentOutOfRangeException ("widths", - string.Format ("Element must be >= {0}, was {1}.", minWidth.Length, curWidth)); - return curWidth; - } - // no more elements, use the last element. - return curWidth; - } - - private static bool IsEolChar (char c) - { - return !char.IsLetterOrDigit (c); - } - - private static int GetLineEnd (int start, int length, string description) - { - int end = System.Math.Min (start + length, description.Length); - int sep = -1; - for (int i = start; i < end; ++i) { - if (i + 2 <= description.Length && description.Substring (i, 2).Equals ("\r\n")) - return i+2; - if (description [i] == '\n') - return i+1; - if (IsEolChar (description [i])) - sep = i+1; - } - if (sep == -1 || end == description.Length) - return end; - return sep; - } - } - - public class OptionValueCollection : IList, IList { - - List values = new List (); - OptionContext c; - - internal OptionValueCollection (OptionContext c) - { - this.c = c; - } - - #region ICollection - void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);} - bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}} - object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}} - #endregion - - #region ICollection - public void Add (string item) {values.Add (item);} - public void Clear () {values.Clear ();} - public bool Contains (string item) {return values.Contains (item);} - public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);} - public bool Remove (string item) {return values.Remove (item);} - public int Count {get {return values.Count;}} - public bool IsReadOnly {get {return false;}} - #endregion - - #region IEnumerable - IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();} - #endregion - - #region IEnumerable - public IEnumerator GetEnumerator () {return values.GetEnumerator ();} - #endregion - - #region IList - int IList.Add (object value) {return (values as IList).Add (value);} - bool IList.Contains (object value) {return (values as IList).Contains (value);} - int IList.IndexOf (object value) {return (values as IList).IndexOf (value);} - void IList.Insert (int index, object value) {(values as IList).Insert (index, value);} - void IList.Remove (object value) {(values as IList).Remove (value);} - void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);} - bool IList.IsFixedSize {get {return false;}} - object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}} - #endregion - - #region IList - public int IndexOf (string item) {return values.IndexOf (item);} - public void Insert (int index, string item) {values.Insert (index, item);} - public void RemoveAt (int index) {values.RemoveAt (index);} - - private void AssertValid (int index) - { - if (c.Option == null) - throw new InvalidOperationException ("OptionContext.Option is null."); - if (index >= c.Option.MaxValueCount) - throw new ArgumentOutOfRangeException ("index"); - if (c.Option.OptionValueType == OptionValueType.Required && - index >= values.Count) - throw new OptionException (string.Format ( - c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), - c.OptionName); - } - - public string this [int index] { - get { - AssertValid (index); - return index >= values.Count ? null : values [index]; - } - set { - values [index] = value; - } - } - #endregion - - public List ToList () - { - return new List (values); - } - - public string[] ToArray () - { - return values.ToArray (); - } - - public override string ToString () - { - return string.Join (", ", values.ToArray ()); - } - } - - public class OptionContext { - private Option option; - private string name; - private int index; - private OptionSet set; - private OptionValueCollection c; - - public OptionContext (OptionSet set) - { - this.set = set; - this.c = new OptionValueCollection (this); - } - - public Option Option { - get {return option;} - set {option = value;} - } - - public string OptionName { - get {return name;} - set {name = value;} - } - - public int OptionIndex { - get {return index;} - set {index = value;} - } - - public OptionSet OptionSet { - get {return set;} - } - - public OptionValueCollection OptionValues { - get {return c;} - } - } - - public enum OptionValueType { - None, - Optional, - Required, - } - - public abstract class Option { - string prototype, description; - string[] names; - OptionValueType type; - int count; - string[] separators; - bool hidden; - - protected Option (string prototype, string description) - : this (prototype, description, 1, false) - { - } - - protected Option (string prototype, string description, int maxValueCount) - : this (prototype, description, maxValueCount, false) - { - } - - protected Option (string prototype, string description, int maxValueCount, bool hidden) - { - if (prototype == null) - throw new ArgumentNullException ("prototype"); - if (prototype.Length == 0) - throw new ArgumentException ("Cannot be the empty string.", "prototype"); - if (maxValueCount < 0) - throw new ArgumentOutOfRangeException ("maxValueCount"); - - this.prototype = prototype; - this.description = description; - this.count = maxValueCount; - this.names = (this is OptionSet.Category) - // append GetHashCode() so that "duplicate" categories have distinct - // names, e.g. adding multiple "" categories should be valid. - ? new[]{prototype + this.GetHashCode ()} - : prototype.Split ('|'); - - if (this is OptionSet.Category || this is CommandOption) - return; - - this.type = ParsePrototype (); - this.hidden = hidden; - - if (this.count == 0 && type != OptionValueType.None) - throw new ArgumentException ( - "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + - "OptionValueType.Optional.", - "maxValueCount"); - if (this.type == OptionValueType.None && maxValueCount > 1) - throw new ArgumentException ( - string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), - "maxValueCount"); - if (Array.IndexOf (names, "<>") >= 0 && - ((names.Length == 1 && this.type != OptionValueType.None) || - (names.Length > 1 && this.MaxValueCount > 1))) - throw new ArgumentException ( - "The default option handler '<>' cannot require values.", - "prototype"); - } - - public string Prototype {get {return prototype;}} - public string Description {get {return description;}} - public OptionValueType OptionValueType {get {return type;}} - public int MaxValueCount {get {return count;}} - public bool Hidden {get {return hidden;}} - - public string[] GetNames () - { - return (string[]) names.Clone (); - } - - public string[] GetValueSeparators () - { - if (separators == null) - return new string [0]; - return (string[]) separators.Clone (); - } - - protected static T Parse (string value, OptionContext c) - { - Type tt = typeof (T); -#if PCL - TypeInfo ti = tt.GetTypeInfo (); -#else - Type ti = tt; -#endif - bool nullable = - ti.IsValueType && - ti.IsGenericType && - !ti.IsGenericTypeDefinition && - ti.GetGenericTypeDefinition () == typeof (Nullable<>); -#if PCL - Type targetType = nullable ? tt.GenericTypeArguments [0] : tt; -#else - Type targetType = nullable ? tt.GetGenericArguments () [0] : tt; -#endif - T t = default (T); - try { - if (value != null) { -#if PCL - if (targetType.GetTypeInfo ().IsEnum) - t = (T) Enum.Parse (targetType, value, true); - else - t = (T) Convert.ChangeType (value, targetType); -#else - TypeConverter conv = TypeDescriptor.GetConverter (targetType); - t = (T) conv.ConvertFromString (value); -#endif - } - } - catch (Exception e) { - throw new OptionException ( - string.Format ( - c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."), - value, targetType.Name, c.OptionName), - c.OptionName, e); - } - return t; - } - - internal string[] Names {get {return names;}} - internal string[] ValueSeparators {get {return separators;}} - - static readonly char[] NameTerminator = new char[]{'=', ':'}; - - private OptionValueType ParsePrototype () - { - char type = '\0'; - List seps = new List (); - for (int i = 0; i < names.Length; ++i) { - string name = names [i]; - if (name.Length == 0) - throw new ArgumentException ("Empty option names are not supported.", "prototype"); - - int end = name.IndexOfAny (NameTerminator); - if (end == -1) - continue; - names [i] = name.Substring (0, end); - if (type == '\0' || type == name [end]) - type = name [end]; - else - throw new ArgumentException ( - string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]), - "prototype"); - AddSeparators (name, end, seps); - } - - if (type == '\0') - return OptionValueType.None; - - if (count <= 1 && seps.Count != 0) - throw new ArgumentException ( - string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count), - "prototype"); - if (count > 1) { - if (seps.Count == 0) - this.separators = new string[]{":", "="}; - else if (seps.Count == 1 && seps [0].Length == 0) - this.separators = null; - else - this.separators = seps.ToArray (); - } - - return type == '=' ? OptionValueType.Required : OptionValueType.Optional; - } - - private static void AddSeparators (string name, int end, ICollection seps) - { - int start = -1; - for (int i = end+1; i < name.Length; ++i) { - switch (name [i]) { - case '{': - if (start != -1) - throw new ArgumentException ( - string.Format ("Ill-formed name/value separator found in \"{0}\".", name), - "prototype"); - start = i+1; - break; - case '}': - if (start == -1) - throw new ArgumentException ( - string.Format ("Ill-formed name/value separator found in \"{0}\".", name), - "prototype"); - seps.Add (name.Substring (start, i-start)); - start = -1; - break; - default: - if (start == -1) - seps.Add (name [i].ToString ()); - break; - } - } - if (start != -1) - throw new ArgumentException ( - string.Format ("Ill-formed name/value separator found in \"{0}\".", name), - "prototype"); - } - - public void Invoke (OptionContext c) - { - OnParseComplete (c); - c.OptionName = null; - c.Option = null; - c.OptionValues.Clear (); - } - - protected abstract void OnParseComplete (OptionContext c); - - internal void InvokeOnParseComplete (OptionContext c) - { - OnParseComplete (c); - } - - public override string ToString () - { - return Prototype; - } - } - - public abstract class ArgumentSource { - - protected ArgumentSource () - { - } - - public abstract string[] GetNames (); - public abstract string Description { get; } - public abstract bool GetArguments (string value, out IEnumerable replacement); - -#if !PCL || NETSTANDARD1_3 - public static IEnumerable GetArgumentsFromFile (string file) - { - return GetArguments (File.OpenText (file), true); - } -#endif - - public static IEnumerable GetArguments (TextReader reader) - { - return GetArguments (reader, false); - } - - // Cribbed from mcs/driver.cs:LoadArgs(string) - static IEnumerable GetArguments (TextReader reader, bool close) - { - try { - StringBuilder arg = new StringBuilder (); - - string line; - while ((line = reader.ReadLine ()) != null) { - int t = line.Length; - - for (int i = 0; i < t; i++) { - char c = line [i]; - - if (c == '"' || c == '\'') { - char end = c; - - for (i++; i < t; i++){ - c = line [i]; - - if (c == end) - break; - arg.Append (c); - } - } else if (c == ' ') { - if (arg.Length > 0) { - yield return arg.ToString (); - arg.Length = 0; - } - } else - arg.Append (c); - } - if (arg.Length > 0) { - yield return arg.ToString (); - arg.Length = 0; - } - } - } - finally { - if (close) - reader.Dispose (); - } - } - } - -#if !PCL || NETSTANDARD1_3 - public class ResponseFileSource : ArgumentSource { - - public override string[] GetNames () - { - return new string[]{"@file"}; - } - - public override string Description { - get {return "Read response file for more options.";} - } - - public override bool GetArguments (string value, out IEnumerable replacement) - { - if (string.IsNullOrEmpty (value) || !value.StartsWith ("@")) { - replacement = null; - return false; - } - replacement = ArgumentSource.GetArgumentsFromFile (value.Substring (1)); - return true; - } - } -#endif - -#if !PCL - [Serializable] -#endif - public class OptionException : Exception { - private string option; - - public OptionException () - { - } - - public OptionException (string message, string optionName) - : base (message) - { - this.option = optionName; - } - - public OptionException (string message, string optionName, Exception innerException) - : base (message, innerException) - { - this.option = optionName; - } - -#if !PCL - protected OptionException (SerializationInfo info, StreamingContext context) - : base (info, context) - { - this.option = info.GetString ("OptionName"); - } -#endif - - public string OptionName { - get {return this.option;} - } - -#if !PCL -#pragma warning disable SYSLIB0003 // Type or member is obsolete - [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)] -#pragma warning restore SYSLIB0003 // Type or member is obsolete - public override void GetObjectData (SerializationInfo info, StreamingContext context) - { - base.GetObjectData (info, context); - info.AddValue ("OptionName", option); - } -#endif - } - - public delegate void OptionAction (TKey key, TValue value); - - public class OptionSet : KeyedCollection - { - public OptionSet () - : this (null) - { - } - - public OptionSet (MessageLocalizerConverter localizer) - { - this.roSources = new ReadOnlyCollection (sources); - this.localizer = localizer; - if (this.localizer == null) { - this.localizer = delegate (string f) { - return f; - }; - } - } - - MessageLocalizerConverter localizer; - - public MessageLocalizerConverter MessageLocalizer { - get {return localizer;} - internal set {localizer = value;} - } - - List sources = new List (); - ReadOnlyCollection roSources; - - public ReadOnlyCollection ArgumentSources { - get {return roSources;} - } - - - protected override string GetKeyForItem (Option item) - { - if (item == null) - throw new ArgumentNullException ("option"); - if (item.Names != null && item.Names.Length > 0) - return item.Names [0]; - // This should never happen, as it's invalid for Option to be - // constructed w/o any names. - throw new InvalidOperationException ("Option has no names!"); - } - - [Obsolete ("Use KeyedCollection.this[string]")] - protected Option GetOptionForName (string option) - { - if (option == null) - throw new ArgumentNullException ("option"); - try { - return base [option]; - } - catch (KeyNotFoundException) { - return null; - } - } - - protected override void InsertItem (int index, Option item) - { - base.InsertItem (index, item); - AddImpl (item); - } - - protected override void RemoveItem (int index) - { - Option p = Items [index]; - base.RemoveItem (index); - // KeyedCollection.RemoveItem() handles the 0th item - for (int i = 1; i < p.Names.Length; ++i) { - Dictionary.Remove (p.Names [i]); - } - } - - protected override void SetItem (int index, Option item) - { - base.SetItem (index, item); - AddImpl (item); - } - - private void AddImpl (Option option) - { - if (option == null) - throw new ArgumentNullException ("option"); - List added = new List (option.Names.Length); - try { - // KeyedCollection.InsertItem/SetItem handle the 0th name. - for (int i = 1; i < option.Names.Length; ++i) { - Dictionary.Add (option.Names [i], option); - added.Add (option.Names [i]); - } - } - catch (Exception) { - foreach (string name in added) - Dictionary.Remove (name); - throw; - } - } - - public OptionSet Add (string header) - { - if (header == null) - throw new ArgumentNullException ("header"); - Add (new Category (header)); - return this; - } - - internal sealed class Category : Option { - - // Prototype starts with '=' because this is an invalid prototype - // (see Option.ParsePrototype(), and thus it'll prevent Category - // instances from being accidentally used as normal options. - public Category (string description) - : base ("=:Category:= " + description, description) - { - } - - protected override void OnParseComplete (OptionContext c) - { - throw new NotSupportedException ("Category.OnParseComplete should not be invoked."); - } - } - - - public new OptionSet Add (Option option) - { - base.Add (option); - return this; - } - - sealed class ActionOption : Option { - Action action; - - public ActionOption (string prototype, string description, int count, Action action) - : this (prototype, description, count, action, false) - { - } - - public ActionOption (string prototype, string description, int count, Action action, bool hidden) - : base (prototype, description, count, hidden) - { - if (action == null) - throw new ArgumentNullException ("action"); - this.action = action; - } - - protected override void OnParseComplete (OptionContext c) - { - action (c.OptionValues); - } - } - - public OptionSet Add (string prototype, Action action) - { - return Add (prototype, null, action); - } - - public OptionSet Add (string prototype, string description, Action action) - { - return Add (prototype, description, action, false); - } - - public OptionSet Add (string prototype, string description, Action action, bool hidden) - { - if (action == null) - throw new ArgumentNullException ("action"); - Option p = new ActionOption (prototype, description, 1, - delegate (OptionValueCollection v) { action (v [0]); }, hidden); - base.Add (p); - return this; - } - - public OptionSet Add (string prototype, OptionAction action) - { - return Add (prototype, null, action); - } - - public OptionSet Add (string prototype, string description, OptionAction action) - { - return Add (prototype, description, action, false); - } - - public OptionSet Add (string prototype, string description, OptionAction action, bool hidden) { - if (action == null) - throw new ArgumentNullException ("action"); - Option p = new ActionOption (prototype, description, 2, - delegate (OptionValueCollection v) {action (v [0], v [1]);}, hidden); - base.Add (p); - return this; - } - - sealed class ActionOption : Option { - Action action; - - public ActionOption (string prototype, string description, Action action) - : base (prototype, description, 1) - { - if (action == null) - throw new ArgumentNullException ("action"); - this.action = action; - } - - protected override void OnParseComplete (OptionContext c) - { - action (Parse (c.OptionValues [0], c)); - } - } - - sealed class ActionOption : Option { - OptionAction action; - - public ActionOption (string prototype, string description, OptionAction action) - : base (prototype, description, 2) - { - if (action == null) - throw new ArgumentNullException ("action"); - this.action = action; - } - - protected override void OnParseComplete (OptionContext c) - { - action ( - Parse (c.OptionValues [0], c), - Parse (c.OptionValues [1], c)); - } - } - - public OptionSet Add (string prototype, Action action) - { - return Add (prototype, null, action); - } - - public OptionSet Add (string prototype, string description, Action action) - { - return Add (new ActionOption (prototype, description, action)); - } - - public OptionSet Add (string prototype, OptionAction action) - { - return Add (prototype, null, action); - } - - public OptionSet Add (string prototype, string description, OptionAction action) - { - return Add (new ActionOption (prototype, description, action)); - } - - public OptionSet Add (ArgumentSource source) - { - if (source == null) - throw new ArgumentNullException ("source"); - sources.Add (source); - return this; - } - - protected virtual OptionContext CreateOptionContext () - { - return new OptionContext (this); - } - - public List Parse (IEnumerable arguments) - { - if (arguments == null) - throw new ArgumentNullException ("arguments"); - OptionContext c = CreateOptionContext (); - c.OptionIndex = -1; - bool process = true; - List unprocessed = new List (); - Option def = Contains ("<>") ? this ["<>"] : null; - ArgumentEnumerator ae = new ArgumentEnumerator (arguments); - foreach (string argument in ae) { - ++c.OptionIndex; - if (argument == "--") { - process = false; - continue; - } - if (!process) { - Unprocessed (unprocessed, def, c, argument); - continue; - } - if (AddSource (ae, argument)) - continue; - if (!Parse (argument, c)) - Unprocessed (unprocessed, def, c, argument); - } - if (c.Option != null) - c.Option.Invoke (c); - return unprocessed; - } - - class ArgumentEnumerator : IEnumerable { - List> sources = new List> (); - - public ArgumentEnumerator (IEnumerable arguments) - { - sources.Add (arguments.GetEnumerator ()); - } - - public void Add (IEnumerable arguments) - { - sources.Add (arguments.GetEnumerator ()); - } - - public IEnumerator GetEnumerator () - { - do { - IEnumerator c = sources [sources.Count-1]; - if (c.MoveNext ()) - yield return c.Current; - else { - c.Dispose (); - sources.RemoveAt (sources.Count-1); - } - } while (sources.Count > 0); - } - - IEnumerator IEnumerable.GetEnumerator () - { - return GetEnumerator (); - } - } - - bool AddSource (ArgumentEnumerator ae, string argument) - { - foreach (ArgumentSource source in sources) { - IEnumerable replacement; - if (!source.GetArguments (argument, out replacement)) - continue; - ae.Add (replacement); - return true; - } - return false; - } - - private static bool Unprocessed (ICollection extra, Option def, OptionContext c, string argument) - { - if (def == null) { - extra.Add (argument); - return false; - } - c.OptionValues.Add (argument); - c.Option = def; - c.Option.Invoke (c); - return false; - } - - private readonly Regex ValueOption = new Regex ( - @"^(?--|-|/)(?[^:=]+)((?[:=])(?.*))?$"); - - protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value) - { - if (argument == null) - throw new ArgumentNullException ("argument"); - - flag = name = sep = value = null; - Match m = ValueOption.Match (argument); - if (!m.Success) { - return false; - } - flag = m.Groups ["flag"].Value; - name = m.Groups ["name"].Value; - if (m.Groups ["sep"].Success && m.Groups ["value"].Success) { - sep = m.Groups ["sep"].Value; - value = m.Groups ["value"].Value; - } - return true; - } - - protected virtual bool Parse (string argument, OptionContext c) - { - if (c.Option != null) { - ParseValue (argument, c); - return true; - } - - string f, n, s, v; - if (!GetOptionParts (argument, out f, out n, out s, out v)) - return false; - - Option p; - if (Contains (n)) { - p = this [n]; - c.OptionName = f + n; - c.Option = p; - switch (p.OptionValueType) { - case OptionValueType.None: - c.OptionValues.Add (n); - c.Option.Invoke (c); - break; - case OptionValueType.Optional: - case OptionValueType.Required: - ParseValue (v, c); - break; - } - return true; - } - // no match; is it a bool option? - if (ParseBool (argument, n, c)) - return true; - // is it a bundled option? - if (ParseBundledValue (f, string.Concat (n + s + v), c)) - return true; - - return false; - } - - private void ParseValue (string option, OptionContext c) - { - if (option != null) - foreach (string o in c.Option.ValueSeparators != null - ? option.Split (c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None) - : new string[]{option}) { - c.OptionValues.Add (o); - } - if (c.OptionValues.Count == c.Option.MaxValueCount || - c.Option.OptionValueType == OptionValueType.Optional) - c.Option.Invoke (c); - else if (c.OptionValues.Count > c.Option.MaxValueCount) { - throw new OptionException (localizer (string.Format ( - "Error: Found {0} option values when expecting {1}.", - c.OptionValues.Count, c.Option.MaxValueCount)), - c.OptionName); - } - } - - private bool ParseBool (string option, string n, OptionContext c) - { - Option p; - string rn; - if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') && - Contains ((rn = n.Substring (0, n.Length-1)))) { - p = this [rn]; - string v = n [n.Length-1] == '+' ? option : null; - c.OptionName = option; - c.Option = p; - c.OptionValues.Add (v); - p.Invoke (c); - return true; - } - return false; - } - - private bool ParseBundledValue (string f, string n, OptionContext c) - { - if (f != "-") - return false; - for (int i = 0; i < n.Length; ++i) { - Option p; - string opt = f + n [i].ToString (); - string rn = n [i].ToString (); - if (!Contains (rn)) { - if (i == 0) - return false; - throw new OptionException (string.Format (localizer ( - "Cannot use unregistered option '{0}' in bundle '{1}'."), rn, f + n), null); - } - p = this [rn]; - switch (p.OptionValueType) { - case OptionValueType.None: - Invoke (c, opt, n, p); - break; - case OptionValueType.Optional: - case OptionValueType.Required: { - string v = n.Substring (i+1); - c.Option = p; - c.OptionName = opt; - ParseValue (v.Length != 0 ? v : null, c); - return true; - } - default: - throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType); - } - } - return true; - } - - private static void Invoke (OptionContext c, string name, string value, Option option) - { - c.OptionName = name; - c.Option = option; - c.OptionValues.Add (value); - option.Invoke (c); - } - - private const int OptionWidth = 29; - private const int Description_FirstWidth = 80 - OptionWidth; - private const int Description_RemWidth = 80 - OptionWidth - 2; - - static readonly string CommandHelpIndentStart = new string (' ', OptionWidth); - static readonly string CommandHelpIndentRemaining = new string (' ', OptionWidth + 2); - - public void WriteOptionDescriptions (TextWriter o) - { - foreach (Option p in this) { - int written = 0; - - if (p.Hidden) - continue; - - Category c = p as Category; - if (c != null) { - WriteDescription (o, p.Description, "", 80, 80); - continue; - } - CommandOption co = p as CommandOption; - if (co != null) { - WriteCommandDescription (o, co.Command, co.CommandName); - continue; - } - - if (!WriteOptionPrototype (o, p, ref written)) - continue; - - if (written < OptionWidth) - o.Write (new string (' ', OptionWidth - written)); - else { - o.WriteLine (); - o.Write (new string (' ', OptionWidth)); - } - - WriteDescription (o, p.Description, new string (' ', OptionWidth+2), - Description_FirstWidth, Description_RemWidth); - } - - foreach (ArgumentSource s in sources) { - string[] names = s.GetNames (); - if (names == null || names.Length == 0) - continue; - - int written = 0; - - Write (o, ref written, " "); - Write (o, ref written, names [0]); - for (int i = 1; i < names.Length; ++i) { - Write (o, ref written, ", "); - Write (o, ref written, names [i]); - } - - if (written < OptionWidth) - o.Write (new string (' ', OptionWidth - written)); - else { - o.WriteLine (); - o.Write (new string (' ', OptionWidth)); - } - - WriteDescription (o, s.Description, new string (' ', OptionWidth+2), - Description_FirstWidth, Description_RemWidth); - } - } - - internal void WriteCommandDescription (TextWriter o, Command c, string commandName) - { - var name = new string (' ', 8) + (commandName ?? c.Name); - if (name.Length < OptionWidth - 1) { - WriteDescription (o, name + new string (' ', OptionWidth - name.Length) + c.Help, CommandHelpIndentRemaining, 80, Description_RemWidth); - } else { - WriteDescription (o, name, "", 80, 80); - WriteDescription (o, CommandHelpIndentStart + c.Help, CommandHelpIndentRemaining, 80, Description_RemWidth); - } - } - - void WriteDescription (TextWriter o, string value, string prefix, int firstWidth, int remWidth) - { - bool indent = false; - foreach (string line in GetLines (localizer (GetDescription (value)), firstWidth, remWidth)) { - if (indent) - o.Write (prefix); - o.WriteLine (line); - indent = true; - } - } - - bool WriteOptionPrototype (TextWriter o, Option p, ref int written) - { - string[] names = p.Names; - - int i = GetNextOptionIndex (names, 0); - if (i == names.Length) - return false; - - if (names [i].Length == 1) { - Write (o, ref written, " -"); - Write (o, ref written, names [0]); - } - else { - Write (o, ref written, " --"); - Write (o, ref written, names [0]); - } - - for ( i = GetNextOptionIndex (names, i+1); - i < names.Length; i = GetNextOptionIndex (names, i+1)) { - Write (o, ref written, ", "); - Write (o, ref written, names [i].Length == 1 ? "-" : "--"); - Write (o, ref written, names [i]); - } - - if (p.OptionValueType == OptionValueType.Optional || - p.OptionValueType == OptionValueType.Required) { - if (p.OptionValueType == OptionValueType.Optional) { - Write (o, ref written, localizer ("[")); - } - Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description))); - string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 - ? p.ValueSeparators [0] - : " "; - for (int c = 1; c < p.MaxValueCount; ++c) { - Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description))); - } - if (p.OptionValueType == OptionValueType.Optional) { - Write (o, ref written, localizer ("]")); - } - } - return true; - } - - static int GetNextOptionIndex (string[] names, int i) - { - while (i < names.Length && names [i] == "<>") { - ++i; - } - return i; - } - - static void Write (TextWriter o, ref int n, string s) - { - n += s.Length; - o.Write (s); - } - - static string GetArgumentName (int index, int maxIndex, string description) - { - var matches = Regex.Matches (description ?? "", @"(?<=(? 1 - if (maxIndex > 1 && parts.Length == 2 && - parts[0] == index.ToString (CultureInfo.InvariantCulture)) { - argName = parts[1]; - } - } - - if (string.IsNullOrEmpty (argName)) { - argName = maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); - } - return argName; - } - - private static string GetDescription (string description) - { - if (description == null) - return string.Empty; - StringBuilder sb = new StringBuilder (description.Length); - int start = -1; - for (int i = 0; i < description.Length; ++i) { - switch (description [i]) { - case '{': - if (i == start) { - sb.Append ('{'); - start = -1; - } - else if (start < 0) - start = i + 1; - break; - case '}': - if (start < 0) { - if ((i+1) == description.Length || description [i+1] != '}') - throw new InvalidOperationException ("Invalid option description: " + description); - ++i; - sb.Append ("}"); - } - else { - sb.Append (description.Substring (start, i - start)); - start = -1; - } - break; - case ':': - if (start < 0) - goto default; - start = i + 1; - break; - default: - if (start < 0) - sb.Append (description [i]); - break; - } - } - return sb.ToString (); - } - - private static IEnumerable GetLines (string description, int firstWidth, int remWidth) - { - return StringCoda.WrappedLines (description, firstWidth, remWidth); - } - } - - public class Command - { - public string Name {get;} - public string Help {get;} - - public OptionSet Options {get; set;} - public Action> Run {get; set;} - - public CommandSet CommandSet {get; internal set;} - - public Command (string name, string help = null) - { - if (string.IsNullOrEmpty (name)) - throw new ArgumentNullException (nameof (name)); - - Name = NormalizeCommandName (name); - Help = help; - } - - static string NormalizeCommandName (string name) - { - var value = new StringBuilder (name.Length); - var space = false; - for (int i = 0; i < name.Length; ++i) { - if (!char.IsWhiteSpace (name, i)) { - space = false; - value.Append (name [i]); - } - else if (!space) { - space = true; - value.Append (' '); - } - } - return value.ToString (); - } - - public virtual int Invoke (IEnumerable arguments) - { - var rest = Options?.Parse (arguments) ?? arguments; - Run?.Invoke (rest); - return 0; - } - } - - class CommandOption : Option - { - public Command Command {get;} - public string CommandName {get;} - - // Prototype starts with '=' because this is an invalid prototype - // (see Option.ParsePrototype(), and thus it'll prevent Category - // instances from being accidentally used as normal options. - public CommandOption (Command command, string commandName = null, bool hidden = false) - : base ("=:Command:= " + (commandName ?? command?.Name), (commandName ?? command?.Name), maxValueCount: 0, hidden: hidden) - { - if (command == null) - throw new ArgumentNullException (nameof (command)); - Command = command; - CommandName = commandName ?? command.Name; - } - - protected override void OnParseComplete (OptionContext c) - { - throw new NotSupportedException ("CommandOption.OnParseComplete should not be invoked."); - } - } - - class HelpOption : Option - { - Option option; - CommandSet commands; - - public HelpOption (CommandSet commands, Option d) - : base (d.Prototype, d.Description, d.MaxValueCount, d.Hidden) - { - this.commands = commands; - this.option = d; - } - - protected override void OnParseComplete (OptionContext c) - { - commands.showHelp = true; - - option?.InvokeOnParseComplete (c); - } - } - - class CommandOptionSet : OptionSet - { - CommandSet commands; - - public CommandOptionSet (CommandSet commands, MessageLocalizerConverter localizer) - : base (localizer) - { - this.commands = commands; - } - - protected override void SetItem (int index, Option item) - { - if (ShouldWrapOption (item)) { - base.SetItem (index, new HelpOption (commands, item)); - return; - } - base.SetItem (index, item); - } - - bool ShouldWrapOption (Option item) - { - if (item == null) - return false; - var help = item as HelpOption; - if (help != null) - return false; - foreach (var n in item.Names) { - if (n == "help") - return true; - } - return false; - } - - protected override void InsertItem (int index, Option item) - { - if (ShouldWrapOption (item)) { - base.InsertItem (index, new HelpOption (commands, item)); - return; - } - base.InsertItem (index, item); - } - } - - public class CommandSet : KeyedCollection - { - readonly string suite; - - OptionSet options; - TextWriter outWriter; - TextWriter errorWriter; - - internal List NestedCommandSets; - - internal HelpCommand help; - - internal bool showHelp; - - internal OptionSet Options => options; - -#if !PCL || NETSTANDARD1_3 - public CommandSet(string suite, MessageLocalizerConverter localizer = null) - : this(suite, Console.Out, Console.Error, localizer) - { - } -#endif - - public CommandSet (string suite, TextWriter output, TextWriter error, MessageLocalizerConverter localizer = null) - { - if (suite == null) - throw new ArgumentNullException (nameof (suite)); - if (output == null) - throw new ArgumentNullException (nameof (output)); - if (error == null) - throw new ArgumentNullException (nameof (error)); - - this.suite = suite; - options = new CommandOptionSet (this, localizer); - outWriter = output; - errorWriter = error; - } - - public string Suite => suite; - public TextWriter Out => outWriter; - public TextWriter Error => errorWriter; - public MessageLocalizerConverter MessageLocalizer => options.MessageLocalizer; - - protected override string GetKeyForItem (Command item) - { - return item?.Name; - } - - public new CommandSet Add (Command value) - { - if (value == null) - throw new ArgumentNullException (nameof (value)); - AddCommand (value); - options.Add (new CommandOption (value)); - return this; - } - - void AddCommand (Command value) - { - if (value.CommandSet != null && value.CommandSet != this) { - throw new ArgumentException ("Command instances can only be added to a single CommandSet.", nameof (value)); - } - value.CommandSet = this; - if (value.Options != null) { - value.Options.MessageLocalizer = options.MessageLocalizer; - } - - base.Add (value); - - help = help ?? value as HelpCommand; - } - - public CommandSet Add (string header) - { - options.Add (header); - return this; - } - - public CommandSet Add (Option option) - { - options.Add (option); - return this; - } - - public CommandSet Add (string prototype, Action action) - { - options.Add (prototype, action); - return this; - } - - public CommandSet Add (string prototype, string description, Action action) - { - options.Add (prototype, description, action); - return this; - } - - public CommandSet Add (string prototype, string description, Action action, bool hidden) - { - options.Add (prototype, description, action, hidden); - return this; - } - - public CommandSet Add (string prototype, OptionAction action) - { - options.Add (prototype, action); - return this; - } - - public CommandSet Add (string prototype, string description, OptionAction action) - { - options.Add (prototype, description, action); - return this; - } - - public CommandSet Add (string prototype, string description, OptionAction action, bool hidden) - { - options.Add (prototype, description, action, hidden); - return this; - } - - public CommandSet Add (string prototype, Action action) - { - options.Add (prototype, null, action); - return this; - } - - public CommandSet Add (string prototype, string description, Action action) - { - options.Add (prototype, description, action); - return this; - } - - public CommandSet Add (string prototype, OptionAction action) - { - options.Add (prototype, action); - return this; - } - - public CommandSet Add (string prototype, string description, OptionAction action) - { - options.Add (prototype, description, action); - return this; - } - - public CommandSet Add (ArgumentSource source) - { - options.Add (source); - return this; - } - - public CommandSet Add (CommandSet nestedCommands) - { - if (nestedCommands == null) - throw new ArgumentNullException (nameof (nestedCommands)); - - if (NestedCommandSets == null) { - NestedCommandSets = new List (); - } - - if (!AlreadyAdded (nestedCommands)) { - NestedCommandSets.Add (nestedCommands); - foreach (var o in nestedCommands.options) { - if (o is CommandOption c) { - options.Add (new CommandOption (c.Command, $"{nestedCommands.Suite} {c.CommandName}")); - } - else { - options.Add (o); - } - } - } - - nestedCommands.options = this.options; - nestedCommands.outWriter = this.outWriter; - nestedCommands.errorWriter = this.errorWriter; - - return this; - } - - bool AlreadyAdded (CommandSet value) - { - if (value == this) - return true; - if (NestedCommandSets == null) - return false; - foreach (var nc in NestedCommandSets) { - if (nc.AlreadyAdded (value)) - return true; - } - return false; - } - - public IEnumerable GetCompletions (string prefix = null) - { - string rest; - ExtractToken (ref prefix, out rest); - - foreach (var command in this) { - if (command.Name.StartsWith (prefix, StringComparison.OrdinalIgnoreCase)) { - yield return command.Name; - } - } - - if (NestedCommandSets == null) - yield break; - - foreach (var subset in NestedCommandSets) { - if (subset.Suite.StartsWith (prefix, StringComparison.OrdinalIgnoreCase)) { - foreach (var c in subset.GetCompletions (rest)) { - yield return $"{subset.Suite} {c}"; - } - } - } - } - - static void ExtractToken (ref string input, out string rest) - { - rest = ""; - input = input ?? ""; - - int top = input.Length; - for (int i = 0; i < top; i++) { - if (char.IsWhiteSpace (input [i])) - continue; - - for (int j = i; j < top; j++) { - if (char.IsWhiteSpace (input [j])) { - rest = input.Substring (j).Trim (); - input = input.Substring (i, j).Trim (); - return; - } - } - rest = ""; - if (i != 0) - input = input.Substring (i).Trim (); - return; - } - } - - public int Run (IEnumerable arguments) - { - if (arguments == null) - throw new ArgumentNullException (nameof (arguments)); - - this.showHelp = false; - if (help == null) { - help = new HelpCommand (); - AddCommand (help); - } - Action setHelp = v => showHelp = v != null; - if (!options.Contains ("help")) { - options.Add ("help", "", setHelp, hidden: true); - } - if (!options.Contains ("?")) { - options.Add ("?", "", setHelp, hidden: true); - } - var extra = options.Parse (arguments); - if (extra.Count == 0) { - if (showHelp) { - return help.Invoke (extra); - } - Out.WriteLine (options.MessageLocalizer ($"Use `{Suite} help` for usage.")); - return 1; - } - var command = GetCommand (extra); - if (command == null) { - help.WriteUnknownCommand (extra [0]); - return 1; - } - if (showHelp) { - if (command.Options?.Contains ("help") ?? true) { - extra.Add ("--help"); - return command.Invoke (extra); - } - command.Options.WriteOptionDescriptions (Out); - return 0; - } - return command.Invoke (extra); - } - - internal Command GetCommand (List extra) - { - return TryGetLocalCommand (extra) ?? TryGetNestedCommand (extra); - } - - Command TryGetLocalCommand (List extra) - { - var name = extra [0]; - if (Contains (name)) { - extra.RemoveAt (0); - return this [name]; - } - for (int i = 1; i < extra.Count; ++i) { - name = name + " " + extra [i]; - if (!Contains (name)) - continue; - extra.RemoveRange (0, i+1); - return this [name]; - } - return null; - } - - Command TryGetNestedCommand (List extra) - { - if (NestedCommandSets == null) - return null; - - var nestedCommands = NestedCommandSets.Find (c => c.Suite == extra [0]); - if (nestedCommands == null) - return null; - - var extraCopy = new List (extra); - extraCopy.RemoveAt (0); - if (extraCopy.Count == 0) - return null; - - var command = nestedCommands.GetCommand (extraCopy); - if (command != null) { - extra.Clear (); - extra.AddRange (extraCopy); - return command; - } - return null; - } - } - - public class HelpCommand : Command - { - public HelpCommand () - : base ("help", help: "Show this message and exit") - { - } - - public override int Invoke (IEnumerable arguments) - { - var extra = new List (arguments ?? new string [0]); - var _ = CommandSet.Options.MessageLocalizer; - if (extra.Count == 0) { - CommandSet.Options.WriteOptionDescriptions (CommandSet.Out); - return 0; - } - var command = CommandSet.GetCommand (extra); - if (command == this || extra.Contains ("--help")) { - CommandSet.Out.WriteLine (_ ($"Usage: {CommandSet.Suite} COMMAND [OPTIONS]")); - CommandSet.Out.WriteLine (_ ($"Use `{CommandSet.Suite} help COMMAND` for help on a specific command.")); - CommandSet.Out.WriteLine (); - CommandSet.Out.WriteLine (_ ($"Available commands:")); - CommandSet.Out.WriteLine (); - var commands = GetCommands (); - commands.Sort ((x, y) => string.Compare (x.Key, y.Key, StringComparison.OrdinalIgnoreCase)); - foreach (var c in commands) { - if (c.Key == "help") { - continue; - } - CommandSet.Options.WriteCommandDescription (CommandSet.Out, c.Value, c.Key); - } - CommandSet.Options.WriteCommandDescription (CommandSet.Out, CommandSet.help, "help"); - return 0; - } - if (command == null) { - WriteUnknownCommand (extra [0]); - return 1; - } - if (command.Options != null) { - command.Options.WriteOptionDescriptions (CommandSet.Out); - return 0; - } - return command.Invoke (new [] { "--help" }); - } - - List> GetCommands () - { - var commands = new List> (); - - foreach (var c in CommandSet) { - commands.Add (new KeyValuePair(c.Name, c)); - } - - if (CommandSet.NestedCommandSets == null) - return commands; - - foreach (var nc in CommandSet.NestedCommandSets) { - AddNestedCommands (commands, "", nc); - } - - return commands; - } - - void AddNestedCommands (List> commands, string outer, CommandSet value) - { - foreach (var v in value) { - commands.Add (new KeyValuePair($"{outer}{value.Suite} {v.Name}", v)); - } - if (value.NestedCommandSets == null) - return; - foreach (var nc in value.NestedCommandSets) { - AddNestedCommands (commands, $"{outer}{value.Suite} ", nc); - } - } - - internal void WriteUnknownCommand (string unknownCommand) - { - CommandSet.Error.WriteLine (CommandSet.Options.MessageLocalizer ($"{CommandSet.Suite}: Unknown command: {unknownCommand}")); - CommandSet.Error.WriteLine (CommandSet.Options.MessageLocalizer ($"{CommandSet.Suite}: Use `{CommandSet.Suite} help` for usage.")); - } - } -} - diff --git a/src/Uno.Wasm.Packager/Uno.Wasm.Packager.csproj b/src/Uno.Wasm.Packager/Uno.Wasm.Packager.csproj deleted file mode 100644 index e0eb35f6a..000000000 --- a/src/Uno.Wasm.Packager/Uno.Wasm.Packager.csproj +++ /dev/null @@ -1,21 +0,0 @@ - - - - net5.0 - Exe - packager - - - Major - - - - - - - - - diff --git a/src/Uno.Wasm.Packager/packager.cs b/src/Uno.Wasm.Packager/packager.cs deleted file mode 100644 index 0c364d8ed..000000000 --- a/src/Uno.Wasm.Packager/packager.cs +++ /dev/null @@ -1,2047 +0,0 @@ -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Mono.Cecil; -using Mono.Options; -using Mono.Cecil.Cil; -using System.Diagnostics; -using System.Runtime.InteropServices; - -// -// Google V8 style options: -// - bool: --foo/--no-foo -// - -enum FlagType { - BoolFlag, -} - -// 'Option' is already used by Mono.Options -class Flag { - public Flag (string name, string desc, FlagType type) { - Name = name; - FlagType = type; - Description = desc; - } - - public string Name { - get; set; - } - - public FlagType FlagType { - get; set; - } - - public string Description { - get; set; - } -} - -class BoolFlag : Flag { - public BoolFlag (string name, string description, bool def_value, Action action) : base (name, description, FlagType.BoolFlag) { - Setter = action; - DefaultValue = def_value; - } - - public Action Setter { - get; set; - } - - public bool DefaultValue { - get; set; - } -} - -class Driver { - static bool enable_debug, enable_linker, invariant_globalization; - static string app_prefix, framework_prefix, bcl_tools_prefix, bcl_facades_prefix, out_prefix; - static List bcl_prefixes; - static HashSet asm_map = new HashSet (); - static List file_list = new List (); - static HashSet assemblies_with_dbg_info = new HashSet (); - static List root_search_paths = new List(); - static List assembly_references = new List(); - static CapturingAssemblyResolver resolver; - - const string BINDINGS_ASM_NAME_MONO = "WebAssembly.Bindings"; - const string BINDINGS_RUNTIME_CLASS_NAME = "WebAssembly.Runtime"; - const string HTTP_ASM_NAME = "System.Net.Http.WebAssemblyHttpHandler"; - const string WEBSOCKETS_ASM_NAME = "WebAssembly.Net.WebSockets"; - const string BINDINGS_MODULE = "corebindings.o"; - const string BINDINGS_MODULE_SUPPORT = "$tool_prefix/src/binding_support.js"; - private static readonly string[] jiterpreterOptions = new[] { "jiterpreter-traces-enabled", "jiterpreter-interp-entry-enabled", "jiterpreter-jit-call-enabled" }; - - class AssemblyData { - // Assembly name - public string name; - // Base filename - public string filename; - // Path outside build tree - public string src_path; - // Path of .bc file - public string bc_path; - // Path of the wasm object file - public string o_path; - // Path in appdir - public string app_path; - // Path of the AOT depfile - public string aot_depfile_path; - // Linker input path - public string linkin_path; - // Linker pdb input path - public string linkin_pdb_path; - // Linker pdb output path - public string linkout_pdb_path; - // Linker output path - public string linkout_path; - // AOT input path - public string aotin_path; - // Final output path after IL strip - public string final_path; - // Whenever to AOT this assembly - public bool aot; - - // If not null, this is a satellite assembly - public string culture; - } - - static List assemblies = new List (); - - enum AssemblyKind { - User, - Framework, - Bcl, - None, - } - - void AddFlag (OptionSet options, Flag flag) { - if (flag is BoolFlag) { - options.Add (flag.Name, s => (flag as BoolFlag).Setter (true)); - options.Add ("no-" + flag.Name, s => (flag as BoolFlag).Setter (false)); - } - option_list.Add (flag); - } - - static List option_list = new List (); - - static void Usage () { - Console.WriteLine ("Usage: packager.exe "); - Console.WriteLine ("Valid options:"); - Console.WriteLine ("\t--help Show this help message"); - Console.WriteLine ("\t--debugrt Use the debug runtime (default release) - this has nothing to do with C# debugging"); - Console.WriteLine ("\t--aot Enable AOT mode"); - Console.WriteLine ("\t--aot-interp Enable AOT+INTERP mode"); - Console.WriteLine ("\t--prefix=x Set the input assembly prefix to 'x' (default to the current directory)"); - Console.WriteLine ("\t--out=x Set the output directory to 'x' (default to the current directory)"); - Console.WriteLine ("\t--mono-sdkdir=x Set the mono sdk directory to 'x'"); - Console.WriteLine ("\t--deploy=x Set the deploy prefix to 'x' (default to 'managed')"); - Console.WriteLine ("\t--vfs=x Set the VFS prefix to 'x' (default to 'managed')"); - Console.WriteLine ("\t--target-framework=x Set app target framework"); - Console.WriteLine ("\t--template=x Set the template name to 'x' (default to 'runtime.js')"); - Console.WriteLine ("\t--asset=x Add specified asset 'x' to list of assets to be copied"); - Console.WriteLine ("\t--search-path=x Add specified path 'x' to list of paths used to resolve assemblies"); - Console.WriteLine ("\t--copy=always|ifnewer Set the type of copy to perform."); - Console.WriteLine ("\t\t 'always' overwrites the file if it exists."); - Console.WriteLine ("\t\t 'ifnewer' copies or overwrites the file if modified or size is different."); - Console.WriteLine ("\t--profile=x Enable the 'x' mono profiler."); - Console.WriteLine ("\t--runtime-config=x sets the mono runtime to use (defaults to release)."); - Console.WriteLine ("\t--pthread-pool-size=x sets the number of available pthreads the runtime can use (defaults to 4)."); - Console.WriteLine ("\t--aot-assemblies=x List of assemblies to AOT in AOT+INTERP mode."); - Console.WriteLine ("\t--skip-aot-assemblies=x List of assemblies to skip AOT in AOT+INTERP mode."); - Console.WriteLine ("\t--aot-compiler-opts=x Adjust aot compiler options."); - Console.WriteLine ("\t--aot-profile=x Use 'x' as the AOT profile."); - Console.WriteLine ("\t--link-mode=sdkonly|all Set the link type used for AOT. (EXPERIMENTAL)"); - Console.WriteLine ("\t--pinvoke-libs=x DllImport libraries used."); - Console.WriteLine ("\t\t 'sdkonly' only link the Core libraries."); - Console.WriteLine ("\t\t 'all' link Core and User assemblies. (default)"); - Console.WriteLine ("\t--pinvoke-libs=x DllImport libraries used."); - Console.WriteLine ("\t--native-lib=x Link the native library 'x' into the final executable."); - Console.WriteLine ("\t--native-compile=x Provide the file to emcc."); - Console.WriteLine ("\t--preload-file=x Preloads the file or directory 'x' into the virtual filesystem."); - Console.WriteLine ("\t--embed-file=x Embeds the file or directory 'x' into the virtual filesystem."); - Console.WriteLine ("\t--extra-emccflags=\"x\" Additional emscripten arguments (e.g. -s USE_LIBPNG=1)."); - Console.WriteLine ("\t--extra-linkerflags=\"x\" Additional linker arguments."); - - Console.WriteLine ("foo.dll Include foo.dll as one of the root assemblies"); - Console.WriteLine (); - - Console.WriteLine ("Additional options (--option/--no-option):"); - foreach (var flag in option_list) { - if (flag is BoolFlag) { - Console.WriteLine (" --" + flag.Name + " (" + flag.Description + ")"); - Console.WriteLine (" type: bool default: " + ((flag as BoolFlag).DefaultValue ? "true" : "false")); - } - } - } - - static void Debug (string s) { - Console.WriteLine (s); - } - - static string FindFrameworkAssembly (string asm) { - return asm; - } - - static bool Try (string prefix, string name, out string out_res) { - out_res = null; - - string res = (Path.Combine (prefix, name)); - if (File.Exists (res)) { - out_res = Path.GetFullPath (res); - return true; - } - return false; - } - - static string ResolveWithExtension (string prefix, string name) { - string res = null; - - if (Try (prefix, name, out res)) - return res; - if (Try (prefix, name + ".dll", out res)) - return res; - if (Try (prefix, name + ".exe", out res)) - return res; - return null; - } - - static string ResolveUser (string asm_name) { - return ResolveWithExtension (app_prefix, asm_name); - } - - static string ResolveFramework (string asm_name) { - return ResolveWithExtension (framework_prefix, asm_name); - } - - static string ResolveBcl (string asm_name) { - foreach (var prefix in bcl_prefixes) { - string res = ResolveWithExtension (prefix, asm_name); - if (res != null) - return res; - } - return null; - } - - static string ResolveBclFacade (string asm_name) { - return ResolveWithExtension (bcl_facades_prefix, asm_name); - } - - static string Resolve (string asm_name, out AssemblyKind kind) { - kind = AssemblyKind.User; - var asm = ResolveUser (asm_name); - if (asm != null) - return asm; - - kind = AssemblyKind.Framework; - asm = ResolveFramework (asm_name); - if (asm != null) - return asm; - - kind = AssemblyKind.Bcl; - asm = ResolveBcl (asm_name); - if (asm == null) - asm = ResolveBclFacade (asm_name); - if (asm != null) - return asm; - - kind = AssemblyKind.None; - throw new Exception ($"Could not resolve {asm_name}"); - } - - static bool is_sdk_assembly (string filename) { - foreach (var prefix in bcl_prefixes) - if (filename.StartsWith (prefix)) - return true; - return false; - } - - static void Import (string ra, AssemblyKind kind) { - if(ra == null) - { - return; - } - - var assemblyFullPath = Path.GetFullPath(ra); - var assemblyDirectory = Path.GetDirectoryName(assemblyFullPath); - - if (!asm_map.Add (assemblyFullPath)) - return; - Console.WriteLine($"Resolving {ra}"); - ReaderParameters rp = new ReaderParameters(); - bool add_pdb = enable_debug && File.Exists (Path.ChangeExtension (ra, "pdb")); - if (add_pdb) { - rp.ReadSymbols = true; - // Facades do not have symbols - rp.ThrowIfSymbolsAreNotMatching = false; - rp.SymbolReaderProvider = new DefaultSymbolReaderProvider(false); - } - - if (resolver == null) - { - resolver = new CapturingAssemblyResolver(assembly_references); - root_search_paths.ForEach(resolver.AddSearchDirectory); - foreach (var prefix in bcl_prefixes) - resolver.AddSearchDirectory(prefix); - resolver.AddSearchDirectory(bcl_facades_prefix); - resolver.AddSearchDirectory(framework_prefix); - } - - rp.AssemblyResolver = resolver; - - rp.InMemory = true; - var image = ModuleDefinition.ReadModule (ra, rp); - file_list.Add (ra); - //Debug ($"Processing {ra} debug {add_pdb}"); - - var data = new AssemblyData () { name = image.Assembly.Name.Name, src_path = ra }; - assemblies.Add (data); - - if (add_pdb && (kind == AssemblyKind.User || kind == AssemblyKind.Framework)) { - var pdb_path = Path.ChangeExtension (Path.GetFullPath (ra), "pdb"); - file_list.Add (pdb_path); - assemblies_with_dbg_info.Add (pdb_path); - } - - var parent_kind = kind; - - foreach (var ar in image.AssemblyReferences) { - // Resolve using root search paths first - AssemblyDefinition resolved = null; - try { - resolved = image.AssemblyResolver.Resolve(ar, rp); - } catch { - } - - if (resolved == null && is_sdk_assembly (ra)) - // FIXME: netcore assemblies have missing references - continue; - - if (resolved != null) { - Import (resolved.MainModule.FileName, parent_kind); - } else { - var resolve = Resolve (ar.Name, out kind); - if (resolve != null) - { - Import(resolve, kind); - } - else - { - Console.WriteLine($"Could not resolve {ar.Name}"); - } - } - } - - // Resolving satellite assemblies - if(!invariant_globalization && kind == AssemblyKind.User) - { - string resourceFile = GetAssemblyResourceFileName(assemblyFullPath); - - foreach (var subDirectory in Directory.EnumerateDirectories(assemblyDirectory)) - { - var satelliteAssembly = Path.Combine(subDirectory, resourceFile); - if (!File.Exists(satelliteAssembly)) - { - continue; - } - - string cultureName = subDirectory.Substring(subDirectory.LastIndexOf(Path.DirectorySeparatorChar) + 1); - string culturePath = Path.Combine(assemblyDirectory, cultureName); - - var satelliteData = new AssemblyData() { - name = resourceFile.Replace(".dll", ""), - src_path = satelliteAssembly.Replace("\\", "/"), - culture = cultureName, - aot = false - }; - - assemblies.Add(satelliteData); - - file_list.Add(satelliteAssembly); - - Console.WriteLine($"Added satellite assembly {cultureName}/{resourceFile}"); - } - } - - Console.WriteLine($"Resolved {ra}"); - } - - static string GetAssemblyResourceFileName(string assembly) - => Path.GetFileNameWithoutExtension(assembly) + ".resources.dll"; - - void GenDriver (string builddir, List profilers, ExecMode ee_mode, bool link_icalls) { - var symbols = new List (); - foreach (var adata in assemblies) { - if (adata.aot) - symbols.Add (String.Format ("mono_aot_module_{0}_info", adata.name.Replace ('.', '_').Replace ('-', '_'))); - } - - var w = File.CreateText (Path.Combine (builddir, "driver-gen.c.in")); - - foreach (var symbol in symbols) { - w.WriteLine ($"extern void *{symbol};"); - } - - w.WriteLine ("static void register_aot_modules ()"); - w.WriteLine ("{"); - foreach (var symbol in symbols) - w.WriteLine ($"\tmono_aot_register_module ({symbol});"); - w.WriteLine ("}"); - - foreach (var profiler in profilers) { - w.WriteLine ($"void mono_profiler_init_{profiler} (const char *desc);"); - w.WriteLine ("EMSCRIPTEN_KEEPALIVE void mono_wasm_load_profiler_" + profiler + " (const char *desc) { mono_profiler_init_" + profiler + " (desc); }"); - } - - switch (ee_mode) { - case ExecMode.AotInterp: - w.WriteLine ("#define EE_MODE_LLVMONLY_INTERP 1"); - break; - case ExecMode.Aot: - w.WriteLine ("#define EE_MODE_LLVMONLY 1"); - break; - default: - break; - } - - if (link_icalls) - w.WriteLine ("#define LINK_ICALLS 1"); - - w.Close (); - } - - public static int Main (string[] args) { - return new Driver ().Run (args); - } - - enum CopyType - { - Default, - Always, - IfNewer - } - - enum ExecMode { - Interp = 1, - Aot = 2, - AotInterp = 3 - } - - enum LinkMode - { - SdkOnly, - All - } - - class WasmOptions { - public bool Debug; - public bool DebugRuntime; - public bool AddBinding; - public bool Linker; - public bool LinkIcalls; - public bool ILStrip; - public bool LinkerVerbose; - public bool EnableZLib; - public bool EnableFS; - public bool EnableThreads; - public bool EnableJiterpreter; - public bool Simd; - public bool PrintSkippedAOTMethods; - public bool EnableDynamicRuntime; - public bool LinkerExcludeDeserialization; - public bool EnableCollation; - public bool EnableICU; - public bool EnableDedup = true; - public bool EmccLinkOptimizations = false; - public bool EnableWasmExceptions = false; - public bool InvariantGlobalization = false; - } - - int Run (string[] args) { - var add_binding = true; - var root_assemblies = new List (); - enable_debug = false; - string builddir = null; - string sdkdir = null; - string emscripten_sdkdir = null; - var aot_assemblies = ""; - var skip_aot_assemblies = ""; - app_prefix = Environment.CurrentDirectory; - var assembly_root = "managed"; - var vfs_prefix = "managed"; - var target_framework = "net5.0"; - var use_release_runtime = true; - var enable_aot = false; - var enable_dedup = true; - var print_usage = false; - var emit_ninja = false; - bool build_wasm = false; - bool enable_lto = false; - bool link_icalls = false; - bool gen_pinvoke = false; - bool enable_zlib = false; - bool enable_fs = false; - bool enable_threads = false; - bool enable_dynamic_runtime = false; - bool is_netcore = false; - bool is_windows = Environment.OSVersion.Platform == PlatformID.Win32NT; - bool enable_simd = false; - bool print_skipped_aot_methods = false; - var il_strip = false; - var linker_verbose = false; - var runtimeTemplate = "runtime.js"; - var assets = new List (); - var profilers = new List (); - var native_libs = new List (); - var preload_files = new List (); - var embed_files = new List (); - var emcc_exported_runtime_methods = new List (); - var native_compile = new List (); - var pinvoke_libs = ""; - var copyTypeParm = "default"; - var copyType = CopyType.Default; - var ee_mode = ExecMode.Interp; - var linkModeParm = "all"; - var linkMode = LinkMode.All; - var linkDescriptor = ""; - var framework = ""; - var runtimepack_dir = ""; - string usermode; - string runtimeOptions = null; - string aot_profile = null; - string aot_compiler_options = ""; - string wasm_runtime_path = null; - var runtime_config = "release"; - int pthread_pool_size = 4; - string wasmStackSize = "5MB"; - string illinker_path = ""; - string extra_emccflags = ""; - string extra_linkerflags = ""; - string linker_optimization_level = ""; - string wasm_tuner_path = ""; - var linker_args = new List(); - - var opts = new WasmOptions () { - AddBinding = true, - Debug = false, - DebugRuntime = false, - Linker = false, - ILStrip = false, // disabled because of https://github.com/dotnet/runtime/issues/50609 - LinkerVerbose = false, - EnableZLib = false, - EnableFS = false, - Simd = false, - EnableDynamicRuntime = false, - LinkerExcludeDeserialization = true, - EnableCollation = false, - EnableICU = false - }; - - var p = new OptionSet () { - { "nobinding", s => opts.AddBinding = false }, - { "out=", s => out_prefix = s }, - { "appdir=", s => out_prefix = s }, - { "builddir=", s => builddir = s }, - { "mono-sdkdir=", s => sdkdir = s }, - { "emscripten-sdkdir=", s => emscripten_sdkdir = s }, - { "runtimepack-dir=", s => runtimepack_dir = s }, - { "prefix=", s => app_prefix = s }, - { "wasm-runtime-path=", s => wasm_runtime_path = s }, - { "deploy=", s => assembly_root = s }, - { "vfs=", s => vfs_prefix = s }, - { "target-framework=", s => target_framework = s }, - { "aot", s => ee_mode = ExecMode.Aot }, - { "aot-interp", s => ee_mode = ExecMode.AotInterp }, - { "template=", s => runtimeTemplate = s }, - { "asset=", s => assets.Add(s) }, - { "search-path=", s => root_search_paths.Add(s) }, - { "asm-ref=", s => assembly_references.Add(s) }, - { "profile=", s => profilers.Add (s) }, - { "copy=", s => copyTypeParm = s }, - { "aot-assemblies=", s => aot_assemblies = s }, - { "aot-profile=", s => aot_profile = s }, - { "runtime-config=", s => runtime_config = s }, - { "pthread-pool-size=", s => int.TryParse(s, out pthread_pool_size) }, - { "wasm-stack-size=", s => wasmStackSize = s }, - { "skip-aot-assemblies=", s => skip_aot_assemblies = s }, - { "aot-compiler-opts=", s => aot_compiler_options = s }, - { "link-mode=", s => linkModeParm = s }, - { "link-descriptor=", s => linkDescriptor = s }, - { "pinvoke-libs=", s => pinvoke_libs = s }, - { "native-compile=", s => native_compile.Add(s) }, - { "native-lib=", s => native_libs.Add (s) }, - { "preload-file=", s => preload_files.Add (s) }, - { "embed-file=", s => embed_files.Add (s) }, - { "emcc-exported-runtime-method=", s => emcc_exported_runtime_methods.Add (s) }, - { "framework=", s => framework = s }, - { "extra-emccflags=", s => extra_emccflags = s }, - { "illinker-path=", s => illinker_path = s }, - { "extra-linkerflags=", s => extra_linkerflags = s }, - { "runtime-options=", s => runtimeOptions = s }, - { "linker-optimization-level=", s => linker_optimization_level = s }, - { "wasm-tuner-path=", s => wasm_tuner_path = s }, - { "help", s => print_usage = true }, - }; - - AddFlag (p, new BoolFlag ("debug", "enable c# debugging", opts.Debug, b => opts.Debug = b)); - AddFlag (p, new BoolFlag ("debugrt", "enable debug runtime", opts.DebugRuntime, b => opts.DebugRuntime = b)); - AddFlag (p, new BoolFlag ("linker", "enable the linker", opts.Linker, b => opts.Linker = b)); - AddFlag (p, new BoolFlag ("binding", "enable the binding engine", opts.AddBinding, b => opts.AddBinding = b)); - AddFlag (p, new BoolFlag ("link-icalls", "link away unused icalls", opts.LinkIcalls, b => opts.LinkIcalls = b)); - AddFlag (p, new BoolFlag ("il-strip", "strip IL code from assemblies in AOT mode", opts.ILStrip, b => opts.ILStrip = b)); - AddFlag (p, new BoolFlag ("linker-verbose", "set verbose option on linker", opts.LinkerVerbose, b => opts.LinkerVerbose = b)); - AddFlag (p, new BoolFlag ("zlib", "enable the use of zlib for System.IO.Compression support", opts.EnableZLib, b => opts.EnableZLib = b)); - AddFlag (p, new BoolFlag ("enable-fs", "enable filesystem support (through Emscripten's file_packager.py in a later phase)", opts.EnableFS, b => opts.EnableFS = b)); - AddFlag (p, new BoolFlag ("threads", "enable threads", opts.EnableThreads, b => opts.EnableThreads = b)); - AddFlag (p, new BoolFlag ("jiterpreter", "enable jiterpreter", opts.EnableJiterpreter, b => opts.EnableJiterpreter = b)); - AddFlag (p, new BoolFlag ("print-skipped-aot-methods", "enable jiterpreter", opts.PrintSkippedAOTMethods, b => opts.PrintSkippedAOTMethods = b)); - AddFlag (p, new BoolFlag ("dedup", "enable dedup pass", opts.EnableDedup, b => opts.EnableDedup = b)); - AddFlag (p, new BoolFlag ("dynamic-runtime", "enable dynamic runtime (support for Emscripten's dlopen)", opts.EnableDynamicRuntime, b => opts.EnableDynamicRuntime = b)); - AddFlag (p, new BoolFlag ("simd", "enable SIMD support", opts.Simd, b => opts.Simd = b)); - AddFlag (p, new BoolFlag ("wasm-exceptions", "enable exceptions", opts.EnableWasmExceptions, b => opts.EnableWasmExceptions = b)); - AddFlag (p, new BoolFlag ("linker-exclude-deserialization", "Link out .NET deserialization support", opts.LinkerExcludeDeserialization, b => opts.LinkerExcludeDeserialization = b)); - AddFlag (p, new BoolFlag ("collation", "enable unicode collation support", opts.EnableCollation, b => opts.EnableCollation = b)); - AddFlag (p, new BoolFlag ("icu", "enable .NET 5+ ICU", opts.EnableICU, b => opts.EnableICU = b)); - AddFlag (p, new BoolFlag ("emcc-link-optimization", "enable emcc link-time optimizations", opts.EmccLinkOptimizations, b => opts.EmccLinkOptimizations = b)); - AddFlag (p, new BoolFlag ("invariant-globalization", "enables invariant globalization", opts.InvariantGlobalization, b => opts.InvariantGlobalization = b)); - p.Add(new ResponseFileSource()); - - var new_args = p.Parse (args).ToArray (); - foreach (var a in new_args) { - root_assemblies.Add (a); - } - - if (print_usage) { - Usage (); - return 0; - } - - if (!Enum.TryParse(copyTypeParm, true, out copyType)) { - Console.WriteLine("Invalid copy value"); - Usage (); - return 1; - } - - if (!Enum.TryParse(linkModeParm, true, out linkMode)) { - Console.WriteLine("Invalid link-mode value"); - Usage (); - return 1; - } - - if (out_prefix == null) { - Console.Error.WriteLine ("The --appdir= argument is required."); - return 1; - } - - enable_debug = opts.Debug; - enable_linker = opts.Linker; - add_binding = opts.AddBinding; - il_strip = opts.ILStrip; - linker_verbose = opts.LinkerVerbose; - gen_pinvoke = pinvoke_libs != ""; - enable_zlib = opts.EnableZLib; - enable_fs = opts.EnableFS; - enable_threads = opts.EnableThreads; - enable_dynamic_runtime = opts.EnableDynamicRuntime; - enable_simd = opts.Simd; - print_skipped_aot_methods = opts.PrintSkippedAOTMethods; - invariant_globalization = opts.InvariantGlobalization; - - // Dedup is disabled by default https://github.com/dotnet/runtime/issues/48814 - enable_dedup = opts.EnableDedup; - - if (opts.DebugRuntime) { - runtime_config = "release"; - } else { - switch (runtime_config) { - case "debug": - enable_debug = true; - break; - - case "release": - break; - - case "release-threads": - enable_threads = true; - break; - - case "debug-threads": - enable_threads = true; - enable_debug = true; - break; - - case "dynamic-release": - enable_dynamic_runtime = true; - break; - - case "dynamic-debug": - enable_dynamic_runtime = true; - enable_debug = true; - break; - - default: - Console.WriteLine ("Invalid --runtime-config value. Must be either debug, release, dynamic-release, dynamic-debug."); - Usage (); - return 1; - } - } - - if (ee_mode == ExecMode.Aot || ee_mode == ExecMode.AotInterp) - enable_aot = true; - - if (enable_aot || opts.Linker) - enable_linker = true; - if (opts.LinkIcalls) - link_icalls = true; - if (!enable_linker || !enable_aot) - enable_dedup = false; - if (enable_aot || link_icalls || gen_pinvoke || profilers.Count > 0 || native_libs.Count > 0 || native_compile.Count > 0 || preload_files.Count > 0 || embed_files.Count > 0) { - build_wasm = true; - emit_ninja = true; - } - if (!enable_aot && link_icalls) - enable_lto = true; - if (ee_mode != ExecMode.Aot) - // Can't strip out IL code in mixed mode, since the interpreter might execute some methods even if they have AOTed code available - il_strip = false; - - if (aot_assemblies != "") { - if (ee_mode != ExecMode.AotInterp) { - Console.Error.WriteLine ("The --aot-assemblies= argument requires --aot-interp."); - return 1; - } - } - if (skip_aot_assemblies != "") { - if (ee_mode != ExecMode.AotInterp) { - Console.Error.WriteLine ("The --skip-aot-assemblies= argument requires --aot-interp."); - return 1; - } - } - if (link_icalls && !enable_linker) { - Console.Error.WriteLine ("The --link-icalls option requires the --linker option."); - return 1; - } - - var tool_prefix = runtimepack_dir; - - if (framework != "") { - if (framework.StartsWith ("net5")) { - is_netcore = true; - if (runtimepack_dir == "") { - Console.Error.WriteLine ("The --runtimepack-dir= argument is required."); - return 1; - } - if (!Directory.Exists (runtimepack_dir)) { - Console.Error.WriteLine ($"The directory '{runtimepack_dir}' doesn't exist."); - return 1; - } - if (!Directory.Exists (Path.Combine (runtimepack_dir, "runtimes", "browser-wasm"))) { - Console.Error.WriteLine ($"The directory '{runtimepack_dir}' doesn't contain a 'runtimes/browser-wasm' subdirectory."); - return 1; - } - runtimepack_dir = Path.Combine (runtimepack_dir, "runtimes", "browser-wasm").Replace("\\", "/"); - } else { - Console.Error.WriteLine ("The only valid value for --framework is 'net5...'"); - return 1; - } - } - - if (aot_profile != null && !File.Exists (aot_profile)) { - Console.Error.WriteLine ($"AOT profile file '{aot_profile}' not found."); - return 1; - } - - if (enable_simd && !is_netcore) { - Console.Error.WriteLine ("--simd is only supported with netcore."); - return 1; - } - - //are we working from the tree? - if (sdkdir != null) { - framework_prefix = Path.Combine (tool_prefix, "framework"); //all framework assemblies are currently side built to packager.exe - } else if (Directory.Exists (Path.Combine (tool_prefix, "../out/wasm-bcl/wasm"))) { - framework_prefix = Path.Combine (tool_prefix, "framework"); //all framework assemblies are currently side built to packager.exe - sdkdir = Path.Combine (tool_prefix, "../out"); - } else { - framework_prefix = Path.Combine (tool_prefix, "framework"); - sdkdir = tool_prefix; - } - string bcl_root = Path.Combine (sdkdir, "wasm-bcl"); - var bcl_prefix = Path.Combine (bcl_root, "wasm"); - bcl_facades_prefix = Path.Combine (bcl_prefix, "Facades"); - bcl_prefixes = new List (); - if (is_netcore) { - bcl_tools_prefix = Path.Combine (sdkdir, "tools"); - /* corelib */ - bcl_prefixes.Add (Path.Combine (runtimepack_dir, "native")); - /* .net runtime */ - bcl_prefixes.Add (Path.Combine (runtimepack_dir, "lib", "net8.0")); - } else { - bcl_tools_prefix = Path.Combine (bcl_root, "wasm_tools"); - bcl_prefixes.Add (bcl_prefix); - } - - Console.WriteLine("Resolving assemblies"); - foreach (var ra in root_assemblies) { - AssemblyKind kind; - var resolved = Resolve (ra, out kind); - Import (resolved, kind); - } - Console.WriteLine("Done resolving assemblies"); - - if (enable_aot) { - var to_aot = new Dictionary (StringComparer.OrdinalIgnoreCase); - if (is_netcore) - to_aot ["System.Private.CoreLib"] = true; - else - to_aot ["mscorlib"] = true; - if (aot_assemblies != "") { - foreach (var s in aot_assemblies.Split (',')) - to_aot [s] = true; - } - foreach (var ass in assemblies) { - if (aot_assemblies == "" || to_aot.ContainsKey (ass.name)) { - ass.aot = true; - - if(ass.culture is not null) - { - // Satellite assemblies cannot be AOTed as they're - // implicitly duplicates. - ass.aot = false; - } - - to_aot.Remove (ass.name); - } - } - - if (to_aot.Count > 0) { - Console.WriteLine ("Skipping AOT for unknown assembly names '" + string.Join(",", to_aot.Keys) + "' in --aot-assemblies option."); - } - - if(skip_aot_assemblies != "") { - var skipList = skip_aot_assemblies.Split(','); - - foreach(var asm in assemblies) { - if (skipList.Any(s => asm.name.Equals(s, StringComparison.OrdinalIgnoreCase))) { - Console.WriteLine ($"Disabling AOT for {asm.name}"); - asm.aot = false; - } - } - } - } - - if (builddir != null) { - emit_ninja = true; - if (!Directory.Exists (builddir)) - Directory.CreateDirectory (builddir); - } - - if (!emit_ninja) - { - if (!Directory.Exists(out_prefix)) - Directory.CreateDirectory(out_prefix); - var bcl_dir = Path.Combine(out_prefix, assembly_root); - if (Directory.Exists(bcl_dir)) - Directory.Delete(bcl_dir, true); - Directory.CreateDirectory(bcl_dir); - - file_list.AsParallel().ForAll(f => - { - var fileName = Path.GetFileName(f); - - if (IsResourceAssembly(f, out var culture)) - { - fileName = Path.Combine(culture, fileName); - } - - CopyFile(f, Path.Combine(bcl_dir, fileName), copyType); - }); - } - - if (assembly_root.EndsWith ("/")) - assembly_root = assembly_root.Substring (0, assembly_root.Length - 1); - if (vfs_prefix.EndsWith ("/")) - vfs_prefix = vfs_prefix.Substring (0, vfs_prefix.Length - 1); - - string src_prefix = is_netcore ? Path.Combine(runtimepack_dir, "native") : Path.Combine(tool_prefix, "src"); - - // wasm core bindings module - var wasm_core_bindings = string.Empty; - if (add_binding) { - wasm_core_bindings = BINDINGS_MODULE; - } - // wasm core bindings support file - var wasm_core_support = string.Empty; - var wasm_core_support_library = string.Empty; - if (add_binding) { - - if (is_netcore) - { - wasm_core_support_library += $"--js-library " + Path.Combine(src_prefix, "pal_random.lib.js") + " "; - } - } - var runtime_js = Path.Combine (emit_ninja ? builddir : out_prefix, "runtime.js"); - if (emit_ninja) { - File.Delete (runtime_js); - File.Copy (runtimeTemplate, runtime_js); - } else { - if (File.Exists(runtime_js) && (File.Exists(runtimeTemplate))) { - CopyFile (runtimeTemplate, runtime_js, CopyType.IfNewer, $"runtime template <{runtimeTemplate}> "); - } else { - if (File.Exists(runtimeTemplate)) - CopyFile (runtimeTemplate, runtime_js, CopyType.IfNewer, $"runtime template <{runtimeTemplate}> "); - else { - var runtime_gen = "\nvar Module = {\n\tonRuntimeInitialized: function () {\n\t\tMONO.mono_load_runtime_and_bcl (\n\t\tconfig.vfs_prefix,\n\t\tconfig.deploy_prefix,\n\t\tconfig.enable_debugging,\n\t\tconfig.file_list,\n\t\tfunction () {\n\t\t\tApp.init ();\n\t\t}\n\t)\n\t},\n};"; - File.Delete (runtime_js); - File.WriteAllText (runtime_js, runtime_gen); - } - } - } - - AssemblyData dedup_asm = null; - - if (enable_dedup) { - dedup_asm = new AssemblyData () { name = "aot-instances", - filename = "aot-instances.dll", - bc_path = Path.Combine("$builddir", "aot-instances.dll.bc"), - o_path = Path.Combine("$builddir", "aot-instances.dll.o"), - app_path = Path.Combine("$appdir", "$deploy_prefix", "aot-instances.dll"), - linkout_path = Path.Combine("$builddir", "linker-out", "aot-instances.dll"), - aot = true - }; - assemblies.Add (dedup_asm); - file_list.Add ("aot-instances.dll"); - } - - file_list.Add ("dotnet.native.wasm"); - file_list.Add ("dotnet.native.js"); - file_list.Add ("dotnet.runtime.js"); - - if (enable_threads) { - file_list.Add("dotnet.native.worker.js"); - } - - string wasm_runtime_dir; - if (is_netcore) { - wasm_runtime_dir = Path.Combine (runtimepack_dir, "native"); - } else { - if (wasm_runtime_path == null) - wasm_runtime_path = Path.Combine (tool_prefix, "builds"); - - if (enable_threads) - wasm_runtime_dir = Path.Combine (wasm_runtime_path, use_release_runtime ? "threads-release" : "threads-debug"); - else if (enable_dynamic_runtime) - wasm_runtime_dir = Path.Combine (wasm_runtime_path, use_release_runtime ? "dynamic-release" : "dynamic-debug"); - else - wasm_runtime_dir = Path.Combine (wasm_runtime_path, use_release_runtime ? "release" : "debug"); - } - - if (is_netcore) - { - if (opts.EnableICU) - { - foreach (var icudat in Directory.EnumerateFiles(wasm_runtime_dir)) - { - if (Path.GetFileName(icudat).StartsWith("icudt.dat")) - { - file_list.Add(icudat); - } - } - } - else - { - // ICU fails when running with AOT, reason yet unknown - Console.WriteLine("WARNING: ICU Disabled when using AOT"); - } - } - - var file_list_str = string.Join(",\n", file_list.Distinct().Select(f => - { - var fileName = Path.GetFileName(f).ToLower(); ; - - var assetType = Path.GetExtension(f).ToLowerInvariant() switch - { - ".dll" => "assembly", - ".pdb" => "assembly", // PDBs are loaded through https://github.com/dotnet/runtime/blob/55d35231b48ec0a66835a2bd71a968baf8ad9a12/src/mono/wasm/runtime/assets.ts#L411-L412 - ".wasm" => "dotnetwasm", - ".js" when fileName is "dotnet.native.worker.js" => "js-module-threads", - ".js" when fileName is "dotnet.native.js" => "js-module-native", - ".js" when fileName is "dotnet.runtime.js" => "js-module-runtime", - ".js" when fileName is "dotnet.js" => "js-module-dotnet", - ".dat" => "icu", - _ => throw new Exception($"Unsupported asset type") - }; - - string cultureField = null; - string culturePathPrefix = null; - - if (assetType is "assembly") - { - if(IsResourceAssembly(f, out var culture)) - { - assetType = "resource"; - cultureField = $", \"culture\":\"{Path.GetFileName(Path.GetDirectoryName(f))}\""; - culturePathPrefix = $"{culture}/"; - } - } - - return $" {{ \"name\": \"{culturePathPrefix}{Path.GetFileName(f)}\",\"virtualPath\": \"{Path.GetFileName(f)}\", \"loadRemote\": true, \"behavior\":\"{assetType}\" {cultureField} }}"; - })); - var debugLevel = enable_debug ? " -1" : "0"; - - // Follow https://github.com/dotnet/runtime/blob/e57438026c25707bf6dd52cd332db657e919bbd4/src/mono/wasm/runtime/dotnet.d.ts#L80 - - var configOptions = new Dictionary() - { - ["assemblyRootFolder"] = $"\"{assembly_root}\"", - ["debugLevel"] = debugLevel.ToString(), - }; - - if (enable_threads) - { - configOptions["pthreadPoolSize"] = pthread_pool_size.ToString(); - } - - var runtimeOptionsSet = runtimeOptions?.Split(" ")?.ToHashSet() ?? new HashSet(3); - foreach (var jiterpreterOption in jiterpreterOptions) - { - if (opts.EnableJiterpreter) - { - if (!runtimeOptionsSet.Contains($"--no-{jiterpreterOption}")) - { - runtimeOptionsSet.Add($"--{jiterpreterOption}"); - } - } - else - { - if (!runtimeOptionsSet.Contains($"--{jiterpreterOption}")) - { - runtimeOptionsSet.Add($"--no-{jiterpreterOption}"); - } - } - } - - configOptions["runtimeOptions"] = $"[{string.Join(",", runtimeOptionsSet.Select(o => $"\"{o}\""))}]"; - configOptions["remoteSources"] = $"[\"{assembly_root}/\"]"; - configOptions["globalizationMode"] = "\"all\""; - - var config = $"{{" + - string.Join(",", configOptions.Select(o => $"\n \t\"{o.Key}\": {o.Value}")) + "," + - $"\n \t\"assets\": [ " + file_list_str + "]\n" + - $"}}"; - - var config_json = Path.Combine(emit_ninja ? builddir : out_prefix, "mono-config.json"); - File.Delete(config_json); - File.WriteAllText(config_json, config); - - if (!emit_ninja) { - var interp_files = new List { "dotnet.js", "dotnet.native.wasm", "dotnet.runtime.js", "dotnet.native.js" }; - - if (enable_threads) { - interp_files.Add ("dotnet.native.worker.js"); - } - foreach (var fname in interp_files) { - File.Delete (Path.Combine (out_prefix, fname)); - File.Copy ( - Path.Combine (wasm_runtime_dir, fname), - Path.Combine (out_prefix, fname)); - } - - assets.AsParallel().ForAll(asset => - { - CopyFile(asset, - Path.Combine(out_prefix, Path.GetFileName(asset)), copyType, "Asset: "); - }); - } - - if (!emit_ninja) - return 0; - - if (builddir == null) { - Console.Error.WriteLine ("The --builddir argument is required."); - return 1; - } - - var filenames = new Dictionary (); - foreach (var a in assemblies) { - var assembly = a.src_path; - if (assembly == null) - continue; - string filename = Path.GetFileName (assembly); - if (filenames.ContainsKey (filename) && !filename.EndsWith(".resources.dll", StringComparison.OrdinalIgnoreCase)) { - Console.WriteLine ("Duplicate input assembly: " + assembly + " " + filenames [filename]); - return 1; - } - filenames [filename] = assembly; - } - - if (build_wasm) { - if (sdkdir == null) { - Console.WriteLine ("The --mono-sdkdir argument is required."); - return 1; - } - if (emscripten_sdkdir == null) { - Console.WriteLine ("The --emscripten-sdkdir argument is required."); - return 1; - } - GenDriver (builddir, profilers, ee_mode, link_icalls); - } - - string runtime_dir; - string runtime_libdir; - if (is_netcore) { - runtime_dir = "$runtimepack_dir/native"; - runtime_libdir = "$runtimepack_dir/native"; - } else { - runtime_dir = "$mono_sdkdir/wasm-runtime-release"; - runtime_libdir = $"{runtime_dir}/lib"; - } - string runtime_libs = ""; - if (ee_mode == ExecMode.Interp || ee_mode == ExecMode.AotInterp || link_icalls) { - runtime_libs += $"$runtime_libdir/libmono-ee-interp.a "; - // We need to link the icall table because the interpreter uses it to lookup icalls even if the aot-ed icall wrappers are available - if (!link_icalls) - runtime_libs += $"$runtime_libdir/libmono-icall-table.a "; - } - runtime_libs += $"$runtime_libdir/libmonosgen-2.0.a "; - if (is_netcore) - { - runtime_libs += $"$runtime_libdir/wasm-bundled-timezones.a "; - - if (enable_simd) - { - runtime_libs += $"$runtime_libdir/libmono-wasm-simd.a "; - } - else - { - runtime_libs += $"$runtime_libdir/libmono-wasm-nosimd.a "; - } - - runtime_libs += $"$runtime_libdir/libSystem.Native.a "; - runtime_libs += $"$runtime_libdir/libSystem.IO.Compression.Native.a "; - runtime_libs += $"$runtime_libdir/libSystem.Globalization.Native.a "; - runtime_libs += $"$runtime_libdir/libicuuc.a "; - runtime_libs += $"$runtime_libdir/libicui18n.a "; - runtime_libs += $"$runtime_libdir/libicudata.a "; - - runtime_libs += opts.EnableWasmExceptions - ? $"$runtime_libdir/libmono-wasm-eh-wasm.a " - : $"$runtime_libdir/libmono-wasm-eh-js.a "; - - if (enable_debug) - { - runtime_libs += $"$runtime_libdir/libmono-component-marshal-ilgen-static.a "; - runtime_libs += $"$runtime_libdir/libmono-component-diagnostics_tracing-static.a "; - runtime_libs += $"$runtime_libdir/libmono-component-hot_reload-static.a "; - runtime_libs += $"$runtime_libdir/libmono-component-debugger-static.a "; - } - else - { - // ilgen is required most of the time and we'll need to include it conditionally - // when incompatible assemblies are detected: https://github.com/dotnet/runtime/blob/8b25fd382260e8eafbfd77f64b0fe28dc7301c2e/src/tasks/MonoTargetsTasks/MarshalingPInvokeScanner/MarshalingPInvokeScanner.cs#L21 - // runtime_libs += $"$runtime_libdir/libmono-component-marshal-ilgen-stub-static.a "; - - // For now, we include the component always, as even basic tests require the component - // to be linked in. - runtime_libs += $"$runtime_libdir/libmono-component-marshal-ilgen-static.a "; - - runtime_libs += $"$runtime_libdir/libmono-component-diagnostics_tracing-stub-static.a "; - runtime_libs += $"$runtime_libdir/libmono-component-hot_reload-stub-static.a "; - runtime_libs += $"$runtime_libdir/libmono-component-debugger-stub-static.a "; - } - } - else - runtime_libs += $"$runtime_libdir/libmono-native.a "; - - string emcc_flags = ""; - - string aot_args = "llvm-path=\"$emscripten_sdkdir/upstream/bin\","; - string profiler_libs = ""; - string profiler_aot_args = ""; - foreach (var profiler in profilers) { - if (is_netcore) - { - profiler_libs += $"$runtime_libdir/libmono-profiler-{profiler}.a "; - } - else - { - profiler_libs += $"$runtime_libdir/libmono-profiler-{profiler}-static.a "; - } - if (profiler_aot_args != "") - profiler_aot_args += " "; - profiler_aot_args += $"--profile={profiler}"; - - if (profiler == "aot") - { - // related to driver.c conditionals - emcc_flags += " -DENABLE_AOT_PROFILER=1 "; - } - } - string extra_link_libs = ""; - foreach (var lib in native_libs) - extra_link_libs += $"{EscapePath(lib)} "; - if (aot_profile != null) { - CopyFile (aot_profile, Path.Combine (builddir, Path.GetFileName (aot_profile)), CopyType.IfNewer, ""); - aot_args += $"profile=\"{aot_profile}\",profile-only,"; - } - if (ee_mode == ExecMode.AotInterp) - aot_args += "interp,"; - if (build_wasm) - enable_zlib = true; - if (is_netcore) - enable_zlib = false; - - wasm_runtime_dir = Path.GetFullPath (wasm_runtime_dir); - sdkdir = Path.GetFullPath (sdkdir); - out_prefix = Path.GetFullPath (out_prefix); - - string driver_deps = ""; - if (link_icalls) - driver_deps += " $builddir/icall-table.h"; - if (gen_pinvoke) - driver_deps += " $builddir/pinvoke-table.h"; - if (enable_lto) - emcc_flags += "--llvm-lto 1 "; - if (enable_zlib || is_netcore) - emcc_flags += "-s USE_ZLIB=1 "; - if (enable_fs) - emcc_flags += "-s FORCE_FILESYSTEM=1 "; - foreach (var pf in preload_files) - emcc_flags += "--preload-file " + pf + " "; - foreach (var f in embed_files) - emcc_flags += "--embed-file " + f + " "; - - var emcc_link_flags = new List(); - if (enable_debug || !opts.EmccLinkOptimizations) - { - emcc_link_flags.Add("-O0 "); - } - else - { - emcc_link_flags.Add(linker_optimization_level); - } - - if (enable_threads) - { - emcc_link_flags.Add("-s USE_PTHREADS=1"); - emcc_link_flags.Add("-Wno-pthreads-mem-growth"); - - emcc_flags += "-s USE_PTHREADS=1 "; - emcc_flags += "-Wno-pthreads-mem-growth "; - - aot_compiler_options += " --wasm-gc-safepoints "; - } - - if (opts.EnableWasmExceptions) - { - emcc_link_flags.Add("-fwasm-exceptions"); - emcc_flags += " -fwasm-exceptions "; - aot_compiler_options += " --wasm-exceptions "; - } - else - { - emcc_flags += " -s DISABLE_EXCEPTION_CATCHING=0 "; - } - - emcc_flags += " -s EXPORT_ES6=1 "; - - // https://github.com/dotnet/runtime/blob/0a57a9b20905b1e14993dc4604bad3bdf0b57fa2/src/mono/wasm/wasm.proj#L187 - emcc_exported_runtime_methods.Add("FS"); - emcc_exported_runtime_methods.Add("out"); - emcc_exported_runtime_methods.Add("err"); - emcc_exported_runtime_methods.Add("ccall"); - emcc_exported_runtime_methods.Add("cwrap"); - emcc_exported_runtime_methods.Add("setValue"); - emcc_exported_runtime_methods.Add("getValue"); - emcc_exported_runtime_methods.Add("UTF8ToString"); - emcc_exported_runtime_methods.Add("UTF8ArrayToString"); - emcc_exported_runtime_methods.Add("stringToUTF8Array"); - emcc_exported_runtime_methods.Add("FS_createPath"); - emcc_exported_runtime_methods.Add("FS_createDataFile"); - emcc_exported_runtime_methods.Add("removeRunDependency"); - emcc_exported_runtime_methods.Add("addRunDependency"); - emcc_exported_runtime_methods.Add("addFunction"); - emcc_exported_runtime_methods.Add("safeSetTimeout"); - emcc_exported_runtime_methods.Add("runtimeKeepalivePush"); - emcc_exported_runtime_methods.Add("runtimeKeepalivePop"); - emcc_exported_runtime_methods.Add("maybeExit"); - - // Additional uno-only exports - emcc_exported_runtime_methods.Add("FS_readFile"); - emcc_exported_runtime_methods.Add("lengthBytesUTF8"); - emcc_exported_runtime_methods.Add("stringToUTF8"); - emcc_exported_runtime_methods.Add("removeFunction"); - emcc_exported_runtime_methods.Add("IDBFS"); - emcc_exported_runtime_methods.Add("print"); - - var exports = string.Join(",", emcc_exported_runtime_methods.Distinct().Select(m => $"\'{m}\'")); - - emcc_link_flags.Add("-s EXPORTED_RUNTIME_METHODS=\"[" + exports + "]\""); - - // https://github.com/dotnet/runtime/blob/0a57a9b20905b1e14993dc4604bad3bdf0b57fa2/src/mono/wasm/wasm.proj#L202 - List exportedFunctions = new() - { - "_fmod" , - "_atan2" , - "_fma" , - "_pow" , - "_fmodf" , - "_atan2f" , - "_fmaf" , - "_powf" , - - "_asin" , - "_asinh" , - "_acos" , - "_acosh" , - "_atan" , - "_atanh" , - "_cbrt" , - "_cos" , - "_cosh" , - "_exp" , - "_log" , - "_log2" , - "_log10" , - "_sin" , - "_sinh" , - "_tan" , - "_tanh" , - - "_asinf" , - "_asinhf" , - "_acosf" , - "_acoshf" , - "_atanf" , - "_atanhf" , - "_cbrtf" , - "_cosf" , - "_coshf" , - "_expf" , - "_logf" , - "_log2f" , - "_log10f" , - "_sinf" , - "_sinhf" , - "_tanf" , - "_tanhf" , - - // Uno specific - "_malloc" , - "stackSave", - "stackRestore", - "stackAlloc", - "_memalign", - "_memset", - "_htons", - "_ntohs", - "_free" - }; - - if (enable_threads) - { - // https://github.com/dotnet/runtime/blob/6c3a197c4e01bb40c58e7c88370f92acbd53d81c/src/mono/wasm/wasm.proj#L265 - exportedFunctions.Add("_emscripten_main_runtime_thread_id"); - } - - var exportedFunctionsValue = string.Join(",", exportedFunctions.Distinct()); - emcc_link_flags.Add($"-s EXPORTED_FUNCTIONS={exportedFunctionsValue}"); - - // workaround for https://github.com/emscripten-core/emscripten/issues/18034 - emcc_link_flags.Add($"-s TEXTDECODER=0"); - - // Align with https://github.com/dotnet/runtime/blob/0a57a9b20905b1e14993dc4604bad3bdf0b57fa2/src/mono/wasm/wasm.proj#L279 - emcc_link_flags.Add("-s EXPORT_ES6=1"); - emcc_link_flags.Add("-s ALLOW_MEMORY_GROWTH=1"); - emcc_link_flags.Add("-s NO_EXIT_RUNTIME=1"); - emcc_link_flags.Add("-s FORCE_FILESYSTEM=1"); - - emcc_link_flags.Add("--source-map-base http://example.com"); - emcc_link_flags.Add("-s EXPORT_NAME=\"'createDotnetRuntime'\""); - emcc_link_flags.Add("-s MODULARIZE=1"); - emcc_link_flags.Add("-s ENVIRONMENT=\"web,webview,worker,node,shell\""); - - emcc_link_flags.Add("-s ALLOW_TABLE_GROWTH=1"); - emcc_link_flags.Add($"-s STACK_SIZE={wasmStackSize}"); - - emcc_link_flags.Add("-s WASM_BIGINT=1"); - emcc_link_flags.Add("-s ERROR_ON_UNDEFINED_SYMBOLS=1"); - emcc_link_flags.Add("-s \"DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[\'memset\']\""); - - // https://github.com/dotnet/runtime/blob/0a57a9b20905b1e14993dc4604bad3bdf0b57fa2/src/mono/wasm/wasm.proj#L303 - emcc_link_flags.Add("-Wno-limited-postlink-optimizations"); - - var failOnError = is_windows - ? "; if ($$LastExitCode -ne 0) { exit 1; }" - : ""; - - if (enable_simd) { - aot_args += "mattr=simd,"; - emcc_flags += "-msimd128 "; - emcc_flags += "-DCONFIGURATION_COMPILE_OPTIONS=\"-msimd128\" -DCONFIGURATION_INTERPSIMDTABLES_LIB=\"simd\" "; - } - - if (print_skipped_aot_methods) - { - aot_args += "print-skipped,"; - } - - if (is_netcore) { - emcc_flags += $"-DGEN_PINVOKE -I{src_prefix} "; - - // No need to emit LLVM, we're not using LTO options - // emcc_flags += $"-emit-llvm "; - } - if (!use_release_runtime) - // -s ASSERTIONS=2 is very slow - emcc_flags += "-s ASSERTIONS=1 "; - - if (!string.IsNullOrEmpty(extra_emccflags)) { - emcc_flags += " " + extra_emccflags + " "; - } - - var ninja = File.CreateText (Path.Combine (builddir, "build.ninja")); - var linkerResponse = Path.Combine (builddir, "linker.rsp"); - - // Defines - ninja.WriteLine ($"mono_sdkdir = {sdkdir}"); - ninja.WriteLine ($"emscripten_sdkdir = {emscripten_sdkdir}"); - ninja.WriteLine ($"tool_prefix = {tool_prefix}"); - ninja.WriteLine ($"appdir = {out_prefix}"); - ninja.WriteLine ($"builddir = ."); - if (is_netcore) - ninja.WriteLine ($"runtimepack_dir = {runtimepack_dir}"); - ninja.WriteLine ($"wasm_runtime_dir = {wasm_runtime_dir}"); - ninja.WriteLine ($"runtime_libdir = {runtime_libdir}"); - ninja.WriteLine ($"deploy_prefix = {assembly_root}"); - ninja.WriteLine ($"bcl_dir = {bcl_prefix}"); - ninja.WriteLine ($"bcl_facades_dir = {bcl_facades_prefix}"); - ninja.WriteLine ($"framework_dir = {framework_prefix}"); - ninja.WriteLine ($"tools_dir = {bcl_tools_prefix}"); - ninja.WriteLine ($"linker_dir = {illinker_path}"); - - if (!is_windows) - { - // emsdk is setup from the bootstrapper to avoid concurrency issues - // in the emsdk environment setup tooling - ninja.WriteLine($"emsdk_env = $builddir/emsdk_env.sh"); - } - else - { - ninja.WriteLine($"emsdk_env = emsdkenv.cmd"); - } - - if (add_binding) { - ninja.WriteLine ($"wasm_core_bindings = $builddir/{BINDINGS_MODULE}"); - ninja.WriteLine ($"wasm_core_support = {wasm_core_support}"); - ninja.WriteLine ($"wasm_core_support_library = {wasm_core_support_library}"); - } else { - ninja.WriteLine ("wasm_core_bindings ="); - ninja.WriteLine ("wasm_core_support ="); - ninja.WriteLine ("wasm_core_support_library ="); - } - - if (is_netcore) - { - var ext = is_windows ? ".exe" : ""; - ninja.WriteLine ($"cross = $runtimepack_dir/native/cross/browser-wasm/mono-aot-cross{ext}"); - } - else - { - ninja.WriteLine ("cross = $mono_sdkdir/wasm-cross-release/bin/wasm32-unknown-none-mono-sgen"); - } - - if (Environment.OSVersion.Platform != PlatformID.Win32NT) - { - ninja.WriteLine ("emcc = source $emsdk_env && PYTHONUTF8=1 LC_ALL=C.UTF-8 emcc"); - } - else - { - ninja.WriteLine("emcc = $$env:PYTHONUTF8=1; emcc "); - } - - ninja.WriteLine ("wasm_opt = $emscripten_sdkdir/upstream/bin/wasm-opt"); - ninja.WriteLine ($"emcc_flags = -DENABLE_METADATA_UPDATE=1 {emcc_flags} "); - ninja.WriteLine ($"aot_base_args = llvmonly,asmonly,no-opt,static,direct-icalls,deterministic,nodebug,{aot_args}"); - - var environment = new List - { - "MONO_PATH=$mono_path" - }; - - if (enable_threads) - { - // environment.Add("MONO_THREADS_SUSPEND=coop"); - } - - var response_prefix = is_windows - ? "`@" - : "@"; - - var aot_cross_prefix = is_windows - ? $"cmd /c set \"MONO_PATH=$mono_path\" &&" + string.Join(" ", environment.Select(e => $"set \"{e}\" &&")) - : string.Join(" ", environment); - - // Rules - ninja.WriteLine ("rule aot"); - ninja.WriteLine ($" command = {aot_cross_prefix} $cross --debug {profiler_aot_args} {aot_compiler_options} --aot=$aot_args,$aot_base_args,depfile=$depfile,llvm-outfile=$outfile $src_file"); - ninja.WriteLine (" description = [AOT] $src_file -> $outfile"); - - ninja.WriteLine ("rule aot-instances"); - ninja.WriteLine ($" command = {aot_cross_prefix} $cross --response=$builddir/aot-instances.rsp"); - ninja.WriteLine ($" rspfile = $builddir/aot-instances.rsp"); - ninja.WriteLine ($" rspfile_content = --debug {profiler_aot_args} {aot_compiler_options} --aot=$aot_base_args,llvm-outfile=$outfile,dedup-include=$dedup_image $src_files"); - ninja.WriteLine (" description = [AOT-INSTANCES] $outfile"); - - ninja.WriteLine ("rule mkdir"); - if (Environment.OSVersion.Platform != PlatformID.Win32NT) - { - ninja.WriteLine(" command = mkdir -p $out"); - } - else - { - ninja.WriteLine(" command = powershell mkdir -Force -p '$out' | Out-Null"); - } - - var cpCommand = Environment.OSVersion.Platform == PlatformID.Win32NT ? "copy" : "cp"; - var commandPrefix = Environment.OSVersion.Platform == PlatformID.Win32NT ? "powershell " : ""; - - if (Environment.OSVersion.Platform != PlatformID.Win32NT) - { - ninja.WriteLine ("rule cp"); - ninja.WriteLine ($" command = {commandPrefix} {cpCommand} $in $out"); - ninja.WriteLine ($" description = [CP] $in -> $out"); - ninja.WriteLine("rule cpifdiff"); - // Copy $in to $out only if it changed - ninja.WriteLine ($" command = /bin/bash -c \"if cmp -s $in $out ; then : ; else {cpCommand} $in $out ; fi\""); - - ninja.WriteLine ("rule cpifdiffex"); - ninja.WriteLine ($" command = /bin/bash -c \"if [ -f $in ] && [ `cmp -s $in $out` ] ; then : ; else {cpCommand} $in $out ; fi\""); - - ninja.WriteLine (" restat = true"); - ninja.WriteLine (" description = [CPIFDIFFEX] $in -> $out"); - } - else - { - ninja.WriteLine ("rule cp"); - ninja.WriteLine ($" command = cmd /V:ON /c set \"in1=$in\" & set \"in2=!in1:/=\\!\" & set \"out1=$out\" & set \"out2=!out1:/=\\!\" & copy /y !in2! !out2! 1> NUL"); - ninja.WriteLine ($" description = [CP] $in -> $out"); - - ninja.WriteLine ("rule cpifdiff"); - ninja.WriteLine ($" command = cmd /V:ON /c set \"in1=$in\" & set \"in2=!in1:/=\\!\" & set \"out1=$out\" & set \"out2=!out1:/=\\!\" & copy /y !in2! !out2! 1> NUL"); - ninja.WriteLine ($" description = [CPIFDIFF] $in -> $out"); - - ninja.WriteLine ("rule cpifdiffex"); - ninja.WriteLine ($" command = cmd /V:ON /c set \"in1=$in\" & set \"in2=!in1:/=\\!\" & set \"out1=$out\" & set \"out2=!out1:/=\\!\" & if exist !in2! copy /y !in2! !out2! 1> NUL"); - ninja.WriteLine ( " restat = true"); - ninja.WriteLine ( " description = [CPIFDIFFEX] $in -> $out"); - } - - var emcc_shell_prefix = is_windows - ? "powershell" - : "bash -c"; - - var tools_shell_prefix = is_windows - ? "powershell" - : ""; - - ninja.WriteLine("rule create-emsdk-env"); - - if (is_windows) - { - ninja.WriteLine($" command = cmd /c \"$emscripten_sdkdir/emsdk.bat\" construct_env > $out"); - } - else - { - ninja.WriteLine($" command = {tools_shell_prefix} \"$emscripten_sdkdir/emsdk\" construct_env > $out"); - } - - ninja.WriteLine ("rule emcc"); - ninja.WriteLine ($" command = {emcc_shell_prefix} \"$emcc $emcc_flags $flags -Oz -c -o $out $in\""); - ninja.WriteLine (" description = [EMCC] $in -> $out"); - - var src_prefix_es6 = Path.Combine(src_prefix, "es6") + Path.DirectorySeparatorChar; - - // Additional parameters are not supported in the same way between linux and windows. - var jsAdditionals = - $"--pre-js {src_prefix_es6}dotnet.es6.pre.js " + - $"--js-library {src_prefix_es6}dotnet.es6.lib.js " + - $"--extern-post-js {src_prefix_es6}dotnet.es6.extpost.js " + - wasm_core_support_library; - - var emcc_link_additionals_command = is_windows ? jsAdditionals : ""; - var emcc_link_additionals_response = is_windows ? "" : jsAdditionals; - - // Prevents https://github.com/emscripten-core/emscripten/blob/347262aec9c4450e34b6af617d1420dbda2f6662/src/preamble.js#L945 to remove - // the `env` member: https://github.com/emscripten-core/emscripten/blob/347262aec9c4450e34b6af617d1420dbda2f6662/emcc.py#L2534 - // which is being used here: https://github.com/dotnet/runtime/blob/e131899322693dff60b835a83bbf02f7916e3991/src/mono/wasm/runtime/startup.ts#LL446C1-L446C10 - emcc_link_flags.Add("-s ASSERTIONS=1"); - - ninja.WriteLine("rule emcc-link"); - ninja.WriteLine($" command = {emcc_shell_prefix} \"$emcc {response_prefix}$builddir/emcc_link.rsp {emcc_link_additionals_command} {failOnError} \""); - ninja.WriteLine($" rspfile = $builddir/emcc_link.rsp"); - ninja.WriteLine($" rspfile_content = $emcc_flags {string.Join(" ", emcc_link_flags)} -v -o \"$out_js\" -s MODULARIZE=1 {emcc_link_additionals_response} $in"); - ninja.WriteLine($" description = [EMCC-LINK] $in -> $out"); - - ninja.WriteLine ("rule linker"); - var linkerBin = "dotnet \'$linker_dir/illink.dll\'"; - - var assemblyRefPaths = assembly_references.Distinct().Select(p => $"-reference \"{p}\" "); - var linkerSearchPaths = root_search_paths.Concat(bcl_prefixes).Distinct().Select(p => $"-d \"{p}\" "); - - var tunerBinary = string.IsNullOrEmpty(wasm_tuner_path) - ? $"$tools_dir{Path.DirectorySeparatorChar}wasm-tuner.dll" - : wasm_tuner_path; - - var tunerCommand = $"dotnet '{tunerBinary}'"; - - var exitCommand = is_windows ? failOnError : "|| exit 1"; - - linker_args.Add($"-out ./linker-out --deterministic --disable-opt unreachablebodies"); - linker_args.Add($"--strip-link-attributes"); - linker_args.Add(extra_linkerflags); - linker_args.AddRange(assemblyRefPaths); - linker_args.AddRange(linkerSearchPaths); - - ninja.WriteLine ($" command = {tools_shell_prefix} {linkerBin} \'@{linkerResponse}\' {exitCommand}; {tunerCommand} --gen-empty-assemblies \'@$builddir/tuner.rsp\'"); - ninja.WriteLine (" rspfile = $builddir/tuner.rsp"); - ninja.WriteLine (" rspfile_content = $out"); - ninja.WriteLine (" description = [IL-LINK]"); - ninja.WriteLine ("rule aot-instances-dll"); - - if (is_windows) - { - ninja.WriteLine($" command = cmd /c \"dotnet new classlib -o aot-instances && del aot-instances\\*.cs && dotnet build aot-instances\\aot-instances.csproj /r -p:Deterministic=true -p:ImplicitUsings=false -p:TargetFramework={target_framework} -p:UseSharedCompilation=false /p:OutputPath=..\\linker-out\""); - } - else - { - ninja.WriteLine($" command = dotnet new classlib -o aot-instances; rm aot-instances/*.cs; dotnet build aot-instances/aot-instances.csproj /r -p:Deterministic=true -p:ImplicitUsings=false -p:TargetFramework={target_framework} -p:UseSharedCompilation=false /p:OutputPath=../linker-out/"); - } - - ninja.WriteLine ("rule gen-runtime-icall-table"); - ninja.WriteLine ($" command = {aot_cross_prefix} $cross --print-icall-table > $out"); - ninja.WriteLine ("rule gen-icall-table"); - ninja.WriteLine ($" command = {tools_shell_prefix} {tunerCommand} --gen-icall-table $out $runtime_table $in"); - ninja.WriteLine ("rule gen-pinvoke-table"); - ninja.WriteLine ($" command = {tools_shell_prefix} {tunerCommand} --gen-pinvoke-table \'@$builddir/gen-pinvoke.rsp\'"); - ninja.WriteLine ($" rspfile = $builddir/gen-pinvoke.rsp"); - ninja.WriteLine ($" rspfile_content = $out $pinvoke_libs $in"); - ninja.WriteLine ("rule ilstrip"); - ninja.WriteLine ($" command = {commandPrefix} {cpCommand} $in $out; mono $tools_dir/mono-cil-strip.exe -q $out"); - ninja.WriteLine (" description = [IL-STRIP]"); - - // Targets - ninja.WriteLine ("build $appdir: mkdir"); - ninja.WriteLine ("build $appdir/$deploy_prefix: mkdir"); - ninja.WriteLine ("build $appdir/runtime.js: cpifdiff $builddir/runtime.js"); - ninja.WriteLine ("build $appdir/mono-config.json: cpifdiff $builddir/mono-config.json"); - if (build_wasm) { - var source_file = Path.GetFullPath(Path.Combine(src_prefix, "driver.c")); - ninja.WriteLine($"build $builddir/driver.c: cpifdiff {EscapePath(source_file)}"); - ninja.WriteLine($"build $builddir/driver-gen.c: cpifdiff $builddir/driver-gen.c.in"); - source_file = Path.GetFullPath(Path.Combine(src_prefix, "pinvoke.c")); - ninja.WriteLine($"build $builddir/pinvoke.c: cpifdiff {EscapePath(source_file)}"); - source_file = Path.GetFullPath(Path.Combine(src_prefix, "pinvoke.h")); - ninja.WriteLine($"build $builddir/pinvoke.h: cpifdiff {EscapePath(source_file)}"); - - if (!is_netcore) - { - var pinvoke_file_name = is_netcore ? "pinvoke-table.h" : "pinvoke-tables-default.h"; - var pinvoke_file = Path.GetFullPath(Path.Combine(src_prefix, pinvoke_file_name)); - ninja.WriteLine($"build $builddir/pinvoke-tables-default.h: cpifdiff {EscapePath(pinvoke_file)}"); - driver_deps += $" $builddir/pinvoke-tables-default.h"; - } - - var driver_cflags = enable_aot ? "-DENABLE_AOT=1" : ""; - - if (add_binding) { - var bindings_source_file = Path.GetFullPath (Path.Combine (src_prefix, "corebindings.c")); - ninja.WriteLine ($"build $builddir/corebindings.c: cpifdiff {EscapePath(bindings_source_file)}"); - - ninja.WriteLine ($"build $builddir/corebindings.o: emcc $builddir/corebindings.c | $emsdk_env"); - ninja.WriteLine ($" flags = -I{runtime_dir}/include/mono-2.0"); - driver_cflags += " -DCORE_BINDINGS "; - } - if (gen_pinvoke) - driver_cflags += " -DGEN_PINVOKE "; - if (is_netcore) - driver_cflags += " -DENABLE_NETCORE "; - - ninja.WriteLine ("build $emsdk_env: create-emsdk-env"); - ninja.WriteLine ($"build $builddir/driver.o: emcc $builddir/driver.c | $emsdk_env $builddir/driver-gen.c {driver_deps}"); - ninja.WriteLine ($" flags = {driver_cflags} -DDRIVER_GEN=1 -I{runtime_dir}/include/mono-2.0"); - ninja.WriteLine ($"build $builddir/pinvoke.o: emcc $builddir/pinvoke.c | $emsdk_env {driver_deps}"); - ninja.WriteLine ($" flags = {driver_cflags} -DDRIVER_GEN=1 -I{runtime_dir}/include/mono-2.0"); - - foreach (var nativeCompile in native_compile) - { - var fileName = Path.GetFileName(nativeCompile); - var fileNameWithoutExt = Path.GetFileNameWithoutExtension(nativeCompile); - - ninja.WriteLine($"build $builddir/{fileName}: cpifdiff {EscapePath(source_file)}"); - ninja.WriteLine($"build $builddir/{fileNameWithoutExt}.o: emcc {EscapePath(nativeCompile)} | $emsdk_env {driver_deps}"); - ninja.WriteLine($" flags = {driver_cflags} -DDRIVER_GEN=1 -I{runtime_dir}/include/mono-2.0"); - } - - if (enable_zlib) { - var zlib_source_file = Path.GetFullPath (Path.Combine (src_prefix, "zlib-helper.c")); - ninja.WriteLine ($"build $builddir/zlib-helper.c: cpifdiff {EscapePath(zlib_source_file)}"); - - ninja.WriteLine ($"build $builddir/zlib-helper.o: emcc $builddir/zlib-helper.c | $emsdk_env"); - ninja.WriteLine ($" flags = -s USE_ZLIB=1 -I{runtime_dir}/include/mono-2.0"); - } - } else { - ninja.WriteLine ("build $appdir/dotnet.native.js: cpifdiff $wasm_runtime_dir/dotnet.native.js"); - ninja.WriteLine ("build $appdir/dotnet.native.wasm: cpifdiff $wasm_runtime_dir/dotnet.native.wasm"); - if (enable_threads) { - ninja.WriteLine ("build $appdir/dotnet.native.worker.js: cpifdiff $wasm_runtime_dir/dotnet.native.worker.js"); - } - } - if (enable_aot) - ninja.WriteLine ("build $builddir/aot-in: mkdir"); - { - var list = new List(); - - if (!is_netcore) - { - list.Add("linker-preserves.xml"); - list.Add("linker-subs.xml"); - list.Add("linker-disable-collation.xml"); - } - - foreach (var file in list) { - var source_file = Path.GetFullPath (Path.Combine (src_prefix, file)); - ninja.WriteLine ($"build $builddir/{file}: cpifdiff {EscapePath(source_file)}"); - } - } - var ofiles = ""; - var bc_files = ""; - string linker_infiles = ""; - string linker_ofiles = ""; - string linker_ofiles_dedup = ""; - string dedup_infiles = ""; - if (enable_linker) { - string path = Path.Combine (builddir, "linker-in"); - if (!Directory.Exists (path)) - Directory.CreateDirectory (path); - } - string aot_in_path = enable_linker ? Path.Combine("$builddir","linker-out") : "$builddir"; - foreach (var a in assemblies) { - var assembly = a.src_path; - if (assembly == null) - continue; - string filename = Path.GetFileName (assembly); - - if(a.culture is not null) - { - filename = Path.Combine(a.culture, filename); - } - - var filename_noext = Path.GetFileNameWithoutExtension (filename); - string filename_pdb = Path.ChangeExtension (filename, "pdb"); - var source_file_path = Path.GetFullPath (assembly); - var source_file_path_pdb = Path.ChangeExtension (source_file_path, "pdb"); - string infile = ""; - string infile_pdb = ""; - bool emit_pdb = assemblies_with_dbg_info.Contains (source_file_path_pdb); - if (enable_linker) { - a.linkin_path = Path.Combine("$builddir", "linker-in", filename); - a.linkin_pdb_path = Path.Combine("$builddir", "linker-in", filename_pdb); - a.linkout_path = Path.Combine("$builddir", "linker-out", filename); - a.linkout_pdb_path = Path.Combine("$builddir", "linker-out", filename_pdb); - linker_infiles += $"{a.linkin_path} "; - linker_ofiles += $" {a.linkout_path}"; - - if (a.aot) { - linker_ofiles_dedup += $" {a.linkout_path}"; - } - ninja.WriteLine ($"build {a.linkin_path}: cp {EscapePath(source_file_path)}"); - if (File.Exists(source_file_path_pdb)) { - ninja.WriteLine($"build {a.linkin_pdb_path}: cp {EscapePath(source_file_path_pdb)}"); - linker_ofiles += $" {a.linkout_pdb_path}"; - infile_pdb = a.linkout_pdb_path; - } - a.aotin_path = a.linkout_path; - infile = $"{a.aotin_path}"; - } else { - infile = Path.Combine("$builddir", filename); - ninja.WriteLine ($"build $builddir/{filename}: cpifdiff {EscapePath(source_file_path)}"); - a.linkout_path = infile; - if (emit_pdb) { - ninja.WriteLine ($"build $builddir/{filename_pdb}: cpifdiffex {EscapePath(source_file_path_pdb)}"); - infile_pdb = $"$builddir/{filename_pdb}"; - } - } - - a.final_path = infile; - if (il_strip) { - ninja.WriteLine ($"build $builddir/ilstrip-out/{filename} : ilstrip {infile}"); - a.final_path = $"$builddir/ilstrip-out/{filename}"; - } - - ninja.WriteLine ($"build $appdir/$deploy_prefix/{filename}: cpifdiff {EscapePath(a.final_path)}"); - if (emit_pdb && infile_pdb != "") - ninja.WriteLine ($"build $appdir/$deploy_prefix/{filename_pdb}: cpifdiffex {EscapePath(infile_pdb)}"); - if (a.aot) { - a.bc_path = $"$builddir/{filename}.bc"; - a.o_path = $"$builddir/{filename}.o"; - a.aot_depfile_path = $"$builddir/linker-out/{filename}.depfile"; - - if (filename == "mscorlib.dll") { - // mscorlib has no dependencies so we can skip the aot step if the input didn't change - // The other assemblies depend on their references - infile = "$builddir/aot-in/mscorlib.dll"; - a.aotin_path = infile; - ninja.WriteLine ($"build {a.aotin_path}: cpifdiff {EscapePath(a.linkout_path)}"); - } - ninja.WriteLine ($"build {a.bc_path}.tmp: aot {infile}"); - ninja.WriteLine ($" src_file={infile}"); - ninja.WriteLine ($" outfile={a.bc_path}.tmp"); - if (is_windows) - { - ninja.WriteLine($" mono_path={aot_in_path}"); - } - else - { - ninja.WriteLine($" mono_path=$builddir/aot-in:{aot_in_path}"); - } - ninja.WriteLine ($" depfile={a.aot_depfile_path}"); - if (enable_dedup) - ninja.WriteLine ($" aot_args=dedup-skip"); - - ninja.WriteLine ($"build {a.bc_path}: cpifdiff {EscapePath(a.bc_path)}.tmp"); - ninja.WriteLine ($"build {a.o_path}: emcc {a.bc_path} | $emsdk_env"); - - ofiles += " " + $"{a.o_path}"; - bc_files += " " + $"{a.bc_path}"; - dedup_infiles += $" {a.aotin_path}"; - } - } - if (enable_dedup) { - /* - * Run the aot compiler in dedup mode: - * mono --aot=,dedup-include=aot-instances.dll aot-instances.dll - * This will process all assemblies and emit all instances into the aot image of aot-instances.dll - */ - var a = dedup_asm; - /* - * The dedup process will read in the .dedup files created when running with dedup-skip, so add all the - * .bc files as dependencies. - */ - ninja.WriteLine ($"build {a.bc_path}.tmp: aot-instances | {bc_files} {a.linkout_path}"); - ninja.WriteLine ($" dedup_image={a.filename}"); - ninja.WriteLine ($" src_files={dedup_infiles} {a.linkout_path}"); - ninja.WriteLine ($" outfile={a.bc_path}.tmp"); - - if (is_windows) - { - ninja.WriteLine($" mono_path={aot_in_path}"); - } - else - { - ninja.WriteLine($" mono_path=$builddir/aot-in:{aot_in_path}"); - } - - ninja.WriteLine ($"build {a.app_path}: cpifdiff {EscapePath(a.linkout_path)}"); - ninja.WriteLine ($"build {a.linkout_path}: aot-instances-dll"); - // The dedup image might not have changed - ninja.WriteLine ($"build {a.bc_path}: cpifdiff {EscapePath(a.bc_path)}.tmp"); - ninja.WriteLine ($"build {a.o_path}: emcc {a.bc_path} | $emsdk_env"); - ofiles += $" {a.o_path}"; - } - - if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - ninja.WriteLine("build $builddir/icall-table.json: gen-runtime-icall-table"); - } - - if (link_icalls) { - - string icall_assemblies = ""; - foreach (var a in assemblies.Where(a => a.culture is null)) { - if (a.name == "mscorlib" || a.name == "System") - icall_assemblies += $"{a.linkout_path} "; - } - ninja.WriteLine ($"build $builddir/icall-table.h: gen-icall-table {icall_assemblies}"); - ninja.WriteLine ($" runtime_table=$builddir/icall-table.json"); - } - else - { - // Fake a command so that __static_icalls__ gets to the tuner - ninja.WriteLine ("build __static_icalls__: mkdir"); - } - if (gen_pinvoke) { - string pinvoke_assemblies = ""; - foreach (var a in assemblies.Where(a => a.culture is null)) - pinvoke_assemblies += $"{a.linkout_path} "; - - ninja.WriteLine ($"build $builddir/pinvoke-table.h: cpifdiff $builddir/pinvoke-table.h.tmp"); - - var icallTable = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "__static_icalls__" : "$builddir/icall-table.json"; - ninja.WriteLine ($"build $builddir/pinvoke-table.h.tmp: gen-pinvoke-table {icallTable} {pinvoke_assemblies}"); - - if (is_netcore) - { - ninja.WriteLine($" pinvoke_libs=libSystem.Native,libSystem.IO.Compression.Native,libSystem.Globalization.Native,QCall,{pinvoke_libs}"); - } - else - { - ninja.WriteLine($" pinvoke_libs=System.Native,{pinvoke_libs}"); - } - } - if (build_wasm) { - string zlibhelper = enable_zlib ? "$builddir/zlib-helper.o" : ""; - - var native_compile_params = string.Join(" ", native_compile.Select(f => $"$builddir/{Path.GetFileNameWithoutExtension(f)}.o")); - - ninja.WriteLine ($"build $appdir/dotnet.native.js $appdir/dotnet.native.wasm: emcc-link $builddir/driver.o $builddir/pinvoke.o {native_compile_params} {zlibhelper} {wasm_core_bindings} {ofiles} {profiler_libs} {extra_link_libs} {runtime_libs} | {EscapePath(src_prefix)}/es6/dotnet.es6.lib.js {wasm_core_support} $emsdk_env"); - ninja.WriteLine ($" out_wasm=$appdir/dotnet.native.wasm"); - ninja.WriteLine ($" out_js=$appdir/dotnet.native.js"); - } - if (enable_linker) { - switch (linkMode) { - case LinkMode.SdkOnly: - usermode = "copy"; - break; - case LinkMode.All: - usermode = "link"; - break; - default: - usermode = "link"; - break; - } - - // Removed because of https://github.com/dotnet/runtime/issues/65325 - //if (enable_aot) - // // Only used by the AOT compiler - // linker_args.Add("--explicit-reflection "); - - // disabled to align with the .NET SDK default behavior (https://github.com/dotnet/runtime/issues/90745) - // linker_args.Add("--used-attrs-only true "); - - if (!is_netcore) - { - linker_args.Add("--substitutions linker-subs.xml "); - linker_infiles += "| linker-subs.xml "; - linker_args.Add("-x linker-preserves.xml "); - linker_infiles += "linker-preserves.xml "; - } - - if (opts.LinkerExcludeDeserialization && !is_netcore) - linker_args.Add("--exclude-feature deserialization "); - - if (!opts.EnableCollation && !is_netcore) { - linker_args.Add("--substitutions linker-disable-collation.xml "); - linker_infiles += "linker-disable-collation.xml"; - } - if (opts.Debug) { - linker_args.Add("-b true "); - } - if (!string.IsNullOrEmpty (linkDescriptor)) { - linker_args.Add($"-x {linkDescriptor} "); - foreach (var assembly in root_assemblies) { - string filename = Path.GetFileName (assembly); - linker_args.Add($"-p {usermode} {filename} -r linker-in/{filename} "); - } - } else { - foreach (var assembly in root_assemblies) { - string filename = Path.GetFileName (assembly); - linker_args.Add($"-a linker-in/{filename} {(IsSupportAssembly(filename) ? string.Empty : "entrypoint")} "); - } - } - - if (linker_verbose) { - linker_args.Add("--verbose "); - } - linker_args.Add($"-d linker-in -d {bcl_prefix} -d {bcl_facades_prefix} -d {bcl_facades_prefix} "); - - // Metadata linking https://github.com/mono/linker/commit/fafb6cf6a385a8c753faa174b9ab7c3600a9d494 - linker_args.Add($"--keep-metadata all "); - - linker_args.Add($" --verbose "); - - ninja.WriteLine ("build $builddir/linker-out: mkdir"); - ninja.WriteLine ($"build {linker_ofiles}: linker {linker_infiles}"); - - File.WriteAllLines(linkerResponse, linker_args); - } - if (il_strip) - ninja.WriteLine ("build $builddir/ilstrip-out: mkdir"); - - foreach(var asset in assets) { - var filename = Path.GetFileName (asset); - var abs_path = Path.GetFullPath (asset); - ninja.WriteLine ($"build $appdir/{filename}: cpifdiff {abs_path}"); - } - - ninja.Close (); - - return 0; - } - - private bool IsResourceAssembly(string f, out string culture) - { - if (f.EndsWith(".resources.dll", StringComparison.OrdinalIgnoreCase)) - { - var originalAssembly = Path.GetFileName(f.Replace(".resources.dll", ".dll", StringComparison.OrdinalIgnoreCase)); - - var resourceAssemblyDirectory = Path.GetDirectoryName(Path.GetDirectoryName(f)); - if (File.Exists(Path.Combine(resourceAssemblyDirectory, originalAssembly))) - { - culture = Path.GetFileName(Path.GetDirectoryName(f)); - - return true; - } - } - - culture = null; - return false; - } - - private static bool IsSupportAssembly(string filename) - => - filename switch - { - "Uno.Wasm.AotProfiler.dll" => true, - "Uno.Wasm.LogProfiler.dll" => true, - "Uno.Wasm.MetadataUpdater.dll" => true, - _ => false - }; - - static void CopyFile(string sourceFileName, string destFileName, CopyType copyType, string typeFile = "") - { - Console.WriteLine($"{typeFile}cp: {copyType} - {sourceFileName} -> {destFileName}"); - - Directory.CreateDirectory(Path.GetDirectoryName(destFileName)); - - switch (copyType) - { - case CopyType.Always: - File.Copy(sourceFileName, destFileName, true); - break; - case CopyType.IfNewer: - if (!File.Exists(destFileName)) - { - File.Copy(sourceFileName, destFileName); - } - else - { - var srcInfo = new FileInfo (sourceFileName); - var dstInfo = new FileInfo (destFileName); - - if (srcInfo.LastWriteTime.Ticks > dstInfo.LastWriteTime.Ticks || srcInfo.Length > dstInfo.Length) - File.Copy(sourceFileName, destFileName, true); - else - Console.WriteLine($" skipping: {sourceFileName}"); - } - break; - default: - File.Copy(sourceFileName, destFileName); - break; - } - - } - - private string EscapePath(string path) - => path.Replace(" ", "$ ").Replace(":", "$:"); -} diff --git a/src/Uno.Wasm.Sample.RayTracer.Shared/Program.cs b/src/Uno.Wasm.Sample.RayTracer.Shared/Program.cs index fc681cce6..e401b45ff 100644 --- a/src/Uno.Wasm.Sample.RayTracer.Shared/Program.cs +++ b/src/Uno.Wasm.Sample.RayTracer.Shared/Program.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; +using System.Threading.Tasks; using RayTraceBenchmark; using WebAssembly; @@ -10,8 +11,12 @@ namespace Uno.Wasm.Test.Empty { class Program { - static int Main(string[] args) + static async Task Main(string[] args) { + await Task.Yield(); + + Runtime.InvokeJS($"Interop.appendResult(\"test\")"); + System.Console.WriteLine($"Mono Runtime Mode: " + Environment.GetEnvironmentVariable("UNO_BOOTSTRAP_MONO_RUNTIME_MODE")); var w = Stopwatch.StartNew(); diff --git a/src/Uno.Wasm.Sample.RayTracer/Uno.Wasm.Sample.RayTracer.csproj b/src/Uno.Wasm.Sample.RayTracer/Uno.Wasm.Sample.RayTracer.csproj index 80394b842..ae836d8a5 100644 --- a/src/Uno.Wasm.Sample.RayTracer/Uno.Wasm.Sample.RayTracer.csproj +++ b/src/Uno.Wasm.Sample.RayTracer/Uno.Wasm.Sample.RayTracer.csproj @@ -1,7 +1,7 @@ - + - net6.0 + net9.0 Exe false true @@ -10,27 +10,28 @@ $(DefineConstants);__WASM__;UWP manifest.json - true + True + true + true + + $(MSBuildThisFileDirectory)aot.profile + + - + - - false - true - TargetFramework - false true @@ -38,24 +39,25 @@ - - - - - + + + + <_appOutput>$(PublishDir)wwwroot + + <_AdditionalFile1 Include="pwa-images\android\android-launchericon-144-144.png" /> <_AdditionalFile1 Include="pwa-images\windows10\SplashScreen.scale-100.png" /> - - + + diff --git a/src/Uno.Wasm.Sample.Server.Net7/Uno.Wasm.Sample.Server.Net7.csproj b/src/Uno.Wasm.Sample.Server.Net7/Uno.Wasm.Sample.Server.Net7.csproj index 2a55999b2..c78e7c4a1 100644 --- a/src/Uno.Wasm.Sample.Server.Net7/Uno.Wasm.Sample.Server.Net7.csproj +++ b/src/Uno.Wasm.Sample.Server.Net7/Uno.Wasm.Sample.Server.Net7.csproj @@ -1,7 +1,7 @@ - net7.0 + net9.0 enable LatestMajor diff --git a/src/Uno.Wasm.Sample/Program.cs b/src/Uno.Wasm.Sample/Program.cs index 0b891a1a3..9224eae43 100644 --- a/src/Uno.Wasm.Sample/Program.cs +++ b/src/Uno.Wasm.Sample/Program.cs @@ -19,6 +19,8 @@ using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Globalization; +using System.Runtime.InteropServices.JavaScript; +using System.Threading.Tasks; namespace Uno.Wasm.Sample { @@ -59,13 +61,20 @@ static void Main(string[] args) #endif Console.WriteLine($"requireJSAvailable: {requireAvailable}"); + Console.WriteLine($"CultureInfo.CurrentCulture: {CultureInfo.CurrentCulture}"); + Console.WriteLine($"CultureInfo.CurrentUICulture: {CultureInfo.CurrentUICulture}"); + Console.WriteLine($"Thread.CurrentThread.CurrentCulture: {Thread.CurrentThread.CurrentCulture}"); + Console.WriteLine($"Thread.CurrentThread.CurrentUICulture: {Thread.CurrentThread.CurrentUICulture}"); + Console.WriteLine($"CultureInfo.DefaultThreadCurrentCulture: { CultureInfo.DefaultThreadCurrentCulture?.ToString() ?? "" }"); + Console.WriteLine($"CultureInfo.DefaultThreadCurrentUICulture: { CultureInfo.DefaultThreadCurrentUICulture?.ToString() ?? ""}"); + Console.WriteLine($"Timezone: {TimeZoneInfo.Local.StandardName}"); Console.WriteLine(typeof(Microsoft.Extensions.Logging.Abstractions.NullLogger)); var r = new System.Resources.ResourceManager("FxResources.System.Web.Services.Description.SR", typeof(System.Web.Services.Description.Binding).Assembly); Console.WriteLine($"Res(en): {r.GetString("WebDescriptionMissing", new CultureInfo("en-US"))}"); - Console.WriteLine($"Res(fr): {r.GetString("WebDescriptionMissing", new CultureInfo("fr-CA"))}"); + Console.WriteLine($"Res(fr): {r.GetString("WebDescriptionMissing", new CultureInfo("fr"))}"); _t = new Timer(_ => { Console.WriteLine("message"); @@ -84,6 +93,9 @@ public static partial class Imports [System.Runtime.InteropServices.JavaScript.JSImport("globalThis.isRequireAvailable")] public static partial bool IsRequireAvailable(); + + [JSImport("INTERNAL.loadSatelliteAssemblies")] + internal static partial Task LoadSatelliteAssemblies(string[] culturesToLoad); } #endif diff --git a/src/Uno.Wasm.Sample/Runtime.cs b/src/Uno.Wasm.Sample/Runtime.cs index 3b9d34303..fb78b2dec 100644 --- a/src/Uno.Wasm.Sample/Runtime.cs +++ b/src/Uno.Wasm.Sample/Runtime.cs @@ -8,3 +8,4 @@ internal sealed class Runtime public static extern string InvokeJS(string str, out int exceptional_result); } } + diff --git a/src/Uno.Wasm.Sample/WasmScripts/test.js b/src/Uno.Wasm.Sample/WasmScripts/test.js index 66bfdab29..f830c08a5 100644 --- a/src/Uno.Wasm.Sample/WasmScripts/test.js +++ b/src/Uno.Wasm.Sample/WasmScripts/test.js @@ -8,10 +8,10 @@ async function initializeExports() { if (Module.getAssemblyExports !== undefined) { try { - globalThis.samplesNetExports = await Module.getAssemblyExports("Uno.Wasm.SampleNet"); + globalThis.samplesNetExports = await Module.getAssemblyExports("Uno.Wasm.SampleNet7"); } catch (e) { - log.error(e); + console.error(e); } } } @@ -27,12 +27,13 @@ function isRequireAvailable() { } function testCallback() { + try { if (Module.getAssemblyExports !== undefined && samplesNetExports.hasOwnProperty('Uno')) { return samplesNetExports.Uno.Wasm.Sample.Exports.MyExportedMethod1(); } else { - return Module.mono_bind_static_method("[Uno.Wasm.SampleNet] Uno.Wasm.Sample.Exports:MyExportedMethod2")(); + return Module.mono_bind_static_method("[Uno.Wasm.SampleNet7] Uno.Wasm.Sample.Exports:MyExportedMethod2")(); } } catch (e) { diff --git a/src/Uno.Wasm.Sample/sample.common.props b/src/Uno.Wasm.Sample/sample.common.props index 0fa29c2a8..8976d6148 100644 --- a/src/Uno.Wasm.Sample/sample.common.props +++ b/src/Uno.Wasm.Sample/sample.common.props @@ -2,7 +2,6 @@ - @@ -20,7 +19,10 @@ - Uno.Wasm.SampleNet + Uno.Wasm.SampleNet7 + true + + true @@ -29,50 +31,7 @@ - - - <_AdditionalFile1 Include="SomeContent01.txt" /> - <_AdditionalFile1 Include="SomeContent02.txt" /> - <_AdditionalFile1 Include=".editorconfig" /> - <_AdditionalFile1 Include="nuget.config" /> - - <_duplicateValidationItems Include="$(WasmShellOutputPackagePath)\**\System.Private.CoreLib.clr" /> - - - - <_monoConfigJson>$([System.IO.File]::ReadAllText('$(WasmShellOutputPackagePath)\mono-config.json')) - <_duplicateValidation>@(_duplicateValidationItems) - - - - - - - - - - - - - - - - - - - - - - - false - true - TargetFramework - false true diff --git a/src/Uno.Wasm.SampleNet6.Aot/Uno.Wasm.SampleNet6.Aot.csproj b/src/Uno.Wasm.SampleNet6.Aot/Uno.Wasm.SampleNet6.Aot.csproj index bfcfee888..92cf605f7 100644 --- a/src/Uno.Wasm.SampleNet6.Aot/Uno.Wasm.SampleNet6.Aot.csproj +++ b/src/Uno.Wasm.SampleNet6.Aot/Uno.Wasm.SampleNet6.Aot.csproj @@ -1,16 +1,14 @@ - + - net5 - Exe - false - Uno.Wasm.Sample.Program + net9.0 true InterpreterAndAOT true true + true @@ -26,8 +24,8 @@ + - @@ -44,11 +42,6 @@ - - false - true - TargetFramework - false true diff --git a/src/Uno.Wasm.SampleNet6.LogProfiler/LinkerConfig.xml b/src/Uno.Wasm.SampleNet6.LogProfiler/LinkerConfig.xml deleted file mode 100644 index 635cbeb02..000000000 --- a/src/Uno.Wasm.SampleNet6.LogProfiler/LinkerConfig.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/src/Uno.Wasm.SampleNet6.LogProfiler/Uno.Wasm.SampleNet6.LogProfiler.csproj b/src/Uno.Wasm.SampleNet6.LogProfiler/Uno.Wasm.SampleNet6.LogProfiler.csproj deleted file mode 100644 index 4429e5376..000000000 --- a/src/Uno.Wasm.SampleNet6.LogProfiler/Uno.Wasm.SampleNet6.LogProfiler.csproj +++ /dev/null @@ -1,35 +0,0 @@ - - - - net6.0 - Exe - false - Uno.Wasm.Sample.Program - / - - true - - - true - - true - - - - - - - - - - - - - - - - - - - - diff --git a/src/Uno.Wasm.SampleNet6.LogProfiler/wwwroot/favicon.ico b/src/Uno.Wasm.SampleNet6.LogProfiler/wwwroot/favicon.ico deleted file mode 100644 index 131108413..000000000 Binary files a/src/Uno.Wasm.SampleNet6.LogProfiler/wwwroot/favicon.ico and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6.LogProfiler/wwwroot/web.config b/src/Uno.Wasm.SampleNet6.LogProfiler/wwwroot/web.config deleted file mode 100644 index 9385f43a9..000000000 --- a/src/Uno.Wasm.SampleNet6.LogProfiler/wwwroot/web.config +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Uno.Wasm.SampleNet6/LinkerConfig.xml b/src/Uno.Wasm.SampleNet6/LinkerConfig.xml deleted file mode 100644 index ed78e52b0..000000000 --- a/src/Uno.Wasm.SampleNet6/LinkerConfig.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/Uno.Wasm.SampleNet6/Uno.Wasm.SampleNet6.csproj b/src/Uno.Wasm.SampleNet6/Uno.Wasm.SampleNet6.csproj deleted file mode 100644 index de0e75cba..000000000 --- a/src/Uno.Wasm.SampleNet6/Uno.Wasm.SampleNet6.csproj +++ /dev/null @@ -1,31 +0,0 @@ - - - - net6.0 - Exe - false - Uno.Wasm.Sample.Program - / - - - - - true - - true - - - - - - - - - - - - - - - - diff --git a/src/Uno.Wasm.SampleNet6/favicon.ico b/src/Uno.Wasm.SampleNet6/favicon.ico deleted file mode 100644 index 131108413..000000000 Binary files a/src/Uno.Wasm.SampleNet6/favicon.ico and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/web.config b/src/Uno.Wasm.SampleNet6/web.config deleted file mode 100644 index 9385f43a9..000000000 --- a/src/Uno.Wasm.SampleNet6/web.config +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/favicon.ico b/src/Uno.Wasm.SampleNet6/wwwroot/favicon.ico deleted file mode 100644 index 131108413..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/favicon.ico and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-144-144.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-144-144.png deleted file mode 100644 index e8388115e..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-144-144.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-192-192.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-192-192.png deleted file mode 100644 index a135ee16d..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-192-192.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-48-48.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-48-48.png deleted file mode 100644 index cb5e47bf2..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-48-48.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-512-512.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-512-512.png deleted file mode 100644 index b74932f18..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-512-512.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-72-72.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-72-72.png deleted file mode 100644 index eb4e32b6c..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-72-72.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-96-96.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-96-96.png deleted file mode 100644 index d7ff4321a..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/android/android-launchericon-96-96.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/chrome/chrome-extensionmanagementpage-48-48.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/chrome/chrome-extensionmanagementpage-48-48.png deleted file mode 100644 index cb5e47bf2..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/chrome/chrome-extensionmanagementpage-48-48.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/chrome/chrome-favicon-16-16.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/chrome/chrome-favicon-16-16.png deleted file mode 100644 index acac95c18..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/chrome/chrome-favicon-16-16.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/chrome/chrome-installprocess-128-128.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/chrome/chrome-installprocess-128-128.png deleted file mode 100644 index b3329f082..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/chrome/chrome-installprocess-128-128.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-128-128.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-128-128.png deleted file mode 100644 index b3329f082..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-128-128.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-16-16.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-16-16.png deleted file mode 100644 index acac95c18..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-16-16.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-256-256.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-256-256.png deleted file mode 100644 index a305069e5..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-256-256.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-32-32.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-32-32.png deleted file mode 100644 index 16adaf420..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-32-32.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-48-48.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-48-48.png deleted file mode 100644 index cb5e47bf2..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-48-48.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-64-64.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-64-64.png deleted file mode 100644 index 43adca5e1..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-64-64.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-90-90.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-90-90.png deleted file mode 100644 index 1b515a81b..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-general-90-90.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-marketplace-128-128.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-marketplace-128-128.png deleted file mode 100644 index b3329f082..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-marketplace-128-128.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-marketplace-512-512.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-marketplace-512-512.png deleted file mode 100644 index b74932f18..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/firefox/firefox-marketplace-512-512.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-appicon-1024-1024.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-appicon-1024-1024.png deleted file mode 100644 index 92c7a4d56..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-appicon-1024-1024.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-appicon-120-120.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-appicon-120-120.png deleted file mode 100644 index a9fd2651f..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-appicon-120-120.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-appicon-152-152.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-appicon-152-152.png deleted file mode 100644 index c48c22fc4..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-appicon-152-152.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-appicon-180-180.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-appicon-180-180.png deleted file mode 100644 index f0a0ed233..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-appicon-180-180.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-appicon-76-76.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-appicon-76-76.png deleted file mode 100644 index dd31b6be9..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-appicon-76-76.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-1024-768.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-1024-768.png deleted file mode 100644 index 1cc966690..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-1024-768.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-1242-2208.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-1242-2208.png deleted file mode 100644 index fa4c609dc..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-1242-2208.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-1334-750.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-1334-750.png deleted file mode 100644 index b255efa26..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-1334-750.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-1536-2048.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-1536-2048.png deleted file mode 100644 index 0cf7a1f88..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-1536-2048.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-2048-1536.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-2048-1536.png deleted file mode 100644 index ff2a88e72..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-2048-1536.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-2208-1242.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-2208-1242.png deleted file mode 100644 index e811a2d92..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-2208-1242.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-640-1136.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-640-1136.png deleted file mode 100644 index 0a9902a74..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-640-1136.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-640-960.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-640-960.png deleted file mode 100644 index 18e773e7e..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-640-960.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-750-1334.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-750-1334.png deleted file mode 100644 index 8f22f7ff8..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-750-1334.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-768-1024.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-768-1024.png deleted file mode 100644 index 951844dab..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/ios/ios-launchimage-768-1024.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-smallsquare-24-24.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-smallsquare-24-24.png deleted file mode 100644 index eb0398738..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-smallsquare-24-24.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-smallsquare-30-30.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-smallsquare-30-30.png deleted file mode 100644 index d0f92a363..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-smallsquare-30-30.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-smallsquare-42-42.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-smallsquare-42-42.png deleted file mode 100644 index 4056ff4ac..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-smallsquare-42-42.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-smallsquare-54-54.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-smallsquare-54-54.png deleted file mode 100644 index 717da1314..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-smallsquare-54-54.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-splashscreen-1116-540.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-splashscreen-1116-540.png deleted file mode 100644 index 815b05e4e..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-splashscreen-1116-540.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-splashscreen-620-300.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-splashscreen-620-300.png deleted file mode 100644 index 6c31a63a7..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-splashscreen-620-300.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-splashscreen-868-420.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-splashscreen-868-420.png deleted file mode 100644 index accc7a793..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-splashscreen-868-420.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-squarelogo-120-120.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-squarelogo-120-120.png deleted file mode 100644 index a9fd2651f..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-squarelogo-120-120.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-squarelogo-150-150.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-squarelogo-150-150.png deleted file mode 100644 index c2260a841..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-squarelogo-150-150.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-squarelogo-210-210.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-squarelogo-210-210.png deleted file mode 100644 index 6e7d0d1cf..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-squarelogo-210-210.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-squarelogo-270-270.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-squarelogo-270-270.png deleted file mode 100644 index 36c1d1a4b..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-squarelogo-270-270.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-storelogo-50-50.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-storelogo-50-50.png deleted file mode 100644 index bc585363f..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-storelogo-50-50.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-storelogo-70-70.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-storelogo-70-70.png deleted file mode 100644 index 6e1d9bb52..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-storelogo-70-70.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-storelogo-90-90.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-storelogo-90-90.png deleted file mode 100644 index 1b515a81b..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windows-storelogo-90-90.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-appicon-106-106.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-appicon-106-106.png deleted file mode 100644 index 142d90969..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-appicon-106-106.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-appicon-44-44.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-appicon-44-44.png deleted file mode 100644 index 1b47f4790..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-appicon-44-44.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-appicon-62-62.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-appicon-62-62.png deleted file mode 100644 index 2ef84f401..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-appicon-62-62.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-mediumtile-150-150.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-mediumtile-150-150.png deleted file mode 100644 index c2260a841..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-mediumtile-150-150.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-mediumtile-210-210.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-mediumtile-210-210.png deleted file mode 100644 index 6e7d0d1cf..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-mediumtile-210-210.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-mediumtile-360-360.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-mediumtile-360-360.png deleted file mode 100644 index 8ececfbff..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-mediumtile-360-360.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-smalltile-170-170.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-smalltile-170-170.png deleted file mode 100644 index 0be719eb0..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-smalltile-170-170.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-smalltile-71-71.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-smalltile-71-71.png deleted file mode 100644 index 724116ebe..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-smalltile-71-71.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-smalltile-99-99.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-smalltile-99-99.png deleted file mode 100644 index a4603f20c..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-smalltile-99-99.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-storelogo-120-120.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-storelogo-120-120.png deleted file mode 100644 index a9fd2651f..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-storelogo-120-120.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-storelogo-50-50.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-storelogo-50-50.png deleted file mode 100644 index bc585363f..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-storelogo-50-50.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-storelogo-70-70.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-storelogo-70-70.png deleted file mode 100644 index 6e1d9bb52..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows/windowsphone-storelogo-70-70.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/SplashScreen.scale-100.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/SplashScreen.scale-100.png deleted file mode 100644 index 6c31a63a7..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/SplashScreen.scale-100.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/SplashScreen.scale-125.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/SplashScreen.scale-125.png deleted file mode 100644 index b1f07c7b1..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/SplashScreen.scale-125.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/SplashScreen.scale-150.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/SplashScreen.scale-150.png deleted file mode 100644 index d222e0bb3..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/SplashScreen.scale-150.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/SplashScreen.scale-200.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/SplashScreen.scale-200.png deleted file mode 100644 index 8c265cf27..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/SplashScreen.scale-200.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/SplashScreen.scale-400.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/SplashScreen.scale-400.png deleted file mode 100644 index 010c53f6b..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/SplashScreen.scale-400.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square150x150Logo.scale-100.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square150x150Logo.scale-100.png deleted file mode 100644 index c2260a841..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square150x150Logo.scale-100.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square150x150Logo.scale-125.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square150x150Logo.scale-125.png deleted file mode 100644 index 88d6b0512..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square150x150Logo.scale-125.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square150x150Logo.scale-150.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square150x150Logo.scale-150.png deleted file mode 100644 index d16d65a37..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square150x150Logo.scale-150.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square150x150Logo.scale-200.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square150x150Logo.scale-200.png deleted file mode 100644 index 9ad09e66a..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square150x150Logo.scale-200.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square150x150Logo.scale-400.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square150x150Logo.scale-400.png deleted file mode 100644 index 62076cb25..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square150x150Logo.scale-400.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square310x310Logo.scale-100.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square310x310Logo.scale-100.png deleted file mode 100644 index dbf326c2c..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square310x310Logo.scale-100.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square310x310Logo.scale-125.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square310x310Logo.scale-125.png deleted file mode 100644 index 2f773bc66..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square310x310Logo.scale-125.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square310x310Logo.scale-150.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square310x310Logo.scale-150.png deleted file mode 100644 index 9d021d777..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square310x310Logo.scale-150.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square310x310Logo.scale-200.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square310x310Logo.scale-200.png deleted file mode 100644 index 6869ac3b8..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square310x310Logo.scale-200.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square310x310Logo.scale-400.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square310x310Logo.scale-400.png deleted file mode 100644 index 23f9b56e3..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square310x310Logo.scale-400.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.scale-100.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.scale-100.png deleted file mode 100644 index 1b47f4790..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.scale-100.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.scale-125.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.scale-125.png deleted file mode 100644 index 2eacba1ce..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.scale-125.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.scale-150.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.scale-150.png deleted file mode 100644 index 21ded376c..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.scale-150.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.scale-200.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.scale-200.png deleted file mode 100644 index 1cf187ef0..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.scale-200.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.scale-400.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.scale-400.png deleted file mode 100644 index 9f74108f4..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.scale-400.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-16.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-16.png deleted file mode 100644 index acac95c18..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-16.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-16_altform-unplated.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-16_altform-unplated.png deleted file mode 100644 index acac95c18..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-16_altform-unplated.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-24.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-24.png deleted file mode 100644 index eb0398738..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-24.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-24_altform-unplated.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-24_altform-unplated.png deleted file mode 100644 index eb0398738..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-24_altform-unplated.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-256.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-256.png deleted file mode 100644 index a305069e5..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-256.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-256_altform-unplated.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-256_altform-unplated.png deleted file mode 100644 index a305069e5..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-256_altform-unplated.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-48.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-48.png deleted file mode 100644 index cb5e47bf2..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-48.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-48_altform-unplated.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-48_altform-unplated.png deleted file mode 100644 index cb5e47bf2..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square44x44Logo.targetsize-48_altform-unplated.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square71x71Logo.scale-100.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square71x71Logo.scale-100.png deleted file mode 100644 index 724116ebe..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square71x71Logo.scale-100.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square71x71Logo.scale-125.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square71x71Logo.scale-125.png deleted file mode 100644 index f46e0ad2b..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square71x71Logo.scale-125.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square71x71Logo.scale-150.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square71x71Logo.scale-150.png deleted file mode 100644 index 3c9b37bcb..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square71x71Logo.scale-150.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square71x71Logo.scale-200.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square71x71Logo.scale-200.png deleted file mode 100644 index 785df9c25..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square71x71Logo.scale-200.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square71x71Logo.scale-400.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square71x71Logo.scale-400.png deleted file mode 100644 index febcb3f3e..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Square71x71Logo.scale-400.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.png deleted file mode 100644 index bc585363f..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.scale-100.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.scale-100.png deleted file mode 100644 index bc585363f..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.scale-100.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.scale-125.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.scale-125.png deleted file mode 100644 index 9def8089a..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.scale-125.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.scale-150.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.scale-150.png deleted file mode 100644 index 9a2f80134..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.scale-150.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.scale-200.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.scale-200.png deleted file mode 100644 index d7b20290c..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.scale-200.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.scale-400.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.scale-400.png deleted file mode 100644 index 0224c8956..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/StoreLogo.scale-400.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Wide310x150Logo.scale-100.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Wide310x150Logo.scale-100.png deleted file mode 100644 index 01a7ecee3..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Wide310x150Logo.scale-100.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Wide310x150Logo.scale-125.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Wide310x150Logo.scale-125.png deleted file mode 100644 index 649fbaa18..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Wide310x150Logo.scale-125.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Wide310x150Logo.scale-150.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Wide310x150Logo.scale-150.png deleted file mode 100644 index 5e8425c81..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Wide310x150Logo.scale-150.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Wide310x150Logo.scale-200.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Wide310x150Logo.scale-200.png deleted file mode 100644 index 6c31a63a7..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Wide310x150Logo.scale-200.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Wide310x150Logo.scale-400.png b/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Wide310x150Logo.scale-400.png deleted file mode 100644 index 8c265cf27..000000000 Binary files a/src/Uno.Wasm.SampleNet6/wwwroot/pwa-images/windows10/Wide310x150Logo.scale-400.png and /dev/null differ diff --git a/src/Uno.Wasm.SampleNet6/wwwroot/web.config b/src/Uno.Wasm.SampleNet6/wwwroot/web.config deleted file mode 100644 index 9385f43a9..000000000 --- a/src/Uno.Wasm.SampleNet6/wwwroot/web.config +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Uno.Wasm.SampleNet7/Uno.Wasm.SampleNet7.csproj b/src/Uno.Wasm.SampleNet7/Uno.Wasm.SampleNet7.csproj index 6f47f67c9..579424379 100644 --- a/src/Uno.Wasm.SampleNet7/Uno.Wasm.SampleNet7.csproj +++ b/src/Uno.Wasm.SampleNet7/Uno.Wasm.SampleNet7.csproj @@ -1,11 +1,14 @@ - + - net7.0 + net9.0 Exe false Uno.Wasm.Sample.Program - / + + + + @@ -15,6 +18,8 @@ true latest true + false + --jiterpreter-stats-enabled diff --git a/src/Uno.Wasm.SampleNet7/wwwroot/web.config b/src/Uno.Wasm.SampleNet7/wwwroot/web.config deleted file mode 100644 index b4c347b28..000000000 --- a/src/Uno.Wasm.SampleNet7/wwwroot/web.config +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Uno.Wasm.Static Linking/Uno.Wasm.StaticLinking.csproj b/src/Uno.Wasm.Static Linking/Uno.Wasm.StaticLinking.csproj index 5cb2d15c0..03665db50 100644 --- a/src/Uno.Wasm.Static Linking/Uno.Wasm.StaticLinking.csproj +++ b/src/Uno.Wasm.Static Linking/Uno.Wasm.StaticLinking.csproj @@ -1,7 +1,7 @@ - + - net5.0 + net9.0 Uno.Wasm.StaticLinking Exe false @@ -15,12 +15,13 @@ - + + + - @@ -41,11 +42,6 @@ - - false - true - TargetFramework - false true @@ -53,4 +49,4 @@ - \ No newline at end of file + diff --git a/src/Uno.Wasm.StaticLinking.Aot.Net6/Uno.Wasm.StaticLinking.Aot.Net6.csproj b/src/Uno.Wasm.StaticLinking.Aot.Net6/Uno.Wasm.StaticLinking.Aot.Net6.csproj index d1664b980..c722944d2 100644 --- a/src/Uno.Wasm.StaticLinking.Aot.Net6/Uno.Wasm.StaticLinking.Aot.Net6.csproj +++ b/src/Uno.Wasm.StaticLinking.Aot.Net6/Uno.Wasm.StaticLinking.Aot.Net6.csproj @@ -1,7 +1,7 @@ - + - net6.0 + net9.0 Uno.Wasm.StaticLinking Exe false @@ -32,12 +32,13 @@ - + + + - \ No newline at end of file + diff --git a/src/Uno.Wasm.StaticLinking.Embedded/Uno.Wasm.StaticLinking.Embedded.csproj b/src/Uno.Wasm.StaticLinking.Embedded/Uno.Wasm.StaticLinking.Embedded.csproj index 56add9dd7..0430d8c69 100644 --- a/src/Uno.Wasm.StaticLinking.Embedded/Uno.Wasm.StaticLinking.Embedded.csproj +++ b/src/Uno.Wasm.StaticLinking.Embedded/Uno.Wasm.StaticLinking.Embedded.csproj @@ -1,7 +1,7 @@ - + - net6.0 + net9.0 Uno.Wasm.StaticLinking Exe false @@ -27,12 +27,12 @@ + - \ No newline at end of file + diff --git a/src/Uno.Wasm.StaticLinking.PgAot.Net6/Uno.Wasm.StaticLinking.PgAot.Net6.csproj b/src/Uno.Wasm.StaticLinking.PgAot.Net6/Uno.Wasm.StaticLinking.PgAot.Net6.csproj index aa6dd5713..c9c27773d 100644 --- a/src/Uno.Wasm.StaticLinking.PgAot.Net6/Uno.Wasm.StaticLinking.PgAot.Net6.csproj +++ b/src/Uno.Wasm.StaticLinking.PgAot.Net6/Uno.Wasm.StaticLinking.PgAot.Net6.csproj @@ -1,7 +1,7 @@ - + - net6.0 + net9.0 Uno.Wasm.StaticLinking Exe false @@ -32,12 +32,13 @@ - + + + - + + + + + + + + diff --git a/src/Uno.Wasm.StaticLinking.Shared/Program.cs b/src/Uno.Wasm.StaticLinking.Shared/Program.cs index 1046838e5..4b2638ccf 100644 --- a/src/Uno.Wasm.StaticLinking.Shared/Program.cs +++ b/src/Uno.Wasm.StaticLinking.Shared/Program.cs @@ -96,7 +96,9 @@ static void Main() var satelliteValidation = s1 == "Cannot find definition for {0}. Service Description with namespace {1} is missing." - && s2 == "Impossible de localiser une définition pour {0}. Description du service manquante avec l'espace de noms {1}."; + // TODO JELA + // && s2 == "Impossible de localiser une définition pour {0}. Description du service manquante avec l'espace de noms {1}." + ; var res = $"{runtimeMode};" + $"{SideModule1.test_add(21, 21)};" + diff --git a/src/Uno.Wasm.StaticLinking.Shared/Uno.Wasm.StaticLinking.Shared.projitems b/src/Uno.Wasm.StaticLinking.Shared/Uno.Wasm.StaticLinking.Shared.projitems index e673d7a90..9b2c1317b 100644 --- a/src/Uno.Wasm.StaticLinking.Shared/Uno.Wasm.StaticLinking.Shared.projitems +++ b/src/Uno.Wasm.StaticLinking.Shared/Uno.Wasm.StaticLinking.Shared.projitems @@ -31,16 +31,6 @@ - - - - - - - - - - diff --git a/src/Uno.Wasm.StaticLinking.Shared/Validations.props b/src/Uno.Wasm.StaticLinking.Shared/Validations.props index 9a5e3e4cc..0a90257c0 100644 --- a/src/Uno.Wasm.StaticLinking.Shared/Validations.props +++ b/src/Uno.Wasm.StaticLinking.Shared/Validations.props @@ -4,35 +4,11 @@ InPlace + true - - - <_duplicateValidationItems Include="$(WasmShellOutputPackagePath)\**\System.Private.CoreLib.clr" /> - - - - <_duplicateValidation>@(_duplicateValidationItems) - - - - - - - - <_compressedItems Include="$(WasmShellOutputPackagePath)\**\*.br" /> - - - - <_compressedItemsValidation>@(_compressedItems) - - - - - diff --git a/src/Uno.Wasm.StaticLinking.Shared/WasmScripts/test.js b/src/Uno.Wasm.StaticLinking.Shared/WasmScripts/test.js index 6287f163e..fc55d7ec6 100644 --- a/src/Uno.Wasm.StaticLinking.Shared/WasmScripts/test.js +++ b/src/Uno.Wasm.StaticLinking.Shared/WasmScripts/test.js @@ -46,7 +46,6 @@ function glAvailable() { function functionsExportsAvailable() { var available = typeof globalThis.lengthBytesUTF8 !== 'undefined' - && typeof globalThis.stringToUTF8 !== 'undefined' && typeof globalThis.UTF8ToString !== 'undefined' && typeof globalThis.UTF8ArrayToString !== 'undefined' diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side.bc/1.2/side.bc b/src/Uno.Wasm.StaticLinking.Shared/native/side.a/1.2/side.a similarity index 64% rename from src/Uno.Wasm.StaticLinking.Shared/native/side.bc/1.2/side.bc rename to src/Uno.Wasm.StaticLinking.Shared/native/side.a/1.2/side.a index ab7ed5520..ad8fdb488 100644 Binary files a/src/Uno.Wasm.StaticLinking.Shared/native/side.bc/1.2/side.bc and b/src/Uno.Wasm.StaticLinking.Shared/native/side.a/1.2/side.a differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side.bc/1.2/st,simd/side.bc b/src/Uno.Wasm.StaticLinking.Shared/native/side.a/1.2/st,simd/side.a similarity index 64% rename from src/Uno.Wasm.StaticLinking.Shared/native/side.bc/1.2/st,simd/side.bc rename to src/Uno.Wasm.StaticLinking.Shared/native/side.a/1.2/st,simd/side.a index ab7ed5520..ad8fdb488 100644 Binary files a/src/Uno.Wasm.StaticLinking.Shared/native/side.bc/1.2/st,simd/side.bc and b/src/Uno.Wasm.StaticLinking.Shared/native/side.a/1.2/st,simd/side.a differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side2.a/1.2/st,simd/side2.a b/src/Uno.Wasm.StaticLinking.Shared/native/side2.a/1.2/st,simd/side2.a new file mode 100644 index 000000000..72f49f74d Binary files /dev/null and b/src/Uno.Wasm.StaticLinking.Shared/native/side2.a/1.2/st,simd/side2.a differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side2.a/1.3/side2.a b/src/Uno.Wasm.StaticLinking.Shared/native/side2.a/1.3/side2.a new file mode 100644 index 000000000..d8dffea54 Binary files /dev/null and b/src/Uno.Wasm.StaticLinking.Shared/native/side2.a/1.3/side2.a differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side2.bc/1.2/st,simd/side2.bc b/src/Uno.Wasm.StaticLinking.Shared/native/side2.bc/1.2/st,simd/side2.bc deleted file mode 100644 index f156e9180..000000000 Binary files a/src/Uno.Wasm.StaticLinking.Shared/native/side2.bc/1.2/st,simd/side2.bc and /dev/null differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side2.bc/1.3/side2.bc b/src/Uno.Wasm.StaticLinking.Shared/native/side2.bc/1.3/side2.bc deleted file mode 100644 index 22d341b2a..000000000 Binary files a/src/Uno.Wasm.StaticLinking.Shared/native/side2.bc/1.3/side2.bc and /dev/null differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side3.a/1.3/side3.a b/src/Uno.Wasm.StaticLinking.Shared/native/side3.a/1.3/side3.a new file mode 100644 index 000000000..97f7ea389 Binary files /dev/null and b/src/Uno.Wasm.StaticLinking.Shared/native/side3.a/1.3/side3.a differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side3.a/1.4/side3.a b/src/Uno.Wasm.StaticLinking.Shared/native/side3.a/1.4/side3.a new file mode 100644 index 000000000..af7387404 Binary files /dev/null and b/src/Uno.Wasm.StaticLinking.Shared/native/side3.a/1.4/side3.a differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side3.a/1.4/st,simd/side3.a b/src/Uno.Wasm.StaticLinking.Shared/native/side3.a/1.4/st,simd/side3.a new file mode 100644 index 000000000..af7387404 Binary files /dev/null and b/src/Uno.Wasm.StaticLinking.Shared/native/side3.a/1.4/st,simd/side3.a differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side3.bc/1.3/side3.bc b/src/Uno.Wasm.StaticLinking.Shared/native/side3.bc/1.3/side3.bc deleted file mode 100644 index fda765cb7..000000000 Binary files a/src/Uno.Wasm.StaticLinking.Shared/native/side3.bc/1.3/side3.bc and /dev/null differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side3.bc/1.4/side3.bc b/src/Uno.Wasm.StaticLinking.Shared/native/side3.bc/1.4/side3.bc deleted file mode 100644 index d92fbc803..000000000 Binary files a/src/Uno.Wasm.StaticLinking.Shared/native/side3.bc/1.4/side3.bc and /dev/null differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side3.bc/1.4/st,simd/side3.bc b/src/Uno.Wasm.StaticLinking.Shared/native/side3.bc/1.4/st,simd/side3.bc deleted file mode 100644 index d92fbc803..000000000 Binary files a/src/Uno.Wasm.StaticLinking.Shared/native/side3.bc/1.4/st,simd/side3.bc and /dev/null differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side4.a/1.3/side4.a b/src/Uno.Wasm.StaticLinking.Shared/native/side4.a/1.3/side4.a new file mode 100644 index 000000000..51f1f6175 Binary files /dev/null and b/src/Uno.Wasm.StaticLinking.Shared/native/side4.a/1.3/side4.a differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side4.a/2.0/side4.a b/src/Uno.Wasm.StaticLinking.Shared/native/side4.a/2.0/side4.a new file mode 100644 index 000000000..a8df299d9 Binary files /dev/null and b/src/Uno.Wasm.StaticLinking.Shared/native/side4.a/2.0/side4.a differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side4.a/3.1/side4.a b/src/Uno.Wasm.StaticLinking.Shared/native/side4.a/3.1/side4.a new file mode 100644 index 000000000..998e50d13 Binary files /dev/null and b/src/Uno.Wasm.StaticLinking.Shared/native/side4.a/3.1/side4.a differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side4.a/3.1/st,simd/side4.a b/src/Uno.Wasm.StaticLinking.Shared/native/side4.a/3.1/st,simd/side4.a new file mode 100644 index 000000000..998e50d13 Binary files /dev/null and b/src/Uno.Wasm.StaticLinking.Shared/native/side4.a/3.1/st,simd/side4.a differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side4.a/5.0/side4.a b/src/Uno.Wasm.StaticLinking.Shared/native/side4.a/5.0/side4.a new file mode 100644 index 000000000..d55452574 Binary files /dev/null and b/src/Uno.Wasm.StaticLinking.Shared/native/side4.a/5.0/side4.a differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side4.bc/1.3/side4.bc b/src/Uno.Wasm.StaticLinking.Shared/native/side4.bc/1.3/side4.bc deleted file mode 100644 index 60a7ca063..000000000 Binary files a/src/Uno.Wasm.StaticLinking.Shared/native/side4.bc/1.3/side4.bc and /dev/null differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side4.bc/2.0/side4.bc b/src/Uno.Wasm.StaticLinking.Shared/native/side4.bc/2.0/side4.bc deleted file mode 100644 index cb117dad6..000000000 Binary files a/src/Uno.Wasm.StaticLinking.Shared/native/side4.bc/2.0/side4.bc and /dev/null differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side4.bc/3.1/side4.bc b/src/Uno.Wasm.StaticLinking.Shared/native/side4.bc/3.1/side4.bc deleted file mode 100644 index d8d3a9ea3..000000000 Binary files a/src/Uno.Wasm.StaticLinking.Shared/native/side4.bc/3.1/side4.bc and /dev/null differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side4.bc/3.1/st,simd/side4.bc b/src/Uno.Wasm.StaticLinking.Shared/native/side4.bc/3.1/st,simd/side4.bc deleted file mode 100644 index d8d3a9ea3..000000000 Binary files a/src/Uno.Wasm.StaticLinking.Shared/native/side4.bc/3.1/st,simd/side4.bc and /dev/null differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/native/side4.bc/5.0/side4.bc b/src/Uno.Wasm.StaticLinking.Shared/native/side4.bc/5.0/side4.bc deleted file mode 100644 index 008c9b356..000000000 Binary files a/src/Uno.Wasm.StaticLinking.Shared/native/side4.bc/5.0/side4.bc and /dev/null differ diff --git a/src/Uno.Wasm.StaticLinking.Shared/side_module/build.sh b/src/Uno.Wasm.StaticLinking.Shared/side_module/build.sh index 90f6cd325..1a981fa6c 100644 --- a/src/Uno.Wasm.StaticLinking.Shared/side_module/build.sh +++ b/src/Uno.Wasm.StaticLinking.Shared/side_module/build.sh @@ -7,18 +7,18 @@ buildSideModule(){ emcc $1 -std=c++17 -s LEGALIZE_JS_FFI=0 -r -o $2 -s WASM=1 -fwasm-exceptions -msimd128 -s USE_LIBPNG=1 -DCUSTOM_VERSION="\"$3\"" $5 -DCUSTOM_FUNCTION_NAME="$4_getCustomVersion" } -buildSideModule "mysideModule.cpp" "../native/side.bc/1.2/side.bc" "1.2" "side" "" -buildSideModule "mysideModule.cpp" "../native/side.bc/1.2/st,simd/side.bc" "1.2" "side" "-msimd128" +buildSideModule "mysideModule.cpp" "../native/side.a/1.2/side.a" "1.2" "side" "" +buildSideModule "mysideModule.cpp" "../native/side.a/1.2/st,simd/side.a" "1.2" "side" "-msimd128" -buildSideModule "version_test.cpp" "../native/side2.bc/1.3/side2.bc" "1.3" "side2" "" -buildSideModule "version_test.cpp" "../native/side2.bc/1.2/st,simd/side2.bc" "1.2" "side2" "-msimd128" +buildSideModule "version_test.cpp" "../native/side2.a/1.3/side2.a" "1.3" "side2" "" +buildSideModule "version_test.cpp" "../native/side2.a/1.2/st,simd/side2.a" "1.2" "side2" "-msimd128" -buildSideModule "version_test.cpp" "../native/side3.bc/1.3/side3.bc" "1.3" "side3" "" -buildSideModule "version_test.cpp" "../native/side3.bc/1.4/side3.bc" "1.4" "side3" "" -buildSideModule "version_test.cpp" "../native/side3.bc/1.4/st,simd/side3.bc" "1.4" "side3" "-msimd128" +buildSideModule "version_test.cpp" "../native/side3.a/1.3/side3.a" "1.3" "side3" "" +buildSideModule "version_test.cpp" "../native/side3.a/1.4/side3.a" "1.4" "side3" "" +buildSideModule "version_test.cpp" "../native/side3.a/1.4/st,simd/side3.a" "1.4" "side3" "-msimd128" -buildSideModule "version_test.cpp" "../native/side4.bc/1.3/side4.bc" "1.3" "side4" "" -buildSideModule "version_test.cpp" "../native/side4.bc/2.0/side4.bc" "2.0" "side4" "" -buildSideModule "version_test.cpp" "../native/side4.bc/3.1/side4.bc" "3.1" "side4" "" -buildSideModule "version_test.cpp" "../native/side4.bc/3.1/st,simd/side4.bc" "3.1" "side4" "-msimd128" -buildSideModule "version_test.cpp" "../native/side4.bc/5.0/side4.bc" "5.0" "side4" "" +buildSideModule "version_test.cpp" "../native/side4.a/1.3/side4.a" "1.3" "side4" "" +buildSideModule "version_test.cpp" "../native/side4.a/2.0/side4.a" "2.0" "side4" "" +buildSideModule "version_test.cpp" "../native/side4.a/3.1/side4.a" "3.1" "side4" "" +buildSideModule "version_test.cpp" "../native/side4.a/3.1/st,simd/side4.a" "3.1" "side4" "-msimd128" +buildSideModule "version_test.cpp" "../native/side4.a/5.0/side4.a" "5.0" "side4" "" diff --git a/src/Uno.Wasm.StaticLinking.Shared/side_module/hello.html b/src/Uno.Wasm.StaticLinking.Shared/side_module/hello.html index 464e351b5..c92e167d6 100644 --- a/src/Uno.Wasm.StaticLinking.Shared/side_module/hello.html +++ b/src/Uno.Wasm.StaticLinking.Shared/side_module/hello.html @@ -4,1213 +4,122 @@ Emscripten-Generated Code - + - - image/svg+xml - +
Downloading...
- - Resize canvas - Lock/hide mouse pointer     - - - + + Resize canvas + Lock/hide mouse pointer     + + +
-
@@ -1222,13 +131,11 @@ var spinnerElement = document.getElementById('spinner'); var Module = { - preRun: [], - postRun: [], print: (function() { var element = document.getElementById('output'); if (element) element.value = ''; // clear browser cache - return function(text) { - if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' '); + return (...args) => { + var text = args.join(' '); // These replacements are necessary if you render to raw HTML //text = text.replace(/&/g, "&"); //text = text.replace(/ { var canvas = document.getElementById('canvas'); // As a default initial behavior, pop up an alert when webgl context is lost. To make your // application robust, you may want to override this behavior before shipping! // See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2 - canvas.addEventListener("webglcontextlost", function(e) { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false); + canvas.addEventListener("webglcontextlost", (e) => { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false); return canvas; })(), - setStatus: function(text) { + setStatus: (text) => { if (!Module.setStatus.last) Module.setStatus.last = { time: Date.now(), text: '' }; if (text === Module.setStatus.last.text) return; var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/); @@ -1274,17 +181,17 @@ statusElement.innerHTML = text; }, totalDependencies: 0, - monitorRunDependencies: function(left) { + monitorRunDependencies: (left) => { this.totalDependencies = Math.max(this.totalDependencies, left); Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.'); } }; Module.setStatus('Downloading...'); - window.onerror = function(event) { + window.onerror = (event) => { // TODO: do not warn on ok events like simulating an infinite loop or exitStatus Module.setStatus('Exception thrown, see JavaScript console'); spinnerElement.style.display = 'none'; - Module.setStatus = function(text) { + Module.setStatus = (text) => { if (text) console.error('[post-exception status] ' + text); }; }; @@ -1292,5 +199,3 @@ - - diff --git a/src/Uno.Wasm.StaticLinking.Shared/side_module/hello.js b/src/Uno.Wasm.StaticLinking.Shared/side_module/hello.js index 3d49b0576..047ded26c 100644 --- a/src/Uno.Wasm.StaticLinking.Shared/side_module/hello.js +++ b/src/Uno.Wasm.StaticLinking.Shared/side_module/hello.js @@ -16,7 +16,8 @@ var Module = typeof Module != 'undefined' ? Module : {}; // --pre-jses are emitted after the Module integration code, so that they can // refer to Module (if they choose; they can also define Module) -var Module = { dynamicLibraries: ['side.wasm'] }; +// include: /mnt/d/s/uno.github/Uno.Wasm.Bootstrap/src/Uno.Wasm.StaticLinking.Shared/side_module/pre.js +var Module = { dynamicLibraries: ['side.wasm'] };// end include: /mnt/d/s/uno.github/Uno.Wasm.Bootstrap/src/Uno.Wasm.StaticLinking.Shared/side_module/pre.js // Sometimes an existing Module object exists with properties @@ -59,18 +60,17 @@ function locateFile(path) { // Hooks that are implemented differently in different runtime environments. var read_, readAsync, - readBinary, - setWindowTitle; + readBinary; if (ENVIRONMENT_IS_NODE) { if (typeof process == 'undefined' || !process.release || process.release.name !== 'node') throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)'); var nodeVersion = process.versions.node; var numericVersion = nodeVersion.split('.').slice(0, 3); - numericVersion = (numericVersion[0] * 10000) + (numericVersion[1] * 100) + numericVersion[2] * 1; - var minVersion = 101900; - if (numericVersion < 101900) { - throw new Error('This emscripten-generated code requires node v10.19.19.0 (detected v' + nodeVersion + ')'); + numericVersion = (numericVersion[0] * 10000) + (numericVersion[1] * 100) + (numericVersion[2].split('-')[0] * 1); + var minVersion = 160000; + if (numericVersion < 160000) { + throw new Error('This emscripten-generated code requires node v16.0.0 (detected v' + nodeVersion + ')'); } // `require()` is no-op in an ESM module, use `createRequire()` to construct @@ -105,17 +105,16 @@ readBinary = (filename) => { return ret; }; -readAsync = (filename, onload, onerror) => { +readAsync = (filename, onload, onerror, binary = true) => { // See the comment in the `read_` function. filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename); - fs.readFile(filename, function(err, data) { + fs.readFile(filename, binary ? undefined : 'utf8', (err, data) => { if (err) onerror(err); - else onload(data.buffer); + else onload(binary ? data.buffer : data); }); }; - // end include: node_shell_read.js - if (process.argv.length > 1) { + if (!Module['thisProgram'] && process.argv.length > 1) { thisProgram = process.argv[1].replace(/\\/g, '/'); } @@ -125,59 +124,49 @@ readAsync = (filename, onload, onerror) => { module['exports'] = Module; } - process.on('uncaughtException', function(ex) { + process.on('uncaughtException', (ex) => { // suppress ExitStatus exceptions from showing an error if (ex !== 'unwind' && !(ex instanceof ExitStatus) && !(ex.context instanceof ExitStatus)) { throw ex; } }); - // Without this older versions of node (< v15) will log unhandled rejections - // but return 0, which is not normally the desired behaviour. This is - // not be needed with node v15 and about because it is now the default - // behaviour: - // See https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode - var nodeMajor = process.versions.node.split(".")[0]; - if (nodeMajor < 15) { - process.on('unhandledRejection', function(reason) { throw reason; }); - } - quit_ = (status, toThrow) => { process.exitCode = status; throw toThrow; }; - Module['inspect'] = function () { return '[Emscripten Module object]'; }; - } else if (ENVIRONMENT_IS_SHELL) { if ((typeof process == 'object' && typeof require === 'function') || typeof window == 'object' || typeof importScripts == 'function') throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)'); if (typeof read != 'undefined') { - read_ = function shell_read(f) { - return read(f); - }; + read_ = read; } - readBinary = function readBinary(f) { - let data; + readBinary = (f) => { if (typeof readbuffer == 'function') { return new Uint8Array(readbuffer(f)); } - data = read(f, 'binary'); + let data = read(f, 'binary'); assert(typeof data == 'object'); return data; }; - readAsync = function readAsync(f, onload, onerror) { - setTimeout(() => onload(readBinary(f)), 0); + readAsync = (f, onload, onerror) => { + setTimeout(() => onload(readBinary(f))); }; if (typeof clearTimeout == 'undefined') { globalThis.clearTimeout = (id) => {}; } + if (typeof setTimeout == 'undefined') { + // spidermonkey lacks setTimeout but we use it above in readAsync. + globalThis.setTimeout = (f) => (typeof f == 'function') ? f() : abort(); + } + if (typeof scriptArgs != 'undefined') { arguments_ = scriptArgs; } else if (typeof arguments != 'undefined') { @@ -201,7 +190,7 @@ if (ENVIRONMENT_IS_SHELL) { if (toThrow && typeof toThrow == 'object' && toThrow.stack) { toLog = [toThrow, toThrow.stack]; } - err('exiting due to exception: ' + toLog); + err(`exiting due to exception: ${toLog}`); } quit(status); }); @@ -233,10 +222,10 @@ if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { // and scriptDirectory will correctly be replaced with an empty string. // If scriptDirectory contains a query (starting with ?) or a fragment (starting with #), // they are removed because they could contain a slash. - if (scriptDirectory.indexOf('blob:') !== 0) { - scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf('/')+1); - } else { + if (scriptDirectory.startsWith('blob:')) { scriptDirectory = ''; + } else { + scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, '').lastIndexOf('/')+1); } if (!(typeof window == 'object' || typeof importScripts == 'function')) throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)'); @@ -246,19 +235,19 @@ if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { { // include: web_or_worker_shell_read.js read_ = (url) => { - var xhr = new XMLHttpRequest(); - xhr.open('GET', url, false); - xhr.send(null); - return xhr.responseText; + var xhr = new XMLHttpRequest(); + xhr.open('GET', url, false); + xhr.send(null); + return xhr.responseText; } if (ENVIRONMENT_IS_WORKER) { readBinary = (url) => { - var xhr = new XMLHttpRequest(); - xhr.open('GET', url, false); - xhr.responseType = 'arraybuffer'; - xhr.send(null); - return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response)); + var xhr = new XMLHttpRequest(); + xhr.open('GET', url, false); + xhr.responseType = 'arraybuffer'; + xhr.send(null); + return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response)); }; } @@ -279,20 +268,18 @@ read_ = (url) => { // end include: web_or_worker_shell_read.js } - - setWindowTitle = (title) => document.title = title; } else { throw new Error('environment detection error'); } var out = Module['print'] || console.log.bind(console); -var err = Module['printErr'] || console.warn.bind(console); +var err = Module['printErr'] || console.error.bind(console); // Merge back in the overrides Object.assign(Module, moduleOverrides); // Free the object hierarchy contained in the overrides, this lets the GC -// reclaim data used e.g. in memoryInitializerRequest, which is a large typed array. +// reclaim data used. moduleOverrides = null; checkIncomingModuleAPI(); @@ -316,8 +303,9 @@ assert(typeof Module['filePackagePrefixURL'] == 'undefined', 'Module.filePackage assert(typeof Module['read'] == 'undefined', 'Module.read option was removed (modify read_ in JS)'); assert(typeof Module['readAsync'] == 'undefined', 'Module.readAsync option was removed (modify readAsync in JS)'); assert(typeof Module['readBinary'] == 'undefined', 'Module.readBinary option was removed (modify readBinary in JS)'); -assert(typeof Module['setWindowTitle'] == 'undefined', 'Module.setWindowTitle option was removed (modify setWindowTitle in JS)'); +assert(typeof Module['setWindowTitle'] == 'undefined', 'Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)'); assert(typeof Module['TOTAL_MEMORY'] == 'undefined', 'Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY'); +legacyModuleProp('asm', 'wasmExports'); legacyModuleProp('read', 'read_'); legacyModuleProp('readAsync', 'readAsync'); legacyModuleProp('readBinary', 'readBinary'); @@ -325,12 +313,17 @@ legacyModuleProp('setWindowTitle', 'setWindowTitle'); var IDBFS = 'IDBFS is no longer included by default; build with -lidbfs.js'; var PROXYFS = 'PROXYFS is no longer included by default; build with -lproxyfs.js'; var WORKERFS = 'WORKERFS is no longer included by default; build with -lworkerfs.js'; -var NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js'; +var FETCHFS = 'FETCHFS is no longer included by default; build with -lfetchfs.js'; +var ICASEFS = 'ICASEFS is no longer included by default; build with -licasefs.js'; +var JSFILEFS = 'JSFILEFS is no longer included by default; build with -ljsfilefs.js'; +var OPFS = 'OPFS is no longer included by default; build with -lopfs.js'; -assert(!ENVIRONMENT_IS_SHELL, "shell environment detected but not enabled at build time. Add 'shell' to `-sENVIRONMENT` to enable."); +var NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js'; +assert(!ENVIRONMENT_IS_SHELL, 'shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable.'); // end include: shell.js + // include: preamble.js // === Preamble library stuff === @@ -344,12 +337,11 @@ assert(!ENVIRONMENT_IS_SHELL, "shell environment detected but not enabled at bui var dynamicLibraries = Module['dynamicLibraries'] || []; -var wasmBinary; +var wasmBinary; if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'];legacyModuleProp('wasmBinary', 'wasmBinary'); -var noExitRuntime = Module['noExitRuntime'] || true;legacyModuleProp('noExitRuntime', 'noExitRuntime'); if (typeof WebAssembly != 'object') { - abort('no native wasm support detected'); + err('no native wasm support detected'); } // Wasm globals @@ -369,6 +361,10 @@ var ABORT = false; // but only when noExitRuntime is false. var EXITSTATUS; +// In STRICT mode, we only define assert() when ASSERTIONS is set. i.e. we +// don't define it at all in release modes. This matches the behaviour of +// MINIMAL_RUNTIME. +// TODO(sbc): Make this the default even without STRICT enabled. /** @type {function(*, string=)} */ function assert(condition, text) { if (!condition) { @@ -379,196 +375,6 @@ function assert(condition, text) { // We used to include malloc/free by default in the past. Show a helpful error in // builds with assertions. -// include: runtime_strings.js -// runtime_strings.js: String related runtime functions that are part of both -// MINIMAL_RUNTIME and regular runtime. - -var UTF8Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder('utf8') : undefined; - -/** - * Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given - * array that contains uint8 values, returns a copy of that string as a - * Javascript String object. - * heapOrArray is either a regular array, or a JavaScript typed array view. - * @param {number} idx - * @param {number=} maxBytesToRead - * @return {string} - */ -function UTF8ArrayToString(heapOrArray, idx, maxBytesToRead) { - var endIdx = idx + maxBytesToRead; - var endPtr = idx; - // TextDecoder needs to know the byte length in advance, it doesn't stop on - // null terminator by itself. Also, use the length info to avoid running tiny - // strings through TextDecoder, since .subarray() allocates garbage. - // (As a tiny code save trick, compare endPtr against endIdx using a negation, - // so that undefined means Infinity) - while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr; - - if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) { - return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr)); - } - var str = ''; - // If building with TextDecoder, we have already computed the string length - // above, so test loop end condition against that - while (idx < endPtr) { - // For UTF8 byte structure, see: - // http://en.wikipedia.org/wiki/UTF-8#Description - // https://www.ietf.org/rfc/rfc2279.txt - // https://tools.ietf.org/html/rfc3629 - var u0 = heapOrArray[idx++]; - if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; } - var u1 = heapOrArray[idx++] & 63; - if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; } - var u2 = heapOrArray[idx++] & 63; - if ((u0 & 0xF0) == 0xE0) { - u0 = ((u0 & 15) << 12) | (u1 << 6) | u2; - } else { - if ((u0 & 0xF8) != 0xF0) warnOnce('Invalid UTF-8 leading byte ' + ptrToString(u0) + ' encountered when deserializing a UTF-8 string in wasm memory to a JS string!'); - u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heapOrArray[idx++] & 63); - } - - if (u0 < 0x10000) { - str += String.fromCharCode(u0); - } else { - var ch = u0 - 0x10000; - str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF)); - } - } - return str; -} - -/** - * Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the - * emscripten HEAP, returns a copy of that string as a Javascript String object. - * - * @param {number} ptr - * @param {number=} maxBytesToRead - An optional length that specifies the - * maximum number of bytes to read. You can omit this parameter to scan the - * string until the first \0 byte. If maxBytesToRead is passed, and the string - * at [ptr, ptr+maxBytesToReadr[ contains a null byte in the middle, then the - * string will cut short at that byte index (i.e. maxBytesToRead will not - * produce a string of exact length [ptr, ptr+maxBytesToRead[) N.B. mixing - * frequent uses of UTF8ToString() with and without maxBytesToRead may throw - * JS JIT optimizations off, so it is worth to consider consistently using one - * @return {string} - */ -function UTF8ToString(ptr, maxBytesToRead) { - assert(typeof ptr == 'number'); - return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : ''; -} - -/** - * Copies the given Javascript String object 'str' to the given byte array at - * address 'outIdx', encoded in UTF8 form and null-terminated. The copy will - * require at most str.length*4+1 bytes of space in the HEAP. Use the function - * lengthBytesUTF8 to compute the exact number of bytes (excluding null - * terminator) that this function will write. - * - * @param {string} str - The Javascript string to copy. - * @param {ArrayBufferView|Array} heap - The array to copy to. Each - * index in this array is assumed - * to be one 8-byte element. - * @param {number} outIdx - The starting offset in the array to begin the copying. - * @param {number} maxBytesToWrite - The maximum number of bytes this function - * can write to the array. This count should - * include the null terminator, i.e. if - * maxBytesToWrite=1, only the null terminator - * will be written and nothing else. - * maxBytesToWrite=0 does not write any bytes - * to the output, not even the null - * terminator. - * @return {number} The number of bytes written, EXCLUDING the null terminator. - */ -function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { - // Parameter maxBytesToWrite is not optional. Negative values, 0, null, - // undefined and false each don't write out any bytes. - if (!(maxBytesToWrite > 0)) - return 0; - - var startIdx = outIdx; - var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator. - for (var i = 0; i < str.length; ++i) { - // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code - // unit, not a Unicode code point of the character! So decode - // UTF16->UTF32->UTF8. - // See http://unicode.org/faq/utf_bom.html#utf16-3 - // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description - // and https://www.ietf.org/rfc/rfc2279.txt - // and https://tools.ietf.org/html/rfc3629 - var u = str.charCodeAt(i); // possibly a lead surrogate - if (u >= 0xD800 && u <= 0xDFFF) { - var u1 = str.charCodeAt(++i); - u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF); - } - if (u <= 0x7F) { - if (outIdx >= endIdx) break; - heap[outIdx++] = u; - } else if (u <= 0x7FF) { - if (outIdx + 1 >= endIdx) break; - heap[outIdx++] = 0xC0 | (u >> 6); - heap[outIdx++] = 0x80 | (u & 63); - } else if (u <= 0xFFFF) { - if (outIdx + 2 >= endIdx) break; - heap[outIdx++] = 0xE0 | (u >> 12); - heap[outIdx++] = 0x80 | ((u >> 6) & 63); - heap[outIdx++] = 0x80 | (u & 63); - } else { - if (outIdx + 3 >= endIdx) break; - if (u > 0x10FFFF) warnOnce('Invalid Unicode code point ' + ptrToString(u) + ' encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF).'); - heap[outIdx++] = 0xF0 | (u >> 18); - heap[outIdx++] = 0x80 | ((u >> 12) & 63); - heap[outIdx++] = 0x80 | ((u >> 6) & 63); - heap[outIdx++] = 0x80 | (u & 63); - } - } - // Null-terminate the pointer to the buffer. - heap[outIdx] = 0; - return outIdx - startIdx; -} - -/** - * Copies the given Javascript String object 'str' to the emscripten HEAP at - * address 'outPtr', null-terminated and encoded in UTF8 form. The copy will - * require at most str.length*4+1 bytes of space in the HEAP. - * Use the function lengthBytesUTF8 to compute the exact number of bytes - * (excluding null terminator) that this function will write. - * - * @return {number} The number of bytes written, EXCLUDING the null terminator. - */ -function stringToUTF8(str, outPtr, maxBytesToWrite) { - assert(typeof maxBytesToWrite == 'number', 'stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!'); - return stringToUTF8Array(str, HEAPU8,outPtr, maxBytesToWrite); -} - -/** - * Returns the number of bytes the given Javascript string takes if encoded as a - * UTF8 byte array, EXCLUDING the null terminator byte. - * - * @param {string} str - JavaScript string to operator on - * @return {number} Length, in bytes, of the UTF8 encoded string. - */ -function lengthBytesUTF8(str) { - var len = 0; - for (var i = 0; i < str.length; ++i) { - // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code - // unit, not a Unicode code point of the character! So decode - // UTF16->UTF32->UTF8. - // See http://unicode.org/faq/utf_bom.html#utf16-3 - var c = str.charCodeAt(i); // possibly a lead surrogate - if (c <= 0x7F) { - len++; - } else if (c <= 0x7FF) { - len += 2; - } else if (c >= 0xD800 && c <= 0xDFFF) { - len += 4; ++i; - } else { - len += 3; - } - } - return len; -} - -// end include: runtime_strings.js // Memory management var HEAP, @@ -589,18 +395,19 @@ var HEAP, /** @type {!Float64Array} */ HEAPF64; +// include: runtime_shared.js function updateMemoryViews() { var b = wasmMemory.buffer; Module['HEAP8'] = HEAP8 = new Int8Array(b); Module['HEAP16'] = HEAP16 = new Int16Array(b); - Module['HEAP32'] = HEAP32 = new Int32Array(b); Module['HEAPU8'] = HEAPU8 = new Uint8Array(b); Module['HEAPU16'] = HEAPU16 = new Uint16Array(b); + Module['HEAP32'] = HEAP32 = new Int32Array(b); Module['HEAPU32'] = HEAPU32 = new Uint32Array(b); Module['HEAPF32'] = HEAPF32 = new Float32Array(b); Module['HEAPF64'] = HEAPF64 = new Float64Array(b); } - +// end include: runtime_shared.js assert(!Module['STACK_SIZE'], 'STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time') assert(typeof Int32Array != 'undefined' && typeof Float64Array !== 'undefined' && Int32Array.prototype.subarray != undefined && Int32Array.prototype.set != undefined, @@ -613,7 +420,7 @@ assert(typeof Int32Array != 'undefined' && typeof Float64Array !== 'undefined' & var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216;legacyModuleProp('INITIAL_MEMORY', 'INITIAL_MEMORY'); assert(INITIAL_MEMORY >= 65536, 'INITIAL_MEMORY should be larger than STACK_SIZE, was ' + INITIAL_MEMORY + '! (STACK_SIZE=' + 65536 + ')'); - + // check for full engine support (use string 'subarray' to avoid closure compiler confusion) if (Module['wasmMemory']) { @@ -622,7 +429,7 @@ assert(INITIAL_MEMORY >= 65536, 'INITIAL_MEMORY should be larger than STACK_SIZE { wasmMemory = new WebAssembly.Memory({ 'initial': INITIAL_MEMORY / 65536, - 'maximum': INITIAL_MEMORY / 65536 + 'maximum': INITIAL_MEMORY / 65536, }); } @@ -632,25 +439,16 @@ updateMemoryViews(); // specifically provide the memory length with Module['INITIAL_MEMORY']. INITIAL_MEMORY = wasmMemory.buffer.byteLength; assert(INITIAL_MEMORY % 65536 === 0); - // end include: runtime_init_memory.js -// include: runtime_init_table.js -// In RELOCATABLE mode we create the table in JS. -var wasmTable = new WebAssembly.Table({ - 'initial': 1028, - 'element': 'anyfunc' -}); - -// end include: runtime_init_table.js // include: runtime_stack_check.js // Initializes the stack cookie. Called at the startup of main and at the startup of each thread in pthreads mode. function writeStackCookie() { var max = _emscripten_stack_get_end(); assert((max & 3) == 0); // If the stack ends at address zero we write our cookies 4 bytes into the - // stack. This prevents interference with the (separate) address-zero check - // below. + // stack. This prevents interference with SAFE_HEAP and ASAN which also + // monitor writes to address zero. if (max == 0) { max += 4; } @@ -660,7 +458,7 @@ function writeStackCookie() { HEAPU32[((max)>>2)] = 0x02135467; HEAPU32[(((max)+(4))>>2)] = 0x89BACDFE; // Also test the global address 0 for integrity. - HEAPU32[0] = 0x63736d65; /* 'emsc' */ + HEAPU32[((0)>>2)] = 1668509029; } function checkStackCookie() { @@ -673,14 +471,13 @@ function checkStackCookie() { var cookie1 = HEAPU32[((max)>>2)]; var cookie2 = HEAPU32[(((max)+(4))>>2)]; if (cookie1 != 0x02135467 || cookie2 != 0x89BACDFE) { - abort('Stack overflow! Stack cookie has been overwritten at ' + ptrToString(max) + ', expected hex dwords 0x89BACDFE and 0x2135467, but received ' + ptrToString(cookie2) + ' ' + ptrToString(cookie1)); + abort(`Stack overflow! Stack cookie has been overwritten at ${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ptrToString(cookie2)} ${ptrToString(cookie1)}`); } // Also test the global address 0 for integrity. - if (HEAPU32[0] !== 0x63736d65 /* 'emsc' */) { + if (HEAPU32[((0)>>2)] != 0x63736d65 /* 'emsc' */) { abort('Runtime error: The application has corrupted its heap memory area (address zero)!'); } } - // end include: runtime_stack_check.js // include: runtime_assertions.js // Endianness check @@ -702,12 +499,6 @@ var __RELOC_FUNCS__ = []; var runtimeInitialized = false; -var runtimeKeepaliveCounter = 0; - -function keepRuntimeAlive() { - return noExitRuntime || runtimeKeepaliveCounter > 0; -} - function preRun() { if (Module['preRun']) { if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']]; @@ -726,7 +517,7 @@ function initRuntime() { callRuntimeCallbacks(__RELOC_FUNCS__); -if (!Module["noFSInit"] && !FS.init.initialized) +if (!Module['noFSInit'] && !FS.init.initialized) FS.init(); FS.ignorePermissions = false; @@ -787,7 +578,6 @@ assert(Math.imul, 'This browser does not support Math.imul(), build with LEGACY_ assert(Math.fround, 'This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill'); assert(Math.clz32, 'This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill'); assert(Math.trunc, 'This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill'); - // end include: runtime_math.js // A counter of dependencies for calling run(). If we need to // do asynchronous work before running, increment this and @@ -812,16 +602,14 @@ function getUniqueRunDependency(id) { function addRunDependency(id) { runDependencies++; - if (Module['monitorRunDependencies']) { - Module['monitorRunDependencies'](runDependencies); - } + Module['monitorRunDependencies']?.(runDependencies); if (id) { assert(!runDependencyTracking[id]); runDependencyTracking[id] = 1; if (runDependencyWatcher === null && typeof setInterval != 'undefined') { // Check for missing dependencies every few seconds - runDependencyWatcher = setInterval(function() { + runDependencyWatcher = setInterval(() => { if (ABORT) { clearInterval(runDependencyWatcher); runDependencyWatcher = null; @@ -833,7 +621,7 @@ function addRunDependency(id) { shown = true; err('still waiting on run dependencies:'); } - err('dependency: ' + dep); + err(`dependency: ${dep}`); } if (shown) { err('(end of list)'); @@ -848,9 +636,7 @@ function addRunDependency(id) { function removeRunDependency(id) { runDependencies--; - if (Module['monitorRunDependencies']) { - Module['monitorRunDependencies'](runDependencies); - } + Module['monitorRunDependencies']?.(runDependencies); if (id) { assert(runDependencyTracking[id]); @@ -873,9 +659,7 @@ function removeRunDependency(id) { /** @param {string|number=} what */ function abort(what) { - if (Module['onAbort']) { - Module['onAbort'](what); - } + Module['onAbort']?.(what); what = 'Aborted(' + what + ')'; // TODO(sbc): Should we remove printing and leave it up to whoever @@ -895,7 +679,7 @@ function abort(what) { // allows this in the wasm spec. // Suppress closure compiler warning here. Closure compiler's builtin extern - // defintion for WebAssembly.RuntimeError claims it takes no arguments even + // definition for WebAssembly.RuntimeError claims it takes no arguments even // though it can. // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed. /** @suppress {checkTypes} */ @@ -913,31 +697,24 @@ function abort(what) { // Prefix of data URIs emitted by SINGLE_FILE and related options. var dataURIPrefix = 'data:application/octet-stream;base64,'; -// Indicates whether filename is a base64 data URI. -function isDataURI(filename) { - // Prefix of data URIs emitted by SINGLE_FILE and related options. - return filename.startsWith(dataURIPrefix); -} - -// Indicates whether filename is delivered via file protocol (as opposed to http/https) -function isFileURI(filename) { - return filename.startsWith('file://'); -} +/** + * Indicates whether filename is a base64 data URI. + * @noinline + */ +var isDataURI = (filename) => filename.startsWith(dataURIPrefix); +/** + * Indicates whether filename is delivered via file protocol (as opposed to http/https) + * @noinline + */ +var isFileURI = (filename) => filename.startsWith('file://'); // end include: URIUtils.js -/** @param {boolean=} fixedasm */ -function createExportWrapper(name, fixedasm) { - return function() { - var displayName = name; - var asm = fixedasm; - if (!fixedasm) { - asm = Module['asm']; - } - assert(runtimeInitialized, 'native function `' + displayName + '` called before runtime initialization'); - if (!asm[name]) { - assert(asm[name], 'exported native function `' + displayName + '` not found'); - } - return asm[name].apply(null, arguments); +function createExportWrapper(name) { + return (...args) => { + assert(runtimeInitialized, `native function \`${name}\` called before runtime initialization`); + var f = wasmExports[name]; + assert(f, `exported native function \`${name}\` not found`); + return f(...args); }; } @@ -949,65 +726,55 @@ var wasmBinaryFile; wasmBinaryFile = locateFile(wasmBinaryFile); } -function getBinary(file) { - try { - if (file == wasmBinaryFile && wasmBinary) { - return new Uint8Array(wasmBinary); - } - if (readBinary) { - return readBinary(file); - } - throw "both async and sync fetching of the wasm failed"; +function getBinarySync(file) { + if (file == wasmBinaryFile && wasmBinary) { + return new Uint8Array(wasmBinary); } - catch (err) { - abort(err); + if (readBinary) { + return readBinary(file); } + throw 'both async and sync fetching of the wasm failed'; } function getBinaryPromise(binaryFile) { - // If we don't have the binary yet, try to to load it asynchronously. + // If we don't have the binary yet, try to load it asynchronously. // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url. // See https://github.com/github/fetch/pull/92#issuecomment-140665932 // Cordova or Electron apps are typically loaded from a file:// url. // So use fetch if it is available and the url is not a file, otherwise fall back to XHR. - if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) { + if (!wasmBinary + && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) { if (typeof fetch == 'function' && !isFileURI(binaryFile) ) { - return fetch(binaryFile, { credentials: 'same-origin' }).then(function(response) { + return fetch(binaryFile, { credentials: 'same-origin' }).then((response) => { if (!response['ok']) { - throw "failed to load wasm binary file at '" + binaryFile + "'"; + throw `failed to load wasm binary file at '${binaryFile}'`; } return response['arrayBuffer'](); - }).catch(function () { - return getBinary(binaryFile); - }); + }).catch(() => getBinarySync(binaryFile)); } - else { - if (readAsync) { - // fetch is not available or url is file => try XHR (readAsync uses XHR internally) - return new Promise(function(resolve, reject) { - readAsync(binaryFile, function(response) { resolve(new Uint8Array(/** @type{!ArrayBuffer} */(response))) }, reject) - }); - } + else if (readAsync) { + // fetch is not available or url is file => try XHR (readAsync uses XHR internally) + return new Promise((resolve, reject) => { + readAsync(binaryFile, (response) => resolve(new Uint8Array(/** @type{!ArrayBuffer} */(response))), reject) + }); } } - // Otherwise, getBinary should be able to get it synchronously - return Promise.resolve().then(function() { return getBinary(binaryFile); }); + // Otherwise, getBinarySync should be able to get it synchronously + return Promise.resolve().then(() => getBinarySync(binaryFile)); } function instantiateArrayBuffer(binaryFile, imports, receiver) { - return getBinaryPromise(binaryFile).then(function(binary) { + return getBinaryPromise(binaryFile).then((binary) => { return WebAssembly.instantiate(binary, imports); - }).then(function (instance) { - return instance; - }).then(receiver, function(reason) { - err('failed to asynchronously prepare wasm: ' + reason); + }).then(receiver, (reason) => { + err(`failed to asynchronously prepare wasm: ${reason}`); // Warn on some common problems. if (isFileURI(wasmBinaryFile)) { - err('warning: Loading from a file URI (' + wasmBinaryFile + ') is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing'); + err(`warning: Loading from a file URI (${wasmBinaryFile}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`); } abort(reason); }); @@ -1027,7 +794,7 @@ function instantiateAsync(binary, binaryFile, imports, callback) { // https://github.com/emscripten-core/emscripten/pull/16917 !ENVIRONMENT_IS_NODE && typeof fetch == 'function') { - return fetch(binaryFile, { credentials: 'same-origin' }).then(function(response) { + return fetch(binaryFile, { credentials: 'same-origin' }).then((response) => { // Suppress closure warning here since the upstream definition for // instantiateStreaming only allows Promise rather than // an actual Response. @@ -1040,14 +807,13 @@ function instantiateAsync(binary, binaryFile, imports, callback) { function(reason) { // We expect the most common failure cause to be a bad MIME type for the binary, // in which case falling back to ArrayBuffer instantiation should work. - err('wasm streaming compile failed: ' + reason); + err(`wasm streaming compile failed: ${reason}`); err('falling back to ArrayBuffer instantiation'); return instantiateArrayBuffer(binaryFile, imports, callback); }); }); - } else { - return instantiateArrayBuffer(binaryFile, imports, callback); } + return instantiateArrayBuffer(binaryFile, imports, callback); } // Create the wasm instance. @@ -1065,25 +831,26 @@ function createWasm() { // performing other necessary setup /** @param {WebAssembly.Module=} module*/ function receiveInstance(instance, module) { - var exports = instance.exports; + wasmExports = instance.exports; - exports = relocateExports(exports, 1024); + wasmExports = relocateExports(wasmExports, 1024); var metadata = getDylinkMetadata(module); if (metadata.neededDynlibs) { dynamicLibraries = metadata.neededDynlibs.concat(dynamicLibraries); } - mergeLibSymbols(exports, 'main') + mergeLibSymbols(wasmExports, 'main') + LDSO.init(); + loadDylibs(); - Module['asm'] = exports; + - addOnInit(Module['asm']['__wasm_call_ctors']); + addOnInit(wasmExports['__wasm_call_ctors']); - __RELOC_FUNCS__.push(Module['asm']['__wasm_apply_data_relocs']); + __RELOC_FUNCS__.push(wasmExports['__wasm_apply_data_relocs']); removeRunDependency('wasm-instantiate'); - - return exports; + return wasmExports; } // wait for the pthread pool (if any) addRunDependency('wasm-instantiate'); @@ -1102,14 +869,17 @@ function createWasm() { } // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback - // to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel - // to any other async startup actions they are performing. - // Also pthreads and wasm workers initialize the wasm instance through this path. + // to manually instantiate the Wasm module themselves. This allows pages to + // run the instantiation parallel to any other async startup actions they are + // performing. + // Also pthreads and wasm workers initialize the wasm instance through this + // path. if (Module['instantiateWasm']) { + try { return Module['instantiateWasm'](info, receiveInstance); } catch(e) { - err('Module.instantiateWasm callback failed with error: ' + e); + err(`Module.instantiateWasm callback failed with error: ${e}`); return false; } } @@ -1123,12 +893,14 @@ var tempDouble; var tempI64; // include: runtime_debug.js -function legacyModuleProp(prop, newName) { +function legacyModuleProp(prop, newName, incoming=true) { if (!Object.getOwnPropertyDescriptor(Module, prop)) { Object.defineProperty(Module, prop, { configurable: true, - get: function() { - abort('Module.' + prop + ' has been replaced with plain ' + newName + ' (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)'); + get() { + let extra = incoming ? ' (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)' : ''; + abort(`\`Module.${prop}\` has been replaced by \`${newName}\`` + extra); + } }); } @@ -1136,7 +908,7 @@ function legacyModuleProp(prop, newName) { function ignoredModuleProp(prop) { if (Object.getOwnPropertyDescriptor(Module, prop)) { - abort('`Module.' + prop + '` was supplied but `' + prop + '` not included in INCOMING_MODULE_JS_API'); + abort(`\`Module.${prop}\` was supplied but \`${prop}\` not included in INCOMING_MODULE_JS_API`); } } @@ -1157,8 +929,8 @@ function missingGlobal(sym, msg) { if (typeof globalThis !== 'undefined') { Object.defineProperty(globalThis, sym, { configurable: true, - get: function() { - warnOnce('`' + sym + '` is not longer defined by emscripten. ' + msg); + get() { + warnOnce(`\`${sym}\` is not longer defined by emscripten. ${msg}`); return undefined; } }); @@ -1166,15 +938,16 @@ function missingGlobal(sym, msg) { } missingGlobal('buffer', 'Please use HEAP8.buffer or wasmMemory.buffer'); +missingGlobal('asm', 'Please use wasmExports instead'); function missingLibrarySymbol(sym) { if (typeof globalThis !== 'undefined' && !Object.getOwnPropertyDescriptor(globalThis, sym)) { Object.defineProperty(globalThis, sym, { configurable: true, - get: function() { + get() { // Can't `abort()` here because it would break code that does runtime // checks. e.g. `if (typeof SDL === 'undefined')`. - var msg = '`' + sym + '` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line'; + var msg = `\`${sym}\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`; // DEFAULT_LIBRARY_FUNCS_TO_INCLUDE requires the name as it appears in // library.js, which means $name for a JS name with no prefix, or name // for a JS name like _name. @@ -1182,7 +955,7 @@ function missingLibrarySymbol(sym) { if (!librarySymbol.startsWith('_')) { librarySymbol = '$' + sym; } - msg += " (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE=" + librarySymbol + ")"; + msg += ` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${librarySymbol}')`; if (isExportedByForceFilesystem(sym)) { msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you'; } @@ -1191,7 +964,7 @@ function missingLibrarySymbol(sym) { } }); } - // Any symbol that is not included from the JS libary is also (by definition) + // Any symbol that is not included from the JS library is also (by definition) // not exported on the Module object. unexportedRuntimeSymbol(sym); } @@ -1200,8 +973,8 @@ function unexportedRuntimeSymbol(sym) { if (!Object.getOwnPropertyDescriptor(Module, sym)) { Object.defineProperty(Module, sym, { configurable: true, - get: function() { - var msg = "'" + sym + "' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)"; + get() { + var msg = `'${sym}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`; if (isExportedByForceFilesystem(sym)) { msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you'; } @@ -1212,38 +985,38 @@ function unexportedRuntimeSymbol(sym) { } // Used by XXXXX_DEBUG settings to output debug messages. -function dbg(text) { +function dbg(...args) { // TODO(sbc): Make this configurable somehow. Its not always convenient for - // logging to show up as errors. - console.error(text); + // logging to show up as warnings. + console.warn(...args); } - // end include: runtime_debug.js // === Body === var ASM_CONSTS = { - 380080: ($0) => { if (!$0) { AL.alcErr = 0xA004 ; return 1; } }, - 380128: ($0) => { if (!AL.currentCtx) { err("alGetProcAddress() called without a valid context"); return 1; } if (!$0) { AL.currentCtx.err = 0xA003 ; return 1; } } + 380640: ($0) => { if (!$0) { AL.alcErr = 0xA004 ; return 1; } }, + 380688: ($0) => { if (!AL.currentCtx) { err("alGetProcAddress() called without a valid context"); return 1; } if (!$0) { AL.currentCtx.err = 0xA003 ; return 1; } } }; - - // end include: preamble.js + /** @constructor */ function ExitStatus(status) { this.name = 'ExitStatus'; - this.message = 'Program terminated with exit(' + status + ')'; + this.message = `Program terminated with exit(${status})`; this.status = status; } - Module["ExitStatus"] = ExitStatus; + Module['ExitStatus'] = ExitStatus; - var GOT = {}; - Module["GOT"] = GOT; + var GOT = { + }; + Module['GOT'] = GOT; var currentModuleWeakSymbols = new Set([]); - Module["currentModuleWeakSymbols"] = currentModuleWeakSymbols; - var GOTHandler = {get:function(obj, symName) { + Module['currentModuleWeakSymbols'] = currentModuleWeakSymbols; + var GOTHandler = { + get(obj, symName) { var rtn = GOT[symName]; if (!rtn) { rtn = GOT[symName] = new WebAssembly.Global({'value': 'i32', 'mutable': true}); @@ -1255,18 +1028,74 @@ var ASM_CONSTS = { rtn.required = true; } return rtn; - }}; - Module["GOTHandler"] = GOTHandler; + }, + }; + Module['GOTHandler'] = GOTHandler; - function callRuntimeCallbacks(callbacks) { + var callRuntimeCallbacks = (callbacks) => { while (callbacks.length > 0) { // Pass the module as the first argument. callbacks.shift()(Module); } - } - Module["callRuntimeCallbacks"] = callRuntimeCallbacks; + }; + Module['callRuntimeCallbacks'] = callRuntimeCallbacks; - function getDylinkMetadata(binary) { + var UTF8Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder('utf8') : undefined; + Module['UTF8Decoder'] = UTF8Decoder; + + /** + * Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given + * array that contains uint8 values, returns a copy of that string as a + * Javascript String object. + * heapOrArray is either a regular array, or a JavaScript typed array view. + * @param {number} idx + * @param {number=} maxBytesToRead + * @return {string} + */ + var UTF8ArrayToString = (heapOrArray, idx, maxBytesToRead) => { + var endIdx = idx + maxBytesToRead; + var endPtr = idx; + // TextDecoder needs to know the byte length in advance, it doesn't stop on + // null terminator by itself. Also, use the length info to avoid running tiny + // strings through TextDecoder, since .subarray() allocates garbage. + // (As a tiny code save trick, compare endPtr against endIdx using a negation, + // so that undefined means Infinity) + while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr; + + if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) { + return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr)); + } + var str = ''; + // If building with TextDecoder, we have already computed the string length + // above, so test loop end condition against that + while (idx < endPtr) { + // For UTF8 byte structure, see: + // http://en.wikipedia.org/wiki/UTF-8#Description + // https://www.ietf.org/rfc/rfc2279.txt + // https://tools.ietf.org/html/rfc3629 + var u0 = heapOrArray[idx++]; + if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; } + var u1 = heapOrArray[idx++] & 63; + if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; } + var u2 = heapOrArray[idx++] & 63; + if ((u0 & 0xF0) == 0xE0) { + u0 = ((u0 & 15) << 12) | (u1 << 6) | u2; + } else { + if ((u0 & 0xF8) != 0xF0) warnOnce('Invalid UTF-8 leading byte ' + ptrToString(u0) + ' encountered when deserializing a UTF-8 string in wasm memory to a JS string!'); + u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heapOrArray[idx++] & 63); + } + + if (u0 < 0x10000) { + str += String.fromCharCode(u0); + } else { + var ch = u0 - 0x10000; + str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF)); + } + } + return str; + }; + Module['UTF8ArrayToString'] = UTF8ArrayToString; + var getDylinkMetadata = (binary) => { var offset = 0; var end = 0; @@ -1376,7 +1205,7 @@ var ASM_CONSTS = { } } } else { - err('unknown dylink.0 subsection: ' + subsectionType) + err(`unknown dylink.0 subsection: ${subsectionType}`) // unknown subsection offset += subsectionSize; } @@ -1384,12 +1213,12 @@ var ASM_CONSTS = { } var tableAlign = Math.pow(2, customSection.tableAlign); - assert(tableAlign === 1, 'invalid tableAlign ' + tableAlign); + assert(tableAlign === 1, `invalid tableAlign ${tableAlign}`); assert(offset == end); return customSection; - } - Module["getDylinkMetadata"] = getDylinkMetadata; + }; + Module['getDylinkMetadata'] = getDylinkMetadata; /** @@ -1399,23 +1228,23 @@ var ASM_CONSTS = { function getValue(ptr, type = 'i8') { if (type.endsWith('*')) type = '*'; switch (type) { - case 'i1': return HEAP8[((ptr)>>0)]; - case 'i8': return HEAP8[((ptr)>>0)]; + case 'i1': return HEAP8[ptr]; + case 'i8': return HEAP8[ptr]; case 'i16': return HEAP16[((ptr)>>1)]; case 'i32': return HEAP32[((ptr)>>2)]; - case 'i64': return HEAP32[((ptr)>>2)]; + case 'i64': abort('to do getValue(i64) use WASM_BIGINT'); case 'float': return HEAPF32[((ptr)>>2)]; case 'double': return HEAPF64[((ptr)>>3)]; case '*': return HEAPU32[((ptr)>>2)]; - default: abort('invalid type for getValue: ' + type); + default: abort(`invalid type for getValue: ${type}`); } } - Module["getValue"] = getValue; + Module['getValue'] = getValue; - function newDSO(name, handle, syms) { + var newDSO = (name, handle, syms) => { var dso = { refcount: Infinity, - name: name, + name, exports: syms, global: true, }; @@ -1424,22 +1253,40 @@ var ASM_CONSTS = { LDSO.loadedLibsByHandle[handle] = dso; } return dso; - } - Module["newDSO"] = newDSO; - var LDSO = {loadedLibsByName:{},loadedLibsByHandle:{},init:() => newDSO('__main__', 0, wasmImports)}; - Module["LDSO"] = LDSO; + }; + Module['newDSO'] = newDSO; + var LDSO = { + loadedLibsByName:{ + }, + loadedLibsByHandle:{ + }, + init() { + // This function needs to run after the initial wasmImports object + // as been created. + assert(wasmImports); + newDSO('__main__', 0, wasmImports); + }, + }; + Module['LDSO'] = LDSO; - var ___heap_base = 491744; - Module["___heap_base"] = ___heap_base; + var ___heap_base = 492464; + Module['___heap_base'] = ___heap_base; - function zeroMemory(address, size) { + var zeroMemory = (address, size) => { HEAPU8.fill(0, address, address + size); return address; - } - Module["zeroMemory"] = zeroMemory; - function getMemory(size) { + }; + Module['zeroMemory'] = zeroMemory; + + var alignMemory = (size, alignment) => { + assert(alignment, "alignment argument is required"); + return Math.ceil(size / alignment) * alignment; + }; + Module['alignMemory'] = alignMemory; + + var getMemory = (size) => { // After the runtime is initialized, we must only use sbrk() normally. if (runtimeInitialized) { // Currently we don't support freeing of static data when modules are @@ -1448,16 +1295,17 @@ var ASM_CONSTS = { return zeroMemory(_malloc(size), size); } var ret = ___heap_base; - var end = (ret + size + 15) & -16; + // Keep __heap_base stack aligned. + var end = ret + alignMemory(size, 16); assert(end <= HEAP8.length, 'failure to getMemory - memory growth etc. is not supported there, call malloc/sbrk directly or increase INITIAL_MEMORY'); ___heap_base = end; GOT['__heap_base'].value = end; return ret; - } - Module["getMemory"] = getMemory; + }; + Module['getMemory'] = getMemory; - function isInternalSym(symName) { + var isInternalSym = (symName) => { // TODO: find a way to mark these in the binary or avoid exporting them. return [ '__cpp_exception', @@ -1472,28 +1320,31 @@ var ASM_CONSTS = { '__wasm_call_ctors', '__start_em_asm', '__stop_em_asm', - ].includes(symName) + '__start_em_js', + '__stop_em_js', + ].includes(symName) || symName.startsWith('__em_js__') ; - } - Module["isInternalSym"] = isInternalSym; + }; + Module['isInternalSym'] = isInternalSym; - function uleb128Encode(n, target) { + var uleb128Encode = (n, target) => { assert(n < 16384); if (n < 128) { target.push(n); } else { target.push((n % 128) | 128, n >> 7); } - } - Module["uleb128Encode"] = uleb128Encode; + }; + Module['uleb128Encode'] = uleb128Encode; - function sigToWasmTypes(sig) { + var sigToWasmTypes = (sig) => { + assert(!sig.includes('j'), 'i64 not permitted in function signatures when WASM_BIGINT is disabled'); var typeNames = { 'i': 'i32', - // i64 values will be split into two i32s. - 'j': 'i32', + 'j': 'i64', 'f': 'f32', 'd': 'f64', + 'e': 'externref', 'p': 'i32', }; var type = { @@ -1503,15 +1354,12 @@ var ASM_CONSTS = { for (var i = 1; i < sig.length; ++i) { assert(sig[i] in typeNames, 'invalid signature char: ' + sig[i]); type.parameters.push(typeNames[sig[i]]); - if (sig[i] === 'j') { - type.parameters.push('i32'); - } } return type; - } - Module["sigToWasmTypes"] = sigToWasmTypes; + }; + Module['sigToWasmTypes'] = sigToWasmTypes; - function generateFuncType(sig, target){ + var generateFuncType = (sig, target) => { var sigRet = sig.slice(0, 1); var sigParam = sig.slice(1); var typeCodes = { @@ -1520,16 +1368,17 @@ var ASM_CONSTS = { 'j': 0x7e, // i64 'f': 0x7d, // f32 'd': 0x7c, // f64 + 'e': 0x6f, // externref }; - + // Parameters, length + signatures target.push(0x60 /* form: func */); uleb128Encode(sigParam.length, target); for (var i = 0; i < sigParam.length; ++i) { assert(sigParam[i] in typeCodes, 'invalid signature char: ' + sigParam[i]); - target.push(typeCodes[sigParam[i]]); + target.push(typeCodes[sigParam[i]]); } - + // Return values, length + signatures // With no multi-return in MVP, either 0 (void) or 1 (anything else) if (sigRet == 'v') { @@ -1537,9 +1386,11 @@ var ASM_CONSTS = { } else { target.push(0x01, typeCodes[sigRet]); } - } - Module["generateFuncType"] = generateFuncType; - function convertJsFunctionToWasm(func, sig) { + }; + Module['generateFuncType'] = generateFuncType; + var convertJsFunctionToWasm = (func, sig) => { + + assert(!sig.includes('j'), 'i64 not permitted in function signatures when WASM_BIGINT is disabled'); // If the type reflection proposal is available, use the new // "WebAssembly.Function" constructor. @@ -1564,7 +1415,7 @@ var ASM_CONSTS = { ]; // Write the overall length of the type section followed by the body uleb128Encode(typeSectionBody.length, bytes); - bytes.push.apply(bytes, typeSectionBody); + bytes.push(...typeSectionBody); // The rest of the module is static bytes.push( @@ -1582,24 +1433,30 @@ var ASM_CONSTS = { var instance = new WebAssembly.Instance(module, { 'e': { 'f': func } }); var wrappedFunc = instance.exports['f']; return wrappedFunc; - } - Module["convertJsFunctionToWasm"] = convertJsFunctionToWasm; + }; + Module['convertJsFunctionToWasm'] = convertJsFunctionToWasm; var wasmTableMirror = []; - Module["wasmTableMirror"] = wasmTableMirror; + Module['wasmTableMirror'] = wasmTableMirror; - function getWasmTableEntry(funcPtr) { + var wasmTable = new WebAssembly.Table({ + 'initial': 1054, + 'element': 'anyfunc' + }); + ; + Module['wasmTable'] = wasmTable; + var getWasmTableEntry = (funcPtr) => { var func = wasmTableMirror[funcPtr]; if (!func) { if (funcPtr >= wasmTableMirror.length) wasmTableMirror.length = funcPtr + 1; wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr); } - assert(wasmTable.get(funcPtr) == func, "JavaScript-side Wasm function table mirror is out of date!"); + assert(wasmTable.get(funcPtr) == func, 'JavaScript-side Wasm function table mirror is out of date!'); return func; - } - Module["getWasmTableEntry"] = getWasmTableEntry; + }; + Module['getWasmTableEntry'] = getWasmTableEntry; - function updateTableMap(offset, count) { + var updateTableMap = (offset, count) => { if (functionsInTableMap) { for (var i = offset; i < offset + count; i++) { var item = getWasmTableEntry(i); @@ -1609,25 +1466,27 @@ var ASM_CONSTS = { } } } - } - Module["updateTableMap"] = updateTableMap; + }; + Module['updateTableMap'] = updateTableMap; + + var functionsInTableMap; + Module['functionsInTableMap'] = functionsInTableMap; - var functionsInTableMap = undefined; - Module["functionsInTableMap"] = functionsInTableMap; - function getFunctionAddress(func) { + var getFunctionAddress = (func) => { // First, create the map if this is the first use. if (!functionsInTableMap) { functionsInTableMap = new WeakMap(); updateTableMap(0, wasmTable.length); } return functionsInTableMap.get(func) || 0; - } - Module["getFunctionAddress"] = getFunctionAddress; + }; + Module['getFunctionAddress'] = getFunctionAddress; var freeTableIndexes = []; - Module["freeTableIndexes"] = freeTableIndexes; - function getEmptyTableSlot() { + Module['freeTableIndexes'] = freeTableIndexes; + + var getEmptyTableSlot = () => { // Reuse a free index if there is one, otherwise grow. if (freeTableIndexes.length) { return freeTableIndexes.pop(); @@ -1642,20 +1501,22 @@ var ASM_CONSTS = { throw 'Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.'; } return wasmTable.length - 1; - } - Module["getEmptyTableSlot"] = getEmptyTableSlot; + }; + Module['getEmptyTableSlot'] = getEmptyTableSlot; + - function setWasmTableEntry(idx, func) { + var setWasmTableEntry = (idx, func) => { wasmTable.set(idx, func); // With ABORT_ON_WASM_EXCEPTIONS wasmTable.get is overridden to return wrapped // functions so we need to call it here to retrieve the potential wrapper correctly // instead of just storing 'func' directly into wasmTableMirror wasmTableMirror[idx] = wasmTable.get(idx); - } - Module["setWasmTableEntry"] = setWasmTableEntry; + }; + Module['setWasmTableEntry'] = setWasmTableEntry; + /** @param {string=} sig */ - function addFunction(func, sig) { + var addFunction = (func, sig) => { assert(typeof func != 'undefined'); // Check if the function is already in the table, to ensure each function // gets a unique index. @@ -1684,10 +1545,10 @@ var ASM_CONSTS = { functionsInTableMap.set(func, ret); return ret; - } - Module["addFunction"] = addFunction; + }; + Module['addFunction'] = addFunction; - function updateGOT(exports, replace) { + var updateGOT = (exports, replace) => { for (var symName in exports) { if (isInternalSym(symName)) { continue; @@ -1699,23 +1560,21 @@ var ASM_CONSTS = { replace = true; } - if (!GOT[symName]) { - GOT[symName] = new WebAssembly.Global({'value': 'i32', 'mutable': true}); - } + GOT[symName] ||= new WebAssembly.Global({'value': 'i32', 'mutable': true}); if (replace || GOT[symName].value == 0) { if (typeof value == 'function') { GOT[symName].value = addFunction(value); } else if (typeof value == 'number') { GOT[symName].value = value; } else { - err("unhandled export type for `" + symName + "`: " + (typeof value)); + err(`unhandled export type for '${symName}': ${typeof value}`); } } } - } - Module["updateGOT"] = updateGOT; + }; + Module['updateGOT'] = updateGOT; /** @param {boolean=} replace */ - function relocateExports(exports, memoryBase, replace) { + var relocateExports = (exports, memoryBase, replace) => { var relocated = {}; for (var e in exports) { @@ -1732,55 +1591,24 @@ var ASM_CONSTS = { } updateGOT(relocated, replace); return relocated; - } - Module["relocateExports"] = relocateExports; + }; + Module['relocateExports'] = relocateExports; - function isSymbolDefined(symName) { + var isSymbolDefined = (symName) => { // Ignore 'stub' symbols that are auto-generated as part of the original - // `wasmImports` used to instantate the main module. + // `wasmImports` used to instantiate the main module. var existing = wasmImports[symName]; if (!existing || existing.stub) { return false; } return true; - } - Module["isSymbolDefined"] = isSymbolDefined; - function resolveGlobalSymbol(symName, direct = false) { - var sym; - // First look for the orig$ symbol which is the symbol without i64 - // legalization performed. - if (direct && ('orig$' + symName in wasmImports)) { - symName = 'orig$' + symName; - } - if (isSymbolDefined(symName)) { - sym = wasmImports[symName]; - } - // Asm.js-style exception handling: invoke wrapper generation - else if (symName.startsWith('invoke_')) { - // Create (and cache) new invoke_ functions on demand. - sym = wasmImports[symName] = createInvokeFunction(symName.split('_')[1]); - } - return {sym: sym, name: symName}; - } - Module["resolveGlobalSymbol"] = resolveGlobalSymbol; - - - - function alignMemory(size, alignment) { - assert(alignment, "alignment argument is required"); - return Math.ceil(size / alignment) * alignment; - } - Module["alignMemory"] = alignMemory; - - - - - + }; + Module['isSymbolDefined'] = isSymbolDefined; - function createDyncallWrapper(sig) { + var createDyncallWrapper = (sig) => { var sections = []; var prelude = [ 0x00, 0x61, 0x73, 0x6d, // magic ("\0asm") @@ -1805,7 +1633,7 @@ var ASM_CONSTS = { var typeSection = [0x01 /* Type section code */]; uleb128Encode(typeSectionBody.length, typeSection); // length of section in bytes - typeSection.push.apply(typeSection, typeSectionBody); + typeSection.push(...typeSectionBody); sections.push(typeSection); var importSection = [ @@ -1907,10 +1735,10 @@ var ASM_CONSTS = { var codeBody = [0x01]; // one code uleb128Encode(convert_code.length, codeBody); - codeBody.push.apply(codeBody, convert_code); + codeBody.push(...convert_code); var codeSection = [0x0A /* Code section code */]; uleb128Encode(codeBody.length, codeSection); - codeSection.push.apply(codeSection, codeBody); + codeSection.push(...codeBody); sections.push(codeSection); var bytes = new Uint8Array([].concat.apply([], sections)); @@ -1924,11 +1752,11 @@ var ASM_CONSTS = { }); var wrappedFunc = instance.exports['f']; return wrappedFunc; - } - Module["createDyncallWrapper"] = createDyncallWrapper; - function dynCallLegacy(sig, ptr, args) { - assert(('dynCall_' + sig) in Module, 'bad function pointer type - dynCall function not found for sig \'' + sig + '\''); - if (args && args.length) { + }; + Module['createDyncallWrapper'] = createDyncallWrapper; + var dynCallLegacy = (sig, ptr, args) => { + assert(('dynCall_' + sig) in Module, `bad function pointer type - dynCall function not found for sig '${sig}'`); + if (args?.length) { // j (64-bit integer) must be passed in as two numbers [low 32, high 32]. assert(args.length === sig.substring(1).replace(/j/g, '--').length); } else { @@ -1938,26 +1766,27 @@ var ASM_CONSTS = { Module['dynCall_' + sig] = createDyncallWrapper(sig); } var f = Module['dynCall_' + sig]; - return args && args.length ? f.apply(null, [ptr].concat(args)) : f.call(null, ptr); - } - Module["dynCallLegacy"] = dynCallLegacy; + return f(ptr, ...args); + }; + Module['dynCallLegacy'] = dynCallLegacy; - /** @param {Object=} args */ - function dynCall(sig, ptr, args) { + var dynCall = (sig, ptr, args = []) => { // Without WASM_BIGINT support we cannot directly call function with i64 as - // part of thier signature, so we rely the dynCall functions generated by + // part of their signature, so we rely on the dynCall functions generated by // wasm-emscripten-finalize if (sig.includes('j')) { return dynCallLegacy(sig, ptr, args); } - assert(getWasmTableEntry(ptr), 'missing table entry in dynCall: ' + ptr); - var rtn = getWasmTableEntry(ptr).apply(null, args); + assert(getWasmTableEntry(ptr), `missing table entry in dynCall: ${ptr}`); + var rtn = getWasmTableEntry(ptr)(...args); return rtn; - } - Module["dynCall"] = dynCall; + }; + Module['dynCall'] = dynCall; + + - function createInvokeFunction(sig) { + var createInvokeFunction = (sig) => { return function() { var sp = stackSave(); try { @@ -1972,14 +1801,62 @@ var ASM_CONSTS = { _setThrew(1, 0); } } - } - Module["createInvokeFunction"] = createInvokeFunction; + }; + Module['createInvokeFunction'] = createInvokeFunction; + var resolveGlobalSymbol = (symName, direct = false) => { + var sym; + // First look for the orig$ symbol which is the symbol without i64 + // legalization performed. + if (direct && ('orig$' + symName in wasmImports)) { + symName = 'orig$' + symName; + } + if (isSymbolDefined(symName)) { + sym = wasmImports[symName]; + } + // Asm.js-style exception handling: invoke wrapper generation + else if (symName.startsWith('invoke_')) { + // Create (and cache) new invoke_ functions on demand. + sym = wasmImports[symName] = createInvokeFunction(symName.split('_')[1]); + } + return {sym, name: symName}; + }; + Module['resolveGlobalSymbol'] = resolveGlobalSymbol; + + + + + + + + + + /** + * Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the + * emscripten HEAP, returns a copy of that string as a Javascript String object. + * + * @param {number} ptr + * @param {number=} maxBytesToRead - An optional length that specifies the + * maximum number of bytes to read. You can omit this parameter to scan the + * string until the first 0 byte. If maxBytesToRead is passed, and the string + * at [ptr, ptr+maxBytesToReadr[ contains a null byte in the middle, then the + * string will cut short at that byte index (i.e. maxBytesToRead will not + * produce a string of exact length [ptr, ptr+maxBytesToRead[) N.B. mixing + * frequent uses of UTF8ToString() with and without maxBytesToRead may throw + * JS JIT optimizations off, so it is worth to consider consistently using one + * @return {string} + */ + var UTF8ToString = (ptr, maxBytesToRead) => { + assert(typeof ptr == 'number', `UTF8ToString expects a number (got ${typeof ptr})`); + return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : ''; + }; + Module['UTF8ToString'] = UTF8ToString; /** + * @param {string=} libName * @param {Object=} localScope * @param {number=} handle */ - function loadWebAssemblyModule(binary, flags, localScope, handle) { + var loadWebAssemblyModule = (binary, flags, libName, localScope, handle) => { var metadata = getDylinkMetadata(binary); currentModuleWeakSymbols = metadata.weakImports; var originalTable = wasmTable; @@ -1994,17 +1871,15 @@ var ASM_CONSTS = { // If `handle` is specified than it is assumed that the calling thread has // exclusive access to it for the duration of this function. See the // locking in `dynlink.c`. - var firstLoad = !handle || !HEAP8[(((handle)+(8))>>0)]; + var firstLoad = !handle || !HEAP8[(handle)+(8)]; if (firstLoad) { // alignments are powers of 2 var memAlign = Math.pow(2, metadata.memoryAlign); - // finalize alignments and verify them - memAlign = Math.max(memAlign, 16); // we at least need stack alignment // prepare memory var memoryBase = metadata.memorySize ? alignMemory(getMemory(metadata.memorySize + memAlign), memAlign) : 0; // TODO: add to cleanups var tableBase = metadata.tableSize ? wasmTable.length : 0; if (handle) { - HEAP8[(((handle)+(8))>>0)] = 1; + HEAP8[(handle)+(8)] = 1; HEAPU32[(((handle)+(12))>>2)] = memoryBase; HEAP32[(((handle)+(16))>>2)] = metadata.memorySize; HEAPU32[(((handle)+(20))>>2)] = tableBase; @@ -2035,7 +1910,7 @@ var ASM_CONSTS = { if (!resolved) { resolved = moduleExports[sym]; } - assert(resolved, 'undefined symbol `' + sym + '`. perhaps a side module was not linked in? if this global was expected to arrive from a system library, try to build the MAIN_MODULE with EMCC_FORCE_STDLIBS=1 in the environment'); + assert(resolved, `undefined symbol '${sym}'. perhaps a side module was not linked in? if this global was expected to arrive from a system library, try to build the MAIN_MODULE with EMCC_FORCE_STDLIBS=1 in the environment`); return resolved; } @@ -2051,7 +1926,7 @@ var ASM_CONSTS = { // are. To do that here, we use a JS proxy (another option would // be to inspect the binary directly). var proxyHandler = { - 'get': function(stubs, prop) { + get(stubs, prop) { // symbols that should be local to this module switch (prop) { case '__memory_base': @@ -2067,9 +1942,9 @@ var ASM_CONSTS = { // when first called. if (!(prop in stubs)) { var resolved; - stubs[prop] = function() { - if (!resolved) resolved = resolveSymbol(prop); - return resolved.apply(null, arguments); + stubs[prop] = (...args) => { + resolved ||= resolveSymbol(prop); + return resolved(...args); }; } return stubs[prop]; @@ -2080,10 +1955,10 @@ var ASM_CONSTS = { 'GOT.mem': new Proxy({}, GOTHandler), 'GOT.func': new Proxy({}, GOTHandler), 'env': proxy, - wasi_snapshot_preview1: proxy, + 'wasi_snapshot_preview1': proxy, }; - function postInstantiation(instance) { + function postInstantiation(module, instance) { // the table should be unchanged assert(wasmTable === originalTable); // add new entries to functionsInTableMap @@ -2104,7 +1979,7 @@ var ASM_CONSTS = { } } args = args.join(','); - var func = '(' + args +' ) => { ' + body + '};' + var func = `(${args}) => { ${body} };`; ASM_CONSTS[start] = eval(func); } @@ -2121,6 +1996,36 @@ var ASM_CONSTS = { } } + function addEmJs(name, cSig, body) { + // The signature here is a C signature (e.g. "(int foo, char* bar)"). + // See `create_em_js` in emcc.py` for the build-time version of this + // code. + var jsArgs = []; + cSig = cSig.slice(1, -1) + if (cSig != 'void') { + cSig = cSig.split(','); + for (var i in cSig) { + var jsArg = cSig[i].split(' ').pop(); + jsArgs.push(jsArg.replace('*', '')); + } + } + var func = `(${jsArgs}) => ${body};`; + moduleExports[name] = eval(func); + } + + for (var name in moduleExports) { + if (name.startsWith('__em_js__')) { + var start = moduleExports[name] + + var jsString = UTF8ToString(start); + // EM_JS strings are stored in the data section in the form + // SIG<::>BODY. + var parts = jsString.split('<::>'); + addEmJs(name.replace('__em_js__', ''), parts[0], parts[1]); + delete moduleExports[name]; + } + } + // initialize the module var applyRelocs = moduleExports['__wasm_apply_data_relocs']; if (applyRelocs) { @@ -2145,43 +2050,36 @@ var ASM_CONSTS = { if (flags.loadAsync) { if (binary instanceof WebAssembly.Module) { var instance = new WebAssembly.Instance(binary, info); - return Promise.resolve(postInstantiation(instance)); + return Promise.resolve(postInstantiation(binary, instance)); } - return WebAssembly.instantiate(binary, info).then(function(result) { - return postInstantiation(result.instance); - }); + return WebAssembly.instantiate(binary, info).then( + (result) => postInstantiation(result.module, result.instance) + ); } var module = binary instanceof WebAssembly.Module ? binary : new WebAssembly.Module(binary); var instance = new WebAssembly.Instance(module, info); - return postInstantiation(instance); + return postInstantiation(module, instance); } // now load needed libraries and the module itself. if (flags.loadAsync) { - return metadata.neededDynlibs.reduce(function(chain, dynNeeded) { - return chain.then(function() { - return loadDynamicLibrary(dynNeeded, flags); - }); - }, Promise.resolve()).then(function() { - return loadModule(); - }); + return metadata.neededDynlibs + .reduce((chain, dynNeeded) => chain.then(() => + loadDynamicLibrary(dynNeeded, flags) + ), Promise.resolve()) + .then(loadModule); } - metadata.neededDynlibs.forEach(function(dynNeeded) { - loadDynamicLibrary(dynNeeded, flags, localScope); - }); + metadata.neededDynlibs.forEach((needed) => loadDynamicLibrary(needed, flags, localScope)); return loadModule(); - } - Module["loadWebAssemblyModule"] = loadWebAssemblyModule; + }; + Module['loadWebAssemblyModule'] = loadWebAssemblyModule; - function mergeLibSymbols(exports, libName) { + var mergeLibSymbols = (exports, libName) => { // add symbols into global namespace TODO: weak linking etc. - for (var sym in exports) { - if (!exports.hasOwnProperty(sym)) { - continue; - } + for (var [sym, exp] of Object.entries(exports)) { // When RTLD_GLOBAL is enabled, the symbols defined by this shared object // will be made available for symbol resolution of subsequently loaded @@ -2191,7 +2089,7 @@ var ASM_CONSTS = { // SIDE_MODULE to MAIN_MODULE. const setImport = (target) => { if (!isSymbolDefined(target)) { - wasmImports[target] = exports[sym]; + wasmImports[target] = exp; } } setImport(sym); @@ -2208,16 +2106,67 @@ var ASM_CONSTS = { } if (sym.startsWith('dynCall_') && !Module.hasOwnProperty(sym)) { - Module[sym] = exports[sym]; + Module[sym] = exp; } } - } - Module["mergeLibSymbols"] = mergeLibSymbols; + }; + Module['mergeLibSymbols'] = mergeLibSymbols; - /** - * @param {number=} handle - * @param {Object=} localScope + /** @param {boolean=} noRunDep */ + var asyncLoad = (url, onload, onerror, noRunDep) => { + var dep = !noRunDep ? getUniqueRunDependency(`al ${url}`) : ''; + readAsync(url, (arrayBuffer) => { + assert(arrayBuffer, `Loading data file "${url}" failed (no arrayBuffer).`); + onload(new Uint8Array(arrayBuffer)); + if (dep) removeRunDependency(dep); + }, (event) => { + if (onerror) { + onerror(); + } else { + throw `Loading data file "${url}" failed.`; + } + }); + if (dep) addRunDependency(dep); + }; + Module['asyncLoad'] = asyncLoad; + + var preloadPlugins = Module['preloadPlugins'] || []; + Module['preloadPlugins'] = preloadPlugins; + var registerWasmPlugin = () => { + // Use string keys here to avoid minification since the plugin consumer + // also uses string keys. + var wasmPlugin = { + 'promiseChainEnd': Promise.resolve(), + 'canHandle': (name) => { + return !Module.noWasmDecoding && name.endsWith('.so') + }, + 'handle': (byteArray, name, onload, onerror) => { + // loadWebAssemblyModule can not load modules out-of-order, so rather + // than just running the promises in parallel, this makes a chain of + // promises to run in series. + wasmPlugin['promiseChainEnd'] = wasmPlugin['promiseChainEnd'].then( + () => loadWebAssemblyModule(byteArray, {loadAsync: true, nodelete: true}, name)).then( + (exports) => { + preloadedWasm[name] = exports; + onload(byteArray); + }, + (error) => { + err(`failed to instantiate wasm: ${name}: ${error}`); + onerror(); + }); + } + }; + preloadPlugins.push(wasmPlugin); + }; + Module['registerWasmPlugin'] = registerWasmPlugin; + var preloadedWasm = { + }; + Module['preloadedWasm'] = preloadedWasm; + + /** + * @param {number=} handle + * @param {Object=} localScope */ function loadDynamicLibrary(libName, flags = {global: true, nodelete: true}, localScope, handle) { // when loadDynamicLibrary did not have flags, libraries were loaded @@ -2226,15 +2175,16 @@ var ASM_CONSTS = { var dso = LDSO.loadedLibsByName[libName]; if (dso) { // the library is being loaded or has been loaded already. - // - // however it could be previously loaded only locally and if we get - // load request with global=true we have to make it globally visible now. - if (flags.global && !dso.global) { + assert(dso.exports !== 'loading', `Attempt to load '${libName}' twice before the first load completed`); + if (!flags.global) { + if (localScope) { + Object.assign(localScope, dso.exports); + } + } else if (!dso.global) { + // The library was previously loaded only locally but not + // we have a request with global=true. dso.global = true; - if (dso.exports !== 'loading') { - // ^^^ if module is 'loading' - symbols merging will be eventually done by the loader. - mergeLibSymbols(dso.exports, libName) - } + mergeLibSymbols(dso.exports, libName) } // same for "nodelete" if (flags.nodelete && dso.refcount !== Infinity) { @@ -2254,25 +2204,27 @@ var ASM_CONSTS = { // libName -> libData function loadLibData() { + // for wasm, we can use fetch for async, but for fs mode we can only imitate it - if (flags.fs && flags.fs.findObject(libName)) { - var libData = flags.fs.readFile(libName, {encoding: 'binary'}); - if (!(libData instanceof Uint8Array)) { - libData = new Uint8Array(libData); + if (handle) { + var data = HEAPU32[(((handle)+(28))>>2)]; + var dataSize = HEAPU32[(((handle)+(32))>>2)]; + if (data && dataSize) { + var libData = HEAP8.slice(data, data + dataSize); + return flags.loadAsync ? Promise.resolve(libData) : libData; } - return flags.loadAsync ? Promise.resolve(libData) : libData; } var libFile = locateFile(libName); if (flags.loadAsync) { return new Promise(function(resolve, reject) { - readAsync(libFile, (data) => resolve(new Uint8Array(data)), reject); + asyncLoad(libFile, resolve, reject); }); } // load the binary synchronously if (!readBinary) { - throw new Error(libFile + ': file not found, and synchronous loading of external files is not available'); + throw new Error(`${libFile}: file not found, and synchronous loading of external files is not available`); } return readBinary(libFile); } @@ -2280,17 +2232,17 @@ var ASM_CONSTS = { // libName -> exports function getExports() { // lookup preloaded cache first - if (typeof preloadedWasm != 'undefined' && preloadedWasm[libName]) { - var libModule = preloadedWasm[libName]; - return flags.loadAsync ? Promise.resolve(libModule) : libModule; + var preloaded = preloadedWasm[libName]; + if (preloaded) { + return flags.loadAsync ? Promise.resolve(preloaded) : preloaded; } // module not preloaded - load lib data and create new module from it if (flags.loadAsync) { - return loadLibData().then((libData) => loadWebAssemblyModule(libData, flags, localScope, handle)); + return loadLibData().then((libData) => loadWebAssemblyModule(libData, flags, libName, localScope, handle)); } - return loadWebAssemblyModule(loadLibData(), flags, localScope, handle); + return loadWebAssemblyModule(loadLibData(), flags, libName, localScope, handle); } // module for lib is loaded - update the dso & global namespace @@ -2313,31 +2265,31 @@ var ASM_CONSTS = { moduleLoaded(getExports()); return true; } - Module["loadDynamicLibrary"] = loadDynamicLibrary; + Module['loadDynamicLibrary'] = loadDynamicLibrary; - function reportUndefinedSymbols() { - for (var symName in GOT) { - if (GOT[symName].value == 0) { + var reportUndefinedSymbols = () => { + for (var [symName, entry] of Object.entries(GOT)) { + if (entry.value == 0) { var value = resolveGlobalSymbol(symName, true).sym; - if (!value && !GOT[symName].required) { + if (!value && !entry.required) { // Ignore undefined symbols that are imported as weak. continue; } - assert(value, 'undefined symbol `' + symName + '`. perhaps a side module was not linked in? if this global was expected to arrive from a system library, try to build the MAIN_MODULE with EMCC_FORCE_STDLIBS=1 in the environment'); + assert(value, `undefined symbol '${symName}'. perhaps a side module was not linked in? if this global was expected to arrive from a system library, try to build the MAIN_MODULE with EMCC_FORCE_STDLIBS=1 in the environment`); if (typeof value == 'function') { /** @suppress {checkTypes} */ - GOT[symName].value = addFunction(value, value.sig); + entry.value = addFunction(value, value.sig); } else if (typeof value == 'number') { - GOT[symName].value = value; + entry.value = value; } else { - throw new Error('bad export type for `' + symName + '`: ' + (typeof value)); + throw new Error(`bad export type for '${symName}': ${typeof value}`); } } } - } - Module["reportUndefinedSymbols"] = reportUndefinedSymbols; - function loadDylibs() { + }; + Module['reportUndefinedSymbols'] = reportUndefinedSymbols; + var loadDylibs = () => { if (!dynamicLibraries.length) { reportUndefinedSymbols(); return; @@ -2345,24 +2297,29 @@ var ASM_CONSTS = { // Load binaries asynchronously addRunDependency('loadDylibs'); - dynamicLibraries.reduce(function(chain, lib) { - return chain.then(function() { - return loadDynamicLibrary(lib, {loadAsync: true, global: true, nodelete: true, allowUndefined: true}); + dynamicLibraries + .reduce((chain, lib) => chain.then(() => + loadDynamicLibrary(lib, {loadAsync: true, global: true, nodelete: true, allowUndefined: true}) + ), Promise.resolve()) + .then(() => { + // we got them all, wonderful + reportUndefinedSymbols(); + removeRunDependency('loadDylibs'); }); - }, Promise.resolve()).then(function() { - // we got them all, wonderful - reportUndefinedSymbols(); - removeRunDependency('loadDylibs'); - }); - } - Module["loadDylibs"] = loadDylibs; + }; + Module['loadDylibs'] = loadDylibs; - function ptrToString(ptr) { + var noExitRuntime = Module['noExitRuntime'] || true; + Module['noExitRuntime'] = noExitRuntime; + + var ptrToString = (ptr) => { assert(typeof ptr === 'number'); + // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned. + ptr >>>= 0; return '0x' + ptr.toString(16).padStart(8, '0'); - } - Module["ptrToString"] = ptrToString; + }; + Module['ptrToString'] = ptrToString; @@ -2375,58 +2332,59 @@ var ASM_CONSTS = { function setValue(ptr, value, type = 'i8') { if (type.endsWith('*')) type = '*'; switch (type) { - case 'i1': HEAP8[((ptr)>>0)] = value; break; - case 'i8': HEAP8[((ptr)>>0)] = value; break; + case 'i1': HEAP8[ptr] = value; break; + case 'i8': HEAP8[ptr] = value; break; case 'i16': HEAP16[((ptr)>>1)] = value; break; case 'i32': HEAP32[((ptr)>>2)] = value; break; - case 'i64': (tempI64 = [value>>>0,(tempDouble=value,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[((ptr)>>2)] = tempI64[0],HEAP32[(((ptr)+(4))>>2)] = tempI64[1]); break; + case 'i64': abort('to do setValue(i64) use WASM_BIGINT'); case 'float': HEAPF32[((ptr)>>2)] = value; break; case 'double': HEAPF64[((ptr)>>3)] = value; break; case '*': HEAPU32[((ptr)>>2)] = value; break; - default: abort('invalid type for setValue: ' + type); + default: abort(`invalid type for setValue: ${type}`); } } - Module["setValue"] = setValue; + Module['setValue'] = setValue; - function warnOnce(text) { - if (!warnOnce.shown) warnOnce.shown = {}; + var warnOnce = (text) => { + warnOnce.shown ||= {}; if (!warnOnce.shown[text]) { warnOnce.shown[text] = 1; if (ENVIRONMENT_IS_NODE) text = 'warning: ' + text; err(text); } - } - Module["warnOnce"] = warnOnce; + }; + Module['warnOnce'] = warnOnce; - function ___assert_fail(condition, filename, line, func) { - abort('Assertion failed: ' + UTF8ToString(condition) + ', at: ' + [filename ? UTF8ToString(filename) : 'unknown filename', line, func ? UTF8ToString(func) : 'unknown function']); - } - Module["___assert_fail"] = ___assert_fail; + var ___assert_fail = (condition, filename, line, func) => { + abort(`Assertion failed: ${UTF8ToString(condition)}, at: ` + [filename ? UTF8ToString(filename) : 'unknown filename', line, func ? UTF8ToString(func) : 'unknown function']); + }; + Module['___assert_fail'] = ___assert_fail; ___assert_fail.sig = 'vppip'; - function ___call_sighandler(fp, sig) { - getWasmTableEntry(fp)(sig); - } - Module["___call_sighandler"] = ___call_sighandler; + var ___call_sighandler = (fp, sig) => getWasmTableEntry(fp)(sig); + Module['___call_sighandler'] = ___call_sighandler; ___call_sighandler.sig = 'vpi'; var ___memory_base = new WebAssembly.Global({'value': 'i32', 'mutable': false}, 1024); - Module["___memory_base"] = ___memory_base; + Module['___memory_base'] = ___memory_base; - var ___stack_high = 491744; - Module["___stack_high"] = ___stack_high; + var ___stack_high = 492464; + Module['___stack_high'] = ___stack_high; - var ___stack_low = 426208; - Module["___stack_low"] = ___stack_low; + var ___stack_low = 426928; + Module['___stack_low'] = ___stack_low; - var ___stack_pointer = new WebAssembly.Global({'value': 'i32', 'mutable': true}, 491744); - Module["___stack_pointer"] = ___stack_pointer; + var ___stack_pointer = new WebAssembly.Global({'value': 'i32', 'mutable': true}, 492464); + Module['___stack_pointer'] = ___stack_pointer; - var PATH = {isAbs:(path) => path.charAt(0) === '/',splitPath:(filename) => { + var PATH = { + isAbs:(path) => path.charAt(0) === '/', + splitPath:(filename) => { var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; return splitPathRe.exec(filename).slice(1); - },normalizeArray:(parts, allowAboveRoot) => { + }, + normalizeArray:(parts, allowAboveRoot) => { // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = parts.length - 1; i >= 0; i--) { @@ -2448,7 +2406,8 @@ var ASM_CONSTS = { } } return parts; - },normalize:(path) => { + }, + normalize:(path) => { var isAbsolute = PATH.isAbs(path), trailingSlash = path.substr(-1) === '/'; // Normalize the path @@ -2460,7 +2419,8 @@ var ASM_CONSTS = { path += '/'; } return (isAbsolute ? '/' : '') + path; - },dirname:(path) => { + }, + dirname:(path) => { var result = PATH.splitPath(path), root = result[0], dir = result[1]; @@ -2473,7 +2433,8 @@ var ASM_CONSTS = { dir = dir.substr(0, dir.length - 1); } return root + dir; - },basename:(path) => { + }, + basename:(path) => { // EMSCRIPTEN return '/'' for '/', not an empty string if (path === '/') return '/'; path = PATH.normalize(path); @@ -2481,42 +2442,55 @@ var ASM_CONSTS = { var lastSlash = path.lastIndexOf('/'); if (lastSlash === -1) return path; return path.substr(lastSlash+1); - },join:function() { - var paths = Array.prototype.slice.call(arguments); - return PATH.normalize(paths.join('/')); - },join2:(l, r) => { - return PATH.normalize(l + '/' + r); - }}; - Module["PATH"] = PATH; - - function getRandomDevice() { + }, + join:(...paths) => PATH.normalize(paths.join('/')), + join2:(l, r) => PATH.normalize(l + '/' + r), + }; + Module['PATH'] = PATH; + + var initRandomFill = () => { if (typeof crypto == 'object' && typeof crypto['getRandomValues'] == 'function') { // for modern web browsers - var randomBuffer = new Uint8Array(1); - return () => { crypto.getRandomValues(randomBuffer); return randomBuffer[0]; }; + return (view) => crypto.getRandomValues(view); } else if (ENVIRONMENT_IS_NODE) { // for nodejs with or without crypto support included try { var crypto_module = require('crypto'); - // nodejs has crypto support - return () => crypto_module['randomBytes'](1)[0]; + var randomFillSync = crypto_module['randomFillSync']; + if (randomFillSync) { + // nodejs with LTS crypto support + return (view) => crypto_module['randomFillSync'](view); + } + // very old nodejs with the original crypto API + var randomBytes = crypto_module['randomBytes']; + return (view) => ( + view.set(randomBytes(view.byteLength)), + // Return the original view to match modern native implementations. + view + ); } catch (e) { // nodejs doesn't have crypto support } } // we couldn't find a proper implementation, as Math.random() is not suitable for /dev/random, see emscripten-core/emscripten/pull/7096 - return () => abort("no cryptographic support found for randomDevice. consider polyfilling it if you want to use something insecure like Math.random(), e.g. put this in a --pre-js: var crypto = { getRandomValues: function(array) { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };"); - } - Module["getRandomDevice"] = getRandomDevice; + abort('no cryptographic support found for randomDevice. consider polyfilling it if you want to use something insecure like Math.random(), e.g. put this in a --pre-js: var crypto = { getRandomValues: (array) => { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };'); + }; + Module['initRandomFill'] = initRandomFill; + var randomFill = (view) => { + // Lazily init on the first invocation. + return (randomFill = initRandomFill())(view); + }; + Module['randomFill'] = randomFill; - var PATH_FS = {resolve:function() { + var PATH_FS = { + resolve:(...args) => { var resolvedPath = '', resolvedAbsolute = false; - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) ? arguments[i] : FS.cwd(); + for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? args[i] : FS.cwd(); // Skip empty and invalid entries if (typeof path != 'string') { throw new TypeError('Arguments to path.resolve must be strings'); @@ -2530,7 +2504,8 @@ var ASM_CONSTS = { // handle relative paths to be safe (might happen when process.cwd() fails) resolvedPath = PATH.normalizeArray(resolvedPath.split('/').filter((p) => !!p), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; - },relative:(from, to) => { + }, + relative:(from, to) => { from = PATH_FS.resolve(from).substr(1); to = PATH_FS.resolve(to).substr(1); function trim(arr) { @@ -2561,10 +2536,85 @@ var ASM_CONSTS = { } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); - }}; - Module["PATH_FS"] = PATH_FS; + }, + }; + Module['PATH_FS'] = PATH_FS; + + + + var FS_stdin_getChar_buffer = []; + Module['FS_stdin_getChar_buffer'] = FS_stdin_getChar_buffer; + + var lengthBytesUTF8 = (str) => { + var len = 0; + for (var i = 0; i < str.length; ++i) { + // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code + // unit, not a Unicode code point of the character! So decode + // UTF16->UTF32->UTF8. + // See http://unicode.org/faq/utf_bom.html#utf16-3 + var c = str.charCodeAt(i); // possibly a lead surrogate + if (c <= 0x7F) { + len++; + } else if (c <= 0x7FF) { + len += 2; + } else if (c >= 0xD800 && c <= 0xDFFF) { + len += 4; ++i; + } else { + len += 3; + } + } + return len; + }; + Module['lengthBytesUTF8'] = lengthBytesUTF8; + var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => { + assert(typeof str === 'string', `stringToUTF8Array expects a string (got ${typeof str})`); + // Parameter maxBytesToWrite is not optional. Negative values, 0, null, + // undefined and false each don't write out any bytes. + if (!(maxBytesToWrite > 0)) + return 0; + var startIdx = outIdx; + var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator. + for (var i = 0; i < str.length; ++i) { + // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code + // unit, not a Unicode code point of the character! So decode + // UTF16->UTF32->UTF8. + // See http://unicode.org/faq/utf_bom.html#utf16-3 + // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description + // and https://www.ietf.org/rfc/rfc2279.txt + // and https://tools.ietf.org/html/rfc3629 + var u = str.charCodeAt(i); // possibly a lead surrogate + if (u >= 0xD800 && u <= 0xDFFF) { + var u1 = str.charCodeAt(++i); + u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF); + } + if (u <= 0x7F) { + if (outIdx >= endIdx) break; + heap[outIdx++] = u; + } else if (u <= 0x7FF) { + if (outIdx + 1 >= endIdx) break; + heap[outIdx++] = 0xC0 | (u >> 6); + heap[outIdx++] = 0x80 | (u & 63); + } else if (u <= 0xFFFF) { + if (outIdx + 2 >= endIdx) break; + heap[outIdx++] = 0xE0 | (u >> 12); + heap[outIdx++] = 0x80 | ((u >> 6) & 63); + heap[outIdx++] = 0x80 | (u & 63); + } else { + if (outIdx + 3 >= endIdx) break; + if (u > 0x10FFFF) warnOnce('Invalid Unicode code point ' + ptrToString(u) + ' encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF).'); + heap[outIdx++] = 0xF0 | (u >> 18); + heap[outIdx++] = 0x80 | ((u >> 12) & 63); + heap[outIdx++] = 0x80 | ((u >> 6) & 63); + heap[outIdx++] = 0x80 | (u & 63); + } + } + // Null-terminate the pointer to the buffer. + heap[outIdx] = 0; + return outIdx - startIdx; + }; + Module['stringToUTF8Array'] = stringToUTF8Array; /** @type {function(string, boolean=, number=)} */ function intArrayFromString(stringy, dontAddNull, length) { var len = length > 0 ? length : lengthBytesUTF8(stringy)+1; @@ -2573,8 +2623,65 @@ var ASM_CONSTS = { if (dontAddNull) u8array.length = numBytesWritten; return u8array; } - Module["intArrayFromString"] = intArrayFromString; - var TTY = {ttys:[],init:function () { + Module['intArrayFromString'] = intArrayFromString; + var FS_stdin_getChar = () => { + if (!FS_stdin_getChar_buffer.length) { + var result = null; + if (ENVIRONMENT_IS_NODE) { + // we will read data by chunks of BUFSIZE + var BUFSIZE = 256; + var buf = Buffer.alloc(BUFSIZE); + var bytesRead = 0; + + // For some reason we must suppress a closure warning here, even though + // fd definitely exists on process.stdin, and is even the proper way to + // get the fd of stdin, + // https://github.com/nodejs/help/issues/2136#issuecomment-523649904 + // This started to happen after moving this logic out of library_tty.js, + // so it is related to the surrounding code in some unclear manner. + /** @suppress {missingProperties} */ + var fd = process.stdin.fd; + + try { + bytesRead = fs.readSync(fd, buf); + } catch(e) { + // Cross-platform differences: on Windows, reading EOF throws an exception, but on other OSes, + // reading EOF returns 0. Uniformize behavior by treating the EOF exception to return 0. + if (e.toString().includes('EOF')) bytesRead = 0; + else throw e; + } + + if (bytesRead > 0) { + result = buf.slice(0, bytesRead).toString('utf-8'); + } else { + result = null; + } + } else + if (typeof window != 'undefined' && + typeof window.prompt == 'function') { + // Browser. + result = window.prompt('Input: '); // returns null on cancel + if (result !== null) { + result += '\n'; + } + } else if (typeof readline == 'function') { + // Command line. + result = readline(); + if (result !== null) { + result += '\n'; + } + } + if (!result) { + return null; + } + FS_stdin_getChar_buffer = intArrayFromString(result, true); + } + return FS_stdin_getChar_buffer.shift(); + }; + Module['FS_stdin_getChar'] = FS_stdin_getChar; + var TTY = { + ttys:[], + init() { // https://github.com/emscripten-core/emscripten/pull/1555 // if (ENVIRONMENT_IS_NODE) { // // currently, FS.init does not distinguish if process.stdin is a file or TTY @@ -2583,7 +2690,8 @@ var ASM_CONSTS = { // // with text files until FS.init can be refactored. // process.stdin.setEncoding('utf8'); // } - },shutdown:function() { + }, + shutdown() { // https://github.com/emscripten-core/emscripten/pull/1555 // if (ENVIRONMENT_IS_NODE) { // // inolen: any idea as to why node -e 'process.stdin.read()' wouldn't exit immediately (with process.stdin being a tty)? @@ -2593,22 +2701,28 @@ var ASM_CONSTS = { // // isaacs: do process.stdin.pause() and i'd think it'd probably close the pending call // process.stdin.pause(); // } - },register:function(dev, ops) { + }, + register(dev, ops) { TTY.ttys[dev] = { input: [], output: [], ops: ops }; FS.registerDevice(dev, TTY.stream_ops); - },stream_ops:{open:function(stream) { + }, + stream_ops:{ + open(stream) { var tty = TTY.ttys[stream.node.rdev]; if (!tty) { throw new FS.ErrnoError(43); } stream.tty = tty; stream.seekable = false; - },close:function(stream) { + }, + close(stream) { // flush any pending line data stream.tty.ops.fsync(stream.tty); - },fsync:function(stream) { + }, + fsync(stream) { stream.tty.ops.fsync(stream.tty); - },read:function(stream, buffer, offset, length, pos /* ignored */) { + }, + read(stream, buffer, offset, length, pos /* ignored */) { if (!stream.tty || !stream.tty.ops.get_char) { throw new FS.ErrnoError(60); } @@ -2631,7 +2745,8 @@ var ASM_CONSTS = { stream.node.timestamp = Date.now(); } return bytesRead; - },write:function(stream, buffer, offset, length, pos) { + }, + write(stream, buffer, offset, length, pos) { if (!stream.tty || !stream.tty.ops.put_char) { throw new FS.ErrnoError(60); } @@ -2646,142 +2761,133 @@ var ASM_CONSTS = { stream.node.timestamp = Date.now(); } return i; - }},default_tty_ops:{get_char:function(tty) { - if (!tty.input.length) { - var result = null; - if (ENVIRONMENT_IS_NODE) { - // we will read data by chunks of BUFSIZE - var BUFSIZE = 256; - var buf = Buffer.alloc(BUFSIZE); - var bytesRead = 0; - - try { - bytesRead = fs.readSync(process.stdin.fd, buf, 0, BUFSIZE, -1); - } catch(e) { - // Cross-platform differences: on Windows, reading EOF throws an exception, but on other OSes, - // reading EOF returns 0. Uniformize behavior by treating the EOF exception to return 0. - if (e.toString().includes('EOF')) bytesRead = 0; - else throw e; - } - - if (bytesRead > 0) { - result = buf.slice(0, bytesRead).toString('utf-8'); - } else { - result = null; - } - } else - if (typeof window != 'undefined' && - typeof window.prompt == 'function') { - // Browser. - result = window.prompt('Input: '); // returns null on cancel - if (result !== null) { - result += '\n'; - } - } else if (typeof readline == 'function') { - // Command line. - result = readline(); - if (result !== null) { - result += '\n'; - } - } - if (!result) { - return null; - } - tty.input = intArrayFromString(result, true); - } - return tty.input.shift(); - },put_char:function(tty, val) { + }, + }, + default_tty_ops:{ + get_char(tty) { + return FS_stdin_getChar(); + }, + put_char(tty, val) { if (val === null || val === 10) { out(UTF8ArrayToString(tty.output, 0)); tty.output = []; } else { if (val != 0) tty.output.push(val); // val == 0 would cut text output off in the middle. } - },fsync:function(tty) { + }, + fsync(tty) { if (tty.output && tty.output.length > 0) { out(UTF8ArrayToString(tty.output, 0)); tty.output = []; } - }},default_tty1_ops:{put_char:function(tty, val) { + }, + ioctl_tcgets(tty) { + // typical setting + return { + c_iflag: 25856, + c_oflag: 5, + c_cflag: 191, + c_lflag: 35387, + c_cc: [ + 0x03, 0x1c, 0x7f, 0x15, 0x04, 0x00, 0x01, 0x00, 0x11, 0x13, 0x1a, 0x00, + 0x12, 0x0f, 0x17, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ] + }; + }, + ioctl_tcsets(tty, optional_actions, data) { + // currently just ignore + return 0; + }, + ioctl_tiocgwinsz(tty) { + return [24, 80]; + }, + }, + default_tty1_ops:{ + put_char(tty, val) { if (val === null || val === 10) { err(UTF8ArrayToString(tty.output, 0)); tty.output = []; } else { if (val != 0) tty.output.push(val); } - },fsync:function(tty) { + }, + fsync(tty) { if (tty.output && tty.output.length > 0) { err(UTF8ArrayToString(tty.output, 0)); tty.output = []; } - }}}; - Module["TTY"] = TTY; + }, + }, + }; + Module['TTY'] = TTY; - function mmapAlloc(size) { + var mmapAlloc = (size) => { size = alignMemory(size, 65536); var ptr = _emscripten_builtin_memalign(65536, size); if (!ptr) return 0; return zeroMemory(ptr, size); - } - Module["mmapAlloc"] = mmapAlloc; - var MEMFS = {ops_table:null,mount:function(mount) { + }; + Module['mmapAlloc'] = mmapAlloc; + var MEMFS = { + ops_table:null, + mount(mount) { return MEMFS.createNode(null, '/', 16384 | 511 /* 0777 */, 0); - },createNode:function(parent, name, mode, dev) { + }, + createNode(parent, name, mode, dev) { if (FS.isBlkdev(mode) || FS.isFIFO(mode)) { // no supported throw new FS.ErrnoError(63); } - if (!MEMFS.ops_table) { - MEMFS.ops_table = { - dir: { - node: { - getattr: MEMFS.node_ops.getattr, - setattr: MEMFS.node_ops.setattr, - lookup: MEMFS.node_ops.lookup, - mknod: MEMFS.node_ops.mknod, - rename: MEMFS.node_ops.rename, - unlink: MEMFS.node_ops.unlink, - rmdir: MEMFS.node_ops.rmdir, - readdir: MEMFS.node_ops.readdir, - symlink: MEMFS.node_ops.symlink - }, - stream: { - llseek: MEMFS.stream_ops.llseek - } - }, - file: { - node: { - getattr: MEMFS.node_ops.getattr, - setattr: MEMFS.node_ops.setattr - }, - stream: { - llseek: MEMFS.stream_ops.llseek, - read: MEMFS.stream_ops.read, - write: MEMFS.stream_ops.write, - allocate: MEMFS.stream_ops.allocate, - mmap: MEMFS.stream_ops.mmap, - msync: MEMFS.stream_ops.msync - } + MEMFS.ops_table ||= { + dir: { + node: { + getattr: MEMFS.node_ops.getattr, + setattr: MEMFS.node_ops.setattr, + lookup: MEMFS.node_ops.lookup, + mknod: MEMFS.node_ops.mknod, + rename: MEMFS.node_ops.rename, + unlink: MEMFS.node_ops.unlink, + rmdir: MEMFS.node_ops.rmdir, + readdir: MEMFS.node_ops.readdir, + symlink: MEMFS.node_ops.symlink }, - link: { - node: { - getattr: MEMFS.node_ops.getattr, - setattr: MEMFS.node_ops.setattr, - readlink: MEMFS.node_ops.readlink - }, - stream: {} + stream: { + llseek: MEMFS.stream_ops.llseek + } + }, + file: { + node: { + getattr: MEMFS.node_ops.getattr, + setattr: MEMFS.node_ops.setattr }, - chrdev: { - node: { - getattr: MEMFS.node_ops.getattr, - setattr: MEMFS.node_ops.setattr - }, - stream: FS.chrdev_stream_ops + stream: { + llseek: MEMFS.stream_ops.llseek, + read: MEMFS.stream_ops.read, + write: MEMFS.stream_ops.write, + allocate: MEMFS.stream_ops.allocate, + mmap: MEMFS.stream_ops.mmap, + msync: MEMFS.stream_ops.msync } - }; - } + }, + link: { + node: { + getattr: MEMFS.node_ops.getattr, + setattr: MEMFS.node_ops.setattr, + readlink: MEMFS.node_ops.readlink + }, + stream: {} + }, + chrdev: { + node: { + getattr: MEMFS.node_ops.getattr, + setattr: MEMFS.node_ops.setattr + }, + stream: FS.chrdev_stream_ops + } + }; var node = FS.createNode(parent, name, mode, dev); if (FS.isDir(node.mode)) { node.node_ops = MEMFS.ops_table.dir.node; @@ -2809,11 +2915,13 @@ var ASM_CONSTS = { parent.timestamp = node.timestamp; } return node; - },getFileDataAsTypedArray:function(node) { + }, + getFileDataAsTypedArray(node) { if (!node.contents) return new Uint8Array(0); if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes); // Make sure to not return excess unused bytes. return new Uint8Array(node.contents); - },expandFileStorage:function(node, newCapacity) { + }, + expandFileStorage(node, newCapacity) { var prevCapacity = node.contents ? node.contents.length : 0; if (prevCapacity >= newCapacity) return; // No need to expand, the storage was already large enough. // Don't expand strictly to the given requested limit if it's only a very small increase, but instead geometrically grow capacity. @@ -2825,7 +2933,8 @@ var ASM_CONSTS = { var oldContents = node.contents; node.contents = new Uint8Array(newCapacity); // Allocate new storage. if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0); // Copy old data over to the new storage. - },resizeFileStorage:function(node, newSize) { + }, + resizeFileStorage(node, newSize) { if (node.usedBytes == newSize) return; if (newSize == 0) { node.contents = null; // Fully decommit when requesting a resize to zero. @@ -2838,7 +2947,9 @@ var ASM_CONSTS = { } node.usedBytes = newSize; } - },node_ops:{getattr:function(node) { + }, + node_ops:{ + getattr(node) { var attr = {}; // device numbers reuse inode numbers. attr.dev = FS.isChrdev(node.mode) ? node.id : 1; @@ -2865,7 +2976,8 @@ var ASM_CONSTS = { attr.blksize = 4096; attr.blocks = Math.ceil(attr.size / attr.blksize); return attr; - },setattr:function(node, attr) { + }, + setattr(node, attr) { if (attr.mode !== undefined) { node.mode = attr.mode; } @@ -2875,11 +2987,14 @@ var ASM_CONSTS = { if (attr.size !== undefined) { MEMFS.resizeFileStorage(node, attr.size); } - },lookup:function(parent, name) { + }, + lookup(parent, name) { throw FS.genericErrors[44]; - },mknod:function(parent, name, mode, dev) { + }, + mknod(parent, name, mode, dev) { return MEMFS.createNode(parent, name, mode, dev); - },rename:function(old_node, new_dir, new_name) { + }, + rename(old_node, new_dir, new_name) { // if we're overwriting a directory at new_name, make sure it's empty. if (FS.isDir(old_node.mode)) { var new_node; @@ -2900,35 +3015,40 @@ var ASM_CONSTS = { new_dir.contents[new_name] = old_node; new_dir.timestamp = old_node.parent.timestamp; old_node.parent = new_dir; - },unlink:function(parent, name) { + }, + unlink(parent, name) { delete parent.contents[name]; parent.timestamp = Date.now(); - },rmdir:function(parent, name) { + }, + rmdir(parent, name) { var node = FS.lookupNode(parent, name); for (var i in node.contents) { throw new FS.ErrnoError(55); } delete parent.contents[name]; parent.timestamp = Date.now(); - },readdir:function(node) { + }, + readdir(node) { var entries = ['.', '..']; - for (var key in node.contents) { - if (!node.contents.hasOwnProperty(key)) { - continue; - } + for (var key of Object.keys(node.contents)) { entries.push(key); } return entries; - },symlink:function(parent, newname, oldpath) { + }, + symlink(parent, newname, oldpath) { var node = MEMFS.createNode(parent, newname, 511 /* 0777 */ | 40960, 0); node.link = oldpath; return node; - },readlink:function(node) { + }, + readlink(node) { if (!FS.isLink(node.mode)) { throw new FS.ErrnoError(28); } return node.link; - }},stream_ops:{read:function(stream, buffer, offset, length, position) { + }, + }, + stream_ops:{ + read(stream, buffer, offset, length, position) { var contents = stream.node.contents; if (position >= stream.node.usedBytes) return 0; var size = Math.min(stream.node.usedBytes - position, length); @@ -2939,7 +3059,8 @@ var ASM_CONSTS = { for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i]; } return size; - },write:function(stream, buffer, offset, length, position, canOwn) { + }, + write(stream, buffer, offset, length, position, canOwn) { // The data buffer should be a typed array view assert(!(buffer instanceof ArrayBuffer)); @@ -2975,7 +3096,8 @@ var ASM_CONSTS = { } node.usedBytes = Math.max(node.usedBytes, position + length); return length; - },llseek:function(stream, offset, whence) { + }, + llseek(stream, offset, whence) { var position = offset; if (whence === 1) { position += stream.position; @@ -2988,10 +3110,12 @@ var ASM_CONSTS = { throw new FS.ErrnoError(28); } return position; - },allocate:function(stream, offset, length) { + }, + allocate(stream, offset, length) { MEMFS.expandFileStorage(stream.node, offset + length); stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length); - },mmap:function(stream, length, position, prot, flags) { + }, + mmap(stream, length, position, prot, flags) { if (!FS.isFile(stream.node.mode)) { throw new FS.ErrnoError(43); } @@ -3020,141 +3144,542 @@ var ASM_CONSTS = { } HEAP8.set(contents, ptr); } - return { ptr: ptr, allocated: allocated }; - },msync:function(stream, buffer, offset, length, mmapFlags) { + return { ptr, allocated }; + }, + msync(stream, buffer, offset, length, mmapFlags) { MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false); // should we check if bytesWritten and length are the same? return 0; - }}}; - Module["MEMFS"] = MEMFS; - - /** @param {boolean=} noRunDep */ - function asyncLoad(url, onload, onerror, noRunDep) { - var dep = !noRunDep ? getUniqueRunDependency('al ' + url) : ''; - readAsync(url, (arrayBuffer) => { - assert(arrayBuffer, 'Loading data file "' + url + '" failed (no arrayBuffer).'); - onload(new Uint8Array(arrayBuffer)); - if (dep) removeRunDependency(dep); - }, (event) => { - if (onerror) { - onerror(); - } else { - throw 'Loading data file "' + url + '" failed.'; - } - }); - if (dep) addRunDependency(dep); - } - Module["asyncLoad"] = asyncLoad; - - - var ERRNO_MESSAGES = {0:"Success",1:"Arg list too long",2:"Permission denied",3:"Address already in use",4:"Address not available",5:"Address family not supported by protocol family",6:"No more processes",7:"Socket already connected",8:"Bad file number",9:"Trying to read unreadable message",10:"Mount device busy",11:"Operation canceled",12:"No children",13:"Connection aborted",14:"Connection refused",15:"Connection reset by peer",16:"File locking deadlock error",17:"Destination address required",18:"Math arg out of domain of func",19:"Quota exceeded",20:"File exists",21:"Bad address",22:"File too large",23:"Host is unreachable",24:"Identifier removed",25:"Illegal byte sequence",26:"Connection already in progress",27:"Interrupted system call",28:"Invalid argument",29:"I/O error",30:"Socket is already connected",31:"Is a directory",32:"Too many symbolic links",33:"Too many open files",34:"Too many links",35:"Message too long",36:"Multihop attempted",37:"File or path name too long",38:"Network interface is not configured",39:"Connection reset by network",40:"Network is unreachable",41:"Too many open files in system",42:"No buffer space available",43:"No such device",44:"No such file or directory",45:"Exec format error",46:"No record locks available",47:"The link has been severed",48:"Not enough core",49:"No message of desired type",50:"Protocol not available",51:"No space left on device",52:"Function not implemented",53:"Socket is not connected",54:"Not a directory",55:"Directory not empty",56:"State not recoverable",57:"Socket operation on non-socket",59:"Not a typewriter",60:"No such device or address",61:"Value too large for defined data type",62:"Previous owner died",63:"Not super-user",64:"Broken pipe",65:"Protocol error",66:"Unknown protocol",67:"Protocol wrong type for socket",68:"Math result not representable",69:"Read only file system",70:"Illegal seek",71:"No such process",72:"Stale file handle",73:"Connection timed out",74:"Text file busy",75:"Cross-device link",100:"Device not a stream",101:"Bad font file fmt",102:"Invalid slot",103:"Invalid request code",104:"No anode",105:"Block device required",106:"Channel number out of range",107:"Level 3 halted",108:"Level 3 reset",109:"Link number out of range",110:"Protocol driver not attached",111:"No CSI structure available",112:"Level 2 halted",113:"Invalid exchange",114:"Invalid request descriptor",115:"Exchange full",116:"No data (for no delay io)",117:"Timer expired",118:"Out of streams resources",119:"Machine is not on the network",120:"Package not installed",121:"The object is remote",122:"Advertise error",123:"Srmount error",124:"Communication error on send",125:"Cross mount point (not really error)",126:"Given log. name not unique",127:"f.d. invalid for this operation",128:"Remote address changed",129:"Can access a needed shared lib",130:"Accessing a corrupted shared lib",131:".lib section in a.out corrupted",132:"Attempting to link in too many libs",133:"Attempting to exec a shared library",135:"Streams pipe error",136:"Too many users",137:"Socket type not supported",138:"Not supported",139:"Protocol family not supported",140:"Can't send after socket shutdown",141:"Too many references",142:"Host is down",148:"No medium (in tape drive)",156:"Level 2 not synchronized"}; - Module["ERRNO_MESSAGES"] = ERRNO_MESSAGES; + }, + }, + }; + Module['MEMFS'] = MEMFS; - var ERRNO_CODES = {}; - Module["ERRNO_CODES"] = ERRNO_CODES; - function demangle(func) { - warnOnce('warning: build with -sDEMANGLE_SUPPORT to link in libcxxabi demangling'); - return func; - } - Module["demangle"] = demangle; - function demangleAll(text) { - var regex = - /\b_Z[\w\d_]+/g; - return text.replace(regex, - function(x) { - var y = demangle(x); - return x === y ? x : (y + ' [' + x + ']'); - }); - } - Module["demangleAll"] = demangleAll; - var FS = {root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(path, opts = {}) => { - path = PATH_FS.resolve(path); - if (!path) return { path: '', node: null }; + var FS_createDataFile = (parent, name, fileData, canRead, canWrite, canOwn) => { + FS.createDataFile(parent, name, fileData, canRead, canWrite, canOwn); + }; + Module['FS_createDataFile'] = FS_createDataFile; - var defaults = { - follow_mount: true, - recurse_count: 0 - }; - opts = Object.assign(defaults, opts) + var FS_handledByPreloadPlugin = (byteArray, fullname, finish, onerror) => { + // Ensure plugins are ready. + if (typeof Browser != 'undefined') Browser.init(); - if (opts.recurse_count > 8) { // max recursive lookup of 8 - throw new FS.ErrnoError(32); + var handled = false; + preloadPlugins.forEach((plugin) => { + if (handled) return; + if (plugin['canHandle'](fullname)) { + plugin['handle'](byteArray, fullname, finish, onerror); + handled = true; } - - // split the absolute path - var parts = path.split('/').filter((p) => !!p); - - // start at the root - var current = FS.root; - var current_path = '/'; - - for (var i = 0; i < parts.length; i++) { - var islast = (i === parts.length-1); - if (islast && opts.parent) { - // stop resolving - break; - } - - current = FS.lookupNode(current, parts[i]); - current_path = PATH.join2(current_path, parts[i]); - - // jump to the mount's root node if this is a mountpoint - if (FS.isMountpoint(current)) { - if (!islast || (islast && opts.follow_mount)) { - current = current.mounted.root; - } - } - - // by default, lookupPath will not follow a symlink if it is the final path component. - // setting opts.follow = true will override this behavior. - if (!islast || opts.follow) { - var count = 0; - while (FS.isLink(current.mode)) { - var link = FS.readlink(current_path); - current_path = PATH_FS.resolve(PATH.dirname(current_path), link); - - var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count + 1 }); - current = lookup.node; - - if (count++ > 40) { // limit max consecutive symlinks to 40 (SYMLOOP_MAX). - throw new FS.ErrnoError(32); - } - } - } + }); + return handled; + }; + Module['FS_handledByPreloadPlugin'] = FS_handledByPreloadPlugin; + var FS_createPreloadedFile = (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => { + // TODO we should allow people to just pass in a complete filename instead + // of parent and name being that we just join them anyways + var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent; + var dep = getUniqueRunDependency(`cp ${fullname}`); // might have several active requests for the same fullname + function processData(byteArray) { + function finish(byteArray) { + preFinish?.(); + if (!dontCreateFile) { + FS_createDataFile(parent, name, byteArray, canRead, canWrite, canOwn); + } + onload?.(); + removeRunDependency(dep); + } + if (FS_handledByPreloadPlugin(byteArray, fullname, finish, () => { + onerror?.(); + removeRunDependency(dep); + })) { + return; } + finish(byteArray); + } + addRunDependency(dep); + if (typeof url == 'string') { + asyncLoad(url, processData, onerror); + } else { + processData(url); + } + }; + Module['FS_createPreloadedFile'] = FS_createPreloadedFile; + + var FS_modeStringToFlags = (str) => { + var flagModes = { + 'r': 0, + 'r+': 2, + 'w': 512 | 64 | 1, + 'w+': 512 | 64 | 2, + 'a': 1024 | 64 | 1, + 'a+': 1024 | 64 | 2, + }; + var flags = flagModes[str]; + if (typeof flags == 'undefined') { + throw new Error(`Unknown file open mode: ${str}`); + } + return flags; + }; + Module['FS_modeStringToFlags'] = FS_modeStringToFlags; - return { path: current_path, node: current }; - },getPath:(node) => { - var path; - while (true) { - if (FS.isRoot(node)) { - var mount = node.mount.mountpoint; - if (!path) return mount; - return mount[mount.length-1] !== '/' ? mount + '/' + path : mount + path; - } - path = path ? node.name + '/' + path : node.name; - node = node.parent; - } - },hashName:(parentid, name) => { - var hash = 0; + var FS_getMode = (canRead, canWrite) => { + var mode = 0; + if (canRead) mode |= 292 | 73; + if (canWrite) mode |= 146; + return mode; + }; + Module['FS_getMode'] = FS_getMode; + + + + + var ERRNO_MESSAGES = { + 0:"Success", + 1:"Arg list too long", + 2:"Permission denied", + 3:"Address already in use", + 4:"Address not available", + 5:"Address family not supported by protocol family", + 6:"No more processes", + 7:"Socket already connected", + 8:"Bad file number", + 9:"Trying to read unreadable message", + 10:"Mount device busy", + 11:"Operation canceled", + 12:"No children", + 13:"Connection aborted", + 14:"Connection refused", + 15:"Connection reset by peer", + 16:"File locking deadlock error", + 17:"Destination address required", + 18:"Math arg out of domain of func", + 19:"Quota exceeded", + 20:"File exists", + 21:"Bad address", + 22:"File too large", + 23:"Host is unreachable", + 24:"Identifier removed", + 25:"Illegal byte sequence", + 26:"Connection already in progress", + 27:"Interrupted system call", + 28:"Invalid argument", + 29:"I/O error", + 30:"Socket is already connected", + 31:"Is a directory", + 32:"Too many symbolic links", + 33:"Too many open files", + 34:"Too many links", + 35:"Message too long", + 36:"Multihop attempted", + 37:"File or path name too long", + 38:"Network interface is not configured", + 39:"Connection reset by network", + 40:"Network is unreachable", + 41:"Too many open files in system", + 42:"No buffer space available", + 43:"No such device", + 44:"No such file or directory", + 45:"Exec format error", + 46:"No record locks available", + 47:"The link has been severed", + 48:"Not enough core", + 49:"No message of desired type", + 50:"Protocol not available", + 51:"No space left on device", + 52:"Function not implemented", + 53:"Socket is not connected", + 54:"Not a directory", + 55:"Directory not empty", + 56:"State not recoverable", + 57:"Socket operation on non-socket", + 59:"Not a typewriter", + 60:"No such device or address", + 61:"Value too large for defined data type", + 62:"Previous owner died", + 63:"Not super-user", + 64:"Broken pipe", + 65:"Protocol error", + 66:"Unknown protocol", + 67:"Protocol wrong type for socket", + 68:"Math result not representable", + 69:"Read only file system", + 70:"Illegal seek", + 71:"No such process", + 72:"Stale file handle", + 73:"Connection timed out", + 74:"Text file busy", + 75:"Cross-device link", + 100:"Device not a stream", + 101:"Bad font file fmt", + 102:"Invalid slot", + 103:"Invalid request code", + 104:"No anode", + 105:"Block device required", + 106:"Channel number out of range", + 107:"Level 3 halted", + 108:"Level 3 reset", + 109:"Link number out of range", + 110:"Protocol driver not attached", + 111:"No CSI structure available", + 112:"Level 2 halted", + 113:"Invalid exchange", + 114:"Invalid request descriptor", + 115:"Exchange full", + 116:"No data (for no delay io)", + 117:"Timer expired", + 118:"Out of streams resources", + 119:"Machine is not on the network", + 120:"Package not installed", + 121:"The object is remote", + 122:"Advertise error", + 123:"Srmount error", + 124:"Communication error on send", + 125:"Cross mount point (not really error)", + 126:"Given log. name not unique", + 127:"f.d. invalid for this operation", + 128:"Remote address changed", + 129:"Can access a needed shared lib", + 130:"Accessing a corrupted shared lib", + 131:".lib section in a.out corrupted", + 132:"Attempting to link in too many libs", + 133:"Attempting to exec a shared library", + 135:"Streams pipe error", + 136:"Too many users", + 137:"Socket type not supported", + 138:"Not supported", + 139:"Protocol family not supported", + 140:"Can't send after socket shutdown", + 141:"Too many references", + 142:"Host is down", + 148:"No medium (in tape drive)", + 156:"Level 2 not synchronized", + }; + Module['ERRNO_MESSAGES'] = ERRNO_MESSAGES; - for (var i = 0; i < name.length; i++) { - hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0; - } - return ((parentid + hash) >>> 0) % FS.nameTable.length; - },hashAddNode:(node) => { - var hash = FS.hashName(node.parent.id, node.name); - node.name_next = FS.nameTable[hash]; - FS.nameTable[hash] = node; - },hashRemoveNode:(node) => { - var hash = FS.hashName(node.parent.id, node.name); - if (FS.nameTable[hash] === node) { - FS.nameTable[hash] = node.name_next; - } else { - var current = FS.nameTable[hash]; - while (current) { + var ERRNO_CODES = { + 'EPERM': 63, + 'ENOENT': 44, + 'ESRCH': 71, + 'EINTR': 27, + 'EIO': 29, + 'ENXIO': 60, + 'E2BIG': 1, + 'ENOEXEC': 45, + 'EBADF': 8, + 'ECHILD': 12, + 'EAGAIN': 6, + 'EWOULDBLOCK': 6, + 'ENOMEM': 48, + 'EACCES': 2, + 'EFAULT': 21, + 'ENOTBLK': 105, + 'EBUSY': 10, + 'EEXIST': 20, + 'EXDEV': 75, + 'ENODEV': 43, + 'ENOTDIR': 54, + 'EISDIR': 31, + 'EINVAL': 28, + 'ENFILE': 41, + 'EMFILE': 33, + 'ENOTTY': 59, + 'ETXTBSY': 74, + 'EFBIG': 22, + 'ENOSPC': 51, + 'ESPIPE': 70, + 'EROFS': 69, + 'EMLINK': 34, + 'EPIPE': 64, + 'EDOM': 18, + 'ERANGE': 68, + 'ENOMSG': 49, + 'EIDRM': 24, + 'ECHRNG': 106, + 'EL2NSYNC': 156, + 'EL3HLT': 107, + 'EL3RST': 108, + 'ELNRNG': 109, + 'EUNATCH': 110, + 'ENOCSI': 111, + 'EL2HLT': 112, + 'EDEADLK': 16, + 'ENOLCK': 46, + 'EBADE': 113, + 'EBADR': 114, + 'EXFULL': 115, + 'ENOANO': 104, + 'EBADRQC': 103, + 'EBADSLT': 102, + 'EDEADLOCK': 16, + 'EBFONT': 101, + 'ENOSTR': 100, + 'ENODATA': 116, + 'ETIME': 117, + 'ENOSR': 118, + 'ENONET': 119, + 'ENOPKG': 120, + 'EREMOTE': 121, + 'ENOLINK': 47, + 'EADV': 122, + 'ESRMNT': 123, + 'ECOMM': 124, + 'EPROTO': 65, + 'EMULTIHOP': 36, + 'EDOTDOT': 125, + 'EBADMSG': 9, + 'ENOTUNIQ': 126, + 'EBADFD': 127, + 'EREMCHG': 128, + 'ELIBACC': 129, + 'ELIBBAD': 130, + 'ELIBSCN': 131, + 'ELIBMAX': 132, + 'ELIBEXEC': 133, + 'ENOSYS': 52, + 'ENOTEMPTY': 55, + 'ENAMETOOLONG': 37, + 'ELOOP': 32, + 'EOPNOTSUPP': 138, + 'EPFNOSUPPORT': 139, + 'ECONNRESET': 15, + 'ENOBUFS': 42, + 'EAFNOSUPPORT': 5, + 'EPROTOTYPE': 67, + 'ENOTSOCK': 57, + 'ENOPROTOOPT': 50, + 'ESHUTDOWN': 140, + 'ECONNREFUSED': 14, + 'EADDRINUSE': 3, + 'ECONNABORTED': 13, + 'ENETUNREACH': 40, + 'ENETDOWN': 38, + 'ETIMEDOUT': 73, + 'EHOSTDOWN': 142, + 'EHOSTUNREACH': 23, + 'EINPROGRESS': 26, + 'EALREADY': 7, + 'EDESTADDRREQ': 17, + 'EMSGSIZE': 35, + 'EPROTONOSUPPORT': 66, + 'ESOCKTNOSUPPORT': 137, + 'EADDRNOTAVAIL': 4, + 'ENETRESET': 39, + 'EISCONN': 30, + 'ENOTCONN': 53, + 'ETOOMANYREFS': 141, + 'EUSERS': 136, + 'EDQUOT': 19, + 'ESTALE': 72, + 'ENOTSUP': 138, + 'ENOMEDIUM': 148, + 'EILSEQ': 25, + 'EOVERFLOW': 61, + 'ECANCELED': 11, + 'ENOTRECOVERABLE': 56, + 'EOWNERDEAD': 62, + 'ESTRPIPE': 135, + }; + Module['ERRNO_CODES'] = ERRNO_CODES; + var FS = { + root:null, + mounts:[], + devices:{ + }, + streams:[], + nextInode:1, + nameTable:null, + currentPath:"/", + initialized:false, + ignorePermissions:true, + ErrnoError:class extends Error { + // We set the `name` property to be able to identify `FS.ErrnoError` + // - the `name` is a standard ECMA-262 property of error objects. Kind of good to have it anyway. + // - when using PROXYFS, an error can come from an underlying FS + // as different FS objects have their own FS.ErrnoError each, + // the test `err instanceof FS.ErrnoError` won't detect an error coming from another filesystem, causing bugs. + // we'll use the reliable test `err.name == "ErrnoError"` instead + constructor(errno) { + super(ERRNO_MESSAGES[errno]); + // TODO(sbc): Use the inline member declaration syntax once we + // support it in acorn and closure. + this.name = 'ErrnoError'; + this.errno = errno; + for (var key in ERRNO_CODES) { + if (ERRNO_CODES[key] === errno) { + this.code = key; + break; + } + } + } + }, + genericErrors:{ + }, + filesystems:null, + syncFSRequests:0, + FSStream:class { + constructor() { + // TODO(https://github.com/emscripten-core/emscripten/issues/21414): + // Use inline field declarations. + this.shared = {}; + } + get object() { + return this.node; + } + set object(val) { + this.node = val; + } + get isRead() { + return (this.flags & 2097155) !== 1; + } + get isWrite() { + return (this.flags & 2097155) !== 0; + } + get isAppend() { + return (this.flags & 1024); + } + get flags() { + return this.shared.flags; + } + set flags(val) { + this.shared.flags = val; + } + get position() { + return this.shared.position; + } + set position(val) { + this.shared.position = val; + } + }, + FSNode:class { + constructor(parent, name, mode, rdev) { + if (!parent) { + parent = this; // root node sets parent to itself + } + this.parent = parent; + this.mount = parent.mount; + this.mounted = null; + this.id = FS.nextInode++; + this.name = name; + this.mode = mode; + this.node_ops = {}; + this.stream_ops = {}; + this.rdev = rdev; + this.readMode = 292/*292*/ | 73/*73*/; + this.writeMode = 146/*146*/; + } + get read() { + return (this.mode & this.readMode) === this.readMode; + } + set read(val) { + val ? this.mode |= this.readMode : this.mode &= ~this.readMode; + } + get write() { + return (this.mode & this.writeMode) === this.writeMode; + } + set write(val) { + val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode; + } + get isFolder() { + return FS.isDir(this.mode); + } + get isDevice() { + return FS.isChrdev(this.mode); + } + }, + lookupPath(path, opts = {}) { + path = PATH_FS.resolve(path); + + if (!path) return { path: '', node: null }; + + var defaults = { + follow_mount: true, + recurse_count: 0 + }; + opts = Object.assign(defaults, opts) + + if (opts.recurse_count > 8) { // max recursive lookup of 8 + throw new FS.ErrnoError(32); + } + + // split the absolute path + var parts = path.split('/').filter((p) => !!p); + + // start at the root + var current = FS.root; + var current_path = '/'; + + for (var i = 0; i < parts.length; i++) { + var islast = (i === parts.length-1); + if (islast && opts.parent) { + // stop resolving + break; + } + + current = FS.lookupNode(current, parts[i]); + current_path = PATH.join2(current_path, parts[i]); + + // jump to the mount's root node if this is a mountpoint + if (FS.isMountpoint(current)) { + if (!islast || (islast && opts.follow_mount)) { + current = current.mounted.root; + } + } + + // by default, lookupPath will not follow a symlink if it is the final path component. + // setting opts.follow = true will override this behavior. + if (!islast || opts.follow) { + var count = 0; + while (FS.isLink(current.mode)) { + var link = FS.readlink(current_path); + current_path = PATH_FS.resolve(PATH.dirname(current_path), link); + + var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count + 1 }); + current = lookup.node; + + if (count++ > 40) { // limit max consecutive symlinks to 40 (SYMLOOP_MAX). + throw new FS.ErrnoError(32); + } + } + } + } + + return { path: current_path, node: current }; + }, + getPath(node) { + var path; + while (true) { + if (FS.isRoot(node)) { + var mount = node.mount.mountpoint; + if (!path) return mount; + return mount[mount.length-1] !== '/' ? `${mount}/${path}` : mount + path; + } + path = path ? `${node.name}/${path}` : node.name; + node = node.parent; + } + }, + hashName(parentid, name) { + var hash = 0; + + for (var i = 0; i < name.length; i++) { + hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0; + } + return ((parentid + hash) >>> 0) % FS.nameTable.length; + }, + hashAddNode(node) { + var hash = FS.hashName(node.parent.id, node.name); + node.name_next = FS.nameTable[hash]; + FS.nameTable[hash] = node; + }, + hashRemoveNode(node) { + var hash = FS.hashName(node.parent.id, node.name); + if (FS.nameTable[hash] === node) { + FS.nameTable[hash] = node.name_next; + } else { + var current = FS.nameTable[hash]; + while (current) { if (current.name_next === node) { current.name_next = node.name_next; break; @@ -3162,10 +3687,11 @@ var ASM_CONSTS = { current = current.name_next; } } - },lookupNode:(parent, name) => { + }, + lookupNode(parent, name) { var errCode = FS.mayLookup(parent); if (errCode) { - throw new FS.ErrnoError(errCode, parent); + throw new FS.ErrnoError(errCode); } var hash = FS.hashName(parent.id, name); for (var node = FS.nameTable[hash]; node; node = node.name_next) { @@ -3176,46 +3702,53 @@ var ASM_CONSTS = { } // if we failed to find it in the cache, call into the VFS return FS.lookup(parent, name); - },createNode:(parent, name, mode, rdev) => { + }, + createNode(parent, name, mode, rdev) { assert(typeof parent == 'object') var node = new FS.FSNode(parent, name, mode, rdev); FS.hashAddNode(node); return node; - },destroyNode:(node) => { + }, + destroyNode(node) { FS.hashRemoveNode(node); - },isRoot:(node) => { + }, + isRoot(node) { return node === node.parent; - },isMountpoint:(node) => { + }, + isMountpoint(node) { return !!node.mounted; - },isFile:(mode) => { + }, + isFile(mode) { return (mode & 61440) === 32768; - },isDir:(mode) => { + }, + isDir(mode) { return (mode & 61440) === 16384; - },isLink:(mode) => { + }, + isLink(mode) { return (mode & 61440) === 40960; - },isChrdev:(mode) => { + }, + isChrdev(mode) { return (mode & 61440) === 8192; - },isBlkdev:(mode) => { + }, + isBlkdev(mode) { return (mode & 61440) === 24576; - },isFIFO:(mode) => { + }, + isFIFO(mode) { return (mode & 61440) === 4096; - },isSocket:(mode) => { + }, + isSocket(mode) { return (mode & 49152) === 49152; - },flagModes:{"r":0,"r+":2,"w":577,"w+":578,"a":1089,"a+":1090},modeStringToFlags:(str) => { - var flags = FS.flagModes[str]; - if (typeof flags == 'undefined') { - throw new Error('Unknown file open mode: ' + str); - } - return flags; - },flagsToPermissionString:(flag) => { + }, + flagsToPermissionString(flag) { var perms = ['r', 'w', 'rw'][flag & 3]; if ((flag & 512)) { perms += 'w'; } return perms; - },nodePermissions:(node, perms) => { + }, + nodePermissions(node, perms) { if (FS.ignorePermissions) { return 0; } @@ -3228,19 +3761,23 @@ var ASM_CONSTS = { return 2; } return 0; - },mayLookup:(dir) => { + }, + mayLookup(dir) { + if (!FS.isDir(dir.mode)) return 54; var errCode = FS.nodePermissions(dir, 'x'); if (errCode) return errCode; if (!dir.node_ops.lookup) return 2; return 0; - },mayCreate:(dir, name) => { + }, + mayCreate(dir, name) { try { var node = FS.lookupNode(dir, name); return 20; } catch (e) { } return FS.nodePermissions(dir, 'wx'); - },mayDelete:(dir, name, isdir) => { + }, + mayDelete(dir, name, isdir) { var node; try { node = FS.lookupNode(dir, name); @@ -3264,7 +3801,8 @@ var ASM_CONSTS = { } } return 0; - },mayOpen:(node, flags) => { + }, + mayOpen(node, flags) { if (!node) { return 44; } @@ -3277,73 +3815,63 @@ var ASM_CONSTS = { } } return FS.nodePermissions(node, FS.flagsToPermissionString(flags)); - },MAX_OPEN_FDS:4096,nextfd:(fd_start = 0, fd_end = FS.MAX_OPEN_FDS) => { - for (var fd = fd_start; fd <= fd_end; fd++) { + }, + MAX_OPEN_FDS:4096, + nextfd() { + for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) { if (!FS.streams[fd]) { return fd; } } throw new FS.ErrnoError(33); - },getStream:(fd) => FS.streams[fd],createStream:(stream, fd_start, fd_end) => { - if (!FS.FSStream) { - FS.FSStream = /** @constructor */ function() { - this.shared = { }; - }; - FS.FSStream.prototype = {}; - Object.defineProperties(FS.FSStream.prototype, { - object: { - /** @this {FS.FSStream} */ - get: function() { return this.node; }, - /** @this {FS.FSStream} */ - set: function(val) { this.node = val; } - }, - isRead: { - /** @this {FS.FSStream} */ - get: function() { return (this.flags & 2097155) !== 1; } - }, - isWrite: { - /** @this {FS.FSStream} */ - get: function() { return (this.flags & 2097155) !== 0; } - }, - isAppend: { - /** @this {FS.FSStream} */ - get: function() { return (this.flags & 1024); } - }, - flags: { - /** @this {FS.FSStream} */ - get: function() { return this.shared.flags; }, - /** @this {FS.FSStream} */ - set: function(val) { this.shared.flags = val; }, - }, - position : { - /** @this {FS.FSStream} */ - get: function() { return this.shared.position; }, - /** @this {FS.FSStream} */ - set: function(val) { this.shared.position = val; }, - }, - }); + }, + getStreamChecked(fd) { + var stream = FS.getStream(fd); + if (!stream) { + throw new FS.ErrnoError(8); } + return stream; + }, + getStream:(fd) => FS.streams[fd], + createStream(stream, fd = -1) { + // clone it, so we can return an instance of FSStream stream = Object.assign(new FS.FSStream(), stream); - var fd = FS.nextfd(fd_start, fd_end); + if (fd == -1) { + fd = FS.nextfd(); + } stream.fd = fd; FS.streams[fd] = stream; return stream; - },closeStream:(fd) => { + }, + closeStream(fd) { FS.streams[fd] = null; - },chrdev_stream_ops:{open:(stream) => { + }, + dupStream(origStream, fd = -1) { + var stream = FS.createStream(origStream, fd); + stream.stream_ops?.dup?.(stream); + return stream; + }, + chrdev_stream_ops:{ + open(stream) { var device = FS.getDevice(stream.node.rdev); // override node's stream ops with the device's stream.stream_ops = device.stream_ops; // forward the open call - if (stream.stream_ops.open) { - stream.stream_ops.open(stream); - } - },llseek:() => { + stream.stream_ops.open?.(stream); + }, + llseek() { throw new FS.ErrnoError(70); - }},major:(dev) => ((dev) >> 8),minor:(dev) => ((dev) & 0xff),makedev:(ma, mi) => ((ma) << 8 | (mi)),registerDevice:(dev, ops) => { + }, + }, + major:(dev) => ((dev) >> 8), + minor:(dev) => ((dev) & 0xff), + makedev:(ma, mi) => ((ma) << 8 | (mi)), + registerDevice(dev, ops) { FS.devices[dev] = { stream_ops: ops }; - },getDevice:(dev) => FS.devices[dev],getMounts:(mount) => { + }, + getDevice:(dev) => FS.devices[dev], + getMounts(mount) { var mounts = []; var check = [mount]; @@ -3352,11 +3880,12 @@ var ASM_CONSTS = { mounts.push(m); - check.push.apply(check, m.mounts); + check.push(...m.mounts); } return mounts; - },syncfs:(populate, callback) => { + }, + syncfs(populate, callback) { if (typeof populate == 'function') { callback = populate; populate = false; @@ -3365,7 +3894,7 @@ var ASM_CONSTS = { FS.syncFSRequests++; if (FS.syncFSRequests > 1) { - err('warning: ' + FS.syncFSRequests + ' FS.syncfs operations in flight at once, probably just doing extra work'); + err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`); } var mounts = FS.getMounts(FS.root.mount); @@ -3397,7 +3926,8 @@ var ASM_CONSTS = { } mount.type.syncfs(mount, populate, done); }); - },mount:(type, opts, mountpoint) => { + }, + mount(type, opts, mountpoint) { if (typeof type == 'string') { // The filesystem was not included, and instead we have an error // message stored in the variable. @@ -3425,9 +3955,9 @@ var ASM_CONSTS = { } var mount = { - type: type, - opts: opts, - mountpoint: mountpoint, + type, + opts, + mountpoint, mounts: [] }; @@ -3449,7 +3979,8 @@ var ASM_CONSTS = { } return mountRoot; - },unmount:(mountpoint) => { + }, + unmount(mountpoint) { var lookup = FS.lookupPath(mountpoint, { follow_mount: false }); if (!FS.isMountpoint(lookup.node)) { @@ -3482,9 +4013,11 @@ var ASM_CONSTS = { var idx = node.mount.mounts.indexOf(mount); assert(idx !== -1); node.mount.mounts.splice(idx, 1); - },lookup:(parent, name) => { + }, + lookup(parent, name) { return parent.node_ops.lookup(parent, name); - },mknod:(path, mode, dev) => { + }, + mknod(path, mode, dev) { var lookup = FS.lookupPath(path, { parent: true }); var parent = lookup.node; var name = PATH.basename(path); @@ -3499,17 +4032,20 @@ var ASM_CONSTS = { throw new FS.ErrnoError(63); } return parent.node_ops.mknod(parent, name, mode, dev); - },create:(path, mode) => { + }, + create(path, mode) { mode = mode !== undefined ? mode : 438 /* 0666 */; mode &= 4095; mode |= 32768; return FS.mknod(path, mode, 0); - },mkdir:(path, mode) => { + }, + mkdir(path, mode) { mode = mode !== undefined ? mode : 511 /* 0777 */; mode &= 511 | 512; mode |= 16384; return FS.mknod(path, mode, 0); - },mkdirTree:(path, mode) => { + }, + mkdirTree(path, mode) { var dirs = path.split('/'); var d = ''; for (var i = 0; i < dirs.length; ++i) { @@ -3521,14 +4057,16 @@ var ASM_CONSTS = { if (e.errno != 20) throw e; } } - },mkdev:(path, mode, dev) => { + }, + mkdev(path, mode, dev) { if (typeof dev == 'undefined') { dev = mode; mode = 438 /* 0666 */; } mode |= 8192; return FS.mknod(path, mode, dev); - },symlink:(oldpath, newpath) => { + }, + symlink(oldpath, newpath) { if (!PATH_FS.resolve(oldpath)) { throw new FS.ErrnoError(44); } @@ -3546,7 +4084,8 @@ var ASM_CONSTS = { throw new FS.ErrnoError(63); } return parent.node_ops.symlink(parent, newname, oldpath); - },rename:(old_path, new_path) => { + }, + rename(old_path, new_path) { var old_dirname = PATH.dirname(old_path); var new_dirname = PATH.dirname(new_path); var old_name = PATH.basename(old_path); @@ -3554,7 +4093,7 @@ var ASM_CONSTS = { // parents must exist var lookup, old_dir, new_dir; - // let the errors from non existant directories percolate up + // let the errors from non existent directories percolate up lookup = FS.lookupPath(old_path, { parent: true }); old_dir = lookup.node; lookup = FS.lookupPath(new_path, { parent: true }); @@ -3627,7 +4166,8 @@ var ASM_CONSTS = { // changed its name) FS.hashAddNode(old_node); } - },rmdir:(path) => { + }, + rmdir(path) { var lookup = FS.lookupPath(path, { parent: true }); var parent = lookup.node; var name = PATH.basename(path); @@ -3644,14 +4184,16 @@ var ASM_CONSTS = { } parent.node_ops.rmdir(parent, name); FS.destroyNode(node); - },readdir:(path) => { + }, + readdir(path) { var lookup = FS.lookupPath(path, { follow: true }); var node = lookup.node; if (!node.node_ops.readdir) { throw new FS.ErrnoError(54); } return node.node_ops.readdir(node); - },unlink:(path) => { + }, + unlink(path) { var lookup = FS.lookupPath(path, { parent: true }); var parent = lookup.node; if (!parent) { @@ -3674,7 +4216,8 @@ var ASM_CONSTS = { } parent.node_ops.unlink(parent, name); FS.destroyNode(node); - },readlink:(path) => { + }, + readlink(path) { var lookup = FS.lookupPath(path); var link = lookup.node; if (!link) { @@ -3684,7 +4227,8 @@ var ASM_CONSTS = { throw new FS.ErrnoError(28); } return PATH_FS.resolve(FS.getPath(link.parent), link.node_ops.readlink(link)); - },stat:(path, dontFollow) => { + }, + stat(path, dontFollow) { var lookup = FS.lookupPath(path, { follow: !dontFollow }); var node = lookup.node; if (!node) { @@ -3694,9 +4238,11 @@ var ASM_CONSTS = { throw new FS.ErrnoError(63); } return node.node_ops.getattr(node); - },lstat:(path) => { + }, + lstat(path) { return FS.stat(path, true); - },chmod:(path, mode, dontFollow) => { + }, + chmod(path, mode, dontFollow) { var node; if (typeof path == 'string') { var lookup = FS.lookupPath(path, { follow: !dontFollow }); @@ -3711,15 +4257,15 @@ var ASM_CONSTS = { mode: (mode & 4095) | (node.mode & ~4095), timestamp: Date.now() }); - },lchmod:(path, mode) => { + }, + lchmod(path, mode) { FS.chmod(path, mode, true); - },fchmod:(fd, mode) => { - var stream = FS.getStream(fd); - if (!stream) { - throw new FS.ErrnoError(8); - } + }, + fchmod(fd, mode) { + var stream = FS.getStreamChecked(fd); FS.chmod(stream.node, mode); - },chown:(path, uid, gid, dontFollow) => { + }, + chown(path, uid, gid, dontFollow) { var node; if (typeof path == 'string') { var lookup = FS.lookupPath(path, { follow: !dontFollow }); @@ -3734,15 +4280,15 @@ var ASM_CONSTS = { timestamp: Date.now() // we ignore the uid / gid for now }); - },lchown:(path, uid, gid) => { + }, + lchown(path, uid, gid) { FS.chown(path, uid, gid, true); - },fchown:(fd, uid, gid) => { - var stream = FS.getStream(fd); - if (!stream) { - throw new FS.ErrnoError(8); - } + }, + fchown(fd, uid, gid) { + var stream = FS.getStreamChecked(fd); FS.chown(stream.node, uid, gid); - },truncate:(path, len) => { + }, + truncate(path, len) { if (len < 0) { throw new FS.ErrnoError(28); } @@ -3770,26 +4316,26 @@ var ASM_CONSTS = { size: len, timestamp: Date.now() }); - },ftruncate:(fd, len) => { - var stream = FS.getStream(fd); - if (!stream) { - throw new FS.ErrnoError(8); - } + }, + ftruncate(fd, len) { + var stream = FS.getStreamChecked(fd); if ((stream.flags & 2097155) === 0) { throw new FS.ErrnoError(28); } FS.truncate(stream.node, len); - },utime:(path, atime, mtime) => { + }, + utime(path, atime, mtime) { var lookup = FS.lookupPath(path, { follow: true }); var node = lookup.node; node.node_ops.setattr(node, { timestamp: Math.max(atime, mtime) }); - },open:(path, flags, mode) => { + }, + open(path, flags, mode) { if (path === "") { throw new FS.ErrnoError(44); } - flags = typeof flags == 'string' ? FS.modeStringToFlags(flags) : flags; + flags = typeof flags == 'string' ? FS_modeStringToFlags(flags) : flags; mode = typeof mode == 'undefined' ? 438 /* 0666 */ : mode; if ((flags & 64)) { mode = (mode & 4095) | 32768; @@ -3853,9 +4399,9 @@ var ASM_CONSTS = { // register the stream with the filesystem var stream = FS.createStream({ - node: node, + node, path: FS.getPath(node), // we want the absolute path to the node - flags: flags, + flags, seekable: true, position: 0, stream_ops: node.stream_ops, @@ -3874,7 +4420,8 @@ var ASM_CONSTS = { } } return stream; - },close:(stream) => { + }, + close(stream) { if (FS.isClosed(stream)) { throw new FS.ErrnoError(8); } @@ -3889,9 +4436,11 @@ var ASM_CONSTS = { FS.closeStream(stream.fd); } stream.fd = null; - },isClosed:(stream) => { + }, + isClosed(stream) { return stream.fd === null; - },llseek:(stream, offset, whence) => { + }, + llseek(stream, offset, whence) { if (FS.isClosed(stream)) { throw new FS.ErrnoError(8); } @@ -3904,7 +4453,9 @@ var ASM_CONSTS = { stream.position = stream.stream_ops.llseek(stream, offset, whence); stream.ungotten = []; return stream.position; - },read:(stream, buffer, offset, length, position) => { + }, + read(stream, buffer, offset, length, position) { + assert(offset >= 0); if (length < 0 || position < 0) { throw new FS.ErrnoError(28); } @@ -3929,7 +4480,9 @@ var ASM_CONSTS = { var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position); if (!seeking) stream.position += bytesRead; return bytesRead; - },write:(stream, buffer, offset, length, position, canOwn) => { + }, + write(stream, buffer, offset, length, position, canOwn) { + assert(offset >= 0); if (length < 0 || position < 0) { throw new FS.ErrnoError(28); } @@ -3958,7 +4511,8 @@ var ASM_CONSTS = { var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn); if (!seeking) stream.position += bytesWritten; return bytesWritten; - },allocate:(stream, offset, length) => { + }, + allocate(stream, offset, length) { if (FS.isClosed(stream)) { throw new FS.ErrnoError(8); } @@ -3975,7 +4529,8 @@ var ASM_CONSTS = { throw new FS.ErrnoError(138); } stream.stream_ops.allocate(stream, offset, length); - },mmap:(stream, length, position, prot, flags) => { + }, + mmap(stream, length, position, prot, flags) { // User requests writing to file (prot & PROT_WRITE != 0). // Checking if we have permissions to write to the file unless // MAP_PRIVATE flag is set. According to POSIX spec it is possible @@ -3994,21 +4549,25 @@ var ASM_CONSTS = { throw new FS.ErrnoError(43); } return stream.stream_ops.mmap(stream, length, position, prot, flags); - },msync:(stream, buffer, offset, length, mmapFlags) => { + }, + msync(stream, buffer, offset, length, mmapFlags) { + assert(offset >= 0); if (!stream.stream_ops.msync) { return 0; } return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags); - },munmap:(stream) => 0,ioctl:(stream, cmd, arg) => { + }, + ioctl(stream, cmd, arg) { if (!stream.stream_ops.ioctl) { throw new FS.ErrnoError(59); } return stream.stream_ops.ioctl(stream, cmd, arg); - },readFile:(path, opts = {}) => { + }, + readFile(path, opts = {}) { opts.flags = opts.flags || 0; opts.encoding = opts.encoding || 'binary'; if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') { - throw new Error('Invalid encoding type "' + opts.encoding + '"'); + throw new Error(`Invalid encoding type "${opts.encoding}"`); } var ret; var stream = FS.open(path, opts.flags); @@ -4023,7 +4582,8 @@ var ASM_CONSTS = { } FS.close(stream); return ret; - },writeFile:(path, data, opts = {}) => { + }, + writeFile(path, data, opts = {}) { opts.flags = opts.flags || 577; var stream = FS.open(path, opts.flags, opts.mode); if (typeof data == 'string') { @@ -4036,7 +4596,9 @@ var ASM_CONSTS = { throw new Error('Unsupported data type'); } FS.close(stream); - },cwd:() => FS.currentPath,chdir:(path) => { + }, + cwd:() => FS.currentPath, + chdir(path) { var lookup = FS.lookupPath(path, { follow: true }); if (lookup.node === null) { throw new FS.ErrnoError(44); @@ -4049,11 +4611,13 @@ var ASM_CONSTS = { throw new FS.ErrnoError(errCode); } FS.currentPath = lookup.path; - },createDefaultDirectories:() => { + }, + createDefaultDirectories() { FS.mkdir('/tmp'); FS.mkdir('/home'); FS.mkdir('/home/web_user'); - },createDefaultDevices:() => { + }, + createDefaultDevices() { // create /dev FS.mkdir('/dev'); // setup /dev/null @@ -4070,27 +4634,34 @@ var ASM_CONSTS = { FS.mkdev('/dev/tty', FS.makedev(5, 0)); FS.mkdev('/dev/tty1', FS.makedev(6, 0)); // setup /dev/[u]random - var random_device = getRandomDevice(); - FS.createDevice('/dev', 'random', random_device); - FS.createDevice('/dev', 'urandom', random_device); + // use a buffer to avoid overhead of individual crypto calls per byte + var randomBuffer = new Uint8Array(1024), randomLeft = 0; + var randomByte = () => { + if (randomLeft === 0) { + randomLeft = randomFill(randomBuffer).byteLength; + } + return randomBuffer[--randomLeft]; + }; + FS.createDevice('/dev', 'random', randomByte); + FS.createDevice('/dev', 'urandom', randomByte); // we're not going to emulate the actual shm device, // just create the tmp dirs that reside in it commonly FS.mkdir('/dev/shm'); FS.mkdir('/dev/shm/tmp'); - },createSpecialDirectories:() => { + }, + createSpecialDirectories() { // create /proc/self/fd which allows /proc/self/fd/6 => readlink gives the // name of the stream for fd 6 (see test_unistd_ttyname) FS.mkdir('/proc'); var proc_self = FS.mkdir('/proc/self'); FS.mkdir('/proc/self/fd'); FS.mount({ - mount: () => { + mount() { var node = FS.createNode(proc_self, 'fd', 16384 | 511 /* 0777 */, 73); node.node_ops = { - lookup: (parent, name) => { + lookup(parent, name) { var fd = +name; - var stream = FS.getStream(fd); - if (!stream) throw new FS.ErrnoError(8); + var stream = FS.getStreamChecked(fd); var ret = { parent: null, mount: { mountpoint: 'fake' }, @@ -4103,7 +4674,8 @@ var ASM_CONSTS = { return node; } }, {}, '/proc/self/fd'); - },createStandardStreams:() => { + }, + createStandardStreams() { // TODO deprecate the old functionality of a single // input / output callback and that utilizes FS.createDevice // and instead require a unique set of stream ops @@ -4132,49 +4704,16 @@ var ASM_CONSTS = { var stdin = FS.open('/dev/stdin', 0); var stdout = FS.open('/dev/stdout', 1); var stderr = FS.open('/dev/stderr', 1); - assert(stdin.fd === 0, 'invalid handle for stdin (' + stdin.fd + ')'); - assert(stdout.fd === 1, 'invalid handle for stdout (' + stdout.fd + ')'); - assert(stderr.fd === 2, 'invalid handle for stderr (' + stderr.fd + ')'); - },ensureErrnoError:() => { - if (FS.ErrnoError) return; - FS.ErrnoError = /** @this{Object} */ function ErrnoError(errno, node) { - // We set the `name` property to be able to identify `FS.ErrnoError` - // - the `name` is a standard ECMA-262 property of error objects. Kind of good to have it anyway. - // - when using PROXYFS, an error can come from an underlying FS - // as different FS objects have their own FS.ErrnoError each, - // the test `err instanceof FS.ErrnoError` won't detect an error coming from another filesystem, causing bugs. - // we'll use the reliable test `err.name == "ErrnoError"` instead - this.name = 'ErrnoError'; - this.node = node; - this.setErrno = /** @this{Object} */ function(errno) { - this.errno = errno; - for (var key in ERRNO_CODES) { - if (ERRNO_CODES[key] === errno) { - this.code = key; - break; - } - } - }; - this.setErrno(errno); - this.message = ERRNO_MESSAGES[errno]; - - // Try to get a maximally helpful stack trace. On Node.js, getting Error.stack - // now ensures it shows what we want. - if (this.stack) { - // Define the stack property for Node.js 4, which otherwise errors on the next line. - Object.defineProperty(this, "stack", { value: (new Error).stack, writable: true }); - this.stack = demangleAll(this.stack); - } - }; - FS.ErrnoError.prototype = new Error(); - FS.ErrnoError.prototype.constructor = FS.ErrnoError; + assert(stdin.fd === 0, `invalid handle for stdin (${stdin.fd})`); + assert(stdout.fd === 1, `invalid handle for stdout (${stdout.fd})`); + assert(stderr.fd === 2, `invalid handle for stderr (${stderr.fd})`); + }, + staticInit() { // Some errors may happen quite a bit, to avoid overhead we reuse them (and suffer a lack of stack info) [44].forEach((code) => { FS.genericErrors[code] = new FS.ErrnoError(code); FS.genericErrors[code].stack = ''; }); - },staticInit:() => { - FS.ensureErrnoError(); FS.nameTable = new Array(4096); @@ -4187,19 +4726,19 @@ var ASM_CONSTS = { FS.filesystems = { 'MEMFS': MEMFS, }; - },init:(input, output, error) => { + }, + init(input, output, error) { assert(!FS.init.initialized, 'FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)'); FS.init.initialized = true; - FS.ensureErrnoError(); - // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here Module['stdin'] = input || Module['stdin']; Module['stdout'] = output || Module['stdout']; Module['stderr'] = error || Module['stderr']; FS.createStandardStreams(); - },quit:() => { + }, + quit() { FS.init.initialized = false; // force-flush all streams, so we get musl std streams printed out _fflush(0); @@ -4211,18 +4750,15 @@ var ASM_CONSTS = { } FS.close(stream); } - },getMode:(canRead, canWrite) => { - var mode = 0; - if (canRead) mode |= 292 | 73; - if (canWrite) mode |= 146; - return mode; - },findObject:(path, dontResolveLastLink) => { + }, + findObject(path, dontResolveLastLink) { var ret = FS.analyzePath(path, dontResolveLastLink); if (!ret.exists) { return null; } return ret.object; - },analyzePath:(path, dontResolveLastLink) => { + }, + analyzePath(path, dontResolveLastLink) { // operate from within the context of the symlink's target try { var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink }); @@ -4249,7 +4785,8 @@ var ASM_CONSTS = { ret.error = e.errno; }; return ret; - },createPath:(parent, path, canRead, canWrite) => { + }, + createPath(parent, path, canRead, canWrite) { parent = typeof parent == 'string' ? parent : FS.getPath(parent); var parts = path.split('/').reverse(); while (parts.length) { @@ -4264,17 +4801,19 @@ var ASM_CONSTS = { parent = current; } return current; - },createFile:(parent, name, properties, canRead, canWrite) => { + }, + createFile(parent, name, properties, canRead, canWrite) { var path = PATH.join2(typeof parent == 'string' ? parent : FS.getPath(parent), name); - var mode = FS.getMode(canRead, canWrite); + var mode = FS_getMode(canRead, canWrite); return FS.create(path, mode); - },createDataFile:(parent, name, data, canRead, canWrite, canOwn) => { + }, + createDataFile(parent, name, data, canRead, canWrite, canOwn) { var path = name; if (parent) { parent = typeof parent == 'string' ? parent : FS.getPath(parent); path = name ? PATH.join2(parent, name) : parent; } - var mode = FS.getMode(canRead, canWrite); + var mode = FS_getMode(canRead, canWrite); var node = FS.create(path, mode); if (data) { if (typeof data == 'string') { @@ -4289,25 +4828,25 @@ var ASM_CONSTS = { FS.close(stream); FS.chmod(node, mode); } - return node; - },createDevice:(parent, name, input, output) => { + }, + createDevice(parent, name, input, output) { var path = PATH.join2(typeof parent == 'string' ? parent : FS.getPath(parent), name); - var mode = FS.getMode(!!input, !!output); + var mode = FS_getMode(!!input, !!output); if (!FS.createDevice.major) FS.createDevice.major = 64; var dev = FS.makedev(FS.createDevice.major++, 0); // Create a fake device that a set of stream ops to emulate // the old behavior. FS.registerDevice(dev, { - open: (stream) => { + open(stream) { stream.seekable = false; }, - close: (stream) => { + close(stream) { // flush any pending line data - if (output && output.buffer && output.buffer.length) { + if (output?.buffer?.length) { output(10); } }, - read: (stream, buffer, offset, length, pos /* ignored */) => { + read(stream, buffer, offset, length, pos /* ignored */) { var bytesRead = 0; for (var i = 0; i < length; i++) { var result; @@ -4328,7 +4867,7 @@ var ASM_CONSTS = { } return bytesRead; }, - write: (stream, buffer, offset, length, pos) => { + write(stream, buffer, offset, length, pos) { for (var i = 0; i < length; i++) { try { output(buffer[offset+i]); @@ -4343,7 +4882,8 @@ var ASM_CONSTS = { } }); return FS.mkdev(path, mode, dev); - },forceLoadFile:(obj) => { + }, + forceLoadFile(obj) { if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true; if (typeof XMLHttpRequest != 'undefined') { throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread."); @@ -4360,108 +4900,105 @@ var ASM_CONSTS = { } else { throw new Error('Cannot load without read() or XMLHttpRequest.'); } - },createLazyFile:(parent, name, url, canRead, canWrite) => { - // Lazy chunked Uint8Array (implements get and length from Uint8Array). Actual getting is abstracted away for eventual reuse. - /** @constructor */ - function LazyUint8Array() { - this.lengthKnown = false; - this.chunks = []; // Loaded chunks. Index is the chunk number - } - LazyUint8Array.prototype.get = /** @this{Object} */ function LazyUint8Array_get(idx) { - if (idx > this.length-1 || idx < 0) { - return undefined; + }, + createLazyFile(parent, name, url, canRead, canWrite) { + // Lazy chunked Uint8Array (implements get and length from Uint8Array). + // Actual getting is abstracted away for eventual reuse. + class LazyUint8Array { + constructor() { + this.lengthKnown = false; + this.chunks = []; // Loaded chunks. Index is the chunk number + } + get(idx) { + if (idx > this.length-1 || idx < 0) { + return undefined; + } + var chunkOffset = idx % this.chunkSize; + var chunkNum = (idx / this.chunkSize)|0; + return this.getter(chunkNum)[chunkOffset]; } - var chunkOffset = idx % this.chunkSize; - var chunkNum = (idx / this.chunkSize)|0; - return this.getter(chunkNum)[chunkOffset]; - }; - LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter(getter) { - this.getter = getter; - }; - LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() { - // Find length - var xhr = new XMLHttpRequest(); - xhr.open('HEAD', url, false); - xhr.send(null); - if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status); - var datalength = Number(xhr.getResponseHeader("Content-length")); - var header; - var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes"; - var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip"; - - var chunkSize = 1024*1024; // Chunk size in bytes - - if (!hasByteServing) chunkSize = datalength; - - // Function to get a range from the remote URL. - var doXHR = (from, to) => { - if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!"); - if (to > datalength-1) throw new Error("only " + datalength + " bytes available! programmer error!"); - - // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available. + setDataGetter(getter) { + this.getter = getter; + } + cacheLength() { + // Find length var xhr = new XMLHttpRequest(); - xhr.open('GET', url, false); - if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to); + xhr.open('HEAD', url, false); + xhr.send(null); + if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status); + var datalength = Number(xhr.getResponseHeader("Content-length")); + var header; + var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes"; + var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip"; + + var chunkSize = 1024*1024; // Chunk size in bytes + + if (!hasByteServing) chunkSize = datalength; + + // Function to get a range from the remote URL. + var doXHR = (from, to) => { + if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!"); + if (to > datalength-1) throw new Error("only " + datalength + " bytes available! programmer error!"); + + // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available. + var xhr = new XMLHttpRequest(); + xhr.open('GET', url, false); + if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to); - // Some hints to the browser that we want binary data. - xhr.responseType = 'arraybuffer'; - if (xhr.overrideMimeType) { - xhr.overrideMimeType('text/plain; charset=x-user-defined'); + // Some hints to the browser that we want binary data. + xhr.responseType = 'arraybuffer'; + if (xhr.overrideMimeType) { + xhr.overrideMimeType('text/plain; charset=x-user-defined'); + } + + xhr.send(null); + if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status); + if (xhr.response !== undefined) { + return new Uint8Array(/** @type{Array} */(xhr.response || [])); + } + return intArrayFromString(xhr.responseText || '', true); + }; + var lazyArray = this; + lazyArray.setDataGetter((chunkNum) => { + var start = chunkNum * chunkSize; + var end = (chunkNum+1) * chunkSize - 1; // including this byte + end = Math.min(end, datalength-1); // if datalength-1 is selected, this is the last block + if (typeof lazyArray.chunks[chunkNum] == 'undefined') { + lazyArray.chunks[chunkNum] = doXHR(start, end); + } + if (typeof lazyArray.chunks[chunkNum] == 'undefined') throw new Error('doXHR failed!'); + return lazyArray.chunks[chunkNum]; + }); + + if (usesGzip || !datalength) { + // if the server uses gzip or doesn't supply the length, we have to download the whole file to get the (uncompressed) length + chunkSize = datalength = 1; // this will force getter(0)/doXHR do download the whole file + datalength = this.getter(0).length; + chunkSize = datalength; + out("LazyFiles on gzip forces download of the whole file when length is accessed"); } - xhr.send(null); - if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status); - if (xhr.response !== undefined) { - return new Uint8Array(/** @type{Array} */(xhr.response || [])); + this._length = datalength; + this._chunkSize = chunkSize; + this.lengthKnown = true; + } + get length() { + if (!this.lengthKnown) { + this.cacheLength(); } - return intArrayFromString(xhr.responseText || '', true); - }; - var lazyArray = this; - lazyArray.setDataGetter((chunkNum) => { - var start = chunkNum * chunkSize; - var end = (chunkNum+1) * chunkSize - 1; // including this byte - end = Math.min(end, datalength-1); // if datalength-1 is selected, this is the last block - if (typeof lazyArray.chunks[chunkNum] == 'undefined') { - lazyArray.chunks[chunkNum] = doXHR(start, end); + return this._length; + } + get chunkSize() { + if (!this.lengthKnown) { + this.cacheLength(); } - if (typeof lazyArray.chunks[chunkNum] == 'undefined') throw new Error('doXHR failed!'); - return lazyArray.chunks[chunkNum]; - }); - - if (usesGzip || !datalength) { - // if the server uses gzip or doesn't supply the length, we have to download the whole file to get the (uncompressed) length - chunkSize = datalength = 1; // this will force getter(0)/doXHR do download the whole file - datalength = this.getter(0).length; - chunkSize = datalength; - out("LazyFiles on gzip forces download of the whole file when length is accessed"); + return this._chunkSize; } + } - this._length = datalength; - this._chunkSize = chunkSize; - this.lengthKnown = true; - }; if (typeof XMLHttpRequest != 'undefined') { if (!ENVIRONMENT_IS_WORKER) throw 'Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc'; var lazyArray = new LazyUint8Array(); - Object.defineProperties(lazyArray, { - length: { - get: /** @this{Object} */ function() { - if (!this.lengthKnown) { - this.cacheLength(); - } - return this._length; - } - }, - chunkSize: { - get: /** @this{Object} */ function() { - if (!this.lengthKnown) { - this.cacheLength(); - } - return this._chunkSize; - } - } - }); - var properties = { isDevice: false, contents: lazyArray }; } else { var properties = { isDevice: false, url: url }; @@ -4480,7 +5017,7 @@ var ASM_CONSTS = { // Add a function that defers querying the file size until it is asked the first time. Object.defineProperties(node, { usedBytes: { - get: /** @this {FSNode} */ function() { return this.contents.length; } + get: function() { return this.contents.length; } } }); // override each stream op with one that tries to force load the lazy file first @@ -4488,9 +5025,9 @@ var ASM_CONSTS = { var keys = Object.keys(node.stream_ops); keys.forEach((key) => { var fn = node.stream_ops[key]; - stream_ops[key] = function forceLoadLazyFile() { + stream_ops[key] = (...args) => { FS.forceLoadFile(node); - return fn.apply(null, arguments); + return fn(...args); }; }); function writeChunks(stream, buffer, offset, length, position) { @@ -4523,121 +5060,35 @@ var ASM_CONSTS = { throw new FS.ErrnoError(48); } writeChunks(stream, HEAP8, ptr, length, position); - return { ptr: ptr, allocated: true }; + return { ptr, allocated: true }; }; node.stream_ops = stream_ops; return node; - },createPreloadedFile:(parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => { - // TODO we should allow people to just pass in a complete filename instead - // of parent and name being that we just join them anyways - var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent; - var dep = getUniqueRunDependency('cp ' + fullname); // might have several active requests for the same fullname - function processData(byteArray) { - function finish(byteArray) { - if (preFinish) preFinish(); - if (!dontCreateFile) { - FS.createDataFile(parent, name, byteArray, canRead, canWrite, canOwn); - } - if (onload) onload(); - removeRunDependency(dep); - } - if (Browser.handledByPreloadPlugin(byteArray, fullname, finish, () => { - if (onerror) onerror(); - removeRunDependency(dep); - })) { - return; - } - finish(byteArray); - } - addRunDependency(dep); - if (typeof url == 'string') { - asyncLoad(url, (byteArray) => processData(byteArray), onerror); - } else { - processData(url); - } - },indexedDB:() => { - return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; - },DB_NAME:() => { - return 'EM_FS_' + window.location.pathname; - },DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:(paths, onload = (() => {}), onerror = (() => {})) => { - var indexedDB = FS.indexedDB(); - try { - var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION); - } catch (e) { - return onerror(e); - } - openRequest.onupgradeneeded = () => { - out('creating db'); - var db = openRequest.result; - db.createObjectStore(FS.DB_STORE_NAME); - }; - openRequest.onsuccess = () => { - var db = openRequest.result; - var transaction = db.transaction([FS.DB_STORE_NAME], 'readwrite'); - var files = transaction.objectStore(FS.DB_STORE_NAME); - var ok = 0, fail = 0, total = paths.length; - function finish() { - if (fail == 0) onload(); else onerror(); - } - paths.forEach((path) => { - var putRequest = files.put(FS.analyzePath(path).object.contents, path); - putRequest.onsuccess = () => { ok++; if (ok + fail == total) finish() }; - putRequest.onerror = () => { fail++; if (ok + fail == total) finish() }; - }); - transaction.onerror = onerror; - }; - openRequest.onerror = onerror; - },loadFilesFromDB:(paths, onload = (() => {}), onerror = (() => {})) => { - var indexedDB = FS.indexedDB(); - try { - var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION); - } catch (e) { - return onerror(e); - } - openRequest.onupgradeneeded = onerror; // no database to load from - openRequest.onsuccess = () => { - var db = openRequest.result; - try { - var transaction = db.transaction([FS.DB_STORE_NAME], 'readonly'); - } catch(e) { - onerror(e); - return; - } - var files = transaction.objectStore(FS.DB_STORE_NAME); - var ok = 0, fail = 0, total = paths.length; - function finish() { - if (fail == 0) onload(); else onerror(); - } - paths.forEach((path) => { - var getRequest = files.get(path); - getRequest.onsuccess = () => { - if (FS.analyzePath(path).exists) { - FS.unlink(path); - } - FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequest.result, true, true, true); - ok++; - if (ok + fail == total) finish(); - }; - getRequest.onerror = () => { fail++; if (ok + fail == total) finish() }; - }); - transaction.onerror = onerror; - }; - openRequest.onerror = onerror; - },absolutePath:() => { + }, + absolutePath() { abort('FS.absolutePath has been removed; use PATH_FS.resolve instead'); - },createFolder:() => { + }, + createFolder() { abort('FS.createFolder has been removed; use FS.mkdir instead'); - },createLink:() => { + }, + createLink() { abort('FS.createLink has been removed; use FS.symlink instead'); - },joinPath:() => { + }, + joinPath() { abort('FS.joinPath has been removed; use PATH.join instead'); - },mmapAlloc:() => { + }, + mmapAlloc() { abort('FS.mmapAlloc has been replaced by the top level function mmapAlloc'); - },standardizePath:() => { + }, + standardizePath() { abort('FS.standardizePath has been removed; use PATH.normalize instead'); - }}; - Module["FS"] = FS; - var SYSCALLS = {DEFAULT_POLLMASK:5,calculateAt:function(dirfd, path, allowEmpty) { + }, + }; + Module['FS'] = FS; + + var SYSCALLS = { + DEFAULT_POLLMASK:5, + calculateAt(dirfd, path, allowEmpty) { if (PATH.isAbs(path)) { return path; } @@ -4656,38 +5107,31 @@ var ASM_CONSTS = { return dir; } return PATH.join2(dir, path); - },doStat:function(func, path, buf) { - try { - var stat = func(path); - } catch (e) { - if (e && e.node && PATH.normalize(path) !== PATH.normalize(FS.getPath(e.node))) { - // an error occurred while trying to look up the path; we should just report ENOTDIR - return -54; - } - throw e; - } + }, + doStat(func, path, buf) { + var stat = func(path); HEAP32[((buf)>>2)] = stat.dev; - HEAP32[(((buf)+(8))>>2)] = stat.ino; - HEAP32[(((buf)+(12))>>2)] = stat.mode; - HEAPU32[(((buf)+(16))>>2)] = stat.nlink; - HEAP32[(((buf)+(20))>>2)] = stat.uid; - HEAP32[(((buf)+(24))>>2)] = stat.gid; - HEAP32[(((buf)+(28))>>2)] = stat.rdev; - (tempI64 = [stat.size>>>0,(tempDouble=stat.size,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((buf)+(40))>>2)] = tempI64[0],HEAP32[(((buf)+(44))>>2)] = tempI64[1]); - HEAP32[(((buf)+(48))>>2)] = 4096; - HEAP32[(((buf)+(52))>>2)] = stat.blocks; + HEAP32[(((buf)+(4))>>2)] = stat.mode; + HEAPU32[(((buf)+(8))>>2)] = stat.nlink; + HEAP32[(((buf)+(12))>>2)] = stat.uid; + HEAP32[(((buf)+(16))>>2)] = stat.gid; + HEAP32[(((buf)+(20))>>2)] = stat.rdev; + (tempI64 = [stat.size>>>0,(tempDouble = stat.size,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? (+(Math.floor((tempDouble)/4294967296.0)))>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)], HEAP32[(((buf)+(24))>>2)] = tempI64[0],HEAP32[(((buf)+(28))>>2)] = tempI64[1]); + HEAP32[(((buf)+(32))>>2)] = 4096; + HEAP32[(((buf)+(36))>>2)] = stat.blocks; var atime = stat.atime.getTime(); var mtime = stat.mtime.getTime(); var ctime = stat.ctime.getTime(); - (tempI64 = [Math.floor(atime / 1000)>>>0,(tempDouble=Math.floor(atime / 1000),(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((buf)+(56))>>2)] = tempI64[0],HEAP32[(((buf)+(60))>>2)] = tempI64[1]); - HEAPU32[(((buf)+(64))>>2)] = (atime % 1000) * 1000; - (tempI64 = [Math.floor(mtime / 1000)>>>0,(tempDouble=Math.floor(mtime / 1000),(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((buf)+(72))>>2)] = tempI64[0],HEAP32[(((buf)+(76))>>2)] = tempI64[1]); - HEAPU32[(((buf)+(80))>>2)] = (mtime % 1000) * 1000; - (tempI64 = [Math.floor(ctime / 1000)>>>0,(tempDouble=Math.floor(ctime / 1000),(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((buf)+(88))>>2)] = tempI64[0],HEAP32[(((buf)+(92))>>2)] = tempI64[1]); - HEAPU32[(((buf)+(96))>>2)] = (ctime % 1000) * 1000; - (tempI64 = [stat.ino>>>0,(tempDouble=stat.ino,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((buf)+(104))>>2)] = tempI64[0],HEAP32[(((buf)+(108))>>2)] = tempI64[1]); + (tempI64 = [Math.floor(atime / 1000)>>>0,(tempDouble = Math.floor(atime / 1000),(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? (+(Math.floor((tempDouble)/4294967296.0)))>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)], HEAP32[(((buf)+(40))>>2)] = tempI64[0],HEAP32[(((buf)+(44))>>2)] = tempI64[1]); + HEAPU32[(((buf)+(48))>>2)] = (atime % 1000) * 1000; + (tempI64 = [Math.floor(mtime / 1000)>>>0,(tempDouble = Math.floor(mtime / 1000),(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? (+(Math.floor((tempDouble)/4294967296.0)))>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)], HEAP32[(((buf)+(56))>>2)] = tempI64[0],HEAP32[(((buf)+(60))>>2)] = tempI64[1]); + HEAPU32[(((buf)+(64))>>2)] = (mtime % 1000) * 1000; + (tempI64 = [Math.floor(ctime / 1000)>>>0,(tempDouble = Math.floor(ctime / 1000),(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? (+(Math.floor((tempDouble)/4294967296.0)))>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)], HEAP32[(((buf)+(72))>>2)] = tempI64[0],HEAP32[(((buf)+(76))>>2)] = tempI64[1]); + HEAPU32[(((buf)+(80))>>2)] = (ctime % 1000) * 1000; + (tempI64 = [stat.ino>>>0,(tempDouble = stat.ino,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? (+(Math.floor((tempDouble)/4294967296.0)))>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)], HEAP32[(((buf)+(88))>>2)] = tempI64[0],HEAP32[(((buf)+(92))>>2)] = tempI64[1]); return 0; - },doMsync:function(addr, stream, len, flags, offset) { + }, + doMsync(addr, stream, len, flags, offset) { if (!FS.isFile(stream.node.mode)) { throw new FS.ErrnoError(43); } @@ -4697,29 +5141,35 @@ var ASM_CONSTS = { } var buffer = HEAPU8.slice(addr, addr + len); FS.msync(stream, buffer, offset, len, flags); - },varargs:undefined,get:function() { + }, + varargs:undefined, + get() { assert(SYSCALLS.varargs != undefined); + // the `+` prepended here is necessary to convince the JSCompiler that varargs is indeed a number. + var ret = HEAP32[((+SYSCALLS.varargs)>>2)]; SYSCALLS.varargs += 4; - var ret = HEAP32[(((SYSCALLS.varargs)-(4))>>2)]; return ret; - },getStr:function(ptr) { + }, + getp() { return SYSCALLS.get() }, + getStr(ptr) { var ret = UTF8ToString(ptr); return ret; - },getStreamFromFD:function(fd) { - var stream = FS.getStream(fd); - if (!stream) throw new FS.ErrnoError(8); + }, + getStreamFromFD(fd) { + var stream = FS.getStreamChecked(fd); return stream; - }}; - Module["SYSCALLS"] = SYSCALLS; + }, + }; + Module['SYSCALLS'] = SYSCALLS; function ___syscall__newselect(nfds, readfds, writefds, exceptfds, timeout) { try { // readfds are supported, // writefds checks socket open status - // exceptfds not supported - // timeout is always 0 - fully async + // exceptfds are supported, although on web, such exceptional conditions never arise in web sockets + // and so the exceptfds list will always return empty. + // timeout is supported, although on SOCKFS and PIPEFS these are ignored and always treated as 0 - fully async assert(nfds <= 64, 'nfds must be less than or equal to 64'); // fd sets have 64 bits // TODO: this could be 1024 based on current musl headers - assert(!exceptfds, 'exceptfds not supported'); var total = 0; @@ -4759,7 +5209,18 @@ var ASM_CONSTS = { var flags = SYSCALLS.DEFAULT_POLLMASK; if (stream.stream_ops.poll) { - flags = stream.stream_ops.poll(stream); + var timeoutInMillis = -1; + if (timeout) { + // select(2) is declared to accept "struct timeval { time_t tv_sec; suseconds_t tv_usec; }". + // However, musl passes the two values to the syscall as an array of long values. + // Note that sizeof(time_t) != sizeof(long) in wasm32. The former is 8, while the latter is 4. + // This means using "C_STRUCTS.timeval.tv_usec" leads to a wrong offset. + // So, instead, we use POINTER_SIZE. + var tv_sec = (readfds ? HEAP32[((timeout)>>2)] : 0), + tv_usec = (readfds ? HEAP32[(((timeout)+(4))>>2)] : 0); + timeoutInMillis = (tv_sec + tv_usec / 1000000) * 1000; + } + flags = stream.stream_ops.poll(stream, timeoutInMillis); } if ((flags & 1) && check(fd, srcReadLow, srcReadHigh, mask)) { @@ -4795,9 +5256,11 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall__newselect"] = ___syscall__newselect; + Module['___syscall__newselect'] = ___syscall__newselect; + ___syscall__newselect.sig = 'iipppp'; - var SOCKFS = {mount:function(mount) { + var SOCKFS = { + mount(mount) { // If Module['websocket'] has already been defined (e.g. for configuring // the subprotocol/url) use that, if not initialise it to a new object. Module['websocket'] = (Module['websocket'] && @@ -4823,7 +5286,8 @@ var ASM_CONSTS = { // If debug is enabled register simple default logging callbacks for each Event. return FS.createNode(null, '/', 16384 | 511 /* 0777 */, 0); - },createSocket:function(family, type, protocol) { + }, + createSocket(family, type, protocol) { type &= ~526336; // Some applications may pass it; it makes no sense for a single process. var streaming = type == 1; if (streaming && protocol && protocol != 6) { @@ -4832,9 +5296,9 @@ var ASM_CONSTS = { // create our internal socket structure var sock = { - family: family, - type: type, - protocol: protocol, + family, + type, + protocol, server: null, error: null, // Used in getsockopt for SOL_SOCKET/SO_ERROR test peers: {}, @@ -4852,7 +5316,7 @@ var ASM_CONSTS = { // as read and write to indirectly interact with the socket var stream = FS.createStream({ path: name, - node: node, + node, flags: 2, seekable: false, stream_ops: SOCKFS.stream_ops @@ -4863,19 +5327,24 @@ var ASM_CONSTS = { sock.stream = stream; return sock; - },getSocket:function(fd) { + }, + getSocket(fd) { var stream = FS.getStream(fd); if (!stream || !FS.isSocket(stream.node.mode)) { return null; } return stream.node.sock; - },stream_ops:{poll:function(stream) { + }, + stream_ops:{ + poll(stream) { var sock = stream.node.sock; return sock.sock_ops.poll(sock); - },ioctl:function(stream, request, varargs) { + }, + ioctl(stream, request, varargs) { var sock = stream.node.sock; return sock.sock_ops.ioctl(sock, request, varargs); - },read:function(stream, buffer, offset, length, position /* ignored */) { + }, + read(stream, buffer, offset, length, position /* ignored */) { var sock = stream.node.sock; var msg = sock.sock_ops.recvmsg(sock, length); if (!msg) { @@ -4884,18 +5353,24 @@ var ASM_CONSTS = { } buffer.set(msg.buffer, offset); return msg.buffer.length; - },write:function(stream, buffer, offset, length, position /* ignored */) { + }, + write(stream, buffer, offset, length, position /* ignored */) { var sock = stream.node.sock; return sock.sock_ops.sendmsg(sock, buffer, offset, length); - },close:function(stream) { + }, + close(stream) { var sock = stream.node.sock; sock.sock_ops.close(sock); - }},nextname:function() { + }, + }, + nextname() { if (!SOCKFS.nextname.current) { SOCKFS.nextname.current = 0; } return 'socket[' + (SOCKFS.nextname.current++) + ']'; - },websocket_sock_ops:{createPeer:function(sock, addr, port) { + }, + websocket_sock_ops:{ + createPeer(sock, addr, port) { var ws; if (typeof addr == 'object') { @@ -4984,8 +5459,8 @@ var ASM_CONSTS = { } var peer = { - addr: addr, - port: port, + addr, + port, socket: ws, dgram_send_queue: [] }; @@ -5005,13 +5480,17 @@ var ASM_CONSTS = { } return peer; - },getPeer:function(sock, addr, port) { + }, + getPeer(sock, addr, port) { return sock.peers[addr + ':' + port]; - },addPeer:function(sock, peer) { + }, + addPeer(sock, peer) { sock.peers[peer.addr + ':' + peer.port] = peer; - },removePeer:function(sock, peer) { + }, + removePeer(sock, peer) { delete sock.peers[peer.addr + ':' + peer.port]; - },handlePeerEvents:function(sock, peer) { + }, + handlePeerEvents(sock, peer) { var first = true; var handleOpen = function () { @@ -5100,7 +5579,8 @@ var ASM_CONSTS = { Module['websocket'].emit('error', [sock.stream.fd, sock.error, 'ECONNREFUSED: Connection refused']); }; } - },poll:function(sock) { + }, + poll(sock) { if (sock.type === 1 && sock.server) { // listen sockets should only say they're available for reading // if there are pending clients. @@ -5130,7 +5610,8 @@ var ASM_CONSTS = { } return mask; - },ioctl:function(sock, request, arg) { + }, + ioctl(sock, request, arg) { switch (request) { case 21531: var bytes = 0; @@ -5142,7 +5623,8 @@ var ASM_CONSTS = { default: return 28; } - },close:function(sock) { + }, + close(sock) { // if we've spawned a listen server, close it if (sock.server) { try { @@ -5162,7 +5644,8 @@ var ASM_CONSTS = { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } return 0; - },bind:function(sock, addr, port) { + }, + bind(sock, addr, port) { if (typeof sock.saddr != 'undefined' || typeof sock.sport != 'undefined') { throw new FS.ErrnoError(28); // already bound } @@ -5186,7 +5669,8 @@ var ASM_CONSTS = { if (e.errno !== 138) throw e; } } - },connect:function(sock, addr, port) { + }, + connect(sock, addr, port) { if (sock.server) { throw new FS.ErrnoError(138); } @@ -5215,7 +5699,8 @@ var ASM_CONSTS = { // always "fail" in non-blocking mode throw new FS.ErrnoError(26); - },listen:function(sock, backlog) { + }, + listen(sock, backlog) { if (!ENVIRONMENT_IS_NODE) { throw new FS.ErrnoError(138); } @@ -5225,7 +5710,7 @@ var ASM_CONSTS = { var WebSocketServer = require('ws').Server; var host = sock.saddr; sock.server = new WebSocketServer({ - host: host, + host, port: sock.sport // TODO support backlog }); @@ -5266,14 +5751,16 @@ var ASM_CONSTS = { Module['websocket'].emit('error', [sock.stream.fd, sock.error, 'EHOSTUNREACH: Host is unreachable']); // don't throw }); - },accept:function(listensock) { + }, + accept(listensock) { if (!listensock.server || !listensock.pending.length) { throw new FS.ErrnoError(28); } var newsock = listensock.pending.shift(); newsock.stream.flags = listensock.stream.flags; return newsock; - },getname:function(sock, peer) { + }, + getname(sock, peer) { var addr, port; if (peer) { if (sock.daddr === undefined || sock.dport === undefined) { @@ -5287,8 +5774,9 @@ var ASM_CONSTS = { addr = sock.saddr || 0; port = sock.sport || 0; } - return { addr: addr, port: port }; - },sendmsg:function(sock, buffer, offset, length, addr, port) { + return { addr, port }; + }, + sendmsg(sock, buffer, offset, length, addr, port) { if (sock.type === 2) { // connection-less sockets will honor the message address, // and otherwise fall back to the bound destination address @@ -5350,7 +5838,8 @@ var ASM_CONSTS = { } catch (e) { throw new FS.ErrnoError(28); } - },recvmsg:function(sock, length) { + }, + recvmsg(sock, length) { // http://pubs.opengroup.org/onlinepubs/7908799/xns/recvmsg.html if (sock.type === 1 && sock.server) { // tcp servers should not be recv()'ing on the listen socket @@ -5396,25 +5885,37 @@ var ASM_CONSTS = { } return res; - }}}; - Module["SOCKFS"] = SOCKFS; + }, + }, + }; + Module['SOCKFS'] = SOCKFS; - function getSocketFromFD(fd) { + var getSocketFromFD = (fd) => { var socket = SOCKFS.getSocket(fd); if (!socket) throw new FS.ErrnoError(8); return socket; - } - Module["getSocketFromFD"] = getSocketFromFD; - - function setErrNo(value) { - HEAP32[((___errno_location())>>2)] = value; - return value; - } - Module["setErrNo"] = setErrNo; - var Sockets = {BUFFER_SIZE:10240,MAX_BUFFER_SIZE:10485760,nextFd:1,fds:{},nextport:1,maxport:65535,peer:null,connections:{},portmap:{},localAddr:4261412874,addrPool:[33554442,50331658,67108874,83886090,100663306,117440522,134217738,150994954,167772170,184549386,201326602,218103818,234881034]}; - Module["Sockets"] = Sockets; + }; + Module['getSocketFromFD'] = getSocketFromFD; + + var Sockets = { + BUFFER_SIZE:10240, + MAX_BUFFER_SIZE:10485760, + nextFd:1, + fds:{ + }, + nextport:1, + maxport:65535, + peer:null, + connections:{ + }, + portmap:{ + }, + localAddr:4261412874, + addrPool:[33554442,50331658,67108874,83886090,100663306,117440522,134217738,150994954,167772170,184549386,201326602,218103818,234881034], + }; + Module['Sockets'] = Sockets; - function inetPton4(str) { + var inetPton4 = (str) => { var b = str.split('.'); for (var i = 0; i < 4; i++) { var tmp = Number(b[i]); @@ -5422,16 +5923,14 @@ var ASM_CONSTS = { b[i] = tmp; } return (b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24)) >>> 0; - } - Module["inetPton4"] = inetPton4; + }; + Module['inetPton4'] = inetPton4; /** @suppress {checkTypes} */ - function jstoi_q(str) { - return parseInt(str); - } - Module["jstoi_q"] = jstoi_q; - function inetPton6(str) { + var jstoi_q = (str) => parseInt(str); + Module['jstoi_q'] = jstoi_q; + var inetPton6 = (str) => { var words; var w, offset, z, i; /* http://home.deds.nl/~aeron/regex/ */ @@ -5485,11 +5984,12 @@ var ASM_CONSTS = { (parts[5] << 16) | parts[4], (parts[7] << 16) | parts[6] ]; - } - Module["inetPton6"] = inetPton6; + }; + Module['inetPton6'] = inetPton6; + /** @param {number=} addrlen */ - function writeSockaddr(sa, family, addr, port, addrlen) { + var writeSockaddr = (sa, family, addr, port, addrlen) => { switch (family) { case 2: addr = inetPton4(addr); @@ -5518,11 +6018,19 @@ var ASM_CONSTS = { return 5; } return 0; - } - Module["writeSockaddr"] = writeSockaddr; - - - var DNS = {address_map:{id:1,addrs:{},names:{}},lookup_name:function (name) { + }; + Module['writeSockaddr'] = writeSockaddr; + + + var DNS = { + address_map:{ + id:1, + addrs:{ + }, + names:{ + }, + }, + lookup_name(name) { // If the name is already a valid ipv4 / ipv6 address, don't generate a fake one. var res = inetPton4(name); if (res !== null) { @@ -5549,16 +6057,17 @@ var ASM_CONSTS = { } return addr; - },lookup_addr:function (addr) { + }, + lookup_addr(addr) { if (DNS.address_map.names[addr]) { return DNS.address_map.names[addr]; } return null; - }}; - Module["DNS"] = DNS; - - function ___syscall_accept4(fd, addr, addrlen, flags) { + }, + }; + Module['DNS'] = DNS; + function ___syscall_accept4(fd, addr, addrlen, flags, d1, d2) { try { var sock = getSocketFromFD(fd); @@ -5573,17 +6082,18 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_accept4"] = ___syscall_accept4; + Module['___syscall_accept4'] = ___syscall_accept4; + ___syscall_accept4.sig = 'iippiii'; - function inetNtop4(addr) { + var inetNtop4 = (addr) => { return (addr & 0xff) + '.' + ((addr >> 8) & 0xff) + '.' + ((addr >> 16) & 0xff) + '.' + ((addr >> 24) & 0xff) - } - Module["inetNtop4"] = inetNtop4; + }; + Module['inetNtop4'] = inetNtop4; - function inetNtop6(ints) { + var inetNtop6 = (ints) => { // ref: http://www.ietf.org/rfc/rfc2373.txt - section 2.5.4 // Format for IPv4 compatible and mapped 128-bit IPv6 Addresses // 128-bits are split into eight 16-bit words @@ -5678,10 +6188,10 @@ var ASM_CONSTS = { str += word < 7 ? ":" : ""; } return str; - } - Module["inetNtop6"] = inetNtop6; + }; + Module['inetNtop6'] = inetNtop6; - function readSockaddr(sa, salen) { + var readSockaddr = (sa, salen) => { // family / port offsets are common to both sockaddr_in and sockaddr_in6 var family = HEAP16[((sa)>>1)]; var port = _ntohs(HEAPU16[(((sa)+(2))>>1)]); @@ -5712,21 +6222,20 @@ var ASM_CONSTS = { } return { family: family, addr: addr, port: port }; - } - Module["readSockaddr"] = readSockaddr; + }; + Module['readSockaddr'] = readSockaddr; /** @param {boolean=} allowNull */ - function getSocketAddress(addrp, addrlen, allowNull) { + var getSocketAddress = (addrp, addrlen, allowNull) => { if (allowNull && addrp === 0) return null; var info = readSockaddr(addrp, addrlen); if (info.errno) throw new FS.ErrnoError(info.errno); info.addr = DNS.lookup_addr(info.addr) || info.addr; return info; - } - Module["getSocketAddress"] = getSocketAddress; - - function ___syscall_bind(fd, addr, addrlen) { + }; + Module['getSocketAddress'] = getSocketAddress; + function ___syscall_bind(fd, addr, addrlen, d1, d2, d3) { try { var sock = getSocketFromFD(fd); @@ -5738,8 +6247,8 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_bind"] = ___syscall_bind; - ___syscall_bind.sig = 'iipi'; + Module['___syscall_bind'] = ___syscall_bind; + ___syscall_bind.sig = 'iippiii'; function ___syscall_chdir(path) { try { @@ -5752,7 +6261,7 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_chdir"] = ___syscall_chdir; + Module['___syscall_chdir'] = ___syscall_chdir; ___syscall_chdir.sig = 'ip'; function ___syscall_chmod(path, mode) { @@ -5766,12 +6275,11 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_chmod"] = ___syscall_chmod; + Module['___syscall_chmod'] = ___syscall_chmod; ___syscall_chmod.sig = 'ipi'; - - function ___syscall_connect(fd, addr, addrlen) { + function ___syscall_connect(fd, addr, addrlen, d1, d2, d3) { try { var sock = getSocketFromFD(fd); @@ -5783,37 +6291,38 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_connect"] = ___syscall_connect; - ___syscall_connect.sig = 'iipi'; + Module['___syscall_connect'] = ___syscall_connect; + ___syscall_connect.sig = 'iippiii'; function ___syscall_dup(fd) { try { var old = SYSCALLS.getStreamFromFD(fd); - return FS.createStream(old, 0).fd; + return FS.dupStream(old).fd; } catch (e) { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; return -e.errno; } } - Module["___syscall_dup"] = ___syscall_dup; + Module['___syscall_dup'] = ___syscall_dup; ___syscall_dup.sig = 'ii'; - function ___syscall_dup3(fd, suggestFD, flags) { + function ___syscall_dup3(fd, newfd, flags) { try { var old = SYSCALLS.getStreamFromFD(fd); assert(!flags); - if (old.fd === suggestFD) return -28; - var suggest = FS.getStream(suggestFD); - if (suggest) FS.close(suggest); - return FS.createStream(old, suggestFD, suggestFD + 1).fd; + if (old.fd === newfd) return -28; + var existing = FS.getStream(newfd); + if (existing) FS.close(existing); + return FS.dupStream(old, newfd).fd; } catch (e) { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; return -e.errno; } } - Module["___syscall_dup3"] = ___syscall_dup3; + Module['___syscall_dup3'] = ___syscall_dup3; + ___syscall_dup3.sig = 'iiii'; function ___syscall_faccessat(dirfd, path, amode, flags) { try { @@ -5843,29 +6352,30 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_faccessat"] = ___syscall_faccessat; + Module['___syscall_faccessat'] = ___syscall_faccessat; ___syscall_faccessat.sig = 'iipii'; - function ___syscall_fadvise64(fd, offset, len, advice) { + var ___syscall_fadvise64 = (fd, offset, len, advice) => { return 0; // your advice is important to us (but we can't use it) - } - Module["___syscall_fadvise64"] = ___syscall_fadvise64; + }; + Module['___syscall_fadvise64'] = ___syscall_fadvise64; + ___syscall_fadvise64.sig = 'iiiiiii'; - function convertI32PairToI53Checked(lo, hi) { + + var convertI32PairToI53Checked = (lo, hi) => { assert(lo == (lo >>> 0) || lo == (lo|0)); // lo should either be a i32 or a u32 assert(hi === (hi|0)); // hi should be a i32 return ((hi + 0x200000) >>> 0 < 0x400001 - !!lo) ? (lo >>> 0) + hi * 4294967296 : NaN; - } - Module["convertI32PairToI53Checked"] = convertI32PairToI53Checked; - - - + }; + Module['convertI32PairToI53Checked'] = convertI32PairToI53Checked; + function ___syscall_fallocate(fd,mode,offset_low, offset_high,len_low, len_high) { + var offset = convertI32PairToI53Checked(offset_low, offset_high); + var len = convertI32PairToI53Checked(len_low, len_high); - function ___syscall_fallocate(fd, mode, offset_low, offset_high, len_low, len_high) { + try { - var offset = convertI32PairToI53Checked(offset_low, offset_high); if (isNaN(offset)) return -61; - var len = convertI32PairToI53Checked(len_low, len_high); if (isNaN(len)) return -61; + if (isNaN(offset)) return 61; var stream = SYSCALLS.getStreamFromFD(fd) assert(mode === 0); FS.allocate(stream, offset, len); @@ -5874,8 +6384,10 @@ var ASM_CONSTS = { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; return -e.errno; } + ; } - Module["___syscall_fallocate"] = ___syscall_fallocate; + Module['___syscall_fallocate'] = ___syscall_fallocate; + ___syscall_fallocate.sig = 'iiiiiii'; function ___syscall_fchdir(fd) { try { @@ -5888,7 +6400,8 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_fchdir"] = ___syscall_fchdir; + Module['___syscall_fchdir'] = ___syscall_fchdir; + ___syscall_fchdir.sig = 'ii'; function ___syscall_fchmod(fd, mode) { try { @@ -5900,7 +6413,8 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_fchmod"] = ___syscall_fchmod; + Module['___syscall_fchmod'] = ___syscall_fchmod; + ___syscall_fchmod.sig = 'iii'; function ___syscall_fchmodat(dirfd, path, mode, varargs) { SYSCALLS.varargs = varargs; @@ -5915,7 +6429,7 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_fchmodat"] = ___syscall_fchmodat; + Module['___syscall_fchmodat'] = ___syscall_fchmodat; ___syscall_fchmodat.sig = 'iipip'; function ___syscall_fchown32(fd, owner, group) { @@ -5928,7 +6442,8 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_fchown32"] = ___syscall_fchown32; + Module['___syscall_fchown32'] = ___syscall_fchown32; + ___syscall_fchown32.sig = 'iiii'; function ___syscall_fchownat(dirfd, path, owner, group, flags) { try { @@ -5945,10 +6460,9 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_fchownat"] = ___syscall_fchownat; + Module['___syscall_fchownat'] = ___syscall_fchownat; ___syscall_fchownat.sig = 'iipiii'; - function ___syscall_fcntl64(fd, cmd, varargs) { SYSCALLS.varargs = varargs; try { @@ -5960,8 +6474,11 @@ var ASM_CONSTS = { if (arg < 0) { return -28; } + while (FS.streams[arg]) { + arg++; + } var newStream; - newStream = FS.createStream(stream, arg); + newStream = FS.dupStream(stream, arg); return newStream.fd; } case 1: @@ -5974,39 +6491,24 @@ var ASM_CONSTS = { stream.flags |= arg; return 0; } - case 5: - /* case 5: Currently in musl F_GETLK64 has same value as F_GETLK, so omitted to avoid duplicate case blocks. If that changes, uncomment this */ { - - var arg = SYSCALLS.get(); + case 12: { + var arg = SYSCALLS.getp(); var offset = 0; // We're always unlocked. HEAP16[(((arg)+(offset))>>1)] = 2; return 0; } - case 6: - case 7: - /* case 6: Currently in musl F_SETLK64 has same value as F_SETLK, so omitted to avoid duplicate case blocks. If that changes, uncomment this */ - /* case 7: Currently in musl F_SETLKW64 has same value as F_SETLKW, so omitted to avoid duplicate case blocks. If that changes, uncomment this */ - - + case 13: + case 14: return 0; // Pretend that the locking is successful. - case 16: - case 8: - return -28; // These are for sockets. We don't have them fully implemented yet. - case 9: - // musl trusts getown return values, due to a bug where they must be, as they overlap with errors. just return -1 here, so fcntl() returns that, and we set errno ourselves. - setErrNo(28); - return -1; - default: { - return -28; - } } + return -28; } catch (e) { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; return -e.errno; } } - Module["___syscall_fcntl64"] = ___syscall_fcntl64; + Module['___syscall_fcntl64'] = ___syscall_fcntl64; ___syscall_fcntl64.sig = 'iiip'; function ___syscall_fdatasync(fd) { @@ -6019,7 +6521,8 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_fdatasync"] = ___syscall_fdatasync; + Module['___syscall_fdatasync'] = ___syscall_fdatasync; + ___syscall_fdatasync.sig = 'ii'; function ___syscall_fstat64(fd, buf) { try { @@ -6031,7 +6534,7 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_fstat64"] = ___syscall_fstat64; + Module['___syscall_fstat64'] = ___syscall_fstat64; ___syscall_fstat64.sig = 'iip'; function ___syscall_statfs64(path, size, buf) { @@ -6057,7 +6560,7 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_statfs64"] = ___syscall_statfs64; + Module['___syscall_statfs64'] = ___syscall_statfs64; ___syscall_statfs64.sig = 'ippp'; function ___syscall_fstatfs64(fd, size, buf) { @@ -6070,26 +6573,33 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_fstatfs64"] = ___syscall_fstatfs64; + Module['___syscall_fstatfs64'] = ___syscall_fstatfs64; + ___syscall_fstatfs64.sig = 'iipp'; + function ___syscall_ftruncate64(fd,length_low, length_high) { + var length = convertI32PairToI53Checked(length_low, length_high); - - - - function ___syscall_ftruncate64(fd, length_low, length_high) { + try { - var length = convertI32PairToI53Checked(length_low, length_high); if (isNaN(length)) return -61; + if (isNaN(length)) return 61; FS.ftruncate(fd, length); return 0; } catch (e) { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; return -e.errno; } + ; } - Module["___syscall_ftruncate64"] = ___syscall_ftruncate64; - ___syscall_ftruncate64.sig = 'iij'; + Module['___syscall_ftruncate64'] = ___syscall_ftruncate64; + ___syscall_ftruncate64.sig = 'iiii'; + + var stringToUTF8 = (str, outPtr, maxBytesToWrite) => { + assert(typeof maxBytesToWrite == 'number', 'stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!'); + return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite); + }; + Module['stringToUTF8'] = stringToUTF8; function ___syscall_getcwd(buf, size) { try { @@ -6104,16 +6614,15 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_getcwd"] = ___syscall_getcwd; + Module['___syscall_getcwd'] = ___syscall_getcwd; ___syscall_getcwd.sig = 'ipp'; + function ___syscall_getdents64(fd, dirp, count) { try { var stream = SYSCALLS.getStreamFromFD(fd) - if (!stream.getdents) { - stream.getdents = FS.readdir(stream.path); - } + stream.getdents ||= FS.readdir(stream.path); var struct_size = 280; var pos = 0; @@ -6143,10 +6652,10 @@ var ASM_CONSTS = { 8; // DT_REG, regular file. } assert(id); - (tempI64 = [id>>>0,(tempDouble=id,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[((dirp + pos)>>2)] = tempI64[0],HEAP32[(((dirp + pos)+(4))>>2)] = tempI64[1]); - (tempI64 = [(idx + 1) * struct_size>>>0,(tempDouble=(idx + 1) * struct_size,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((dirp + pos)+(8))>>2)] = tempI64[0],HEAP32[(((dirp + pos)+(12))>>2)] = tempI64[1]); + (tempI64 = [id>>>0,(tempDouble = id,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? (+(Math.floor((tempDouble)/4294967296.0)))>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)], HEAP32[((dirp + pos)>>2)] = tempI64[0],HEAP32[(((dirp + pos)+(4))>>2)] = tempI64[1]); + (tempI64 = [(idx + 1) * struct_size>>>0,(tempDouble = (idx + 1) * struct_size,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? (+(Math.floor((tempDouble)/4294967296.0)))>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)], HEAP32[(((dirp + pos)+(8))>>2)] = tempI64[0],HEAP32[(((dirp + pos)+(12))>>2)] = tempI64[1]); HEAP16[(((dirp + pos)+(16))>>1)] = 280; - HEAP8[(((dirp + pos)+(18))>>0)] = type; + HEAP8[(dirp + pos)+(18)] = type; stringToUTF8(name, dirp + pos + 19, 256); pos += struct_size; idx += 1; @@ -6158,13 +6667,12 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_getdents64"] = ___syscall_getdents64; - ___syscall_getdents64.sig = 'iipi'; + Module['___syscall_getdents64'] = ___syscall_getdents64; + ___syscall_getdents64.sig = 'iipp'; - - function ___syscall_getpeername(fd, addr, addrlen) { + function ___syscall_getpeername(fd, addr, addrlen, d1, d2, d3) { try { var sock = getSocketFromFD(fd); @@ -6179,15 +6687,14 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_getpeername"] = ___syscall_getpeername; + Module['___syscall_getpeername'] = ___syscall_getpeername; + ___syscall_getpeername.sig = 'iippiii'; - - function ___syscall_getsockname(fd, addr, addrlen) { + function ___syscall_getsockname(fd, addr, addrlen, d1, d2, d3) { try { - err("__syscall_getsockname " + fd); var sock = getSocketFromFD(fd); // TODO: sock.saddr should never be undefined, see TODO in websocket_sock_ops.getname var errno = writeSockaddr(addr, sock.family, DNS.lookup_name(sock.saddr || '0.0.0.0'), sock.sport, addrlen); @@ -6198,10 +6705,10 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_getsockname"] = ___syscall_getsockname; + Module['___syscall_getsockname'] = ___syscall_getsockname; + ___syscall_getsockname.sig = 'iippiii'; - - function ___syscall_getsockopt(fd, level, optname, optval, optlen) { + function ___syscall_getsockopt(fd, level, optname, optval, optlen, d1) { try { var sock = getSocketFromFD(fd); @@ -6221,7 +6728,8 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_getsockopt"] = ___syscall_getsockopt; + Module['___syscall_getsockopt'] = ___syscall_getsockopt; + ___syscall_getsockopt.sig = 'iiiippi'; function ___syscall_ioctl(fd, op, varargs) { SYSCALLS.varargs = varargs; @@ -6229,23 +6737,53 @@ var ASM_CONSTS = { var stream = SYSCALLS.getStreamFromFD(fd); switch (op) { - case 21509: + case 21509: { + if (!stream.tty) return -59; + return 0; + } case 21505: { if (!stream.tty) return -59; + if (stream.tty.ops.ioctl_tcgets) { + var termios = stream.tty.ops.ioctl_tcgets(stream); + var argp = SYSCALLS.getp(); + HEAP32[((argp)>>2)] = termios.c_iflag || 0; + HEAP32[(((argp)+(4))>>2)] = termios.c_oflag || 0; + HEAP32[(((argp)+(8))>>2)] = termios.c_cflag || 0; + HEAP32[(((argp)+(12))>>2)] = termios.c_lflag || 0; + for (var i = 0; i < 32; i++) { + HEAP8[(argp + i)+(17)] = termios.c_cc[i] || 0; + } + return 0; + } return 0; } case 21510: case 21511: - case 21512: + case 21512: { + if (!stream.tty) return -59; + return 0; // no-op, not actually adjusting terminal settings + } case 21506: case 21507: case 21508: { if (!stream.tty) return -59; + if (stream.tty.ops.ioctl_tcsets) { + var argp = SYSCALLS.getp(); + var c_iflag = HEAP32[((argp)>>2)]; + var c_oflag = HEAP32[(((argp)+(4))>>2)]; + var c_cflag = HEAP32[(((argp)+(8))>>2)]; + var c_lflag = HEAP32[(((argp)+(12))>>2)]; + var c_cc = [] + for (var i = 0; i < 32; i++) { + c_cc.push(HEAP8[(argp + i)+(17)]); + } + return stream.tty.ops.ioctl_tcsets(stream.tty, op, { c_iflag, c_oflag, c_cflag, c_lflag, c_cc }); + } return 0; // no-op, not actually adjusting terminal settings } case 21519: { if (!stream.tty) return -59; - var argp = SYSCALLS.get(); + var argp = SYSCALLS.getp(); HEAP32[((argp)>>2)] = 0; return 0; } @@ -6254,13 +6792,19 @@ var ASM_CONSTS = { return -28; // not supported } case 21531: { - var argp = SYSCALLS.get(); + var argp = SYSCALLS.getp(); return FS.ioctl(stream, op, argp); } case 21523: { // TODO: in theory we should write to the winsize struct that gets // passed in, but for now musl doesn't read anything on it if (!stream.tty) return -59; + if (stream.tty.ops.ioctl_tiocgwinsz) { + var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty); + var argp = SYSCALLS.getp(); + HEAP16[((argp)>>1)] = winsize[0]; + HEAP16[(((argp)+(2))>>1)] = winsize[1]; + } return 0; } case 21524: { @@ -6270,6 +6814,10 @@ var ASM_CONSTS = { if (!stream.tty) return -59; return 0; } + case 21515: { + if (!stream.tty) return -59; + return 0; + } default: return -28; // not supported } } catch (e) { @@ -6277,15 +6825,9 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_ioctl"] = ___syscall_ioctl; + Module['___syscall_ioctl'] = ___syscall_ioctl; ___syscall_ioctl.sig = 'iiip'; - function ___syscall_linkat(olddirfd, oldpath, newdirfd, newpath, flags) { - return -34; // no hardlinks for us - } - Module["___syscall_linkat"] = ___syscall_linkat; - - function ___syscall_listen(fd, backlog) { try { @@ -6297,7 +6839,8 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_listen"] = ___syscall_listen; + Module['___syscall_listen'] = ___syscall_listen; + ___syscall_listen.sig = 'iiiiiii'; function ___syscall_lstat64(path, buf) { try { @@ -6309,7 +6852,7 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_lstat64"] = ___syscall_lstat64; + Module['___syscall_lstat64'] = ___syscall_lstat64; ___syscall_lstat64.sig = 'ipp'; function ___syscall_mkdirat(dirfd, path, mode) { @@ -6328,7 +6871,7 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_mkdirat"] = ___syscall_mkdirat; + Module['___syscall_mkdirat'] = ___syscall_mkdirat; ___syscall_mkdirat.sig = 'iipi'; function ___syscall_mknodat(dirfd, path, mode, dev) { @@ -6353,7 +6896,7 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_mknodat"] = ___syscall_mknodat; + Module['___syscall_mknodat'] = ___syscall_mknodat; ___syscall_mknodat.sig = 'iipii'; function ___syscall_newfstatat(dirfd, path, buf, flags) { @@ -6363,7 +6906,7 @@ var ASM_CONSTS = { var nofollow = flags & 256; var allowEmpty = flags & 4096; flags = flags & (~6400); - assert(!flags, 'unknown flags in __syscall_newfstatat: ' + flags); + assert(!flags, `unknown flags in __syscall_newfstatat: ${flags}`); path = SYSCALLS.calculateAt(dirfd, path, allowEmpty); return SYSCALLS.doStat(nofollow ? FS.lstat : FS.stat, path, buf); } catch (e) { @@ -6371,7 +6914,7 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_newfstatat"] = ___syscall_newfstatat; + Module['___syscall_newfstatat'] = ___syscall_newfstatat; ___syscall_newfstatat.sig = 'iippi'; function ___syscall_openat(dirfd, path, flags, varargs) { @@ -6387,14 +6930,17 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_openat"] = ___syscall_openat; + Module['___syscall_openat'] = ___syscall_openat; ___syscall_openat.sig = 'iipip'; - var PIPEFS = {BUCKET_BUFFER_SIZE:8192,mount:function (mount) { + var PIPEFS = { + BUCKET_BUFFER_SIZE:8192, + mount(mount) { // Do not pollute the real root directory or its child nodes with pipes // Looks like it is OK to create another pseudo-root node not linked to the FS.root hierarchy this way return FS.createNode(null, '/', 16384 | 511 /* 0777 */, 0); - },createPipe:function () { + }, + createPipe() { var pipe = { buckets: [], // refcnt 2 because pipe has a read end and a write end. We need to be @@ -6438,7 +6984,9 @@ var ASM_CONSTS = { readable_fd: readableStream.fd, writable_fd: writableStream.fd }; - },stream_ops:{poll:function (stream) { + }, + stream_ops:{ + poll(stream) { var pipe = stream.node.pipe; if ((stream.flags & 2097155) === 1) { @@ -6454,11 +7002,14 @@ var ASM_CONSTS = { } return 0; - },ioctl:function (stream, request, varargs) { + }, + ioctl(stream, request, varargs) { return 28; - },fsync:function (stream) { + }, + fsync(stream) { return 28; - },read:function (stream, buffer, offset, length, position /* ignored */) { + }, + read(stream, buffer, offset, length, position /* ignored */) { var pipe = stream.node.pipe; var currentLength = 0; @@ -6516,7 +7067,8 @@ var ASM_CONSTS = { pipe.buckets.splice(0, toRemove); return totalRead; - },write:function (stream, buffer, offset, length, position /* ignored */) { + }, + write(stream, buffer, offset, length, position /* ignored */) { var pipe = stream.node.pipe; assert(buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer)); @@ -6578,20 +7130,23 @@ var ASM_CONSTS = { } return dataLen; - },close:function (stream) { + }, + close(stream) { var pipe = stream.node.pipe; pipe.refcnt--; if (pipe.refcnt === 0) { pipe.buckets = null; } - }},nextname:function () { + }, + }, + nextname() { if (!PIPEFS.nextname.current) { PIPEFS.nextname.current = 0; } return 'pipe[' + (PIPEFS.nextname.current++) + ']'; - }}; - Module["PIPEFS"] = PIPEFS; - + }, + }; + Module['PIPEFS'] = PIPEFS; function ___syscall_pipe(fdPtr) { try { @@ -6610,7 +7165,7 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_pipe"] = ___syscall_pipe; + Module['___syscall_pipe'] = ___syscall_pipe; ___syscall_pipe.sig = 'ip'; function ___syscall_poll(fds, nfds, timeout) { @@ -6626,7 +7181,7 @@ var ASM_CONSTS = { if (stream) { mask = SYSCALLS.DEFAULT_POLLMASK; if (stream.stream_ops.poll) { - mask = stream.stream_ops.poll(stream); + mask = stream.stream_ops.poll(stream, -1); } } mask &= events | 8 | 16; @@ -6639,9 +7194,11 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_poll"] = ___syscall_poll; + Module['___syscall_poll'] = ___syscall_poll; ___syscall_poll.sig = 'ipii'; + + function ___syscall_readlinkat(dirfd, path, buf, bufsize) { try { @@ -6662,12 +7219,11 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_readlinkat"] = ___syscall_readlinkat; - ___syscall_readlinkat.sig = 'vippp'; + Module['___syscall_readlinkat'] = ___syscall_readlinkat; + ___syscall_readlinkat.sig = 'iippp'; - function ___syscall_recvfrom(fd, buf, len, flags, addr, addrlen) { try { @@ -6685,12 +7241,12 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_recvfrom"] = ___syscall_recvfrom; + Module['___syscall_recvfrom'] = ___syscall_recvfrom; + ___syscall_recvfrom.sig = 'iippipp'; - - function ___syscall_recvmsg(fd, message, flags) { + function ___syscall_recvmsg(fd, message, flags, d1, d2, d3) { try { var sock = getSocketFromFD(fd); @@ -6750,7 +7306,8 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_recvmsg"] = ___syscall_recvmsg; + Module['___syscall_recvmsg'] = ___syscall_recvmsg; + ___syscall_recvmsg.sig = 'iipiiii'; function ___syscall_renameat(olddirfd, oldpath, newdirfd, newpath) { try { @@ -6766,7 +7323,7 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_renameat"] = ___syscall_renameat; + Module['___syscall_renameat'] = ___syscall_renameat; ___syscall_renameat.sig = 'iipip'; function ___syscall_rmdir(path) { @@ -6780,13 +7337,12 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_rmdir"] = ___syscall_rmdir; + Module['___syscall_rmdir'] = ___syscall_rmdir; ___syscall_rmdir.sig = 'ip'; - - function ___syscall_sendmsg(fd, message, flags) { + function ___syscall_sendmsg(fd, message, flags, d1, d2, d3) { try { var sock = getSocketFromFD(fd); @@ -6813,7 +7369,7 @@ var ASM_CONSTS = { var iovbase = HEAPU32[(((iov)+((8 * i) + 0))>>2)]; var iovlen = HEAP32[(((iov)+((8 * i) + 4))>>2)]; for (var j = 0; j < iovlen; j++) { - view[offset++] = HEAP8[(((iovbase)+(j))>>0)]; + view[offset++] = HEAP8[(iovbase)+(j)]; } } // write the buffer @@ -6823,10 +7379,10 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_sendmsg"] = ___syscall_sendmsg; + Module['___syscall_sendmsg'] = ___syscall_sendmsg; + ___syscall_sendmsg.sig = 'iipippi'; - function ___syscall_sendto(fd, message, length, flags, addr, addr_len) { try { @@ -6834,19 +7390,18 @@ var ASM_CONSTS = { var dest = getSocketAddress(addr, addr_len, true); if (!dest) { // send, no address provided - return FS.write(sock.stream, HEAP8,message, length); + return FS.write(sock.stream, HEAP8, message, length); } // sendto an address - return sock.sock_ops.sendmsg(sock, HEAP8,message, length, dest.addr, dest.port); + return sock.sock_ops.sendmsg(sock, HEAP8, message, length, dest.addr, dest.port); } catch (e) { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; return -e.errno; } } - Module["___syscall_sendto"] = ___syscall_sendto; - ___syscall_sendto.sig = 'iipiipi'; + Module['___syscall_sendto'] = ___syscall_sendto; + ___syscall_sendto.sig = 'iippipp'; - function ___syscall_socket(domain, type, protocol) { try { @@ -6858,7 +7413,8 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_socket"] = ___syscall_socket; + Module['___syscall_socket'] = ___syscall_socket; + ___syscall_socket.sig = 'iiiiiii'; function ___syscall_stat64(path, buf) { try { @@ -6870,7 +7426,7 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_stat64"] = ___syscall_stat64; + Module['___syscall_stat64'] = ___syscall_stat64; ___syscall_stat64.sig = 'ipp'; @@ -6886,7 +7442,7 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_symlink"] = ___syscall_symlink; + Module['___syscall_symlink'] = ___syscall_symlink; ___syscall_symlink.sig = 'ipp'; function ___syscall_symlinkat(target, newdirfd, linkpath) { @@ -6900,16 +7456,17 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_symlinkat"] = ___syscall_symlinkat; + Module['___syscall_symlinkat'] = ___syscall_symlinkat; + ___syscall_symlinkat.sig = 'ipip'; + function ___syscall_truncate64(path,length_low, length_high) { + var length = convertI32PairToI53Checked(length_low, length_high); - - - function ___syscall_truncate64(path, length_low, length_high) { + try { - var length = convertI32PairToI53Checked(length_low, length_high); if (isNaN(length)) return -61; + if (isNaN(length)) return 61; path = SYSCALLS.getStr(path); FS.truncate(path, length); return 0; @@ -6917,9 +7474,10 @@ var ASM_CONSTS = { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; return -e.errno; } + ; } - Module["___syscall_truncate64"] = ___syscall_truncate64; - ___syscall_truncate64.sig = 'ipj'; + Module['___syscall_truncate64'] = ___syscall_truncate64; + ___syscall_truncate64.sig = 'ipii'; function ___syscall_unlinkat(dirfd, path, flags) { try { @@ -6939,13 +7497,13 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_unlinkat"] = ___syscall_unlinkat; + Module['___syscall_unlinkat'] = ___syscall_unlinkat; ___syscall_unlinkat.sig = 'iipi'; - function readI53FromI64(ptr) { - return HEAPU32[ptr>>2] + HEAP32[ptr+4>>2] * 4294967296; - } - Module["readI53FromI64"] = readI53FromI64; + var readI53FromI64 = (ptr) => { + return HEAPU32[((ptr)>>2)] + HEAP32[(((ptr)+(4))>>2)] * 4294967296; + }; + Module['readI53FromI64'] = readI53FromI64; function ___syscall_utimensat(dirfd, path, times, flags) { try { @@ -6972,67 +7530,51 @@ var ASM_CONSTS = { return -e.errno; } } - Module["___syscall_utimensat"] = ___syscall_utimensat; + Module['___syscall_utimensat'] = ___syscall_utimensat; ___syscall_utimensat.sig = 'iippi'; var ___table_base = new WebAssembly.Global({'value': 'i32', 'mutable': false}, 1); - Module["___table_base"] = ___table_base; + Module['___table_base'] = ___table_base; + var ENV = { + }; + Module['ENV'] = ENV; - var ENV = {}; - Module["ENV"] = ENV; - function allocateUTF8OnStack(str) { + var stringToUTF8OnStack = (str) => { var size = lengthBytesUTF8(str) + 1; var ret = stackAlloc(size); - stringToUTF8Array(str, HEAP8, ret, size); + stringToUTF8(str, ret, size); return ret; - } - Module["allocateUTF8OnStack"] = allocateUTF8OnStack; + }; + Module['stringToUTF8OnStack'] = stringToUTF8OnStack; - function withStackSave(f) { + + var withStackSave = (f) => { var stack = stackSave(); var ret = f(); stackRestore(stack); return ret; - } - Module["withStackSave"] = withStackSave; - function dlSetError(msg) { - withStackSave(function() { - var cmsg = allocateUTF8OnStack(msg); + }; + Module['withStackSave'] = withStackSave; + var dlSetError = (msg) => { + withStackSave(() => { + var cmsg = stringToUTF8OnStack(msg); ___dl_seterr(cmsg, 0); }); - } - Module["dlSetError"] = dlSetError; + }; + Module['dlSetError'] = dlSetError; + - function dlopenInternal(handle, jsflags) { + var dlopenInternal = (handle, jsflags) => { // void *dlopen(const char *file, int mode); // http://pubs.opengroup.org/onlinepubs/009695399/functions/dlopen.html - var filename = UTF8ToString(handle + 28); + var filename = UTF8ToString(handle + 36); var flags = HEAP32[(((handle)+(4))>>2)]; filename = PATH.normalize(filename); var searchpaths = []; - var isValidFile = (filename) => { - var target = FS.findObject(filename); - return target && !target.isFolder && !target.isDevice; - }; - - if (!isValidFile(filename)) { - if (ENV['LD_LIBRARY_PATH']) { - searchpaths = ENV['LD_LIBRARY_PATH'].split(':'); - } - - for (var ident in searchpaths) { - var searchfile = PATH.join2(searchpaths[ident], filename); - if (isValidFile(searchfile)) { - filename = searchfile; - break; - } - } - } - var global = Boolean(flags & 256); var localScope = global ? null : {}; @@ -7041,7 +7583,6 @@ var ASM_CONSTS = { global, nodelete: Boolean(flags & 4096), loadAsync: jsflags.loadAsync, - fs: jsflags.fs, } if (jsflags.loadAsync) { @@ -7051,25 +7592,22 @@ var ASM_CONSTS = { try { return loadDynamicLibrary(filename, combinedFlags, localScope, handle) } catch (e) { - err('Error in loading dynamic library ' + filename + ": " + e); - dlSetError('Could not load dynamic lib: ' + filename + '\n' + e); + err(`Error in loading dynamic library ${filename}: ${e}`); + dlSetError(`Could not load dynamic lib: ${filename}\n${e}`); return 0; } - } - Module["dlopenInternal"] = dlopenInternal; - function __dlopen_js(handle) { - var jsflags = { - loadAsync: false, - fs: FS, // load libraries from provided filesystem - } - return dlopenInternal(handle, jsflags); - } - Module["__dlopen_js"] = __dlopen_js; + }; + Module['dlopenInternal'] = dlopenInternal; + var __dlopen_js = (handle) => { + return dlopenInternal(handle, { loadAsync: false }); + }; + Module['__dlopen_js'] = __dlopen_js; __dlopen_js.sig = 'pp'; - function __dlsym_js(handle, symbol, symbolIndex) { + + var __dlsym_js = (handle, symbol, symbolIndex) => { // void *dlsym(void *restrict handle, const char *restrict name); // http://pubs.opengroup.org/onlinepubs/009695399/functions/dlsym.html symbol = UTF8ToString(symbol); @@ -7077,9 +7615,9 @@ var ASM_CONSTS = { var newSymIndex; var lib = LDSO.loadedLibsByHandle[handle]; - assert(lib, 'Tried to dlsym() from an unopened handle: ' + handle); + assert(lib, `Tried to dlsym() from an unopened handle: ${handle}`); if (!lib.exports.hasOwnProperty(symbol) || lib.exports[symbol].stub) { - dlSetError('Tried to lookup unknown symbol "' + symbol + '" in dynamic lib: ' + lib.name) + dlSetError(`Tried to lookup unknown symbol "${symbol}" in dynamic lib: ${lib.name}`) return 0; } newSymIndex = Object.keys(lib.exports).indexOf(symbol); @@ -7106,18 +7644,12 @@ var ASM_CONSTS = { } } return result; - } - Module["__dlsym_js"] = __dlsym_js; + }; + Module['__dlsym_js'] = __dlsym_js; __dlsym_js.sig = 'pppp'; - function __emscripten_dbg(str) { - dbg(UTF8ToString(str)); - } - Module["__emscripten_dbg"] = __emscripten_dbg; - __emscripten_dbg.sig = 'vp'; - - function handleException(e) { + var handleException = (e) => { // Certain exception types we do not treat as errors since they are used for // internal control flow. // 1. ExitStatus, which is thrown by exit() @@ -7129,44 +7661,51 @@ var ASM_CONSTS = { checkStackCookie(); if (e instanceof WebAssembly.RuntimeError) { if (_emscripten_stack_get_current() <= 0) { - err('Stack overflow detected. You can try increasing -sSTACK_SIZE (currently set to ' + 65536 + ')'); + err('Stack overflow detected. You can try increasing -sSTACK_SIZE (currently set to 65536)'); } } quit_(1, e); - } - Module["handleException"] = handleException; + }; + Module['handleException'] = handleException; - function _proc_exit(code) { + var runtimeKeepaliveCounter = 0; + Module['runtimeKeepaliveCounter'] = runtimeKeepaliveCounter; + var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0; + Module['keepRuntimeAlive'] = keepRuntimeAlive; + var _proc_exit = (code) => { EXITSTATUS = code; if (!keepRuntimeAlive()) { - if (Module['onExit']) Module['onExit'](code); + Module['onExit']?.(code); ABORT = true; } quit_(code, new ExitStatus(code)); - } - Module["_proc_exit"] = _proc_exit; + }; + Module['_proc_exit'] = _proc_exit; _proc_exit.sig = 'vi'; + + /** @suppress {duplicate } */ /** @param {boolean|number=} implicit */ - function exitJS(status, implicit) { + var exitJS = (status, implicit) => { EXITSTATUS = status; checkUnflushedContent(); // if exit() was called explicitly, warn the user if the runtime isn't actually being shut down if (keepRuntimeAlive() && !implicit) { - var msg = 'program exited (with status: ' + status + '), but keepRuntimeAlive() is set (counter=' + runtimeKeepaliveCounter + ') due to an async operation, so halting execution but not exiting the runtime or preventing further async execution (you can use emscripten_force_exit, if you want to force a true shutdown)'; + var msg = `program exited (with status: ${status}), but keepRuntimeAlive() is set (counter=${runtimeKeepaliveCounter}) due to an async operation, so halting execution but not exiting the runtime or preventing further async execution (you can use emscripten_force_exit, if you want to force a true shutdown)`; err(msg); } _proc_exit(status); - } - Module["exitJS"] = exitJS; + }; + Module['exitJS'] = exitJS; var _exit = exitJS; - Module["_exit"] = _exit; + Module['_exit'] = _exit; _exit.sig = 'vi'; - function maybeExit() { + + var maybeExit = () => { if (!keepRuntimeAlive()) { try { _exit(EXITSTATUS); @@ -7174,9 +7713,9 @@ var ASM_CONSTS = { handleException(e); } } - } - Module["maybeExit"] = maybeExit; - function callUserCallback(func) { + }; + Module['maybeExit'] = maybeExit; + var callUserCallback = (func) => { if (ABORT) { err('user callback triggered after runtime exited or application aborted. Ignoring.'); return; @@ -7187,21 +7726,22 @@ var ASM_CONSTS = { } catch (e) { handleException(e); } - } - Module["callUserCallback"] = callUserCallback; + }; + Module['callUserCallback'] = callUserCallback; + - function __emscripten_dlopen_js(handle, onsuccess, onerror, user_data) { + var __emscripten_dlopen_js = (handle, onsuccess, onerror, user_data) => { /** @param {Object=} e */ function errorCallback(e) { - var filename = UTF8ToString(HEAPU32[(((handle)+(28))>>2)]); - dlSetError('Could not load dynamic lib: ' + filename + '\n' + e); + var filename = UTF8ToString(handle + 36); + dlSetError(`'Could not load dynamic lib: ${filename}\n${e}`); - callUserCallback(function () { getWasmTableEntry(onerror)(handle, user_data); }); + callUserCallback(() => getWasmTableEntry(onerror)(handle, user_data)); } function successCallback() { - callUserCallback(function () { getWasmTableEntry(onsuccess)(handle, user_data); }); + callUserCallback(() => getWasmTableEntry(onsuccess)(handle, user_data)); } @@ -7211,46 +7751,102 @@ var ASM_CONSTS = { } else { errorCallback(); } - } - Module["__emscripten_dlopen_js"] = __emscripten_dlopen_js; - __emscripten_dlopen_js.sig = 'vppp'; - - function __emscripten_err(str) { - err(UTF8ToString(str)); - } - Module["__emscripten_err"] = __emscripten_err; - __emscripten_err.sig = 'vp'; + }; + Module['__emscripten_dlopen_js'] = __emscripten_dlopen_js; + __emscripten_dlopen_js.sig = 'vpppp'; - var nowIsMonotonic = true;; - Module["nowIsMonotonic"] = nowIsMonotonic; - function __emscripten_get_now_is_monotonic() { - return nowIsMonotonic; - } - Module["__emscripten_get_now_is_monotonic"] = __emscripten_get_now_is_monotonic; + var nowIsMonotonic = 1; + Module['nowIsMonotonic'] = nowIsMonotonic; + var __emscripten_get_now_is_monotonic = () => nowIsMonotonic; + Module['__emscripten_get_now_is_monotonic'] = __emscripten_get_now_is_monotonic; __emscripten_get_now_is_monotonic.sig = 'i'; - function __emscripten_get_progname(str, len) { + var __emscripten_get_progname = (str, len) => { assert(typeof str == 'number'); assert(typeof len == 'number'); stringToUTF8(thisProgram, str, len); - } - Module["__emscripten_get_progname"] = __emscripten_get_progname; - __emscripten_get_progname.sig = 'vpp'; + }; + Module['__emscripten_get_progname'] = __emscripten_get_progname; + __emscripten_get_progname.sig = 'vpi'; - function __emscripten_out(str) { - out(UTF8ToString(str)); - } - Module["__emscripten_out"] = __emscripten_out; - __emscripten_out.sig = 'vp'; + + + + var __emscripten_lookup_name = (name) => { + // uint32_t _emscripten_lookup_name(const char *name); + var nameString = UTF8ToString(name); + return inetPton4(DNS.lookup_name(nameString)); + }; + Module['__emscripten_lookup_name'] = __emscripten_lookup_name; + __emscripten_lookup_name.sig = 'ip'; - function __emscripten_throw_longjmp() { - throw Infinity; - } - Module["__emscripten_throw_longjmp"] = __emscripten_throw_longjmp; + var __emscripten_runtime_keepalive_clear = () => { + noExitRuntime = false; + runtimeKeepaliveCounter = 0; + }; + Module['__emscripten_runtime_keepalive_clear'] = __emscripten_runtime_keepalive_clear; + __emscripten_runtime_keepalive_clear.sig = 'v'; + + var __emscripten_set_offscreencanvas_size = (target, width, height) => { + err('emscripten_set_offscreencanvas_size: Build with -sOFFSCREENCANVAS_SUPPORT=1 to enable transferring canvases to pthreads.'); + return -1; + }; + Module['__emscripten_set_offscreencanvas_size'] = __emscripten_set_offscreencanvas_size; + __emscripten_set_offscreencanvas_size.sig = 'ipii'; + + var __emscripten_system = (command) => { + if (ENVIRONMENT_IS_NODE) { + if (!command) return 1; // shell is available + + var cmdstr = UTF8ToString(command); + if (!cmdstr.length) return 0; // this is what glibc seems to do (shell works test?) + + var cp = require('child_process'); + var ret = cp.spawnSync(cmdstr, [], {shell:true, stdio:'inherit'}); + + var _W_EXITCODE = (ret, sig) => ((ret) << 8 | (sig)); + + // this really only can happen if process is killed by signal + if (ret.status === null) { + // sadly node doesn't expose such function + var signalToNumber = (sig) => { + // implement only the most common ones, and fallback to SIGINT + switch (sig) { + case 'SIGHUP': return 1; + case 'SIGINT': return 2; + case 'SIGQUIT': return 3; + case 'SIGFPE': return 8; + case 'SIGKILL': return 9; + case 'SIGALRM': return 14; + case 'SIGTERM': return 15; + } + return 2; // SIGINT + } + return _W_EXITCODE(0, signalToNumber(ret.signal)); + } + + return _W_EXITCODE(ret.status, 0); + } + // int system(const char *command); + // http://pubs.opengroup.org/onlinepubs/000095399/functions/system.html + // Can't call external programs. + if (!command) return 0; // no shell available + return -52; + }; + Module['__emscripten_system'] = __emscripten_system; + __emscripten_system.sig = 'ip'; + + var __emscripten_throw_longjmp = () => { + throw Infinity; + }; + Module['__emscripten_throw_longjmp'] = __emscripten_throw_longjmp; __emscripten_throw_longjmp.sig = 'v'; - function __gmtime_js(time, tmPtr) { - var date = new Date(readI53FromI64(time)*1000); + function __gmtime_js(time_low, time_high,tmPtr) { + var time = convertI32PairToI53Checked(time_low, time_high); + + + var date = new Date(time * 1000); HEAP32[((tmPtr)>>2)] = date.getUTCSeconds(); HEAP32[(((tmPtr)+(4))>>2)] = date.getUTCMinutes(); HEAP32[(((tmPtr)+(8))>>2)] = date.getUTCHours(); @@ -7261,31 +7857,33 @@ var ASM_CONSTS = { var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0); var yday = ((date.getTime() - start) / (1000 * 60 * 60 * 24))|0; HEAP32[(((tmPtr)+(28))>>2)] = yday; - } - Module["__gmtime_js"] = __gmtime_js; - __gmtime_js.sig = 'ipp'; + ; + } + Module['__gmtime_js'] = __gmtime_js; + __gmtime_js.sig = 'viip'; + var isLeapYear = (year) => year%4 === 0 && (year%100 !== 0 || year%400 === 0); + Module['isLeapYear'] = isLeapYear; - function __isLeapYear(year) { - return year%4 === 0 && (year%100 !== 0 || year%400 === 0); - } - Module["__isLeapYear"] = __isLeapYear; - - var __MONTH_DAYS_LEAP_CUMULATIVE = [0,31,60,91,121,152,182,213,244,274,305,335]; - Module["__MONTH_DAYS_LEAP_CUMULATIVE"] = __MONTH_DAYS_LEAP_CUMULATIVE; + var MONTH_DAYS_LEAP_CUMULATIVE = [0,31,60,91,121,152,182,213,244,274,305,335]; + Module['MONTH_DAYS_LEAP_CUMULATIVE'] = MONTH_DAYS_LEAP_CUMULATIVE; - var __MONTH_DAYS_REGULAR_CUMULATIVE = [0,31,59,90,120,151,181,212,243,273,304,334]; - Module["__MONTH_DAYS_REGULAR_CUMULATIVE"] = __MONTH_DAYS_REGULAR_CUMULATIVE; - function __yday_from_date(date) { - var isLeapYear = __isLeapYear(date.getFullYear()); - var monthDaysCumulative = (isLeapYear ? __MONTH_DAYS_LEAP_CUMULATIVE : __MONTH_DAYS_REGULAR_CUMULATIVE); + var MONTH_DAYS_REGULAR_CUMULATIVE = [0,31,59,90,120,151,181,212,243,273,304,334]; + Module['MONTH_DAYS_REGULAR_CUMULATIVE'] = MONTH_DAYS_REGULAR_CUMULATIVE; + var ydayFromDate = (date) => { + var leap = isLeapYear(date.getFullYear()); + var monthDaysCumulative = (leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE); var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1; // -1 since it's days since Jan 1 return yday; - } - Module["__yday_from_date"] = __yday_from_date; - function __localtime_js(time, tmPtr) { - var date = new Date(readI53FromI64(time)*1000); + }; + Module['ydayFromDate'] = ydayFromDate; + + function __localtime_js(time_low, time_high,tmPtr) { + var time = convertI32PairToI53Checked(time_low, time_high); + + + var date = new Date(time*1000); HEAP32[((tmPtr)>>2)] = date.getSeconds(); HEAP32[(((tmPtr)+(4))>>2)] = date.getMinutes(); HEAP32[(((tmPtr)+(8))>>2)] = date.getHours(); @@ -7294,7 +7892,7 @@ var ASM_CONSTS = { HEAP32[(((tmPtr)+(20))>>2)] = date.getFullYear()-1900; HEAP32[(((tmPtr)+(24))>>2)] = date.getDay(); - var yday = __yday_from_date(date)|0; + var yday = ydayFromDate(date)|0; HEAP32[(((tmPtr)+(28))>>2)] = yday; HEAP32[(((tmPtr)+(36))>>2)] = -(date.getTimezoneOffset() * 60); @@ -7304,11 +7902,16 @@ var ASM_CONSTS = { var winterOffset = start.getTimezoneOffset(); var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset))|0; HEAP32[(((tmPtr)+(32))>>2)] = dst; - } - Module["__localtime_js"] = __localtime_js; - __localtime_js.sig = 'ipp'; + ; + } + Module['__localtime_js'] = __localtime_js; + __localtime_js.sig = 'viip'; - function __mktime_js(tmPtr) { + + + var __mktime_js = function(tmPtr) { + + var ret = (() => { var date = new Date(HEAP32[(((tmPtr)+(20))>>2)] + 1900, HEAP32[(((tmPtr)+(16))>>2)], HEAP32[(((tmPtr)+(12))>>2)], @@ -7337,7 +7940,7 @@ var ASM_CONSTS = { } HEAP32[(((tmPtr)+(24))>>2)] = date.getDay(); - var yday = __yday_from_date(date)|0; + var yday = ydayFromDate(date)|0; HEAP32[(((tmPtr)+(28))>>2)] = yday; // To match expected behavior, update fields from date HEAP32[((tmPtr)>>2)] = date.getSeconds(); @@ -7347,18 +7950,32 @@ var ASM_CONSTS = { HEAP32[(((tmPtr)+(16))>>2)] = date.getMonth(); HEAP32[(((tmPtr)+(20))>>2)] = date.getYear(); - return (date.getTime() / 1000)|0; - } - Module["__mktime_js"] = __mktime_js; + var timeMs = date.getTime(); + if (isNaN(timeMs)) { + return -1; + } + // Return time in microseconds + return timeMs / 1000; + })(); + return (setTempRet0((tempDouble = ret,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? (+(Math.floor((tempDouble)/4294967296.0)))>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)), ret>>>0); + }; + Module['__mktime_js'] = __mktime_js; __mktime_js.sig = 'ip'; - function __mmap_js(len, prot, flags, fd, off, allocated, addr) { + + + + function __mmap_js(len,prot,flags,fd,offset_low, offset_high,allocated,addr) { + var offset = convertI32PairToI53Checked(offset_low, offset_high); + + try { + if (isNaN(offset)) return 61; var stream = SYSCALLS.getStreamFromFD(fd); - var res = FS.mmap(stream, len, off, prot, flags); + var res = FS.mmap(stream, len, offset, prot, flags); var ptr = res.ptr; HEAP32[((allocated)>>2)] = res.allocated; HEAPU32[((addr)>>2)] = ptr; @@ -7367,57 +7984,65 @@ var ASM_CONSTS = { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; return -e.errno; } + ; } - Module["__mmap_js"] = __mmap_js; - __mmap_js.sig = 'ipiiippp'; + Module['__mmap_js'] = __mmap_js; + __mmap_js.sig = 'ipiiiiipp'; - function __msync_js(addr, len, prot, flags, fd, offset) { + + function __msync_js(addr,len,prot,flags,fd,offset_low, offset_high) { + var offset = convertI32PairToI53Checked(offset_low, offset_high); + + try { - SYSCALLS.doMsync(addr, SYSCALLS.getStreamFromFD(fd), len, flags, 0); + if (isNaN(offset)) return 61; + SYSCALLS.doMsync(addr, SYSCALLS.getStreamFromFD(fd), len, flags, offset); return 0; } catch (e) { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; return -e.errno; } + ; } - Module["__msync_js"] = __msync_js; - __msync_js.sig = 'ippiiip'; + Module['__msync_js'] = __msync_js; + __msync_js.sig = 'ippiiiii'; + function __munmap_js(addr,len,prot,flags,fd,offset_low, offset_high) { + var offset = convertI32PairToI53Checked(offset_low, offset_high); - function __munmap_js(addr, len, prot, flags, fd, offset) { + try { var stream = SYSCALLS.getStreamFromFD(fd); if (prot & 2) { SYSCALLS.doMsync(addr, stream, len, flags, offset); } - FS.munmap(stream); - // implicitly return 0 } catch (e) { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; return -e.errno; } + ; } - Module["__munmap_js"] = __munmap_js; - __munmap_js.sig = 'ippiiip'; + Module['__munmap_js'] = __munmap_js; + __munmap_js.sig = 'ippiiiii'; - var timers = {}; - Module["timers"] = timers; + var timers = { + }; + Module['timers'] = timers; - var _emscripten_get_now;if (ENVIRONMENT_IS_NODE) { - _emscripten_get_now = () => { - var t = process.hrtime(); - return t[0] * 1e3 + t[1] / 1e6; - }; - } else _emscripten_get_now = () => performance.now(); + var _emscripten_get_now; + // Modern environment where performance.now() is supported: + // N.B. a shorter form "_emscripten_get_now = performance.now;" is + // unfortunately not allowed even in current browsers (e.g. FF Nightly 75). + _emscripten_get_now = () => performance.now(); ; - Module["_emscripten_get_now"] = _emscripten_get_now; + Module['_emscripten_get_now'] = _emscripten_get_now; _emscripten_get_now.sig = 'd'; - function __setitimer_js(which, timeout_ms) { + var __setitimer_js = (which, timeout_ms) => { // First, clear any existing timer. if (timers[which]) { clearTimeout(timers[which].id); @@ -7433,13 +8058,16 @@ var ASM_CONSTS = { delete timers[which]; callUserCallback(() => __emscripten_timeout(which, _emscripten_get_now())); }, timeout_ms); - timers[which] = { id: id, timeout_ms: timeout_ms }; + timers[which] = { id, timeout_ms }; return 0; - } - Module["__setitimer_js"] = __setitimer_js; + }; + Module['__setitimer_js'] = __setitimer_js; __setitimer_js.sig = 'iid'; - function __timegm_js(tmPtr) { + + var __timegm_js = function(tmPtr) { + + var ret = (() => { var time = Date.UTC(HEAP32[(((tmPtr)+(20))>>2)] + 1900, HEAP32[(((tmPtr)+(16))>>2)], HEAP32[(((tmPtr)+(12))>>2)], @@ -7454,19 +8082,14 @@ var ASM_CONSTS = { var yday = ((date.getTime() - start) / (1000 * 60 * 60 * 24))|0; HEAP32[(((tmPtr)+(28))>>2)] = yday; - return (date.getTime() / 1000)|0; - } - Module["__timegm_js"] = __timegm_js; + return date.getTime() / 1000; + })(); + return (setTempRet0((tempDouble = ret,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? (+(Math.floor((tempDouble)/4294967296.0)))>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)), ret>>>0); + }; + Module['__timegm_js'] = __timegm_js; __timegm_js.sig = 'ip'; - function allocateUTF8(str) { - var size = lengthBytesUTF8(str) + 1; - var ret = _malloc(size); - if (ret) stringToUTF8Array(str, HEAP8, ret, size); - return ret; - } - Module["allocateUTF8"] = allocateUTF8; - function __tzset_js(timezone, daylight, tzname) { + var __tzset_js = (timezone, daylight, std_name, dst_name) => { // TODO: Use (malleable) environment variables instead of system settings. var currentYear = new Date().getFullYear(); var winter = new Date(currentYear, 0, 1); @@ -7474,9 +8097,12 @@ var ASM_CONSTS = { var winterOffset = winter.getTimezoneOffset(); var summerOffset = summer.getTimezoneOffset(); - // Local standard timezone offset. Local standard time is not adjusted for daylight savings. - // This code uses the fact that getTimezoneOffset returns a greater value during Standard Time versus Daylight Saving Time (DST). - // Thus it determines the expected output during Standard Time, and it compares whether the output of the given date the same (Standard) or less (DST). + // Local standard timezone offset. Local standard time is not adjusted for + // daylight savings. This code uses the fact that getTimezoneOffset returns + // a greater value during Standard Time versus Daylight Saving Time (DST). + // Thus it determines the expected output during Standard Time, and it + // compares whether the output of the given date the same (Standard) or less + // (DST). var stdTimezoneOffset = Math.max(winterOffset, summerOffset); // timezone is specified as seconds west of UTC ("The external variable @@ -7494,27 +8120,25 @@ var ASM_CONSTS = { }; var winterName = extractZone(winter); var summerName = extractZone(summer); - var winterNamePtr = allocateUTF8(winterName); - var summerNamePtr = allocateUTF8(summerName); if (summerOffset < winterOffset) { // Northern hemisphere - HEAPU32[((tzname)>>2)] = winterNamePtr; - HEAPU32[(((tzname)+(4))>>2)] = summerNamePtr; + stringToUTF8(winterName, std_name, 7); + stringToUTF8(summerName, dst_name, 7); } else { - HEAPU32[((tzname)>>2)] = summerNamePtr; - HEAPU32[(((tzname)+(4))>>2)] = winterNamePtr; + stringToUTF8(winterName, dst_name, 7); + stringToUTF8(summerName, std_name, 7); } - } - Module["__tzset_js"] = __tzset_js; - __tzset_js.sig = 'vppp'; + }; + Module['__tzset_js'] = __tzset_js; + __tzset_js.sig = 'vpppp'; - function _abort() { + var _abort = () => { abort('native code called abort()'); - } - Module["_abort"] = _abort; + }; + Module['_abort'] = _abort; _abort.sig = 'v'; - function _emscripten_set_main_loop_timing(mode, value) { + var _emscripten_set_main_loop_timing = (mode, value) => { Browser.mainLoop.timingMode = mode; Browser.mainLoop.timingValue = value; @@ -7527,49 +8151,53 @@ var ASM_CONSTS = { Browser.mainLoop.running = true; } - if (mode == 0 /*EM_TIMING_SETTIMEOUT*/) { + if (mode == 0) { Browser.mainLoop.scheduler = function Browser_mainLoop_scheduler_setTimeout() { var timeUntilNextTick = Math.max(0, Browser.mainLoop.tickStartTime + value - _emscripten_get_now())|0; setTimeout(Browser.mainLoop.runner, timeUntilNextTick); // doing this each time means that on exception, we stop }; Browser.mainLoop.method = 'timeout'; - } else if (mode == 1 /*EM_TIMING_RAF*/) { + } else if (mode == 1) { Browser.mainLoop.scheduler = function Browser_mainLoop_scheduler_rAF() { Browser.requestAnimationFrame(Browser.mainLoop.runner); }; Browser.mainLoop.method = 'rAF'; - } else if (mode == 2 /*EM_TIMING_SETIMMEDIATE*/) { - if (typeof setImmediate == 'undefined') { - // Emulate setImmediate. (note: not a complete polyfill, we don't emulate clearImmediate() to keep code size to minimum, since not needed) - var setImmediates = []; - var emscriptenMainLoopMessageId = 'setimmediate'; - /** @param {Event} event */ - var Browser_setImmediate_messageHandler = (event) => { - // When called in current thread or Worker, the main loop ID is structured slightly different to accommodate for --proxy-to-worker runtime listening to Worker events, - // so check for both cases. - if (event.data === emscriptenMainLoopMessageId || event.data.target === emscriptenMainLoopMessageId) { - event.stopPropagation(); - setImmediates.shift()(); - } - }; - addEventListener("message", Browser_setImmediate_messageHandler, true); - setImmediate = /** @type{function(function(): ?, ...?): number} */(function Browser_emulated_setImmediate(func) { - setImmediates.push(func); - if (ENVIRONMENT_IS_WORKER) { - if (Module['setImmediates'] === undefined) Module['setImmediates'] = []; - Module['setImmediates'].push(func); - postMessage({target: emscriptenMainLoopMessageId}); // In --proxy-to-worker, route the message via proxyClient.js - } else postMessage(emscriptenMainLoopMessageId, "*"); // On the main thread, can just send the message to itself. - }) + } else if (mode == 2) { + if (typeof Browser.setImmediate == 'undefined') { + if (typeof setImmediate == 'undefined') { + // Emulate setImmediate. (note: not a complete polyfill, we don't emulate clearImmediate() to keep code size to minimum, since not needed) + var setImmediates = []; + var emscriptenMainLoopMessageId = 'setimmediate'; + /** @param {Event} event */ + var Browser_setImmediate_messageHandler = (event) => { + // When called in current thread or Worker, the main loop ID is structured slightly different to accommodate for --proxy-to-worker runtime listening to Worker events, + // so check for both cases. + if (event.data === emscriptenMainLoopMessageId || event.data.target === emscriptenMainLoopMessageId) { + event.stopPropagation(); + setImmediates.shift()(); + } + }; + addEventListener("message", Browser_setImmediate_messageHandler, true); + Browser.setImmediate = /** @type{function(function(): ?, ...?): number} */(function Browser_emulated_setImmediate(func) { + setImmediates.push(func); + if (ENVIRONMENT_IS_WORKER) { + if (Module['setImmediates'] === undefined) Module['setImmediates'] = []; + Module['setImmediates'].push(func); + postMessage({target: emscriptenMainLoopMessageId}); // In --proxy-to-worker, route the message via proxyClient.js + } else postMessage(emscriptenMainLoopMessageId, "*"); // On the main thread, can just send the message to itself. + }); + } else { + Browser.setImmediate = setImmediate; + } } Browser.mainLoop.scheduler = function Browser_mainLoop_scheduler_setImmediate() { - setImmediate(Browser.mainLoop.runner); + Browser.setImmediate(Browser.mainLoop.runner); }; Browser.mainLoop.method = 'immediate'; } return 0; - } - Module["_emscripten_set_main_loop_timing"] = _emscripten_set_main_loop_timing; + }; + Module['_emscripten_set_main_loop_timing'] = _emscripten_set_main_loop_timing; _emscripten_set_main_loop_timing.sig = 'iii'; @@ -7578,13 +8206,21 @@ var ASM_CONSTS = { * @param {number=} arg * @param {boolean=} noSetTiming */ - function setMainLoop(browserIterationFunc, fps, simulateInfiniteLoop, arg, noSetTiming) { + var setMainLoop = (browserIterationFunc, fps, simulateInfiniteLoop, arg, noSetTiming) => { assert(!Browser.mainLoop.func, 'emscripten_set_main_loop: there can only be one main loop function at once: call emscripten_cancel_main_loop to cancel the previous one before setting a new one with different parameters.'); - Browser.mainLoop.func = browserIterationFunc; Browser.mainLoop.arg = arg; - var thisMainLoopId = Browser.mainLoop.currentlyRunningMainloop; + // Closure compiler bug(?): Closure does not see that the assignment + // var thisMainLoopId = Browser.mainLoop.currentlyRunningMainloop + // is a value copy of a number (even with the JSDoc @type annotation) + // but optimizeis the code as if the assignment was a reference assignment, + // which results in Browser.mainLoop.pause() not working. Hence use a + // workaround to make Closure believe this is a value copy that should occur: + // (TODO: Minimize this down to a small test case and report - was unable + // to reproduce in a small written test case) + /** @type{number} */ + var thisMainLoopId = (() => Browser.mainLoop.currentlyRunningMainloop)(); function checkIsRunning() { if (thisMainLoopId < Browser.mainLoop.currentlyRunningMainloop) { @@ -7616,7 +8252,6 @@ var ASM_CONSTS = { Browser.mainLoop.remainingBlockers = (8*remaining + next)/9; } } - out('main loop blocker "' + blocker.name + '" took ' + (Date.now() - start) + ' ms'); //, left: ' + Browser.mainLoop.remainingBlockers); Browser.mainLoop.updateStatus(); // catches pause/resume main loop from blocker execution @@ -7631,11 +8266,11 @@ var ASM_CONSTS = { // Implement very basic swap interval control Browser.mainLoop.currentFrameNumber = Browser.mainLoop.currentFrameNumber + 1 | 0; - if (Browser.mainLoop.timingMode == 1/*EM_TIMING_RAF*/ && Browser.mainLoop.timingValue > 1 && Browser.mainLoop.currentFrameNumber % Browser.mainLoop.timingValue != 0) { + if (Browser.mainLoop.timingMode == 1 && Browser.mainLoop.timingValue > 1 && Browser.mainLoop.currentFrameNumber % Browser.mainLoop.timingValue != 0) { // Not the scheduled time to render this frame - skip. Browser.mainLoop.scheduler(); return; - } else if (Browser.mainLoop.timingMode == 0/*EM_TIMING_SETTIMEOUT*/) { + } else if (Browser.mainLoop.timingMode == 0) { Browser.mainLoop.tickStartTime = _emscripten_get_now(); } @@ -7658,14 +8293,18 @@ var ASM_CONSTS = { // to queue the newest produced audio samples. // TODO: Consider adding pre- and post- rAF callbacks so that GL.newRenderingFrameStarted() and SDL.audio.queueNewAudioData() // do not need to be hardcoded into this function, but can be more generic. - if (typeof SDL == 'object' && SDL.audio && SDL.audio.queueNewAudioData) SDL.audio.queueNewAudioData(); + if (typeof SDL == 'object') SDL.audio?.queueNewAudioData?.(); Browser.mainLoop.scheduler(); } if (!noSetTiming) { - if (fps && fps > 0) _emscripten_set_main_loop_timing(0/*EM_TIMING_SETTIMEOUT*/, 1000.0 / fps); - else _emscripten_set_main_loop_timing(1/*EM_TIMING_RAF*/, 1); // Do rAF by rendering each frame (no decimating) + if (fps && fps > 0) { + _emscripten_set_main_loop_timing(0, 1000.0 / fps); + } else { + // Do rAF by rendering each frame (no decimating) + _emscripten_set_main_loop_timing(1, 1); + } Browser.mainLoop.scheduler(); } @@ -7673,27 +8312,42 @@ var ASM_CONSTS = { if (simulateInfiniteLoop) { throw 'unwind'; } - } - Module["setMainLoop"] = setMainLoop; + }; + Module['setMainLoop'] = setMainLoop; /** @param {number=} timeout */ - function safeSetTimeout(func, timeout) { + var safeSetTimeout = (func, timeout) => { - return setTimeout(function() { + return setTimeout(() => { callUserCallback(func); }, timeout); - } - Module["safeSetTimeout"] = safeSetTimeout; + }; + Module['safeSetTimeout'] = safeSetTimeout; - var Browser = {mainLoop:{running:false,scheduler:null,method:"",currentlyRunningMainloop:0,func:null,arg:0,timingMode:0,timingValue:0,currentFrameNumber:0,queue:[],pause:function() { + + + var Browser = { + mainLoop:{ + running:false, + scheduler:null, + method:"", + currentlyRunningMainloop:0, + func:null, + arg:0, + timingMode:0, + timingValue:0, + currentFrameNumber:0, + queue:[], + pause() { Browser.mainLoop.scheduler = null; // Incrementing this signals the previous main loop that it's now become old, and it must return. Browser.mainLoop.currentlyRunningMainloop++; - },resume:function() { + }, + resume() { Browser.mainLoop.currentlyRunningMainloop++; var timingMode = Browser.mainLoop.timingMode; var timingValue = Browser.mainLoop.timingValue; @@ -7703,14 +8357,15 @@ var ASM_CONSTS = { setMainLoop(func, 0, false, Browser.mainLoop.arg, true); _emscripten_set_main_loop_timing(timingMode, timingValue); Browser.mainLoop.scheduler(); - },updateStatus:function() { + }, + updateStatus() { if (Module['setStatus']) { var message = Module['statusMessage'] || 'Please wait...'; var remaining = Browser.mainLoop.remainingBlockers; var expected = Browser.mainLoop.expectedBlockers; if (remaining) { if (remaining < expected) { - Module['setStatus'](message + ' (' + (expected - remaining) + '/' + expected + ')'); + Module['setStatus'](`{message} ({expected - remaining}/{expected})`); } else { Module['setStatus'](message); } @@ -7718,7 +8373,8 @@ var ASM_CONSTS = { Module['setStatus'](''); } } - },runIter:function(func) { + }, + runIter(func) { if (ABORT) return; if (Module['preMainLoop']) { var preRet = Module['preMainLoop'](); @@ -7727,29 +8383,19 @@ var ASM_CONSTS = { } } callUserCallback(func); - if (Module['postMainLoop']) Module['postMainLoop'](); - }},isFullscreen:false,pointerLock:false,moduleContextCreatedCallbacks:[],workers:[],init:function() { - if (!Module["preloadPlugins"]) Module["preloadPlugins"] = []; // needs to exist even in workers - + Module['postMainLoop']?.(); + }, + }, + isFullscreen:false, + pointerLock:false, + moduleContextCreatedCallbacks:[], + workers:[], + init() { if (Browser.initted) return; Browser.initted = true; - try { - new Blob(); - Browser.hasBlobConstructor = true; - } catch(e) { - Browser.hasBlobConstructor = false; - err("warning: no blob constructor, cannot create blobs with mimetypes"); - } - Browser.BlobBuilder = typeof MozBlobBuilder != "undefined" ? MozBlobBuilder : (typeof WebKitBlobBuilder != "undefined" ? WebKitBlobBuilder : (!Browser.hasBlobConstructor ? err("warning: no BlobBuilder") : null)); - Browser.URLObject = typeof window != "undefined" ? (window.URL ? window.URL : window.webkitURL) : undefined; - if (!Module.noImageDecoding && typeof Browser.URLObject == 'undefined') { - err("warning: Browser does not support creating object URLs. Built-in browser image decoding will not be available."); - Module.noImageDecoding = true; - } - // Support for plugins that can process preloaded files. You can add more of these to - // your app by creating and appending to Module.preloadPlugins. + // your app by creating and appending to preloadPlugins. // // Each plugin is asked if it can handle a file based on the file's name. If it can, // it is given the file's raw data. When it is done, it calls a callback with the file's @@ -7761,44 +8407,32 @@ var ASM_CONSTS = { return !Module.noImageDecoding && /\.(jpg|jpeg|png|bmp)$/i.test(name); }; imagePlugin['handle'] = function imagePlugin_handle(byteArray, name, onload, onerror) { - var b = null; - if (Browser.hasBlobConstructor) { - try { - b = new Blob([byteArray], { type: Browser.getMimetype(name) }); - if (b.size !== byteArray.length) { // Safari bug #118630 - // Safari's Blob can only take an ArrayBuffer - b = new Blob([(new Uint8Array(byteArray)).buffer], { type: Browser.getMimetype(name) }); - } - } catch(e) { - warnOnce('Blob constructor present but fails: ' + e + '; falling back to blob builder'); - } + var b = new Blob([byteArray], { type: Browser.getMimetype(name) }); + if (b.size !== byteArray.length) { // Safari bug #118630 + // Safari's Blob can only take an ArrayBuffer + b = new Blob([(new Uint8Array(byteArray)).buffer], { type: Browser.getMimetype(name) }); } - if (!b) { - var bb = new Browser.BlobBuilder(); - bb.append((new Uint8Array(byteArray)).buffer); // we need to pass a buffer, and must copy the array to get the right data range - b = bb.getBlob(); - } - var url = Browser.URLObject.createObjectURL(b); + var url = URL.createObjectURL(b); assert(typeof url == 'string', 'createObjectURL must return a url as a string'); var img = new Image(); img.onload = () => { - assert(img.complete, 'Image ' + name + ' could not be decoded'); + assert(img.complete, `Image ${name} could not be decoded`); var canvas = /** @type {!HTMLCanvasElement} */ (document.createElement('canvas')); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); preloadedImages[name] = canvas; - Browser.URLObject.revokeObjectURL(url); - if (onload) onload(byteArray); + URL.revokeObjectURL(url); + onload?.(byteArray); }; img.onerror = (event) => { - out('Image ' + url + ' could not be decoded'); - if (onerror) onerror(); + err(`Image ${url} could not be decoded`); + onerror?.(); }; img.src = url; }; - Module['preloadPlugins'].push(imagePlugin); + preloadPlugins.push(imagePlugin); var audioPlugin = {}; audioPlugin['canHandle'] = function audioPlugin_canHandle(name) { @@ -7810,89 +8444,56 @@ var ASM_CONSTS = { if (done) return; done = true; preloadedAudios[name] = audio; - if (onload) onload(byteArray); + onload?.(byteArray); } function fail() { if (done) return; done = true; preloadedAudios[name] = new Audio(); // empty shim - if (onerror) onerror(); + onerror?.(); } - if (Browser.hasBlobConstructor) { - try { - var b = new Blob([byteArray], { type: Browser.getMimetype(name) }); - } catch(e) { - return fail(); - } - var url = Browser.URLObject.createObjectURL(b); // XXX we never revoke this! - assert(typeof url == 'string', 'createObjectURL must return a url as a string'); - var audio = new Audio(); - audio.addEventListener('canplaythrough', () => finish(audio), false); // use addEventListener due to chromium bug 124926 - audio.onerror = function audio_onerror(event) { - if (done) return; - err('warning: browser could not fully decode audio ' + name + ', trying slower base64 approach'); - function encode64(data) { - var BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - var PAD = '='; - var ret = ''; - var leftchar = 0; - var leftbits = 0; - for (var i = 0; i < data.length; i++) { - leftchar = (leftchar << 8) | data[i]; - leftbits += 8; - while (leftbits >= 6) { - var curr = (leftchar >> (leftbits-6)) & 0x3f; - leftbits -= 6; - ret += BASE[curr]; - } - } - if (leftbits == 2) { - ret += BASE[(leftchar&3) << 4]; - ret += PAD + PAD; - } else if (leftbits == 4) { - ret += BASE[(leftchar&0xf) << 2]; - ret += PAD; + var b = new Blob([byteArray], { type: Browser.getMimetype(name) }); + var url = URL.createObjectURL(b); // XXX we never revoke this! + assert(typeof url == 'string', 'createObjectURL must return a url as a string'); + var audio = new Audio(); + audio.addEventListener('canplaythrough', () => finish(audio), false); // use addEventListener due to chromium bug 124926 + audio.onerror = function audio_onerror(event) { + if (done) return; + err(`warning: browser could not fully decode audio ${name}, trying slower base64 approach`); + function encode64(data) { + var BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + var PAD = '='; + var ret = ''; + var leftchar = 0; + var leftbits = 0; + for (var i = 0; i < data.length; i++) { + leftchar = (leftchar << 8) | data[i]; + leftbits += 8; + while (leftbits >= 6) { + var curr = (leftchar >> (leftbits-6)) & 0x3f; + leftbits -= 6; + ret += BASE[curr]; } - return ret; } - audio.src = 'data:audio/x-' + name.substr(-3) + ';base64,' + encode64(byteArray); - finish(audio); // we don't wait for confirmation this worked - but it's worth trying - }; - audio.src = url; - // workaround for chrome bug 124926 - we do not always get oncanplaythrough or onerror - safeSetTimeout(function() { - finish(audio); // try to use it even though it is not necessarily ready to play - }, 10000); - } else { - return fail(); - } - }; - Module['preloadPlugins'].push(audioPlugin); - - // Use string keys here to avoid minification since the plugin consumer - // also uses string keys. - var wasmPlugin = { - 'promiseChainEnd': Promise.resolve(), - 'canHandle': function(name) { - return !Module.noWasmDecoding && name.endsWith('.so') - }, - 'handle': function(byteArray, name, onload, onerror) { - // loadWebAssemblyModule can not load modules out-of-order, so rather - // than just running the promises in parallel, this makes a chain of - // promises to run in series. - wasmPlugin['promiseChainEnd'] = wasmPlugin['promiseChainEnd'].then( - () => loadWebAssemblyModule(byteArray, {loadAsync: true, nodelete: true})).then( - (module) => { - preloadedWasm[name] = module; - onload(); - }, - (err) => { - console.warn("Couldn't instantiate wasm: " + name + " '" + err + "'"); - onerror(); - }); - } + if (leftbits == 2) { + ret += BASE[(leftchar&3) << 4]; + ret += PAD + PAD; + } else if (leftbits == 4) { + ret += BASE[(leftchar&0xf) << 2]; + ret += PAD; + } + return ret; + } + audio.src = 'data:audio/x-' + name.substr(-3) + ';base64,' + encode64(byteArray); + finish(audio); // we don't wait for confirmation this worked - but it's worth trying + }; + audio.src = url; + // workaround for chrome bug 124926 - we do not always get oncanplaythrough or onerror + safeSetTimeout(() => { + finish(audio); // try to use it even though it is not necessarily ready to play + }, 10000); }; - Module['preloadPlugins'].push(wasmPlugin); + preloadPlugins.push(audioPlugin); // Canvas event setup @@ -7933,20 +8534,8 @@ var ASM_CONSTS = { }, false); } } - },handledByPreloadPlugin:function(byteArray, fullname, finish, onerror) { - // Ensure plugins are ready. - Browser.init(); - - var handled = false; - Module['preloadPlugins'].forEach(function(plugin) { - if (handled) return; - if (plugin['canHandle'](fullname)) { - plugin['handle'](byteArray, fullname, finish, onerror); - handled = true; - } - }); - return handled; - },createContext:function(/** @type {HTMLCanvasElement} */ canvas, useWebGL, setInModule, webGLContextAttributes) { + }, + createContext(/** @type {HTMLCanvasElement} */ canvas, useWebGL, setInModule, webGLContextAttributes) { if (useWebGL && Module.ctx && canvas == Module.canvas) return Module.ctx; // no need to recreate GL context if it's already been created for this canvas. var ctx; @@ -7982,15 +8571,19 @@ var ASM_CONSTS = { if (setInModule) { if (!useWebGL) assert(typeof GLctx == 'undefined', 'cannot set in module if GLctx is used, but we are a non-GL context that would replace it'); - Module.ctx = ctx; if (useWebGL) GL.makeContextCurrent(contextHandle); Module.useWebGL = useWebGL; - Browser.moduleContextCreatedCallbacks.forEach(function(callback) { callback() }); + Browser.moduleContextCreatedCallbacks.forEach((callback) => callback()); Browser.init(); } return ctx; - },destroyContext:function(canvas, useWebGL, setInModule) {},fullscreenHandlersInstalled:false,lockPointer:undefined,resizeCanvas:undefined,requestFullscreen:function(lockPointer, resizeCanvas) { + }, + destroyContext(canvas, useWebGL, setInModule) {}, + fullscreenHandlersInstalled:false, + lockPointer:undefined, + resizeCanvas:undefined, + requestFullscreen(lockPointer, resizeCanvas) { Browser.lockPointer = lockPointer; Browser.resizeCanvas = resizeCanvas; if (typeof Browser.lockPointer == 'undefined') Browser.lockPointer = true; @@ -8022,8 +8615,8 @@ var ASM_CONSTS = { Browser.updateCanvasDimensions(canvas); } } - if (Module['onFullScreen']) Module['onFullScreen'](Browser.isFullscreen); - if (Module['onFullscreen']) Module['onFullscreen'](Browser.isFullscreen); + Module['onFullScreen']?.(Browser.isFullscreen); + Module['onFullscreen']?.(Browser.isFullscreen); } if (!Browser.fullscreenHandlersInstalled) { @@ -8047,9 +8640,11 @@ var ASM_CONSTS = { (canvasContainer['webkitRequestFullScreen'] ? () => canvasContainer['webkitRequestFullScreen'](Element['ALLOW_KEYBOARD_INPUT']) : null); canvasContainer.requestFullscreen(); - },requestFullScreen:function() { + }, + requestFullScreen() { abort('Module.requestFullScreen has been replaced by Module.requestFullscreen (without a capital S)'); - },exitFullscreen:function() { + }, + exitFullscreen() { // This is workaround for chrome. Trying to exit from fullscreen // not in fullscreen state will cause "TypeError: Document not active" // in chrome. See https://github.com/emscripten-core/emscripten/pull/8236 @@ -8062,10 +8657,12 @@ var ASM_CONSTS = { document['mozCancelFullScreen'] || document['msExitFullscreen'] || document['webkitCancelFullScreen'] || - (function() {}); + (() => {}); CFS.apply(document, []); return true; - },nextRAF:0,fakeRequestAnimationFrame:function(func) { + }, + nextRAF:0, + fakeRequestAnimationFrame(func) { // try to keep 60fps between calls to here var now = Date.now(); if (Browser.nextRAF === 0) { @@ -8077,25 +8674,29 @@ var ASM_CONSTS = { } var delay = Math.max(Browser.nextRAF - now, 0); setTimeout(func, delay); - },requestAnimationFrame:function(func) { + }, + requestAnimationFrame(func) { if (typeof requestAnimationFrame == 'function') { requestAnimationFrame(func); return; } var RAF = Browser.fakeRequestAnimationFrame; RAF(func); - },safeSetTimeout:function(func, timeout) { + }, + safeSetTimeout(func, timeout) { // Legacy function, this is used by the SDL2 port so we need to keep it // around at least until that is updated. // See https://github.com/libsdl-org/SDL/pull/6304 return safeSetTimeout(func, timeout); - },safeRequestAnimationFrame:function(func) { + }, + safeRequestAnimationFrame(func) { - return Browser.requestAnimationFrame(function() { + return Browser.requestAnimationFrame(() => { callUserCallback(func); }); - },getMimetype:function(name) { + }, + getMimetype(name) { return { 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', @@ -8105,23 +8706,25 @@ var ASM_CONSTS = { 'wav': 'audio/wav', 'mp3': 'audio/mpeg' }[name.substr(name.lastIndexOf('.')+1)]; - },getUserMedia:function(func) { - if (!window.getUserMedia) { - window.getUserMedia = navigator['getUserMedia'] || + }, + getUserMedia(func) { + window.getUserMedia ||= navigator['getUserMedia'] || navigator['mozGetUserMedia']; - } window.getUserMedia(func); - },getMovementX:function(event) { + }, + getMovementX(event) { return event['movementX'] || event['mozMovementX'] || event['webkitMovementX'] || 0; - },getMovementY:function(event) { + }, + getMovementY(event) { return event['movementY'] || event['mozMovementY'] || event['webkitMovementY'] || 0; - },getMouseWheelDelta:function(event) { + }, + getMouseWheelDelta(event) { var delta = 0; switch (event.type) { case 'DOMMouseScroll': @@ -8155,7 +8758,49 @@ var ASM_CONSTS = { throw 'unrecognized mouse wheel event: ' + event.type; } return delta; - },mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,touches:{},lastTouches:{},calculateMouseEvent:function(event) { // event should be mousemove, mousedown or mouseup + }, + mouseX:0, + mouseY:0, + mouseMovementX:0, + mouseMovementY:0, + touches:{ + }, + lastTouches:{ + }, + calculateMouseCoords(pageX, pageY) { + // Calculate the movement based on the changes + // in the coordinates. + var rect = Module["canvas"].getBoundingClientRect(); + var cw = Module["canvas"].width; + var ch = Module["canvas"].height; + + // Neither .scrollX or .pageXOffset are defined in a spec, but + // we prefer .scrollX because it is currently in a spec draft. + // (see: http://www.w3.org/TR/2013/WD-cssom-view-20131217/) + var scrollX = ((typeof window.scrollX != 'undefined') ? window.scrollX : window.pageXOffset); + var scrollY = ((typeof window.scrollY != 'undefined') ? window.scrollY : window.pageYOffset); + // If this assert lands, it's likely because the browser doesn't support scrollX or pageXOffset + // and we have no viable fallback. + assert((typeof scrollX != 'undefined') && (typeof scrollY != 'undefined'), 'Unable to retrieve scroll position, mouse positions likely broken.'); + var adjustedX = pageX - (scrollX + rect.left); + var adjustedY = pageY - (scrollY + rect.top); + + // the canvas might be CSS-scaled compared to its backbuffer; + // SDL-using content will want mouse coordinates in terms + // of backbuffer units. + adjustedX = adjustedX * (cw / rect.width); + adjustedY = adjustedY * (ch / rect.height); + + return { x: adjustedX, y: adjustedY }; + }, + setMouseCoords(pageX, pageY) { + const {x, y} = Browser.calculateMouseCoords(pageX, pageY); + Browser.mouseMovementX = x - Browser.mouseX; + Browser.mouseMovementY = y - Browser.mouseY; + Browser.mouseX = x; + Browser.mouseY = y; + }, + calculateMouseEvent(event) { // event should be mousemove, mousedown or mouseup if (Browser.pointerLock) { // When the pointer is locked, calculate the coordinates // based on the movement of the mouse. @@ -8173,77 +8818,48 @@ var ASM_CONSTS = { Browser.mouseX = SDL.mouseX + Browser.mouseMovementX; Browser.mouseY = SDL.mouseY + Browser.mouseMovementY; } else { - // just add the mouse delta to the current absolut mouse position + // just add the mouse delta to the current absolute mouse position // FIXME: ideally this should be clamped against the canvas size and zero Browser.mouseX += Browser.mouseMovementX; Browser.mouseY += Browser.mouseMovementY; } } else { - // Otherwise, calculate the movement based on the changes - // in the coordinates. - var rect = Module["canvas"].getBoundingClientRect(); - var cw = Module["canvas"].width; - var ch = Module["canvas"].height; - - // Neither .scrollX or .pageXOffset are defined in a spec, but - // we prefer .scrollX because it is currently in a spec draft. - // (see: http://www.w3.org/TR/2013/WD-cssom-view-20131217/) - var scrollX = ((typeof window.scrollX != 'undefined') ? window.scrollX : window.pageXOffset); - var scrollY = ((typeof window.scrollY != 'undefined') ? window.scrollY : window.pageYOffset); - // If this assert lands, it's likely because the browser doesn't support scrollX or pageXOffset - // and we have no viable fallback. - assert((typeof scrollX != 'undefined') && (typeof scrollY != 'undefined'), 'Unable to retrieve scroll position, mouse positions likely broken.'); - if (event.type === 'touchstart' || event.type === 'touchend' || event.type === 'touchmove') { var touch = event.touch; if (touch === undefined) { return; // the "touch" property is only defined in SDL } - var adjustedX = touch.pageX - (scrollX + rect.left); - var adjustedY = touch.pageY - (scrollY + rect.top); - - adjustedX = adjustedX * (cw / rect.width); - adjustedY = adjustedY * (ch / rect.height); - - var coords = { x: adjustedX, y: adjustedY }; + var coords = Browser.calculateMouseCoords(touch.pageX, touch.pageY); if (event.type === 'touchstart') { Browser.lastTouches[touch.identifier] = coords; Browser.touches[touch.identifier] = coords; } else if (event.type === 'touchend' || event.type === 'touchmove') { var last = Browser.touches[touch.identifier]; - if (!last) last = coords; + last ||= coords; Browser.lastTouches[touch.identifier] = last; Browser.touches[touch.identifier] = coords; } return; } - var x = event.pageX - (scrollX + rect.left); - var y = event.pageY - (scrollY + rect.top); - - // the canvas might be CSS-scaled compared to its backbuffer; - // SDL-using content will want mouse coordinates in terms - // of backbuffer units. - x = x * (cw / rect.width); - y = y * (ch / rect.height); - - Browser.mouseMovementX = x - Browser.mouseX; - Browser.mouseMovementY = y - Browser.mouseY; - Browser.mouseX = x; - Browser.mouseY = y; + Browser.setMouseCoords(event.pageX, event.pageY); } - },resizeListeners:[],updateResizeListeners:function() { + }, + resizeListeners:[], + updateResizeListeners() { var canvas = Module['canvas']; - Browser.resizeListeners.forEach(function(listener) { - listener(canvas.width, canvas.height); - }); - },setCanvasSize:function(width, height, noUpdates) { + Browser.resizeListeners.forEach((listener) => listener(canvas.width, canvas.height)); + }, + setCanvasSize(width, height, noUpdates) { var canvas = Module['canvas']; Browser.updateCanvasDimensions(canvas, width, height); if (!noUpdates) Browser.updateResizeListeners(); - },windowedWidth:0,windowedHeight:0,setFullscreenCanvasSize:function() { + }, + windowedWidth:0, + windowedHeight:0, + setFullscreenCanvasSize() { // check if SDL is available if (typeof SDL != "undefined") { var flags = HEAPU32[((SDL.screen)>>2)]; @@ -8252,7 +8868,8 @@ var ASM_CONSTS = { } Browser.updateCanvasDimensions(Module['canvas']); Browser.updateResizeListeners(); - },setWindowedCanvasSize:function() { + }, + setWindowedCanvasSize() { // check if SDL is available if (typeof SDL != "undefined") { var flags = HEAPU32[((SDL.screen)>>2)]; @@ -8261,7 +8878,8 @@ var ASM_CONSTS = { } Browser.updateCanvasDimensions(Module['canvas']); Browser.updateResizeListeners(); - },updateCanvasDimensions:function(canvas, wNative, hNative) { + }, + updateCanvasDimensions(canvas, wNative, hNative) { if (wNative && hNative) { canvas.widthNative = wNative; canvas.heightNative = hNative; @@ -8305,28 +8923,71 @@ var ASM_CONSTS = { } } } - }}; - Module["Browser"] = Browser; - - var AL = {QUEUE_INTERVAL:25,QUEUE_LOOKAHEAD:0.1,DEVICE_NAME:"Emscripten OpenAL",CAPTURE_DEVICE_NAME:"Emscripten OpenAL capture",ALC_EXTENSIONS:{ALC_SOFT_pause_device:true,ALC_SOFT_HRTF:true},AL_EXTENSIONS:{AL_EXT_float32:true,AL_SOFT_loop_points:true,AL_SOFT_source_length:true,AL_EXT_source_distance_model:true,AL_SOFT_source_spatialize:true},_alcErr:0,alcErr:0,deviceRefCounts:{},alcStringCache:{},paused:false,stringCache:{},contexts:{},currentCtx:null,buffers:{0:{id:0,refCount:0,audioBuf:null,frequency:0,bytesPerSample:2,channels:1,length:0}},paramArray:[],_nextId:1,newId:function() { - return AL.freeIds.length > 0 ? AL.freeIds.pop() : AL._nextId++; - },freeIds:[],scheduleContextAudio:function(ctx) { + }, + }; + Module['Browser'] = Browser; + + var AL = { + QUEUE_INTERVAL:25, + QUEUE_LOOKAHEAD:0.1, + DEVICE_NAME:"Emscripten OpenAL", + CAPTURE_DEVICE_NAME:"Emscripten OpenAL capture", + ALC_EXTENSIONS:{ + ALC_SOFT_pause_device:true, + ALC_SOFT_HRTF:true, + }, + AL_EXTENSIONS:{ + AL_EXT_float32:true, + AL_SOFT_loop_points:true, + AL_SOFT_source_length:true, + AL_EXT_source_distance_model:true, + AL_SOFT_source_spatialize:true, + }, + _alcErr:0, + alcErr:0, + deviceRefCounts:{ + }, + alcStringCache:{ + }, + paused:false, + stringCache:{ + }, + contexts:{ + }, + currentCtx:null, + buffers:{ + 0:{ + id:0, + refCount:0, + audioBuf:null, + frequency:0, + bytesPerSample:2, + channels:1, + length:0, + }, + }, + paramArray:[], + _nextId:1, + newId:() => AL.freeIds.length > 0 ? AL.freeIds.pop() : AL._nextId++, + freeIds:[], + scheduleContextAudio:(ctx) => { // If we are animating using the requestAnimationFrame method, then the main loop does not run when in the background. // To give a perfect glitch-free audio stop when switching from foreground to background, we need to avoid updating // audio altogether when in the background, so detect that case and kill audio buffer streaming if so. - if (Browser.mainLoop.timingMode === 1 /* EM_TIMING_RAF */ && document['visibilityState'] != 'visible') { + if (Browser.mainLoop.timingMode === 1 && document['visibilityState'] != 'visible') { return; } for (var i in ctx.sources) { AL.scheduleSourceAudio(ctx.sources[i]); } - },scheduleSourceAudio:function(src, lookahead) { + }, + scheduleSourceAudio:(src, lookahead) => { // See comment on scheduleContextAudio above. - if (Browser.mainLoop.timingMode === 1 /*EM_TIMING_RAF*/ && document['visibilityState'] != 'visible') { + if (Browser.mainLoop.timingMode === 1 && document['visibilityState'] != 'visible') { return; } - if (src.state !== 0x1012 /* AL_PLAYING */) { + if (src.state !== 4114) { return; } @@ -8377,7 +9038,7 @@ var ASM_CONSTS = { var duration = 0.0; // If the source is a looping static buffer, use native looping for gapless playback - if (src.type === 0x1028 /* AL_STATIC */ && src.looping) { + if (src.type === 4136 && src.looping) { duration = Number.POSITIVE_INFINITY; audioSrc.loop = true; if (buf.audioBuf._loopStart) { @@ -8414,9 +9075,10 @@ var ASM_CONSTS = { startOffset = 0.0; bufCursor++; } - },updateSourceTime:function(src) { + }, + updateSourceTime:(src) => { var currentTime = src.context.audioCtx.currentTime; - if (src.state !== 0x1012 /* AL_PLAYING */) { + if (src.state !== 4114) { return currentTime; } @@ -8447,8 +9109,8 @@ var ASM_CONSTS = { if (src.bufsProcessed >= src.bufQueue.length && !src.looping) { // The source has played its entire queue and is non-looping, so just mark it as stopped. - AL.setSourceState(src, 0x1014 /* AL_STOPPED */); - } else if (src.type === 0x1028 /* AL_STATIC */ && src.looping) { + AL.setSourceState(src, 4116); + } else if (src.type === 4136 && src.looping) { // If the source is a looping static buffer, determine the buffer offset based on the loop points var buf = src.bufQueue[0]; if (buf.length === 0) { @@ -8477,7 +9139,7 @@ var ASM_CONSTS = { // We need to determine what state we would be in by this point in time so that when we next schedule // audio playback, it will be just as if no underrun occurred. - if (src.type !== 0x1028 /* AL_STATIC */ && src.looping) { + if (src.type !== 4136 && src.looping) { // if the source is a looping buffer queue, let's first calculate the queue duration, so we can // quickly fast forward past any full loops of the queue and only worry about the remainder. var srcDuration = AL.sourceDuration(src) / src.playbackRate; @@ -8494,7 +9156,7 @@ var ASM_CONSTS = { if (src.looping) { src.bufsProcessed %= src.bufQueue.length; } else { - AL.setSourceState(src, 0x1014 /* AL_STOPPED */); + AL.setSourceState(src, 4116); break; } } @@ -8517,7 +9179,8 @@ var ASM_CONSTS = { } return currentTime; - },cancelPendingSourceAudio:function(src) { + }, + cancelPendingSourceAudio:(src) => { AL.updateSourceTime(src); for (var i = 1; i < src.audioQueue.length; i++) { @@ -8528,14 +9191,16 @@ var ASM_CONSTS = { if (src.audioQueue.length > 1) { src.audioQueue.length = 1; } - },stopSourceAudio:function(src) { + }, + stopSourceAudio:(src) => { for (var i = 0; i < src.audioQueue.length; i++) { src.audioQueue[i].stop(); } src.audioQueue.length = 0; - },setSourceState:function(src, state) { - if (state === 0x1012 /* AL_PLAYING */) { - if (src.state === 0x1012 /* AL_PLAYING */ || src.state == 0x1014 /* AL_STOPPED */) { + }, + setSourceState:(src, state) => { + if (state === 4114) { + if (src.state === 4114 || src.state == 4116) { src.bufsProcessed = 0; src.bufOffset = 0.0; } else { @@ -8543,35 +9208,36 @@ var ASM_CONSTS = { AL.stopSourceAudio(src); - src.state = 0x1012 /* AL_PLAYING */; + src.state = 4114; src.bufStartTime = Number.NEGATIVE_INFINITY; AL.scheduleSourceAudio(src); - } else if (state === 0x1013 /* AL_PAUSED */) { - if (src.state === 0x1012 /* AL_PLAYING */) { + } else if (state === 4115) { + if (src.state === 4114) { // Store off the current offset to restore with on resume. AL.updateSourceTime(src); AL.stopSourceAudio(src); - src.state = 0x1013 /* AL_PAUSED */; + src.state = 4115; } - } else if (state === 0x1014 /* AL_STOPPED */) { - if (src.state !== 0x1011 /* AL_INITIAL */) { - src.state = 0x1014 /* AL_STOPPED */; + } else if (state === 4116) { + if (src.state !== 4113) { + src.state = 4116; src.bufsProcessed = src.bufQueue.length; src.bufStartTime = Number.NEGATIVE_INFINITY; src.bufOffset = 0.0; AL.stopSourceAudio(src); } - } else if (state === 0x1011 /* AL_INITIAL */) { - if (src.state !== 0x1011 /* AL_INITIAL */) { - src.state = 0x1011 /* AL_INITIAL */; + } else if (state === 4113) { + if (src.state !== 4113) { + src.state = 4113; src.bufsProcessed = 0; src.bufStartTime = Number.NEGATIVE_INFINITY; src.bufOffset = 0.0; AL.stopSourceAudio(src); } } - },initSourcePanner:function(src) { + }, + initSourcePanner:(src) => { if (src.type === 0x1030 /* AL_UNDETERMINED */) { return; } @@ -8607,11 +9273,13 @@ var ASM_CONSTS = { src.gain.connect(src.context.gain); src.panner = null; } - },updateContextGlobal:function(ctx) { + }, + updateContextGlobal:(ctx) => { for (var i in ctx.sources) { AL.updateSourceGlobal(ctx.sources[i]); } - },updateSourceGlobal:function(src) { + }, + updateSourceGlobal:(src) => { var panner = src.panner; if (!panner) { return; @@ -8643,7 +9311,8 @@ var ASM_CONSTS = { panner.distanceModel = 'exponential'; break; } - },updateListenerSpace:function(ctx) { + }, + updateListenerSpace:(ctx) => { var listener = ctx.audioCtx.listener; if (listener.positionX) { listener.positionX.value = ctx.listener.position[0]; @@ -8669,7 +9338,8 @@ var ASM_CONSTS = { for (var i in ctx.sources) { AL.updateSourceSpace(ctx.sources[i]); } - },updateSourceSpace:function(src) { + }, + updateSourceSpace:(src) => { if (!src.panner) { return; } @@ -8709,7 +9379,7 @@ var ASM_CONSTS = { var lUpY = listener.up[1]; var lUpZ = listener.up[2]; - var inverseMagnitude = function(x, y, z) { + var inverseMagnitude = (x, y, z) => { var length = Math.sqrt(x * x + y * y + z * z); if (length < Number.EPSILON) { @@ -8825,8 +9495,9 @@ var ASM_CONSTS = { if (src.dopplerShift !== oldShift) { AL.updateSourceRate(src); } - },updateSourceRate:function(src) { - if (src.state === 0x1012 /* AL_PLAYING */) { + }, + updateSourceRate:(src) => { + if (src.state === 4114) { // clear scheduled buffers AL.cancelPendingSourceAudio(src); @@ -8836,7 +9507,7 @@ var ASM_CONSTS = { } var duration; - if (src.type === 0x1028 /* AL_STATIC */ && src.looping) { + if (src.type === 4136 && src.looping) { duration = Number.POSITIVE_INFINITY; } else { // audioSrc._duration is expressed after factoring in playbackRate, so when changing playback rate, need @@ -8850,14 +9521,16 @@ var ASM_CONSTS = { // reschedule buffers with the new playbackRate AL.scheduleSourceAudio(src); } - },sourceDuration:function(src) { + }, + sourceDuration:(src) => { var length = 0.0; for (var i = 0; i < src.bufQueue.length; i++) { var audioBuf = src.bufQueue[i].audioBuf; length += audioBuf ? audioBuf.duration : 0.0; } return length; - },sourceTell:function(src) { + }, + sourceTell:(src) => { AL.updateSourceTime(src); var offset = 0.0; @@ -8869,10 +9542,11 @@ var ASM_CONSTS = { offset += src.bufOffset; return offset; - },sourceSeek:function(src, offset) { - var playing = src.state == 0x1012 /* AL_PLAYING */; + }, + sourceSeek:(src, offset) => { + var playing = src.state == 4114; if (playing) { - AL.setSourceState(src, 0x1011 /* AL_INITIAL */); + AL.setSourceState(src, 4113); } if (src.bufQueue[src.bufsProcessed].audioBuf !== null) { @@ -8886,9 +9560,10 @@ var ASM_CONSTS = { } if (playing) { - AL.setSourceState(src, 0x1012 /* AL_PLAYING */); + AL.setSourceState(src, 4114); } - },getGlobalParam:function(funcname, param) { + }, + getGlobalParam:(funcname, param) => { if (!AL.currentCtx) { return null; } @@ -8904,7 +9579,8 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return null; } - },setGlobalParam:function(funcname, param, value) { + }, + setGlobalParam:(funcname, param, value) => { if (!AL.currentCtx) { return; } @@ -8949,7 +9625,8 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - },getListenerParam:function(funcname, param) { + }, + getListenerParam:(funcname, param) => { if (!AL.currentCtx) { return null; } @@ -8967,7 +9644,8 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return null; } - },setListenerParam:function(funcname, param, value) { + }, + setListenerParam:(funcname, param, value) => { if (!AL.currentCtx) { return; } @@ -9028,7 +9706,8 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - },getBufferParam:function(funcname, bufferId, param) { + }, + getBufferParam:(funcname, bufferId, param) => { if (!AL.currentCtx) { return; } @@ -9059,7 +9738,8 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return null; } - },setBufferParam:function(funcname, bufferId, param, value) { + }, + setBufferParam:(funcname, bufferId, param, value) => { if (!AL.currentCtx) { return; } @@ -9101,7 +9781,8 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - },getSourceParam:function(funcname, sourceId, param) { + }, + getSourceParam:(funcname, sourceId, param) => { if (!AL.currentCtx) { return null; } @@ -9129,7 +9810,7 @@ var ASM_CONSTS = { case 0x1007 /* AL_LOOPING */: return src.looping; case 0x1009 /* AL_BUFFER */: - if (src.type === 0x1028 /* AL_STATIC */) { + if (src.type === 4136) { return src.bufQueue[0].id; } return 0; @@ -9201,7 +9882,8 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return null; } - },setSourceParam:function(funcname, sourceId, param, value) { + }, + setSourceParam:(funcname, sourceId, param, value) => { if (!AL.currentCtx) { return; } @@ -9300,7 +9982,7 @@ var ASM_CONSTS = { if (value === 1) { src.looping = true; AL.updateSourceTime(src); - if (src.type === 0x1028 /* AL_STATIC */ && src.audioQueue.length > 0) { + if (src.type === 4136 && src.audioQueue.length > 0) { var audioSrc = src.audioQueue[0]; audioSrc.loop = true; audioSrc._duration = Number.POSITIVE_INFINITY; @@ -9308,7 +9990,7 @@ var ASM_CONSTS = { } else if (value === 0) { src.looping = false; var currentTime = AL.updateSourceTime(src); - if (src.type === 0x1028 /* AL_STATIC */ && src.audioQueue.length > 0) { + if (src.type === 4136 && src.audioQueue.length > 0) { var audioSrc = src.audioQueue[0]; audioSrc.loop = false; audioSrc._duration = src.bufQueue[0].audioBuf.duration / src.playbackRate; @@ -9320,7 +10002,7 @@ var ASM_CONSTS = { } break; case 0x1009 /* AL_BUFFER */: - if (src.state === 0x1012 /* AL_PLAYING */ || src.state === 0x1013 /* AL_PAUSED */) { + if (src.state === 4114 || src.state === 4115) { AL.currentCtx.err = 40964; return; } @@ -9349,7 +10031,7 @@ var ASM_CONSTS = { buf.refCount++; src.bufQueue = [buf]; src.bufsProcessed = 0; - src.type = 0x1028 /* AL_STATIC */; + src.type = 4136; } AL.initSourcePanner(src); @@ -9500,7 +10182,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - },captures:{},sharedCaptureAudioCtx:null,requireValidCaptureDevice:function(deviceId, funcname) { + }, + captures:{ + }, + sharedCaptureAudioCtx:null, + requireValidCaptureDevice:(deviceId, funcname) => { if (deviceId === 0) { AL.alcErr = 40961; return null; @@ -9516,21 +10202,22 @@ var ASM_CONSTS = { return null; } return c; - }}; - Module["AL"] = AL; - function _alBuffer3f(bufferId, param, value0, value1, value2) { + }, + }; + Module['AL'] = AL; + var _alBuffer3f = (bufferId, param, value0, value1, value2) => { AL.setBufferParam('alBuffer3f', bufferId, param, null); - } - Module["_alBuffer3f"] = _alBuffer3f; + }; + Module['_alBuffer3f'] = _alBuffer3f; _alBuffer3f.sig = 'viifff'; - function _alBuffer3i(bufferId, param, value0, value1, value2) { + var _alBuffer3i = (bufferId, param, value0, value1, value2) => { AL.setBufferParam('alBuffer3i', bufferId, param, null); - } - Module["_alBuffer3i"] = _alBuffer3i; + }; + Module['_alBuffer3i'] = _alBuffer3i; _alBuffer3i.sig = 'viiiii'; - function _alBufferData(bufferId, format, pData, size, freq) { + var _alBufferData = (bufferId, format, pData, size, freq) => { if (!AL.currentCtx) { return; } @@ -9639,17 +10326,17 @@ var ASM_CONSTS = { AL.currentCtx.err = 40963; return; } - } - Module["_alBufferData"] = _alBufferData; - _alBufferData.sig = 'viiiii'; + }; + Module['_alBufferData'] = _alBufferData; + _alBufferData.sig = 'viipii'; - function _alBufferf(bufferId, param, value) { + var _alBufferf = (bufferId, param, value) => { AL.setBufferParam('alBufferf', bufferId, param, null); - } - Module["_alBufferf"] = _alBufferf; + }; + Module['_alBufferf'] = _alBufferf; _alBufferf.sig = 'viif'; - function _alBufferfv(bufferId, param, pValues) { + var _alBufferfv = (bufferId, param, pValues) => { if (!AL.currentCtx) { return; } @@ -9659,17 +10346,17 @@ var ASM_CONSTS = { } AL.setBufferParam('alBufferfv', bufferId, param, null); - } - Module["_alBufferfv"] = _alBufferfv; - _alBufferfv.sig = 'viii'; + }; + Module['_alBufferfv'] = _alBufferfv; + _alBufferfv.sig = 'viip'; - function _alBufferi(bufferId, param, value) { + var _alBufferi = (bufferId, param, value) => { AL.setBufferParam('alBufferi', bufferId, param, null); - } - Module["_alBufferi"] = _alBufferi; + }; + Module['_alBufferi'] = _alBufferi; _alBufferi.sig = 'viii'; - function _alBufferiv(bufferId, param, pValues) { + var _alBufferiv = (bufferId, param, pValues) => { if (!AL.currentCtx) { return; } @@ -9688,11 +10375,11 @@ var ASM_CONSTS = { AL.setBufferParam('alBufferiv', bufferId, param, null); break; } - } - Module["_alBufferiv"] = _alBufferiv; - _alBufferiv.sig = 'viii'; + }; + Module['_alBufferiv'] = _alBufferiv; + _alBufferiv.sig = 'viip'; - function _alDeleteBuffers(count, pBufferIds) { + var _alDeleteBuffers = (count, pBufferIds) => { if (!AL.currentCtx) { return; } @@ -9727,11 +10414,11 @@ var ASM_CONSTS = { delete AL.buffers[bufId]; AL.freeIds.push(bufId); } - } - Module["_alDeleteBuffers"] = _alDeleteBuffers; - _alDeleteBuffers.sig = 'vii'; + }; + Module['_alDeleteBuffers'] = _alDeleteBuffers; + _alDeleteBuffers.sig = 'vip'; - function _alSourcei(sourceId, param, value) { + var _alSourcei = (sourceId, param, value) => { switch (param) { case 0x202 /* AL_SOURCE_RELATIVE */: case 0x1001 /* AL_CONE_INNER_ANGLE */: @@ -9754,11 +10441,11 @@ var ASM_CONSTS = { AL.setSourceParam('alSourcei', sourceId, param, null); break; } - } - Module["_alSourcei"] = _alSourcei; + }; + Module['_alSourcei'] = _alSourcei; _alSourcei.sig = 'viii'; - function _alDeleteSources(count, pSourceIds) { + var _alDeleteSources = (count, pSourceIds) => { if (!AL.currentCtx) { return; } @@ -9773,16 +10460,16 @@ var ASM_CONSTS = { for (var i = 0; i < count; ++i) { var srcId = HEAP32[(((pSourceIds)+(i*4))>>2)]; - AL.setSourceState(AL.currentCtx.sources[srcId], 0x1014 /* AL_STOPPED */); + AL.setSourceState(AL.currentCtx.sources[srcId], 4116); _alSourcei(srcId, 0x1009 /* AL_BUFFER */, 0); delete AL.currentCtx.sources[srcId]; AL.freeIds.push(srcId); } - } - Module["_alDeleteSources"] = _alDeleteSources; - _alDeleteSources.sig = 'vii'; + }; + Module['_alDeleteSources'] = _alDeleteSources; + _alDeleteSources.sig = 'vip'; - function _alDisable(param) { + var _alDisable = (param) => { if (!AL.currentCtx) { return; } @@ -9795,23 +10482,23 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alDisable"] = _alDisable; + }; + Module['_alDisable'] = _alDisable; _alDisable.sig = 'vi'; - function _alDistanceModel(model) { + var _alDistanceModel = (model) => { AL.setGlobalParam('alDistanceModel', 53248, model); - } - Module["_alDistanceModel"] = _alDistanceModel; + }; + Module['_alDistanceModel'] = _alDistanceModel; _alDistanceModel.sig = 'vi'; - function _alDopplerFactor(value) { + var _alDopplerFactor = (value) => { AL.setGlobalParam('alDopplerFactor', 49152, value); - } - Module["_alDopplerFactor"] = _alDopplerFactor; - _alDopplerFactor.sig = 'vi'; + }; + Module['_alDopplerFactor'] = _alDopplerFactor; + _alDopplerFactor.sig = 'vf'; - function _alDopplerVelocity(value) { + var _alDopplerVelocity = (value) => { warnOnce('alDopplerVelocity() is deprecated, and only kept for compatibility with OpenAL 1.0. Use alSpeedOfSound() instead.'); if (!AL.currentCtx) { return; @@ -9820,11 +10507,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40963; return; } - } - Module["_alDopplerVelocity"] = _alDopplerVelocity; - _alDopplerVelocity.sig = 'vi'; + }; + Module['_alDopplerVelocity'] = _alDopplerVelocity; + _alDopplerVelocity.sig = 'vf'; - function _alEnable(param) { + var _alEnable = (param) => { if (!AL.currentCtx) { return; } @@ -9837,11 +10524,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alEnable"] = _alEnable; + }; + Module['_alEnable'] = _alEnable; _alEnable.sig = 'vi'; - function _alGenBuffers(count, pBufferIds) { + var _alGenBuffers = (count, pBufferIds) => { if (!AL.currentCtx) { return; } @@ -9861,11 +10548,11 @@ var ASM_CONSTS = { AL.buffers[buf.id] = buf; HEAP32[(((pBufferIds)+(i*4))>>2)] = buf.id; } - } - Module["_alGenBuffers"] = _alGenBuffers; - _alGenBuffers.sig = 'vii'; + }; + Module['_alGenBuffers'] = _alGenBuffers; + _alGenBuffers.sig = 'vip'; - function _alGenSources(count, pSourceIds) { + var _alGenSources = (count, pSourceIds) => { if (!AL.currentCtx) { return; } @@ -9876,13 +10563,13 @@ var ASM_CONSTS = { context: AL.currentCtx, id: AL.newId(), type: 0x1030 /* AL_UNDETERMINED */, - state: 0x1011 /* AL_INITIAL */, + state: 4113, bufQueue: [AL.buffers[0]], audioQueue: [], looping: false, pitch: 1.0, dopplerShift: 1.0, - gain: gain, + gain, minGain: 0.0, maxGain: 1.0, panner: null, @@ -9909,11 +10596,11 @@ var ASM_CONSTS = { AL.currentCtx.sources[src.id] = src; HEAP32[(((pSourceIds)+(i*4))>>2)] = src.id; } - } - Module["_alGenSources"] = _alGenSources; - _alGenSources.sig = 'vii'; + }; + Module['_alGenSources'] = _alGenSources; + _alGenSources.sig = 'vip'; - function _alGetBoolean(param) { + var _alGetBoolean = (param) => { var val = AL.getGlobalParam('alGetBoolean', param); if (val === null) { return 0; @@ -9928,11 +10615,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return 0; } - } - Module["_alGetBoolean"] = _alGetBoolean; + }; + Module['_alGetBoolean'] = _alGetBoolean; _alGetBoolean.sig = 'ii'; - function _alGetBooleanv(param, pValues) { + var _alGetBooleanv = (param, pValues) => { var val = AL.getGlobalParam('alGetBooleanv', param); // Silently ignore null destinations, as per the spec for global state functions if (val === null || !pValues) { @@ -9943,17 +10630,17 @@ var ASM_CONSTS = { case 49152: case 49155: case 53248: - HEAP8[((pValues)>>0)] = val; + HEAP8[pValues] = val; break; default: AL.currentCtx.err = 40962; return; } - } - Module["_alGetBooleanv"] = _alGetBooleanv; - _alGetBooleanv.sig = 'vii'; + }; + Module['_alGetBooleanv'] = _alGetBooleanv; + _alGetBooleanv.sig = 'vip'; - function _alGetBuffer3f(bufferId, param, pValue0, pValue1, pValue2) { + var _alGetBuffer3f = (bufferId, param, pValue0, pValue1, pValue2) => { var val = AL.getBufferParam('alGetBuffer3f', bufferId, param); if (val === null) { return; @@ -9964,11 +10651,11 @@ var ASM_CONSTS = { } AL.currentCtx.err = 40962; - } - Module["_alGetBuffer3f"] = _alGetBuffer3f; - _alGetBuffer3f.sig = 'viiiii'; + }; + Module['_alGetBuffer3f'] = _alGetBuffer3f; + _alGetBuffer3f.sig = 'viippp'; - function _alGetBuffer3i(bufferId, param, pValue0, pValue1, pValue2) { + var _alGetBuffer3i = (bufferId, param, pValue0, pValue1, pValue2) => { var val = AL.getBufferParam('alGetBuffer3i', bufferId, param); if (val === null) { return; @@ -9979,11 +10666,11 @@ var ASM_CONSTS = { } AL.currentCtx.err = 40962; - } - Module["_alGetBuffer3i"] = _alGetBuffer3i; - _alGetBuffer3i.sig = 'viiiii'; + }; + Module['_alGetBuffer3i'] = _alGetBuffer3i; + _alGetBuffer3i.sig = 'viippp'; - function _alGetBufferf(bufferId, param, pValue) { + var _alGetBufferf = (bufferId, param, pValue) => { var val = AL.getBufferParam('alGetBufferf', bufferId, param); if (val === null) { return; @@ -9994,11 +10681,11 @@ var ASM_CONSTS = { } AL.currentCtx.err = 40962; - } - Module["_alGetBufferf"] = _alGetBufferf; - _alGetBufferf.sig = 'viii'; + }; + Module['_alGetBufferf'] = _alGetBufferf; + _alGetBufferf.sig = 'viip'; - function _alGetBufferfv(bufferId, param, pValues) { + var _alGetBufferfv = (bufferId, param, pValues) => { var val = AL.getBufferParam('alGetBufferfv', bufferId, param); if (val === null) { return; @@ -10009,11 +10696,11 @@ var ASM_CONSTS = { } AL.currentCtx.err = 40962; - } - Module["_alGetBufferfv"] = _alGetBufferfv; - _alGetBufferfv.sig = 'viii'; + }; + Module['_alGetBufferfv'] = _alGetBufferfv; + _alGetBufferfv.sig = 'viip'; - function _alGetBufferi(bufferId, param, pValue) { + var _alGetBufferi = (bufferId, param, pValue) => { var val = AL.getBufferParam('alGetBufferi', bufferId, param); if (val === null) { return; @@ -10034,11 +10721,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetBufferi"] = _alGetBufferi; - _alGetBufferi.sig = 'viii'; + }; + Module['_alGetBufferi'] = _alGetBufferi; + _alGetBufferi.sig = 'viip'; - function _alGetBufferiv(bufferId, param, pValues) { + var _alGetBufferiv = (bufferId, param, pValues) => { var val = AL.getBufferParam('alGetBufferiv', bufferId, param); if (val === null) { return; @@ -10063,11 +10750,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetBufferiv"] = _alGetBufferiv; - _alGetBufferiv.sig = 'viii'; + }; + Module['_alGetBufferiv'] = _alGetBufferiv; + _alGetBufferiv.sig = 'viip'; - function _alGetDouble(param) { + var _alGetDouble = (param) => { var val = AL.getGlobalParam('alGetDouble', param); if (val === null) { return 0.0; @@ -10082,11 +10769,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return 0.0; } - } - Module["_alGetDouble"] = _alGetDouble; + }; + Module['_alGetDouble'] = _alGetDouble; _alGetDouble.sig = 'di'; - function _alGetDoublev(param, pValues) { + var _alGetDoublev = (param, pValues) => { var val = AL.getGlobalParam('alGetDoublev', param); // Silently ignore null destinations, as per the spec for global state functions if (val === null || !pValues) { @@ -10103,11 +10790,12 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetDoublev"] = _alGetDoublev; - _alGetDoublev.sig = 'vii'; + }; + Module['_alGetDoublev'] = _alGetDoublev; + _alGetDoublev.sig = 'vip'; - function _alGetEnumValue(pEnumName) { + + var _alGetEnumValue = (pEnumName) => { if (!AL.currentCtx) { return 0; } @@ -10206,11 +10894,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40963; return 0; } - } - Module["_alGetEnumValue"] = _alGetEnumValue; - _alGetEnumValue.sig = 'ii'; + }; + Module['_alGetEnumValue'] = _alGetEnumValue; + _alGetEnumValue.sig = 'ip'; - function _alGetError() { + var _alGetError = () => { if (!AL.currentCtx) { return 40964; } @@ -10218,11 +10906,11 @@ var ASM_CONSTS = { var err = AL.currentCtx.err; AL.currentCtx.err = 0; return err; - } - Module["_alGetError"] = _alGetError; + }; + Module['_alGetError'] = _alGetError; _alGetError.sig = 'i'; - function _alGetFloat(param) { + var _alGetFloat = (param) => { var val = AL.getGlobalParam('alGetFloat', param); if (val === null) { return 0.0; @@ -10236,11 +10924,11 @@ var ASM_CONSTS = { default: return 0.0; } - } - Module["_alGetFloat"] = _alGetFloat; + }; + Module['_alGetFloat'] = _alGetFloat; _alGetFloat.sig = 'fi'; - function _alGetFloatv(param, pValues) { + var _alGetFloatv = (param, pValues) => { var val = AL.getGlobalParam('alGetFloatv', param); // Silently ignore null destinations, as per the spec for global state functions if (val === null || !pValues) { @@ -10257,11 +10945,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetFloatv"] = _alGetFloatv; - _alGetFloatv.sig = 'vii'; + }; + Module['_alGetFloatv'] = _alGetFloatv; + _alGetFloatv.sig = 'vip'; - function _alGetInteger(param) { + var _alGetInteger = (param) => { var val = AL.getGlobalParam('alGetInteger', param); if (val === null) { return 0; @@ -10276,11 +10964,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return 0; } - } - Module["_alGetInteger"] = _alGetInteger; + }; + Module['_alGetInteger'] = _alGetInteger; _alGetInteger.sig = 'ii'; - function _alGetIntegerv(param, pValues) { + var _alGetIntegerv = (param, pValues) => { var val = AL.getGlobalParam('alGetIntegerv', param); // Silently ignore null destinations, as per the spec for global state functions if (val === null || !pValues) { @@ -10297,11 +10985,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetIntegerv"] = _alGetIntegerv; - _alGetIntegerv.sig = 'vii'; + }; + Module['_alGetIntegerv'] = _alGetIntegerv; + _alGetIntegerv.sig = 'vip'; - function _alGetListener3f(param, pValue0, pValue1, pValue2) { + var _alGetListener3f = (param, pValue0, pValue1, pValue2) => { var val = AL.getListenerParam('alGetListener3f', param); if (val === null) { return; @@ -10322,11 +11010,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetListener3f"] = _alGetListener3f; - _alGetListener3f.sig = 'viiii'; + }; + Module['_alGetListener3f'] = _alGetListener3f; + _alGetListener3f.sig = 'vippp'; - function _alGetListener3i(param, pValue0, pValue1, pValue2) { + var _alGetListener3i = (param, pValue0, pValue1, pValue2) => { var val = AL.getListenerParam('alGetListener3i', param); if (val === null) { return; @@ -10347,11 +11035,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetListener3i"] = _alGetListener3i; - _alGetListener3i.sig = 'viiii'; + }; + Module['_alGetListener3i'] = _alGetListener3i; + _alGetListener3i.sig = 'vippp'; - function _alGetListenerf(param, pValue) { + var _alGetListenerf = (param, pValue) => { var val = AL.getListenerParam('alGetListenerf', param); if (val === null) { return; @@ -10369,11 +11057,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetListenerf"] = _alGetListenerf; - _alGetListenerf.sig = 'vii'; + }; + Module['_alGetListenerf'] = _alGetListenerf; + _alGetListenerf.sig = 'vip'; - function _alGetListenerfv(param, pValues) { + var _alGetListenerfv = (param, pValues) => { var val = AL.getListenerParam('alGetListenerfv', param); if (val === null) { return; @@ -10402,11 +11090,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetListenerfv"] = _alGetListenerfv; - _alGetListenerfv.sig = 'vii'; + }; + Module['_alGetListenerfv'] = _alGetListenerfv; + _alGetListenerfv.sig = 'vip'; - function _alGetListeneri(param, pValue) { + var _alGetListeneri = (param, pValue) => { var val = AL.getListenerParam('alGetListeneri', param); if (val === null) { return; @@ -10417,11 +11105,11 @@ var ASM_CONSTS = { } AL.currentCtx.err = 40962; - } - Module["_alGetListeneri"] = _alGetListeneri; - _alGetListeneri.sig = 'vii'; + }; + Module['_alGetListeneri'] = _alGetListeneri; + _alGetListeneri.sig = 'vip'; - function _alGetListeneriv(param, pValues) { + var _alGetListeneriv = (param, pValues) => { var val = AL.getListenerParam('alGetListeneriv', param); if (val === null) { return; @@ -10450,11 +11138,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetListeneriv"] = _alGetListeneriv; - _alGetListeneriv.sig = 'vii'; + }; + Module['_alGetListeneriv'] = _alGetListeneriv; + _alGetListeneriv.sig = 'vip'; - function _alGetSource3f(sourceId, param, pValue0, pValue1, pValue2) { + var _alGetSource3f = (sourceId, param, pValue0, pValue1, pValue2) => { var val = AL.getSourceParam('alGetSource3f', sourceId, param); if (val === null) { return; @@ -10476,11 +11164,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetSource3f"] = _alGetSource3f; - _alGetSource3f.sig = 'viiiii'; + }; + Module['_alGetSource3f'] = _alGetSource3f; + _alGetSource3f.sig = 'viippp'; - function _alGetSource3i(sourceId, param, pValue0, pValue1, pValue2) { + var _alGetSource3i = (sourceId, param, pValue0, pValue1, pValue2) => { var val = AL.getSourceParam('alGetSource3i', sourceId, param); if (val === null) { return; @@ -10502,11 +11190,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetSource3i"] = _alGetSource3i; - _alGetSource3i.sig = 'viiiii'; + }; + Module['_alGetSource3i'] = _alGetSource3i; + _alGetSource3i.sig = 'viippp'; - function _alGetSourcef(sourceId, param, pValue) { + var _alGetSourcef = (sourceId, param, pValue) => { var val = AL.getSourceParam('alGetSourcef', sourceId, param); if (val === null) { return; @@ -10537,11 +11225,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetSourcef"] = _alGetSourcef; - _alGetSourcef.sig = 'viii'; + }; + Module['_alGetSourcef'] = _alGetSourcef; + _alGetSourcef.sig = 'viip'; - function _alGetSourcefv(sourceId, param, pValues) { + var _alGetSourcefv = (sourceId, param, pValues) => { var val = AL.getSourceParam('alGetSourcefv', sourceId, param); if (val === null) { return; @@ -10579,11 +11267,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetSourcefv"] = _alGetSourcefv; - _alGetSourcefv.sig = 'viii'; + }; + Module['_alGetSourcefv'] = _alGetSourcefv; + _alGetSourcefv.sig = 'viip'; - function _alGetSourcei(sourceId, param, pValue) { + var _alGetSourcei = (sourceId, param, pValue) => { var val = AL.getSourceParam('alGetSourcei', sourceId, param); if (val === null) { return; @@ -10619,11 +11307,11 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetSourcei"] = _alGetSourcei; - _alGetSourcei.sig = 'viii'; + }; + Module['_alGetSourcei'] = _alGetSourcei; + _alGetSourcei.sig = 'viip'; - function _alGetSourceiv(sourceId, param, pValues) { + var _alGetSourceiv = (sourceId, param, pValues) => { var val = AL.getSourceParam('alGetSourceiv', sourceId, param); if (val === null) { return; @@ -10666,17 +11354,26 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return; } - } - Module["_alGetSourceiv"] = _alGetSourceiv; - _alGetSourceiv.sig = 'viii'; + }; + Module['_alGetSourceiv'] = _alGetSourceiv; + _alGetSourceiv.sig = 'viip'; - function _alGetString(param) { - if (AL.stringCache[param]) { - return AL.stringCache[param]; - } - var ret; + var stringToNewUTF8 = (str) => { + var size = lengthBytesUTF8(str) + 1; + var ret = _malloc(size); + if (ret) stringToUTF8(str, ret, size); + return ret; + }; + Module['stringToNewUTF8'] = stringToNewUTF8; + + var _alGetString = (param) => { + if (AL.stringCache[param]) { + return AL.stringCache[param]; + } + + var ret; switch (param) { case 0: ret = 'No Error'; @@ -10721,14 +11418,14 @@ var ASM_CONSTS = { return 0; } - ret = allocateUTF8(ret); + ret = stringToNewUTF8(ret); AL.stringCache[param] = ret; return ret; - } - Module["_alGetString"] = _alGetString; - _alGetString.sig = 'ii'; + }; + Module['_alGetString'] = _alGetString; + _alGetString.sig = 'pi'; - function _alIsBuffer(bufferId) { + var _alIsBuffer = (bufferId) => { if (!AL.currentCtx) { return false; } @@ -10740,11 +11437,11 @@ var ASM_CONSTS = { return false; } return true; - } - Module["_alIsBuffer"] = _alIsBuffer; + }; + Module['_alIsBuffer'] = _alIsBuffer; _alIsBuffer.sig = 'ii'; - function _alIsEnabled(param) { + var _alIsEnabled = (param) => { if (!AL.currentCtx) { return 0; } @@ -10755,19 +11452,20 @@ var ASM_CONSTS = { AL.currentCtx.err = 40962; return 0; } - } - Module["_alIsEnabled"] = _alIsEnabled; + }; + Module['_alIsEnabled'] = _alIsEnabled; _alIsEnabled.sig = 'ii'; - function _alIsExtensionPresent(pExtName) { + + var _alIsExtensionPresent = (pExtName) => { var name = UTF8ToString(pExtName); return AL.AL_EXTENSIONS[name] ? 1 : 0; - } - Module["_alIsExtensionPresent"] = _alIsExtensionPresent; - _alIsExtensionPresent.sig = 'ii'; + }; + Module['_alIsExtensionPresent'] = _alIsExtensionPresent; + _alIsExtensionPresent.sig = 'ip'; - function _alIsSource(sourceId) { + var _alIsSource = (sourceId) => { if (!AL.currentCtx) { return false; } @@ -10776,11 +11474,11 @@ var ASM_CONSTS = { return false; } return true; - } - Module["_alIsSource"] = _alIsSource; + }; + Module['_alIsSource'] = _alIsSource; _alIsSource.sig = 'ii'; - function _alListener3f(param, value0, value1, value2) { + var _alListener3f = (param, value0, value1, value2) => { switch (param) { case 4100: case 4102: @@ -10793,11 +11491,11 @@ var ASM_CONSTS = { AL.setListenerParam('alListener3f', param, null); break; } - } - Module["_alListener3f"] = _alListener3f; + }; + Module['_alListener3f'] = _alListener3f; _alListener3f.sig = 'vifff'; - function _alListener3i(param, value0, value1, value2) { + var _alListener3i = (param, value0, value1, value2) => { switch (param) { case 4100: case 4102: @@ -10810,11 +11508,11 @@ var ASM_CONSTS = { AL.setListenerParam('alListener3i', param, null); break; } - } - Module["_alListener3i"] = _alListener3i; + }; + Module['_alListener3i'] = _alListener3i; _alListener3i.sig = 'viiii'; - function _alListenerf(param, value) { + var _alListenerf = (param, value) => { switch (param) { case 4106: AL.setListenerParam('alListenerf', param, value); @@ -10823,11 +11521,11 @@ var ASM_CONSTS = { AL.setListenerParam('alListenerf', param, null); break; } - } - Module["_alListenerf"] = _alListenerf; + }; + Module['_alListenerf'] = _alListenerf; _alListenerf.sig = 'vif'; - function _alListenerfv(param, pValues) { + var _alListenerfv = (param, pValues) => { if (!AL.currentCtx) { return; } @@ -10857,17 +11555,17 @@ var ASM_CONSTS = { AL.setListenerParam('alListenerfv', param, null); break; } - } - Module["_alListenerfv"] = _alListenerfv; - _alListenerfv.sig = 'vii'; + }; + Module['_alListenerfv'] = _alListenerfv; + _alListenerfv.sig = 'vip'; - function _alListeneri(param, value) { + var _alListeneri = (param, value) => { AL.setListenerParam('alListeneri', param, null); - } - Module["_alListeneri"] = _alListeneri; + }; + Module['_alListeneri'] = _alListeneri; _alListeneri.sig = 'vii'; - function _alListeneriv(param, pValues) { + var _alListeneriv = (param, pValues) => { if (!AL.currentCtx) { return; } @@ -10897,11 +11595,11 @@ var ASM_CONSTS = { AL.setListenerParam('alListeneriv', param, null); break; } - } - Module["_alListeneriv"] = _alListeneriv; - _alListeneriv.sig = 'vii'; + }; + Module['_alListeneriv'] = _alListeneriv; + _alListeneriv.sig = 'vip'; - function _alSource3f(sourceId, param, value0, value1, value2) { + var _alSource3f = (sourceId, param, value0, value1, value2) => { switch (param) { case 4100: case 4101: @@ -10915,11 +11613,11 @@ var ASM_CONSTS = { AL.setSourceParam('alSource3f', sourceId, param, null); break; } - } - Module["_alSource3f"] = _alSource3f; + }; + Module['_alSource3f'] = _alSource3f; _alSource3f.sig = 'viifff'; - function _alSource3i(sourceId, param, value0, value1, value2) { + var _alSource3i = (sourceId, param, value0, value1, value2) => { switch (param) { case 4100: case 4101: @@ -10933,11 +11631,11 @@ var ASM_CONSTS = { AL.setSourceParam('alSource3i', sourceId, param, null); break; } - } - Module["_alSource3i"] = _alSource3i; + }; + Module['_alSource3i'] = _alSource3i; _alSource3i.sig = 'viiiii'; - function _alSourcePause(sourceId) { + var _alSourcePause = (sourceId) => { if (!AL.currentCtx) { return; } @@ -10946,12 +11644,12 @@ var ASM_CONSTS = { AL.currentCtx.err = 40961; return; } - AL.setSourceState(src, 0x1013 /* AL_PAUSED */); - } - Module["_alSourcePause"] = _alSourcePause; + AL.setSourceState(src, 4115); + }; + Module['_alSourcePause'] = _alSourcePause; _alSourcePause.sig = 'vi'; - function _alSourcePausev(count, pSourceIds) { + var _alSourcePausev = (count, pSourceIds) => { if (!AL.currentCtx) { return; } @@ -10967,13 +11665,13 @@ var ASM_CONSTS = { for (var i = 0; i < count; ++i) { var srcId = HEAP32[(((pSourceIds)+(i*4))>>2)]; - AL.setSourceState(AL.currentCtx.sources[srcId], 0x1013 /* AL_PAUSED */); + AL.setSourceState(AL.currentCtx.sources[srcId], 4115); } - } - Module["_alSourcePausev"] = _alSourcePausev; - _alSourcePausev.sig = 'vii'; + }; + Module['_alSourcePausev'] = _alSourcePausev; + _alSourcePausev.sig = 'vip'; - function _alSourcePlay(sourceId) { + var _alSourcePlay = (sourceId) => { if (!AL.currentCtx) { return; } @@ -10982,12 +11680,12 @@ var ASM_CONSTS = { AL.currentCtx.err = 40961; return; } - AL.setSourceState(src, 0x1012 /* AL_PLAYING */); - } - Module["_alSourcePlay"] = _alSourcePlay; + AL.setSourceState(src, 4114); + }; + Module['_alSourcePlay'] = _alSourcePlay; _alSourcePlay.sig = 'vi'; - function _alSourcePlayv(count, pSourceIds) { + var _alSourcePlayv = (count, pSourceIds) => { if (!AL.currentCtx) { return; } @@ -11003,13 +11701,13 @@ var ASM_CONSTS = { for (var i = 0; i < count; ++i) { var srcId = HEAP32[(((pSourceIds)+(i*4))>>2)]; - AL.setSourceState(AL.currentCtx.sources[srcId], 0x1012 /* AL_PLAYING */); + AL.setSourceState(AL.currentCtx.sources[srcId], 4114); } - } - Module["_alSourcePlayv"] = _alSourcePlayv; - _alSourcePlayv.sig = 'vii'; + }; + Module['_alSourcePlayv'] = _alSourcePlayv; + _alSourcePlayv.sig = 'vip'; - function _alSourceQueueBuffers(sourceId, count, pBufferIds) { + var _alSourceQueueBuffers = (sourceId, count, pBufferIds) => { if (!AL.currentCtx) { return; } @@ -11018,7 +11716,7 @@ var ASM_CONSTS = { AL.currentCtx.err = 40961; return; } - if (src.type === 0x1028 /* AL_STATIC */) { + if (src.type === 4136) { AL.currentCtx.err = 40964; return; } @@ -11074,11 +11772,11 @@ var ASM_CONSTS = { AL.initSourcePanner(src); AL.scheduleSourceAudio(src); - } - Module["_alSourceQueueBuffers"] = _alSourceQueueBuffers; - _alSourceQueueBuffers.sig = 'viii'; + }; + Module['_alSourceQueueBuffers'] = _alSourceQueueBuffers; + _alSourceQueueBuffers.sig = 'viip'; - function _alSourceRewind(sourceId) { + var _alSourceRewind = (sourceId) => { if (!AL.currentCtx) { return; } @@ -11088,14 +11786,14 @@ var ASM_CONSTS = { return; } // Stop the source first to clear the source queue - AL.setSourceState(src, 0x1014 /* AL_STOPPED */); + AL.setSourceState(src, 4116); // Now set the state of AL_INITIAL according to the specification - AL.setSourceState(src, 0x1011 /* AL_INITIAL */); - } - Module["_alSourceRewind"] = _alSourceRewind; + AL.setSourceState(src, 4113); + }; + Module['_alSourceRewind'] = _alSourceRewind; _alSourceRewind.sig = 'vi'; - function _alSourceRewindv(count, pSourceIds) { + var _alSourceRewindv = (count, pSourceIds) => { if (!AL.currentCtx) { return; } @@ -11111,13 +11809,13 @@ var ASM_CONSTS = { for (var i = 0; i < count; ++i) { var srcId = HEAP32[(((pSourceIds)+(i*4))>>2)]; - AL.setSourceState(AL.currentCtx.sources[srcId], 0x1011 /* AL_INITIAL */); + AL.setSourceState(AL.currentCtx.sources[srcId], 4113); } - } - Module["_alSourceRewindv"] = _alSourceRewindv; - _alSourceRewindv.sig = 'vii'; + }; + Module['_alSourceRewindv'] = _alSourceRewindv; + _alSourceRewindv.sig = 'vip'; - function _alSourceStop(sourceId) { + var _alSourceStop = (sourceId) => { if (!AL.currentCtx) { return; } @@ -11126,12 +11824,12 @@ var ASM_CONSTS = { AL.currentCtx.err = 40961; return; } - AL.setSourceState(src, 0x1014 /* AL_STOPPED */); - } - Module["_alSourceStop"] = _alSourceStop; + AL.setSourceState(src, 4116); + }; + Module['_alSourceStop'] = _alSourceStop; _alSourceStop.sig = 'vi'; - function _alSourceStopv(count, pSourceIds) { + var _alSourceStopv = (count, pSourceIds) => { if (!AL.currentCtx) { return; } @@ -11147,13 +11845,13 @@ var ASM_CONSTS = { for (var i = 0; i < count; ++i) { var srcId = HEAP32[(((pSourceIds)+(i*4))>>2)]; - AL.setSourceState(AL.currentCtx.sources[srcId], 0x1014 /* AL_STOPPED */); + AL.setSourceState(AL.currentCtx.sources[srcId], 4116); } - } - Module["_alSourceStopv"] = _alSourceStopv; - _alSourceStopv.sig = 'vii'; + }; + Module['_alSourceStopv'] = _alSourceStopv; + _alSourceStopv.sig = 'vip'; - function _alSourceUnqueueBuffers(sourceId, count, pBufferIds) { + var _alSourceUnqueueBuffers = (sourceId, count, pBufferIds) => { if (!AL.currentCtx) { return; } @@ -11186,11 +11884,11 @@ var ASM_CONSTS = { AL.initSourcePanner(src); AL.scheduleSourceAudio(src); - } - Module["_alSourceUnqueueBuffers"] = _alSourceUnqueueBuffers; - _alSourceUnqueueBuffers.sig = 'viii'; + }; + Module['_alSourceUnqueueBuffers'] = _alSourceUnqueueBuffers; + _alSourceUnqueueBuffers.sig = 'viip'; - function _alSourcef(sourceId, param, value) { + var _alSourcef = (sourceId, param, value) => { switch (param) { case 0x1001 /* AL_CONE_INNER_ANGLE */: case 0x1002 /* AL_CONE_OUTER_ANGLE */: @@ -11212,11 +11910,11 @@ var ASM_CONSTS = { AL.setSourceParam('alSourcef', sourceId, param, null); break; } - } - Module["_alSourcef"] = _alSourcef; + }; + Module['_alSourcef'] = _alSourcef; _alSourcef.sig = 'viif'; - function _alSourcefv(sourceId, param, pValues) { + var _alSourcefv = (sourceId, param, pValues) => { if (!AL.currentCtx) { return; } @@ -11255,12 +11953,12 @@ var ASM_CONSTS = { AL.setSourceParam('alSourcefv', sourceId, param, null); break; } - } - Module["_alSourcefv"] = _alSourcefv; - _alSourcefv.sig = 'viii'; + }; + Module['_alSourcefv'] = _alSourcefv; + _alSourcefv.sig = 'viip'; - function _alSourceiv(sourceId, param, pValues) { + var _alSourceiv = (sourceId, param, pValues) => { if (!AL.currentCtx) { return; } @@ -11300,17 +11998,17 @@ var ASM_CONSTS = { AL.setSourceParam('alSourceiv', sourceId, param, null); break; } - } - Module["_alSourceiv"] = _alSourceiv; - _alSourceiv.sig = 'viii'; + }; + Module['_alSourceiv'] = _alSourceiv; + _alSourceiv.sig = 'viip'; - function _alSpeedOfSound(value) { + var _alSpeedOfSound = (value) => { AL.setGlobalParam('alSpeedOfSound', 49155, value); - } - Module["_alSpeedOfSound"] = _alSpeedOfSound; - _alSpeedOfSound.sig = 'vi'; + }; + Module['_alSpeedOfSound'] = _alSpeedOfSound; + _alSpeedOfSound.sig = 'vf'; - function _alcCaptureCloseDevice(deviceId) { + var _alcCaptureCloseDevice = (deviceId) => { var c = AL.requireValidCaptureDevice(deviceId, 'alcCaptureCloseDevice'); if (!c) return false; @@ -11320,17 +12018,15 @@ var ASM_CONSTS = { // This clean-up might be unnecessary (paranoid) ? // May happen if user hasn't decided to grant or deny input - if (c.mediaStreamSourceNode) c.mediaStreamSourceNode.disconnect(); - if (c.mergerNode) c.mergerNode.disconnect(); - if (c.splitterNode) c.splitterNode.disconnect(); + c.mediaStreamSourceNode?.disconnect(); + c.mergerNode?.disconnect(); + c.splitterNode?.disconnect(); // May happen if user hasn't decided to grant or deny input - if (c.scriptProcessorNode) c.scriptProcessorNode.disconnect(); + c.scriptProcessorNode?.disconnect(); if (c.mediaStream) { // Disabling the microphone of the browser. // Without this operation, the red dot on the browser tab page will remain. - c.mediaStream.getTracks().forEach(function(track) { - track.stop(); - }); + c.mediaStream.getTracks().forEach((track) => track.stop()); } delete c.buffers; @@ -11339,21 +12035,21 @@ var ASM_CONSTS = { c.isCapturing = false; return true; - } - Module["_alcCaptureCloseDevice"] = _alcCaptureCloseDevice; - _alcCaptureCloseDevice.sig = 'ii'; + }; + Module['_alcCaptureCloseDevice'] = _alcCaptureCloseDevice; + _alcCaptureCloseDevice.sig = 'ip'; - function listenOnce(object, event, func) { + var listenOnce = (object, event, func) => { object.addEventListener(event, func, { 'once': true }); - } - Module["listenOnce"] = listenOnce; + }; + Module['listenOnce'] = listenOnce; /** @param {Object=} elements */ - function autoResumeAudioContext(ctx, elements) { + var autoResumeAudioContext = (ctx, elements) => { if (!elements) { elements = [document, document.getElementById('canvas')]; } - ['keydown', 'mousedown', 'touchstart'].forEach(function(event) { - elements.forEach(function(element) { + ['keydown', 'mousedown', 'touchstart'].forEach((event) => { + elements.forEach((element) => { if (element) { listenOnce(element, event, () => { if (ctx.state === 'suspended') ctx.resume(); @@ -11361,10 +12057,11 @@ var ASM_CONSTS = { } }); }); - } - Module["autoResumeAudioContext"] = autoResumeAudioContext; + }; + Module['autoResumeAudioContext'] = autoResumeAudioContext; - function _alcCaptureOpenDevice(pDeviceName, requestedSampleRate, format, bufferFrameCapacity) { + + var _alcCaptureOpenDevice = (pDeviceName, requestedSampleRate, format, bufferFrameCapacity) => { var resolvedDeviceName = AL.CAPTURE_DEVICE_NAME; @@ -11474,9 +12171,9 @@ var ASM_CONSTS = { var newCapture = { audioCtx: AL.sharedCaptureAudioCtx, deviceName: resolvedDeviceName, - requestedSampleRate: requestedSampleRate, - requestedSampleType: requestedSampleType, - outputChannelCount: outputChannelCount, + requestedSampleRate, + requestedSampleType, + outputChannelCount, inputChannelCount: null, // Not known until the getUserMedia() promise resolves mediaStreamError: null, // Used by other functions to return early and report an error. mediaStreamSourceNode: null, @@ -11486,7 +12183,7 @@ var ASM_CONSTS = { splitterNode: null, scriptProcessorNode: null, isCapturing: false, - buffers: buffers, + buffers, get bufferFrameCapacity() { return buffers[0].length; }, @@ -11497,10 +12194,10 @@ var ASM_CONSTS = { // Preparing for getUserMedia() - var onError = function(mediaStreamError) { + var onError = (mediaStreamError) => { newCapture.mediaStreamError = mediaStreamError; }; - var onSuccess = function(mediaStream) { + var onSuccess = (mediaStream) => { newCapture.mediaStreamSourceNode = newCapture.audioCtx.createMediaStreamSource(mediaStream); newCapture.mediaStream = mediaStream; @@ -11542,8 +12239,7 @@ var ASM_CONSTS = { newCapture.scriptProcessorNode.connect(newCapture.audioCtx.destination); - newCapture.scriptProcessorNode.onaudioprocess = function(audioProcessingEvent) { - + newCapture.scriptProcessorNode.onaudioprocess = (audioProcessingEvent) => { if (!newCapture.isCapturing) { return; } @@ -11612,7 +12308,7 @@ var ASM_CONSTS = { }; // The latest way to call getUserMedia() - if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { + if (navigator.mediaDevices?.getUserMedia) { navigator.mediaDevices .getUserMedia({audio: true}) .then(onSuccess) @@ -11624,11 +12320,11 @@ var ASM_CONSTS = { var id = AL.newId(); AL.captures[id] = newCapture; return id; - } - Module["_alcCaptureOpenDevice"] = _alcCaptureOpenDevice; - _alcCaptureOpenDevice.sig = 'iiiii'; + }; + Module['_alcCaptureOpenDevice'] = _alcCaptureOpenDevice; + _alcCaptureOpenDevice.sig = 'ppiii'; - function _alcCaptureSamples(deviceId, pFrames, requestedFrameCount) { + var _alcCaptureSamples = (deviceId, pFrames, requestedFrameCount) => { var c = AL.requireValidCaptureDevice(deviceId, 'alcCaptureSamples'); if (!c) return; @@ -11656,7 +12352,7 @@ var ASM_CONSTS = { HEAP16[(((pFrames)+(2*i))>>1)] = sample; } function setU8Sample(i, sample) { - HEAP8[(((pFrames)+(i))>>0)] = sample; + HEAP8[(pFrames)+(i)] = sample; } var setSample; @@ -11701,11 +12397,11 @@ var ASM_CONSTS = { // of available captured sample-frames, but not only would it // be insane not to do, OpenAL-Soft happens to do that as well. c.capturedFrameCount = 0; - } - Module["_alcCaptureSamples"] = _alcCaptureSamples; - _alcCaptureSamples.sig = 'viii'; + }; + Module['_alcCaptureSamples'] = _alcCaptureSamples; + _alcCaptureSamples.sig = 'vppi'; - function _alcCaptureStart(deviceId) { + var _alcCaptureStart = (deviceId) => { var c = AL.requireValidCaptureDevice(deviceId, 'alcCaptureStart'); if (!c) return; @@ -11719,20 +12415,20 @@ var ASM_CONSTS = { c.isCapturing = true; c.capturedFrameCount = 0; c.capturePlayhead = 0; - } - Module["_alcCaptureStart"] = _alcCaptureStart; - _alcCaptureStart.sig = 'vi'; + }; + Module['_alcCaptureStart'] = _alcCaptureStart; + _alcCaptureStart.sig = 'vp'; - function _alcCaptureStop(deviceId) { + var _alcCaptureStop = (deviceId) => { var c = AL.requireValidCaptureDevice(deviceId, 'alcCaptureStop'); if (!c) return; c.isCapturing = false; - } - Module["_alcCaptureStop"] = _alcCaptureStop; - _alcCaptureStop.sig = 'vi'; + }; + Module['_alcCaptureStop'] = _alcCaptureStop; + _alcCaptureStop.sig = 'vp'; - function _alcCloseDevice(deviceId) { + var _alcCloseDevice = (deviceId) => { if (!(deviceId in AL.deviceRefCounts) || AL.deviceRefCounts[deviceId] > 0) { return 0; } @@ -11740,12 +12436,12 @@ var ASM_CONSTS = { delete AL.deviceRefCounts[deviceId]; AL.freeIds.push(deviceId); return 1; - } - Module["_alcCloseDevice"] = _alcCloseDevice; - _alcCloseDevice.sig = 'ii'; + }; + Module['_alcCloseDevice'] = _alcCloseDevice; + _alcCloseDevice.sig = 'ip'; - function _alcCreateContext(deviceId, pAttrList) { + var _alcCreateContext = (deviceId, pAttrList) => { if (!(deviceId in AL.deviceRefCounts)) { AL.alcErr = 0xA001; /* ALC_INVALID_DEVICE */ return 0; @@ -11836,19 +12532,19 @@ var ASM_CONSTS = { var gain = ac.createGain(); gain.connect(ac.destination); var ctx = { - deviceId: deviceId, + deviceId, id: AL.newId(), - attrs: attrs, + attrs, audioCtx: ac, listener: { - position: [0.0, 0.0, 0.0], - velocity: [0.0, 0.0, 0.0], - direction: [0.0, 0.0, 0.0], - up: [0.0, 0.0, 0.0] + position: [0.0, 0.0, 0.0], + velocity: [0.0, 0.0, 0.0], + direction: [0.0, 0.0, 0.0], + up: [0.0, 0.0, 0.0] }, sources: [], - interval: setInterval(function() { AL.scheduleContextAudio(ctx); }, AL.QUEUE_INTERVAL), - gain: gain, + interval: setInterval(() => AL.scheduleContextAudio(ctx), AL.QUEUE_INTERVAL), + gain, distanceModel: 0xd002 /* AL_INVERSE_DISTANCE_CLAMPED */, speedOfSound: 343.3, dopplerFactor: 1.0, @@ -11881,11 +12577,11 @@ var ASM_CONSTS = { } return ctx.id; - } - Module["_alcCreateContext"] = _alcCreateContext; - _alcCreateContext.sig = 'iii'; + }; + Module['_alcCreateContext'] = _alcCreateContext; + _alcCreateContext.sig = 'ppp'; - function _alcDestroyContext(contextId) { + var _alcDestroyContext = (contextId) => { var ctx = AL.contexts[contextId]; if (AL.currentCtx === ctx) { AL.alcErr = 0xA002 /* ALC_INVALID_CONTEXT */; @@ -11899,29 +12595,30 @@ var ASM_CONSTS = { AL.deviceRefCounts[ctx.deviceId]--; delete AL.contexts[contextId]; AL.freeIds.push(contextId); - } - Module["_alcDestroyContext"] = _alcDestroyContext; - _alcDestroyContext.sig = 'vi'; + }; + Module['_alcDestroyContext'] = _alcDestroyContext; + _alcDestroyContext.sig = 'vp'; - function _alcGetContextsDevice(contextId) { + var _alcGetContextsDevice = (contextId) => { if (contextId in AL.contexts) { return AL.contexts[contextId].deviceId; } return 0; - } - Module["_alcGetContextsDevice"] = _alcGetContextsDevice; - _alcGetContextsDevice.sig = 'ii'; + }; + Module['_alcGetContextsDevice'] = _alcGetContextsDevice; + _alcGetContextsDevice.sig = 'pp'; - function _alcGetCurrentContext() { + var _alcGetCurrentContext = () => { if (AL.currentCtx !== null) { return AL.currentCtx.id; } return 0; - } - Module["_alcGetCurrentContext"] = _alcGetCurrentContext; - _alcGetCurrentContext.sig = 'i'; + }; + Module['_alcGetCurrentContext'] = _alcGetCurrentContext; + _alcGetCurrentContext.sig = 'p'; - function _alcGetEnumValue(deviceId, pEnumName) { + + var _alcGetEnumValue = (deviceId, pEnumName) => { // Spec says : // Using a NULL handle is legal, but only the // tokens defined by the AL core are guaranteed. @@ -11976,19 +12673,19 @@ var ASM_CONSTS = { AL.alcErr = 40964; return 0; } - } - Module["_alcGetEnumValue"] = _alcGetEnumValue; - _alcGetEnumValue.sig = 'iii'; + }; + Module['_alcGetEnumValue'] = _alcGetEnumValue; + _alcGetEnumValue.sig = 'ipp'; - function _alcGetError(deviceId) { + var _alcGetError = (deviceId) => { var err = AL.alcErr; AL.alcErr = 0; return err; - } - Module["_alcGetError"] = _alcGetError; - _alcGetError.sig = 'ii'; + }; + Module['_alcGetError'] = _alcGetError; + _alcGetError.sig = 'ip'; - function _alcGetIntegerv(deviceId, param, size, pValues) { + var _alcGetIntegerv = (deviceId, param, size, pValues) => { if (size === 0 || !pValues) { // Ignore the query, per the spec return; @@ -12101,12 +12798,12 @@ var ASM_CONSTS = { AL.alcErr = 40963; return; } - } - Module["_alcGetIntegerv"] = _alcGetIntegerv; - _alcGetIntegerv.sig = 'viiii'; + }; + Module['_alcGetIntegerv'] = _alcGetIntegerv; + _alcGetIntegerv.sig = 'vpiip'; - function _alcGetString(deviceId, param) { + var _alcGetString = (deviceId, param) => { if (AL.alcStringCache[param]) { return AL.alcStringCache[param]; } @@ -12179,33 +12876,35 @@ var ASM_CONSTS = { return 0; } - ret = allocateUTF8(ret); + ret = stringToNewUTF8(ret); AL.alcStringCache[param] = ret; return ret; - } - Module["_alcGetString"] = _alcGetString; - _alcGetString.sig = 'iii'; + }; + Module['_alcGetString'] = _alcGetString; + _alcGetString.sig = 'ppi'; - function _alcIsExtensionPresent(deviceId, pExtName) { + + var _alcIsExtensionPresent = (deviceId, pExtName) => { var name = UTF8ToString(pExtName); return AL.ALC_EXTENSIONS[name] ? 1 : 0; - } - Module["_alcIsExtensionPresent"] = _alcIsExtensionPresent; - _alcIsExtensionPresent.sig = 'iii'; + }; + Module['_alcIsExtensionPresent'] = _alcIsExtensionPresent; + _alcIsExtensionPresent.sig = 'ipp'; - function _alcMakeContextCurrent(contextId) { + var _alcMakeContextCurrent = (contextId) => { if (contextId === 0) { AL.currentCtx = null; } else { AL.currentCtx = AL.contexts[contextId]; } return 1; - } - Module["_alcMakeContextCurrent"] = _alcMakeContextCurrent; - _alcMakeContextCurrent.sig = 'ii'; + }; + Module['_alcMakeContextCurrent'] = _alcMakeContextCurrent; + _alcMakeContextCurrent.sig = 'ip'; - function _alcOpenDevice(pDeviceName) { + + var _alcOpenDevice = (pDeviceName) => { if (pDeviceName) { var name = UTF8ToString(pDeviceName); if (name !== AL.DEVICE_NAME) { @@ -12219,19 +12918,19 @@ var ASM_CONSTS = { return deviceId; } return 0; - } - Module["_alcOpenDevice"] = _alcOpenDevice; - _alcOpenDevice.sig = 'ii'; + }; + Module['_alcOpenDevice'] = _alcOpenDevice; + _alcOpenDevice.sig = 'pp'; - function _alcProcessContext(contextId) {} - Module["_alcProcessContext"] = _alcProcessContext; - _alcProcessContext.sig = 'vi'; + var _alcProcessContext = (contextId) => {}; + Module['_alcProcessContext'] = _alcProcessContext; + _alcProcessContext.sig = 'vp'; - function _alcSuspendContext(contextId) {} - Module["_alcSuspendContext"] = _alcSuspendContext; - _alcSuspendContext.sig = 'vi'; + var _alcSuspendContext = (contextId) => {}; + Module['_alcSuspendContext'] = _alcSuspendContext; + _alcSuspendContext.sig = 'vp'; - function _emscripten_alcDevicePauseSOFT(deviceId) { + var _emscripten_alcDevicePauseSOFT = (deviceId) => { if (!(deviceId in AL.deviceRefCounts)) { AL.alcErr = 40961; return; @@ -12252,11 +12951,11 @@ var ASM_CONSTS = { clearInterval(ctx.interval); ctx.interval = null; } - } - Module["_emscripten_alcDevicePauseSOFT"] = _emscripten_alcDevicePauseSOFT; + }; + Module['_emscripten_alcDevicePauseSOFT'] = _emscripten_alcDevicePauseSOFT; _emscripten_alcDevicePauseSOFT.sig = 'vi'; - function _emscripten_alcDeviceResumeSOFT(deviceId) { + var _emscripten_alcDeviceResumeSOFT = (deviceId) => { if (!(deviceId in AL.deviceRefCounts)) { AL.alcErr = 40961; return; @@ -12273,16 +12972,16 @@ var ASM_CONSTS = { continue; } - ctx.interval = setInterval(function() { AL.scheduleContextAudio(ctx); }, AL.QUEUE_INTERVAL); + ctx.interval = setInterval(() => AL.scheduleContextAudio(ctx), AL.QUEUE_INTERVAL); ctx.audioCtx.resume(); } - } - Module["_emscripten_alcDeviceResumeSOFT"] = _emscripten_alcDeviceResumeSOFT; + }; + Module['_emscripten_alcDeviceResumeSOFT'] = _emscripten_alcDeviceResumeSOFT; _emscripten_alcDeviceResumeSOFT.sig = 'vi'; - function _emscripten_alcGetStringiSOFT(deviceId, param, index) { + var _emscripten_alcGetStringiSOFT = (deviceId, param, index) => { if (!(deviceId in AL.deviceRefCounts)) { AL.alcErr = 40961; return 0; @@ -12310,14 +13009,14 @@ var ASM_CONSTS = { return _alcGetString(deviceId, param); } - ret = allocateUTF8(ret); + ret = stringToNewUTF8(ret); AL.alcStringCache[param] = ret; return ret; - } - Module["_emscripten_alcGetStringiSOFT"] = _emscripten_alcGetStringiSOFT; + }; + Module['_emscripten_alcGetStringiSOFT'] = _emscripten_alcGetStringiSOFT; _emscripten_alcGetStringiSOFT.sig = 'iiii'; - function _emscripten_alcResetDeviceSOFT(deviceId, pAttrList) { + var _emscripten_alcResetDeviceSOFT = (deviceId, pAttrList) => { if (!(deviceId in AL.deviceRefCounts)) { AL.alcErr = 40961; return 0; @@ -12359,13 +13058,13 @@ var ASM_CONSTS = { } return 1; - } - Module["_emscripten_alcResetDeviceSOFT"] = _emscripten_alcResetDeviceSOFT; + }; + Module['_emscripten_alcResetDeviceSOFT'] = _emscripten_alcResetDeviceSOFT; _emscripten_alcResetDeviceSOFT.sig = 'iii'; var readEmAsmArgsArray = []; - Module["readEmAsmArgsArray"] = readEmAsmArgsArray; - function readEmAsmArgs(sigPtr, buf) { + Module['readEmAsmArgsArray'] = readEmAsmArgsArray; + var readEmAsmArgs = (sigPtr, buf) => { // Nobody should have mutated _readEmAsmArgsArray underneath us to be something else than an array. assert(Array.isArray(readEmAsmArgsArray)); // The input buffer is allocated on the stack, so it must be stack-aligned. @@ -12374,148 +13073,239 @@ var ASM_CONSTS = { var ch; // Most arguments are i32s, so shift the buffer pointer so it is a plain // index into HEAP32. - buf >>= 2; while (ch = HEAPU8[sigPtr++]) { var chr = String.fromCharCode(ch); - var validChars = ['d', 'f', 'i']; - assert(validChars.includes(chr), 'Invalid character ' + ch + '("' + chr + '") in readEmAsmArgs! Use only [' + validChars + '], and do not specify "v" for void return argument.'); - // Floats are always passed as doubles, and doubles and int64s take up 8 - // bytes (two 32-bit slots) in memory, align reads to these: - buf += (ch != 105/*i*/) & buf; + var validChars = ['d', 'f', 'i', 'p']; + assert(validChars.includes(chr), `Invalid character ${ch}("${chr}") in readEmAsmArgs! Use only [${validChars}], and do not specify "v" for void return argument.`); + // Floats are always passed as doubles, so all types except for 'i' + // are 8 bytes and require alignment. + var wide = (ch != 105); + wide &= (ch != 112); + buf += wide && (buf % 8) ? 4 : 0; readEmAsmArgsArray.push( - ch == 105/*i*/ ? HEAP32[buf] : - HEAPF64[buf++ >> 1] + // Special case for pointers under wasm64 or CAN_ADDRESS_2GB mode. + ch == 112 ? HEAPU32[((buf)>>2)] : + ch == 105 ? + HEAP32[((buf)>>2)] : + HEAPF64[((buf)>>3)] ); - ++buf; + buf += wide ? 8 : 4; } return readEmAsmArgsArray; - } - Module["readEmAsmArgs"] = readEmAsmArgs; - function runEmAsmFunction(code, sigPtr, argbuf) { + }; + Module['readEmAsmArgs'] = readEmAsmArgs; + var runEmAsmFunction = (code, sigPtr, argbuf) => { var args = readEmAsmArgs(sigPtr, argbuf); - if (!ASM_CONSTS.hasOwnProperty(code)) abort('No EM_ASM constant found at address ' + code); - return ASM_CONSTS[code].apply(null, args); - } - Module["runEmAsmFunction"] = runEmAsmFunction; - runEmAsmFunction.sig = 'ippp'; - function _emscripten_asm_const_int(code, sigPtr, argbuf) { + assert(ASM_CONSTS.hasOwnProperty(code), `No EM_ASM constant found at address ${code}. The loaded WebAssembly file is likely out of sync with the generated JavaScript.`); + return ASM_CONSTS[code](...args); + }; + Module['runEmAsmFunction'] = runEmAsmFunction; + var _emscripten_asm_const_int = (code, sigPtr, argbuf) => { return runEmAsmFunction(code, sigPtr, argbuf); - } - Module["_emscripten_asm_const_int"] = _emscripten_asm_const_int; + }; + Module['_emscripten_asm_const_int'] = _emscripten_asm_const_int; _emscripten_asm_const_int.sig = 'ippp'; - function _emscripten_console_error(str) { + var _emscripten_console_error = (str) => { assert(typeof str == 'number'); console.error(UTF8ToString(str)); - } - Module["_emscripten_console_error"] = _emscripten_console_error; + }; + Module['_emscripten_console_error'] = _emscripten_console_error; _emscripten_console_error.sig = 'vp'; - function _emscripten_console_log(str) { + var _emscripten_console_log = (str) => { assert(typeof str == 'number'); console.log(UTF8ToString(str)); - } - Module["_emscripten_console_log"] = _emscripten_console_log; + }; + Module['_emscripten_console_log'] = _emscripten_console_log; _emscripten_console_log.sig = 'vp'; - function _emscripten_console_warn(str) { + var _emscripten_console_warn = (str) => { assert(typeof str == 'number'); console.warn(UTF8ToString(str)); - } - Module["_emscripten_console_warn"] = _emscripten_console_warn; + }; + Module['_emscripten_console_warn'] = _emscripten_console_warn; _emscripten_console_warn.sig = 'vp'; - function _emscripten_date_now() { - return Date.now(); - } - Module["_emscripten_date_now"] = _emscripten_date_now; + var _emscripten_date_now = () => Date.now(); + Module['_emscripten_date_now'] = _emscripten_date_now; _emscripten_date_now.sig = 'd'; - function getHeapMax() { - return HEAPU8.length; - } - Module["getHeapMax"] = getHeapMax; - function _emscripten_get_heap_max() { - return getHeapMax(); - } - Module["_emscripten_get_heap_max"] = _emscripten_get_heap_max; + var _emscripten_dbg = (str) => dbg(UTF8ToString(str)); + Module['_emscripten_dbg'] = _emscripten_dbg; + _emscripten_dbg.sig = 'vp'; + + var _emscripten_err = (str) => err(UTF8ToString(str)); + Module['_emscripten_err'] = _emscripten_err; + _emscripten_err.sig = 'vp'; + + var getHeapMax = () => + HEAPU8.length; + Module['getHeapMax'] = getHeapMax; + var _emscripten_get_heap_max = () => getHeapMax(); + Module['_emscripten_get_heap_max'] = _emscripten_get_heap_max; _emscripten_get_heap_max.sig = 'p'; - function _emscripten_get_now_res() { // return resolution of get_now, in nanoseconds + var _emscripten_get_now_res = () => { // return resolution of get_now, in nanoseconds if (ENVIRONMENT_IS_NODE) { return 1; // nanoseconds - } else + } // Modern environment where performance.now() is supported: return 1000; // microseconds (1/1000 of a millisecond) - } - Module["_emscripten_get_now_res"] = _emscripten_get_now_res; + }; + Module['_emscripten_get_now_res'] = _emscripten_get_now_res; + _emscripten_get_now_res.sig = 'd'; - function __webgl_enable_ANGLE_instanced_arrays(ctx) { + var webgl_enable_ANGLE_instanced_arrays = (ctx) => { // Extension available in WebGL 1 from Firefox 26 and Google Chrome 30 onwards. Core feature in WebGL 2. var ext = ctx.getExtension('ANGLE_instanced_arrays'); if (ext) { - ctx['vertexAttribDivisor'] = function(index, divisor) { ext['vertexAttribDivisorANGLE'](index, divisor); }; - ctx['drawArraysInstanced'] = function(mode, first, count, primcount) { ext['drawArraysInstancedANGLE'](mode, first, count, primcount); }; - ctx['drawElementsInstanced'] = function(mode, count, type, indices, primcount) { ext['drawElementsInstancedANGLE'](mode, count, type, indices, primcount); }; + ctx['vertexAttribDivisor'] = (index, divisor) => ext['vertexAttribDivisorANGLE'](index, divisor); + ctx['drawArraysInstanced'] = (mode, first, count, primcount) => ext['drawArraysInstancedANGLE'](mode, first, count, primcount); + ctx['drawElementsInstanced'] = (mode, count, type, indices, primcount) => ext['drawElementsInstancedANGLE'](mode, count, type, indices, primcount); return 1; } - } - Module["__webgl_enable_ANGLE_instanced_arrays"] = __webgl_enable_ANGLE_instanced_arrays; + }; + Module['webgl_enable_ANGLE_instanced_arrays'] = webgl_enable_ANGLE_instanced_arrays; - function __webgl_enable_OES_vertex_array_object(ctx) { + var webgl_enable_OES_vertex_array_object = (ctx) => { // Extension available in WebGL 1 from Firefox 25 and WebKit 536.28/desktop Safari 6.0.3 onwards. Core feature in WebGL 2. var ext = ctx.getExtension('OES_vertex_array_object'); if (ext) { - ctx['createVertexArray'] = function() { return ext['createVertexArrayOES'](); }; - ctx['deleteVertexArray'] = function(vao) { ext['deleteVertexArrayOES'](vao); }; - ctx['bindVertexArray'] = function(vao) { ext['bindVertexArrayOES'](vao); }; - ctx['isVertexArray'] = function(vao) { return ext['isVertexArrayOES'](vao); }; + ctx['createVertexArray'] = () => ext['createVertexArrayOES'](); + ctx['deleteVertexArray'] = (vao) => ext['deleteVertexArrayOES'](vao); + ctx['bindVertexArray'] = (vao) => ext['bindVertexArrayOES'](vao); + ctx['isVertexArray'] = (vao) => ext['isVertexArrayOES'](vao); return 1; } - } - Module["__webgl_enable_OES_vertex_array_object"] = __webgl_enable_OES_vertex_array_object; + }; + Module['webgl_enable_OES_vertex_array_object'] = webgl_enable_OES_vertex_array_object; - function __webgl_enable_WEBGL_draw_buffers(ctx) { + var webgl_enable_WEBGL_draw_buffers = (ctx) => { // Extension available in WebGL 1 from Firefox 28 onwards. Core feature in WebGL 2. var ext = ctx.getExtension('WEBGL_draw_buffers'); if (ext) { - ctx['drawBuffers'] = function(n, bufs) { ext['drawBuffersWEBGL'](n, bufs); }; + ctx['drawBuffers'] = (n, bufs) => ext['drawBuffersWEBGL'](n, bufs); return 1; } - } - Module["__webgl_enable_WEBGL_draw_buffers"] = __webgl_enable_WEBGL_draw_buffers; + }; + Module['webgl_enable_WEBGL_draw_buffers'] = webgl_enable_WEBGL_draw_buffers; - function __webgl_enable_WEBGL_multi_draw(ctx) { + var webgl_enable_WEBGL_multi_draw = (ctx) => { // Closure is expected to be allowed to minify the '.multiDrawWebgl' property, so not accessing it quoted. return !!(ctx.multiDrawWebgl = ctx.getExtension('WEBGL_multi_draw')); - } - Module["__webgl_enable_WEBGL_multi_draw"] = __webgl_enable_WEBGL_multi_draw; - - var GL = {counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],shaders:[],vaos:[],contexts:[],offscreenCanvases:{},queries:[],stringCache:{},unpackAlignment:4,recordError:function recordError(errorCode) { + }; + Module['webgl_enable_WEBGL_multi_draw'] = webgl_enable_WEBGL_multi_draw; + + var getEmscriptenSupportedExtensions = (ctx) => { + // Restrict the list of advertised extensions to those that we actually + // support. + var supportedExtensions = [ + // WebGL 1 extensions + 'ANGLE_instanced_arrays', + 'EXT_blend_minmax', + 'EXT_disjoint_timer_query', + 'EXT_frag_depth', + 'EXT_shader_texture_lod', + 'EXT_sRGB', + 'OES_element_index_uint', + 'OES_fbo_render_mipmap', + 'OES_standard_derivatives', + 'OES_texture_float', + 'OES_texture_half_float', + 'OES_texture_half_float_linear', + 'OES_vertex_array_object', + 'WEBGL_color_buffer_float', + 'WEBGL_depth_texture', + 'WEBGL_draw_buffers', + // WebGL 1 and WebGL 2 extensions + 'EXT_color_buffer_half_float', + 'EXT_depth_clamp', + 'EXT_float_blend', + 'EXT_texture_compression_bptc', + 'EXT_texture_compression_rgtc', + 'EXT_texture_filter_anisotropic', + 'KHR_parallel_shader_compile', + 'OES_texture_float_linear', + 'WEBGL_blend_func_extended', + 'WEBGL_compressed_texture_astc', + 'WEBGL_compressed_texture_etc', + 'WEBGL_compressed_texture_etc1', + 'WEBGL_compressed_texture_s3tc', + 'WEBGL_compressed_texture_s3tc_srgb', + 'WEBGL_debug_renderer_info', + 'WEBGL_debug_shaders', + 'WEBGL_lose_context', + 'WEBGL_multi_draw', + ]; + // .getSupportedExtensions() can return null if context is lost, so coerce to empty array. + return (ctx.getSupportedExtensions() || []).filter(ext => supportedExtensions.includes(ext)); + }; + Module['getEmscriptenSupportedExtensions'] = getEmscriptenSupportedExtensions; + + + var GL = { + counter:1, + buffers:[], + programs:[], + framebuffers:[], + renderbuffers:[], + textures:[], + shaders:[], + vaos:[], + contexts:[], + offscreenCanvases:{ + }, + queries:[], + stringCache:{ + }, + unpackAlignment:4, + recordError:(errorCode) => { if (!GL.lastError) { GL.lastError = errorCode; } - },getNewId:function(table) { + }, + getNewId:(table) => { var ret = GL.counter++; for (var i = table.length; i < ret; i++) { table[i] = null; } return ret; - },getSource:function(shader, count, string, length) { + }, + genObject:(n, buffers, createFunction, objectTable + ) => { + for (var i = 0; i < n; i++) { + var buffer = GLctx[createFunction](); + var id = buffer && GL.getNewId(objectTable); + if (buffer) { + buffer.name = id; + objectTable[id] = buffer; + } else { + GL.recordError(0x502 /* GL_INVALID_OPERATION */); + } + HEAP32[(((buffers)+(i*4))>>2)] = id; + } + }, + getSource:(shader, count, string, length) => { var source = ''; for (var i = 0; i < count; ++i) { - var len = length ? HEAP32[(((length)+(i*4))>>2)] : -1; - source += UTF8ToString(HEAP32[(((string)+(i*4))>>2)], len < 0 ? undefined : len); + var len = length ? HEAPU32[(((length)+(i*4))>>2)] : undefined; + source += UTF8ToString(HEAPU32[(((string)+(i*4))>>2)], len); } return source; - },createContext:function(/** @type {HTMLCanvasElement} */ canvas, webGLContextAttributes) { - - // BUG: Workaround Safari WebGL issue: After successfully acquiring WebGL context on a canvas, - // calling .getContext() will always return that context independent of which 'webgl' or 'webgl2' - // context version was passed. See https://bugs.webkit.org/show_bug.cgi?id=222758 and - // https://github.com/emscripten-core/emscripten/issues/13295. - // TODO: Once the bug is fixed and shipped in Safari, adjust the Safari version field in above check. + }, + createContext:(/** @type {HTMLCanvasElement} */ canvas, webGLContextAttributes) => { + + // BUG: Workaround Safari WebGL issue: After successfully acquiring WebGL + // context on a canvas, calling .getContext() will always return that + // context independent of which 'webgl' or 'webgl2' + // context version was passed. See: + // https://bugs.webkit.org/show_bug.cgi?id=222758 + // and: + // https://github.com/emscripten-core/emscripten/issues/13295. + // TODO: Once the bug is fixed and shipped in Safari, adjust the Safari + // version field in above check. if (!canvas.getContextSafariWebGL2Fixed) { canvas.getContextSafariWebGL2Fixed = canvas.getContext; /** @type {function(this:HTMLCanvasElement, string, (Object|null)=): (Object|null)} */ @@ -12536,18 +13326,20 @@ var ASM_CONSTS = { var handle = GL.registerContext(ctx, webGLContextAttributes); return handle; - },registerContext:function(ctx, webGLContextAttributes) { + }, + registerContext:(ctx, webGLContextAttributes) => { // without pthreads a context is just an integer ID var handle = GL.getNewId(GL.contexts); var context = { - handle: handle, + handle, attributes: webGLContextAttributes, version: webGLContextAttributes.majorVersion, GLctx: ctx }; - // Store the created context object so that we can access the context given a canvas without having to pass the parameters again. + // Store the created context object so that we can access the context + // given a canvas without having to pass the parameters again. if (ctx.canvas) ctx.canvas.GLctxObject = context; GL.contexts[handle] = context; if (typeof webGLContextAttributes.enableExtensionsByDefault == 'undefined' || webGLContextAttributes.enableExtensionsByDefault) { @@ -12555,221 +13347,369 @@ var ASM_CONSTS = { } return handle; - },makeContextCurrent:function(contextHandle) { + }, + makeContextCurrent:(contextHandle) => { - GL.currentContext = GL.contexts[contextHandle]; // Active Emscripten GL layer context object. - Module.ctx = GLctx = GL.currentContext && GL.currentContext.GLctx; // Active WebGL context object. + // Active Emscripten GL layer context object. + GL.currentContext = GL.contexts[contextHandle]; + // Active WebGL context object. + Module.ctx = GLctx = GL.currentContext?.GLctx; return !(contextHandle && !GLctx); - },getContext:function(contextHandle) { + }, + getContext:(contextHandle) => { return GL.contexts[contextHandle]; - },deleteContext:function(contextHandle) { - if (GL.currentContext === GL.contexts[contextHandle]) GL.currentContext = null; - if (typeof JSEvents == 'object') JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas); // Release all JS event handlers on the DOM element that the GL context is associated with since the context is now deleted. - if (GL.contexts[contextHandle] && GL.contexts[contextHandle].GLctx.canvas) GL.contexts[contextHandle].GLctx.canvas.GLctxObject = undefined; // Make sure the canvas object no longer refers to the context object so there are no GC surprises. + }, + deleteContext:(contextHandle) => { + if (GL.currentContext === GL.contexts[contextHandle]) { + GL.currentContext = null; + } + if (typeof JSEvents == 'object') { + // Release all JS event handlers on the DOM element that the GL context is + // associated with since the context is now deleted. + JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas); + } + // Make sure the canvas object no longer refers to the context object so + // there are no GC surprises. + if (GL.contexts[contextHandle] && GL.contexts[contextHandle].GLctx.canvas) { + GL.contexts[contextHandle].GLctx.canvas.GLctxObject = undefined; + } GL.contexts[contextHandle] = null; - },initExtensions:function(context) { - // If this function is called without a specific context object, init the extensions of the currently active context. - if (!context) context = GL.currentContext; + }, + initExtensions:(context) => { + // If this function is called without a specific context object, init the + // extensions of the currently active context. + context ||= GL.currentContext; if (context.initExtensionsDone) return; context.initExtensionsDone = true; var GLctx = context.GLctx; - // Detect the presence of a few extensions manually, this GL interop layer itself will need to know if they exist. + // Detect the presence of a few extensions manually, ction GL interop + // layer itself will need to know if they exist. - // Extensions that are only available in WebGL 1 (the calls will be no-ops if called on a WebGL 2 context active) - __webgl_enable_ANGLE_instanced_arrays(GLctx); - __webgl_enable_OES_vertex_array_object(GLctx); - __webgl_enable_WEBGL_draw_buffers(GLctx); + // Extensions that are only available in WebGL 1 (the calls will be no-ops + // if called on a WebGL 2 context active) + webgl_enable_ANGLE_instanced_arrays(GLctx); + webgl_enable_OES_vertex_array_object(GLctx); + webgl_enable_WEBGL_draw_buffers(GLctx); { GLctx.disjointTimerQueryExt = GLctx.getExtension("EXT_disjoint_timer_query"); } - __webgl_enable_WEBGL_multi_draw(GLctx); + webgl_enable_WEBGL_multi_draw(GLctx); - // .getSupportedExtensions() can return null if context is lost, so coerce to empty array. - var exts = GLctx.getSupportedExtensions() || []; - exts.forEach(function(ext) { - // WEBGL_lose_context, WEBGL_debug_renderer_info and WEBGL_debug_shaders are not enabled by default. + getEmscriptenSupportedExtensions(GLctx).forEach((ext) => { + // WEBGL_lose_context, WEBGL_debug_renderer_info and WEBGL_debug_shaders + // are not enabled by default. if (!ext.includes('lose_context') && !ext.includes('debug')) { // Call .getExtension() to enable that extension permanently. GLctx.getExtension(ext); } }); - }}; - Module["GL"] = GL; - function _emscripten_glActiveTexture(x0) { GLctx['activeTexture'](x0) } - Module["_emscripten_glActiveTexture"] = _emscripten_glActiveTexture; + }, + }; + Module['GL'] = GL; + /** @suppress {duplicate } */ + var _glActiveTexture = (x0) => GLctx.activeTexture(x0); + Module['_glActiveTexture'] = _glActiveTexture; + _glActiveTexture.sig = 'vi'; + var _emscripten_glActiveTexture = _glActiveTexture; + Module['_emscripten_glActiveTexture'] = _emscripten_glActiveTexture; _emscripten_glActiveTexture.sig = 'vi'; - function _emscripten_glAttachShader(program, shader) { + /** @suppress {duplicate } */ + var _glAttachShader = (program, shader) => { GLctx.attachShader(GL.programs[program], GL.shaders[shader]); - } - Module["_emscripten_glAttachShader"] = _emscripten_glAttachShader; + }; + Module['_glAttachShader'] = _glAttachShader; + _glAttachShader.sig = 'vii'; + var _emscripten_glAttachShader = _glAttachShader; + Module['_emscripten_glAttachShader'] = _emscripten_glAttachShader; _emscripten_glAttachShader.sig = 'vii'; - function _emscripten_glBeginQueryEXT(target, id) { + /** @suppress {duplicate } */ + var _glBeginQueryEXT = (target, id) => { GLctx.disjointTimerQueryExt['beginQueryEXT'](target, GL.queries[id]); - } - Module["_emscripten_glBeginQueryEXT"] = _emscripten_glBeginQueryEXT; - _emscripten_glBeginQueryEXT.sig = 'vii'; + }; + Module['_glBeginQueryEXT'] = _glBeginQueryEXT; + _glBeginQueryEXT.sig = 'vii'; + var _emscripten_glBeginQueryEXT = _glBeginQueryEXT; + Module['_emscripten_glBeginQueryEXT'] = _emscripten_glBeginQueryEXT; - function _emscripten_glBindAttribLocation(program, index, name) { + + /** @suppress {duplicate } */ + var _glBindAttribLocation = (program, index, name) => { GLctx.bindAttribLocation(GL.programs[program], index, UTF8ToString(name)); - } - Module["_emscripten_glBindAttribLocation"] = _emscripten_glBindAttribLocation; - _emscripten_glBindAttribLocation.sig = 'viii'; + }; + Module['_glBindAttribLocation'] = _glBindAttribLocation; + _glBindAttribLocation.sig = 'viip'; + var _emscripten_glBindAttribLocation = _glBindAttribLocation; + Module['_emscripten_glBindAttribLocation'] = _emscripten_glBindAttribLocation; + _emscripten_glBindAttribLocation.sig = 'viip'; - function _emscripten_glBindBuffer(target, buffer) { + /** @suppress {duplicate } */ + var _glBindBuffer = (target, buffer) => { GLctx.bindBuffer(target, GL.buffers[buffer]); - } - Module["_emscripten_glBindBuffer"] = _emscripten_glBindBuffer; + }; + Module['_glBindBuffer'] = _glBindBuffer; + _glBindBuffer.sig = 'vii'; + var _emscripten_glBindBuffer = _glBindBuffer; + Module['_emscripten_glBindBuffer'] = _emscripten_glBindBuffer; _emscripten_glBindBuffer.sig = 'vii'; - function _emscripten_glBindFramebuffer(target, framebuffer) { + /** @suppress {duplicate } */ + var _glBindFramebuffer = (target, framebuffer) => { GLctx.bindFramebuffer(target, GL.framebuffers[framebuffer]); - } - Module["_emscripten_glBindFramebuffer"] = _emscripten_glBindFramebuffer; + }; + Module['_glBindFramebuffer'] = _glBindFramebuffer; + _glBindFramebuffer.sig = 'vii'; + var _emscripten_glBindFramebuffer = _glBindFramebuffer; + Module['_emscripten_glBindFramebuffer'] = _emscripten_glBindFramebuffer; _emscripten_glBindFramebuffer.sig = 'vii'; - function _emscripten_glBindRenderbuffer(target, renderbuffer) { + /** @suppress {duplicate } */ + var _glBindRenderbuffer = (target, renderbuffer) => { GLctx.bindRenderbuffer(target, GL.renderbuffers[renderbuffer]); - } - Module["_emscripten_glBindRenderbuffer"] = _emscripten_glBindRenderbuffer; + }; + Module['_glBindRenderbuffer'] = _glBindRenderbuffer; + _glBindRenderbuffer.sig = 'vii'; + var _emscripten_glBindRenderbuffer = _glBindRenderbuffer; + Module['_emscripten_glBindRenderbuffer'] = _emscripten_glBindRenderbuffer; _emscripten_glBindRenderbuffer.sig = 'vii'; - function _emscripten_glBindTexture(target, texture) { + /** @suppress {duplicate } */ + var _glBindTexture = (target, texture) => { GLctx.bindTexture(target, GL.textures[texture]); - } - Module["_emscripten_glBindTexture"] = _emscripten_glBindTexture; + }; + Module['_glBindTexture'] = _glBindTexture; + _glBindTexture.sig = 'vii'; + var _emscripten_glBindTexture = _glBindTexture; + Module['_emscripten_glBindTexture'] = _emscripten_glBindTexture; _emscripten_glBindTexture.sig = 'vii'; - function _emscripten_glBindVertexArrayOES(vao) { - GLctx['bindVertexArray'](GL.vaos[vao]); - } - Module["_emscripten_glBindVertexArrayOES"] = _emscripten_glBindVertexArrayOES; + + /** @suppress {duplicate } */ + var _glBindVertexArray = (vao) => { + GLctx.bindVertexArray(GL.vaos[vao]); + }; + Module['_glBindVertexArray'] = _glBindVertexArray; + _glBindVertexArray.sig = 'vi'; + /** @suppress {duplicate } */ + var _glBindVertexArrayOES = _glBindVertexArray; + Module['_glBindVertexArrayOES'] = _glBindVertexArrayOES; + _glBindVertexArrayOES.sig = 'vi'; + var _emscripten_glBindVertexArrayOES = _glBindVertexArrayOES; + Module['_emscripten_glBindVertexArrayOES'] = _emscripten_glBindVertexArrayOES; _emscripten_glBindVertexArrayOES.sig = 'vi'; - function _emscripten_glBlendColor(x0, x1, x2, x3) { GLctx['blendColor'](x0, x1, x2, x3) } - Module["_emscripten_glBlendColor"] = _emscripten_glBlendColor; + /** @suppress {duplicate } */ + var _glBlendColor = (x0, x1, x2, x3) => GLctx.blendColor(x0, x1, x2, x3); + Module['_glBlendColor'] = _glBlendColor; + _glBlendColor.sig = 'vffff'; + var _emscripten_glBlendColor = _glBlendColor; + Module['_emscripten_glBlendColor'] = _emscripten_glBlendColor; _emscripten_glBlendColor.sig = 'vffff'; - function _emscripten_glBlendEquation(x0) { GLctx['blendEquation'](x0) } - Module["_emscripten_glBlendEquation"] = _emscripten_glBlendEquation; + /** @suppress {duplicate } */ + var _glBlendEquation = (x0) => GLctx.blendEquation(x0); + Module['_glBlendEquation'] = _glBlendEquation; + _glBlendEquation.sig = 'vi'; + var _emscripten_glBlendEquation = _glBlendEquation; + Module['_emscripten_glBlendEquation'] = _emscripten_glBlendEquation; _emscripten_glBlendEquation.sig = 'vi'; - function _emscripten_glBlendEquationSeparate(x0, x1) { GLctx['blendEquationSeparate'](x0, x1) } - Module["_emscripten_glBlendEquationSeparate"] = _emscripten_glBlendEquationSeparate; + /** @suppress {duplicate } */ + var _glBlendEquationSeparate = (x0, x1) => GLctx.blendEquationSeparate(x0, x1); + Module['_glBlendEquationSeparate'] = _glBlendEquationSeparate; + _glBlendEquationSeparate.sig = 'vii'; + var _emscripten_glBlendEquationSeparate = _glBlendEquationSeparate; + Module['_emscripten_glBlendEquationSeparate'] = _emscripten_glBlendEquationSeparate; _emscripten_glBlendEquationSeparate.sig = 'vii'; - function _emscripten_glBlendFunc(x0, x1) { GLctx['blendFunc'](x0, x1) } - Module["_emscripten_glBlendFunc"] = _emscripten_glBlendFunc; + /** @suppress {duplicate } */ + var _glBlendFunc = (x0, x1) => GLctx.blendFunc(x0, x1); + Module['_glBlendFunc'] = _glBlendFunc; + _glBlendFunc.sig = 'vii'; + var _emscripten_glBlendFunc = _glBlendFunc; + Module['_emscripten_glBlendFunc'] = _emscripten_glBlendFunc; _emscripten_glBlendFunc.sig = 'vii'; - function _emscripten_glBlendFuncSeparate(x0, x1, x2, x3) { GLctx['blendFuncSeparate'](x0, x1, x2, x3) } - Module["_emscripten_glBlendFuncSeparate"] = _emscripten_glBlendFuncSeparate; + /** @suppress {duplicate } */ + var _glBlendFuncSeparate = (x0, x1, x2, x3) => GLctx.blendFuncSeparate(x0, x1, x2, x3); + Module['_glBlendFuncSeparate'] = _glBlendFuncSeparate; + _glBlendFuncSeparate.sig = 'viiii'; + var _emscripten_glBlendFuncSeparate = _glBlendFuncSeparate; + Module['_emscripten_glBlendFuncSeparate'] = _emscripten_glBlendFuncSeparate; _emscripten_glBlendFuncSeparate.sig = 'viiii'; - function _emscripten_glBufferData(target, size, data, usage) { + /** @suppress {duplicate } */ + var _glBufferData = (target, size, data, usage) => { - // N.b. here first form specifies a heap subarray, second form an integer size, so the ?: code here is polymorphic. It is advised to avoid - // randomly mixing both uses in calling code, to avoid any potential JS engine JIT issues. - GLctx.bufferData(target, data ? HEAPU8.subarray(data, data+size) : size, usage); - } - Module["_emscripten_glBufferData"] = _emscripten_glBufferData; - _emscripten_glBufferData.sig = 'viiii'; - - function _emscripten_glBufferSubData(target, offset, size, data) { + // N.b. here first form specifies a heap subarray, second form an integer + // size, so the ?: code here is polymorphic. It is advised to avoid + // randomly mixing both uses in calling code, to avoid any potential JS + // engine JIT issues. + GLctx.bufferData(target, data ? HEAPU8.subarray(data, data+size) : size, usage); + }; + Module['_glBufferData'] = _glBufferData; + _glBufferData.sig = 'vippi'; + var _emscripten_glBufferData = _glBufferData; + Module['_emscripten_glBufferData'] = _emscripten_glBufferData; + _emscripten_glBufferData.sig = 'vippi'; + + /** @suppress {duplicate } */ + var _glBufferSubData = (target, offset, size, data) => { GLctx.bufferSubData(target, offset, HEAPU8.subarray(data, data+size)); - } - Module["_emscripten_glBufferSubData"] = _emscripten_glBufferSubData; - _emscripten_glBufferSubData.sig = 'viiii'; - - function _emscripten_glCheckFramebufferStatus(x0) { return GLctx['checkFramebufferStatus'](x0) } - Module["_emscripten_glCheckFramebufferStatus"] = _emscripten_glCheckFramebufferStatus; + }; + Module['_glBufferSubData'] = _glBufferSubData; + _glBufferSubData.sig = 'vippp'; + var _emscripten_glBufferSubData = _glBufferSubData; + Module['_emscripten_glBufferSubData'] = _emscripten_glBufferSubData; + _emscripten_glBufferSubData.sig = 'vippp'; + + /** @suppress {duplicate } */ + var _glCheckFramebufferStatus = (x0) => GLctx.checkFramebufferStatus(x0); + Module['_glCheckFramebufferStatus'] = _glCheckFramebufferStatus; + _glCheckFramebufferStatus.sig = 'ii'; + var _emscripten_glCheckFramebufferStatus = _glCheckFramebufferStatus; + Module['_emscripten_glCheckFramebufferStatus'] = _emscripten_glCheckFramebufferStatus; _emscripten_glCheckFramebufferStatus.sig = 'ii'; - function _emscripten_glClear(x0) { GLctx['clear'](x0) } - Module["_emscripten_glClear"] = _emscripten_glClear; + /** @suppress {duplicate } */ + var _glClear = (x0) => GLctx.clear(x0); + Module['_glClear'] = _glClear; + _glClear.sig = 'vi'; + var _emscripten_glClear = _glClear; + Module['_emscripten_glClear'] = _emscripten_glClear; _emscripten_glClear.sig = 'vi'; - function _emscripten_glClearColor(x0, x1, x2, x3) { GLctx['clearColor'](x0, x1, x2, x3) } - Module["_emscripten_glClearColor"] = _emscripten_glClearColor; + /** @suppress {duplicate } */ + var _glClearColor = (x0, x1, x2, x3) => GLctx.clearColor(x0, x1, x2, x3); + Module['_glClearColor'] = _glClearColor; + _glClearColor.sig = 'vffff'; + var _emscripten_glClearColor = _glClearColor; + Module['_emscripten_glClearColor'] = _emscripten_glClearColor; _emscripten_glClearColor.sig = 'vffff'; - function _emscripten_glClearDepthf(x0) { GLctx['clearDepth'](x0) } - Module["_emscripten_glClearDepthf"] = _emscripten_glClearDepthf; + /** @suppress {duplicate } */ + var _glClearDepthf = (x0) => GLctx.clearDepth(x0); + Module['_glClearDepthf'] = _glClearDepthf; + _glClearDepthf.sig = 'vf'; + var _emscripten_glClearDepthf = _glClearDepthf; + Module['_emscripten_glClearDepthf'] = _emscripten_glClearDepthf; _emscripten_glClearDepthf.sig = 'vf'; - function _emscripten_glClearStencil(x0) { GLctx['clearStencil'](x0) } - Module["_emscripten_glClearStencil"] = _emscripten_glClearStencil; + /** @suppress {duplicate } */ + var _glClearStencil = (x0) => GLctx.clearStencil(x0); + Module['_glClearStencil'] = _glClearStencil; + _glClearStencil.sig = 'vi'; + var _emscripten_glClearStencil = _glClearStencil; + Module['_emscripten_glClearStencil'] = _emscripten_glClearStencil; _emscripten_glClearStencil.sig = 'vi'; - function _emscripten_glColorMask(red, green, blue, alpha) { + /** @suppress {duplicate } */ + var _glColorMask = (red, green, blue, alpha) => { GLctx.colorMask(!!red, !!green, !!blue, !!alpha); - } - Module["_emscripten_glColorMask"] = _emscripten_glColorMask; + }; + Module['_glColorMask'] = _glColorMask; + _glColorMask.sig = 'viiii'; + var _emscripten_glColorMask = _glColorMask; + Module['_emscripten_glColorMask'] = _emscripten_glColorMask; _emscripten_glColorMask.sig = 'viiii'; - function _emscripten_glCompileShader(shader) { + /** @suppress {duplicate } */ + var _glCompileShader = (shader) => { GLctx.compileShader(GL.shaders[shader]); - } - Module["_emscripten_glCompileShader"] = _emscripten_glCompileShader; + }; + Module['_glCompileShader'] = _glCompileShader; + _glCompileShader.sig = 'vi'; + var _emscripten_glCompileShader = _glCompileShader; + Module['_emscripten_glCompileShader'] = _emscripten_glCompileShader; _emscripten_glCompileShader.sig = 'vi'; - function _emscripten_glCompressedTexImage2D(target, level, internalFormat, width, height, border, imageSize, data) { - GLctx['compressedTexImage2D'](target, level, internalFormat, width, height, border, data ? HEAPU8.subarray((data), (data+imageSize)) : null); - } - Module["_emscripten_glCompressedTexImage2D"] = _emscripten_glCompressedTexImage2D; - _emscripten_glCompressedTexImage2D.sig = 'viiiiiiii'; - - function _emscripten_glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data) { - GLctx['compressedTexSubImage2D'](target, level, xoffset, yoffset, width, height, format, data ? HEAPU8.subarray((data), (data+imageSize)) : null); - } - Module["_emscripten_glCompressedTexSubImage2D"] = _emscripten_glCompressedTexSubImage2D; - _emscripten_glCompressedTexSubImage2D.sig = 'viiiiiiiii'; - - function _emscripten_glCopyTexImage2D(x0, x1, x2, x3, x4, x5, x6, x7) { GLctx['copyTexImage2D'](x0, x1, x2, x3, x4, x5, x6, x7) } - Module["_emscripten_glCopyTexImage2D"] = _emscripten_glCopyTexImage2D; + /** @suppress {duplicate } */ + var _glCompressedTexImage2D = (target, level, internalFormat, width, height, border, imageSize, data) => { + GLctx.compressedTexImage2D(target, level, internalFormat, width, height, border, data ? HEAPU8.subarray((data), data+imageSize) : null); + }; + Module['_glCompressedTexImage2D'] = _glCompressedTexImage2D; + _glCompressedTexImage2D.sig = 'viiiiiiip'; + var _emscripten_glCompressedTexImage2D = _glCompressedTexImage2D; + Module['_emscripten_glCompressedTexImage2D'] = _emscripten_glCompressedTexImage2D; + _emscripten_glCompressedTexImage2D.sig = 'viiiiiiip'; + + /** @suppress {duplicate } */ + var _glCompressedTexSubImage2D = (target, level, xoffset, yoffset, width, height, format, imageSize, data) => { + GLctx.compressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, data ? HEAPU8.subarray((data), data+imageSize) : null); + }; + Module['_glCompressedTexSubImage2D'] = _glCompressedTexSubImage2D; + _glCompressedTexSubImage2D.sig = 'viiiiiiiip'; + var _emscripten_glCompressedTexSubImage2D = _glCompressedTexSubImage2D; + Module['_emscripten_glCompressedTexSubImage2D'] = _emscripten_glCompressedTexSubImage2D; + _emscripten_glCompressedTexSubImage2D.sig = 'viiiiiiiip'; + + /** @suppress {duplicate } */ + var _glCopyTexImage2D = (x0, x1, x2, x3, x4, x5, x6, x7) => GLctx.copyTexImage2D(x0, x1, x2, x3, x4, x5, x6, x7); + Module['_glCopyTexImage2D'] = _glCopyTexImage2D; + _glCopyTexImage2D.sig = 'viiiiiiii'; + var _emscripten_glCopyTexImage2D = _glCopyTexImage2D; + Module['_emscripten_glCopyTexImage2D'] = _emscripten_glCopyTexImage2D; _emscripten_glCopyTexImage2D.sig = 'viiiiiiii'; - function _emscripten_glCopyTexSubImage2D(x0, x1, x2, x3, x4, x5, x6, x7) { GLctx['copyTexSubImage2D'](x0, x1, x2, x3, x4, x5, x6, x7) } - Module["_emscripten_glCopyTexSubImage2D"] = _emscripten_glCopyTexSubImage2D; + /** @suppress {duplicate } */ + var _glCopyTexSubImage2D = (x0, x1, x2, x3, x4, x5, x6, x7) => GLctx.copyTexSubImage2D(x0, x1, x2, x3, x4, x5, x6, x7); + Module['_glCopyTexSubImage2D'] = _glCopyTexSubImage2D; + _glCopyTexSubImage2D.sig = 'viiiiiiii'; + var _emscripten_glCopyTexSubImage2D = _glCopyTexSubImage2D; + Module['_emscripten_glCopyTexSubImage2D'] = _emscripten_glCopyTexSubImage2D; _emscripten_glCopyTexSubImage2D.sig = 'viiiiiiii'; - function _emscripten_glCreateProgram() { + /** @suppress {duplicate } */ + var _glCreateProgram = () => { var id = GL.getNewId(GL.programs); var program = GLctx.createProgram(); // Store additional information needed for each shader program: program.name = id; - // Lazy cache results of glGetProgramiv(GL_ACTIVE_UNIFORM_MAX_LENGTH/GL_ACTIVE_ATTRIBUTE_MAX_LENGTH/GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH) + // Lazy cache results of + // glGetProgramiv(GL_ACTIVE_UNIFORM_MAX_LENGTH/GL_ACTIVE_ATTRIBUTE_MAX_LENGTH/GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH) program.maxUniformLength = program.maxAttributeLength = program.maxUniformBlockNameLength = 0; program.uniformIdCounter = 1; GL.programs[id] = program; return id; - } - Module["_emscripten_glCreateProgram"] = _emscripten_glCreateProgram; + }; + Module['_glCreateProgram'] = _glCreateProgram; + _glCreateProgram.sig = 'i'; + var _emscripten_glCreateProgram = _glCreateProgram; + Module['_emscripten_glCreateProgram'] = _emscripten_glCreateProgram; _emscripten_glCreateProgram.sig = 'i'; - function _emscripten_glCreateShader(shaderType) { + /** @suppress {duplicate } */ + var _glCreateShader = (shaderType) => { var id = GL.getNewId(GL.shaders); GL.shaders[id] = GLctx.createShader(shaderType); return id; - } - Module["_emscripten_glCreateShader"] = _emscripten_glCreateShader; + }; + Module['_glCreateShader'] = _glCreateShader; + _glCreateShader.sig = 'ii'; + var _emscripten_glCreateShader = _glCreateShader; + Module['_emscripten_glCreateShader'] = _emscripten_glCreateShader; _emscripten_glCreateShader.sig = 'ii'; - function _emscripten_glCullFace(x0) { GLctx['cullFace'](x0) } - Module["_emscripten_glCullFace"] = _emscripten_glCullFace; + /** @suppress {duplicate } */ + var _glCullFace = (x0) => GLctx.cullFace(x0); + Module['_glCullFace'] = _glCullFace; + _glCullFace.sig = 'vi'; + var _emscripten_glCullFace = _glCullFace; + Module['_emscripten_glCullFace'] = _emscripten_glCullFace; _emscripten_glCullFace.sig = 'vi'; - function _emscripten_glDeleteBuffers(n, buffers) { + /** @suppress {duplicate } */ + var _glDeleteBuffers = (n, buffers) => { for (var i = 0; i < n; i++) { var id = HEAP32[(((buffers)+(i*4))>>2)]; var buffer = GL.buffers[id]; @@ -12783,11 +13723,15 @@ var ASM_CONSTS = { GL.buffers[id] = null; } - } - Module["_emscripten_glDeleteBuffers"] = _emscripten_glDeleteBuffers; - _emscripten_glDeleteBuffers.sig = 'vii'; - - function _emscripten_glDeleteFramebuffers(n, framebuffers) { + }; + Module['_glDeleteBuffers'] = _glDeleteBuffers; + _glDeleteBuffers.sig = 'vip'; + var _emscripten_glDeleteBuffers = _glDeleteBuffers; + Module['_emscripten_glDeleteBuffers'] = _emscripten_glDeleteBuffers; + _emscripten_glDeleteBuffers.sig = 'vip'; + + /** @suppress {duplicate } */ + var _glDeleteFramebuffers = (n, framebuffers) => { for (var i = 0; i < n; ++i) { var id = HEAP32[(((framebuffers)+(i*4))>>2)]; var framebuffer = GL.framebuffers[id]; @@ -12796,25 +13740,35 @@ var ASM_CONSTS = { framebuffer.name = 0; GL.framebuffers[id] = null; } - } - Module["_emscripten_glDeleteFramebuffers"] = _emscripten_glDeleteFramebuffers; - _emscripten_glDeleteFramebuffers.sig = 'vii'; - - function _emscripten_glDeleteProgram(id) { + }; + Module['_glDeleteFramebuffers'] = _glDeleteFramebuffers; + _glDeleteFramebuffers.sig = 'vip'; + var _emscripten_glDeleteFramebuffers = _glDeleteFramebuffers; + Module['_emscripten_glDeleteFramebuffers'] = _emscripten_glDeleteFramebuffers; + _emscripten_glDeleteFramebuffers.sig = 'vip'; + + /** @suppress {duplicate } */ + var _glDeleteProgram = (id) => { if (!id) return; var program = GL.programs[id]; - if (!program) { // glDeleteProgram actually signals an error when deleting a nonexisting object, unlike some other GL delete functions. + if (!program) { + // glDeleteProgram actually signals an error when deleting a nonexisting + // object, unlike some other GL delete functions. GL.recordError(0x501 /* GL_INVALID_VALUE */); return; } GLctx.deleteProgram(program); program.name = 0; GL.programs[id] = null; - } - Module["_emscripten_glDeleteProgram"] = _emscripten_glDeleteProgram; + }; + Module['_glDeleteProgram'] = _glDeleteProgram; + _glDeleteProgram.sig = 'vi'; + var _emscripten_glDeleteProgram = _glDeleteProgram; + Module['_emscripten_glDeleteProgram'] = _emscripten_glDeleteProgram; _emscripten_glDeleteProgram.sig = 'vi'; - function _emscripten_glDeleteQueriesEXT(n, ids) { + /** @suppress {duplicate } */ + var _glDeleteQueriesEXT = (n, ids) => { for (var i = 0; i < n; i++) { var id = HEAP32[(((ids)+(i*4))>>2)]; var query = GL.queries[id]; @@ -12822,11 +13776,14 @@ var ASM_CONSTS = { GLctx.disjointTimerQueryExt['deleteQueryEXT'](query); GL.queries[id] = null; } - } - Module["_emscripten_glDeleteQueriesEXT"] = _emscripten_glDeleteQueriesEXT; - _emscripten_glDeleteQueriesEXT.sig = 'vii'; + }; + Module['_glDeleteQueriesEXT'] = _glDeleteQueriesEXT; + _glDeleteQueriesEXT.sig = 'vip'; + var _emscripten_glDeleteQueriesEXT = _glDeleteQueriesEXT; + Module['_emscripten_glDeleteQueriesEXT'] = _emscripten_glDeleteQueriesEXT; - function _emscripten_glDeleteRenderbuffers(n, renderbuffers) { + /** @suppress {duplicate } */ + var _glDeleteRenderbuffers = (n, renderbuffers) => { for (var i = 0; i < n; i++) { var id = HEAP32[(((renderbuffers)+(i*4))>>2)]; var renderbuffer = GL.renderbuffers[id]; @@ -12835,194 +13792,293 @@ var ASM_CONSTS = { renderbuffer.name = 0; GL.renderbuffers[id] = null; } - } - Module["_emscripten_glDeleteRenderbuffers"] = _emscripten_glDeleteRenderbuffers; - _emscripten_glDeleteRenderbuffers.sig = 'vii'; - - function _emscripten_glDeleteShader(id) { + }; + Module['_glDeleteRenderbuffers'] = _glDeleteRenderbuffers; + _glDeleteRenderbuffers.sig = 'vip'; + var _emscripten_glDeleteRenderbuffers = _glDeleteRenderbuffers; + Module['_emscripten_glDeleteRenderbuffers'] = _emscripten_glDeleteRenderbuffers; + _emscripten_glDeleteRenderbuffers.sig = 'vip'; + + /** @suppress {duplicate } */ + var _glDeleteShader = (id) => { if (!id) return; var shader = GL.shaders[id]; - if (!shader) { // glDeleteShader actually signals an error when deleting a nonexisting object, unlike some other GL delete functions. + if (!shader) { + // glDeleteShader actually signals an error when deleting a nonexisting + // object, unlike some other GL delete functions. GL.recordError(0x501 /* GL_INVALID_VALUE */); return; } GLctx.deleteShader(shader); GL.shaders[id] = null; - } - Module["_emscripten_glDeleteShader"] = _emscripten_glDeleteShader; + }; + Module['_glDeleteShader'] = _glDeleteShader; + _glDeleteShader.sig = 'vi'; + var _emscripten_glDeleteShader = _glDeleteShader; + Module['_emscripten_glDeleteShader'] = _emscripten_glDeleteShader; _emscripten_glDeleteShader.sig = 'vi'; - function _emscripten_glDeleteTextures(n, textures) { + /** @suppress {duplicate } */ + var _glDeleteTextures = (n, textures) => { for (var i = 0; i < n; i++) { var id = HEAP32[(((textures)+(i*4))>>2)]; var texture = GL.textures[id]; - if (!texture) continue; // GL spec: "glDeleteTextures silently ignores 0s and names that do not correspond to existing textures". + // GL spec: "glDeleteTextures silently ignores 0s and names that do not + // correspond to existing textures". + if (!texture) continue; GLctx.deleteTexture(texture); texture.name = 0; GL.textures[id] = null; } - } - Module["_emscripten_glDeleteTextures"] = _emscripten_glDeleteTextures; - _emscripten_glDeleteTextures.sig = 'vii'; + }; + Module['_glDeleteTextures'] = _glDeleteTextures; + _glDeleteTextures.sig = 'vip'; + var _emscripten_glDeleteTextures = _glDeleteTextures; + Module['_emscripten_glDeleteTextures'] = _emscripten_glDeleteTextures; + _emscripten_glDeleteTextures.sig = 'vip'; - function _emscripten_glDeleteVertexArraysOES(n, vaos) { + + /** @suppress {duplicate } */ + var _glDeleteVertexArrays = (n, vaos) => { for (var i = 0; i < n; i++) { var id = HEAP32[(((vaos)+(i*4))>>2)]; - GLctx['deleteVertexArray'](GL.vaos[id]); + GLctx.deleteVertexArray(GL.vaos[id]); GL.vaos[id] = null; } - } - Module["_emscripten_glDeleteVertexArraysOES"] = _emscripten_glDeleteVertexArraysOES; - _emscripten_glDeleteVertexArraysOES.sig = 'vii'; - - function _emscripten_glDepthFunc(x0) { GLctx['depthFunc'](x0) } - Module["_emscripten_glDepthFunc"] = _emscripten_glDepthFunc; + }; + Module['_glDeleteVertexArrays'] = _glDeleteVertexArrays; + _glDeleteVertexArrays.sig = 'vip'; + /** @suppress {duplicate } */ + var _glDeleteVertexArraysOES = _glDeleteVertexArrays; + Module['_glDeleteVertexArraysOES'] = _glDeleteVertexArraysOES; + _glDeleteVertexArraysOES.sig = 'vip'; + var _emscripten_glDeleteVertexArraysOES = _glDeleteVertexArraysOES; + Module['_emscripten_glDeleteVertexArraysOES'] = _emscripten_glDeleteVertexArraysOES; + _emscripten_glDeleteVertexArraysOES.sig = 'vip'; + + /** @suppress {duplicate } */ + var _glDepthFunc = (x0) => GLctx.depthFunc(x0); + Module['_glDepthFunc'] = _glDepthFunc; + _glDepthFunc.sig = 'vi'; + var _emscripten_glDepthFunc = _glDepthFunc; + Module['_emscripten_glDepthFunc'] = _emscripten_glDepthFunc; _emscripten_glDepthFunc.sig = 'vi'; - function _emscripten_glDepthMask(flag) { + /** @suppress {duplicate } */ + var _glDepthMask = (flag) => { GLctx.depthMask(!!flag); - } - Module["_emscripten_glDepthMask"] = _emscripten_glDepthMask; + }; + Module['_glDepthMask'] = _glDepthMask; + _glDepthMask.sig = 'vi'; + var _emscripten_glDepthMask = _glDepthMask; + Module['_emscripten_glDepthMask'] = _emscripten_glDepthMask; _emscripten_glDepthMask.sig = 'vi'; - function _emscripten_glDepthRangef(x0, x1) { GLctx['depthRange'](x0, x1) } - Module["_emscripten_glDepthRangef"] = _emscripten_glDepthRangef; - _emscripten_glDepthRangef.sig = 'vii'; + /** @suppress {duplicate } */ + var _glDepthRangef = (x0, x1) => GLctx.depthRange(x0, x1); + Module['_glDepthRangef'] = _glDepthRangef; + _glDepthRangef.sig = 'vff'; + var _emscripten_glDepthRangef = _glDepthRangef; + Module['_emscripten_glDepthRangef'] = _emscripten_glDepthRangef; + _emscripten_glDepthRangef.sig = 'vff'; - function _emscripten_glDetachShader(program, shader) { + /** @suppress {duplicate } */ + var _glDetachShader = (program, shader) => { GLctx.detachShader(GL.programs[program], GL.shaders[shader]); - } - Module["_emscripten_glDetachShader"] = _emscripten_glDetachShader; + }; + Module['_glDetachShader'] = _glDetachShader; + _glDetachShader.sig = 'vii'; + var _emscripten_glDetachShader = _glDetachShader; + Module['_emscripten_glDetachShader'] = _emscripten_glDetachShader; _emscripten_glDetachShader.sig = 'vii'; - function _emscripten_glDisable(x0) { GLctx['disable'](x0) } - Module["_emscripten_glDisable"] = _emscripten_glDisable; + /** @suppress {duplicate } */ + var _glDisable = (x0) => GLctx.disable(x0); + Module['_glDisable'] = _glDisable; + _glDisable.sig = 'vi'; + var _emscripten_glDisable = _glDisable; + Module['_emscripten_glDisable'] = _emscripten_glDisable; _emscripten_glDisable.sig = 'vi'; - function _emscripten_glDisableVertexAttribArray(index) { + /** @suppress {duplicate } */ + var _glDisableVertexAttribArray = (index) => { GLctx.disableVertexAttribArray(index); - } - Module["_emscripten_glDisableVertexAttribArray"] = _emscripten_glDisableVertexAttribArray; + }; + Module['_glDisableVertexAttribArray'] = _glDisableVertexAttribArray; + _glDisableVertexAttribArray.sig = 'vi'; + var _emscripten_glDisableVertexAttribArray = _glDisableVertexAttribArray; + Module['_emscripten_glDisableVertexAttribArray'] = _emscripten_glDisableVertexAttribArray; _emscripten_glDisableVertexAttribArray.sig = 'vi'; - function _emscripten_glDrawArrays(mode, first, count) { + /** @suppress {duplicate } */ + var _glDrawArrays = (mode, first, count) => { GLctx.drawArrays(mode, first, count); - } - Module["_emscripten_glDrawArrays"] = _emscripten_glDrawArrays; + }; + Module['_glDrawArrays'] = _glDrawArrays; + _glDrawArrays.sig = 'viii'; + var _emscripten_glDrawArrays = _glDrawArrays; + Module['_emscripten_glDrawArrays'] = _emscripten_glDrawArrays; _emscripten_glDrawArrays.sig = 'viii'; - function _emscripten_glDrawArraysInstancedANGLE(mode, first, count, primcount) { - GLctx['drawArraysInstanced'](mode, first, count, primcount); - } - Module["_emscripten_glDrawArraysInstancedANGLE"] = _emscripten_glDrawArraysInstancedANGLE; - _emscripten_glDrawArraysInstancedANGLE.sig = 'viiii'; + + /** @suppress {duplicate } */ + var _glDrawArraysInstanced = (mode, first, count, primcount) => { + GLctx.drawArraysInstanced(mode, first, count, primcount); + }; + Module['_glDrawArraysInstanced'] = _glDrawArraysInstanced; + _glDrawArraysInstanced.sig = 'viiii'; + /** @suppress {duplicate } */ + var _glDrawArraysInstancedANGLE = _glDrawArraysInstanced; + Module['_glDrawArraysInstancedANGLE'] = _glDrawArraysInstancedANGLE; + var _emscripten_glDrawArraysInstancedANGLE = _glDrawArraysInstancedANGLE; + Module['_emscripten_glDrawArraysInstancedANGLE'] = _emscripten_glDrawArraysInstancedANGLE; + var tempFixedLengthArray = []; - Module["tempFixedLengthArray"] = tempFixedLengthArray; + Module['tempFixedLengthArray'] = tempFixedLengthArray; - function _emscripten_glDrawBuffersWEBGL(n, bufs) { + /** @suppress {duplicate } */ + var _glDrawBuffers = (n, bufs) => { var bufArray = tempFixedLengthArray[n]; for (var i = 0; i < n; i++) { bufArray[i] = HEAP32[(((bufs)+(i*4))>>2)]; } - GLctx['drawBuffers'](bufArray); - } - Module["_emscripten_glDrawBuffersWEBGL"] = _emscripten_glDrawBuffersWEBGL; - _emscripten_glDrawBuffersWEBGL.sig = 'vii'; + GLctx.drawBuffers(bufArray); + }; + Module['_glDrawBuffers'] = _glDrawBuffers; + _glDrawBuffers.sig = 'vip'; + /** @suppress {duplicate } */ + var _glDrawBuffersWEBGL = _glDrawBuffers; + Module['_glDrawBuffersWEBGL'] = _glDrawBuffersWEBGL; + var _emscripten_glDrawBuffersWEBGL = _glDrawBuffersWEBGL; + Module['_emscripten_glDrawBuffersWEBGL'] = _emscripten_glDrawBuffersWEBGL; - function _emscripten_glDrawElements(mode, count, type, indices) { + /** @suppress {duplicate } */ + var _glDrawElements = (mode, count, type, indices) => { GLctx.drawElements(mode, count, type, indices); - } - Module["_emscripten_glDrawElements"] = _emscripten_glDrawElements; - _emscripten_glDrawElements.sig = 'viiii'; - - function _emscripten_glDrawElementsInstancedANGLE(mode, count, type, indices, primcount) { - GLctx['drawElementsInstanced'](mode, count, type, indices, primcount); - } - Module["_emscripten_glDrawElementsInstancedANGLE"] = _emscripten_glDrawElementsInstancedANGLE; - _emscripten_glDrawElementsInstancedANGLE.sig = 'viiiii'; + }; + Module['_glDrawElements'] = _glDrawElements; + _glDrawElements.sig = 'viiip'; + var _emscripten_glDrawElements = _glDrawElements; + Module['_emscripten_glDrawElements'] = _emscripten_glDrawElements; + _emscripten_glDrawElements.sig = 'viiip'; - function _emscripten_glEnable(x0) { GLctx['enable'](x0) } - Module["_emscripten_glEnable"] = _emscripten_glEnable; + + /** @suppress {duplicate } */ + var _glDrawElementsInstanced = (mode, count, type, indices, primcount) => { + GLctx.drawElementsInstanced(mode, count, type, indices, primcount); + }; + Module['_glDrawElementsInstanced'] = _glDrawElementsInstanced; + _glDrawElementsInstanced.sig = 'viiipi'; + /** @suppress {duplicate } */ + var _glDrawElementsInstancedANGLE = _glDrawElementsInstanced; + Module['_glDrawElementsInstancedANGLE'] = _glDrawElementsInstancedANGLE; + var _emscripten_glDrawElementsInstancedANGLE = _glDrawElementsInstancedANGLE; + Module['_emscripten_glDrawElementsInstancedANGLE'] = _emscripten_glDrawElementsInstancedANGLE; + + /** @suppress {duplicate } */ + var _glEnable = (x0) => GLctx.enable(x0); + Module['_glEnable'] = _glEnable; + _glEnable.sig = 'vi'; + var _emscripten_glEnable = _glEnable; + Module['_emscripten_glEnable'] = _emscripten_glEnable; _emscripten_glEnable.sig = 'vi'; - function _emscripten_glEnableVertexAttribArray(index) { + /** @suppress {duplicate } */ + var _glEnableVertexAttribArray = (index) => { GLctx.enableVertexAttribArray(index); - } - Module["_emscripten_glEnableVertexAttribArray"] = _emscripten_glEnableVertexAttribArray; + }; + Module['_glEnableVertexAttribArray'] = _glEnableVertexAttribArray; + _glEnableVertexAttribArray.sig = 'vi'; + var _emscripten_glEnableVertexAttribArray = _glEnableVertexAttribArray; + Module['_emscripten_glEnableVertexAttribArray'] = _emscripten_glEnableVertexAttribArray; _emscripten_glEnableVertexAttribArray.sig = 'vi'; - function _emscripten_glEndQueryEXT(target) { + /** @suppress {duplicate } */ + var _glEndQueryEXT = (target) => { GLctx.disjointTimerQueryExt['endQueryEXT'](target); - } - Module["_emscripten_glEndQueryEXT"] = _emscripten_glEndQueryEXT; - _emscripten_glEndQueryEXT.sig = 'vi'; + }; + Module['_glEndQueryEXT'] = _glEndQueryEXT; + _glEndQueryEXT.sig = 'vi'; + var _emscripten_glEndQueryEXT = _glEndQueryEXT; + Module['_emscripten_glEndQueryEXT'] = _emscripten_glEndQueryEXT; - function _emscripten_glFinish() { GLctx['finish']() } - Module["_emscripten_glFinish"] = _emscripten_glFinish; + /** @suppress {duplicate } */ + var _glFinish = () => GLctx.finish(); + Module['_glFinish'] = _glFinish; + _glFinish.sig = 'v'; + var _emscripten_glFinish = _glFinish; + Module['_emscripten_glFinish'] = _emscripten_glFinish; _emscripten_glFinish.sig = 'v'; - function _emscripten_glFlush() { GLctx['flush']() } - Module["_emscripten_glFlush"] = _emscripten_glFlush; + /** @suppress {duplicate } */ + var _glFlush = () => GLctx.flush(); + Module['_glFlush'] = _glFlush; + _glFlush.sig = 'v'; + var _emscripten_glFlush = _glFlush; + Module['_emscripten_glFlush'] = _emscripten_glFlush; _emscripten_glFlush.sig = 'v'; - function _emscripten_glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer) { + /** @suppress {duplicate } */ + var _glFramebufferRenderbuffer = (target, attachment, renderbuffertarget, renderbuffer) => { GLctx.framebufferRenderbuffer(target, attachment, renderbuffertarget, GL.renderbuffers[renderbuffer]); - } - Module["_emscripten_glFramebufferRenderbuffer"] = _emscripten_glFramebufferRenderbuffer; + }; + Module['_glFramebufferRenderbuffer'] = _glFramebufferRenderbuffer; + _glFramebufferRenderbuffer.sig = 'viiii'; + var _emscripten_glFramebufferRenderbuffer = _glFramebufferRenderbuffer; + Module['_emscripten_glFramebufferRenderbuffer'] = _emscripten_glFramebufferRenderbuffer; _emscripten_glFramebufferRenderbuffer.sig = 'viiii'; - function _emscripten_glFramebufferTexture2D(target, attachment, textarget, texture, level) { + /** @suppress {duplicate } */ + var _glFramebufferTexture2D = (target, attachment, textarget, texture, level) => { GLctx.framebufferTexture2D(target, attachment, textarget, GL.textures[texture], level); - } - Module["_emscripten_glFramebufferTexture2D"] = _emscripten_glFramebufferTexture2D; + }; + Module['_glFramebufferTexture2D'] = _glFramebufferTexture2D; + _glFramebufferTexture2D.sig = 'viiiii'; + var _emscripten_glFramebufferTexture2D = _glFramebufferTexture2D; + Module['_emscripten_glFramebufferTexture2D'] = _emscripten_glFramebufferTexture2D; _emscripten_glFramebufferTexture2D.sig = 'viiiii'; - function _emscripten_glFrontFace(x0) { GLctx['frontFace'](x0) } - Module["_emscripten_glFrontFace"] = _emscripten_glFrontFace; + /** @suppress {duplicate } */ + var _glFrontFace = (x0) => GLctx.frontFace(x0); + Module['_glFrontFace'] = _glFrontFace; + _glFrontFace.sig = 'vi'; + var _emscripten_glFrontFace = _glFrontFace; + Module['_emscripten_glFrontFace'] = _emscripten_glFrontFace; _emscripten_glFrontFace.sig = 'vi'; - function __glGenObject(n, buffers, createFunction, objectTable - ) { - for (var i = 0; i < n; i++) { - var buffer = GLctx[createFunction](); - var id = buffer && GL.getNewId(objectTable); - if (buffer) { - buffer.name = id; - objectTable[id] = buffer; - } else { - GL.recordError(0x502 /* GL_INVALID_OPERATION */); - } - HEAP32[(((buffers)+(i*4))>>2)] = id; - } - } - Module["__glGenObject"] = __glGenObject; - __glGenObject.sig = 'vii'; - - function _emscripten_glGenBuffers(n, buffers) { - __glGenObject(n, buffers, 'createBuffer', GL.buffers + /** @suppress {duplicate } */ + var _glGenBuffers = (n, buffers) => { + GL.genObject(n, buffers, 'createBuffer', GL.buffers ); - } - Module["_emscripten_glGenBuffers"] = _emscripten_glGenBuffers; - _emscripten_glGenBuffers.sig = 'vii'; - - - function _emscripten_glGenFramebuffers(n, ids) { - __glGenObject(n, ids, 'createFramebuffer', GL.framebuffers + }; + Module['_glGenBuffers'] = _glGenBuffers; + _glGenBuffers.sig = 'vip'; + var _emscripten_glGenBuffers = _glGenBuffers; + Module['_emscripten_glGenBuffers'] = _emscripten_glGenBuffers; + _emscripten_glGenBuffers.sig = 'vip'; + + /** @suppress {duplicate } */ + var _glGenFramebuffers = (n, ids) => { + GL.genObject(n, ids, 'createFramebuffer', GL.framebuffers ); - } - Module["_emscripten_glGenFramebuffers"] = _emscripten_glGenFramebuffers; - _emscripten_glGenFramebuffers.sig = 'vii'; - - function _emscripten_glGenQueriesEXT(n, ids) { + }; + Module['_glGenFramebuffers'] = _glGenFramebuffers; + _glGenFramebuffers.sig = 'vip'; + var _emscripten_glGenFramebuffers = _glGenFramebuffers; + Module['_emscripten_glGenFramebuffers'] = _emscripten_glGenFramebuffers; + _emscripten_glGenFramebuffers.sig = 'vip'; + + /** @suppress {duplicate } */ + var _glGenQueriesEXT = (n, ids) => { for (var i = 0; i < n; i++) { var query = GLctx.disjointTimerQueryExt['createQueryEXT'](); if (!query) { @@ -13035,64 +14091,95 @@ var ASM_CONSTS = { GL.queries[id] = query; HEAP32[(((ids)+(i*4))>>2)] = id; } - } - Module["_emscripten_glGenQueriesEXT"] = _emscripten_glGenQueriesEXT; - _emscripten_glGenQueriesEXT.sig = 'vii'; - - - function _emscripten_glGenRenderbuffers(n, renderbuffers) { - __glGenObject(n, renderbuffers, 'createRenderbuffer', GL.renderbuffers + }; + Module['_glGenQueriesEXT'] = _glGenQueriesEXT; + _glGenQueriesEXT.sig = 'vip'; + var _emscripten_glGenQueriesEXT = _glGenQueriesEXT; + Module['_emscripten_glGenQueriesEXT'] = _emscripten_glGenQueriesEXT; + + /** @suppress {duplicate } */ + var _glGenRenderbuffers = (n, renderbuffers) => { + GL.genObject(n, renderbuffers, 'createRenderbuffer', GL.renderbuffers ); - } - Module["_emscripten_glGenRenderbuffers"] = _emscripten_glGenRenderbuffers; - _emscripten_glGenRenderbuffers.sig = 'vii'; - - - function _emscripten_glGenTextures(n, textures) { - __glGenObject(n, textures, 'createTexture', GL.textures + }; + Module['_glGenRenderbuffers'] = _glGenRenderbuffers; + _glGenRenderbuffers.sig = 'vip'; + var _emscripten_glGenRenderbuffers = _glGenRenderbuffers; + Module['_emscripten_glGenRenderbuffers'] = _emscripten_glGenRenderbuffers; + _emscripten_glGenRenderbuffers.sig = 'vip'; + + /** @suppress {duplicate } */ + var _glGenTextures = (n, textures) => { + GL.genObject(n, textures, 'createTexture', GL.textures ); - } - Module["_emscripten_glGenTextures"] = _emscripten_glGenTextures; - _emscripten_glGenTextures.sig = 'vii'; + }; + Module['_glGenTextures'] = _glGenTextures; + _glGenTextures.sig = 'vip'; + var _emscripten_glGenTextures = _glGenTextures; + Module['_emscripten_glGenTextures'] = _emscripten_glGenTextures; + _emscripten_glGenTextures.sig = 'vip'; - function _emscripten_glGenVertexArraysOES(n, arrays) { - __glGenObject(n, arrays, 'createVertexArray', GL.vaos + /** @suppress {duplicate } */ + var _glGenVertexArrays = (n, arrays) => { + GL.genObject(n, arrays, 'createVertexArray', GL.vaos ); - } - Module["_emscripten_glGenVertexArraysOES"] = _emscripten_glGenVertexArraysOES; - _emscripten_glGenVertexArraysOES.sig = 'vii'; - - function _emscripten_glGenerateMipmap(x0) { GLctx['generateMipmap'](x0) } - Module["_emscripten_glGenerateMipmap"] = _emscripten_glGenerateMipmap; + }; + Module['_glGenVertexArrays'] = _glGenVertexArrays; + _glGenVertexArrays.sig = 'vip'; + /** @suppress {duplicate } */ + var _glGenVertexArraysOES = _glGenVertexArrays; + Module['_glGenVertexArraysOES'] = _glGenVertexArraysOES; + _glGenVertexArraysOES.sig = 'vip'; + var _emscripten_glGenVertexArraysOES = _glGenVertexArraysOES; + Module['_emscripten_glGenVertexArraysOES'] = _emscripten_glGenVertexArraysOES; + _emscripten_glGenVertexArraysOES.sig = 'vip'; + + /** @suppress {duplicate } */ + var _glGenerateMipmap = (x0) => GLctx.generateMipmap(x0); + Module['_glGenerateMipmap'] = _glGenerateMipmap; + _glGenerateMipmap.sig = 'vi'; + var _emscripten_glGenerateMipmap = _glGenerateMipmap; + Module['_emscripten_glGenerateMipmap'] = _emscripten_glGenerateMipmap; _emscripten_glGenerateMipmap.sig = 'vi'; - function __glGetActiveAttribOrUniform(funcName, program, index, bufSize, length, size, type, name) { + + var __glGetActiveAttribOrUniform = (funcName, program, index, bufSize, length, size, type, name) => { program = GL.programs[program]; var info = GLctx[funcName](program, index); - if (info) { // If an error occurs, nothing will be written to length, size and type and name. + if (info) { + // If an error occurs, nothing will be written to length, size and type and name. var numBytesWrittenExclNull = name && stringToUTF8(info.name, name, bufSize); if (length) HEAP32[((length)>>2)] = numBytesWrittenExclNull; if (size) HEAP32[((size)>>2)] = info.size; if (type) HEAP32[((type)>>2)] = info.type; } - } - Module["__glGetActiveAttribOrUniform"] = __glGetActiveAttribOrUniform; + }; + Module['__glGetActiveAttribOrUniform'] = __glGetActiveAttribOrUniform; - function _emscripten_glGetActiveAttrib(program, index, bufSize, length, size, type, name) { + /** @suppress {duplicate } */ + var _glGetActiveAttrib = (program, index, bufSize, length, size, type, name) => { __glGetActiveAttribOrUniform('getActiveAttrib', program, index, bufSize, length, size, type, name); - } - Module["_emscripten_glGetActiveAttrib"] = _emscripten_glGetActiveAttrib; - _emscripten_glGetActiveAttrib.sig = 'viiiiiii'; + }; + Module['_glGetActiveAttrib'] = _glGetActiveAttrib; + _glGetActiveAttrib.sig = 'viiipppp'; + var _emscripten_glGetActiveAttrib = _glGetActiveAttrib; + Module['_emscripten_glGetActiveAttrib'] = _emscripten_glGetActiveAttrib; + _emscripten_glGetActiveAttrib.sig = 'viiipppp'; - function _emscripten_glGetActiveUniform(program, index, bufSize, length, size, type, name) { + /** @suppress {duplicate } */ + var _glGetActiveUniform = (program, index, bufSize, length, size, type, name) => { __glGetActiveAttribOrUniform('getActiveUniform', program, index, bufSize, length, size, type, name); - } - Module["_emscripten_glGetActiveUniform"] = _emscripten_glGetActiveUniform; - _emscripten_glGetActiveUniform.sig = 'viiiiiii'; - - function _emscripten_glGetAttachedShaders(program, maxCount, count, shaders) { + }; + Module['_glGetActiveUniform'] = _glGetActiveUniform; + _glGetActiveUniform.sig = 'viiipppp'; + var _emscripten_glGetActiveUniform = _glGetActiveUniform; + Module['_emscripten_glGetActiveUniform'] = _emscripten_glGetActiveUniform; + _emscripten_glGetActiveUniform.sig = 'viiipppp'; + + /** @suppress {duplicate } */ + var _glGetAttachedShaders = (program, maxCount, count, shaders) => { var result = GLctx.getAttachedShaders(GL.programs[program]); var len = result.length; if (len > maxCount) { @@ -13103,34 +14190,45 @@ var ASM_CONSTS = { var id = GL.shaders.indexOf(result[i]); HEAP32[(((shaders)+(i*4))>>2)] = id; } - } - Module["_emscripten_glGetAttachedShaders"] = _emscripten_glGetAttachedShaders; - _emscripten_glGetAttachedShaders.sig = 'viiii'; + }; + Module['_glGetAttachedShaders'] = _glGetAttachedShaders; + _glGetAttachedShaders.sig = 'viipp'; + var _emscripten_glGetAttachedShaders = _glGetAttachedShaders; + Module['_emscripten_glGetAttachedShaders'] = _emscripten_glGetAttachedShaders; + _emscripten_glGetAttachedShaders.sig = 'viipp'; - function _emscripten_glGetAttribLocation(program, name) { + + /** @suppress {duplicate } */ + var _glGetAttribLocation = (program, name) => { return GLctx.getAttribLocation(GL.programs[program], UTF8ToString(name)); - } - Module["_emscripten_glGetAttribLocation"] = _emscripten_glGetAttribLocation; - _emscripten_glGetAttribLocation.sig = 'iii'; + }; + Module['_glGetAttribLocation'] = _glGetAttribLocation; + _glGetAttribLocation.sig = 'iip'; + var _emscripten_glGetAttribLocation = _glGetAttribLocation; + Module['_emscripten_glGetAttribLocation'] = _emscripten_glGetAttribLocation; + _emscripten_glGetAttribLocation.sig = 'iip'; - function readI53FromU64(ptr) { - return HEAPU32[ptr>>2] + HEAPU32[ptr+4>>2] * 4294967296; - } - Module["readI53FromU64"] = readI53FromU64; - function writeI53ToI64(ptr, num) { - HEAPU32[ptr>>2] = num; - HEAPU32[ptr+4>>2] = (num - HEAPU32[ptr>>2])/4294967296; + var readI53FromU64 = (ptr) => { + return HEAPU32[((ptr)>>2)] + HEAPU32[(((ptr)+(4))>>2)] * 4294967296; + }; + Module['readI53FromU64'] = readI53FromU64; + var writeI53ToI64 = (ptr, num) => { + HEAPU32[((ptr)>>2)] = num; + var lower = HEAPU32[((ptr)>>2)]; + HEAPU32[(((ptr)+(4))>>2)] = (num - lower)/4294967296; var deserialized = (num >= 0) ? readI53FromU64(ptr) : readI53FromI64(ptr); - if (deserialized != num) warnOnce('writeI53ToI64() out of range: serialized JS Number ' + num + ' to Wasm heap as bytes lo=' + ptrToString(HEAPU32[ptr>>2]) + ', hi=' + ptrToString(HEAPU32[ptr+4>>2]) + ', which deserializes back to ' + deserialized + ' instead!'); - } - Module["writeI53ToI64"] = writeI53ToI64; + var offset = ((ptr)>>2); + if (deserialized != num) warnOnce(`writeI53ToI64() out of range: serialized JS Number ${num} to Wasm heap as bytes lo=${ptrToString(HEAPU32[offset])}, hi=${ptrToString(HEAPU32[offset+1])}, which deserializes back to ${deserialized} instead!`); + }; + Module['writeI53ToI64'] = writeI53ToI64; - function emscriptenWebGLGet(name_, p, type) { + var emscriptenWebGLGet = (name_, p, type) => { // Guard against user passing a null pointer. - // Note that GLES2 spec does not say anything about how passing a null pointer should be treated. - // Testing on desktop core GL 3, the application crashes on glGetIntegerv to a null pointer, but - // better to report an error instead of doing anything random. + // Note that GLES2 spec does not say anything about how passing a null + // pointer should be treated. Testing on desktop core GL 3, the application + // crashes on glGetIntegerv to a null pointer, but better to report an error + // instead of doing anything random. if (!p) { GL.recordError(0x501 /* GL_INVALID_VALUE */); return; @@ -13144,13 +14242,17 @@ var ASM_CONSTS = { if (type != 0 && type != 1) { GL.recordError(0x500); // GL_INVALID_ENUM } - return; // Do not write anything to the out pointer, since no binary formats are supported. + // Do not write anything to the out pointer, since no binary formats are + // supported. + return; case 0x8DF9: // GL_NUM_SHADER_BINARY_FORMATS ret = 0; break; case 0x86A2: // GL_NUM_COMPRESSED_TEXTURE_FORMATS - // WebGL doesn't have GL_NUM_COMPRESSED_TEXTURE_FORMATS (it's obsolete since GL_COMPRESSED_TEXTURE_FORMATS returns a JS array that can be queried for length), - // so implement it ourselves to allow C++ GLES2 code get the length. + // WebGL doesn't have GL_NUM_COMPRESSED_TEXTURE_FORMATS (it's obsolete + // since GL_COMPRESSED_TEXTURE_FORMATS returns a JS array that can be + // queried for length), so implement it ourselves to allow C++ GLES2 + // code get the length. var formats = GLctx.getParameter(0x86A3 /*GL_COMPRESSED_TEXTURE_FORMATS*/); ret = formats ? formats.length : 0; break; @@ -13171,8 +14273,9 @@ var ASM_CONSTS = { return; case "object": if (result === null) { - // null is a valid result for some (e.g., which buffer is bound - perhaps nothing is bound), but otherwise - // can mean an invalid name_, which we need to report as an error + // null is a valid result for some (e.g., which buffer is bound - + // perhaps nothing is bound), but otherwise can mean an invalid + // name_, which we need to report as an error switch (name_) { case 0x8894: // ARRAY_BUFFER_BINDING case 0x8B8D: // CURRENT_PROGRAM @@ -13198,7 +14301,7 @@ var ASM_CONSTS = { switch (type) { case 0: HEAP32[(((p)+(i*4))>>2)] = result[i]; break; case 2: HEAPF32[(((p)+(i*4))>>2)] = result[i]; break; - case 4: HEAP8[(((p)+(i))>>0)] = result[i] ? 1 : 0; break; + case 4: HEAP8[(p)+(i)] = result[i] ? 1 : 0; break; } } return; @@ -13207,14 +14310,14 @@ var ASM_CONSTS = { ret = result.name | 0; } catch(e) { GL.recordError(0x500); // GL_INVALID_ENUM - err('GL_INVALID_ENUM in glGet' + type + 'v: Unknown object returned from WebGL getParameter(' + name_ + ')! (error: ' + e + ')'); + err(`GL_INVALID_ENUM in glGet${type}v: Unknown object returned from WebGL getParameter(${name_})! (error: ${e})`); return; } } break; default: GL.recordError(0x500); // GL_INVALID_ENUM - err('GL_INVALID_ENUM in glGet' + type + 'v: Native code calling glGet' + type + 'v(' + name_ + ') and it returns ' + result + ' of type ' + typeof(result) + '!'); + err(`GL_INVALID_ENUM in glGet${type}v: Native code calling glGet${type}v(${name_}) and it returns ${result} of type ${typeof(result)}!`); return; } } @@ -13223,75 +14326,100 @@ var ASM_CONSTS = { case 1: writeI53ToI64(p, ret); break; case 0: HEAP32[((p)>>2)] = ret; break; case 2: HEAPF32[((p)>>2)] = ret; break; - case 4: HEAP8[((p)>>0)] = ret ? 1 : 0; break; + case 4: HEAP8[p] = ret ? 1 : 0; break; } - } - Module["emscriptenWebGLGet"] = emscriptenWebGLGet; - - function _emscripten_glGetBooleanv(name_, p) { - emscriptenWebGLGet(name_, p, 4); - } - Module["_emscripten_glGetBooleanv"] = _emscripten_glGetBooleanv; - _emscripten_glGetBooleanv.sig = 'vii'; - - function _emscripten_glGetBufferParameteriv(target, value, data) { + }; + Module['emscriptenWebGLGet'] = emscriptenWebGLGet; + + /** @suppress {duplicate } */ + var _glGetBooleanv = (name_, p) => emscriptenWebGLGet(name_, p, 4); + Module['_glGetBooleanv'] = _glGetBooleanv; + _glGetBooleanv.sig = 'vip'; + var _emscripten_glGetBooleanv = _glGetBooleanv; + Module['_emscripten_glGetBooleanv'] = _emscripten_glGetBooleanv; + _emscripten_glGetBooleanv.sig = 'vip'; + + /** @suppress {duplicate } */ + var _glGetBufferParameteriv = (target, value, data) => { if (!data) { - // GLES2 specification does not specify how to behave if data is a null pointer. Since calling this function does not make sense - // if data == null, issue a GL error to notify user about it. + // GLES2 specification does not specify how to behave if data is a null + // pointer. Since calling this function does not make sense if data == + // null, issue a GL error to notify user about it. GL.recordError(0x501 /* GL_INVALID_VALUE */); return; } HEAP32[((data)>>2)] = GLctx.getBufferParameter(target, value); - } - Module["_emscripten_glGetBufferParameteriv"] = _emscripten_glGetBufferParameteriv; - _emscripten_glGetBufferParameteriv.sig = 'viii'; - - function _emscripten_glGetError() { + }; + Module['_glGetBufferParameteriv'] = _glGetBufferParameteriv; + _glGetBufferParameteriv.sig = 'viip'; + var _emscripten_glGetBufferParameteriv = _glGetBufferParameteriv; + Module['_emscripten_glGetBufferParameteriv'] = _emscripten_glGetBufferParameteriv; + _emscripten_glGetBufferParameteriv.sig = 'viip'; + + /** @suppress {duplicate } */ + var _glGetError = () => { var error = GLctx.getError() || GL.lastError; GL.lastError = 0/*GL_NO_ERROR*/; return error; - } - Module["_emscripten_glGetError"] = _emscripten_glGetError; + }; + Module['_glGetError'] = _glGetError; + _glGetError.sig = 'i'; + var _emscripten_glGetError = _glGetError; + Module['_emscripten_glGetError'] = _emscripten_glGetError; _emscripten_glGetError.sig = 'i'; - function _emscripten_glGetFloatv(name_, p) { - emscriptenWebGLGet(name_, p, 2); - } - Module["_emscripten_glGetFloatv"] = _emscripten_glGetFloatv; - _emscripten_glGetFloatv.sig = 'vii'; + /** @suppress {duplicate } */ + var _glGetFloatv = (name_, p) => emscriptenWebGLGet(name_, p, 2); + Module['_glGetFloatv'] = _glGetFloatv; + _glGetFloatv.sig = 'vip'; + var _emscripten_glGetFloatv = _glGetFloatv; + Module['_emscripten_glGetFloatv'] = _emscripten_glGetFloatv; + _emscripten_glGetFloatv.sig = 'vip'; - function _emscripten_glGetFramebufferAttachmentParameteriv(target, attachment, pname, params) { + /** @suppress {duplicate } */ + var _glGetFramebufferAttachmentParameteriv = (target, attachment, pname, params) => { var result = GLctx.getFramebufferAttachmentParameter(target, attachment, pname); if (result instanceof WebGLRenderbuffer || result instanceof WebGLTexture) { result = result.name | 0; } HEAP32[((params)>>2)] = result; - } - Module["_emscripten_glGetFramebufferAttachmentParameteriv"] = _emscripten_glGetFramebufferAttachmentParameteriv; - _emscripten_glGetFramebufferAttachmentParameteriv.sig = 'viiii'; - - - function _emscripten_glGetIntegerv(name_, p) { - emscriptenWebGLGet(name_, p, 0); - } - Module["_emscripten_glGetIntegerv"] = _emscripten_glGetIntegerv; - _emscripten_glGetIntegerv.sig = 'vii'; - - function _emscripten_glGetProgramInfoLog(program, maxLength, length, infoLog) { + }; + Module['_glGetFramebufferAttachmentParameteriv'] = _glGetFramebufferAttachmentParameteriv; + _glGetFramebufferAttachmentParameteriv.sig = 'viiip'; + var _emscripten_glGetFramebufferAttachmentParameteriv = _glGetFramebufferAttachmentParameteriv; + Module['_emscripten_glGetFramebufferAttachmentParameteriv'] = _emscripten_glGetFramebufferAttachmentParameteriv; + _emscripten_glGetFramebufferAttachmentParameteriv.sig = 'viiip'; + + + /** @suppress {duplicate } */ + var _glGetIntegerv = (name_, p) => emscriptenWebGLGet(name_, p, 0); + Module['_glGetIntegerv'] = _glGetIntegerv; + _glGetIntegerv.sig = 'vip'; + var _emscripten_glGetIntegerv = _glGetIntegerv; + Module['_emscripten_glGetIntegerv'] = _emscripten_glGetIntegerv; + _emscripten_glGetIntegerv.sig = 'vip'; + + /** @suppress {duplicate } */ + var _glGetProgramInfoLog = (program, maxLength, length, infoLog) => { var log = GLctx.getProgramInfoLog(GL.programs[program]); if (log === null) log = '(unknown error)'; var numBytesWrittenExclNull = (maxLength > 0 && infoLog) ? stringToUTF8(log, infoLog, maxLength) : 0; if (length) HEAP32[((length)>>2)] = numBytesWrittenExclNull; - } - Module["_emscripten_glGetProgramInfoLog"] = _emscripten_glGetProgramInfoLog; - _emscripten_glGetProgramInfoLog.sig = 'viiii'; - - function _emscripten_glGetProgramiv(program, pname, p) { + }; + Module['_glGetProgramInfoLog'] = _glGetProgramInfoLog; + _glGetProgramInfoLog.sig = 'viipp'; + var _emscripten_glGetProgramInfoLog = _glGetProgramInfoLog; + Module['_emscripten_glGetProgramInfoLog'] = _emscripten_glGetProgramInfoLog; + _emscripten_glGetProgramInfoLog.sig = 'viipp'; + + /** @suppress {duplicate } */ + var _glGetProgramiv = (program, pname, p) => { if (!p) { - // GLES2 specification does not specify how to behave if p is a null pointer. Since calling this function does not make sense - // if p == null, issue a GL error to notify user about it. + // GLES2 specification does not specify how to behave if p is a null + // pointer. Since calling this function does not make sense if p == null, + // issue a GL error to notify user about it. GL.recordError(0x501 /* GL_INVALID_VALUE */); return; } @@ -13331,12 +14459,16 @@ var ASM_CONSTS = { } else { HEAP32[((p)>>2)] = GLctx.getProgramParameter(program, pname); } - } - Module["_emscripten_glGetProgramiv"] = _emscripten_glGetProgramiv; - _emscripten_glGetProgramiv.sig = 'viii'; + }; + Module['_glGetProgramiv'] = _glGetProgramiv; + _glGetProgramiv.sig = 'viip'; + var _emscripten_glGetProgramiv = _glGetProgramiv; + Module['_emscripten_glGetProgramiv'] = _emscripten_glGetProgramiv; + _emscripten_glGetProgramiv.sig = 'viip'; - function _emscripten_glGetQueryObjecti64vEXT(id, pname, params) { + /** @suppress {duplicate } */ + var _glGetQueryObjecti64vEXT = (id, pname, params) => { if (!params) { // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense // if p == null, issue a GL error to notify user about it. @@ -13355,11 +14487,14 @@ var ASM_CONSTS = { ret = param; } writeI53ToI64(params, ret); - } - Module["_emscripten_glGetQueryObjecti64vEXT"] = _emscripten_glGetQueryObjecti64vEXT; - _emscripten_glGetQueryObjecti64vEXT.sig = 'viii'; + }; + Module['_glGetQueryObjecti64vEXT'] = _glGetQueryObjecti64vEXT; + _glGetQueryObjecti64vEXT.sig = 'viip'; + var _emscripten_glGetQueryObjecti64vEXT = _glGetQueryObjecti64vEXT; + Module['_emscripten_glGetQueryObjecti64vEXT'] = _emscripten_glGetQueryObjecti64vEXT; - function _emscripten_glGetQueryObjectivEXT(id, pname, params) { + /** @suppress {duplicate } */ + var _glGetQueryObjectivEXT = (id, pname, params) => { if (!params) { // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense // if p == null, issue a GL error to notify user about it. @@ -13375,55 +14510,28 @@ var ASM_CONSTS = { ret = param; } HEAP32[((params)>>2)] = ret; - } - Module["_emscripten_glGetQueryObjectivEXT"] = _emscripten_glGetQueryObjectivEXT; - _emscripten_glGetQueryObjectivEXT.sig = 'viii'; + }; + Module['_glGetQueryObjectivEXT'] = _glGetQueryObjectivEXT; + _glGetQueryObjectivEXT.sig = 'viip'; + var _emscripten_glGetQueryObjectivEXT = _glGetQueryObjectivEXT; + Module['_emscripten_glGetQueryObjectivEXT'] = _emscripten_glGetQueryObjectivEXT; - function _emscripten_glGetQueryObjectui64vEXT(id, pname, params) { - if (!params) { - // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense - // if p == null, issue a GL error to notify user about it. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - var query = GL.queries[id]; - var param; - { - param = GLctx.disjointTimerQueryExt['getQueryObjectEXT'](query, pname); - } - var ret; - if (typeof param == 'boolean') { - ret = param ? 1 : 0; - } else { - ret = param; - } - writeI53ToI64(params, ret); - } - Module["_emscripten_glGetQueryObjectui64vEXT"] = _emscripten_glGetQueryObjectui64vEXT; - _emscripten_glGetQueryObjectui64vEXT.sig = 'viii'; + /** @suppress {duplicate } */ + var _glGetQueryObjectui64vEXT = _glGetQueryObjecti64vEXT; + Module['_glGetQueryObjectui64vEXT'] = _glGetQueryObjectui64vEXT; + var _emscripten_glGetQueryObjectui64vEXT = _glGetQueryObjectui64vEXT; + Module['_emscripten_glGetQueryObjectui64vEXT'] = _emscripten_glGetQueryObjectui64vEXT; - function _emscripten_glGetQueryObjectuivEXT(id, pname, params) { - if (!params) { - // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense - // if p == null, issue a GL error to notify user about it. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - var query = GL.queries[id]; - var param = GLctx.disjointTimerQueryExt['getQueryObjectEXT'](query, pname); - var ret; - if (typeof param == 'boolean') { - ret = param ? 1 : 0; - } else { - ret = param; - } - HEAP32[((params)>>2)] = ret; - } - Module["_emscripten_glGetQueryObjectuivEXT"] = _emscripten_glGetQueryObjectuivEXT; - _emscripten_glGetQueryObjectuivEXT.sig = 'viii'; + + /** @suppress {duplicate } */ + var _glGetQueryObjectuivEXT = _glGetQueryObjectivEXT; + Module['_glGetQueryObjectuivEXT'] = _glGetQueryObjectuivEXT; + var _emscripten_glGetQueryObjectuivEXT = _glGetQueryObjectuivEXT; + Module['_emscripten_glGetQueryObjectuivEXT'] = _emscripten_glGetQueryObjectuivEXT; - function _emscripten_glGetQueryivEXT(target, pname, params) { + /** @suppress {duplicate } */ + var _glGetQueryivEXT = (target, pname, params) => { if (!params) { // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense // if p == null, issue a GL error to notify user about it. @@ -13431,11 +14539,14 @@ var ASM_CONSTS = { return; } HEAP32[((params)>>2)] = GLctx.disjointTimerQueryExt['getQueryEXT'](target, pname); - } - Module["_emscripten_glGetQueryivEXT"] = _emscripten_glGetQueryivEXT; - _emscripten_glGetQueryivEXT.sig = 'viii'; + }; + Module['_glGetQueryivEXT'] = _glGetQueryivEXT; + _glGetQueryivEXT.sig = 'viip'; + var _emscripten_glGetQueryivEXT = _glGetQueryivEXT; + Module['_emscripten_glGetQueryivEXT'] = _emscripten_glGetQueryivEXT; - function _emscripten_glGetRenderbufferParameteriv(target, pname, params) { + /** @suppress {duplicate } */ + var _glGetRenderbufferParameteriv = (target, pname, params) => { if (!params) { // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense // if params == null, issue a GL error to notify user about it. @@ -13443,41 +14554,59 @@ var ASM_CONSTS = { return; } HEAP32[((params)>>2)] = GLctx.getRenderbufferParameter(target, pname); - } - Module["_emscripten_glGetRenderbufferParameteriv"] = _emscripten_glGetRenderbufferParameteriv; - _emscripten_glGetRenderbufferParameteriv.sig = 'viii'; + }; + Module['_glGetRenderbufferParameteriv'] = _glGetRenderbufferParameteriv; + _glGetRenderbufferParameteriv.sig = 'viip'; + var _emscripten_glGetRenderbufferParameteriv = _glGetRenderbufferParameteriv; + Module['_emscripten_glGetRenderbufferParameteriv'] = _emscripten_glGetRenderbufferParameteriv; + _emscripten_glGetRenderbufferParameteriv.sig = 'viip'; - function _emscripten_glGetShaderInfoLog(shader, maxLength, length, infoLog) { + + /** @suppress {duplicate } */ + var _glGetShaderInfoLog = (shader, maxLength, length, infoLog) => { var log = GLctx.getShaderInfoLog(GL.shaders[shader]); if (log === null) log = '(unknown error)'; var numBytesWrittenExclNull = (maxLength > 0 && infoLog) ? stringToUTF8(log, infoLog, maxLength) : 0; if (length) HEAP32[((length)>>2)] = numBytesWrittenExclNull; - } - Module["_emscripten_glGetShaderInfoLog"] = _emscripten_glGetShaderInfoLog; - _emscripten_glGetShaderInfoLog.sig = 'viiii'; - - function _emscripten_glGetShaderPrecisionFormat(shaderType, precisionType, range, precision) { + }; + Module['_glGetShaderInfoLog'] = _glGetShaderInfoLog; + _glGetShaderInfoLog.sig = 'viipp'; + var _emscripten_glGetShaderInfoLog = _glGetShaderInfoLog; + Module['_emscripten_glGetShaderInfoLog'] = _emscripten_glGetShaderInfoLog; + _emscripten_glGetShaderInfoLog.sig = 'viipp'; + + /** @suppress {duplicate } */ + var _glGetShaderPrecisionFormat = (shaderType, precisionType, range, precision) => { var result = GLctx.getShaderPrecisionFormat(shaderType, precisionType); HEAP32[((range)>>2)] = result.rangeMin; HEAP32[(((range)+(4))>>2)] = result.rangeMax; HEAP32[((precision)>>2)] = result.precision; - } - Module["_emscripten_glGetShaderPrecisionFormat"] = _emscripten_glGetShaderPrecisionFormat; - _emscripten_glGetShaderPrecisionFormat.sig = 'viiii'; - - function _emscripten_glGetShaderSource(shader, bufSize, length, source) { + }; + Module['_glGetShaderPrecisionFormat'] = _glGetShaderPrecisionFormat; + _glGetShaderPrecisionFormat.sig = 'viipp'; + var _emscripten_glGetShaderPrecisionFormat = _glGetShaderPrecisionFormat; + Module['_emscripten_glGetShaderPrecisionFormat'] = _emscripten_glGetShaderPrecisionFormat; + _emscripten_glGetShaderPrecisionFormat.sig = 'viipp'; + + /** @suppress {duplicate } */ + var _glGetShaderSource = (shader, bufSize, length, source) => { var result = GLctx.getShaderSource(GL.shaders[shader]); if (!result) return; // If an error occurs, nothing will be written to length or source. var numBytesWrittenExclNull = (bufSize > 0 && source) ? stringToUTF8(result, source, bufSize) : 0; if (length) HEAP32[((length)>>2)] = numBytesWrittenExclNull; - } - Module["_emscripten_glGetShaderSource"] = _emscripten_glGetShaderSource; - _emscripten_glGetShaderSource.sig = 'viiii'; - - function _emscripten_glGetShaderiv(shader, pname, p) { + }; + Module['_glGetShaderSource'] = _glGetShaderSource; + _glGetShaderSource.sig = 'viipp'; + var _emscripten_glGetShaderSource = _glGetShaderSource; + Module['_emscripten_glGetShaderSource'] = _emscripten_glGetShaderSource; + _emscripten_glGetShaderSource.sig = 'viipp'; + + /** @suppress {duplicate } */ + var _glGetShaderiv = (shader, pname, p) => { if (!p) { - // GLES2 specification does not specify how to behave if p is a null pointer. Since calling this function does not make sense - // if p == null, issue a GL error to notify user about it. + // GLES2 specification does not specify how to behave if p is a null + // pointer. Since calling this function does not make sense if p == null, + // issue a GL error to notify user about it. GL.recordError(0x501 /* GL_INVALID_VALUE */); return; } @@ -13499,26 +14628,29 @@ var ASM_CONSTS = { } else { HEAP32[((p)>>2)] = GLctx.getShaderParameter(GL.shaders[shader], pname); } - } - Module["_emscripten_glGetShaderiv"] = _emscripten_glGetShaderiv; - _emscripten_glGetShaderiv.sig = 'viii'; - - function stringToNewUTF8(jsString) { - var length = lengthBytesUTF8(jsString)+1; - var cString = _malloc(length); - stringToUTF8(jsString, cString, length); - return cString; - } - Module["stringToNewUTF8"] = stringToNewUTF8; + }; + Module['_glGetShaderiv'] = _glGetShaderiv; + _glGetShaderiv.sig = 'viip'; + var _emscripten_glGetShaderiv = _glGetShaderiv; + Module['_emscripten_glGetShaderiv'] = _emscripten_glGetShaderiv; + _emscripten_glGetShaderiv.sig = 'viip'; + - function _emscripten_glGetString(name_) { + + var webglGetExtensions = function $webglGetExtensions() { + var exts = getEmscriptenSupportedExtensions(GLctx); + exts = exts.concat(exts.map((e) => "GL_" + e)); + return exts; + }; + Module['webglGetExtensions'] = webglGetExtensions; + + /** @suppress {duplicate } */ + var _glGetString = (name_) => { var ret = GL.stringCache[name_]; if (!ret) { switch (name_) { case 0x1F03 /* GL_EXTENSIONS */: - var exts = GLctx.getSupportedExtensions() || []; // .getSupportedExtensions() can return null if context is lost, so coerce to empty array. - exts = exts.concat(exts.map(function(e) { return "GL_" + e; })); - ret = stringToNewUTF8(exts.join(' ')); + ret = stringToNewUTF8(webglGetExtensions().join(' ')); break; case 0x1F00 /* GL_VENDOR */: case 0x1F01 /* GL_RENDERER */: @@ -13528,14 +14660,14 @@ var ASM_CONSTS = { if (!s) { GL.recordError(0x500/*GL_INVALID_ENUM*/); } - ret = s && stringToNewUTF8(s); + ret = s ? stringToNewUTF8(s) : 0; break; case 0x1F02 /* GL_VERSION */: var glVersion = GLctx.getParameter(0x1F02 /*GL_VERSION*/); // return GLES version string corresponding to the version of the WebGL context { - glVersion = 'OpenGL ES 2.0 (' + glVersion + ')'; + glVersion = `OpenGL ES 2.0 (${glVersion})`; } ret = stringToNewUTF8(glVersion); break; @@ -13546,7 +14678,7 @@ var ASM_CONSTS = { var ver_num = glslVersion.match(ver_re); if (ver_num !== null) { if (ver_num[1].length == 3) ver_num[1] = ver_num[1] + '0'; // ensure minor version has 2 digits - glslVersion = 'OpenGL ES GLSL ES ' + ver_num[1] + ' (' + glslVersion + ')'; + glslVersion = `OpenGL ES GLSL ES ${ver_num[1]} (${glslVersion})`; } ret = stringToNewUTF8(glslVersion); break; @@ -13557,42 +14689,53 @@ var ASM_CONSTS = { GL.stringCache[name_] = ret; } return ret; - } - Module["_emscripten_glGetString"] = _emscripten_glGetString; - _emscripten_glGetString.sig = 'ii'; - - function _emscripten_glGetTexParameterfv(target, pname, params) { + }; + Module['_glGetString'] = _glGetString; + _glGetString.sig = 'pi'; + var _emscripten_glGetString = _glGetString; + Module['_emscripten_glGetString'] = _emscripten_glGetString; + _emscripten_glGetString.sig = 'pi'; + + /** @suppress {duplicate } */ + var _glGetTexParameterfv = (target, pname, params) => { if (!params) { - // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense - // if p == null, issue a GL error to notify user about it. + // GLES2 specification does not specify how to behave if params is a null + // pointer. Since calling this function does not make sense if p == null, + // issue a GL error to notify user about it. GL.recordError(0x501 /* GL_INVALID_VALUE */); return; } HEAPF32[((params)>>2)] = GLctx.getTexParameter(target, pname); - } - Module["_emscripten_glGetTexParameterfv"] = _emscripten_glGetTexParameterfv; - _emscripten_glGetTexParameterfv.sig = 'viii'; - - function _emscripten_glGetTexParameteriv(target, pname, params) { + }; + Module['_glGetTexParameterfv'] = _glGetTexParameterfv; + _glGetTexParameterfv.sig = 'viip'; + var _emscripten_glGetTexParameterfv = _glGetTexParameterfv; + Module['_emscripten_glGetTexParameterfv'] = _emscripten_glGetTexParameterfv; + _emscripten_glGetTexParameterfv.sig = 'viip'; + + /** @suppress {duplicate } */ + var _glGetTexParameteriv = (target, pname, params) => { if (!params) { - // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense - // if p == null, issue a GL error to notify user about it. + // GLES2 specification does not specify how to behave if params is a null + // pointer. Since calling this function does not make sense if p == null, + // issue a GL error to notify user about it. GL.recordError(0x501 /* GL_INVALID_VALUE */); return; } HEAP32[((params)>>2)] = GLctx.getTexParameter(target, pname); - } - Module["_emscripten_glGetTexParameteriv"] = _emscripten_glGetTexParameteriv; - _emscripten_glGetTexParameteriv.sig = 'viii'; + }; + Module['_glGetTexParameteriv'] = _glGetTexParameteriv; + _glGetTexParameteriv.sig = 'viip'; + var _emscripten_glGetTexParameteriv = _glGetTexParameteriv; + Module['_emscripten_glGetTexParameteriv'] = _emscripten_glGetTexParameteriv; + _emscripten_glGetTexParameteriv.sig = 'viip'; /** @noinline */ - function webglGetLeftBracePos(name) { - return name.slice(-1) == ']' && name.lastIndexOf('['); - } - Module["webglGetLeftBracePos"] = webglGetLeftBracePos; + var webglGetLeftBracePos = (name) => name.slice(-1) == ']' && name.lastIndexOf('['); + Module['webglGetLeftBracePos'] = webglGetLeftBracePos; - function webglPrepareUniformLocationsBeforeFirstUse(program) { + var webglPrepareUniformLocationsBeforeFirstUse = (program) => { var uniformLocsById = program.uniformLocsById, // Maps GLuint -> WebGLUniformLocation uniformSizeAndIdsByName = program.uniformSizeAndIdsByName, // Maps name -> [uniform array length, GLuint] i, j; @@ -13624,17 +14767,19 @@ var ASM_CONSTS = { // Store placeholder integers in place that highlight that these // >0 index locations are array indices pending population. - for(j = 0; j < sz; ++j) { + for (j = 0; j < sz; ++j) { uniformLocsById[id] = j; program.uniformArrayNamesById[id++] = arrayName; } } } - } - Module["webglPrepareUniformLocationsBeforeFirstUse"] = webglPrepareUniformLocationsBeforeFirstUse; + }; + Module['webglPrepareUniformLocationsBeforeFirstUse'] = webglPrepareUniformLocationsBeforeFirstUse; - function _emscripten_glGetUniformLocation(program, name) { + + /** @suppress {duplicate } */ + var _glGetUniformLocation = (program, name) => { name = UTF8ToString(name); @@ -13644,11 +14789,14 @@ var ASM_CONSTS = { var arrayIndex = 0; var uniformBaseName = name; - // Invariant: when populating integer IDs for uniform locations, we must maintain the precondition that - // arrays reside in contiguous addresses, i.e. for a 'vec4 colors[10];', colors[4] must be at location colors[0]+4. - // However, user might call glGetUniformLocation(program, "colors") for an array, so we cannot discover based on the user - // input arguments whether the uniform we are dealing with is an array. The only way to discover which uniforms are arrays - // is to enumerate over all the active uniforms in the program. + // Invariant: when populating integer IDs for uniform locations, we must + // maintain the precondition that arrays reside in contiguous addresses, + // i.e. for a 'vec4 colors[10];', colors[4] must be at location + // colors[0]+4. However, user might call glGetUniformLocation(program, + // "colors") for an array, so we cannot discover based on the user input + // arguments whether the uniform we are dealing with is an array. The only + // way to discover which uniforms are arrays is to enumerate over all the + // active uniforms in the program. var leftBrace = webglGetLeftBracePos(name); // If user passed an array accessor "[index]", parse the array index off the accessor. @@ -13658,10 +14806,12 @@ var ASM_CONSTS = { } // Have we cached the location of this uniform before? - var sizeAndId = program.uniformSizeAndIdsByName[uniformBaseName]; // A pair [array length, GLint of the uniform location] + // A pair [array length, GLint of the uniform location] + var sizeAndId = program.uniformSizeAndIdsByName[uniformBaseName]; - // If an uniform with this name exists, and if its index is within the array limits (if it's even an array), - // query the WebGLlocation, or return an existing cached location. + // If an uniform with this name exists, and if its index is within the + // array limits (if it's even an array), query the WebGLlocation, or + // return an existing cached location. if (sizeAndId && arrayIndex < sizeAndId[0]) { arrayIndex += sizeAndId[1]; // Add the base location of the uniform to the array index offset. if ((uniformLocsById[arrayIndex] = uniformLocsById[arrayIndex] || GLctx.getUniformLocation(program, name))) { @@ -13670,41 +14820,46 @@ var ASM_CONSTS = { } } else { - // N.b. we are currently unable to distinguish between GL program IDs that never existed vs GL program IDs that have been deleted, - // so report GL_INVALID_VALUE in both cases. + // N.b. we are currently unable to distinguish between GL program IDs that + // never existed vs GL program IDs that have been deleted, so report + // GL_INVALID_VALUE in both cases. GL.recordError(0x501 /* GL_INVALID_VALUE */); } return -1; - } - Module["_emscripten_glGetUniformLocation"] = _emscripten_glGetUniformLocation; - _emscripten_glGetUniformLocation.sig = 'iii'; + }; + Module['_glGetUniformLocation'] = _glGetUniformLocation; + _glGetUniformLocation.sig = 'iip'; + var _emscripten_glGetUniformLocation = _glGetUniformLocation; + Module['_emscripten_glGetUniformLocation'] = _emscripten_glGetUniformLocation; + _emscripten_glGetUniformLocation.sig = 'iip'; - function webglGetUniformLocation(location) { + var webglGetUniformLocation = (location) => { var p = GLctx.currentProgram; if (p) { var webglLoc = p.uniformLocsById[location]; - // p.uniformLocsById[location] stores either an integer, or a WebGLUniformLocation. - - // If an integer, we have not yet bound the location, so do it now. The integer value specifies the array index - // we should bind to. + // p.uniformLocsById[location] stores either an integer, or a + // WebGLUniformLocation. + // If an integer, we have not yet bound the location, so do it now. The + // integer value specifies the array index we should bind to. if (typeof webglLoc == 'number') { - p.uniformLocsById[location] = webglLoc = GLctx.getUniformLocation(p, p.uniformArrayNamesById[location] + (webglLoc > 0 ? '[' + webglLoc + ']' : '')); + p.uniformLocsById[location] = webglLoc = GLctx.getUniformLocation(p, p.uniformArrayNamesById[location] + (webglLoc > 0 ? `[${webglLoc}]` : '')); } // Else an already cached WebGLUniformLocation, return it. return webglLoc; } else { GL.recordError(0x502/*GL_INVALID_OPERATION*/); } - } - Module["webglGetUniformLocation"] = webglGetUniformLocation; + }; + Module['webglGetUniformLocation'] = webglGetUniformLocation; /** @suppress{checkTypes} */ - function emscriptenWebGLGetUniform(program, location, params, type) { + var emscriptenWebGLGetUniform = (program, location, params, type) => { if (!params) { - // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense - // if params == null, issue a GL error to notify user about it. + // GLES2 specification does not specify how to behave if params is a null + // pointer. Since calling this function does not make sense if params == + // null, issue a GL error to notify user about it. GL.recordError(0x501 /* GL_INVALID_VALUE */); return; } @@ -13724,39 +14879,53 @@ var ASM_CONSTS = { } } } - } - Module["emscriptenWebGLGetUniform"] = emscriptenWebGLGetUniform; + }; + Module['emscriptenWebGLGetUniform'] = emscriptenWebGLGetUniform; - function _emscripten_glGetUniformfv(program, location, params) { + /** @suppress {duplicate } */ + var _glGetUniformfv = (program, location, params) => { emscriptenWebGLGetUniform(program, location, params, 2); - } - Module["_emscripten_glGetUniformfv"] = _emscripten_glGetUniformfv; - _emscripten_glGetUniformfv.sig = 'viii'; + }; + Module['_glGetUniformfv'] = _glGetUniformfv; + _glGetUniformfv.sig = 'viip'; + var _emscripten_glGetUniformfv = _glGetUniformfv; + Module['_emscripten_glGetUniformfv'] = _emscripten_glGetUniformfv; + _emscripten_glGetUniformfv.sig = 'viip'; - function _emscripten_glGetUniformiv(program, location, params) { + /** @suppress {duplicate } */ + var _glGetUniformiv = (program, location, params) => { emscriptenWebGLGetUniform(program, location, params, 0); - } - Module["_emscripten_glGetUniformiv"] = _emscripten_glGetUniformiv; - _emscripten_glGetUniformiv.sig = 'viii'; - - function _emscripten_glGetVertexAttribPointerv(index, pname, pointer) { + }; + Module['_glGetUniformiv'] = _glGetUniformiv; + _glGetUniformiv.sig = 'viip'; + var _emscripten_glGetUniformiv = _glGetUniformiv; + Module['_emscripten_glGetUniformiv'] = _emscripten_glGetUniformiv; + _emscripten_glGetUniformiv.sig = 'viip'; + + /** @suppress {duplicate } */ + var _glGetVertexAttribPointerv = (index, pname, pointer) => { if (!pointer) { - // GLES2 specification does not specify how to behave if pointer is a null pointer. Since calling this function does not make sense - // if pointer == null, issue a GL error to notify user about it. + // GLES2 specification does not specify how to behave if pointer is a null + // pointer. Since calling this function does not make sense if pointer == + // null, issue a GL error to notify user about it. GL.recordError(0x501 /* GL_INVALID_VALUE */); return; } HEAP32[((pointer)>>2)] = GLctx.getVertexAttribOffset(index, pname); - } - Module["_emscripten_glGetVertexAttribPointerv"] = _emscripten_glGetVertexAttribPointerv; - _emscripten_glGetVertexAttribPointerv.sig = 'viii'; + }; + Module['_glGetVertexAttribPointerv'] = _glGetVertexAttribPointerv; + _glGetVertexAttribPointerv.sig = 'viip'; + var _emscripten_glGetVertexAttribPointerv = _glGetVertexAttribPointerv; + Module['_emscripten_glGetVertexAttribPointerv'] = _emscripten_glGetVertexAttribPointerv; + _emscripten_glGetVertexAttribPointerv.sig = 'viip'; /** @suppress{checkTypes} */ - function emscriptenWebGLGetVertexAttrib(index, pname, params, type) { + var emscriptenWebGLGetVertexAttrib = (index, pname, params, type) => { if (!params) { - // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense - // if params == null, issue a GL error to notify user about it. + // GLES2 specification does not specify how to behave if params is a null + // pointer. Since calling this function does not make sense if params == + // null, issue a GL error to notify user about it. GL.recordError(0x501 /* GL_INVALID_VALUE */); return; } @@ -13778,146 +14947,221 @@ var ASM_CONSTS = { } } } - } - Module["emscriptenWebGLGetVertexAttrib"] = emscriptenWebGLGetVertexAttrib; + }; + Module['emscriptenWebGLGetVertexAttrib'] = emscriptenWebGLGetVertexAttrib; - function _emscripten_glGetVertexAttribfv(index, pname, params) { - // N.B. This function may only be called if the vertex attribute was specified using the function glVertexAttrib*f(), - // otherwise the results are undefined. (GLES3 spec 6.1.12) + /** @suppress {duplicate } */ + var _glGetVertexAttribfv = (index, pname, params) => { + // N.B. This function may only be called if the vertex attribute was + // specified using the function glVertexAttrib*f(), otherwise the results + // are undefined. (GLES3 spec 6.1.12) emscriptenWebGLGetVertexAttrib(index, pname, params, 2); - } - Module["_emscripten_glGetVertexAttribfv"] = _emscripten_glGetVertexAttribfv; - _emscripten_glGetVertexAttribfv.sig = 'viii'; - - - function _emscripten_glGetVertexAttribiv(index, pname, params) { - // N.B. This function may only be called if the vertex attribute was specified using the function glVertexAttrib*f(), - // otherwise the results are undefined. (GLES3 spec 6.1.12) + }; + Module['_glGetVertexAttribfv'] = _glGetVertexAttribfv; + _glGetVertexAttribfv.sig = 'viip'; + var _emscripten_glGetVertexAttribfv = _glGetVertexAttribfv; + Module['_emscripten_glGetVertexAttribfv'] = _emscripten_glGetVertexAttribfv; + _emscripten_glGetVertexAttribfv.sig = 'viip'; + + + /** @suppress {duplicate } */ + var _glGetVertexAttribiv = (index, pname, params) => { + // N.B. This function may only be called if the vertex attribute was + // specified using the function glVertexAttrib*f(), otherwise the results + // are undefined. (GLES3 spec 6.1.12) emscriptenWebGLGetVertexAttrib(index, pname, params, 5); - } - Module["_emscripten_glGetVertexAttribiv"] = _emscripten_glGetVertexAttribiv; - _emscripten_glGetVertexAttribiv.sig = 'viii'; - - function _emscripten_glHint(x0, x1) { GLctx['hint'](x0, x1) } - Module["_emscripten_glHint"] = _emscripten_glHint; + }; + Module['_glGetVertexAttribiv'] = _glGetVertexAttribiv; + _glGetVertexAttribiv.sig = 'viip'; + var _emscripten_glGetVertexAttribiv = _glGetVertexAttribiv; + Module['_emscripten_glGetVertexAttribiv'] = _emscripten_glGetVertexAttribiv; + _emscripten_glGetVertexAttribiv.sig = 'viip'; + + /** @suppress {duplicate } */ + var _glHint = (x0, x1) => GLctx.hint(x0, x1); + Module['_glHint'] = _glHint; + _glHint.sig = 'vii'; + var _emscripten_glHint = _glHint; + Module['_emscripten_glHint'] = _emscripten_glHint; _emscripten_glHint.sig = 'vii'; - function _emscripten_glIsBuffer(buffer) { + /** @suppress {duplicate } */ + var _glIsBuffer = (buffer) => { var b = GL.buffers[buffer]; if (!b) return 0; return GLctx.isBuffer(b); - } - Module["_emscripten_glIsBuffer"] = _emscripten_glIsBuffer; + }; + Module['_glIsBuffer'] = _glIsBuffer; + _glIsBuffer.sig = 'ii'; + var _emscripten_glIsBuffer = _glIsBuffer; + Module['_emscripten_glIsBuffer'] = _emscripten_glIsBuffer; _emscripten_glIsBuffer.sig = 'ii'; - function _emscripten_glIsEnabled(x0) { return GLctx['isEnabled'](x0) } - Module["_emscripten_glIsEnabled"] = _emscripten_glIsEnabled; + /** @suppress {duplicate } */ + var _glIsEnabled = (x0) => GLctx.isEnabled(x0); + Module['_glIsEnabled'] = _glIsEnabled; + _glIsEnabled.sig = 'ii'; + var _emscripten_glIsEnabled = _glIsEnabled; + Module['_emscripten_glIsEnabled'] = _emscripten_glIsEnabled; _emscripten_glIsEnabled.sig = 'ii'; - function _emscripten_glIsFramebuffer(framebuffer) { + /** @suppress {duplicate } */ + var _glIsFramebuffer = (framebuffer) => { var fb = GL.framebuffers[framebuffer]; if (!fb) return 0; return GLctx.isFramebuffer(fb); - } - Module["_emscripten_glIsFramebuffer"] = _emscripten_glIsFramebuffer; + }; + Module['_glIsFramebuffer'] = _glIsFramebuffer; + _glIsFramebuffer.sig = 'ii'; + var _emscripten_glIsFramebuffer = _glIsFramebuffer; + Module['_emscripten_glIsFramebuffer'] = _emscripten_glIsFramebuffer; _emscripten_glIsFramebuffer.sig = 'ii'; - function _emscripten_glIsProgram(program) { + /** @suppress {duplicate } */ + var _glIsProgram = (program) => { program = GL.programs[program]; if (!program) return 0; return GLctx.isProgram(program); - } - Module["_emscripten_glIsProgram"] = _emscripten_glIsProgram; + }; + Module['_glIsProgram'] = _glIsProgram; + _glIsProgram.sig = 'ii'; + var _emscripten_glIsProgram = _glIsProgram; + Module['_emscripten_glIsProgram'] = _emscripten_glIsProgram; _emscripten_glIsProgram.sig = 'ii'; - function _emscripten_glIsQueryEXT(id) { + /** @suppress {duplicate } */ + var _glIsQueryEXT = (id) => { var query = GL.queries[id]; if (!query) return 0; return GLctx.disjointTimerQueryExt['isQueryEXT'](query); - } - Module["_emscripten_glIsQueryEXT"] = _emscripten_glIsQueryEXT; - _emscripten_glIsQueryEXT.sig = 'ii'; + }; + Module['_glIsQueryEXT'] = _glIsQueryEXT; + _glIsQueryEXT.sig = 'ii'; + var _emscripten_glIsQueryEXT = _glIsQueryEXT; + Module['_emscripten_glIsQueryEXT'] = _emscripten_glIsQueryEXT; - function _emscripten_glIsRenderbuffer(renderbuffer) { + /** @suppress {duplicate } */ + var _glIsRenderbuffer = (renderbuffer) => { var rb = GL.renderbuffers[renderbuffer]; if (!rb) return 0; return GLctx.isRenderbuffer(rb); - } - Module["_emscripten_glIsRenderbuffer"] = _emscripten_glIsRenderbuffer; + }; + Module['_glIsRenderbuffer'] = _glIsRenderbuffer; + _glIsRenderbuffer.sig = 'ii'; + var _emscripten_glIsRenderbuffer = _glIsRenderbuffer; + Module['_emscripten_glIsRenderbuffer'] = _emscripten_glIsRenderbuffer; _emscripten_glIsRenderbuffer.sig = 'ii'; - function _emscripten_glIsShader(shader) { + /** @suppress {duplicate } */ + var _glIsShader = (shader) => { var s = GL.shaders[shader]; if (!s) return 0; return GLctx.isShader(s); - } - Module["_emscripten_glIsShader"] = _emscripten_glIsShader; + }; + Module['_glIsShader'] = _glIsShader; + _glIsShader.sig = 'ii'; + var _emscripten_glIsShader = _glIsShader; + Module['_emscripten_glIsShader'] = _emscripten_glIsShader; _emscripten_glIsShader.sig = 'ii'; - function _emscripten_glIsTexture(id) { + /** @suppress {duplicate } */ + var _glIsTexture = (id) => { var texture = GL.textures[id]; if (!texture) return 0; return GLctx.isTexture(texture); - } - Module["_emscripten_glIsTexture"] = _emscripten_glIsTexture; + }; + Module['_glIsTexture'] = _glIsTexture; + _glIsTexture.sig = 'ii'; + var _emscripten_glIsTexture = _glIsTexture; + Module['_emscripten_glIsTexture'] = _emscripten_glIsTexture; _emscripten_glIsTexture.sig = 'ii'; - function _emscripten_glIsVertexArrayOES(array) { + + /** @suppress {duplicate } */ + var _glIsVertexArray = (array) => { var vao = GL.vaos[array]; if (!vao) return 0; - return GLctx['isVertexArray'](vao); - } - Module["_emscripten_glIsVertexArrayOES"] = _emscripten_glIsVertexArrayOES; + return GLctx.isVertexArray(vao); + }; + Module['_glIsVertexArray'] = _glIsVertexArray; + _glIsVertexArray.sig = 'ii'; + /** @suppress {duplicate } */ + var _glIsVertexArrayOES = _glIsVertexArray; + Module['_glIsVertexArrayOES'] = _glIsVertexArrayOES; + _glIsVertexArrayOES.sig = 'ii'; + var _emscripten_glIsVertexArrayOES = _glIsVertexArrayOES; + Module['_emscripten_glIsVertexArrayOES'] = _emscripten_glIsVertexArrayOES; _emscripten_glIsVertexArrayOES.sig = 'ii'; - function _emscripten_glLineWidth(x0) { GLctx['lineWidth'](x0) } - Module["_emscripten_glLineWidth"] = _emscripten_glLineWidth; + /** @suppress {duplicate } */ + var _glLineWidth = (x0) => GLctx.lineWidth(x0); + Module['_glLineWidth'] = _glLineWidth; + _glLineWidth.sig = 'vf'; + var _emscripten_glLineWidth = _glLineWidth; + Module['_emscripten_glLineWidth'] = _emscripten_glLineWidth; _emscripten_glLineWidth.sig = 'vf'; - function _emscripten_glLinkProgram(program) { + /** @suppress {duplicate } */ + var _glLinkProgram = (program) => { program = GL.programs[program]; GLctx.linkProgram(program); // Invalidate earlier computed uniform->ID mappings, those have now become stale program.uniformLocsById = 0; // Mark as null-like so that glGetUniformLocation() knows to populate this again. program.uniformSizeAndIdsByName = {}; - } - Module["_emscripten_glLinkProgram"] = _emscripten_glLinkProgram; + }; + Module['_glLinkProgram'] = _glLinkProgram; + _glLinkProgram.sig = 'vi'; + var _emscripten_glLinkProgram = _glLinkProgram; + Module['_emscripten_glLinkProgram'] = _emscripten_glLinkProgram; _emscripten_glLinkProgram.sig = 'vi'; - function _emscripten_glPixelStorei(pname, param) { + /** @suppress {duplicate } */ + var _glPixelStorei = (pname, param) => { if (pname == 0xCF5 /* GL_UNPACK_ALIGNMENT */) { GL.unpackAlignment = param; } GLctx.pixelStorei(pname, param); - } - Module["_emscripten_glPixelStorei"] = _emscripten_glPixelStorei; + }; + Module['_glPixelStorei'] = _glPixelStorei; + _glPixelStorei.sig = 'vii'; + var _emscripten_glPixelStorei = _glPixelStorei; + Module['_emscripten_glPixelStorei'] = _emscripten_glPixelStorei; _emscripten_glPixelStorei.sig = 'vii'; - function _emscripten_glPolygonOffset(x0, x1) { GLctx['polygonOffset'](x0, x1) } - Module["_emscripten_glPolygonOffset"] = _emscripten_glPolygonOffset; + /** @suppress {duplicate } */ + var _glPolygonOffset = (x0, x1) => GLctx.polygonOffset(x0, x1); + Module['_glPolygonOffset'] = _glPolygonOffset; + _glPolygonOffset.sig = 'vff'; + var _emscripten_glPolygonOffset = _glPolygonOffset; + Module['_emscripten_glPolygonOffset'] = _emscripten_glPolygonOffset; _emscripten_glPolygonOffset.sig = 'vff'; - function _emscripten_glQueryCounterEXT(id, target) { + /** @suppress {duplicate } */ + var _glQueryCounterEXT = (id, target) => { GLctx.disjointTimerQueryExt['queryCounterEXT'](GL.queries[id], target); - } - Module["_emscripten_glQueryCounterEXT"] = _emscripten_glQueryCounterEXT; - _emscripten_glQueryCounterEXT.sig = 'vii'; + }; + Module['_glQueryCounterEXT'] = _glQueryCounterEXT; + _glQueryCounterEXT.sig = 'vii'; + var _emscripten_glQueryCounterEXT = _glQueryCounterEXT; + Module['_emscripten_glQueryCounterEXT'] = _emscripten_glQueryCounterEXT; - function computeUnpackAlignedImageSize(width, height, sizePerPixel, alignment) { + var computeUnpackAlignedImageSize = (width, height, sizePerPixel, alignment) => { function roundedToNextMultipleOf(x, y) { return (x + y - 1) & -y; } var plainRowSize = width * sizePerPixel; var alignedRowSize = roundedToNextMultipleOf(plainRowSize, alignment); return height * alignedRowSize; - } - Module["computeUnpackAlignedImageSize"] = computeUnpackAlignedImageSize; + }; + Module['computeUnpackAlignedImageSize'] = computeUnpackAlignedImageSize; - function __colorChannelsInGlTextureFormat(format) { - // Micro-optimizations for size: map format to size by subtracting smallest enum value (0x1902) from all values first. - // Also omit the most common size value (1) from the list, which is assumed by formats not on the list. + var colorChannelsInGlTextureFormat = (format) => { + // Micro-optimizations for size: map format to size by subtracting smallest + // enum value (0x1902) from all values first. Also omit the most common + // size value (1) from the list, which is assumed by formats not on the + // list. var colorChannels = { // 0x1902 /* GL_DEPTH_COMPONENT */ - 0x1902: 1, // 0x1906 /* GL_ALPHA */ - 0x1902: 1, @@ -13929,10 +15173,10 @@ var ASM_CONSTS = { 29504: 4, }; return colorChannels[format - 0x1902]||1; - } - Module["__colorChannelsInGlTextureFormat"] = __colorChannelsInGlTextureFormat; + }; + Module['colorChannelsInGlTextureFormat'] = colorChannelsInGlTextureFormat; - function heapObjectForWebGLType(type) { + var heapObjectForWebGLType = (type) => { // Micro-optimization for size: Subtract lowest GL enum number (0x1400/* GL_BYTE */) from type to compare // smaller values for the heap, for shorter generated code size. // Also the type HEAPU16 is not tested for explicitly, but any unrecognized type will return out HEAPU16. @@ -13951,143 +15195,221 @@ var ASM_CONSTS = { return HEAPU32; return HEAPU16; - } - Module["heapObjectForWebGLType"] = heapObjectForWebGLType; + }; + Module['heapObjectForWebGLType'] = heapObjectForWebGLType; - function heapAccessShiftForWebGLHeap(heap) { - return 31 - Math.clz32(heap.BYTES_PER_ELEMENT); - } - Module["heapAccessShiftForWebGLHeap"] = heapAccessShiftForWebGLHeap; + var toTypedArrayIndex = (pointer, heap) => + pointer >>> (31 - Math.clz32(heap.BYTES_PER_ELEMENT)); + Module['toTypedArrayIndex'] = toTypedArrayIndex; - function emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, internalFormat) { + var emscriptenWebGLGetTexPixelData = (type, format, width, height, pixels, internalFormat) => { var heap = heapObjectForWebGLType(type); - var shift = heapAccessShiftForWebGLHeap(heap); - var byteSize = 1<> shift, pixels + bytes >> shift); - } - Module["emscriptenWebGLGetTexPixelData"] = emscriptenWebGLGetTexPixelData; + return heap.subarray(toTypedArrayIndex(pixels, heap), toTypedArrayIndex(pixels + bytes, heap)); + }; + Module['emscriptenWebGLGetTexPixelData'] = emscriptenWebGLGetTexPixelData; - function _emscripten_glReadPixels(x, y, width, height, format, type, pixels) { + /** @suppress {duplicate } */ + var _glReadPixels = (x, y, width, height, format, type, pixels) => { var pixelData = emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, format); if (!pixelData) { GL.recordError(0x500/*GL_INVALID_ENUM*/); return; } GLctx.readPixels(x, y, width, height, format, type, pixelData); - } - Module["_emscripten_glReadPixels"] = _emscripten_glReadPixels; - _emscripten_glReadPixels.sig = 'viiiiiii'; - - function _emscripten_glReleaseShaderCompiler() { + }; + Module['_glReadPixels'] = _glReadPixels; + _glReadPixels.sig = 'viiiiiip'; + var _emscripten_glReadPixels = _glReadPixels; + Module['_emscripten_glReadPixels'] = _emscripten_glReadPixels; + _emscripten_glReadPixels.sig = 'viiiiiip'; + + /** @suppress {duplicate } */ + var _glReleaseShaderCompiler = () => { // NOP (as allowed by GLES 2.0 spec) - } - Module["_emscripten_glReleaseShaderCompiler"] = _emscripten_glReleaseShaderCompiler; + }; + Module['_glReleaseShaderCompiler'] = _glReleaseShaderCompiler; + _glReleaseShaderCompiler.sig = 'v'; + var _emscripten_glReleaseShaderCompiler = _glReleaseShaderCompiler; + Module['_emscripten_glReleaseShaderCompiler'] = _emscripten_glReleaseShaderCompiler; _emscripten_glReleaseShaderCompiler.sig = 'v'; - function _emscripten_glRenderbufferStorage(x0, x1, x2, x3) { GLctx['renderbufferStorage'](x0, x1, x2, x3) } - Module["_emscripten_glRenderbufferStorage"] = _emscripten_glRenderbufferStorage; + /** @suppress {duplicate } */ + var _glRenderbufferStorage = (x0, x1, x2, x3) => GLctx.renderbufferStorage(x0, x1, x2, x3); + Module['_glRenderbufferStorage'] = _glRenderbufferStorage; + _glRenderbufferStorage.sig = 'viiii'; + var _emscripten_glRenderbufferStorage = _glRenderbufferStorage; + Module['_emscripten_glRenderbufferStorage'] = _emscripten_glRenderbufferStorage; _emscripten_glRenderbufferStorage.sig = 'viiii'; - function _emscripten_glSampleCoverage(value, invert) { + /** @suppress {duplicate } */ + var _glSampleCoverage = (value, invert) => { GLctx.sampleCoverage(value, !!invert); - } - Module["_emscripten_glSampleCoverage"] = _emscripten_glSampleCoverage; - _emscripten_glSampleCoverage.sig = 'vii'; - - function _emscripten_glScissor(x0, x1, x2, x3) { GLctx['scissor'](x0, x1, x2, x3) } - Module["_emscripten_glScissor"] = _emscripten_glScissor; + }; + Module['_glSampleCoverage'] = _glSampleCoverage; + _glSampleCoverage.sig = 'vfi'; + var _emscripten_glSampleCoverage = _glSampleCoverage; + Module['_emscripten_glSampleCoverage'] = _emscripten_glSampleCoverage; + _emscripten_glSampleCoverage.sig = 'vfi'; + + /** @suppress {duplicate } */ + var _glScissor = (x0, x1, x2, x3) => GLctx.scissor(x0, x1, x2, x3); + Module['_glScissor'] = _glScissor; + _glScissor.sig = 'viiii'; + var _emscripten_glScissor = _glScissor; + Module['_emscripten_glScissor'] = _emscripten_glScissor; _emscripten_glScissor.sig = 'viiii'; - function _emscripten_glShaderBinary() { + /** @suppress {duplicate } */ + var _glShaderBinary = (count, shaders, binaryformat, binary, length) => { GL.recordError(0x500/*GL_INVALID_ENUM*/); - } - Module["_emscripten_glShaderBinary"] = _emscripten_glShaderBinary; - _emscripten_glShaderBinary.sig = 'v'; - - function _emscripten_glShaderSource(shader, count, string, length) { + }; + Module['_glShaderBinary'] = _glShaderBinary; + _glShaderBinary.sig = 'vipipi'; + var _emscripten_glShaderBinary = _glShaderBinary; + Module['_emscripten_glShaderBinary'] = _emscripten_glShaderBinary; + _emscripten_glShaderBinary.sig = 'vipipi'; + + /** @suppress {duplicate } */ + var _glShaderSource = (shader, count, string, length) => { var source = GL.getSource(shader, count, string, length); GLctx.shaderSource(GL.shaders[shader], source); - } - Module["_emscripten_glShaderSource"] = _emscripten_glShaderSource; - _emscripten_glShaderSource.sig = 'viiii'; - - function _emscripten_glStencilFunc(x0, x1, x2) { GLctx['stencilFunc'](x0, x1, x2) } - Module["_emscripten_glStencilFunc"] = _emscripten_glStencilFunc; + }; + Module['_glShaderSource'] = _glShaderSource; + _glShaderSource.sig = 'viipp'; + var _emscripten_glShaderSource = _glShaderSource; + Module['_emscripten_glShaderSource'] = _emscripten_glShaderSource; + _emscripten_glShaderSource.sig = 'viipp'; + + /** @suppress {duplicate } */ + var _glStencilFunc = (x0, x1, x2) => GLctx.stencilFunc(x0, x1, x2); + Module['_glStencilFunc'] = _glStencilFunc; + _glStencilFunc.sig = 'viii'; + var _emscripten_glStencilFunc = _glStencilFunc; + Module['_emscripten_glStencilFunc'] = _emscripten_glStencilFunc; _emscripten_glStencilFunc.sig = 'viii'; - function _emscripten_glStencilFuncSeparate(x0, x1, x2, x3) { GLctx['stencilFuncSeparate'](x0, x1, x2, x3) } - Module["_emscripten_glStencilFuncSeparate"] = _emscripten_glStencilFuncSeparate; + /** @suppress {duplicate } */ + var _glStencilFuncSeparate = (x0, x1, x2, x3) => GLctx.stencilFuncSeparate(x0, x1, x2, x3); + Module['_glStencilFuncSeparate'] = _glStencilFuncSeparate; + _glStencilFuncSeparate.sig = 'viiii'; + var _emscripten_glStencilFuncSeparate = _glStencilFuncSeparate; + Module['_emscripten_glStencilFuncSeparate'] = _emscripten_glStencilFuncSeparate; _emscripten_glStencilFuncSeparate.sig = 'viiii'; - function _emscripten_glStencilMask(x0) { GLctx['stencilMask'](x0) } - Module["_emscripten_glStencilMask"] = _emscripten_glStencilMask; + /** @suppress {duplicate } */ + var _glStencilMask = (x0) => GLctx.stencilMask(x0); + Module['_glStencilMask'] = _glStencilMask; + _glStencilMask.sig = 'vi'; + var _emscripten_glStencilMask = _glStencilMask; + Module['_emscripten_glStencilMask'] = _emscripten_glStencilMask; _emscripten_glStencilMask.sig = 'vi'; - function _emscripten_glStencilMaskSeparate(x0, x1) { GLctx['stencilMaskSeparate'](x0, x1) } - Module["_emscripten_glStencilMaskSeparate"] = _emscripten_glStencilMaskSeparate; + /** @suppress {duplicate } */ + var _glStencilMaskSeparate = (x0, x1) => GLctx.stencilMaskSeparate(x0, x1); + Module['_glStencilMaskSeparate'] = _glStencilMaskSeparate; + _glStencilMaskSeparate.sig = 'vii'; + var _emscripten_glStencilMaskSeparate = _glStencilMaskSeparate; + Module['_emscripten_glStencilMaskSeparate'] = _emscripten_glStencilMaskSeparate; _emscripten_glStencilMaskSeparate.sig = 'vii'; - function _emscripten_glStencilOp(x0, x1, x2) { GLctx['stencilOp'](x0, x1, x2) } - Module["_emscripten_glStencilOp"] = _emscripten_glStencilOp; + /** @suppress {duplicate } */ + var _glStencilOp = (x0, x1, x2) => GLctx.stencilOp(x0, x1, x2); + Module['_glStencilOp'] = _glStencilOp; + _glStencilOp.sig = 'viii'; + var _emscripten_glStencilOp = _glStencilOp; + Module['_emscripten_glStencilOp'] = _emscripten_glStencilOp; _emscripten_glStencilOp.sig = 'viii'; - function _emscripten_glStencilOpSeparate(x0, x1, x2, x3) { GLctx['stencilOpSeparate'](x0, x1, x2, x3) } - Module["_emscripten_glStencilOpSeparate"] = _emscripten_glStencilOpSeparate; + /** @suppress {duplicate } */ + var _glStencilOpSeparate = (x0, x1, x2, x3) => GLctx.stencilOpSeparate(x0, x1, x2, x3); + Module['_glStencilOpSeparate'] = _glStencilOpSeparate; + _glStencilOpSeparate.sig = 'viiii'; + var _emscripten_glStencilOpSeparate = _glStencilOpSeparate; + Module['_emscripten_glStencilOpSeparate'] = _emscripten_glStencilOpSeparate; _emscripten_glStencilOpSeparate.sig = 'viiii'; - function _emscripten_glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels) { - GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, internalFormat) : null); - } - Module["_emscripten_glTexImage2D"] = _emscripten_glTexImage2D; - _emscripten_glTexImage2D.sig = 'viiiiiiiii'; - - function _emscripten_glTexParameterf(x0, x1, x2) { GLctx['texParameterf'](x0, x1, x2) } - Module["_emscripten_glTexParameterf"] = _emscripten_glTexParameterf; - _emscripten_glTexParameterf.sig = 'viii'; - - function _emscripten_glTexParameterfv(target, pname, params) { + /** @suppress {duplicate } */ + var _glTexImage2D = (target, level, internalFormat, width, height, border, format, type, pixels) => { + var pixelData = pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, internalFormat) : null; + GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixelData); + }; + Module['_glTexImage2D'] = _glTexImage2D; + _glTexImage2D.sig = 'viiiiiiiip'; + var _emscripten_glTexImage2D = _glTexImage2D; + Module['_emscripten_glTexImage2D'] = _emscripten_glTexImage2D; + _emscripten_glTexImage2D.sig = 'viiiiiiiip'; + + /** @suppress {duplicate } */ + var _glTexParameterf = (x0, x1, x2) => GLctx.texParameterf(x0, x1, x2); + Module['_glTexParameterf'] = _glTexParameterf; + _glTexParameterf.sig = 'viif'; + var _emscripten_glTexParameterf = _glTexParameterf; + Module['_emscripten_glTexParameterf'] = _emscripten_glTexParameterf; + _emscripten_glTexParameterf.sig = 'viif'; + + /** @suppress {duplicate } */ + var _glTexParameterfv = (target, pname, params) => { var param = HEAPF32[((params)>>2)]; GLctx.texParameterf(target, pname, param); - } - Module["_emscripten_glTexParameterfv"] = _emscripten_glTexParameterfv; - _emscripten_glTexParameterfv.sig = 'viii'; - - function _emscripten_glTexParameteri(x0, x1, x2) { GLctx['texParameteri'](x0, x1, x2) } - Module["_emscripten_glTexParameteri"] = _emscripten_glTexParameteri; + }; + Module['_glTexParameterfv'] = _glTexParameterfv; + _glTexParameterfv.sig = 'viip'; + var _emscripten_glTexParameterfv = _glTexParameterfv; + Module['_emscripten_glTexParameterfv'] = _emscripten_glTexParameterfv; + _emscripten_glTexParameterfv.sig = 'viip'; + + /** @suppress {duplicate } */ + var _glTexParameteri = (x0, x1, x2) => GLctx.texParameteri(x0, x1, x2); + Module['_glTexParameteri'] = _glTexParameteri; + _glTexParameteri.sig = 'viii'; + var _emscripten_glTexParameteri = _glTexParameteri; + Module['_emscripten_glTexParameteri'] = _emscripten_glTexParameteri; _emscripten_glTexParameteri.sig = 'viii'; - function _emscripten_glTexParameteriv(target, pname, params) { + /** @suppress {duplicate } */ + var _glTexParameteriv = (target, pname, params) => { var param = HEAP32[((params)>>2)]; GLctx.texParameteri(target, pname, param); - } - Module["_emscripten_glTexParameteriv"] = _emscripten_glTexParameteriv; - _emscripten_glTexParameteriv.sig = 'viii'; + }; + Module['_glTexParameteriv'] = _glTexParameteriv; + _glTexParameteriv.sig = 'viip'; + var _emscripten_glTexParameteriv = _glTexParameteriv; + Module['_emscripten_glTexParameteriv'] = _emscripten_glTexParameteriv; + _emscripten_glTexParameteriv.sig = 'viip'; - function _emscripten_glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels) { - var pixelData = null; - if (pixels) pixelData = emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, 0); + /** @suppress {duplicate } */ + var _glTexSubImage2D = (target, level, xoffset, yoffset, width, height, format, type, pixels) => { + var pixelData = pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, 0) : null; GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixelData); - } - Module["_emscripten_glTexSubImage2D"] = _emscripten_glTexSubImage2D; - _emscripten_glTexSubImage2D.sig = 'viiiiiiiii'; + }; + Module['_glTexSubImage2D'] = _glTexSubImage2D; + _glTexSubImage2D.sig = 'viiiiiiiip'; + var _emscripten_glTexSubImage2D = _glTexSubImage2D; + Module['_emscripten_glTexSubImage2D'] = _emscripten_glTexSubImage2D; + _emscripten_glTexSubImage2D.sig = 'viiiiiiiip'; - function _emscripten_glUniform1f(location, v0) { + /** @suppress {duplicate } */ + var _glUniform1f = (location, v0) => { GLctx.uniform1f(webglGetUniformLocation(location), v0); - } - Module["_emscripten_glUniform1f"] = _emscripten_glUniform1f; + }; + Module['_glUniform1f'] = _glUniform1f; + _glUniform1f.sig = 'vif'; + var _emscripten_glUniform1f = _glUniform1f; + Module['_emscripten_glUniform1f'] = _emscripten_glUniform1f; _emscripten_glUniform1f.sig = 'vif'; var miniTempWebGLFloatBuffers = []; - Module["miniTempWebGLFloatBuffers"] = miniTempWebGLFloatBuffers; + Module['miniTempWebGLFloatBuffers'] = miniTempWebGLFloatBuffers; - function _emscripten_glUniform1fv(location, count, value) { + /** @suppress {duplicate } */ + var _glUniform1fv = (location, count, value) => { if (count <= 288) { // avoid allocation when uploading few enough uniforms @@ -14097,51 +15419,67 @@ var ASM_CONSTS = { } } else { - var view = HEAPF32.subarray((value)>>2, (value+count*4)>>2); + var view = HEAPF32.subarray((((value)>>2)), ((value+count*4)>>2)); } GLctx.uniform1fv(webglGetUniformLocation(location), view); - } - Module["_emscripten_glUniform1fv"] = _emscripten_glUniform1fv; - _emscripten_glUniform1fv.sig = 'viii'; + }; + Module['_glUniform1fv'] = _glUniform1fv; + _glUniform1fv.sig = 'viip'; + var _emscripten_glUniform1fv = _glUniform1fv; + Module['_emscripten_glUniform1fv'] = _emscripten_glUniform1fv; + _emscripten_glUniform1fv.sig = 'viip'; - function _emscripten_glUniform1i(location, v0) { + /** @suppress {duplicate } */ + var _glUniform1i = (location, v0) => { GLctx.uniform1i(webglGetUniformLocation(location), v0); - } - Module["_emscripten_glUniform1i"] = _emscripten_glUniform1i; + }; + Module['_glUniform1i'] = _glUniform1i; + _glUniform1i.sig = 'vii'; + var _emscripten_glUniform1i = _glUniform1i; + Module['_emscripten_glUniform1i'] = _emscripten_glUniform1i; _emscripten_glUniform1i.sig = 'vii'; - var __miniTempWebGLIntBuffers = []; - Module["__miniTempWebGLIntBuffers"] = __miniTempWebGLIntBuffers; + var miniTempWebGLIntBuffers = []; + Module['miniTempWebGLIntBuffers'] = miniTempWebGLIntBuffers; - function _emscripten_glUniform1iv(location, count, value) { + /** @suppress {duplicate } */ + var _glUniform1iv = (location, count, value) => { if (count <= 288) { // avoid allocation when uploading few enough uniforms - var view = __miniTempWebGLIntBuffers[count-1]; + var view = miniTempWebGLIntBuffers[count-1]; for (var i = 0; i < count; ++i) { view[i] = HEAP32[(((value)+(4*i))>>2)]; } } else { - var view = HEAP32.subarray((value)>>2, (value+count*4)>>2); + var view = HEAP32.subarray((((value)>>2)), ((value+count*4)>>2)); } GLctx.uniform1iv(webglGetUniformLocation(location), view); - } - Module["_emscripten_glUniform1iv"] = _emscripten_glUniform1iv; - _emscripten_glUniform1iv.sig = 'viii'; + }; + Module['_glUniform1iv'] = _glUniform1iv; + _glUniform1iv.sig = 'viip'; + var _emscripten_glUniform1iv = _glUniform1iv; + Module['_emscripten_glUniform1iv'] = _emscripten_glUniform1iv; + _emscripten_glUniform1iv.sig = 'viip'; - function _emscripten_glUniform2f(location, v0, v1) { + /** @suppress {duplicate } */ + var _glUniform2f = (location, v0, v1) => { GLctx.uniform2f(webglGetUniformLocation(location), v0, v1); - } - Module["_emscripten_glUniform2f"] = _emscripten_glUniform2f; + }; + Module['_glUniform2f'] = _glUniform2f; + _glUniform2f.sig = 'viff'; + var _emscripten_glUniform2f = _glUniform2f; + Module['_emscripten_glUniform2f'] = _emscripten_glUniform2f; _emscripten_glUniform2f.sig = 'viff'; - function _emscripten_glUniform2fv(location, count, value) { + /** @suppress {duplicate } */ + var _glUniform2fv = (location, count, value) => { if (count <= 144) { // avoid allocation when uploading few enough uniforms @@ -14152,50 +15490,66 @@ var ASM_CONSTS = { } } else { - var view = HEAPF32.subarray((value)>>2, (value+count*8)>>2); + var view = HEAPF32.subarray((((value)>>2)), ((value+count*8)>>2)); } GLctx.uniform2fv(webglGetUniformLocation(location), view); - } - Module["_emscripten_glUniform2fv"] = _emscripten_glUniform2fv; - _emscripten_glUniform2fv.sig = 'viii'; + }; + Module['_glUniform2fv'] = _glUniform2fv; + _glUniform2fv.sig = 'viip'; + var _emscripten_glUniform2fv = _glUniform2fv; + Module['_emscripten_glUniform2fv'] = _emscripten_glUniform2fv; + _emscripten_glUniform2fv.sig = 'viip'; - function _emscripten_glUniform2i(location, v0, v1) { + /** @suppress {duplicate } */ + var _glUniform2i = (location, v0, v1) => { GLctx.uniform2i(webglGetUniformLocation(location), v0, v1); - } - Module["_emscripten_glUniform2i"] = _emscripten_glUniform2i; + }; + Module['_glUniform2i'] = _glUniform2i; + _glUniform2i.sig = 'viii'; + var _emscripten_glUniform2i = _glUniform2i; + Module['_emscripten_glUniform2i'] = _emscripten_glUniform2i; _emscripten_glUniform2i.sig = 'viii'; - function _emscripten_glUniform2iv(location, count, value) { + /** @suppress {duplicate } */ + var _glUniform2iv = (location, count, value) => { if (count <= 144) { // avoid allocation when uploading few enough uniforms - var view = __miniTempWebGLIntBuffers[2*count-1]; + var view = miniTempWebGLIntBuffers[2*count-1]; for (var i = 0; i < 2*count; i += 2) { view[i] = HEAP32[(((value)+(4*i))>>2)]; view[i+1] = HEAP32[(((value)+(4*i+4))>>2)]; } } else { - var view = HEAP32.subarray((value)>>2, (value+count*8)>>2); + var view = HEAP32.subarray((((value)>>2)), ((value+count*8)>>2)); } GLctx.uniform2iv(webglGetUniformLocation(location), view); - } - Module["_emscripten_glUniform2iv"] = _emscripten_glUniform2iv; - _emscripten_glUniform2iv.sig = 'viii'; + }; + Module['_glUniform2iv'] = _glUniform2iv; + _glUniform2iv.sig = 'viip'; + var _emscripten_glUniform2iv = _glUniform2iv; + Module['_emscripten_glUniform2iv'] = _emscripten_glUniform2iv; + _emscripten_glUniform2iv.sig = 'viip'; - function _emscripten_glUniform3f(location, v0, v1, v2) { + /** @suppress {duplicate } */ + var _glUniform3f = (location, v0, v1, v2) => { GLctx.uniform3f(webglGetUniformLocation(location), v0, v1, v2); - } - Module["_emscripten_glUniform3f"] = _emscripten_glUniform3f; + }; + Module['_glUniform3f'] = _glUniform3f; + _glUniform3f.sig = 'vifff'; + var _emscripten_glUniform3f = _glUniform3f; + Module['_emscripten_glUniform3f'] = _emscripten_glUniform3f; _emscripten_glUniform3f.sig = 'vifff'; - function _emscripten_glUniform3fv(location, count, value) { + /** @suppress {duplicate } */ + var _glUniform3fv = (location, count, value) => { if (count <= 96) { // avoid allocation when uploading few enough uniforms @@ -14207,27 +15561,35 @@ var ASM_CONSTS = { } } else { - var view = HEAPF32.subarray((value)>>2, (value+count*12)>>2); + var view = HEAPF32.subarray((((value)>>2)), ((value+count*12)>>2)); } GLctx.uniform3fv(webglGetUniformLocation(location), view); - } - Module["_emscripten_glUniform3fv"] = _emscripten_glUniform3fv; - _emscripten_glUniform3fv.sig = 'viii'; + }; + Module['_glUniform3fv'] = _glUniform3fv; + _glUniform3fv.sig = 'viip'; + var _emscripten_glUniform3fv = _glUniform3fv; + Module['_emscripten_glUniform3fv'] = _emscripten_glUniform3fv; + _emscripten_glUniform3fv.sig = 'viip'; - function _emscripten_glUniform3i(location, v0, v1, v2) { + /** @suppress {duplicate } */ + var _glUniform3i = (location, v0, v1, v2) => { GLctx.uniform3i(webglGetUniformLocation(location), v0, v1, v2); - } - Module["_emscripten_glUniform3i"] = _emscripten_glUniform3i; + }; + Module['_glUniform3i'] = _glUniform3i; + _glUniform3i.sig = 'viiii'; + var _emscripten_glUniform3i = _glUniform3i; + Module['_emscripten_glUniform3i'] = _emscripten_glUniform3i; _emscripten_glUniform3i.sig = 'viiii'; - function _emscripten_glUniform3iv(location, count, value) { + /** @suppress {duplicate } */ + var _glUniform3iv = (location, count, value) => { if (count <= 96) { // avoid allocation when uploading few enough uniforms - var view = __miniTempWebGLIntBuffers[3*count-1]; + var view = miniTempWebGLIntBuffers[3*count-1]; for (var i = 0; i < 3*count; i += 3) { view[i] = HEAP32[(((value)+(4*i))>>2)]; view[i+1] = HEAP32[(((value)+(4*i+4))>>2)]; @@ -14235,30 +15597,38 @@ var ASM_CONSTS = { } } else { - var view = HEAP32.subarray((value)>>2, (value+count*12)>>2); + var view = HEAP32.subarray((((value)>>2)), ((value+count*12)>>2)); } GLctx.uniform3iv(webglGetUniformLocation(location), view); - } - Module["_emscripten_glUniform3iv"] = _emscripten_glUniform3iv; - _emscripten_glUniform3iv.sig = 'viii'; + }; + Module['_glUniform3iv'] = _glUniform3iv; + _glUniform3iv.sig = 'viip'; + var _emscripten_glUniform3iv = _glUniform3iv; + Module['_emscripten_glUniform3iv'] = _emscripten_glUniform3iv; + _emscripten_glUniform3iv.sig = 'viip'; - function _emscripten_glUniform4f(location, v0, v1, v2, v3) { + /** @suppress {duplicate } */ + var _glUniform4f = (location, v0, v1, v2, v3) => { GLctx.uniform4f(webglGetUniformLocation(location), v0, v1, v2, v3); - } - Module["_emscripten_glUniform4f"] = _emscripten_glUniform4f; + }; + Module['_glUniform4f'] = _glUniform4f; + _glUniform4f.sig = 'viffff'; + var _emscripten_glUniform4f = _glUniform4f; + Module['_emscripten_glUniform4f'] = _emscripten_glUniform4f; _emscripten_glUniform4f.sig = 'viffff'; - function _emscripten_glUniform4fv(location, count, value) { + /** @suppress {duplicate } */ + var _glUniform4fv = (location, count, value) => { if (count <= 72) { // avoid allocation when uploading few enough uniforms var view = miniTempWebGLFloatBuffers[4*count-1]; // hoist the heap out of the loop for size and for pthreads+growth. var heap = HEAPF32; - value >>= 2; + value = ((value)>>2); for (var i = 0; i < 4 * count; i += 4) { var dst = value + i; view[i] = heap[dst]; @@ -14268,27 +15638,35 @@ var ASM_CONSTS = { } } else { - var view = HEAPF32.subarray((value)>>2, (value+count*16)>>2); + var view = HEAPF32.subarray((((value)>>2)), ((value+count*16)>>2)); } GLctx.uniform4fv(webglGetUniformLocation(location), view); - } - Module["_emscripten_glUniform4fv"] = _emscripten_glUniform4fv; - _emscripten_glUniform4fv.sig = 'viii'; + }; + Module['_glUniform4fv'] = _glUniform4fv; + _glUniform4fv.sig = 'viip'; + var _emscripten_glUniform4fv = _glUniform4fv; + Module['_emscripten_glUniform4fv'] = _emscripten_glUniform4fv; + _emscripten_glUniform4fv.sig = 'viip'; - function _emscripten_glUniform4i(location, v0, v1, v2, v3) { + /** @suppress {duplicate } */ + var _glUniform4i = (location, v0, v1, v2, v3) => { GLctx.uniform4i(webglGetUniformLocation(location), v0, v1, v2, v3); - } - Module["_emscripten_glUniform4i"] = _emscripten_glUniform4i; + }; + Module['_glUniform4i'] = _glUniform4i; + _glUniform4i.sig = 'viiiii'; + var _emscripten_glUniform4i = _glUniform4i; + Module['_emscripten_glUniform4i'] = _emscripten_glUniform4i; _emscripten_glUniform4i.sig = 'viiiii'; - function _emscripten_glUniform4iv(location, count, value) { + /** @suppress {duplicate } */ + var _glUniform4iv = (location, count, value) => { if (count <= 72) { // avoid allocation when uploading few enough uniforms - var view = __miniTempWebGLIntBuffers[4*count-1]; + var view = miniTempWebGLIntBuffers[4*count-1]; for (var i = 0; i < 4*count; i += 4) { view[i] = HEAP32[(((value)+(4*i))>>2)]; view[i+1] = HEAP32[(((value)+(4*i+4))>>2)]; @@ -14297,16 +15675,20 @@ var ASM_CONSTS = { } } else { - var view = HEAP32.subarray((value)>>2, (value+count*16)>>2); + var view = HEAP32.subarray((((value)>>2)), ((value+count*16)>>2)); } GLctx.uniform4iv(webglGetUniformLocation(location), view); - } - Module["_emscripten_glUniform4iv"] = _emscripten_glUniform4iv; - _emscripten_glUniform4iv.sig = 'viii'; + }; + Module['_glUniform4iv'] = _glUniform4iv; + _glUniform4iv.sig = 'viip'; + var _emscripten_glUniform4iv = _glUniform4iv; + Module['_emscripten_glUniform4iv'] = _emscripten_glUniform4iv; + _emscripten_glUniform4iv.sig = 'viip'; - function _emscripten_glUniformMatrix2fv(location, count, transpose, value) { + /** @suppress {duplicate } */ + var _glUniformMatrix2fv = (location, count, transpose, value) => { if (count <= 72) { // avoid allocation when uploading few enough uniforms @@ -14319,16 +15701,20 @@ var ASM_CONSTS = { } } else { - var view = HEAPF32.subarray((value)>>2, (value+count*16)>>2); + var view = HEAPF32.subarray((((value)>>2)), ((value+count*16)>>2)); } GLctx.uniformMatrix2fv(webglGetUniformLocation(location), !!transpose, view); - } - Module["_emscripten_glUniformMatrix2fv"] = _emscripten_glUniformMatrix2fv; - _emscripten_glUniformMatrix2fv.sig = 'viiii'; + }; + Module['_glUniformMatrix2fv'] = _glUniformMatrix2fv; + _glUniformMatrix2fv.sig = 'viiip'; + var _emscripten_glUniformMatrix2fv = _glUniformMatrix2fv; + Module['_emscripten_glUniformMatrix2fv'] = _emscripten_glUniformMatrix2fv; + _emscripten_glUniformMatrix2fv.sig = 'viiip'; - function _emscripten_glUniformMatrix3fv(location, count, transpose, value) { + /** @suppress {duplicate } */ + var _glUniformMatrix3fv = (location, count, transpose, value) => { if (count <= 32) { // avoid allocation when uploading few enough uniforms @@ -14346,23 +15732,27 @@ var ASM_CONSTS = { } } else { - var view = HEAPF32.subarray((value)>>2, (value+count*36)>>2); + var view = HEAPF32.subarray((((value)>>2)), ((value+count*36)>>2)); } GLctx.uniformMatrix3fv(webglGetUniformLocation(location), !!transpose, view); - } - Module["_emscripten_glUniformMatrix3fv"] = _emscripten_glUniformMatrix3fv; - _emscripten_glUniformMatrix3fv.sig = 'viiii'; + }; + Module['_glUniformMatrix3fv'] = _glUniformMatrix3fv; + _glUniformMatrix3fv.sig = 'viiip'; + var _emscripten_glUniformMatrix3fv = _glUniformMatrix3fv; + Module['_emscripten_glUniformMatrix3fv'] = _emscripten_glUniformMatrix3fv; + _emscripten_glUniformMatrix3fv.sig = 'viiip'; - function _emscripten_glUniformMatrix4fv(location, count, transpose, value) { + /** @suppress {duplicate } */ + var _glUniformMatrix4fv = (location, count, transpose, value) => { if (count <= 18) { // avoid allocation when uploading few enough uniforms var view = miniTempWebGLFloatBuffers[16*count-1]; // hoist the heap out of the loop for size and for pthreads+growth. var heap = HEAPF32; - value >>= 2; + value = ((value)>>2); for (var i = 0; i < 16 * count; i += 16) { var dst = value + i; view[i] = heap[dst]; @@ -14384,124 +15774,186 @@ var ASM_CONSTS = { } } else { - var view = HEAPF32.subarray((value)>>2, (value+count*64)>>2); + var view = HEAPF32.subarray((((value)>>2)), ((value+count*64)>>2)); } GLctx.uniformMatrix4fv(webglGetUniformLocation(location), !!transpose, view); - } - Module["_emscripten_glUniformMatrix4fv"] = _emscripten_glUniformMatrix4fv; - _emscripten_glUniformMatrix4fv.sig = 'viiii'; - - function _emscripten_glUseProgram(program) { + }; + Module['_glUniformMatrix4fv'] = _glUniformMatrix4fv; + _glUniformMatrix4fv.sig = 'viiip'; + var _emscripten_glUniformMatrix4fv = _glUniformMatrix4fv; + Module['_emscripten_glUniformMatrix4fv'] = _emscripten_glUniformMatrix4fv; + _emscripten_glUniformMatrix4fv.sig = 'viiip'; + + /** @suppress {duplicate } */ + var _glUseProgram = (program) => { program = GL.programs[program]; GLctx.useProgram(program); // Record the currently active program so that we can access the uniform // mapping table of that program. GLctx.currentProgram = program; - } - Module["_emscripten_glUseProgram"] = _emscripten_glUseProgram; + }; + Module['_glUseProgram'] = _glUseProgram; + _glUseProgram.sig = 'vi'; + var _emscripten_glUseProgram = _glUseProgram; + Module['_emscripten_glUseProgram'] = _emscripten_glUseProgram; _emscripten_glUseProgram.sig = 'vi'; - function _emscripten_glValidateProgram(program) { + /** @suppress {duplicate } */ + var _glValidateProgram = (program) => { GLctx.validateProgram(GL.programs[program]); - } - Module["_emscripten_glValidateProgram"] = _emscripten_glValidateProgram; + }; + Module['_glValidateProgram'] = _glValidateProgram; + _glValidateProgram.sig = 'vi'; + var _emscripten_glValidateProgram = _glValidateProgram; + Module['_emscripten_glValidateProgram'] = _emscripten_glValidateProgram; _emscripten_glValidateProgram.sig = 'vi'; - function _emscripten_glVertexAttrib1f(x0, x1) { GLctx['vertexAttrib1f'](x0, x1) } - Module["_emscripten_glVertexAttrib1f"] = _emscripten_glVertexAttrib1f; + /** @suppress {duplicate } */ + var _glVertexAttrib1f = (x0, x1) => GLctx.vertexAttrib1f(x0, x1); + Module['_glVertexAttrib1f'] = _glVertexAttrib1f; + _glVertexAttrib1f.sig = 'vif'; + var _emscripten_glVertexAttrib1f = _glVertexAttrib1f; + Module['_emscripten_glVertexAttrib1f'] = _emscripten_glVertexAttrib1f; _emscripten_glVertexAttrib1f.sig = 'vif'; - function _emscripten_glVertexAttrib1fv(index, v) { + /** @suppress {duplicate } */ + var _glVertexAttrib1fv = (index, v) => { GLctx.vertexAttrib1f(index, HEAPF32[v>>2]); - } - Module["_emscripten_glVertexAttrib1fv"] = _emscripten_glVertexAttrib1fv; - _emscripten_glVertexAttrib1fv.sig = 'vii'; - - function _emscripten_glVertexAttrib2f(x0, x1, x2) { GLctx['vertexAttrib2f'](x0, x1, x2) } - Module["_emscripten_glVertexAttrib2f"] = _emscripten_glVertexAttrib2f; + }; + Module['_glVertexAttrib1fv'] = _glVertexAttrib1fv; + _glVertexAttrib1fv.sig = 'vip'; + var _emscripten_glVertexAttrib1fv = _glVertexAttrib1fv; + Module['_emscripten_glVertexAttrib1fv'] = _emscripten_glVertexAttrib1fv; + _emscripten_glVertexAttrib1fv.sig = 'vip'; + + /** @suppress {duplicate } */ + var _glVertexAttrib2f = (x0, x1, x2) => GLctx.vertexAttrib2f(x0, x1, x2); + Module['_glVertexAttrib2f'] = _glVertexAttrib2f; + _glVertexAttrib2f.sig = 'viff'; + var _emscripten_glVertexAttrib2f = _glVertexAttrib2f; + Module['_emscripten_glVertexAttrib2f'] = _emscripten_glVertexAttrib2f; _emscripten_glVertexAttrib2f.sig = 'viff'; - function _emscripten_glVertexAttrib2fv(index, v) { + /** @suppress {duplicate } */ + var _glVertexAttrib2fv = (index, v) => { GLctx.vertexAttrib2f(index, HEAPF32[v>>2], HEAPF32[v+4>>2]); - } - Module["_emscripten_glVertexAttrib2fv"] = _emscripten_glVertexAttrib2fv; - _emscripten_glVertexAttrib2fv.sig = 'vii'; - - function _emscripten_glVertexAttrib3f(x0, x1, x2, x3) { GLctx['vertexAttrib3f'](x0, x1, x2, x3) } - Module["_emscripten_glVertexAttrib3f"] = _emscripten_glVertexAttrib3f; + }; + Module['_glVertexAttrib2fv'] = _glVertexAttrib2fv; + _glVertexAttrib2fv.sig = 'vip'; + var _emscripten_glVertexAttrib2fv = _glVertexAttrib2fv; + Module['_emscripten_glVertexAttrib2fv'] = _emscripten_glVertexAttrib2fv; + _emscripten_glVertexAttrib2fv.sig = 'vip'; + + /** @suppress {duplicate } */ + var _glVertexAttrib3f = (x0, x1, x2, x3) => GLctx.vertexAttrib3f(x0, x1, x2, x3); + Module['_glVertexAttrib3f'] = _glVertexAttrib3f; + _glVertexAttrib3f.sig = 'vifff'; + var _emscripten_glVertexAttrib3f = _glVertexAttrib3f; + Module['_emscripten_glVertexAttrib3f'] = _emscripten_glVertexAttrib3f; _emscripten_glVertexAttrib3f.sig = 'vifff'; - function _emscripten_glVertexAttrib3fv(index, v) { + /** @suppress {duplicate } */ + var _glVertexAttrib3fv = (index, v) => { GLctx.vertexAttrib3f(index, HEAPF32[v>>2], HEAPF32[v+4>>2], HEAPF32[v+8>>2]); - } - Module["_emscripten_glVertexAttrib3fv"] = _emscripten_glVertexAttrib3fv; - _emscripten_glVertexAttrib3fv.sig = 'vii'; - - function _emscripten_glVertexAttrib4f(x0, x1, x2, x3, x4) { GLctx['vertexAttrib4f'](x0, x1, x2, x3, x4) } - Module["_emscripten_glVertexAttrib4f"] = _emscripten_glVertexAttrib4f; + }; + Module['_glVertexAttrib3fv'] = _glVertexAttrib3fv; + _glVertexAttrib3fv.sig = 'vip'; + var _emscripten_glVertexAttrib3fv = _glVertexAttrib3fv; + Module['_emscripten_glVertexAttrib3fv'] = _emscripten_glVertexAttrib3fv; + _emscripten_glVertexAttrib3fv.sig = 'vip'; + + /** @suppress {duplicate } */ + var _glVertexAttrib4f = (x0, x1, x2, x3, x4) => GLctx.vertexAttrib4f(x0, x1, x2, x3, x4); + Module['_glVertexAttrib4f'] = _glVertexAttrib4f; + _glVertexAttrib4f.sig = 'viffff'; + var _emscripten_glVertexAttrib4f = _glVertexAttrib4f; + Module['_emscripten_glVertexAttrib4f'] = _emscripten_glVertexAttrib4f; _emscripten_glVertexAttrib4f.sig = 'viffff'; - function _emscripten_glVertexAttrib4fv(index, v) { + /** @suppress {duplicate } */ + var _glVertexAttrib4fv = (index, v) => { GLctx.vertexAttrib4f(index, HEAPF32[v>>2], HEAPF32[v+4>>2], HEAPF32[v+8>>2], HEAPF32[v+12>>2]); - } - Module["_emscripten_glVertexAttrib4fv"] = _emscripten_glVertexAttrib4fv; - _emscripten_glVertexAttrib4fv.sig = 'vii'; - - function _emscripten_glVertexAttribDivisorANGLE(index, divisor) { - GLctx['vertexAttribDivisor'](index, divisor); - } - Module["_emscripten_glVertexAttribDivisorANGLE"] = _emscripten_glVertexAttribDivisorANGLE; - _emscripten_glVertexAttribDivisorANGLE.sig = 'vii'; + }; + Module['_glVertexAttrib4fv'] = _glVertexAttrib4fv; + _glVertexAttrib4fv.sig = 'vip'; + var _emscripten_glVertexAttrib4fv = _glVertexAttrib4fv; + Module['_emscripten_glVertexAttrib4fv'] = _emscripten_glVertexAttrib4fv; + _emscripten_glVertexAttrib4fv.sig = 'vip'; - function _emscripten_glVertexAttribPointer(index, size, type, normalized, stride, ptr) { + + /** @suppress {duplicate } */ + var _glVertexAttribDivisor = (index, divisor) => { + GLctx.vertexAttribDivisor(index, divisor); + }; + Module['_glVertexAttribDivisor'] = _glVertexAttribDivisor; + _glVertexAttribDivisor.sig = 'vii'; + /** @suppress {duplicate } */ + var _glVertexAttribDivisorANGLE = _glVertexAttribDivisor; + Module['_glVertexAttribDivisorANGLE'] = _glVertexAttribDivisorANGLE; + var _emscripten_glVertexAttribDivisorANGLE = _glVertexAttribDivisorANGLE; + Module['_emscripten_glVertexAttribDivisorANGLE'] = _emscripten_glVertexAttribDivisorANGLE; + + /** @suppress {duplicate } */ + var _glVertexAttribPointer = (index, size, type, normalized, stride, ptr) => { GLctx.vertexAttribPointer(index, size, type, !!normalized, stride, ptr); - } - Module["_emscripten_glVertexAttribPointer"] = _emscripten_glVertexAttribPointer; - _emscripten_glVertexAttribPointer.sig = 'viiiiii'; - - function _emscripten_glViewport(x0, x1, x2, x3) { GLctx['viewport'](x0, x1, x2, x3) } - Module["_emscripten_glViewport"] = _emscripten_glViewport; + }; + Module['_glVertexAttribPointer'] = _glVertexAttribPointer; + _glVertexAttribPointer.sig = 'viiiiip'; + var _emscripten_glVertexAttribPointer = _glVertexAttribPointer; + Module['_emscripten_glVertexAttribPointer'] = _emscripten_glVertexAttribPointer; + _emscripten_glVertexAttribPointer.sig = 'viiiiip'; + + /** @suppress {duplicate } */ + var _glViewport = (x0, x1, x2, x3) => GLctx.viewport(x0, x1, x2, x3); + Module['_glViewport'] = _glViewport; + _glViewport.sig = 'viiii'; + var _emscripten_glViewport = _glViewport; + Module['_emscripten_glViewport'] = _emscripten_glViewport; _emscripten_glViewport.sig = 'viiii'; - function _emscripten_memcpy_big(dest, src, num) { - HEAPU8.copyWithin(dest, src, src + num); - } - Module["_emscripten_memcpy_big"] = _emscripten_memcpy_big; - _emscripten_memcpy_big.sig = 'vppp'; + var _emscripten_memcpy_js = (dest, src, num) => HEAPU8.copyWithin(dest, src, src + num); + Module['_emscripten_memcpy_js'] = _emscripten_memcpy_js; + _emscripten_memcpy_js.sig = 'vppp'; - /** @constructor */ - function HandleAllocator() { - this.allocated = []; - this.freelist = []; - this.get = function(id) { - assert(this.allocated[id] !== undefined); + var _emscripten_out = (str) => out(UTF8ToString(str)); + Module['_emscripten_out'] = _emscripten_out; + _emscripten_out.sig = 'vp'; + + class HandleAllocator { + constructor() { + // TODO(https://github.com/emscripten-core/emscripten/issues/21414): + // Use inline field declarations. + this.allocated = [undefined]; + this.freelist = []; + } + get(id) { + assert(this.allocated[id] !== undefined, `invalid handle: ${id}`); return this.allocated[id]; }; - this.allocate = function(handle) { - let id; - if (this.freelist.length > 0) { - id = this.freelist.pop(); - this.allocated[id] = handle; - } else { - id = this.allocated.length; - this.allocated.push(handle); - } + has(id) { + return this.allocated[id] !== undefined; + }; + allocate(handle) { + var id = this.freelist.pop() || this.allocated.length; + this.allocated[id] = handle; return id; }; - this.free = function(id) { + free(id) { assert(this.allocated[id] !== undefined); - delete this.allocated[id]; + // Set the slot to `undefined` rather than using `delete` here since + // apparently arrays with holes in them can be less efficient. + this.allocated[id] = undefined; this.freelist.push(id); }; } - Module["HandleAllocator"] = HandleAllocator; + Module['HandleAllocator'] = HandleAllocator; var promiseMap = new HandleAllocator();; - Module["promiseMap"] = promiseMap; - function makePromise() { + Module['promiseMap'] = promiseMap; + var makePromise = () => { var promiseInfo = {}; promiseInfo.promise = new Promise((resolve, reject) => { promiseInfo.reject = reject; @@ -14509,27 +15961,23 @@ var ASM_CONSTS = { }); promiseInfo.id = promiseMap.allocate(promiseInfo); return promiseInfo; - } - Module["makePromise"] = makePromise; - function _emscripten_promise_create() { - return makePromise().id; - } - Module["_emscripten_promise_create"] = _emscripten_promise_create; + }; + Module['makePromise'] = makePromise; + var _emscripten_promise_create = () => makePromise().id; + Module['_emscripten_promise_create'] = _emscripten_promise_create; _emscripten_promise_create.sig = 'p'; - function _emscripten_promise_destroy(id) { + var _emscripten_promise_destroy = (id) => { promiseMap.free(id); - } - Module["_emscripten_promise_destroy"] = _emscripten_promise_destroy; + }; + Module['_emscripten_promise_destroy'] = _emscripten_promise_destroy; _emscripten_promise_destroy.sig = 'vp'; - function getPromise(id) { - return promiseMap.get(id).promise; - } - Module["getPromise"] = getPromise; + var getPromise = (id) => promiseMap.get(id).promise; + Module['getPromise'] = getPromise; - function _emscripten_promise_resolve(id, result, value) { + var _emscripten_promise_resolve = (id, result, value) => { var info = promiseMap.get(id); switch (result) { case 0: @@ -14547,29 +15995,36 @@ var ASM_CONSTS = { return; } abort("unexpected promise callback result " + result); - } - Module["_emscripten_promise_resolve"] = _emscripten_promise_resolve; + }; + Module['_emscripten_promise_resolve'] = _emscripten_promise_resolve; _emscripten_promise_resolve.sig = 'vpip'; - function abortOnCannotGrowMemory(requestedSize) { - abort('Cannot enlarge memory arrays to size ' + requestedSize + ' bytes (OOM). Either (1) compile with -sINITIAL_MEMORY=X with X higher than the current value ' + HEAP8.length + ', (2) compile with -sALLOW_MEMORY_GROWTH which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -sABORTING_MALLOC=0'); - } - Module["abortOnCannotGrowMemory"] = abortOnCannotGrowMemory; - function _emscripten_resize_heap(requestedSize) { + var abortOnCannotGrowMemory = (requestedSize) => { + abort(`Cannot enlarge memory arrays to size ${requestedSize} bytes (OOM). Either (1) compile with -sINITIAL_MEMORY=X with X higher than the current value ${HEAP8.length}, (2) compile with -sALLOW_MEMORY_GROWTH which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -sABORTING_MALLOC=0`); + }; + Module['abortOnCannotGrowMemory'] = abortOnCannotGrowMemory; + var _emscripten_resize_heap = (requestedSize) => { var oldSize = HEAPU8.length; - requestedSize = requestedSize >>> 0; + // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned. + requestedSize >>>= 0; abortOnCannotGrowMemory(requestedSize); - } - Module["_emscripten_resize_heap"] = _emscripten_resize_heap; + }; + Module['_emscripten_resize_heap'] = _emscripten_resize_heap; _emscripten_resize_heap.sig = 'ip'; + var _emscripten_wget_data = (url, pbuffer, pnum, perror) => { + throw 'Please compile your program with async support in order to use asynchronous operations like emscripten_wget_data'; + }; + Module['_emscripten_wget_data'] = _emscripten_wget_data; + _emscripten_wget_data.sig = 'vpppp'; + - function getExecutableName() { + var getExecutableName = () => { return thisProgram || './this.program'; - } - Module["getExecutableName"] = getExecutableName; - function getEnvStrings() { + }; + Module['getExecutableName'] = getExecutableName; + var getEnvStrings = () => { if (!getEnvStrings.strings) { // Default values. // Browser language detection #8751 @@ -14593,50 +16048,45 @@ var ASM_CONSTS = { } var strings = []; for (var x in env) { - strings.push(x + '=' + env[x]); + strings.push(`${x}=${env[x]}`); } getEnvStrings.strings = strings; } return getEnvStrings.strings; - } - Module["getEnvStrings"] = getEnvStrings; + }; + Module['getEnvStrings'] = getEnvStrings; - /** @param {boolean=} dontAddNull */ - function writeAsciiToMemory(str, buffer, dontAddNull) { + var stringToAscii = (str, buffer) => { for (var i = 0; i < str.length; ++i) { assert(str.charCodeAt(i) === (str.charCodeAt(i) & 0xff)); - HEAP8[((buffer++)>>0)] = str.charCodeAt(i); + HEAP8[buffer++] = str.charCodeAt(i); } - // Null-terminate the pointer to the HEAP. - if (!dontAddNull) HEAP8[((buffer)>>0)] = 0; - } - Module["writeAsciiToMemory"] = writeAsciiToMemory; - - function _environ_get(__environ, environ_buf) { + // Null-terminate the string + HEAP8[buffer] = 0; + }; + Module['stringToAscii'] = stringToAscii; + var _environ_get = (__environ, environ_buf) => { var bufSize = 0; - getEnvStrings().forEach(function(string, i) { + getEnvStrings().forEach((string, i) => { var ptr = environ_buf + bufSize; HEAPU32[(((__environ)+(i*4))>>2)] = ptr; - writeAsciiToMemory(string, ptr); + stringToAscii(string, ptr); bufSize += string.length + 1; }); return 0; - } - Module["_environ_get"] = _environ_get; + }; + Module['_environ_get'] = _environ_get; _environ_get.sig = 'ipp'; - - function _environ_sizes_get(penviron_count, penviron_buf_size) { + var _environ_sizes_get = (penviron_count, penviron_buf_size) => { var strings = getEnvStrings(); HEAPU32[((penviron_count)>>2)] = strings.length; var bufSize = 0; - strings.forEach(function(string) { - bufSize += string.length + 1; - }); + strings.forEach((string) => bufSize += string.length + 1); HEAPU32[((penviron_buf_size)>>2)] = bufSize; return 0; - } - Module["_environ_sizes_get"] = _environ_sizes_get; + }; + Module['_environ_sizes_get'] = _environ_sizes_get; _environ_sizes_get.sig = 'ipp'; @@ -14651,40 +16101,45 @@ var ASM_CONSTS = { return e.errno; } } - Module["_fd_close"] = _fd_close; + Module['_fd_close'] = _fd_close; _fd_close.sig = 'ii'; function _fd_fdstat_get(fd, pbuf) { try { - var stream = SYSCALLS.getStreamFromFD(fd); - // All character devices are terminals (other things a Linux system would - // assume is a character device, like the mouse, we have special APIs for). - var type = stream.tty ? 2 : - FS.isDir(stream.mode) ? 3 : - FS.isLink(stream.mode) ? 7 : - 4; - HEAP8[((pbuf)>>0)] = type; - // TODO HEAP16[(((pbuf)+(2))>>1)] = ?; - // TODO (tempI64 = [?>>>0,(tempDouble=?,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((pbuf)+(8))>>2)] = tempI64[0],HEAP32[(((pbuf)+(12))>>2)] = tempI64[1]); - // TODO (tempI64 = [?>>>0,(tempDouble=?,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((pbuf)+(16))>>2)] = tempI64[0],HEAP32[(((pbuf)+(20))>>2)] = tempI64[1]); + var rightsBase = 0; + var rightsInheriting = 0; + var flags = 0; + { + var stream = SYSCALLS.getStreamFromFD(fd); + // All character devices are terminals (other things a Linux system would + // assume is a character device, like the mouse, we have special APIs for). + var type = stream.tty ? 2 : + FS.isDir(stream.mode) ? 3 : + FS.isLink(stream.mode) ? 7 : + 4; + } + HEAP8[pbuf] = type; + HEAP16[(((pbuf)+(2))>>1)] = flags; + (tempI64 = [rightsBase>>>0,(tempDouble = rightsBase,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? (+(Math.floor((tempDouble)/4294967296.0)))>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)], HEAP32[(((pbuf)+(8))>>2)] = tempI64[0],HEAP32[(((pbuf)+(12))>>2)] = tempI64[1]); + (tempI64 = [rightsInheriting>>>0,(tempDouble = rightsInheriting,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? (+(Math.floor((tempDouble)/4294967296.0)))>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)], HEAP32[(((pbuf)+(16))>>2)] = tempI64[0],HEAP32[(((pbuf)+(20))>>2)] = tempI64[1]); return 0; } catch (e) { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; return e.errno; } } - Module["_fd_fdstat_get"] = _fd_fdstat_get; + Module['_fd_fdstat_get'] = _fd_fdstat_get; _fd_fdstat_get.sig = 'iip'; /** @param {number=} offset */ - function doReadv(stream, iov, iovcnt, offset) { + var doReadv = (stream, iov, iovcnt, offset) => { var ret = 0; for (var i = 0; i < iovcnt; i++) { var ptr = HEAPU32[((iov)>>2)]; var len = HEAPU32[(((iov)+(4))>>2)]; iov += 8; - var curr = FS.read(stream, HEAP8,ptr, len, offset); + var curr = FS.read(stream, HEAP8, ptr, len, offset); if (curr < 0) return -1; ret += curr; if (curr < len) break; // nothing more to read @@ -14693,17 +16148,17 @@ var ASM_CONSTS = { } } return ret; - } - Module["doReadv"] = doReadv; - - + }; + Module['doReadv'] = doReadv; + function _fd_pread(fd,iov,iovcnt,offset_low, offset_high,pnum) { + var offset = convertI32PairToI53Checked(offset_low, offset_high); - function _fd_pread(fd, iov, iovcnt, offset_low, offset_high, pnum) { + try { - var offset = convertI32PairToI53Checked(offset_low, offset_high); if (isNaN(offset)) return 61; + if (isNaN(offset)) return 61; var stream = SYSCALLS.getStreamFromFD(fd) var num = doReadv(stream, iov, iovcnt, offset); HEAPU32[((pnum)>>2)] = num; @@ -14712,18 +16167,19 @@ var ASM_CONSTS = { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; return e.errno; } + ; } - Module["_fd_pread"] = _fd_pread; - _fd_pread.sig = 'iippjp'; + Module['_fd_pread'] = _fd_pread; + _fd_pread.sig = 'iippiip'; /** @param {number=} offset */ - function doWritev(stream, iov, iovcnt, offset) { + var doWritev = (stream, iov, iovcnt, offset) => { var ret = 0; for (var i = 0; i < iovcnt; i++) { var ptr = HEAPU32[((iov)>>2)]; var len = HEAPU32[(((iov)+(4))>>2)]; iov += 8; - var curr = FS.write(stream, HEAP8,ptr, len, offset); + var curr = FS.write(stream, HEAP8, ptr, len, offset); if (curr < 0) return -1; ret += curr; if (typeof offset !== 'undefined') { @@ -14731,17 +16187,17 @@ var ASM_CONSTS = { } } return ret; - } - Module["doWritev"] = doWritev; - - + }; + Module['doWritev'] = doWritev; + function _fd_pwrite(fd,iov,iovcnt,offset_low, offset_high,pnum) { + var offset = convertI32PairToI53Checked(offset_low, offset_high); - function _fd_pwrite(fd, iov, iovcnt, offset_low, offset_high, pnum) { + try { - var offset = convertI32PairToI53Checked(offset_low, offset_high); if (isNaN(offset)) return 61; + if (isNaN(offset)) return 61; var stream = SYSCALLS.getStreamFromFD(fd) var num = doWritev(stream, iov, iovcnt, offset); HEAPU32[((pnum)>>2)] = num; @@ -14750,9 +16206,10 @@ var ASM_CONSTS = { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; return e.errno; } + ; } - Module["_fd_pwrite"] = _fd_pwrite; - _fd_pwrite.sig = 'iippjp'; + Module['_fd_pwrite'] = _fd_pwrite; + _fd_pwrite.sig = 'iippiip'; function _fd_read(fd, iov, iovcnt, pnum) { @@ -14767,35 +16224,36 @@ var ASM_CONSTS = { return e.errno; } } - Module["_fd_read"] = _fd_read; + Module['_fd_read'] = _fd_read; _fd_read.sig = 'iippp'; + function _fd_seek(fd,offset_low, offset_high,whence,newOffset) { + var offset = convertI32PairToI53Checked(offset_low, offset_high); - - - function _fd_seek(fd, offset_low, offset_high, whence, newOffset) { + try { - var offset = convertI32PairToI53Checked(offset_low, offset_high); if (isNaN(offset)) return 61; + if (isNaN(offset)) return 61; var stream = SYSCALLS.getStreamFromFD(fd); FS.llseek(stream, offset, whence); - (tempI64 = [stream.position>>>0,(tempDouble=stream.position,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[((newOffset)>>2)] = tempI64[0],HEAP32[(((newOffset)+(4))>>2)] = tempI64[1]); + (tempI64 = [stream.position>>>0,(tempDouble = stream.position,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? (+(Math.floor((tempDouble)/4294967296.0)))>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)], HEAP32[((newOffset)>>2)] = tempI64[0],HEAP32[(((newOffset)+(4))>>2)] = tempI64[1]); if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null; // reset readdir state return 0; } catch (e) { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; return e.errno; } + ; } - Module["_fd_seek"] = _fd_seek; - _fd_seek.sig = 'iijip'; + Module['_fd_seek'] = _fd_seek; + _fd_seek.sig = 'iiiiip'; function _fd_sync(fd) { try { var stream = SYSCALLS.getStreamFromFD(fd); - if (stream.stream_ops && stream.stream_ops.fsync) { + if (stream.stream_ops?.fsync) { return stream.stream_ops.fsync(stream); } return 0; // we can't do anything synchronously; the in-memory FS is already synced to @@ -14804,7 +16262,7 @@ var ASM_CONSTS = { return e.errno; } } - Module["_fd_sync"] = _fd_sync; + Module['_fd_sync'] = _fd_sync; _fd_sync.sig = 'ii'; @@ -14820,24 +16278,20 @@ var ASM_CONSTS = { return e.errno; } } - Module["_fd_write"] = _fd_write; + Module['_fd_write'] = _fd_write; _fd_write.sig = 'iippp'; - function _getentropy(buffer, size) { - if (!_getentropy.randomDevice) { - _getentropy.randomDevice = getRandomDevice(); - } - for (var i = 0; i < size; i++) { - HEAP8[(((buffer)+(i))>>0)] = _getentropy.randomDevice(); - } + var _getentropy = (buffer, size) => { + randomFill(HEAPU8.subarray(buffer, buffer + size)); return 0; - } - Module["_getentropy"] = _getentropy; + }; + Module['_getentropy'] = _getentropy; _getentropy.sig = 'ipp'; - function _getnameinfo(sa, salen, node, nodelen, serv, servlen, flags) { + + var _getnameinfo = (sa, salen, node, nodelen, serv, servlen, flags) => { var info = readSockaddr(sa, salen); if (info.errno) { return -6; @@ -14878,33 +16332,33 @@ var ASM_CONSTS = { } return 0; - } - Module["_getnameinfo"] = _getnameinfo; + }; + Module['_getnameinfo'] = _getnameinfo; _getnameinfo.sig = 'ipipipii'; - function __arraySum(array, index) { + var arraySum = (array, index) => { var sum = 0; for (var i = 0; i <= index; sum += array[i++]) { // no-op } return sum; - } - Module["__arraySum"] = __arraySum; + }; + Module['arraySum'] = arraySum; - var __MONTH_DAYS_LEAP = [31,29,31,30,31,30,31,31,30,31,30,31]; - Module["__MONTH_DAYS_LEAP"] = __MONTH_DAYS_LEAP; + var MONTH_DAYS_LEAP = [31,29,31,30,31,30,31,31,30,31,30,31]; + Module['MONTH_DAYS_LEAP'] = MONTH_DAYS_LEAP; - var __MONTH_DAYS_REGULAR = [31,28,31,30,31,30,31,31,30,31,30,31]; - Module["__MONTH_DAYS_REGULAR"] = __MONTH_DAYS_REGULAR; - function __addDays(date, days) { + var MONTH_DAYS_REGULAR = [31,28,31,30,31,30,31,31,30,31,30,31]; + Module['MONTH_DAYS_REGULAR'] = MONTH_DAYS_REGULAR; + var addDays = (date, days) => { var newDate = new Date(date.getTime()); while (days > 0) { - var leap = __isLeapYear(newDate.getFullYear()); + var leap = isLeapYear(newDate.getFullYear()); var currentMonth = newDate.getMonth(); - var daysInCurrentMonth = (leap ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR)[currentMonth]; + var daysInCurrentMonth = (leap ? MONTH_DAYS_LEAP : MONTH_DAYS_REGULAR)[currentMonth]; if (days > daysInCurrentMonth-newDate.getDate()) { // we spill over to next month @@ -14924,22 +16378,23 @@ var ASM_CONSTS = { } return newDate; - } - Module["__addDays"] = __addDays; + }; + Module['addDays'] = addDays; - function writeArrayToMemory(array, buffer) { + var writeArrayToMemory = (array, buffer) => { assert(array.length >= 0, 'writeArrayToMemory array must have a length (should be an array or typed array)') HEAP8.set(array, buffer); - } - Module["writeArrayToMemory"] = writeArrayToMemory; - function _strftime(s, maxsize, format, tm) { + }; + Module['writeArrayToMemory'] = writeArrayToMemory; + + var _strftime = (s, maxsize, format, tm) => { // size_t strftime(char *restrict s, size_t maxsize, const char *restrict format, const struct tm *restrict timeptr); // http://pubs.opengroup.org/onlinepubs/009695399/functions/strftime.html - var tm_zone = HEAP32[(((tm)+(40))>>2)]; + var tm_zone = HEAPU32[(((tm)+(40))>>2)]; var date = { tm_sec: HEAP32[((tm)>>2)], @@ -14954,6 +16409,7 @@ var ASM_CONSTS = { tm_gmtoff: HEAP32[(((tm)+(36))>>2)], tm_zone: tm_zone ? UTF8ToString(tm_zone) : '' }; + var pattern = UTF8ToString(format); @@ -15042,7 +16498,7 @@ var ASM_CONSTS = { } function getWeekBasedYear(date) { - var thisDate = __addDays(new Date(date.tm_year+1900, 0, 1), date.tm_yday); + var thisDate = addDays(new Date(date.tm_year+1900, 0, 1), date.tm_yday); var janFourthThisYear = new Date(thisDate.getFullYear(), 0, 4); var janFourthNextYear = new Date(thisDate.getFullYear()+1, 0, 4); @@ -15061,29 +16517,17 @@ var ASM_CONSTS = { } var EXPANSION_RULES_2 = { - '%a': function(date) { - return WEEKDAYS[date.tm_wday].substring(0,3); - }, - '%A': function(date) { - return WEEKDAYS[date.tm_wday]; - }, - '%b': function(date) { - return MONTHS[date.tm_mon].substring(0,3); - }, - '%B': function(date) { - return MONTHS[date.tm_mon]; - }, - '%C': function(date) { + '%a': (date) => WEEKDAYS[date.tm_wday].substring(0,3) , + '%A': (date) => WEEKDAYS[date.tm_wday], + '%b': (date) => MONTHS[date.tm_mon].substring(0,3), + '%B': (date) => MONTHS[date.tm_mon], + '%C': (date) => { var year = date.tm_year+1900; return leadingNulls((year/100)|0,2); }, - '%d': function(date) { - return leadingNulls(date.tm_mday, 2); - }, - '%e': function(date) { - return leadingSomething(date.tm_mday, 2, ' '); - }, - '%g': function(date) { + '%d': (date) => leadingNulls(date.tm_mday, 2), + '%e': (date) => leadingSomething(date.tm_mday, 2, ' '), + '%g': (date) => { // %g, %G, and %V give values according to the ISO 8601:2000 standard week-based year. // In this system, weeks begin on a Monday and week 1 of the year is the week that includes // January 4th, which is also the week that includes the first Thursday of the year, and @@ -15096,51 +16540,35 @@ var ASM_CONSTS = { return getWeekBasedYear(date).toString().substring(2); }, - '%G': function(date) { - return getWeekBasedYear(date); - }, - '%H': function(date) { - return leadingNulls(date.tm_hour, 2); - }, - '%I': function(date) { + '%G': getWeekBasedYear, + '%H': (date) => leadingNulls(date.tm_hour, 2), + '%I': (date) => { var twelveHour = date.tm_hour; if (twelveHour == 0) twelveHour = 12; else if (twelveHour > 12) twelveHour -= 12; return leadingNulls(twelveHour, 2); }, - '%j': function(date) { + '%j': (date) => { // Day of the year (001-366) - return leadingNulls(date.tm_mday+__arraySum(__isLeapYear(date.tm_year+1900) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, date.tm_mon-1), 3); - }, - '%m': function(date) { - return leadingNulls(date.tm_mon+1, 2); - }, - '%M': function(date) { - return leadingNulls(date.tm_min, 2); - }, - '%n': function() { - return '\n'; + return leadingNulls(date.tm_mday + arraySum(isLeapYear(date.tm_year+1900) ? MONTH_DAYS_LEAP : MONTH_DAYS_REGULAR, date.tm_mon-1), 3); }, - '%p': function(date) { + '%m': (date) => leadingNulls(date.tm_mon+1, 2), + '%M': (date) => leadingNulls(date.tm_min, 2), + '%n': () => '\n', + '%p': (date) => { if (date.tm_hour >= 0 && date.tm_hour < 12) { return 'AM'; } return 'PM'; }, - '%S': function(date) { - return leadingNulls(date.tm_sec, 2); - }, - '%t': function() { - return '\t'; - }, - '%u': function(date) { - return date.tm_wday || 7; - }, - '%U': function(date) { + '%S': (date) => leadingNulls(date.tm_sec, 2), + '%t': () => '\t', + '%u': (date) => date.tm_wday || 7, + '%U': (date) => { var days = date.tm_yday + 7 - date.tm_wday; return leadingNulls(Math.floor(days / 7), 2); }, - '%V': function(date) { + '%V': (date) => { // Replaced by the week number of the year (Monday as the first day of the week) // as a decimal number [01,53]. If the week containing 1 January has four // or more days in the new year, then it is considered week 1. @@ -15157,34 +16585,30 @@ var ASM_CONSTS = { // If 31 December of prev year a Thursday, or Friday of a // leap year, then the prev year has 53 weeks. var dec31 = (date.tm_wday + 7 - date.tm_yday - 1) % 7; - if (dec31 == 4 || (dec31 == 5 && __isLeapYear(date.tm_year%400-1))) { + if (dec31 == 4 || (dec31 == 5 && isLeapYear(date.tm_year%400-1))) { val++; } } else if (val == 53) { // If 1 January is not a Thursday, and not a Wednesday of a // leap year, then this year has only 52 weeks. var jan1 = (date.tm_wday + 371 - date.tm_yday) % 7; - if (jan1 != 4 && (jan1 != 3 || !__isLeapYear(date.tm_year))) + if (jan1 != 4 && (jan1 != 3 || !isLeapYear(date.tm_year))) val = 1; } return leadingNulls(val, 2); }, - '%w': function(date) { - return date.tm_wday; - }, - '%W': function(date) { + '%w': (date) => date.tm_wday, + '%W': (date) => { var days = date.tm_yday + 7 - ((date.tm_wday + 6) % 7); return leadingNulls(Math.floor(days / 7), 2); }, - '%y': function(date) { + '%y': (date) => { // Replaced by the last two digits of the year as a decimal number [00,99]. [ tm_year] return (date.tm_year+1900).toString().substring(2); }, - '%Y': function(date) { - // Replaced by the year as a decimal number (for example, 1997). [ tm_year] - return date.tm_year+1900; - }, - '%z': function(date) { + // Replaced by the year as a decimal number (for example, 1997). [ tm_year] + '%Y': (date) => date.tm_year+1900, + '%z': (date) => { // Replaced by the offset from UTC in the ISO 8601:2000 standard format ( +hhmm or -hhmm ). // For example, "-0430" means 4 hours 30 minutes behind UTC (west of Greenwich). var off = date.tm_gmtoff; @@ -15194,12 +16618,8 @@ var ASM_CONSTS = { off = (off / 60)*100 + (off % 60); return (ahead ? '+' : '-') + String("0000" + off).slice(-4); }, - '%Z': function(date) { - return date.tm_zone; - }, - '%%': function() { - return '%'; - } + '%Z': (date) => date.tm_zone, + '%%': () => '%' }; // Replace %% with a pair of NULLs (which cannot occur in a C string), then @@ -15219,20 +16639,79 @@ var ASM_CONSTS = { writeArrayToMemory(bytes, s); return bytes.length-1; - } - Module["_strftime"] = _strftime; + }; + Module['_strftime'] = _strftime; _strftime.sig = 'ppppp'; - function _strftime_l(s, maxsize, format, tm, loc) { + var _strftime_l = (s, maxsize, format, tm, loc) => { return _strftime(s, maxsize, format, tm); // no locale support yet - } - Module["_strftime_l"] = _strftime_l; + }; + Module['_strftime_l'] = _strftime_l; _strftime_l.sig = 'pppppp'; + var writeI53ToI64Clamped = (ptr, num) => { + if (num > 0x7FFFFFFFFFFFFFFF) { + HEAPU32[((ptr)>>2)] = 4294967295; + HEAPU32[(((ptr)+(4))>>2)] = 2147483647; + } else if (num < -0x8000000000000000) { + HEAPU32[((ptr)>>2)] = 0; + HEAPU32[(((ptr)+(4))>>2)] = 2147483648; + } else { + writeI53ToI64(ptr, num); + } + }; + Module['writeI53ToI64Clamped'] = writeI53ToI64Clamped; + + var writeI53ToI64Signaling = (ptr, num) => { + if (num > 0x7FFFFFFFFFFFFFFF || num < -0x8000000000000000) { + throw `RangeError in writeI53ToI64Signaling(): input value ${num} is out of range of int64`; + } + writeI53ToI64(ptr, num); + }; + Module['writeI53ToI64Signaling'] = writeI53ToI64Signaling; + + var writeI53ToU64Clamped = (ptr, num) => { + if (num > 0xFFFFFFFFFFFFFFFF) { + HEAPU32[((ptr)>>2)] = 4294967295; + HEAPU32[(((ptr)+(4))>>2)] = 4294967295; + } else if (num < 0) { + HEAPU32[((ptr)>>2)] = 0; + HEAPU32[(((ptr)+(4))>>2)] = 0; + } else { + writeI53ToI64(ptr, num); + } + }; + Module['writeI53ToU64Clamped'] = writeI53ToU64Clamped; + + var writeI53ToU64Signaling = (ptr, num) => { + if (num < 0 || num > 0xFFFFFFFFFFFFFFFF) { + throw `RangeError in writeI53ToU64Signaling(): input value ${num} is out of range of uint64`; + } + writeI53ToI64(ptr, num); + }; + Module['writeI53ToU64Signaling'] = writeI53ToU64Signaling; + + + + var convertI32PairToI53 = (lo, hi) => { + // This function should not be getting called with too large unsigned numbers + // in high part (if hi >= 0x7FFFFFFFF, one should have been calling + // convertU32PairToI53()) + assert(hi === (hi|0)); + return (lo >>> 0) + hi * 4294967296; + }; + Module['convertI32PairToI53'] = convertI32PairToI53; + + + var convertU32PairToI53 = (lo, hi) => { + return (lo >>> 0) + (hi >>> 0) * 4294967296; + }; + Module['convertU32PairToI53'] = convertU32PairToI53; + @@ -15240,85 +16719,32 @@ var ASM_CONSTS = { - function emscripten_realloc_buffer(size) { + var growMemory = (size) => { var b = wasmMemory.buffer; + var pages = (size - b.byteLength + 65535) / 65536; try { // round size grow request up to wasm page size (fixed 64KB per spec) - wasmMemory.grow((size - b.byteLength + 65535) >>> 16); // .grow() takes a delta compared to the previous size + wasmMemory.grow(pages); // .grow() takes a delta compared to the previous size updateMemoryViews(); return 1 /*success*/; } catch(e) { - err('emscripten_realloc_buffer: Attempted to grow heap from ' + b.byteLength + ' bytes to ' + size + ' bytes, but got error: ' + e); + err(`growMemory: Attempted to grow heap from ${b.byteLength} bytes to ${size} bytes, but got error: ${e}`); } // implicit 0 return to save code size (caller will cast "undefined" into 0 // anyhow) - } - Module["emscripten_realloc_buffer"] = emscripten_realloc_buffer; + }; + Module['growMemory'] = growMemory; - function _emscripten_notify_memory_growth(memoryIndex) { + var _emscripten_notify_memory_growth = (memoryIndex) => { assert(memoryIndex == 0); updateMemoryViews(); - } - Module["_emscripten_notify_memory_growth"] = _emscripten_notify_memory_growth; - - function _system(command) { - if (ENVIRONMENT_IS_NODE) { - if (!command) return 1; // shell is available - - var cmdstr = UTF8ToString(command); - if (!cmdstr.length) return 0; // this is what glibc seems to do (shell works test?) - - var cp = require('child_process'); - var ret = cp.spawnSync(cmdstr, [], {shell:true, stdio:'inherit'}); - - var _W_EXITCODE = (ret, sig) => ((ret) << 8 | (sig)); - - // this really only can happen if process is killed by signal - if (ret.status === null) { - // sadly node doesn't expose such function - var signalToNumber = (sig) => { - // implement only the most common ones, and fallback to SIGINT - switch (sig) { - case 'SIGHUP': return 1; - case 'SIGINT': return 2; - case 'SIGQUIT': return 3; - case 'SIGFPE': return 8; - case 'SIGKILL': return 9; - case 'SIGALRM': return 14; - case 'SIGTERM': return 15; - } - return 2; // SIGINT - } - return _W_EXITCODE(0, signalToNumber(ret.signal)); - } - - return _W_EXITCODE(ret.status, 0); - } - // int system(const char *command); - // http://pubs.opengroup.org/onlinepubs/000095399/functions/system.html - // Can't call external programs. - if (!command) return 0; // no shell available - setErrNo(52); - return -1; - } - Module["_system"] = _system; - _system.sig = 'ip'; + }; + Module['_emscripten_notify_memory_growth'] = _emscripten_notify_memory_growth; + _emscripten_notify_memory_growth.sig = 'vp'; - function _getloadavg(loadavg, nelem) { - // int getloadavg(double loadavg[], int nelem); - // http://linux.die.net/man/3/getloadavg - var limit = Math.min(nelem, 3); - var doubleSize = 8; - for (var i = 0; i < limit; i++) { - HEAPF64[(((loadavg)+(i * doubleSize))>>3)] = 0.1; - } - return limit; - } - Module["_getloadavg"] = _getloadavg; - _getloadavg.sig = 'ipi'; @@ -15326,7 +16752,7 @@ var ASM_CONSTS = { - function ___asctime_r(tmPtr, buf) { + var ___asctime_r = (tmPtr, buf) => { var date = { tm_sec: HEAP32[((tmPtr)>>2)], tm_min: HEAP32[(((tmPtr)+(4))>>2)], @@ -15352,8 +16778,8 @@ var ASM_CONSTS = { // Our undefined behavior is to truncate the write to at most 26 bytes, including null terminator. stringToUTF8(s, buf, 26); return buf; - } - Module["___asctime_r"] = ___asctime_r; + }; + Module['___asctime_r'] = ___asctime_r; ___asctime_r.sig = 'ppp'; @@ -15374,7 +16800,8 @@ var ASM_CONSTS = { - function _strptime(buf, format, tm) { + + var _strptime = (buf, format, tm) => { // char *strptime(const char *restrict buf, const char *restrict format, struct tm *restrict tm); // http://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html var pattern = UTF8ToString(format); @@ -15388,64 +16815,64 @@ var ASM_CONSTS = { // reduce number of matchers var EQUIVALENT_MATCHERS = { - '%A': '%a', - '%B': '%b', - '%c': '%a %b %d %H:%M:%S %Y', - '%D': '%m\\/%d\\/%y', - '%e': '%d', - '%F': '%Y-%m-%d', - '%h': '%b', - '%R': '%H\\:%M', - '%r': '%I\\:%M\\:%S\\s%p', - '%T': '%H\\:%M\\:%S', - '%x': '%m\\/%d\\/(?:%y|%Y)', - '%X': '%H\\:%M\\:%S' + 'A': '%a', + 'B': '%b', + 'c': '%a %b %d %H:%M:%S %Y', + 'D': '%m\\/%d\\/%y', + 'e': '%d', + 'F': '%Y-%m-%d', + 'h': '%b', + 'R': '%H\\:%M', + 'r': '%I\\:%M\\:%S\\s%p', + 'T': '%H\\:%M\\:%S', + 'x': '%m\\/%d\\/(?:%y|%Y)', + 'X': '%H\\:%M\\:%S' }; - for (var matcher in EQUIVALENT_MATCHERS) { - pattern = pattern.replace(matcher, EQUIVALENT_MATCHERS[matcher]); - } - // TODO: take care of locale var DATE_PATTERNS = { - /* weeday name */ '%a': '(?:Sun(?:day)?)|(?:Mon(?:day)?)|(?:Tue(?:sday)?)|(?:Wed(?:nesday)?)|(?:Thu(?:rsday)?)|(?:Fri(?:day)?)|(?:Sat(?:urday)?)', - /* month name */ '%b': '(?:Jan(?:uary)?)|(?:Feb(?:ruary)?)|(?:Mar(?:ch)?)|(?:Apr(?:il)?)|May|(?:Jun(?:e)?)|(?:Jul(?:y)?)|(?:Aug(?:ust)?)|(?:Sep(?:tember)?)|(?:Oct(?:ober)?)|(?:Nov(?:ember)?)|(?:Dec(?:ember)?)', - /* century */ '%C': '\\d\\d', - /* day of month */ '%d': '0[1-9]|[1-9](?!\\d)|1\\d|2\\d|30|31', - /* hour (24hr) */ '%H': '\\d(?!\\d)|[0,1]\\d|20|21|22|23', - /* hour (12hr) */ '%I': '\\d(?!\\d)|0\\d|10|11|12', - /* day of year */ '%j': '00[1-9]|0?[1-9](?!\\d)|0?[1-9]\\d(?!\\d)|[1,2]\\d\\d|3[0-6]\\d', - /* month */ '%m': '0[1-9]|[1-9](?!\\d)|10|11|12', - /* minutes */ '%M': '0\\d|\\d(?!\\d)|[1-5]\\d', - /* whitespace */ '%n': '\\s', - /* AM/PM */ '%p': 'AM|am|PM|pm|A\\.M\\.|a\\.m\\.|P\\.M\\.|p\\.m\\.', - /* seconds */ '%S': '0\\d|\\d(?!\\d)|[1-5]\\d|60', - /* week number */ '%U': '0\\d|\\d(?!\\d)|[1-4]\\d|50|51|52|53', - /* week number */ '%W': '0\\d|\\d(?!\\d)|[1-4]\\d|50|51|52|53', - /* weekday number */ '%w': '[0-6]', - /* 2-digit year */ '%y': '\\d\\d', - /* 4-digit year */ '%Y': '\\d\\d\\d\\d', - /* % */ '%%': '%', - /* whitespace */ '%t': '\\s', + /* weekday name */ 'a': '(?:Sun(?:day)?)|(?:Mon(?:day)?)|(?:Tue(?:sday)?)|(?:Wed(?:nesday)?)|(?:Thu(?:rsday)?)|(?:Fri(?:day)?)|(?:Sat(?:urday)?)', + /* month name */ 'b': '(?:Jan(?:uary)?)|(?:Feb(?:ruary)?)|(?:Mar(?:ch)?)|(?:Apr(?:il)?)|May|(?:Jun(?:e)?)|(?:Jul(?:y)?)|(?:Aug(?:ust)?)|(?:Sep(?:tember)?)|(?:Oct(?:ober)?)|(?:Nov(?:ember)?)|(?:Dec(?:ember)?)', + /* century */ 'C': '\\d\\d', + /* day of month */ 'd': '0[1-9]|[1-9](?!\\d)|1\\d|2\\d|30|31', + /* hour (24hr) */ 'H': '\\d(?!\\d)|[0,1]\\d|20|21|22|23', + /* hour (12hr) */ 'I': '\\d(?!\\d)|0\\d|10|11|12', + /* day of year */ 'j': '00[1-9]|0?[1-9](?!\\d)|0?[1-9]\\d(?!\\d)|[1,2]\\d\\d|3[0-6]\\d', + /* month */ 'm': '0[1-9]|[1-9](?!\\d)|10|11|12', + /* minutes */ 'M': '0\\d|\\d(?!\\d)|[1-5]\\d', + /* whitespace */ 'n': ' ', + /* AM/PM */ 'p': 'AM|am|PM|pm|A\\.M\\.|a\\.m\\.|P\\.M\\.|p\\.m\\.', + /* seconds */ 'S': '0\\d|\\d(?!\\d)|[1-5]\\d|60', + /* week number */ 'U': '0\\d|\\d(?!\\d)|[1-4]\\d|50|51|52|53', + /* week number */ 'W': '0\\d|\\d(?!\\d)|[1-4]\\d|50|51|52|53', + /* weekday number */ 'w': '[0-6]', + /* 2-digit year */ 'y': '\\d\\d', + /* 4-digit year */ 'Y': '\\d\\d\\d\\d', + /* whitespace */ 't': ' ', + /* time zone */ 'z': 'Z|(?:[\\+\\-]\\d\\d:?(?:\\d\\d)?)' }; var MONTH_NUMBERS = {JAN: 0, FEB: 1, MAR: 2, APR: 3, MAY: 4, JUN: 5, JUL: 6, AUG: 7, SEP: 8, OCT: 9, NOV: 10, DEC: 11}; var DAY_NUMBERS_SUN_FIRST = {SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6}; var DAY_NUMBERS_MON_FIRST = {MON: 0, TUE: 1, WED: 2, THU: 3, FRI: 4, SAT: 5, SUN: 6}; - for (var datePattern in DATE_PATTERNS) { - pattern = pattern.replace(datePattern, '('+datePattern+DATE_PATTERNS[datePattern]+')'); - } - - // take care of capturing groups var capture = []; - for (var i=pattern.indexOf('%'); i>=0; i=pattern.indexOf('%')) { - capture.push(pattern[i+1]); - pattern = pattern.replace(new RegExp('\\%'+pattern[i+1], 'g'), ''); - } + var pattern_out = pattern + .replace(/%(.)/g, (m, c) => EQUIVALENT_MATCHERS[c] || m) + .replace(/%(.)/g, (_, c) => { + let pat = DATE_PATTERNS[c]; + if (pat){ + capture.push(c); + return `(${pat})`; + } else { + return c; + } + }) + .replace( // any number of space or tab characters match zero or more spaces + /\s+/g,'\\s*' + ); - var matches = new RegExp('^'+pattern, "i").exec(UTF8ToString(buf)) - // out(UTF8ToString(buf)+ ' is matched by '+((new RegExp('^'+pattern)).source)+' into: '+JSON.stringify(matches)); + var matches = new RegExp('^'+pattern_out, "i").exec(UTF8ToString(buf)) function initDate() { function fixup(value, min, max) { @@ -15457,7 +16884,8 @@ var ASM_CONSTS = { day: fixup(HEAP32[(((tm)+(12))>>2)], 1, 31), hour: fixup(HEAP32[(((tm)+(8))>>2)], 0, 23), min: fixup(HEAP32[(((tm)+(4))>>2)], 0, 59), - sec: fixup(HEAP32[((tm)>>2)], 0, 59) + sec: fixup(HEAP32[((tm)>>2)], 0, 59), + gmtoff: 0 }; }; @@ -15532,10 +16960,10 @@ var ASM_CONSTS = { } else if ((value=getMatch('j'))) { // get day of month from day of year ... var day = jstoi_q(value); - var leapYear = __isLeapYear(date.year); + var leapYear = isLeapYear(date.year); for (var month=0; month<12; ++month) { - var daysUntilMonth = __arraySum(leapYear ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, month-1); - if (day<=daysUntilMonth+(leapYear ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR)[month]) { + var daysUntilMonth = arraySum(leapYear ? MONTH_DAYS_LEAP : MONTH_DAYS_REGULAR, month-1); + if (day<=daysUntilMonth+(leapYear ? MONTH_DAYS_LEAP : MONTH_DAYS_REGULAR)[month]) { date.day = day-daysUntilMonth; } } @@ -15554,10 +16982,10 @@ var ASM_CONSTS = { var endDate; if (janFirst.getDay() === 0) { // Jan 1st is a Sunday, and, hence in the 1st CW - endDate = __addDays(janFirst, weekDayNumber+7*(weekNumber-1)); + endDate = addDays(janFirst, weekDayNumber+7*(weekNumber-1)); } else { // Jan 1st is not a Sunday, and, hence still in the 0th CW - endDate = __addDays(janFirst, 7-janFirst.getDay()+weekDayNumber+7*(weekNumber-1)); + endDate = addDays(janFirst, 7-janFirst.getDay()+weekDayNumber+7*(weekNumber-1)); } date.day = endDate.getDate(); date.month = endDate.getMonth(); @@ -15573,10 +17001,10 @@ var ASM_CONSTS = { var endDate; if (janFirst.getDay()===1) { // Jan 1st is a Monday, and, hence in the 1st CW - endDate = __addDays(janFirst, weekDayNumber+7*(weekNumber-1)); + endDate = addDays(janFirst, weekDayNumber+7*(weekNumber-1)); } else { // Jan 1st is not a Monday, and, hence still in the 0th CW - endDate = __addDays(janFirst, 7-janFirst.getDay()+1+weekDayNumber+7*(weekNumber-1)); + endDate = addDays(janFirst, 7-janFirst.getDay()+1+weekDayNumber+7*(weekNumber-1)); } date.day = endDate.getDate(); @@ -15584,6 +17012,20 @@ var ASM_CONSTS = { } } + // time zone + if ((value = getMatch('z'))) { + // GMT offset as either 'Z' or +-HH:MM or +-HH or +-HHMM + if (value.toLowerCase() === 'z'){ + date.gmtoff = 0; + } else { + var match = value.match(/^((?:\-|\+)\d\d):?(\d\d)?/); + date.gmtoff = match[1] * 3600; + if (match[2]) { + date.gmtoff += date.gmtoff >0 ? match[2] * 60 : -match[2] * 60 + } + } + } + /* tm_sec int seconds after the minute 0-61* tm_min int minutes after the hour 0-59 @@ -15594,6 +17036,7 @@ var ASM_CONSTS = { tm_wday int days since Sunday 0-6 tm_yday int days since January 1 0-365 tm_isdst int Daylight Saving Time flag + tm_gmtoff long offset from GMT (seconds) */ var fullDate = new Date(date.year, date.month, date.day, date.hour, date.min, date.sec, 0); @@ -15604,24 +17047,25 @@ var ASM_CONSTS = { HEAP32[(((tm)+(16))>>2)] = fullDate.getMonth(); HEAP32[(((tm)+(20))>>2)] = fullDate.getFullYear()-1900; HEAP32[(((tm)+(24))>>2)] = fullDate.getDay(); - HEAP32[(((tm)+(28))>>2)] = __arraySum(__isLeapYear(fullDate.getFullYear()) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, fullDate.getMonth()-1)+fullDate.getDate()-1; + HEAP32[(((tm)+(28))>>2)] = arraySum(isLeapYear(fullDate.getFullYear()) ? MONTH_DAYS_LEAP : MONTH_DAYS_REGULAR, fullDate.getMonth()-1)+fullDate.getDate()-1; HEAP32[(((tm)+(32))>>2)] = 0; - + HEAP32[(((tm)+(36))>>2)] = date.gmtoff; + // we need to convert the matched sequence into an integer array to take care of UTF-8 characters > 0x7F // TODO: not sure that intArrayFromString handles all unicode characters correctly return buf+intArrayFromString(matches[0]).length-1; } return 0; - } - Module["_strptime"] = _strptime; + }; + Module['_strptime'] = _strptime; _strptime.sig = 'pppp'; - function _strptime_l(buf, format, tm) { + var _strptime_l = (buf, format, tm, locale) => { return _strptime(buf, format, tm); // no locale support yet - } - Module["_strptime_l"] = _strptime_l; - _strptime_l.sig = 'pppp'; + }; + Module['_strptime_l'] = _strptime_l; + _strptime_l.sig = 'ppppp'; @@ -15637,72 +17081,13 @@ var ASM_CONSTS = { - function getHostByName(name) { - // generate hostent - var ret = _malloc(20); // XXX possibly leaked, as are others here - var nameBuf = _malloc(name.length+1); - stringToUTF8(name, nameBuf, name.length+1); - HEAPU32[((ret)>>2)] = nameBuf; - var aliasesBuf = _malloc(4); - HEAPU32[((aliasesBuf)>>2)] = 0; - HEAPU32[(((ret)+(4))>>2)] = aliasesBuf; - var afinet = 2; - HEAP32[(((ret)+(8))>>2)] = afinet; - HEAP32[(((ret)+(12))>>2)] = 4; - var addrListBuf = _malloc(12); - HEAPU32[((addrListBuf)>>2)] = addrListBuf+8; - HEAPU32[(((addrListBuf)+(4))>>2)] = 0; - HEAP32[(((addrListBuf)+(8))>>2)] = inetPton4(DNS.lookup_name(name)); - HEAPU32[(((ret)+(16))>>2)] = addrListBuf; - return ret; - } - Module["getHostByName"] = getHostByName; - - - function _gethostbyaddr(addr, addrlen, type) { - if (type !== 2) { - setErrNo(5); - // TODO: set h_errno - return null; - } - addr = HEAP32[((addr)>>2)]; // addr is in_addr - var host = inetNtop4(addr); - var lookup = DNS.lookup_addr(host); - if (lookup) { - host = lookup; - } - return getHostByName(host); - } - Module["_gethostbyaddr"] = _gethostbyaddr; - _gethostbyaddr.sig = 'ipii'; - - function _gethostbyname(name) { - return getHostByName(UTF8ToString(name)); - } - Module["_gethostbyname"] = _gethostbyname; - _gethostbyname.sig = 'pp'; - - - - - function _gethostbyname_r(name, ret, buf, buflen, out, err) { - var data = _gethostbyname(name); - _memcpy(ret, data, 20); - _free(data); - HEAP32[((err)>>2)] = 0; - HEAPU32[((out)>>2)] = ret; - return 0; - } - Module["_gethostbyname_r"] = _gethostbyname_r; - _gethostbyname_r.sig = 'ipppipp'; - - function _getaddrinfo(node, service, hint, out) { + var _getaddrinfo = (node, service, hint, out) => { // Note getaddrinfo currently only returns a single addrinfo with ai_next defaulting to NULL. When NULL // hints are specified or ai_family set to AF_UNSPEC or ai_socktype or ai_protocol set to 0 then we // really should provide a linked list of suitable addrinfo values. @@ -15734,7 +17119,7 @@ var ASM_CONSTS = { HEAP32[(((ai)+(4))>>2)] = family; HEAP32[(((ai)+(8))>>2)] = type; HEAP32[(((ai)+(12))>>2)] = proto; - HEAP32[(((ai)+(24))>>2)] = canon; + HEAPU32[(((ai)+(24))>>2)] = canon; HEAPU32[(((ai)+(20))>>2)] = sa; if (family === 10) { HEAP32[(((ai)+(16))>>2)] = 28; @@ -15869,24 +17254,28 @@ var ASM_CONSTS = { ai = allocaddrinfo(family, type, proto, null, addr, port); HEAPU32[((out)>>2)] = ai; return 0; - } - Module["_getaddrinfo"] = _getaddrinfo; + }; + Module['_getaddrinfo'] = _getaddrinfo; _getaddrinfo.sig = 'ipppp'; - var Protocols = {list:[],map:{}}; - Module["Protocols"] = Protocols; + var Protocols = { + list:[], + map:{ + }, + }; + Module['Protocols'] = Protocols; - function _setprotoent(stayopen) { + var _setprotoent = (stayopen) => { // void setprotoent(int stayopen); // Allocate and populate a protoent structure given a name, protocol number and array of aliases function allocprotoent(name, proto, aliases) { // write name into buffer var nameBuf = _malloc(name.length + 1); - writeAsciiToMemory(name, nameBuf); + stringToAscii(name, nameBuf); // write aliases into buffer var j = 0; @@ -15896,7 +17285,7 @@ var ASM_CONSTS = { for (var i = 0; i < length; i++, j += 4) { var alias = aliases[i]; var aliasBuf = _malloc(alias.length + 1); - writeAsciiToMemory(alias, aliasBuf); + stringToAscii(alias, aliasBuf); HEAPU32[(((aliasListBuf)+(j))>>2)] = aliasBuf; } HEAPU32[(((aliasListBuf)+(j))>>2)] = 0; // Terminating NULL pointer. @@ -15923,17 +17312,19 @@ var ASM_CONSTS = { } _setprotoent.index = 0; - } - Module["_setprotoent"] = _setprotoent; + }; + Module['_setprotoent'] = _setprotoent; + _setprotoent.sig = 'vi'; - function _endprotoent() { + var _endprotoent = () => { // void endprotoent(void); // We're not using a real protocol database so we don't do a real close. - } - Module["_endprotoent"] = _endprotoent; + }; + Module['_endprotoent'] = _endprotoent; + _endprotoent.sig = 'v'; - function _getprotoent(number) { + var _getprotoent = (number) => { // struct protoent *getprotoent(void); // reads the next entry from the protocols 'database' or return NULL if 'eof' if (_setprotoent.index === Protocols.list.length) { @@ -15941,27 +17332,31 @@ var ASM_CONSTS = { } var result = Protocols.list[_setprotoent.index++]; return result; - } - Module["_getprotoent"] = _getprotoent; + }; + Module['_getprotoent'] = _getprotoent; + _getprotoent.sig = 'p'; - function _getprotobyname(name) { + + var _getprotobyname = (name) => { // struct protoent *getprotobyname(const char *); name = UTF8ToString(name); _setprotoent(true); var result = Protocols.map[name]; return result; - } - Module["_getprotobyname"] = _getprotobyname; + }; + Module['_getprotobyname'] = _getprotobyname; + _getprotobyname.sig = 'pp'; - function _getprotobynumber(number) { + var _getprotobynumber = (number) => { // struct protoent *getprotobynumber(int proto); _setprotoent(true); var result = Protocols.map[number]; return result; - } - Module["_getprotobynumber"] = _getprotobynumber; + }; + Module['_getprotobynumber'] = _getprotobynumber; + _getprotobynumber.sig = 'pi'; @@ -15969,20 +17364,24 @@ var ASM_CONSTS = { - function _emscripten_run_script(ptr) { + + var _emscripten_run_script = (ptr) => { eval(UTF8ToString(ptr)); - } - Module["_emscripten_run_script"] = _emscripten_run_script; + }; + Module['_emscripten_run_script'] = _emscripten_run_script; _emscripten_run_script.sig = 'vp'; /** @suppress{checkTypes} */ - function _emscripten_run_script_int(ptr) { + var _emscripten_run_script_int = (ptr) => { return eval(UTF8ToString(ptr))|0; - } - Module["_emscripten_run_script_int"] = _emscripten_run_script_int; + }; + Module['_emscripten_run_script_int'] = _emscripten_run_script_int; _emscripten_run_script_int.sig = 'ip'; - function _emscripten_run_script_string(ptr) { + + + + var _emscripten_run_script_string = (ptr) => { var s = eval(UTF8ToString(ptr)); if (s == null) { return 0; @@ -15997,71 +17396,26 @@ var ASM_CONSTS = { } stringToUTF8(s, me.buffer, me.bufferSize); return me.buffer; - } - Module["_emscripten_run_script_string"] = _emscripten_run_script_string; + }; + Module['_emscripten_run_script_string'] = _emscripten_run_script_string; _emscripten_run_script_string.sig = 'pp'; - function _emscripten_random() { - return Math.random(); - } - Module["_emscripten_random"] = _emscripten_random; - + var _emscripten_random = () => Math.random(); + Module['_emscripten_random'] = _emscripten_random; + _emscripten_random.sig = 'f'; - function traverseStack(args) { - if (!args || !args.callee || !args.callee.name) { - return [null, '', '']; - } - - var funstr = args.callee.toString(); - var funcname = args.callee.name; - var str = '('; - var first = true; - for (var i in args) { - var a = args[i]; - if (!first) { - str += ", "; - } - first = false; - if (typeof a == 'number' || typeof a == 'string') { - str += a; - } else { - str += '(' + typeof a + ')'; - } - } - str += ')'; - var caller = args.callee.caller; - args = caller ? caller.arguments : []; - if (first) - str = ''; - return [args, funcname, str]; - } - Module["traverseStack"] = traverseStack; - function jsStackTrace() { - var error = new Error(); - if (!error.stack) { - // IE10+ special cases: It does have callstack info, but it is only - // populated if an Error object is thrown, so try that as a special-case. - try { - throw new Error(); - } catch(e) { - error = e; - } - if (!error.stack) { - return '(no stack trace available)'; - } - } - return error.stack.toString(); + return new Error().stack.toString(); } - Module["jsStackTrace"] = jsStackTrace; + Module['jsStackTrace'] = jsStackTrace; /** @param {number=} flags */ - function _emscripten_get_callstack_js(flags) { + function getCallstack(flags) { var callstack = jsStackTrace(); // Find the symbols in the callstack that corresponds to the functions that @@ -16072,10 +17426,6 @@ var ASM_CONSTS = { var iNextLine = callstack.indexOf('\n', Math.max(iThisFunc, iThisFunc2))+1; callstack = callstack.slice(iNextLine); - if (flags & 32) { - warnOnce('EM_LOG_DEMANGLE is deprecated; ignoring'); - } - // If user requested to see the original source stack, but no source map // information is available, just fall back to showing the JS stack. if (flags & 8 && typeof emscripten_source_map == 'undefined') { @@ -16084,15 +17434,6 @@ var ASM_CONSTS = { flags |= 16; } - var stack_args = null; - if (flags & 128) { - // To get the actual parameters to the functions, traverse the stack via - // the unfortunately deprecated 'arguments.callee' method, if it works: - stack_args = traverseStack(arguments); - while (stack_args[1].includes('_emscripten_')) - stack_args = traverseStack(stack_args[0]); - } - // Process all lines: var lines = callstack.split('\n'); callstack = ''; @@ -16142,43 +17483,31 @@ var ASM_CONSTS = { if (flags & 8) { var orig = emscripten_source_map.originalPositionFor({line: lineno, column: column}); - haveSourceMap = (orig && orig.source); + haveSourceMap = orig?.source; if (haveSourceMap) { if (flags & 64) { orig.source = orig.source.substring(orig.source.replace(/\\/g, "/").lastIndexOf('/')+1); } - callstack += ' at ' + symbolName + ' (' + orig.source + ':' + orig.line + ':' + orig.column + ')\n'; + callstack += ` at ${symbolName} (${orig.source}:${orig.line}:${orig.column})\n`; } } if ((flags & 16) || !haveSourceMap) { if (flags & 64) { file = file.substring(file.replace(/\\/g, "/").lastIndexOf('/')+1); } - callstack += (haveSourceMap ? (' = ' + symbolName) : (' at '+ symbolName)) + ' (' + file + ':' + lineno + ':' + column + ')\n'; - } - - // If we are still keeping track with the callstack by traversing via - // 'arguments.callee', print the function parameters as well. - if (flags & 128 && stack_args[0]) { - if (stack_args[1] == symbolName && stack_args[2].length > 0) { - callstack = callstack.replace(/\s+$/, ''); - callstack += ' with values: ' + stack_args[1] + stack_args[2] + '\n'; - } - stack_args = traverseStack(stack_args[0]); + callstack += (haveSourceMap ? (` = ${symbolName}`) : (` at ${symbolName}`)) + ` (${file}:${lineno}:${column})\n`; } } // Trim extra whitespace at the end of the output. callstack = callstack.replace(/\s+$/, ''); return callstack; } - Module["_emscripten_get_callstack_js"] = _emscripten_get_callstack_js; + Module['getCallstack'] = getCallstack; + + function _emscripten_get_callstack(flags, str, maxbytes) { - // Use explicit calls to from64 rather then using the __sig - // magic here. This is because the __sig wrapper uses arrow function - // notation which causes the inner call to traverseStack to fail. - ; - var callstack = _emscripten_get_callstack_js(flags); + var callstack = getCallstack(flags); // User can query the required amount of bytes to hold the callstack. if (!str || maxbytes <= 0) { return lengthBytesUTF8(callstack)+1; @@ -16189,12 +17518,13 @@ var ASM_CONSTS = { // Return number of bytes written, including null. return bytesWrittenExcludingNull+1; } - Module["_emscripten_get_callstack"] = _emscripten_get_callstack; + Module['_emscripten_get_callstack'] = _emscripten_get_callstack; + _emscripten_get_callstack.sig = 'iipi'; - function _emscripten_log_js(flags, str) { + var emscriptenLog = (flags, str) => { if (flags & 24) { str = str.replace(/\s+$/, ''); // Ensure the message and the callstack are joined cleanly with exactly one newline. - str += (str.length > 0 ? '\n' : '') + _emscripten_get_callstack_js(flags); + str += (str.length > 0 ? '\n' : '') + getCallstack(flags); } if (flags & 1) { @@ -16214,29 +17544,15 @@ var ASM_CONSTS = { } else { out(str); } - } - Module["_emscripten_log_js"] = _emscripten_log_js; + }; + Module['emscriptenLog'] = emscriptenLog; - function reallyNegative(x) { - return x < 0 || (x === 0 && (1/x) === -Infinity); - } - Module["reallyNegative"] = reallyNegative; + var reallyNegative = (x) => x < 0 || (x === 0 && (1/x) === -Infinity); + Module['reallyNegative'] = reallyNegative; - function convertI32PairToI53(lo, hi) { - // This function should not be getting called with too large unsigned numbers - // in high part (if hi >= 0x7FFFFFFFF, one should have been calling - // convertU32PairToI53()) - assert(hi === (hi|0)); - return (lo >>> 0) + hi * 4294967296; - } - Module["convertI32PairToI53"] = convertI32PairToI53; - function convertU32PairToI53(lo, hi) { - return (lo >>> 0) + (hi >>> 0) * 4294967296; - } - Module["convertU32PairToI53"] = convertU32PairToI53; - function reSign(value, bits) { + var reSign = (value, bits) => { if (value <= 0) { return value; } @@ -16252,10 +17568,10 @@ var ASM_CONSTS = { value = -2*half + value; } return value; - } - Module["reSign"] = reSign; + }; + Module['reSign'] = reSign; - function unSign(value, bits) { + var unSign = (value, bits) => { if (value >= 0) { return value; } @@ -16263,17 +17579,17 @@ var ASM_CONSTS = { // bits JS uses in bitshifts return bits <= 32 ? 2*Math.abs(1 << (bits-1)) + value : Math.pow(2, bits) + value; - } - Module["unSign"] = unSign; + }; + Module['unSign'] = unSign; - function strLen(ptr) { + var strLen = (ptr) => { var end = ptr; while (HEAPU8[end]) ++end; return end - ptr; - } - Module["strLen"] = strLen; + }; + Module['strLen'] = strLen; - function formatString(format, varargs) { + var formatString = (format, varargs) => { assert((varargs & 3) === 0); var textIndex = format; var argIndex = varargs; @@ -16316,9 +17632,9 @@ var ASM_CONSTS = { var curr, next, currArg; while (1) { var startTextIndex = textIndex; - curr = HEAP8[((textIndex)>>0)]; + curr = HEAP8[textIndex]; if (curr === 0) break; - next = HEAP8[((textIndex+1)>>0)]; + next = HEAP8[textIndex+1]; if (curr == 37) { // Handle flags. var flagAlwaysSigned = false; @@ -16351,7 +17667,7 @@ var ASM_CONSTS = { break flagsLoop; } textIndex++; - next = HEAP8[((textIndex+1)>>0)]; + next = HEAP8[textIndex+1]; } // Handle width. @@ -16359,12 +17675,12 @@ var ASM_CONSTS = { if (next == 42) { width = getNextArg('i32'); textIndex++; - next = HEAP8[((textIndex+1)>>0)]; + next = HEAP8[textIndex+1]; } else { while (next >= 48 && next <= 57) { width = width * 10 + (next - 48); textIndex++; - next = HEAP8[((textIndex+1)>>0)]; + next = HEAP8[textIndex+1]; } } @@ -16374,20 +17690,20 @@ var ASM_CONSTS = { precision = 0; precisionSet = true; textIndex++; - next = HEAP8[((textIndex+1)>>0)]; + next = HEAP8[textIndex+1]; if (next == 42) { precision = getNextArg('i32'); textIndex++; } else { while (1) { - var precisionChr = HEAP8[((textIndex+1)>>0)]; + var precisionChr = HEAP8[textIndex+1]; if (precisionChr < 48 || precisionChr > 57) break; precision = precision * 10 + (precisionChr - 48); textIndex++; } } - next = HEAP8[((textIndex+1)>>0)]; + next = HEAP8[textIndex+1]; } if (precision < 0) { precision = 6; // Standard default. @@ -16398,7 +17714,7 @@ var ASM_CONSTS = { var argSize; switch (String.fromCharCode(next)) { case 'h': - var nextNext = HEAP8[((textIndex+2)>>0)]; + var nextNext = HEAP8[textIndex+2]; if (nextNext == 104) { textIndex++; argSize = 1; // char (actually i32 in varargs) @@ -16407,7 +17723,7 @@ var ASM_CONSTS = { } break; case 'l': - var nextNext = HEAP8[((textIndex+2)>>0)]; + var nextNext = HEAP8[textIndex+2]; if (nextNext == 108) { textIndex++; argSize = 8; // long long @@ -16429,7 +17745,7 @@ var ASM_CONSTS = { argSize = null; } if (argSize) textIndex++; - next = HEAP8[((textIndex+1)>>0)]; + next = HEAP8[textIndex+1]; // Handle type specifier. switch (String.fromCharCode(next)) { @@ -16631,7 +17947,7 @@ var ASM_CONSTS = { } if (arg) { for (var i = 0; i < argLength; i++) { - ret.push(HEAPU8[((arg++)>>0)]); + ret.push(HEAPU8[arg++]); } } else { ret = ret.concat(intArrayFromString('(null)'.substr(0, argLength), true)); @@ -16666,7 +17982,7 @@ var ASM_CONSTS = { default: { // Unknown specifiers remain untouched. for (var i = startTextIndex; i < textIndex + 2; i++) { - ret.push(HEAP8[((i)>>0)]); + ret.push(HEAP8[i]); } } } @@ -16679,51 +17995,50 @@ var ASM_CONSTS = { } } return ret; - } - Module["formatString"] = formatString; + }; + Module['formatString'] = formatString; - function _emscripten_log(flags, format, varargs) { + var _emscripten_log = (flags, format, varargs) => { var result = formatString(format, varargs); var str = UTF8ArrayToString(result, 0); - _emscripten_log_js(flags, str); - } - Module["_emscripten_log"] = _emscripten_log; + emscriptenLog(flags, str); + }; + Module['_emscripten_log'] = _emscripten_log; _emscripten_log.sig = 'vipp'; - function _emscripten_get_compiler_setting(name) { + var _emscripten_get_compiler_setting = (name) => { throw 'You must build with -sRETAIN_COMPILER_SETTINGS for getCompilerSetting or emscripten_get_compiler_setting to work'; - } - Module["_emscripten_get_compiler_setting"] = _emscripten_get_compiler_setting; + }; + Module['_emscripten_get_compiler_setting'] = _emscripten_get_compiler_setting; _emscripten_get_compiler_setting.sig = 'pp'; - function _emscripten_has_asyncify() { - return 0; - } - Module["_emscripten_has_asyncify"] = _emscripten_has_asyncify; + var _emscripten_has_asyncify = () => 0; + Module['_emscripten_has_asyncify'] = _emscripten_has_asyncify; + _emscripten_has_asyncify.sig = 'i'; - function _emscripten_debugger() { - debugger; - } - Module["_emscripten_debugger"] = _emscripten_debugger; + function _emscripten_debugger() { debugger } + Module['_emscripten_debugger'] = _emscripten_debugger; + _emscripten_debugger.sig = 'v'; - function _emscripten_print_double(x, to, max) { + + var _emscripten_print_double = (x, to, max) => { var str = x + ''; if (to) return stringToUTF8(str, to, max); else return lengthBytesUTF8(str); - } - Module["_emscripten_print_double"] = _emscripten_print_double; - _emscripten_print_double.sig = 'iipi'; + }; + Module['_emscripten_print_double'] = _emscripten_print_double; + _emscripten_print_double.sig = 'idpi'; /** @returns {number} */ - function convertFrameToPC(frame) { + var convertFrameToPC = (frame) => { abort('Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER'); // return 0 if we can't find any return 0; - } - Module["convertFrameToPC"] = convertFrameToPC; + }; + Module['convertFrameToPC'] = convertFrameToPC; - function _emscripten_return_address(level) { + var _emscripten_return_address = (level) => { var callstack = jsStackTrace().split('\n'); if (callstack[0] == 'Error') { callstack.shift(); @@ -16731,25 +18046,26 @@ var ASM_CONSTS = { // skip this function and the caller to get caller's return address var caller = callstack[level + 3]; return convertFrameToPC(caller); - } - Module["_emscripten_return_address"] = _emscripten_return_address; + }; + Module['_emscripten_return_address'] = _emscripten_return_address; _emscripten_return_address.sig = 'pi'; - var UNWIND_CACHE = {}; - Module["UNWIND_CACHE"] = UNWIND_CACHE; + var UNWIND_CACHE = { + }; + Module['UNWIND_CACHE'] = UNWIND_CACHE; - function saveInUnwindCache(callstack) { + var saveInUnwindCache = (callstack) => { callstack.forEach((frame) => { var pc = convertFrameToPC(frame); if (pc) { UNWIND_CACHE[pc] = frame; } }); - } - Module["saveInUnwindCache"] = saveInUnwindCache; + }; + Module['saveInUnwindCache'] = saveInUnwindCache; function _emscripten_stack_snapshot() { var callstack = jsStackTrace().split('\n'); @@ -16764,14 +18080,14 @@ var ASM_CONSTS = { UNWIND_CACHE.last_stack = callstack; return UNWIND_CACHE.last_addr; } - Module["_emscripten_stack_snapshot"] = _emscripten_stack_snapshot; + Module['_emscripten_stack_snapshot'] = _emscripten_stack_snapshot; _emscripten_stack_snapshot.sig = 'p'; - function _emscripten_stack_unwind_buffer(addr, buffer, count) { + var _emscripten_stack_unwind_buffer = (addr, buffer, count) => { var stack; if (UNWIND_CACHE.last_addr == addr) { stack = UNWIND_CACHE.last_stack; @@ -16792,17 +18108,19 @@ var ASM_CONSTS = { HEAP32[(((buffer)+(i*4))>>2)] = convertFrameToPC(stack[i + offset]); } return i; - } - Module["_emscripten_stack_unwind_buffer"] = _emscripten_stack_unwind_buffer; + }; + Module['_emscripten_stack_unwind_buffer'] = _emscripten_stack_unwind_buffer; _emscripten_stack_unwind_buffer.sig = 'ippi'; - function _emscripten_pc_get_function(pc) { + var _emscripten_pc_get_function = (pc) => { abort('Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER'); - } - Module["_emscripten_pc_get_function"] = _emscripten_pc_get_function; + return 0; + }; + Module['_emscripten_pc_get_function'] = _emscripten_pc_get_function; + _emscripten_pc_get_function.sig = 'pp'; - function convertPCtoSourceLocation(pc) { + var convertPCtoSourceLocation = (pc) => { if (UNWIND_CACHE.last_get_source_pc == pc) return UNWIND_CACHE.last_source; var match; @@ -16822,183 +18140,166 @@ var ASM_CONSTS = { UNWIND_CACHE.last_get_source_pc = pc; UNWIND_CACHE.last_source = source; return source; - } - Module["convertPCtoSourceLocation"] = convertPCtoSourceLocation; + }; + Module['convertPCtoSourceLocation'] = convertPCtoSourceLocation; - function _emscripten_pc_get_file(pc) { + var _emscripten_pc_get_file = (pc) => { var result = convertPCtoSourceLocation(pc); if (!result) return 0; if (_emscripten_pc_get_file.ret) _free(_emscripten_pc_get_file.ret); - _emscripten_pc_get_file.ret = allocateUTF8(result.file); + _emscripten_pc_get_file.ret = stringToNewUTF8(result.file); return _emscripten_pc_get_file.ret; - } - Module["_emscripten_pc_get_file"] = _emscripten_pc_get_file; + }; + Module['_emscripten_pc_get_file'] = _emscripten_pc_get_file; _emscripten_pc_get_file.sig = 'pp'; - function _emscripten_pc_get_line(pc) { + var _emscripten_pc_get_line = (pc) => { var result = convertPCtoSourceLocation(pc); return result ? result.line : 0; - } - Module["_emscripten_pc_get_line"] = _emscripten_pc_get_line; + }; + Module['_emscripten_pc_get_line'] = _emscripten_pc_get_line; _emscripten_pc_get_line.sig = 'ip'; - function _emscripten_pc_get_column(pc) { + var _emscripten_pc_get_column = (pc) => { var result = convertPCtoSourceLocation(pc); return result ? result.column || 0 : 0; - } - Module["_emscripten_pc_get_column"] = _emscripten_pc_get_column; + }; + Module['_emscripten_pc_get_column'] = _emscripten_pc_get_column; _emscripten_pc_get_column.sig = 'ip'; - function _emscripten_get_module_name(buf, length) { + var _emscripten_get_module_name = (buf, length) => { return stringToUTF8(wasmBinaryFile, buf, length); - } - Module["_emscripten_get_module_name"] = _emscripten_get_module_name; + }; + Module['_emscripten_get_module_name'] = _emscripten_get_module_name; _emscripten_get_module_name.sig = 'ppp'; - function _emscripten_asm_const_double(code, sigPtr, argbuf) { + var _emscripten_asm_const_double = (code, sigPtr, argbuf) => { return runEmAsmFunction(code, sigPtr, argbuf); - } - Module["_emscripten_asm_const_double"] = _emscripten_asm_const_double; + }; + Module['_emscripten_asm_const_double'] = _emscripten_asm_const_double; _emscripten_asm_const_double.sig = 'dppp'; - var _emscripten_asm_const_ptr = _emscripten_asm_const_int; - Module["_emscripten_asm_const_ptr"] = _emscripten_asm_const_ptr; + var _emscripten_asm_const_ptr = (code, sigPtr, argbuf) => { + return runEmAsmFunction(code, sigPtr, argbuf); + }; + Module['_emscripten_asm_const_ptr'] = _emscripten_asm_const_ptr; + _emscripten_asm_const_ptr.sig = 'pppp'; - function runMainThreadEmAsm(code, sigPtr, argbuf, sync) { + var runMainThreadEmAsm = (emAsmAddr, sigPtr, argbuf, sync) => { var args = readEmAsmArgs(sigPtr, argbuf); - if (!ASM_CONSTS.hasOwnProperty(code)) abort('No EM_ASM constant found at address ' + code); - return ASM_CONSTS[code].apply(null, args); - } - Module["runMainThreadEmAsm"] = runMainThreadEmAsm; - runMainThreadEmAsm.sig = 'iippi'; + assert(ASM_CONSTS.hasOwnProperty(emAsmAddr), `No EM_ASM constant found at address ${emAsmAddr}. The loaded WebAssembly file is likely out of sync with the generated JavaScript.`); + return ASM_CONSTS[emAsmAddr](...args); + }; + Module['runMainThreadEmAsm'] = runMainThreadEmAsm; - function _emscripten_asm_const_int_sync_on_main_thread(code, sigPtr, argbuf) { - return runMainThreadEmAsm(code, sigPtr, argbuf, 1); - } - Module["_emscripten_asm_const_int_sync_on_main_thread"] = _emscripten_asm_const_int_sync_on_main_thread; - _emscripten_asm_const_int_sync_on_main_thread.sig = 'iiii'; + var _emscripten_asm_const_int_sync_on_main_thread = (emAsmAddr, sigPtr, argbuf) => runMainThreadEmAsm(emAsmAddr, sigPtr, argbuf, 1); + Module['_emscripten_asm_const_int_sync_on_main_thread'] = _emscripten_asm_const_int_sync_on_main_thread; + _emscripten_asm_const_int_sync_on_main_thread.sig = 'ippp'; + + var _emscripten_asm_const_ptr_sync_on_main_thread = (emAsmAddr, sigPtr, argbuf) => runMainThreadEmAsm(emAsmAddr, sigPtr, argbuf, 1); + Module['_emscripten_asm_const_ptr_sync_on_main_thread'] = _emscripten_asm_const_ptr_sync_on_main_thread; + _emscripten_asm_const_ptr_sync_on_main_thread.sig = 'pppp'; var _emscripten_asm_const_double_sync_on_main_thread = _emscripten_asm_const_int_sync_on_main_thread; - Module["_emscripten_asm_const_double_sync_on_main_thread"] = _emscripten_asm_const_double_sync_on_main_thread; + Module['_emscripten_asm_const_double_sync_on_main_thread'] = _emscripten_asm_const_double_sync_on_main_thread; + _emscripten_asm_const_double_sync_on_main_thread.sig = 'dppp'; - function _emscripten_asm_const_async_on_main_thread(code, sigPtr, argbuf) { - return runMainThreadEmAsm(code, sigPtr, argbuf, 0); - } - Module["_emscripten_asm_const_async_on_main_thread"] = _emscripten_asm_const_async_on_main_thread; + var _emscripten_asm_const_async_on_main_thread = (emAsmAddr, sigPtr, argbuf) => runMainThreadEmAsm(emAsmAddr, sigPtr, argbuf, 0); + Module['_emscripten_asm_const_async_on_main_thread'] = _emscripten_asm_const_async_on_main_thread; + _emscripten_asm_const_async_on_main_thread.sig = 'vppp'; - function jstoi_s(str) { - return Number(str); - } - Module["jstoi_s"] = jstoi_s; + var jstoi_s = Number; + Module['jstoi_s'] = jstoi_s; - function __Unwind_Backtrace(func, arg) { - var trace = _emscripten_get_callstack_js(); + var __Unwind_Backtrace = (func, arg) => { + var trace = getCallstack(); var parts = trace.split('\n'); for (var i = 0; i < parts.length; i++) { var ret = getWasmTableEntry(func)(0, arg); if (ret !== 0) return; } - } - Module["__Unwind_Backtrace"] = __Unwind_Backtrace; + }; + Module['__Unwind_Backtrace'] = __Unwind_Backtrace; + __Unwind_Backtrace.sig = 'ipp'; - function __Unwind_GetIPInfo() { - abort('Unwind_GetIPInfo'); - } - Module["__Unwind_GetIPInfo"] = __Unwind_GetIPInfo; + var __Unwind_GetIPInfo = (context, ipBefore) => abort('Unwind_GetIPInfo'); + Module['__Unwind_GetIPInfo'] = __Unwind_GetIPInfo; + __Unwind_GetIPInfo.sig = 'ppp'; - function __Unwind_FindEnclosingFunction() { - return 0; // we cannot succeed - } - Module["__Unwind_FindEnclosingFunction"] = __Unwind_FindEnclosingFunction; + var __Unwind_FindEnclosingFunction = (ip) => 0; + Module['__Unwind_FindEnclosingFunction'] = __Unwind_FindEnclosingFunction; + __Unwind_FindEnclosingFunction.sig = 'pp'; - /** @constructor */ - function ExceptionInfo(excPtr) { - this.excPtr = excPtr; - this.ptr = excPtr - 24; + class ExceptionInfo { + // excPtr - Thrown object pointer to wrap. Metadata pointer is calculated from it. + constructor(excPtr) { + this.excPtr = excPtr; + this.ptr = excPtr - 24; + } - this.set_type = function(type) { + set_type(type) { HEAPU32[(((this.ptr)+(4))>>2)] = type; - }; + } - this.get_type = function() { + get_type() { return HEAPU32[(((this.ptr)+(4))>>2)]; - }; + } - this.set_destructor = function(destructor) { + set_destructor(destructor) { HEAPU32[(((this.ptr)+(8))>>2)] = destructor; - }; + } - this.get_destructor = function() { + get_destructor() { return HEAPU32[(((this.ptr)+(8))>>2)]; - }; - - this.set_refcount = function(refcount) { - HEAP32[((this.ptr)>>2)] = refcount; - }; + } - this.set_caught = function (caught) { + set_caught(caught) { caught = caught ? 1 : 0; - HEAP8[(((this.ptr)+(12))>>0)] = caught; - }; + HEAP8[(this.ptr)+(12)] = caught; + } - this.get_caught = function () { - return HEAP8[(((this.ptr)+(12))>>0)] != 0; - }; + get_caught() { + return HEAP8[(this.ptr)+(12)] != 0; + } - this.set_rethrown = function (rethrown) { + set_rethrown(rethrown) { rethrown = rethrown ? 1 : 0; - HEAP8[(((this.ptr)+(13))>>0)] = rethrown; - }; + HEAP8[(this.ptr)+(13)] = rethrown; + } - this.get_rethrown = function () { - return HEAP8[(((this.ptr)+(13))>>0)] != 0; - }; + get_rethrown() { + return HEAP8[(this.ptr)+(13)] != 0; + } // Initialize native structure fields. Should be called once after allocated. - this.init = function(type, destructor) { + init(type, destructor) { this.set_adjusted_ptr(0); this.set_type(type); this.set_destructor(destructor); - this.set_refcount(0); - this.set_caught(false); - this.set_rethrown(false); } - this.add_ref = function() { - var value = HEAP32[((this.ptr)>>2)]; - HEAP32[((this.ptr)>>2)] = value + 1; - }; - - // Returns true if last reference released. - this.release_ref = function() { - var prev = HEAP32[((this.ptr)>>2)]; - HEAP32[((this.ptr)>>2)] = prev - 1; - assert(prev > 0); - return prev === 1; - }; - - this.set_adjusted_ptr = function(adjustedPtr) { + set_adjusted_ptr(adjustedPtr) { HEAPU32[(((this.ptr)+(16))>>2)] = adjustedPtr; - }; + } - this.get_adjusted_ptr = function() { + get_adjusted_ptr() { return HEAPU32[(((this.ptr)+(16))>>2)]; - }; + } // Get pointer which is expected to be received by catch clause in C++ code. It may be adjusted // when the pointer is casted to some of the exception object base classes (e.g. when virtual // inheritance is used). When a pointer is thrown this method should return the thrown pointer // itself. - this.get_exception_ptr = function() { + get_exception_ptr() { // Work around a fastcomp bug, this code is still included for some reason in a build without // exceptions support. var isPointer = ___cxa_is_pointer_type(this.get_type()); @@ -17008,173 +18309,154 @@ var ASM_CONSTS = { var adjusted = this.get_adjusted_ptr(); if (adjusted !== 0) return adjusted; return this.excPtr; - }; + } } - Module["ExceptionInfo"] = ExceptionInfo; + Module['ExceptionInfo'] = ExceptionInfo; var exceptionLast = 0; - Module["exceptionLast"] = exceptionLast; + Module['exceptionLast'] = exceptionLast; var uncaughtExceptionCount = 0; - Module["uncaughtExceptionCount"] = uncaughtExceptionCount; - function ___cxa_throw(ptr, type, destructor) { + Module['uncaughtExceptionCount'] = uncaughtExceptionCount; + var ___cxa_throw = (ptr, type, destructor) => { var info = new ExceptionInfo(ptr); // Initialize ExceptionInfo content after it was allocated in __cxa_allocate_exception. info.init(type, destructor); exceptionLast = ptr; uncaughtExceptionCount++; - throw ptr + " - Exception catching is disabled, this exception cannot be caught. Compile with -sNO_DISABLE_EXCEPTION_CATCHING or -sEXCEPTION_CATCHING_ALLOWED=[..] to catch." + " (note: in dynamic linking, if a side module wants exceptions, the main module must be built with that support)"; - } - Module["___cxa_throw"] = ___cxa_throw; + assert(false, 'Exception thrown, but exception catching is not enabled. Compile with -sNO_DISABLE_EXCEPTION_CATCHING or -sEXCEPTION_CATCHING_ALLOWED=[..] to catch. (note: in dynamic linking, if a side module wants exceptions, the main module must be built with that support)'); + }; + Module['___cxa_throw'] = ___cxa_throw; ___cxa_throw.sig = 'vppp'; - function __Unwind_RaiseException(ex) { + var __Unwind_RaiseException = (ex) => { err('Warning: _Unwind_RaiseException is not correctly implemented'); return ___cxa_throw(ex, 0, 0); - } - Module["__Unwind_RaiseException"] = __Unwind_RaiseException; + }; + Module['__Unwind_RaiseException'] = __Unwind_RaiseException; + __Unwind_RaiseException.sig = 'ip'; - function __Unwind_DeleteException(ex) { + var __Unwind_DeleteException = (ex) => { err('TODO: Unwind_DeleteException'); - } - Module["__Unwind_DeleteException"] = __Unwind_DeleteException; - - function _emscripten_autodebug_i64(line, valuel, valueh) { - out('AD:' + [line, valuel, valueh]); - } - Module["_emscripten_autodebug_i64"] = _emscripten_autodebug_i64; - - function _emscripten_autodebug_i32(line, value) { - out('AD:' + [line, value]); - } - Module["_emscripten_autodebug_i32"] = _emscripten_autodebug_i32; - - function _emscripten_autodebug_i16(line, value) { - out('AD:' + [line, value]); - } - Module["_emscripten_autodebug_i16"] = _emscripten_autodebug_i16; - - function _emscripten_autodebug_i8(line, value) { - out('AD:' + [line, value]); - } - Module["_emscripten_autodebug_i8"] = _emscripten_autodebug_i8; - - function _emscripten_autodebug_float(line, value) { - out('AD:' + [line, value]); - } - Module["_emscripten_autodebug_float"] = _emscripten_autodebug_float; - - function _emscripten_autodebug_double(line, value) { - out('AD:' + [line, value]); - } - Module["_emscripten_autodebug_double"] = _emscripten_autodebug_double; + }; + Module['__Unwind_DeleteException'] = __Unwind_DeleteException; + __Unwind_DeleteException.sig = 'vp'; - function ___handle_stack_overflow(requested) { - requested = requested >>> 0; + var ___handle_stack_overflow = (requested) => { var base = _emscripten_stack_get_base(); var end = _emscripten_stack_get_end(); - abort('stack overflow (Attempt to set SP to ' + ptrToString(requested) + - ', with stack limits [' + ptrToString(end) + ' - ' + ptrToString(base) + + abort(`stack overflow (Attempt to set SP to ${ptrToString(requested)}` + + `, with stack limits [${ptrToString(end)} - ${ptrToString(base)}` + ']). If you require more stack space build with -sSTACK_SIZE='); - } - Module["___handle_stack_overflow"] = ___handle_stack_overflow; + }; + Module['___handle_stack_overflow'] = ___handle_stack_overflow; ___handle_stack_overflow.sig = 'vp'; - - function getDynCaller(sig, ptr) { + var getDynCaller = (sig, ptr) => { assert(sig.includes('j') || sig.includes('p'), 'getDynCaller should only be called with i64 sigs') - var argCache = []; - return function() { - argCache.length = 0; - Object.assign(argCache, arguments); - return dynCall(sig, ptr, argCache); - }; - } - Module["getDynCaller"] = getDynCaller; + return (...args) => dynCall(sig, ptr, args); + }; + Module['getDynCaller'] = getDynCaller; - function _emscripten_exit_with_live_runtime() { + var _emscripten_exit_with_live_runtime = () => { throw 'unwind'; - } - Module["_emscripten_exit_with_live_runtime"] = _emscripten_exit_with_live_runtime; + }; + Module['_emscripten_exit_with_live_runtime'] = _emscripten_exit_with_live_runtime; _emscripten_exit_with_live_runtime.sig = 'v'; + + - function _emscripten_force_exit(status) { + + var _emscripten_force_exit = (status) => { warnOnce('emscripten_force_exit cannot actually shut down the runtime, as the build does not have EXIT_RUNTIME set'); - noExitRuntime = false; - runtimeKeepaliveCounter = 0; + __emscripten_runtime_keepalive_clear(); _exit(status); - } - Module["_emscripten_force_exit"] = _emscripten_force_exit; + }; + Module['_emscripten_force_exit'] = _emscripten_force_exit; _emscripten_force_exit.sig = 'vi'; + var _emscripten_outn = (str, len) => out(UTF8ToString(str, len)); + Module['_emscripten_outn'] = _emscripten_outn; + _emscripten_outn.sig = 'vpp'; + + var _emscripten_errn = (str, len) => err(UTF8ToString(str, len)); + Module['_emscripten_errn'] = _emscripten_errn; + _emscripten_errn.sig = 'vpp'; + var _emscripten_dbgn = (str, len) => dbg(UTF8ToString(str, len)); + Module['_emscripten_dbgn'] = _emscripten_dbgn; + _emscripten_dbgn.sig = 'vpp'; - function _emscripten_throw_number(number) { + + + var _emscripten_throw_number = (number) => { throw number; - } - Module["_emscripten_throw_number"] = _emscripten_throw_number; + }; + Module['_emscripten_throw_number'] = _emscripten_throw_number; + _emscripten_throw_number.sig = 'vd'; - function _emscripten_throw_string(str) { + var _emscripten_throw_string = (str) => { assert(typeof str == 'number'); throw UTF8ToString(str); - } - Module["_emscripten_throw_string"] = _emscripten_throw_string; + }; + Module['_emscripten_throw_string'] = _emscripten_throw_string; + _emscripten_throw_string.sig = 'vp'; + + - function runtimeKeepalivePush() { + var runtimeKeepalivePush = () => { runtimeKeepaliveCounter += 1; - } - Module["runtimeKeepalivePush"] = runtimeKeepalivePush; + }; + Module['runtimeKeepalivePush'] = runtimeKeepalivePush; runtimeKeepalivePush.sig = 'v'; - function runtimeKeepalivePop() { + var runtimeKeepalivePop = () => { assert(runtimeKeepaliveCounter > 0); runtimeKeepaliveCounter -= 1; - } - Module["runtimeKeepalivePop"] = runtimeKeepalivePop; + }; + Module['runtimeKeepalivePop'] = runtimeKeepalivePop; runtimeKeepalivePop.sig = 'v'; var _emscripten_runtime_keepalive_push = runtimeKeepalivePush; - Module["_emscripten_runtime_keepalive_push"] = _emscripten_runtime_keepalive_push; + Module['_emscripten_runtime_keepalive_push'] = _emscripten_runtime_keepalive_push; + _emscripten_runtime_keepalive_push.sig = 'v'; var _emscripten_runtime_keepalive_pop = runtimeKeepalivePop; - Module["_emscripten_runtime_keepalive_pop"] = _emscripten_runtime_keepalive_pop; - - function _emscripten_runtime_keepalive_check() { - // keepRuntimeAlive is a runtime function rather than a library function, - // so we can't use an alias like we do for the two functions above. - return keepRuntimeAlive(); - } - Module["_emscripten_runtime_keepalive_check"] = _emscripten_runtime_keepalive_check; + Module['_emscripten_runtime_keepalive_pop'] = _emscripten_runtime_keepalive_pop; + _emscripten_runtime_keepalive_pop.sig = 'v'; + var _emscripten_runtime_keepalive_check = keepRuntimeAlive; + Module['_emscripten_runtime_keepalive_check'] = _emscripten_runtime_keepalive_check; + _emscripten_runtime_keepalive_check.sig = 'i'; - function asmjsMangle(x) { + var asmjsMangle = (x) => { var unmangledSymbols = ['stackAlloc','stackSave','stackRestore','getTempRet0','setTempRet0']; if (x == '__main_argc_argv') { x = 'main'; } - return x.indexOf('dynCall_') == 0 || unmangledSymbols.includes(x) ? x : '_' + x; - } - Module["asmjsMangle"] = asmjsMangle; + return x.startsWith('dynCall_') || unmangledSymbols.includes(x) ? x : '_' + x; + }; + Module['asmjsMangle'] = asmjsMangle; @@ -17186,10 +18468,11 @@ var ASM_CONSTS = { var ___global_base = 1024; - Module["___global_base"] = ___global_base; + Module['___global_base'] = ___global_base; - function __emscripten_fs_load_embedded_files(ptr) { + + var __emscripten_fs_load_embedded_files = (ptr) => { do { var name_addr = HEAPU32[((ptr)>>2)]; ptr += 4; @@ -17202,13 +18485,13 @@ var ASM_CONSTS = { // canOwn this data in the filesystem, it is a slice of wasm memory that will never change FS.createDataFile(name, null, HEAP8.subarray(content, content + len), true, true, true); } while (HEAPU32[((ptr)>>2)]); - } - Module["__emscripten_fs_load_embedded_files"] = __emscripten_fs_load_embedded_files; + }; + Module['__emscripten_fs_load_embedded_files'] = __emscripten_fs_load_embedded_files; __emscripten_fs_load_embedded_files.sig = 'vp'; var POINTER_SIZE = 4; - Module["POINTER_SIZE"] = POINTER_SIZE; + Module['POINTER_SIZE'] = POINTER_SIZE; function getNativeTypeSize(type) { switch (type) { case 'i1': case 'i8': case 'u8': return 1; @@ -17223,98 +18506,55 @@ var ASM_CONSTS = { } if (type[0] === 'i') { const bits = Number(type.substr(1)); - assert(bits % 8 === 0, 'getNativeTypeSize invalid bits ' + bits + ', type ' + type); + assert(bits % 8 === 0, `getNativeTypeSize invalid bits ${bits}, ${type} type`); return bits / 8; } return 0; } } } - Module["getNativeTypeSize"] = getNativeTypeSize; + Module['getNativeTypeSize'] = getNativeTypeSize; + + var STACK_SIZE = 65536; - Module["STACK_SIZE"] = STACK_SIZE; + Module['STACK_SIZE'] = STACK_SIZE; var STACK_ALIGN = 16; - Module["STACK_ALIGN"] = STACK_ALIGN; + Module['STACK_ALIGN'] = STACK_ALIGN; var ASSERTIONS = 1; - Module["ASSERTIONS"] = ASSERTIONS; - - - function writeI53ToI64Clamped(ptr, num) { - if (num > 0x7FFFFFFFFFFFFFFF) { - HEAPU32[ptr>>2] = 0xFFFFFFFF; - HEAPU32[ptr+4>>2] = 0x7FFFFFFF; - } else if (num < -0x8000000000000000) { - HEAPU32[ptr>>2] = 0; - HEAPU32[ptr+4>>2] = 0x80000000; - } else { - HEAPU32[ptr>>2] = num; - HEAPU32[ptr+4>>2] = (num - HEAPU32[ptr>>2])/4294967296; - } - } - Module["writeI53ToI64Clamped"] = writeI53ToI64Clamped; - - function writeI53ToI64Signaling(ptr, num) { - if (num > 0x7FFFFFFFFFFFFFFF || num < -0x8000000000000000) { - throw 'RangeError in writeI53ToI64Signaling(): input value ' + num + ' is out of range of int64'; - } - HEAPU32[ptr>>2] = num; - HEAPU32[ptr+4>>2] = (num - HEAPU32[ptr>>2])/4294967296; - } - Module["writeI53ToI64Signaling"] = writeI53ToI64Signaling; - - function writeI53ToU64Clamped(ptr, num) { - if (num > 0xFFFFFFFFFFFFFFFF) HEAPU32[ptr>>2] = HEAPU32[ptr+4>>2] = 0xFFFFFFFF; - else if (num < 0) HEAPU32[ptr>>2] = HEAPU32[ptr+4>>2] = 0; - else { - HEAPU32[ptr>>2] = num; - HEAPU32[ptr+4>>2] = (num - HEAPU32[ptr>>2])/4294967296; - } - } - Module["writeI53ToU64Clamped"] = writeI53ToU64Clamped; - - function writeI53ToU64Signaling(ptr, num) { - if (num < 0 || num > 0xFFFFFFFFFFFFFFFF) { - throw 'RangeError in writeI53ToU64Signaling(): input value ' + num + ' is out of range of uint64'; - } - HEAPU32[ptr>>2] = num; - HEAPU32[ptr+4>>2] = (num - HEAPU32[ptr>>2])/4294967296; - } - Module["writeI53ToU64Signaling"] = writeI53ToU64Signaling; + Module['ASSERTIONS'] = ASSERTIONS; - - - - - - function getCFunc(ident) { + var getCFunc = (ident) => { var func = Module['_' + ident]; // closure exported function assert(func, 'Cannot call unknown function ' + ident + ', make sure it is exported'); return func; - } - Module["getCFunc"] = getCFunc; + }; + Module['getCFunc'] = getCFunc; + + + + + /** * @param {string|null=} returnType * @param {Array=} argTypes * @param {Arguments|Array=} args * @param {Object=} opts */ - function ccall(ident, returnType, argTypes, args, opts) { + var ccall = (ident, returnType, argTypes, args, opts) => { // For fast lookup of conversion functions var toC = { 'string': (str) => { var ret = 0; if (str !== null && str !== undefined && str !== 0) { // null string // at most 4 bytes per UTF-8 code point, +1 for the trailing '\0' - var len = (str.length << 2) + 1; - ret = stackAlloc(len); - stringToUTF8(str, ret, len); + ret = stringToUTF8OnStack(str); } return ret; }, @@ -17349,7 +18589,7 @@ var ASM_CONSTS = { } } } - var ret = func.apply(null, cArgs); + var ret = func(...cArgs); function onDone(ret) { if (stack !== 0) stackRestore(stack); return convertReturnValue(ret); @@ -17357,8 +18597,8 @@ var ASM_CONSTS = { ret = onDone(ret); return ret; - } - Module["ccall"] = ccall; + }; + Module['ccall'] = ccall; @@ -17367,12 +18607,10 @@ var ASM_CONSTS = { * @param {Array=} argTypes * @param {Object=} opts */ - function cwrap(ident, returnType, argTypes, opts) { - return function() { - return ccall(ident, returnType, argTypes, arguments, opts); - } - } - Module["cwrap"] = cwrap; + var cwrap = (ident, returnType, argTypes, opts) => { + return (...args) => ccall(ident, returnType, argTypes, args, opts); + }; + Module['cwrap'] = cwrap; @@ -17387,11 +18625,13 @@ var ASM_CONSTS = { - function removeFunction(index) { + + var removeFunction = (index) => { functionsInTableMap.delete(getWasmTableEntry(index)); + setWasmTableEntry(index, null); freeTableIndexes.push(index); - } - Module["removeFunction"] = removeFunction; + }; + Module['removeFunction'] = removeFunction; @@ -17400,143 +18640,125 @@ var ASM_CONSTS = { - function _emscripten_math_cbrt(x) { - return Math.cbrt(x); - } - Module["_emscripten_math_cbrt"] = _emscripten_math_cbrt; + var _emscripten_math_cbrt = (x) => Math.cbrt(x); + Module['_emscripten_math_cbrt'] = _emscripten_math_cbrt; + _emscripten_math_cbrt.sig = 'dd'; - function _emscripten_math_pow(x, y) { - return Math.pow(x, y); - } - Module["_emscripten_math_pow"] = _emscripten_math_pow; + var _emscripten_math_pow = (x, y) => Math.pow(x, y); + Module['_emscripten_math_pow'] = _emscripten_math_pow; + _emscripten_math_pow.sig = 'ddd'; - function _emscripten_math_random() { - return Math.random(); - } - Module["_emscripten_math_random"] = _emscripten_math_random; + var _emscripten_math_random = () => Math.random(); + Module['_emscripten_math_random'] = _emscripten_math_random; + _emscripten_math_random.sig = 'd'; - function _emscripten_math_sign(x) { - return Math.sign(x); - } - Module["_emscripten_math_sign"] = _emscripten_math_sign; + var _emscripten_math_sign = (x) => Math.sign(x); + Module['_emscripten_math_sign'] = _emscripten_math_sign; + _emscripten_math_sign.sig = 'dd'; - function _emscripten_math_sqrt(x) { - return Math.sqrt(x); - } - Module["_emscripten_math_sqrt"] = _emscripten_math_sqrt; + var _emscripten_math_sqrt = (x) => Math.sqrt(x); + Module['_emscripten_math_sqrt'] = _emscripten_math_sqrt; + _emscripten_math_sqrt.sig = 'dd'; - function _emscripten_math_exp(x) { - return Math.exp(x); - } - Module["_emscripten_math_exp"] = _emscripten_math_exp; + var _emscripten_math_exp = (x) => Math.exp(x); + Module['_emscripten_math_exp'] = _emscripten_math_exp; + _emscripten_math_exp.sig = 'dd'; - function _emscripten_math_expm1(x) { - return Math.expm1(x); - } - Module["_emscripten_math_expm1"] = _emscripten_math_expm1; + var _emscripten_math_expm1 = (x) => Math.expm1(x); + Module['_emscripten_math_expm1'] = _emscripten_math_expm1; + _emscripten_math_expm1.sig = 'dd'; - function _emscripten_math_fmod(x, y) { - return x % y; - } - Module["_emscripten_math_fmod"] = _emscripten_math_fmod; + var _emscripten_math_fmod = (x, y) => x % y; + Module['_emscripten_math_fmod'] = _emscripten_math_fmod; + _emscripten_math_fmod.sig = 'ddd'; - function _emscripten_math_log(x) { - return Math.log(x); - } - Module["_emscripten_math_log"] = _emscripten_math_log; + var _emscripten_math_log = (x) => Math.log(x); + Module['_emscripten_math_log'] = _emscripten_math_log; + _emscripten_math_log.sig = 'dd'; - function _emscripten_math_log1p(x) { - return Math.log1p(x); - } - Module["_emscripten_math_log1p"] = _emscripten_math_log1p; + var _emscripten_math_log1p = (x) => Math.log1p(x); + Module['_emscripten_math_log1p'] = _emscripten_math_log1p; + _emscripten_math_log1p.sig = 'dd'; - function _emscripten_math_log10(x) { - return Math.log10(x); - } - Module["_emscripten_math_log10"] = _emscripten_math_log10; + var _emscripten_math_log10 = (x) => Math.log10(x); + Module['_emscripten_math_log10'] = _emscripten_math_log10; + _emscripten_math_log10.sig = 'dd'; - function _emscripten_math_log2(x) { - return Math.log2(x); - } - Module["_emscripten_math_log2"] = _emscripten_math_log2; + var _emscripten_math_log2 = (x) => Math.log2(x); + Module['_emscripten_math_log2'] = _emscripten_math_log2; + _emscripten_math_log2.sig = 'dd'; - function _emscripten_math_round(x) { - return Math.round(x); - } - Module["_emscripten_math_round"] = _emscripten_math_round; + var _emscripten_math_round = (x) => Math.round(x); + Module['_emscripten_math_round'] = _emscripten_math_round; + _emscripten_math_round.sig = 'dd'; - function _emscripten_math_acos(x) { - return Math.acos(x); - } - Module["_emscripten_math_acos"] = _emscripten_math_acos; + var _emscripten_math_acos = (x) => Math.acos(x); + Module['_emscripten_math_acos'] = _emscripten_math_acos; + _emscripten_math_acos.sig = 'dd'; - function _emscripten_math_acosh(x) { - return Math.acosh(x); - } - Module["_emscripten_math_acosh"] = _emscripten_math_acosh; + var _emscripten_math_acosh = (x) => Math.acosh(x); + Module['_emscripten_math_acosh'] = _emscripten_math_acosh; + _emscripten_math_acosh.sig = 'dd'; - function _emscripten_math_asin(x) { - return Math.asin(x); - } - Module["_emscripten_math_asin"] = _emscripten_math_asin; + var _emscripten_math_asin = (x) => Math.asin(x); + Module['_emscripten_math_asin'] = _emscripten_math_asin; + _emscripten_math_asin.sig = 'dd'; - function _emscripten_math_asinh(x) { - return Math.asinh(x); - } - Module["_emscripten_math_asinh"] = _emscripten_math_asinh; + var _emscripten_math_asinh = (x) => Math.asinh(x); + Module['_emscripten_math_asinh'] = _emscripten_math_asinh; + _emscripten_math_asinh.sig = 'dd'; - function _emscripten_math_atan(x) { - return Math.atan(x); - } - Module["_emscripten_math_atan"] = _emscripten_math_atan; + var _emscripten_math_atan = (x) => Math.atan(x); + Module['_emscripten_math_atan'] = _emscripten_math_atan; + _emscripten_math_atan.sig = 'dd'; - function _emscripten_math_atanh(x) { - return Math.atanh(x); - } - Module["_emscripten_math_atanh"] = _emscripten_math_atanh; + var _emscripten_math_atanh = (x) => Math.atanh(x); + Module['_emscripten_math_atanh'] = _emscripten_math_atanh; + _emscripten_math_atanh.sig = 'dd'; - function _emscripten_math_atan2(y, x) { - return Math.atan2(y, x); - } - Module["_emscripten_math_atan2"] = _emscripten_math_atan2; + var _emscripten_math_atan2 = (y, x) => Math.atan2(y, x); + Module['_emscripten_math_atan2'] = _emscripten_math_atan2; + _emscripten_math_atan2.sig = 'ddd'; - function _emscripten_math_cos(x) { - return Math.cos(x); - } - Module["_emscripten_math_cos"] = _emscripten_math_cos; + var _emscripten_math_cos = (x) => Math.cos(x); + Module['_emscripten_math_cos'] = _emscripten_math_cos; + _emscripten_math_cos.sig = 'dd'; - function _emscripten_math_cosh(x) { - return Math.cosh(x); - } - Module["_emscripten_math_cosh"] = _emscripten_math_cosh; + var _emscripten_math_cosh = (x) => Math.cosh(x); + Module['_emscripten_math_cosh'] = _emscripten_math_cosh; + _emscripten_math_cosh.sig = 'dd'; - function _emscripten_math_hypot(count, varargs) { + var _emscripten_math_hypot = (count, varargs) => { var args = []; - for (var i = 0; i < count; ++i) args.push(HEAPF64[(varargs>>3) + i]); - return Math.hypot.apply(null, args); - } - Module["_emscripten_math_hypot"] = _emscripten_math_hypot; - _emscripten_math_hypot.sig = 'iip'; + for (var i = 0; i < count; ++i) { + args.push(HEAPF64[(((varargs)+(i * 8))>>3)]); + } + return Math.hypot(...args); + }; + Module['_emscripten_math_hypot'] = _emscripten_math_hypot; + _emscripten_math_hypot.sig = 'dip'; + + var _emscripten_math_sin = (x) => Math.sin(x); + Module['_emscripten_math_sin'] = _emscripten_math_sin; + _emscripten_math_sin.sig = 'dd'; + + var _emscripten_math_sinh = (x) => Math.sinh(x); + Module['_emscripten_math_sinh'] = _emscripten_math_sinh; + _emscripten_math_sinh.sig = 'dd'; + + var _emscripten_math_tan = (x) => Math.tan(x); + Module['_emscripten_math_tan'] = _emscripten_math_tan; + _emscripten_math_tan.sig = 'dd'; + + var _emscripten_math_tanh = (x) => Math.tanh(x); + Module['_emscripten_math_tanh'] = _emscripten_math_tanh; + _emscripten_math_tanh.sig = 'dd'; + + - function _emscripten_math_sin(x) { - return Math.sin(x); - } - Module["_emscripten_math_sin"] = _emscripten_math_sin; - function _emscripten_math_sinh(x) { - return Math.sinh(x); - } - Module["_emscripten_math_sinh"] = _emscripten_math_sinh; - function _emscripten_math_tan(x) { - return Math.tan(x); - } - Module["_emscripten_math_tan"] = _emscripten_math_tan; - function _emscripten_math_tanh(x) { - return Math.tanh(x); - } - Module["_emscripten_math_tanh"] = _emscripten_math_tanh; @@ -17546,34 +18768,30 @@ var ASM_CONSTS = { for (var i = 0; i < array.length; i++) { var chr = array[i]; if (chr > 0xFF) { - assert(false, 'Character code ' + chr + ' (' + String.fromCharCode(chr) + ') at offset ' + i + ' not in 0x00-0xFF.'); + assert(false, `Character code ${chr} (${String.fromCharCode(chr)}) at offset ${i} not in 0x00-0xFF.`); chr &= 0xFF; } ret.push(String.fromCharCode(chr)); } return ret.join(''); } - Module["intArrayToString"] = intArrayToString; + Module['intArrayToString'] = intArrayToString; - function AsciiToString(ptr) { + var AsciiToString = (ptr) => { var str = ''; while (1) { - var ch = HEAPU8[((ptr++)>>0)]; + var ch = HEAPU8[ptr++]; if (!ch) return str; str += String.fromCharCode(ch); } - } - Module["AsciiToString"] = AsciiToString; + }; + Module['AsciiToString'] = AsciiToString; - function stringToAscii(str, outPtr) { - return writeAsciiToMemory(str, outPtr, false); - } - Module["stringToAscii"] = stringToAscii; var UTF16Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder('utf-16le') : undefined;; - Module["UTF16Decoder"] = UTF16Decoder; + Module['UTF16Decoder'] = UTF16Decoder; - function UTF16ToString(ptr, maxBytesToRead) { + var UTF16ToString = (ptr, maxBytesToRead) => { assert(ptr % 2 == 0, 'Pointer passed to UTF16ToString must be aligned to two bytes!'); var endPtr = ptr; // TextDecoder needs to know the byte length in advance, it doesn't stop on @@ -17605,16 +18823,14 @@ var ASM_CONSTS = { } return str; - } - Module["UTF16ToString"] = UTF16ToString; + }; + Module['UTF16ToString'] = UTF16ToString; - function stringToUTF16(str, outPtr, maxBytesToWrite) { + var stringToUTF16 = (str, outPtr, maxBytesToWrite) => { assert(outPtr % 2 == 0, 'Pointer passed to stringToUTF16 must be aligned to two bytes!'); assert(typeof maxBytesToWrite == 'number', 'stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!'); // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed. - if (maxBytesToWrite === undefined) { - maxBytesToWrite = 0x7FFFFFFF; - } + maxBytesToWrite ??= 0x7FFFFFFF; if (maxBytesToWrite < 2) return 0; maxBytesToWrite -= 2; // Null terminator. var startPtr = outPtr; @@ -17628,15 +18844,15 @@ var ASM_CONSTS = { // Null-terminate the pointer to the HEAP. HEAP16[((outPtr)>>1)] = 0; return outPtr - startPtr; - } - Module["stringToUTF16"] = stringToUTF16; + }; + Module['stringToUTF16'] = stringToUTF16; - function lengthBytesUTF16(str) { + var lengthBytesUTF16 = (str) => { return str.length*2; - } - Module["lengthBytesUTF16"] = lengthBytesUTF16; + }; + Module['lengthBytesUTF16'] = lengthBytesUTF16; - function UTF32ToString(ptr, maxBytesToRead) { + var UTF32ToString = (ptr, maxBytesToRead) => { assert(ptr % 4 == 0, 'Pointer passed to UTF32ToString must be aligned to four bytes!'); var i = 0; @@ -17657,16 +18873,14 @@ var ASM_CONSTS = { } } return str; - } - Module["UTF32ToString"] = UTF32ToString; + }; + Module['UTF32ToString'] = UTF32ToString; - function stringToUTF32(str, outPtr, maxBytesToWrite) { + var stringToUTF32 = (str, outPtr, maxBytesToWrite) => { assert(outPtr % 4 == 0, 'Pointer passed to stringToUTF32 must be aligned to four bytes!'); assert(typeof maxBytesToWrite == 'number', 'stringToUTF32(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!'); // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed. - if (maxBytesToWrite === undefined) { - maxBytesToWrite = 0x7FFFFFFF; - } + maxBytesToWrite ??= 0x7FFFFFFF; if (maxBytesToWrite < 4) return 0; var startPtr = outPtr; var endPtr = startPtr + maxBytesToWrite - 4; @@ -17685,10 +18899,10 @@ var ASM_CONSTS = { // Null-terminate the pointer to the HEAP. HEAP32[((outPtr)>>2)] = 0; return outPtr - startPtr; - } - Module["stringToUTF32"] = stringToUTF32; + }; + Module['stringToUTF32'] = stringToUTF32; - function lengthBytesUTF32(str) { + var lengthBytesUTF32 = (str) => { var len = 0; for (var i = 0; i < str.length; ++i) { // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! We must decode the string to UTF-32 to the heap. @@ -17699,115 +18913,22 @@ var ASM_CONSTS = { } return len; - } - Module["lengthBytesUTF32"] = lengthBytesUTF32; - - - - /** @deprecated @param {boolean=} dontAddNull */ - function writeStringToMemory(string, buffer, dontAddNull) { - warnOnce('writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!'); - - var /** @type {number} */ lastChar, /** @type {number} */ end; - if (dontAddNull) { - // stringToUTF8Array always appends null. If we don't want to do that, remember the - // character that existed at the location where the null will be placed, and restore - // that after the write (below). - end = buffer + lengthBytesUTF8(string); - lastChar = HEAP8[end]; - } - stringToUTF8(string, buffer, Infinity); - if (dontAddNull) HEAP8[end] = lastChar; // Restore the value under the null character. - } - Module["writeStringToMemory"] = writeStringToMemory; - - - - - - - - - function ___syscall_rename(old_path, new_path) { - try { - - old_path = SYSCALLS.getStr(old_path); - new_path = SYSCALLS.getStr(new_path); - FS.rename(old_path, new_path); - return 0; - } catch (e) { - if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; - return -e.errno; - } - } - Module["___syscall_rename"] = ___syscall_rename; - ___syscall_rename.sig = 'ipp'; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + }; + Module['lengthBytesUTF32'] = lengthBytesUTF32; - var JSEvents = {inEventHandler:0,removeAllEventListeners:function() { - for (var i = JSEvents.eventHandlers.length-1; i >= 0; --i) { - JSEvents._removeHandler(i); + var JSEvents = { + removeAllEventListeners() { + while (JSEvents.eventHandlers.length) { + JSEvents._removeHandler(JSEvents.eventHandlers.length - 1); } - JSEvents.eventHandlers = []; JSEvents.deferredCalls = []; - },registerRemoveEventListeners:function() { - if (!JSEvents.removeEventListenersRegistered) { - __ATEXIT__.push(JSEvents.removeAllEventListeners); - JSEvents.removeEventListenersRegistered = true; - } - },deferredCalls:[],deferCall:function(targetFunction, precedence, argsList) { + }, + inEventHandler:0, + deferredCalls:[], + deferCall(targetFunction, precedence, argsList) { function arraysHaveEqualContent(arrA, arrB) { if (arrA.length != arrB.length) return false; @@ -17824,22 +18945,34 @@ var ASM_CONSTS = { } } JSEvents.deferredCalls.push({ - targetFunction: targetFunction, - precedence: precedence, - argsList: argsList + targetFunction, + precedence, + argsList }); - JSEvents.deferredCalls.sort(function(x,y) { return x.precedence < y.precedence; }); - },removeDeferredCalls:function(targetFunction) { + JSEvents.deferredCalls.sort((x,y) => x.precedence < y.precedence); + }, + removeDeferredCalls(targetFunction) { for (var i = 0; i < JSEvents.deferredCalls.length; ++i) { if (JSEvents.deferredCalls[i].targetFunction == targetFunction) { JSEvents.deferredCalls.splice(i, 1); --i; } } - },canPerformEventHandlerRequests:function() { + }, + canPerformEventHandlerRequests() { + if (navigator.userActivation) { + // Verify against transient activation status from UserActivation API + // whether it is possible to perform a request here without needing to defer. See + // https://developer.mozilla.org/en-US/docs/Web/Security/User_activation#transient_activation + // and https://caniuse.com/mdn-api_useractivation + // At the time of writing, Firefox does not support this API: https://bugzilla.mozilla.org/show_bug.cgi?id=1791079 + return navigator.userActivation.isActive; + } + return JSEvents.inEventHandler && JSEvents.currentEventHandler.allowsDeferredCalls; - },runDeferredCalls:function() { + }, + runDeferredCalls() { if (!JSEvents.canPerformEventHandlerRequests()) { return; } @@ -17847,39 +18980,48 @@ var ASM_CONSTS = { var call = JSEvents.deferredCalls[i]; JSEvents.deferredCalls.splice(i, 1); --i; - call.targetFunction.apply(null, call.argsList); + call.targetFunction(...call.argsList); } - },eventHandlers:[],removeAllHandlersOnTarget:function(target, eventTypeString) { + }, + eventHandlers:[], + removeAllHandlersOnTarget:(target, eventTypeString) => { for (var i = 0; i < JSEvents.eventHandlers.length; ++i) { - if (JSEvents.eventHandlers[i].target == target && + if (JSEvents.eventHandlers[i].target == target && (!eventTypeString || eventTypeString == JSEvents.eventHandlers[i].eventTypeString)) { JSEvents._removeHandler(i--); } } - },_removeHandler:function(i) { + }, + _removeHandler(i) { var h = JSEvents.eventHandlers[i]; h.target.removeEventListener(h.eventTypeString, h.eventListenerFunc, h.useCapture); JSEvents.eventHandlers.splice(i, 1); - },registerOrRemoveHandler:function(eventHandler) { - var jsEventHandler = function jsEventHandler(event) { - // Increment nesting count for the event handler. - ++JSEvents.inEventHandler; - JSEvents.currentEventHandler = eventHandler; - // Process any old deferred calls the user has placed. - JSEvents.runDeferredCalls(); - // Process the actual event, calls back to user C code handler. - eventHandler.handlerFunc(event); - // Process any new deferred calls that were placed right now from this event handler. - JSEvents.runDeferredCalls(); - // Out of event handler - restore nesting count. - --JSEvents.inEventHandler; - }; - + }, + registerOrRemoveHandler(eventHandler) { + if (!eventHandler.target) { + err('registerOrRemoveHandler: the target element for event handler registration does not exist, when processing the following event handler registration:'); + console.dir(eventHandler); + return -4; + } if (eventHandler.callbackfunc) { - eventHandler.eventListenerFunc = jsEventHandler; - eventHandler.target.addEventListener(eventHandler.eventTypeString, jsEventHandler, eventHandler.useCapture); + eventHandler.eventListenerFunc = function(event) { + // Increment nesting count for the event handler. + ++JSEvents.inEventHandler; + JSEvents.currentEventHandler = eventHandler; + // Process any old deferred calls the user has placed. + JSEvents.runDeferredCalls(); + // Process the actual event, calls back to user C code handler. + eventHandler.handlerFunc(event); + // Process any new deferred calls that were placed right now from this event handler. + JSEvents.runDeferredCalls(); + // Out of event handler - restore nesting count. + --JSEvents.inEventHandler; + }; + + eventHandler.target.addEventListener(eventHandler.eventTypeString, + eventHandler.eventListenerFunc, + eventHandler.useCapture); JSEvents.eventHandlers.push(eventHandler); - JSEvents.registerRemoveEventListeners(); } else { for (var i = 0; i < JSEvents.eventHandlers.length; ++i) { if (JSEvents.eventHandlers[i].target == eventHandler.target @@ -17888,49 +19030,56 @@ var ASM_CONSTS = { } } } - },getNodeNameForTarget:function(target) { + return 0; + }, + getNodeNameForTarget(target) { if (!target) return ''; if (target == window) return '#window'; if (target == screen) return '#screen'; - return (target && target.nodeName) ? target.nodeName : ''; - },fullscreenEnabled:function() { + return target?.nodeName || ''; + }, + fullscreenEnabled() { return document.fullscreenEnabled // Safari 13.0.3 on macOS Catalina 10.15.1 still ships with prefixed webkitFullscreenEnabled. // TODO: If Safari at some point ships with unprefixed version, update the version check above. || document.webkitFullscreenEnabled ; - }}; - Module["JSEvents"] = JSEvents; + }, + }; + Module['JSEvents'] = JSEvents; - function maybeCStringToJsString(cString) { + var maybeCStringToJsString = (cString) => { // "cString > 2" checks if the input is a number, and isn't of the special // values we accept here, EMSCRIPTEN_EVENT_TARGET_* (which map to 0, 1, 2). // In other words, if cString > 2 then it's a pointer to a valid place in // memory, and points to a C string. return cString > 2 ? UTF8ToString(cString) : cString; - } - Module["maybeCStringToJsString"] = maybeCStringToJsString; + }; + Module['maybeCStringToJsString'] = maybeCStringToJsString; + /** @type {Object} */ var specialHTMLTargets = [0, typeof document != 'undefined' ? document : 0, typeof window != 'undefined' ? window : 0]; - Module["specialHTMLTargets"] = specialHTMLTargets; - function findEventTarget(target) { + Module['specialHTMLTargets'] = specialHTMLTargets; + var findEventTarget = (target) => { target = maybeCStringToJsString(target); var domElement = specialHTMLTargets[target] || (typeof document != 'undefined' ? document.querySelector(target) : undefined); return domElement; - } - Module["findEventTarget"] = findEventTarget; + }; + Module['findEventTarget'] = findEventTarget; + + - function registerKeyEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { - if (!JSEvents.keyEvent) JSEvents.keyEvent = _malloc( 176 ); + var registerKeyEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { + if (!JSEvents.keyEvent) JSEvents.keyEvent = _malloc(176); - var keyEventHandlerFunc = function(e) { + var keyEventHandlerFunc = (e) => { assert(e); var keyEventData = JSEvents.keyEvent; HEAPF64[((keyEventData)>>3)] = e.timeStamp; - var idx = keyEventData >> 2; + var idx =((keyEventData)>>2); HEAP32[idx + 2] = e.location; HEAP32[idx + 3] = e.ctrlKey; @@ -17951,54 +19100,45 @@ var ASM_CONSTS = { var eventHandler = { target: findEventTarget(target), - allowsDeferredCalls: true, - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + eventTypeString, + callbackfunc, handlerFunc: keyEventHandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerKeyEventCallback"] = registerKeyEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerKeyEventCallback'] = registerKeyEventCallback; - function findCanvasEventTarget(target) { return findEventTarget(target); } - Module["findCanvasEventTarget"] = findCanvasEventTarget; + var findCanvasEventTarget = findEventTarget; + Module['findCanvasEventTarget'] = findCanvasEventTarget; - function _emscripten_set_keypress_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_keypress_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerKeyEventCallback(target, userData, useCapture, callbackfunc, 1, "keypress", targetThread); - return 0; - } - Module["_emscripten_set_keypress_callback_on_thread"] = _emscripten_set_keypress_callback_on_thread; - _emscripten_set_keypress_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_keypress_callback_on_thread'] = _emscripten_set_keypress_callback_on_thread; + _emscripten_set_keypress_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_keydown_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_keydown_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerKeyEventCallback(target, userData, useCapture, callbackfunc, 2, "keydown", targetThread); - return 0; - } - Module["_emscripten_set_keydown_callback_on_thread"] = _emscripten_set_keydown_callback_on_thread; - _emscripten_set_keydown_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_keydown_callback_on_thread'] = _emscripten_set_keydown_callback_on_thread; + _emscripten_set_keydown_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_keyup_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_keyup_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerKeyEventCallback(target, userData, useCapture, callbackfunc, 3, "keyup", targetThread); - return 0; - } - Module["_emscripten_set_keyup_callback_on_thread"] = _emscripten_set_keyup_callback_on_thread; - _emscripten_set_keyup_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_keyup_callback_on_thread'] = _emscripten_set_keyup_callback_on_thread; + _emscripten_set_keyup_callback_on_thread.sig = 'ippipp'; - function getBoundingClientRect(e) { - return specialHTMLTargets.indexOf(e) < 0 ? e.getBoundingClientRect() : {'left':0,'top':0}; - } - Module["getBoundingClientRect"] = getBoundingClientRect; + var getBoundingClientRect = (e) => specialHTMLTargets.indexOf(e) < 0 ? e.getBoundingClientRect() : {'left':0,'top':0}; + Module['getBoundingClientRect'] = getBoundingClientRect; - function fillMouseEventData(eventStruct, e, target) { + var fillMouseEventData = (eventStruct, e, target) => { assert(eventStruct % 4 == 0); HEAPF64[((eventStruct)>>3)] = e.timeStamp; - var idx = eventStruct >> 2; + var idx = ((eventStruct)>>2); HEAP32[idx + 2] = e.screenX; HEAP32[idx + 3] = e.screenY; HEAP32[idx + 4] = e.clientX; @@ -18016,21 +19156,23 @@ var ASM_CONSTS = { HEAP32[idx + 12] = e["movementY"] ; + // Note: rect contains doubles (truncated to placate SAFE_HEAP, which is the same behaviour when writing to HEAP32 anyway) var rect = getBoundingClientRect(target); - HEAP32[idx + 13] = e.clientX - rect.left; - HEAP32[idx + 14] = e.clientY - rect.top; + HEAP32[idx + 13] = e.clientX - (rect.left | 0); + HEAP32[idx + 14] = e.clientY - (rect.top | 0); - } - Module["fillMouseEventData"] = fillMouseEventData; + }; + Module['fillMouseEventData'] = fillMouseEventData; - function registerMouseEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { - if (!JSEvents.mouseEvent) JSEvents.mouseEvent = _malloc( 72 ); + + var registerMouseEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { + if (!JSEvents.mouseEvent) JSEvents.mouseEvent = _malloc(72); target = findEventTarget(target); - var mouseEventHandlerFunc = function(e = event) { + var mouseEventHandlerFunc = (e = event) => { // TODO: Make this access thread safe, or this could update live while app is reading it. fillMouseEventData(JSEvents.mouseEvent, e, target); @@ -18038,99 +19180,82 @@ var ASM_CONSTS = { }; var eventHandler = { - target: target, + target, allowsDeferredCalls: eventTypeString != 'mousemove' && eventTypeString != 'mouseenter' && eventTypeString != 'mouseleave', // Mouse move events do not allow fullscreen/pointer lock requests to be handled in them! - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + eventTypeString, + callbackfunc, handlerFunc: mouseEventHandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerMouseEventCallback"] = registerMouseEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerMouseEventCallback'] = registerMouseEventCallback; - function _emscripten_set_click_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_click_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerMouseEventCallback(target, userData, useCapture, callbackfunc, 4, "click", targetThread); - return 0; - } - Module["_emscripten_set_click_callback_on_thread"] = _emscripten_set_click_callback_on_thread; - _emscripten_set_click_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_click_callback_on_thread'] = _emscripten_set_click_callback_on_thread; + _emscripten_set_click_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_mousedown_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_mousedown_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerMouseEventCallback(target, userData, useCapture, callbackfunc, 5, "mousedown", targetThread); - return 0; - } - Module["_emscripten_set_mousedown_callback_on_thread"] = _emscripten_set_mousedown_callback_on_thread; - _emscripten_set_mousedown_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_mousedown_callback_on_thread'] = _emscripten_set_mousedown_callback_on_thread; + _emscripten_set_mousedown_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_mouseup_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_mouseup_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerMouseEventCallback(target, userData, useCapture, callbackfunc, 6, "mouseup", targetThread); - return 0; - } - Module["_emscripten_set_mouseup_callback_on_thread"] = _emscripten_set_mouseup_callback_on_thread; - _emscripten_set_mouseup_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_mouseup_callback_on_thread'] = _emscripten_set_mouseup_callback_on_thread; + _emscripten_set_mouseup_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_dblclick_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_dblclick_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerMouseEventCallback(target, userData, useCapture, callbackfunc, 7, "dblclick", targetThread); - return 0; - } - Module["_emscripten_set_dblclick_callback_on_thread"] = _emscripten_set_dblclick_callback_on_thread; - _emscripten_set_dblclick_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_dblclick_callback_on_thread'] = _emscripten_set_dblclick_callback_on_thread; + _emscripten_set_dblclick_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_mousemove_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_mousemove_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerMouseEventCallback(target, userData, useCapture, callbackfunc, 8, "mousemove", targetThread); - return 0; - } - Module["_emscripten_set_mousemove_callback_on_thread"] = _emscripten_set_mousemove_callback_on_thread; - _emscripten_set_mousemove_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_mousemove_callback_on_thread'] = _emscripten_set_mousemove_callback_on_thread; + _emscripten_set_mousemove_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_mouseenter_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_mouseenter_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerMouseEventCallback(target, userData, useCapture, callbackfunc, 33, "mouseenter", targetThread); - return 0; - } - Module["_emscripten_set_mouseenter_callback_on_thread"] = _emscripten_set_mouseenter_callback_on_thread; - _emscripten_set_mouseenter_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_mouseenter_callback_on_thread'] = _emscripten_set_mouseenter_callback_on_thread; + _emscripten_set_mouseenter_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_mouseleave_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_mouseleave_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerMouseEventCallback(target, userData, useCapture, callbackfunc, 34, "mouseleave", targetThread); - return 0; - } - Module["_emscripten_set_mouseleave_callback_on_thread"] = _emscripten_set_mouseleave_callback_on_thread; - _emscripten_set_mouseleave_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_mouseleave_callback_on_thread'] = _emscripten_set_mouseleave_callback_on_thread; + _emscripten_set_mouseleave_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_mouseover_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_mouseover_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerMouseEventCallback(target, userData, useCapture, callbackfunc, 35, "mouseover", targetThread); - return 0; - } - Module["_emscripten_set_mouseover_callback_on_thread"] = _emscripten_set_mouseover_callback_on_thread; - _emscripten_set_mouseover_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_mouseover_callback_on_thread'] = _emscripten_set_mouseover_callback_on_thread; + _emscripten_set_mouseover_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_mouseout_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_mouseout_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerMouseEventCallback(target, userData, useCapture, callbackfunc, 36, "mouseout", targetThread); - return 0; - } - Module["_emscripten_set_mouseout_callback_on_thread"] = _emscripten_set_mouseout_callback_on_thread; - _emscripten_set_mouseout_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_mouseout_callback_on_thread'] = _emscripten_set_mouseout_callback_on_thread; + _emscripten_set_mouseout_callback_on_thread.sig = 'ippipp'; - function _emscripten_get_mouse_status(mouseState) { + var _emscripten_get_mouse_status = (mouseState) => { if (!JSEvents.mouseEvent) return -7; // HTML5 does not really have a polling API for mouse events, so implement one manually by // returning the data from the most recently received event. This requires that user has registered // at least some no-op function as an event handler to any of the mouse function. HEAP8.set(HEAP8.subarray(JSEvents.mouseEvent, JSEvents.mouseEvent + 72), mouseState); return 0; - } - Module["_emscripten_get_mouse_status"] = _emscripten_get_mouse_status; - _emscripten_get_mouse_status.sig = 'ii'; + }; + Module['_emscripten_get_mouse_status'] = _emscripten_get_mouse_status; + _emscripten_get_mouse_status.sig = 'ip'; - function registerWheelEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { - if (!JSEvents.wheelEvent) JSEvents.wheelEvent = _malloc( 104 ); + + var registerWheelEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { + if (!JSEvents.wheelEvent) JSEvents.wheelEvent = _malloc(104); // The DOM Level 3 events spec event 'wheel' - var wheelHandlerFunc = function(e = event) { + var wheelHandlerFunc = (e = event) => { var wheelEvent = JSEvents.wheelEvent; fillMouseEventData(wheelEvent, e, target); HEAPF64[(((wheelEvent)+(72))>>3)] = e["deltaX"]; @@ -18141,39 +19266,40 @@ var ASM_CONSTS = { }; var eventHandler = { - target: target, + target, allowsDeferredCalls: true, - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + eventTypeString, + callbackfunc, handlerFunc: wheelHandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerWheelEventCallback"] = registerWheelEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerWheelEventCallback'] = registerWheelEventCallback; - function _emscripten_set_wheel_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_wheel_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => { target = findEventTarget(target); + if (!target) return -4; if (typeof target.onwheel != 'undefined') { - registerWheelEventCallback(target, userData, useCapture, callbackfunc, 9, "wheel", targetThread); - return 0; + return registerWheelEventCallback(target, userData, useCapture, callbackfunc, 9, "wheel", targetThread); } else { return -1; } - } - Module["_emscripten_set_wheel_callback_on_thread"] = _emscripten_set_wheel_callback_on_thread; - _emscripten_set_wheel_callback_on_thread.sig = 'iiiiii'; + }; + Module['_emscripten_set_wheel_callback_on_thread'] = _emscripten_set_wheel_callback_on_thread; + _emscripten_set_wheel_callback_on_thread.sig = 'ippipp'; - function registerUiEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { - if (!JSEvents.uiEvent) JSEvents.uiEvent = _malloc( 36 ); + + var registerUiEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { + if (!JSEvents.uiEvent) JSEvents.uiEvent = _malloc(36); target = findEventTarget(target); - var uiEventHandlerFunc = function(e = event) { + var uiEventHandlerFunc = (e = event) => { if (e.target != target) { // Never take ui events such as scroll via a 'bubbled' route, but always from the direct element that // was targeted. Otherwise e.g. if app logs a message in response to a page scroll, the Emscripten log @@ -18187,49 +19313,47 @@ var ASM_CONSTS = { return; } var uiEvent = JSEvents.uiEvent; - HEAP32[((uiEvent)>>2)] = e.detail; + HEAP32[((uiEvent)>>2)] = 0; // always zero for resize and scroll HEAP32[(((uiEvent)+(4))>>2)] = b.clientWidth; HEAP32[(((uiEvent)+(8))>>2)] = b.clientHeight; HEAP32[(((uiEvent)+(12))>>2)] = innerWidth; HEAP32[(((uiEvent)+(16))>>2)] = innerHeight; HEAP32[(((uiEvent)+(20))>>2)] = outerWidth; HEAP32[(((uiEvent)+(24))>>2)] = outerHeight; - HEAP32[(((uiEvent)+(28))>>2)] = pageXOffset; - HEAP32[(((uiEvent)+(32))>>2)] = pageYOffset; + HEAP32[(((uiEvent)+(28))>>2)] = pageXOffset | 0; // scroll offsets are float + HEAP32[(((uiEvent)+(32))>>2)] = pageYOffset | 0; if (getWasmTableEntry(callbackfunc)(eventTypeId, uiEvent, userData)) e.preventDefault(); }; var eventHandler = { - target: target, - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + target, + eventTypeString, + callbackfunc, handlerFunc: uiEventHandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerUiEventCallback"] = registerUiEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerUiEventCallback'] = registerUiEventCallback; - function _emscripten_set_resize_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_resize_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerUiEventCallback(target, userData, useCapture, callbackfunc, 10, "resize", targetThread); - return 0; - } - Module["_emscripten_set_resize_callback_on_thread"] = _emscripten_set_resize_callback_on_thread; - _emscripten_set_resize_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_resize_callback_on_thread'] = _emscripten_set_resize_callback_on_thread; + _emscripten_set_resize_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_scroll_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_scroll_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerUiEventCallback(target, userData, useCapture, callbackfunc, 11, "scroll", targetThread); - return 0; - } - Module["_emscripten_set_scroll_callback_on_thread"] = _emscripten_set_scroll_callback_on_thread; - _emscripten_set_scroll_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_scroll_callback_on_thread'] = _emscripten_set_scroll_callback_on_thread; + _emscripten_set_scroll_callback_on_thread.sig = 'ippipp'; - function registerFocusEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { - if (!JSEvents.focusEvent) JSEvents.focusEvent = _malloc( 256 ); - var focusEventHandlerFunc = function(e = event) { + + var registerFocusEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { + if (!JSEvents.focusEvent) JSEvents.focusEvent = _malloc(256); + + var focusEventHandlerFunc = (e = event) => { var nodeName = JSEvents.getNodeNameForTarget(e.target); var id = e.target.id ? e.target.id : ''; @@ -18242,58 +19366,50 @@ var ASM_CONSTS = { var eventHandler = { target: findEventTarget(target), - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + eventTypeString, + callbackfunc, handlerFunc: focusEventHandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerFocusEventCallback"] = registerFocusEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerFocusEventCallback'] = registerFocusEventCallback; - function _emscripten_set_blur_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_blur_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerFocusEventCallback(target, userData, useCapture, callbackfunc, 12, "blur", targetThread); - return 0; - } - Module["_emscripten_set_blur_callback_on_thread"] = _emscripten_set_blur_callback_on_thread; - _emscripten_set_blur_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_blur_callback_on_thread'] = _emscripten_set_blur_callback_on_thread; + _emscripten_set_blur_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_focus_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_focus_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerFocusEventCallback(target, userData, useCapture, callbackfunc, 13, "focus", targetThread); - return 0; - } - Module["_emscripten_set_focus_callback_on_thread"] = _emscripten_set_focus_callback_on_thread; - _emscripten_set_focus_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_focus_callback_on_thread'] = _emscripten_set_focus_callback_on_thread; + _emscripten_set_focus_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_focusin_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_focusin_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerFocusEventCallback(target, userData, useCapture, callbackfunc, 14, "focusin", targetThread); - return 0; - } - Module["_emscripten_set_focusin_callback_on_thread"] = _emscripten_set_focusin_callback_on_thread; - _emscripten_set_focusin_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_focusin_callback_on_thread'] = _emscripten_set_focusin_callback_on_thread; + _emscripten_set_focusin_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_focusout_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_focusout_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerFocusEventCallback(target, userData, useCapture, callbackfunc, 15, "focusout", targetThread); - return 0; - } - Module["_emscripten_set_focusout_callback_on_thread"] = _emscripten_set_focusout_callback_on_thread; - _emscripten_set_focusout_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_focusout_callback_on_thread'] = _emscripten_set_focusout_callback_on_thread; + _emscripten_set_focusout_callback_on_thread.sig = 'ippipp'; - function fillDeviceOrientationEventData(eventStruct, e, target) { + var fillDeviceOrientationEventData = (eventStruct, e, target) => { HEAPF64[((eventStruct)>>3)] = e.alpha; HEAPF64[(((eventStruct)+(8))>>3)] = e.beta; HEAPF64[(((eventStruct)+(16))>>3)] = e.gamma; HEAP32[(((eventStruct)+(24))>>2)] = e.absolute; - } - Module["fillDeviceOrientationEventData"] = fillDeviceOrientationEventData; + }; + Module['fillDeviceOrientationEventData'] = fillDeviceOrientationEventData; - function registerDeviceOrientationEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { - if (!JSEvents.deviceOrientationEvent) JSEvents.deviceOrientationEvent = _malloc( 32 ); + var registerDeviceOrientationEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { + if (!JSEvents.deviceOrientationEvent) JSEvents.deviceOrientationEvent = _malloc(32); - var deviceOrientationEventHandlerFunc = function(e = event) { + var deviceOrientationEventHandlerFunc = (e = event) => { fillDeviceOrientationEventData(JSEvents.deviceOrientationEvent, e, target); // TODO: Thread-safety with respect to emscripten_get_deviceorientation_status() if (getWasmTableEntry(callbackfunc)(eventTypeId, JSEvents.deviceOrientationEvent, userData)) e.preventDefault(); @@ -18301,35 +19417,34 @@ var ASM_CONSTS = { var eventHandler = { target: findEventTarget(target), - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + eventTypeString, + callbackfunc, handlerFunc: deviceOrientationEventHandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerDeviceOrientationEventCallback"] = registerDeviceOrientationEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerDeviceOrientationEventCallback'] = registerDeviceOrientationEventCallback; - function _emscripten_set_deviceorientation_callback_on_thread(userData, useCapture, callbackfunc, targetThread) { - registerDeviceOrientationEventCallback(2, userData, useCapture, callbackfunc, 16, "deviceorientation", targetThread); - return 0; - } - Module["_emscripten_set_deviceorientation_callback_on_thread"] = _emscripten_set_deviceorientation_callback_on_thread; - _emscripten_set_deviceorientation_callback_on_thread.sig = 'iiiii'; + var _emscripten_set_deviceorientation_callback_on_thread = (userData, useCapture, callbackfunc, targetThread) => { + return registerDeviceOrientationEventCallback(2, userData, useCapture, callbackfunc, 16, "deviceorientation", targetThread); + }; + Module['_emscripten_set_deviceorientation_callback_on_thread'] = _emscripten_set_deviceorientation_callback_on_thread; + _emscripten_set_deviceorientation_callback_on_thread.sig = 'ipipp'; - function _emscripten_get_deviceorientation_status(orientationState) { + var _emscripten_get_deviceorientation_status = (orientationState) => { if (!JSEvents.deviceOrientationEvent) return -7; // HTML5 does not really have a polling API for device orientation events, so implement one manually by // returning the data from the most recently received event. This requires that user has registered // at least some no-op function as an event handler. HEAP32.set(HEAP32.subarray(JSEvents.deviceOrientationEvent, 32), orientationState); return 0; - } - Module["_emscripten_get_deviceorientation_status"] = _emscripten_get_deviceorientation_status; - _emscripten_get_deviceorientation_status.sig = 'ii'; + }; + Module['_emscripten_get_deviceorientation_status'] = _emscripten_get_deviceorientation_status; + _emscripten_get_deviceorientation_status.sig = 'ip'; - function fillDeviceMotionEventData(eventStruct, e, target) { + var fillDeviceMotionEventData = (eventStruct, e, target) => { var supportedFields = 0; var a = e['acceleration']; supportedFields |= a && 1; @@ -18349,16 +19464,17 @@ var ASM_CONSTS = { HEAPF64[(((eventStruct)+(48))>>3)] = rr["alpha"]; HEAPF64[(((eventStruct)+(56))>>3)] = rr["beta"]; HEAPF64[(((eventStruct)+(64))>>3)] = rr["gamma"]; - } - Module["fillDeviceMotionEventData"] = fillDeviceMotionEventData; + }; + Module['fillDeviceMotionEventData'] = fillDeviceMotionEventData; - function registerDeviceMotionEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { - if (!JSEvents.deviceMotionEvent) JSEvents.deviceMotionEvent = _malloc( 80 ); - var deviceMotionEventHandlerFunc = function(e = event) { + var registerDeviceMotionEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { + if (!JSEvents.deviceMotionEvent) JSEvents.deviceMotionEvent = _malloc(80); + + var deviceMotionEventHandlerFunc = (e = event) => { fillDeviceMotionEventData(JSEvents.deviceMotionEvent, e, target); // TODO: Thread-safety with respect to emscripten_get_devicemotion_status() if (getWasmTableEntry(callbackfunc)(eventTypeId, JSEvents.deviceMotionEvent, userData)) e.preventDefault(); @@ -18366,61 +19482,75 @@ var ASM_CONSTS = { var eventHandler = { target: findEventTarget(target), - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + eventTypeString, + callbackfunc, handlerFunc: deviceMotionEventHandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerDeviceMotionEventCallback"] = registerDeviceMotionEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerDeviceMotionEventCallback'] = registerDeviceMotionEventCallback; - function _emscripten_set_devicemotion_callback_on_thread(userData, useCapture, callbackfunc, targetThread) { - registerDeviceMotionEventCallback(2, userData, useCapture, callbackfunc, 17, "devicemotion", targetThread); - return 0; - } - Module["_emscripten_set_devicemotion_callback_on_thread"] = _emscripten_set_devicemotion_callback_on_thread; - _emscripten_set_devicemotion_callback_on_thread.sig = 'iiiii'; + var _emscripten_set_devicemotion_callback_on_thread = (userData, useCapture, callbackfunc, targetThread) => { + return registerDeviceMotionEventCallback(2, userData, useCapture, callbackfunc, 17, "devicemotion", targetThread); + }; + Module['_emscripten_set_devicemotion_callback_on_thread'] = _emscripten_set_devicemotion_callback_on_thread; + _emscripten_set_devicemotion_callback_on_thread.sig = 'ipipp'; - function _emscripten_get_devicemotion_status(motionState) { + var _emscripten_get_devicemotion_status = (motionState) => { if (!JSEvents.deviceMotionEvent) return -7; // HTML5 does not really have a polling API for device motion events, so implement one manually by // returning the data from the most recently received event. This requires that user has registered // at least some no-op function as an event handler. HEAP32.set(HEAP32.subarray(JSEvents.deviceMotionEvent, 80), motionState); return 0; - } - Module["_emscripten_get_devicemotion_status"] = _emscripten_get_devicemotion_status; - _emscripten_get_devicemotion_status.sig = 'ii'; + }; + Module['_emscripten_get_devicemotion_status'] = _emscripten_get_devicemotion_status; + _emscripten_get_devicemotion_status.sig = 'ip'; - function screenOrientation() { - if (!screen) return undefined; - return screen.orientation || screen.mozOrientation || screen.webkitOrientation || screen.msOrientation; - } - Module["screenOrientation"] = screenOrientation; + var screenOrientation = () => { + if (!window.screen) return undefined; + return screen.orientation || screen['mozOrientation'] || screen['webkitOrientation']; + }; + Module['screenOrientation'] = screenOrientation; - function fillOrientationChangeEventData(eventStruct) { - var orientations = ["portrait-primary", "portrait-secondary", "landscape-primary", "landscape-secondary"]; - var orientations2 = ["portrait", "portrait", "landscape", "landscape"]; + var fillOrientationChangeEventData = (eventStruct) => { + // OrientationType enum + var orientationsType1 = ['portrait-primary', 'portrait-secondary', 'landscape-primary', 'landscape-secondary']; + // alternative selection from OrientationLockType enum + var orientationsType2 = ['portrait', 'portrait', 'landscape', 'landscape']; - var orientationString = screenOrientation(); - var orientation = orientations.indexOf(orientationString); - if (orientation == -1) { - orientation = orientations2.indexOf(orientationString); + var orientationIndex = 0; + var orientationAngle = 0; + var screenOrientObj = screenOrientation(); + if (typeof screenOrientObj === 'object') { + orientationIndex = orientationsType1.indexOf(screenOrientObj.type); + if (orientationIndex < 0) { + orientationIndex = orientationsType2.indexOf(screenOrientObj.type); + } + if (orientationIndex >= 0) { + orientationIndex = 1 << orientationIndex; + } + orientationAngle = screenOrientObj.angle; + } + else { + // fallback for Safari earlier than 16.4 (March 2023) + orientationAngle = window.orientation; } - HEAP32[((eventStruct)>>2)] = 1 << orientation; - HEAP32[(((eventStruct)+(4))>>2)] = orientation; - } - Module["fillOrientationChangeEventData"] = fillOrientationChangeEventData; + HEAP32[((eventStruct)>>2)] = orientationIndex; + HEAP32[(((eventStruct)+(4))>>2)] = orientationAngle; + }; + Module['fillOrientationChangeEventData'] = fillOrientationChangeEventData; - function registerOrientationChangeEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { - if (!JSEvents.orientationChangeEvent) JSEvents.orientationChangeEvent = _malloc( 8 ); - var orientationChangeEventHandlerFunc = function(e = event) { + var registerOrientationChangeEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { + if (!JSEvents.orientationChangeEvent) JSEvents.orientationChangeEvent = _malloc(8); + + var orientationChangeEventHandlerFunc = (e = event) => { var orientationChangeEvent = JSEvents.orientationChangeEvent; fillOrientationChangeEventData(orientationChangeEvent); @@ -18428,39 +19558,35 @@ var ASM_CONSTS = { if (getWasmTableEntry(callbackfunc)(eventTypeId, orientationChangeEvent, userData)) e.preventDefault(); }; - if (eventTypeString == "orientationchange" && screen.mozOrientation !== undefined) { - eventTypeString = "mozorientationchange"; - } - var eventHandler = { - target: target, - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + target, + eventTypeString, + callbackfunc, handlerFunc: orientationChangeEventHandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerOrientationChangeEventCallback"] = registerOrientationChangeEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerOrientationChangeEventCallback'] = registerOrientationChangeEventCallback; - function _emscripten_set_orientationchange_callback_on_thread(userData, useCapture, callbackfunc, targetThread) { - if (!screen || !screen['addEventListener']) return -1; - registerOrientationChangeEventCallback(screen, userData, useCapture, callbackfunc, 18, "orientationchange", targetThread); - return 0; - } - Module["_emscripten_set_orientationchange_callback_on_thread"] = _emscripten_set_orientationchange_callback_on_thread; - _emscripten_set_orientationchange_callback_on_thread.sig = 'iiiii'; + var _emscripten_set_orientationchange_callback_on_thread = (userData, useCapture, callbackfunc, targetThread) => { + if (!window.screen || !screen.orientation) return -1; + return registerOrientationChangeEventCallback(screen.orientation, userData, useCapture, callbackfunc, 18, 'change', targetThread); + }; + Module['_emscripten_set_orientationchange_callback_on_thread'] = _emscripten_set_orientationchange_callback_on_thread; + _emscripten_set_orientationchange_callback_on_thread.sig = 'ipipp'; - function _emscripten_get_orientation_status(orientationChangeEvent) { + var _emscripten_get_orientation_status = (orientationChangeEvent) => { + // screenOrientation() resolving standard, window.orientation being the deprecated mobile-only if (!screenOrientation() && typeof orientation == 'undefined') return -1; fillOrientationChangeEventData(orientationChangeEvent); return 0; - } - Module["_emscripten_get_orientation_status"] = _emscripten_get_orientation_status; - _emscripten_get_orientation_status.sig = 'ii'; + }; + Module['_emscripten_get_orientation_status'] = _emscripten_get_orientation_status; + _emscripten_get_orientation_status.sig = 'ip'; - function _emscripten_lock_orientation(allowedOrientations) { + var _emscripten_lock_orientation = (allowedOrientations) => { var orientations = []; if (allowedOrientations & 1) orientations.push("portrait-primary"); if (allowedOrientations & 2) orientations.push("portrait-secondary"); @@ -18473,8 +19599,6 @@ var ASM_CONSTS = { succeeded = screen.mozLockOrientation(orientations); } else if (screen.webkitLockOrientation) { succeeded = screen.webkitLockOrientation(orientations); - } else if (screen.msLockOrientation) { - succeeded = screen.msLockOrientation(orientations); } else { return -1; } @@ -18482,28 +19606,27 @@ var ASM_CONSTS = { return 0; } return -6; - } - Module["_emscripten_lock_orientation"] = _emscripten_lock_orientation; + }; + Module['_emscripten_lock_orientation'] = _emscripten_lock_orientation; _emscripten_lock_orientation.sig = 'ii'; - function _emscripten_unlock_orientation() { + var _emscripten_unlock_orientation = () => { if (screen.unlockOrientation) { screen.unlockOrientation(); } else if (screen.mozUnlockOrientation) { screen.mozUnlockOrientation(); } else if (screen.webkitUnlockOrientation) { screen.webkitUnlockOrientation(); - } else if (screen.msUnlockOrientation) { - screen.msUnlockOrientation(); } else { return -1; } return 0; - } - Module["_emscripten_unlock_orientation"] = _emscripten_unlock_orientation; + }; + Module['_emscripten_unlock_orientation'] = _emscripten_unlock_orientation; _emscripten_unlock_orientation.sig = 'i'; - function fillFullscreenChangeEventData(eventStruct) { + + var fillFullscreenChangeEventData = (eventStruct) => { var fullscreenElement = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement; var isFullscreen = !!fullscreenElement; // Assigning a boolean to HEAP32 with expected type coercion. @@ -18514,7 +19637,7 @@ var ASM_CONSTS = { // If transitioning to windowed mode, report info about the element that just was fullscreen. var reportedElement = isFullscreen ? fullscreenElement : JSEvents.previousFullscreenElement; var nodeName = JSEvents.getNodeNameForTarget(reportedElement); - var id = (reportedElement && reportedElement.id) ? reportedElement.id : ''; + var id = reportedElement?.id || ''; stringToUTF8(nodeName, eventStruct + 8, 128); stringToUTF8(id, eventStruct + 136, 128); HEAP32[(((eventStruct)+(264))>>2)] = reportedElement ? reportedElement.clientWidth : 0; @@ -18524,16 +19647,17 @@ var ASM_CONSTS = { if (isFullscreen) { JSEvents.previousFullscreenElement = fullscreenElement; } - } - Module["fillFullscreenChangeEventData"] = fillFullscreenChangeEventData; + }; + Module['fillFullscreenChangeEventData'] = fillFullscreenChangeEventData; - function registerFullscreenChangeEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { - if (!JSEvents.fullscreenChangeEvent) JSEvents.fullscreenChangeEvent = _malloc( 280 ); - var fullscreenChangeEventhandlerFunc = function(e = event) { + var registerFullscreenChangeEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { + if (!JSEvents.fullscreenChangeEvent) JSEvents.fullscreenChangeEvent = _malloc(280); + + var fullscreenChangeEventhandlerFunc = (e = event) => { var fullscreenChangeEvent = JSEvents.fullscreenChangeEvent; fillFullscreenChangeEventData(fullscreenChangeEvent); @@ -18542,97 +19666,94 @@ var ASM_CONSTS = { }; var eventHandler = { - target: target, - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + target, + eventTypeString, + callbackfunc, handlerFunc: fullscreenChangeEventhandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerFullscreenChangeEventCallback"] = registerFullscreenChangeEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerFullscreenChangeEventCallback'] = registerFullscreenChangeEventCallback; - function _emscripten_set_fullscreenchange_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_fullscreenchange_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => { if (!JSEvents.fullscreenEnabled()) return -1; target = findEventTarget(target); if (!target) return -4; - registerFullscreenChangeEventCallback(target, userData, useCapture, callbackfunc, 19, "fullscreenchange", targetThread); // Unprefixed Fullscreen API shipped in Chromium 71 (https://bugs.chromium.org/p/chromium/issues/detail?id=383813) // As of Safari 13.0.3 on macOS Catalina 10.15.1 still ships with prefixed webkitfullscreenchange. TODO: revisit this check once Safari ships unprefixed version. registerFullscreenChangeEventCallback(target, userData, useCapture, callbackfunc, 19, "webkitfullscreenchange", targetThread); - return 0; - } - Module["_emscripten_set_fullscreenchange_callback_on_thread"] = _emscripten_set_fullscreenchange_callback_on_thread; - _emscripten_set_fullscreenchange_callback_on_thread.sig = 'iiiiii'; + return registerFullscreenChangeEventCallback(target, userData, useCapture, callbackfunc, 19, "fullscreenchange", targetThread); + }; + Module['_emscripten_set_fullscreenchange_callback_on_thread'] = _emscripten_set_fullscreenchange_callback_on_thread; + _emscripten_set_fullscreenchange_callback_on_thread.sig = 'ippipp'; - function _emscripten_get_fullscreen_status(fullscreenStatus) { + var _emscripten_get_fullscreen_status = (fullscreenStatus) => { if (!JSEvents.fullscreenEnabled()) return -1; fillFullscreenChangeEventData(fullscreenStatus); return 0; - } - Module["_emscripten_get_fullscreen_status"] = _emscripten_get_fullscreen_status; - _emscripten_get_fullscreen_status.sig = 'ii'; + }; + Module['_emscripten_get_fullscreen_status'] = _emscripten_get_fullscreen_status; + _emscripten_get_fullscreen_status.sig = 'ip'; - function _emscripten_get_canvas_element_size(target, width, height) { + var _emscripten_get_canvas_element_size = (target, width, height) => { var canvas = findCanvasEventTarget(target); if (!canvas) return -4; HEAP32[((width)>>2)] = canvas.width; HEAP32[((height)>>2)] = canvas.height; - } - Module["_emscripten_get_canvas_element_size"] = _emscripten_get_canvas_element_size; + }; + Module['_emscripten_get_canvas_element_size'] = _emscripten_get_canvas_element_size; _emscripten_get_canvas_element_size.sig = 'ippp'; - function getCanvasElementSize(target) { - return withStackSave(function() { - var w = stackAlloc(8); - var h = w + 4; - var targetInt = stackAlloc(target.id.length+1); - stringToUTF8(target.id, targetInt, target.id.length+1); - var ret = _emscripten_get_canvas_element_size(targetInt, w, h); - var size = [HEAP32[((w)>>2)], HEAP32[((h)>>2)]]; - return size; - }); - } - Module["getCanvasElementSize"] = getCanvasElementSize; + var getCanvasElementSize = (target) => withStackSave(() => { + var w = stackAlloc(8); + var h = w + 4; + + var targetInt = stringToUTF8OnStack(target.id); + var ret = _emscripten_get_canvas_element_size(targetInt, w, h); + var size = [HEAP32[((w)>>2)], HEAP32[((h)>>2)]]; + return size; + }); + Module['getCanvasElementSize'] = getCanvasElementSize; - function _emscripten_set_canvas_element_size(target, width, height) { + var _emscripten_set_canvas_element_size = (target, width, height) => { var canvas = findCanvasEventTarget(target); if (!canvas) return -4; canvas.width = width; canvas.height = height; return 0; - } - Module["_emscripten_set_canvas_element_size"] = _emscripten_set_canvas_element_size; - _emscripten_set_canvas_element_size.sig = 'iiii'; + }; + Module['_emscripten_set_canvas_element_size'] = _emscripten_set_canvas_element_size; + _emscripten_set_canvas_element_size.sig = 'ipii'; - function setCanvasElementSize(target, width, height) { + + var setCanvasElementSize = (target, width, height) => { if (!target.controlTransferredOffscreen) { target.width = width; target.height = height; } else { // This function is being called from high-level JavaScript code instead of asm.js/Wasm, // and it needs to synchronously proxy over to another thread, so marshal the string onto the heap to do the call. - withStackSave(function() { - var targetInt = stackAlloc(target.id.length+1); - stringToUTF8(target.id, targetInt, target.id.length+1); + withStackSave(() => { + var targetInt = stringToUTF8OnStack(target.id); _emscripten_set_canvas_element_size(targetInt, width, height); }); } - } - Module["setCanvasElementSize"] = setCanvasElementSize; + }; + Module['setCanvasElementSize'] = setCanvasElementSize; - function registerRestoreOldStyle(canvas) { + var registerRestoreOldStyle = (canvas) => { var canvasSize = getCanvasElementSize(canvas); var oldWidth = canvasSize[0]; var oldHeight = canvasSize[1]; @@ -18699,19 +19820,19 @@ var ASM_CONSTS = { // As of Safari 13.0.3 on macOS Catalina 10.15.1 still ships with prefixed webkitfullscreenchange. TODO: revisit this check once Safari ships unprefixed version. document.addEventListener('webkitfullscreenchange', restoreOldStyle); return restoreOldStyle; - } - Module["registerRestoreOldStyle"] = registerRestoreOldStyle; + }; + Module['registerRestoreOldStyle'] = registerRestoreOldStyle; - function setLetterbox(element, topBottom, leftRight) { - // Cannot use margin to specify letterboxes in FF or Chrome, since those ignore margins in fullscreen mode. - element.style.paddingLeft = element.style.paddingRight = leftRight + 'px'; - element.style.paddingTop = element.style.paddingBottom = topBottom + 'px'; - } - Module["setLetterbox"] = setLetterbox; + var setLetterbox = (element, topBottom, leftRight) => { + // Cannot use margin to specify letterboxes in FF or Chrome, since those ignore margins in fullscreen mode. + element.style.paddingLeft = element.style.paddingRight = leftRight + 'px'; + element.style.paddingTop = element.style.paddingBottom = topBottom + 'px'; + }; + Module['setLetterbox'] = setLetterbox; - function JSEvents_resizeCanvasForFullscreen(target, strategy) { + var JSEvents_resizeCanvasForFullscreen = (target, strategy) => { var restoreOldStyle = registerRestoreOldStyle(target); var cssWidth = strategy.softFullscreen ? innerWidth : screen.width; var cssHeight = strategy.softFullscreen ? innerHeight : screen.height; @@ -18766,10 +19887,10 @@ var ASM_CONSTS = { if (target.GLctxObject) target.GLctxObject.GLctx.viewport(0, 0, newWidth, newHeight); } return restoreOldStyle; - } - Module["JSEvents_resizeCanvasForFullscreen"] = JSEvents_resizeCanvasForFullscreen; + }; + Module['JSEvents_resizeCanvasForFullscreen'] = JSEvents_resizeCanvasForFullscreen; - function JSEvents_requestFullscreen(target, strategy) { + var JSEvents_requestFullscreen = (target, strategy) => { // EMSCRIPTEN_FULLSCREEN_SCALE_DEFAULT + EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_NONE is a mode where no extra logic is performed to the DOM elements. if (strategy.scaleMode != 0 || strategy.canvasResolutionScaleMode != 0) { JSEvents_resizeCanvasForFullscreen(target, strategy); @@ -18790,12 +19911,12 @@ var ASM_CONSTS = { } return 0; - } - Module["JSEvents_requestFullscreen"] = JSEvents_requestFullscreen; + }; + Module['JSEvents_requestFullscreen'] = JSEvents_requestFullscreen; - function hideEverythingExceptGivenElement(onlyVisibleElement) { + var hideEverythingExceptGivenElement = (onlyVisibleElement) => { var child = onlyVisibleElement; var parent = child.parentNode; var hiddenElements = []; @@ -18811,22 +19932,23 @@ var ASM_CONSTS = { parent = parent.parentNode; } return hiddenElements; - } - Module["hideEverythingExceptGivenElement"] = hideEverythingExceptGivenElement; + }; + Module['hideEverythingExceptGivenElement'] = hideEverythingExceptGivenElement; - function restoreHiddenElements(hiddenElements) { + var restoreHiddenElements = (hiddenElements) => { for (var i = 0; i < hiddenElements.length; ++i) { hiddenElements[i].node.style.display = hiddenElements[i].displayState; } - } - Module["restoreHiddenElements"] = restoreHiddenElements; + }; + Module['restoreHiddenElements'] = restoreHiddenElements; - var currentFullscreenStrategy = {}; - Module["currentFullscreenStrategy"] = currentFullscreenStrategy; + var currentFullscreenStrategy = { + }; + Module['currentFullscreenStrategy'] = currentFullscreenStrategy; var restoreOldWindowedStyle = null; - Module["restoreOldWindowedStyle"] = restoreOldWindowedStyle; + Module['restoreOldWindowedStyle'] = restoreOldWindowedStyle; @@ -18834,7 +19956,7 @@ var ASM_CONSTS = { - function softFullscreenResizeWebGLRenderTarget() { + var softFullscreenResizeWebGLRenderTarget = () => { var dpr = devicePixelRatio; var inHiDPIFullscreenMode = currentFullscreenStrategy.canvasResolutionScaleMode == 2; var inAspectRatioFixedFullscreenMode = currentFullscreenStrategy.scaleMode == 2; @@ -18886,8 +20008,8 @@ var ASM_CONSTS = { if (!inCenteredWithoutScalingFullscreenMode && currentFullscreenStrategy.canvasResizedCallback) { getWasmTableEntry(currentFullscreenStrategy.canvasResizedCallback)(37, 0, currentFullscreenStrategy.canvasResizedCallbackUserData); } - } - Module["softFullscreenResizeWebGLRenderTarget"] = softFullscreenResizeWebGLRenderTarget; + }; + Module['softFullscreenResizeWebGLRenderTarget'] = softFullscreenResizeWebGLRenderTarget; @@ -18896,7 +20018,7 @@ var ASM_CONSTS = { - function doRequestFullscreen(target, strategy) { + var doRequestFullscreen = (target, strategy) => { if (!JSEvents.fullscreenEnabled()) return -1; target = findEventTarget(target); if (!target) return -4; @@ -18919,39 +20041,39 @@ var ASM_CONSTS = { } return JSEvents_requestFullscreen(target, strategy); - } - Module["doRequestFullscreen"] = doRequestFullscreen; + }; + Module['doRequestFullscreen'] = doRequestFullscreen; - function _emscripten_request_fullscreen(target, deferUntilInEventHandler) { + var _emscripten_request_fullscreen = (target, deferUntilInEventHandler) => { var strategy = { // These options perform no added logic, but just bare request fullscreen. scaleMode: 0, canvasResolutionScaleMode: 0, filteringMode: 0, - deferUntilInEventHandler: deferUntilInEventHandler, + deferUntilInEventHandler, canvasResizedCallbackTargetThread: 2 }; return doRequestFullscreen(target, strategy); - } - Module["_emscripten_request_fullscreen"] = _emscripten_request_fullscreen; - _emscripten_request_fullscreen.sig = 'iii'; + }; + Module['_emscripten_request_fullscreen'] = _emscripten_request_fullscreen; + _emscripten_request_fullscreen.sig = 'ipi'; - function _emscripten_request_fullscreen_strategy(target, deferUntilInEventHandler, fullscreenStrategy) { + var _emscripten_request_fullscreen_strategy = (target, deferUntilInEventHandler, fullscreenStrategy) => { var strategy = { scaleMode: HEAP32[((fullscreenStrategy)>>2)], canvasResolutionScaleMode: HEAP32[(((fullscreenStrategy)+(4))>>2)], filteringMode: HEAP32[(((fullscreenStrategy)+(8))>>2)], - deferUntilInEventHandler: deferUntilInEventHandler, + deferUntilInEventHandler, canvasResizedCallback: HEAP32[(((fullscreenStrategy)+(12))>>2)], canvasResizedCallbackUserData: HEAP32[(((fullscreenStrategy)+(16))>>2)] }; return doRequestFullscreen(target, strategy); - } - Module["_emscripten_request_fullscreen_strategy"] = _emscripten_request_fullscreen_strategy; - _emscripten_request_fullscreen_strategy.sig = 'iiii'; + }; + Module['_emscripten_request_fullscreen_strategy'] = _emscripten_request_fullscreen_strategy; + _emscripten_request_fullscreen_strategy.sig = 'ipip'; @@ -18965,7 +20087,7 @@ var ASM_CONSTS = { - function _emscripten_enter_soft_fullscreen(target, fullscreenStrategy) { + var _emscripten_enter_soft_fullscreen = (target, fullscreenStrategy) => { target = findEventTarget(target); if (!target) return -4; @@ -18975,7 +20097,7 @@ var ASM_CONSTS = { filteringMode: HEAP32[(((fullscreenStrategy)+(8))>>2)], canvasResizedCallback: HEAP32[(((fullscreenStrategy)+(12))>>2)], canvasResizedCallbackUserData: HEAP32[(((fullscreenStrategy)+(16))>>2)], - target: target, + target, softFullscreen: true }; @@ -19006,23 +20128,23 @@ var ASM_CONSTS = { } return 0; - } - Module["_emscripten_enter_soft_fullscreen"] = _emscripten_enter_soft_fullscreen; - _emscripten_enter_soft_fullscreen.sig = 'iii'; + }; + Module['_emscripten_enter_soft_fullscreen'] = _emscripten_enter_soft_fullscreen; + _emscripten_enter_soft_fullscreen.sig = 'ipp'; - function _emscripten_exit_soft_fullscreen() { - if (restoreOldWindowedStyle) restoreOldWindowedStyle(); + var _emscripten_exit_soft_fullscreen = () => { + restoreOldWindowedStyle?.(); restoreOldWindowedStyle = null; return 0; - } - Module["_emscripten_exit_soft_fullscreen"] = _emscripten_exit_soft_fullscreen; + }; + Module['_emscripten_exit_soft_fullscreen'] = _emscripten_exit_soft_fullscreen; _emscripten_exit_soft_fullscreen.sig = 'i'; - function _emscripten_exit_fullscreen() { + var _emscripten_exit_fullscreen = () => { if (!JSEvents.fullscreenEnabled()) return -1; // Make sure no queued up calls will fire after this. JSEvents.removeDeferredCalls(JSEvents_requestFullscreen); @@ -19037,30 +20159,32 @@ var ASM_CONSTS = { } return 0; - } - Module["_emscripten_exit_fullscreen"] = _emscripten_exit_fullscreen; + }; + Module['_emscripten_exit_fullscreen'] = _emscripten_exit_fullscreen; _emscripten_exit_fullscreen.sig = 'i'; - function fillPointerlockChangeEventData(eventStruct) { + + var fillPointerlockChangeEventData = (eventStruct) => { var pointerLockElement = document.pointerLockElement || document.mozPointerLockElement || document.webkitPointerLockElement || document.msPointerLockElement; var isPointerlocked = !!pointerLockElement; // Assigning a boolean to HEAP32 with expected type coercion. /** @suppress{checkTypes} */ HEAP32[((eventStruct)>>2)] = isPointerlocked; var nodeName = JSEvents.getNodeNameForTarget(pointerLockElement); - var id = (pointerLockElement && pointerLockElement.id) ? pointerLockElement.id : ''; + var id = pointerLockElement?.id || ''; stringToUTF8(nodeName, eventStruct + 4, 128); stringToUTF8(id, eventStruct + 132, 128); - } - Module["fillPointerlockChangeEventData"] = fillPointerlockChangeEventData; + }; + Module['fillPointerlockChangeEventData'] = fillPointerlockChangeEventData; - function registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { - if (!JSEvents.pointerlockChangeEvent) JSEvents.pointerlockChangeEvent = _malloc( 260 ); - var pointerlockChangeEventHandlerFunc = function(e = event) { + var registerPointerlockChangeEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { + if (!JSEvents.pointerlockChangeEvent) JSEvents.pointerlockChangeEvent = _malloc(260); + + var pointerlockChangeEventHandlerFunc = (e = event) => { var pointerlockChangeEvent = JSEvents.pointerlockChangeEvent; fillPointerlockChangeEventData(pointerlockChangeEvent); @@ -19068,21 +20192,21 @@ var ASM_CONSTS = { }; var eventHandler = { - target: target, - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + target, + eventTypeString, + callbackfunc, handlerFunc: pointerlockChangeEventHandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerPointerlockChangeEventCallback"] = registerPointerlockChangeEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerPointerlockChangeEventCallback'] = registerPointerlockChangeEventCallback; /** @suppress {missingProperties} */ - function _emscripten_set_pointerlockchange_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_pointerlockchange_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => { // TODO: Currently not supported in pthreads or in --proxy-to-worker mode. (In pthreads mode, document object is not defined) if (!document || !document.body || (!document.body.requestPointerLock && !document.body.mozRequestPointerLock && !document.body.webkitRequestPointerLock && !document.body.msRequestPointerLock)) { return -1; @@ -19090,40 +20214,39 @@ var ASM_CONSTS = { target = findEventTarget(target); if (!target) return -4; - registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, 20, "pointerlockchange", targetThread); registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, 20, "mozpointerlockchange", targetThread); registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, 20, "webkitpointerlockchange", targetThread); registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, 20, "mspointerlockchange", targetThread); - return 0; - } - Module["_emscripten_set_pointerlockchange_callback_on_thread"] = _emscripten_set_pointerlockchange_callback_on_thread; - _emscripten_set_pointerlockchange_callback_on_thread.sig = 'iiiiii'; + return registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, 20, "pointerlockchange", targetThread); + }; + Module['_emscripten_set_pointerlockchange_callback_on_thread'] = _emscripten_set_pointerlockchange_callback_on_thread; + _emscripten_set_pointerlockchange_callback_on_thread.sig = 'ippipp'; - function registerPointerlockErrorEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { + var registerPointerlockErrorEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { - var pointerlockErrorEventHandlerFunc = function(e = event) { + var pointerlockErrorEventHandlerFunc = (e = event) => { if (getWasmTableEntry(callbackfunc)(eventTypeId, 0, userData)) e.preventDefault(); }; var eventHandler = { - target: target, - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + target, + eventTypeString, + callbackfunc, handlerFunc: pointerlockErrorEventHandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerPointerlockErrorEventCallback"] = registerPointerlockErrorEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerPointerlockErrorEventCallback'] = registerPointerlockErrorEventCallback; /** @suppress {missingProperties} */ - function _emscripten_set_pointerlockerror_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_pointerlockerror_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => { // TODO: Currently not supported in pthreads or in --proxy-to-worker mode. (In pthreads mode, document object is not defined) if (!document || !document.body.requestPointerLock && !document.body.mozRequestPointerLock && !document.body.webkitRequestPointerLock && !document.body.msRequestPointerLock) { return -1; @@ -19132,27 +20255,26 @@ var ASM_CONSTS = { target = findEventTarget(target); if (!target) return -4; - registerPointerlockErrorEventCallback(target, userData, useCapture, callbackfunc, 38, "pointerlockerror", targetThread); registerPointerlockErrorEventCallback(target, userData, useCapture, callbackfunc, 38, "mozpointerlockerror", targetThread); registerPointerlockErrorEventCallback(target, userData, useCapture, callbackfunc, 38, "webkitpointerlockerror", targetThread); registerPointerlockErrorEventCallback(target, userData, useCapture, callbackfunc, 38, "mspointerlockerror", targetThread); - return 0; - } - Module["_emscripten_set_pointerlockerror_callback_on_thread"] = _emscripten_set_pointerlockerror_callback_on_thread; - _emscripten_set_pointerlockerror_callback_on_thread.sig = 'iiiiii'; + return registerPointerlockErrorEventCallback(target, userData, useCapture, callbackfunc, 38, "pointerlockerror", targetThread); + }; + Module['_emscripten_set_pointerlockerror_callback_on_thread'] = _emscripten_set_pointerlockerror_callback_on_thread; + _emscripten_set_pointerlockerror_callback_on_thread.sig = 'ippipp'; /** @suppress {missingProperties} */ - function _emscripten_get_pointerlock_status(pointerlockStatus) { + var _emscripten_get_pointerlock_status = (pointerlockStatus) => { if (pointerlockStatus) fillPointerlockChangeEventData(pointerlockStatus); if (!document.body || (!document.body.requestPointerLock && !document.body.mozRequestPointerLock && !document.body.webkitRequestPointerLock && !document.body.msRequestPointerLock)) { return -1; } return 0; - } - Module["_emscripten_get_pointerlock_status"] = _emscripten_get_pointerlock_status; - _emscripten_get_pointerlock_status.sig = 'ii'; + }; + Module['_emscripten_get_pointerlock_status'] = _emscripten_get_pointerlock_status; + _emscripten_get_pointerlock_status.sig = 'ip'; - function requestPointerLock(target) { + var requestPointerLock = (target) => { if (target.requestPointerLock) { target.requestPointerLock(); } else { @@ -19165,12 +20287,12 @@ var ASM_CONSTS = { return -1; } return 0; - } - Module["requestPointerLock"] = requestPointerLock; + }; + Module['requestPointerLock'] = requestPointerLock; - function _emscripten_request_pointerlock(target, deferUntilInEventHandler) { + var _emscripten_request_pointerlock = (target, deferUntilInEventHandler) => { target = findEventTarget(target); if (!target) return -4; if (!target.requestPointerLock @@ -19190,12 +20312,12 @@ var ASM_CONSTS = { } return requestPointerLock(target); - } - Module["_emscripten_request_pointerlock"] = _emscripten_request_pointerlock; - _emscripten_request_pointerlock.sig = 'iii'; + }; + Module['_emscripten_request_pointerlock'] = _emscripten_request_pointerlock; + _emscripten_request_pointerlock.sig = 'ipi'; - function _emscripten_exit_pointerlock() { + var _emscripten_exit_pointerlock = () => { // Make sure no queued up calls will fire after this. JSEvents.removeDeferredCalls(requestPointerLock); @@ -19205,19 +20327,19 @@ var ASM_CONSTS = { return -1; } return 0; - } - Module["_emscripten_exit_pointerlock"] = _emscripten_exit_pointerlock; + }; + Module['_emscripten_exit_pointerlock'] = _emscripten_exit_pointerlock; _emscripten_exit_pointerlock.sig = 'i'; - function _emscripten_vibrate(msecs) { - if (!navigator.vibrate) return -1; + var _emscripten_vibrate = (msecs) => { + if (!navigator.vibrate) return -1; navigator.vibrate(msecs); return 0; - } - Module["_emscripten_vibrate"] = _emscripten_vibrate; + }; + Module['_emscripten_vibrate'] = _emscripten_vibrate; _emscripten_vibrate.sig = 'ii'; - function _emscripten_vibrate_pattern(msecsArray, numEntries) { + var _emscripten_vibrate_pattern = (msecsArray, numEntries) => { if (!navigator.vibrate) return -1; var vibrateList = []; @@ -19227,11 +20349,11 @@ var ASM_CONSTS = { } navigator.vibrate(vibrateList); return 0; - } - Module["_emscripten_vibrate_pattern"] = _emscripten_vibrate_pattern; - _emscripten_vibrate_pattern.sig = 'iii'; + }; + Module['_emscripten_vibrate_pattern'] = _emscripten_vibrate_pattern; + _emscripten_vibrate_pattern.sig = 'ipi'; - function fillVisibilityChangeEventData(eventStruct) { + var fillVisibilityChangeEventData = (eventStruct) => { var visibilityStates = [ "hidden", "visible", "prerender", "unloaded" ]; var visibilityState = visibilityStates.indexOf(document.visibilityState); @@ -19239,16 +20361,17 @@ var ASM_CONSTS = { /** @suppress{checkTypes} */ HEAP32[((eventStruct)>>2)] = document.hidden; HEAP32[(((eventStruct)+(4))>>2)] = visibilityState; - } - Module["fillVisibilityChangeEventData"] = fillVisibilityChangeEventData; + }; + Module['fillVisibilityChangeEventData'] = fillVisibilityChangeEventData; - function registerVisibilityChangeEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { - if (!JSEvents.visibilityChangeEvent) JSEvents.visibilityChangeEvent = _malloc( 8 ); - var visibilityChangeEventHandlerFunc = function(e = event) { + var registerVisibilityChangeEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { + if (!JSEvents.visibilityChangeEvent) JSEvents.visibilityChangeEvent = _malloc(8); + + var visibilityChangeEventHandlerFunc = (e = event) => { var visibilityChangeEvent = JSEvents.visibilityChangeEvent; fillVisibilityChangeEventData(visibilityChangeEvent); @@ -19257,49 +20380,49 @@ var ASM_CONSTS = { }; var eventHandler = { - target: target, - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + target, + eventTypeString, + callbackfunc, handlerFunc: visibilityChangeEventHandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerVisibilityChangeEventCallback"] = registerVisibilityChangeEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerVisibilityChangeEventCallback'] = registerVisibilityChangeEventCallback; - function _emscripten_set_visibilitychange_callback_on_thread(userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_visibilitychange_callback_on_thread = (userData, useCapture, callbackfunc, targetThread) => { if (!specialHTMLTargets[1]) { return -4; } - registerVisibilityChangeEventCallback(specialHTMLTargets[1], userData, useCapture, callbackfunc, 21, "visibilitychange", targetThread); - return 0; - } - Module["_emscripten_set_visibilitychange_callback_on_thread"] = _emscripten_set_visibilitychange_callback_on_thread; - _emscripten_set_visibilitychange_callback_on_thread.sig = 'iiiii'; + return registerVisibilityChangeEventCallback(specialHTMLTargets[1], userData, useCapture, callbackfunc, 21, "visibilitychange", targetThread); + }; + Module['_emscripten_set_visibilitychange_callback_on_thread'] = _emscripten_set_visibilitychange_callback_on_thread; + _emscripten_set_visibilitychange_callback_on_thread.sig = 'ipipp'; - function _emscripten_get_visibility_status(visibilityStatus) { + var _emscripten_get_visibility_status = (visibilityStatus) => { if (typeof document.visibilityState == 'undefined' && typeof document.hidden == 'undefined') { return -1; } - fillVisibilityChangeEventData(visibilityStatus); + fillVisibilityChangeEventData(visibilityStatus); return 0; - } - Module["_emscripten_get_visibility_status"] = _emscripten_get_visibility_status; - _emscripten_get_visibility_status.sig = 'ii'; + }; + Module['_emscripten_get_visibility_status'] = _emscripten_get_visibility_status; + _emscripten_get_visibility_status.sig = 'ip'; - function registerTouchEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { - if (!JSEvents.touchEvent) JSEvents.touchEvent = _malloc( 1696 ); + + var registerTouchEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { + if (!JSEvents.touchEvent) JSEvents.touchEvent = _malloc(1696); target = findEventTarget(target); - var touchEventHandlerFunc = function(e) { + var touchEventHandlerFunc = (e) => { assert(e); var t, touches = {}, et = e.touches; - // To ease marshalling different kinds of touches that browser reports (all touches are listed in e.touches, + // To ease marshalling different kinds of touches that browser reports (all touches are listed in e.touches, // only changed touches in e.changedTouches, and touches on target at a.targetTouches), mark a boolean in // each Touch object so that we can later loop only once over all touches we see to marshall over to Wasm. @@ -19323,7 +20446,7 @@ var ASM_CONSTS = { var touchEvent = JSEvents.touchEvent; HEAPF64[((touchEvent)>>3)] = e.timeStamp; - var idx = touchEvent>>2; // Pre-shift the ptr to index to HEAP32 to save code size + var idx =((touchEvent)>>2);// Pre-shift the ptr to index to HEAP32 to save code size HEAP32[idx + 3] = e.ctrlKey; HEAP32[idx + 4] = e.shiftKey; HEAP32[idx + 5] = e.altKey; @@ -19342,8 +20465,8 @@ var ASM_CONSTS = { HEAP32[idx + 6] = t.pageY; HEAP32[idx + 7] = t.isChanged; HEAP32[idx + 8] = t.onTarget; - HEAP32[idx + 9] = t.clientX - targetRect.left; - HEAP32[idx + 10] = t.clientY - targetRect.top; + HEAP32[idx + 9] = t.clientX - (targetRect.left | 0); + HEAP32[idx + 10] = t.clientY - (targetRect.top | 0); idx += 13; @@ -19357,46 +20480,38 @@ var ASM_CONSTS = { }; var eventHandler = { - target: target, + target, allowsDeferredCalls: eventTypeString == 'touchstart' || eventTypeString == 'touchend', - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + eventTypeString, + callbackfunc, handlerFunc: touchEventHandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerTouchEventCallback"] = registerTouchEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerTouchEventCallback'] = registerTouchEventCallback; - function _emscripten_set_touchstart_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_touchstart_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerTouchEventCallback(target, userData, useCapture, callbackfunc, 22, "touchstart", targetThread); - return 0; - } - Module["_emscripten_set_touchstart_callback_on_thread"] = _emscripten_set_touchstart_callback_on_thread; - _emscripten_set_touchstart_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_touchstart_callback_on_thread'] = _emscripten_set_touchstart_callback_on_thread; + _emscripten_set_touchstart_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_touchend_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_touchend_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerTouchEventCallback(target, userData, useCapture, callbackfunc, 23, "touchend", targetThread); - return 0; - } - Module["_emscripten_set_touchend_callback_on_thread"] = _emscripten_set_touchend_callback_on_thread; - _emscripten_set_touchend_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_touchend_callback_on_thread'] = _emscripten_set_touchend_callback_on_thread; + _emscripten_set_touchend_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_touchmove_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_touchmove_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerTouchEventCallback(target, userData, useCapture, callbackfunc, 24, "touchmove", targetThread); - return 0; - } - Module["_emscripten_set_touchmove_callback_on_thread"] = _emscripten_set_touchmove_callback_on_thread; - _emscripten_set_touchmove_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_touchmove_callback_on_thread'] = _emscripten_set_touchmove_callback_on_thread; + _emscripten_set_touchmove_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_touchcancel_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { + var _emscripten_set_touchcancel_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => registerTouchEventCallback(target, userData, useCapture, callbackfunc, 25, "touchcancel", targetThread); - return 0; - } - Module["_emscripten_set_touchcancel_callback_on_thread"] = _emscripten_set_touchcancel_callback_on_thread; - _emscripten_set_touchcancel_callback_on_thread.sig = 'iiiiii'; + Module['_emscripten_set_touchcancel_callback_on_thread'] = _emscripten_set_touchcancel_callback_on_thread; + _emscripten_set_touchcancel_callback_on_thread.sig = 'ippipp'; - function fillGamepadEventData(eventStruct, e) { + var fillGamepadEventData = (eventStruct, e) => { HEAPF64[((eventStruct)>>3)] = e.timestamp; for (var i = 0; i < e.axes.length; ++i) { HEAPF64[(((eventStruct+i*8)+(16))>>3)] = e.axes[i]; @@ -19423,16 +20538,17 @@ var ASM_CONSTS = { HEAP32[(((eventStruct)+(12))>>2)] = e.buttons.length; stringToUTF8(e.id, eventStruct + 1304, 64); stringToUTF8(e.mapping, eventStruct + 1368, 64); - } - Module["fillGamepadEventData"] = fillGamepadEventData; + }; + Module['fillGamepadEventData'] = fillGamepadEventData; - function registerGamepadEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { - if (!JSEvents.gamepadEvent) JSEvents.gamepadEvent = _malloc( 1432 ); - var gamepadEventHandlerFunc = function(e = event) { + var registerGamepadEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { + if (!JSEvents.gamepadEvent) JSEvents.gamepadEvent = _malloc(1432); + + var gamepadEventHandlerFunc = (e = event) => { var gamepadEvent = JSEvents.gamepadEvent; fillGamepadEventData(gamepadEvent, e["gamepad"]); @@ -19442,51 +20558,57 @@ var ASM_CONSTS = { var eventHandler = { target: findEventTarget(target), allowsDeferredCalls: true, - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + eventTypeString, + callbackfunc, handlerFunc: gamepadEventHandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerGamepadEventCallback"] = registerGamepadEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerGamepadEventCallback'] = registerGamepadEventCallback; - function _emscripten_set_gamepadconnected_callback_on_thread(userData, useCapture, callbackfunc, targetThread) { - if (!navigator.getGamepads && !navigator.webkitGetGamepads) return -1; - registerGamepadEventCallback(2, userData, useCapture, callbackfunc, 26, "gamepadconnected", targetThread); - return 0; - } - Module["_emscripten_set_gamepadconnected_callback_on_thread"] = _emscripten_set_gamepadconnected_callback_on_thread; - _emscripten_set_gamepadconnected_callback_on_thread.sig = 'iiiii'; + + /** @suppress {checkTypes} */ + var _emscripten_sample_gamepad_data = () => { + try { + if (navigator.getGamepads) return (JSEvents.lastGamepadState = navigator.getGamepads()) + ? 0 : -1; + } catch(e) { + err(`navigator.getGamepads() exists, but failed to execute with exception ${e}. Disabling Gamepad access.`); + navigator.getGamepads = null; // Disable getGamepads() so that it won't be attempted to be used again. + } + return -1; + }; + Module['_emscripten_sample_gamepad_data'] = _emscripten_sample_gamepad_data; + _emscripten_sample_gamepad_data.sig = 'i'; + var _emscripten_set_gamepadconnected_callback_on_thread = (userData, useCapture, callbackfunc, targetThread) => { + if (_emscripten_sample_gamepad_data()) return -1; + return registerGamepadEventCallback(2, userData, useCapture, callbackfunc, 26, "gamepadconnected", targetThread); + }; + Module['_emscripten_set_gamepadconnected_callback_on_thread'] = _emscripten_set_gamepadconnected_callback_on_thread; + _emscripten_set_gamepadconnected_callback_on_thread.sig = 'ipipp'; - function _emscripten_set_gamepaddisconnected_callback_on_thread(userData, useCapture, callbackfunc, targetThread) { - if (!navigator.getGamepads && !navigator.webkitGetGamepads) return -1; - registerGamepadEventCallback(2, userData, useCapture, callbackfunc, 27, "gamepaddisconnected", targetThread); - return 0; - } - Module["_emscripten_set_gamepaddisconnected_callback_on_thread"] = _emscripten_set_gamepaddisconnected_callback_on_thread; - _emscripten_set_gamepaddisconnected_callback_on_thread.sig = 'iiiii'; + + var _emscripten_set_gamepaddisconnected_callback_on_thread = (userData, useCapture, callbackfunc, targetThread) => { + if (_emscripten_sample_gamepad_data()) return -1; + return registerGamepadEventCallback(2, userData, useCapture, callbackfunc, 27, "gamepaddisconnected", targetThread); + }; + Module['_emscripten_set_gamepaddisconnected_callback_on_thread'] = _emscripten_set_gamepaddisconnected_callback_on_thread; + _emscripten_set_gamepaddisconnected_callback_on_thread.sig = 'ipipp'; - function _emscripten_sample_gamepad_data() { - return (JSEvents.lastGamepadState = (navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : null))) - ? 0 : -1; - } - Module["_emscripten_sample_gamepad_data"] = _emscripten_sample_gamepad_data; - _emscripten_sample_gamepad_data.sig = 'i'; - function _emscripten_get_num_gamepads() { + var _emscripten_get_num_gamepads = () => { if (!JSEvents.lastGamepadState) throw 'emscripten_get_num_gamepads() can only be called after having first called emscripten_sample_gamepad_data() and that function has returned EMSCRIPTEN_RESULT_SUCCESS!'; // N.B. Do not call emscripten_get_num_gamepads() unless having first called emscripten_sample_gamepad_data(), and that has returned EMSCRIPTEN_RESULT_SUCCESS. // Otherwise the following line will throw an exception. return JSEvents.lastGamepadState.length; - } - Module["_emscripten_get_num_gamepads"] = _emscripten_get_num_gamepads; + }; + Module['_emscripten_get_num_gamepads'] = _emscripten_get_num_gamepads; _emscripten_get_num_gamepads.sig = 'i'; - function _emscripten_get_gamepad_status(index, gamepadState) { + var _emscripten_get_gamepad_status = (index, gamepadState) => { if (!JSEvents.lastGamepadState) throw 'emscripten_get_gamepad_status() can only be called after having first called emscripten_sample_gamepad_data() and that function has returned EMSCRIPTEN_RESULT_SUCCESS!'; - // INVALID_PARAM is returned on a Gamepad index that never was there. if (index < 0 || index >= JSEvents.lastGamepadState.length) return -5; @@ -19498,17 +20620,18 @@ var ASM_CONSTS = { fillGamepadEventData(gamepadState, JSEvents.lastGamepadState[index]); return 0; - } - Module["_emscripten_get_gamepad_status"] = _emscripten_get_gamepad_status; - _emscripten_get_gamepad_status.sig = 'iii'; + }; + Module['_emscripten_get_gamepad_status'] = _emscripten_get_gamepad_status; + _emscripten_get_gamepad_status.sig = 'iip'; - function registerBeforeUnloadEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString) { - var beforeUnloadEventHandlerFunc = function(e = event) { + + var registerBeforeUnloadEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString) => { + var beforeUnloadEventHandlerFunc = (e = event) => { // Note: This is always called on the main browser thread, since it needs synchronously return a value! var confirmationMessage = getWasmTableEntry(callbackfunc)(eventTypeId, 0, userData); - + if (confirmationMessage) { confirmationMessage = UTF8ToString(confirmationMessage); } @@ -19521,46 +20644,45 @@ var ASM_CONSTS = { var eventHandler = { target: findEventTarget(target), - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + eventTypeString, + callbackfunc, handlerFunc: beforeUnloadEventHandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerBeforeUnloadEventCallback"] = registerBeforeUnloadEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerBeforeUnloadEventCallback'] = registerBeforeUnloadEventCallback; - function _emscripten_set_beforeunload_callback_on_thread(userData, callbackfunc, targetThread) { + var _emscripten_set_beforeunload_callback_on_thread = (userData, callbackfunc, targetThread) => { if (typeof onbeforeunload == 'undefined') return -1; // beforeunload callback can only be registered on the main browser thread, because the page will go away immediately after returning from the handler, // and there is no time to start proxying it anywhere. if (targetThread !== 1) return -5; - registerBeforeUnloadEventCallback(2, userData, true, callbackfunc, 28, "beforeunload"); - return 0; - } - Module["_emscripten_set_beforeunload_callback_on_thread"] = _emscripten_set_beforeunload_callback_on_thread; - _emscripten_set_beforeunload_callback_on_thread.sig = 'iii'; + return registerBeforeUnloadEventCallback(2, userData, true, callbackfunc, 28, "beforeunload"); + }; + Module['_emscripten_set_beforeunload_callback_on_thread'] = _emscripten_set_beforeunload_callback_on_thread; + _emscripten_set_beforeunload_callback_on_thread.sig = 'ippp'; - function fillBatteryEventData(eventStruct, e) { + var fillBatteryEventData = (eventStruct, e) => { HEAPF64[((eventStruct)>>3)] = e.chargingTime; HEAPF64[(((eventStruct)+(8))>>3)] = e.dischargingTime; HEAPF64[(((eventStruct)+(16))>>3)] = e.level; HEAP32[(((eventStruct)+(24))>>2)] = e.charging; - } - Module["fillBatteryEventData"] = fillBatteryEventData; + }; + Module['fillBatteryEventData'] = fillBatteryEventData; - function battery() { return navigator.battery || navigator.mozBattery || navigator.webkitBattery; } - Module["battery"] = battery; + var battery = () => navigator.battery || navigator.mozBattery || navigator.webkitBattery; + Module['battery'] = battery; - function registerBatteryEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { - if (!JSEvents.batteryEvent) JSEvents.batteryEvent = _malloc( 32 ); + var registerBatteryEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { + if (!JSEvents.batteryEvent) JSEvents.batteryEvent = _malloc(32); - var batteryEventHandlerFunc = function(e = event) { + var batteryEventHandlerFunc = (e = event) => { var batteryEvent = JSEvents.batteryEvent; fillBatteryEventData(batteryEvent, battery()); @@ -19569,50 +20691,47 @@ var ASM_CONSTS = { var eventHandler = { target: findEventTarget(target), - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + eventTypeString, + callbackfunc, handlerFunc: batteryEventHandlerFunc, - useCapture: useCapture + useCapture }; - JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["registerBatteryEventCallback"] = registerBatteryEventCallback; + return JSEvents.registerOrRemoveHandler(eventHandler); + }; + Module['registerBatteryEventCallback'] = registerBatteryEventCallback; - - function _emscripten_set_batterychargingchange_callback_on_thread(userData, callbackfunc, targetThread) { - if (!battery()) return -1; - registerBatteryEventCallback(battery(), userData, true, callbackfunc, 29, "chargingchange", targetThread); - return 0; - } - Module["_emscripten_set_batterychargingchange_callback_on_thread"] = _emscripten_set_batterychargingchange_callback_on_thread; - _emscripten_set_batterychargingchange_callback_on_thread.sig = 'iii'; + var _emscripten_set_batterychargingchange_callback_on_thread = (userData, callbackfunc, targetThread) => { + if (!battery()) return -1; + return registerBatteryEventCallback(battery(), userData, true, callbackfunc, 29, "chargingchange", targetThread); + }; + Module['_emscripten_set_batterychargingchange_callback_on_thread'] = _emscripten_set_batterychargingchange_callback_on_thread; + _emscripten_set_batterychargingchange_callback_on_thread.sig = 'ippp'; - - function _emscripten_set_batterylevelchange_callback_on_thread(userData, callbackfunc, targetThread) { - if (!battery()) return -1; - registerBatteryEventCallback(battery(), userData, true, callbackfunc, 30, "levelchange", targetThread); - return 0; - } - Module["_emscripten_set_batterylevelchange_callback_on_thread"] = _emscripten_set_batterylevelchange_callback_on_thread; - _emscripten_set_batterylevelchange_callback_on_thread.sig = 'iii'; + var _emscripten_set_batterylevelchange_callback_on_thread = (userData, callbackfunc, targetThread) => { + if (!battery()) return -1; + return registerBatteryEventCallback(battery(), userData, true, callbackfunc, 30, "levelchange", targetThread); + }; + Module['_emscripten_set_batterylevelchange_callback_on_thread'] = _emscripten_set_batterylevelchange_callback_on_thread; + _emscripten_set_batterylevelchange_callback_on_thread.sig = 'ippp'; - function _emscripten_get_battery_status(batteryState) { - if (!battery()) return -1; + var _emscripten_get_battery_status = (batteryState) => { + if (!battery()) return -1; fillBatteryEventData(batteryState, battery()); return 0; - } - Module["_emscripten_get_battery_status"] = _emscripten_get_battery_status; - _emscripten_get_battery_status.sig = 'ii'; + }; + Module['_emscripten_get_battery_status'] = _emscripten_get_battery_status; + _emscripten_get_battery_status.sig = 'ip'; + - function _emscripten_set_element_css_size(target, width, height) { + var _emscripten_set_element_css_size = (target, width, height) => { target = findEventTarget(target); if (!target) return -4; @@ -19620,13 +20739,13 @@ var ASM_CONSTS = { target.style.height = height + "px"; return 0; - } - Module["_emscripten_set_element_css_size"] = _emscripten_set_element_css_size; - _emscripten_set_element_css_size.sig = 'iiii'; + }; + Module['_emscripten_set_element_css_size'] = _emscripten_set_element_css_size; + _emscripten_set_element_css_size.sig = 'ipdd'; - function _emscripten_get_element_css_size(target, width, height) { + var _emscripten_get_element_css_size = (target, width, height) => { target = findEventTarget(target); if (!target) return -4; @@ -19635,78 +20754,87 @@ var ASM_CONSTS = { HEAPF64[((height)>>3)] = rect.height; return 0; - } - Module["_emscripten_get_element_css_size"] = _emscripten_get_element_css_size; - _emscripten_get_element_css_size.sig = 'iiii'; + }; + Module['_emscripten_get_element_css_size'] = _emscripten_get_element_css_size; + _emscripten_get_element_css_size.sig = 'ippp'; - function _emscripten_html5_remove_all_event_listeners() { - JSEvents.removeAllEventListeners(); - } - Module["_emscripten_html5_remove_all_event_listeners"] = _emscripten_html5_remove_all_event_listeners; + var _emscripten_html5_remove_all_event_listeners = () => JSEvents.removeAllEventListeners(); + Module['_emscripten_html5_remove_all_event_listeners'] = _emscripten_html5_remove_all_event_listeners; _emscripten_html5_remove_all_event_listeners.sig = 'v'; - function _emscripten_request_animation_frame(cb, userData) { - return requestAnimationFrame(function(timeStamp) { - getWasmTableEntry(cb)(timeStamp, userData); - }); - } - Module["_emscripten_request_animation_frame"] = _emscripten_request_animation_frame; + var _emscripten_request_animation_frame = (cb, userData) => + requestAnimationFrame((timeStamp) => getWasmTableEntry(cb)(timeStamp, userData)); + Module['_emscripten_request_animation_frame'] = _emscripten_request_animation_frame; + _emscripten_request_animation_frame.sig = 'ipp'; - function _emscripten_cancel_animation_frame(id) { - cancelAnimationFrame(id); - } - Module["_emscripten_cancel_animation_frame"] = _emscripten_cancel_animation_frame; + var _emscripten_cancel_animation_frame = (id) => cancelAnimationFrame(id); + Module['_emscripten_cancel_animation_frame'] = _emscripten_cancel_animation_frame; + _emscripten_cancel_animation_frame.sig = 'vi'; - function _emscripten_request_animation_frame_loop(cb, userData) { + var _emscripten_request_animation_frame_loop = (cb, userData) => { function tick(timeStamp) { if (getWasmTableEntry(cb)(timeStamp, userData)) { requestAnimationFrame(tick); } } return requestAnimationFrame(tick); - } - Module["_emscripten_request_animation_frame_loop"] = _emscripten_request_animation_frame_loop; + }; + Module['_emscripten_request_animation_frame_loop'] = _emscripten_request_animation_frame_loop; + _emscripten_request_animation_frame_loop.sig = 'vpp'; - function _emscripten_performance_now() { - return performance.now(); - } - Module["_emscripten_performance_now"] = _emscripten_performance_now; + var _emscripten_performance_now = () => performance.now(); + Module['_emscripten_performance_now'] = _emscripten_performance_now; + _emscripten_performance_now.sig = 'd'; - function _emscripten_get_device_pixel_ratio() { + var _emscripten_get_device_pixel_ratio = () => { return (typeof devicePixelRatio == 'number' && devicePixelRatio) || 1.0; - } - Module["_emscripten_get_device_pixel_ratio"] = _emscripten_get_device_pixel_ratio; + }; + Module['_emscripten_get_device_pixel_ratio'] = _emscripten_get_device_pixel_ratio; _emscripten_get_device_pixel_ratio.sig = 'd'; - - - function stackTrace() { var js = jsStackTrace(); if (Module['extraStackTrace']) js += '\n' + Module['extraStackTrace'](); - return demangleAll(js); + return js; } - Module["stackTrace"] = stackTrace; + Module['stackTrace'] = stackTrace; + + function _random_get(buf, buf_len) { + try { + + _getentropy(buf, buf_len); + return 0; + } catch (e) { + if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; + return e.errno; + } + } + Module['_random_get'] = _random_get; + _random_get.sig = 'ipp'; + - function checkWasiClock(clock_id) { + var checkWasiClock = (clock_id) => { return clock_id == 0 || clock_id == 1 || clock_id == 2 || clock_id == 3; - } - Module["checkWasiClock"] = checkWasiClock; + }; + Module['checkWasiClock'] = checkWasiClock; - function _clock_time_get(clk_id, ignored_precision_low, ignored_precision_high, ptime) { + function _clock_time_get(clk_id,ignored_precision_low, ignored_precision_high,ptime) { + var ignored_precision = convertI32PairToI53Checked(ignored_precision_low, ignored_precision_high); + + if (!checkWasiClock(clk_id)) { return 28; } @@ -19724,15 +20852,15 @@ var ASM_CONSTS = { HEAP32[((ptime)>>2)] = nsec >>> 0; HEAP32[(((ptime)+(4))>>2)] = (nsec / Math.pow(2, 32)) >>> 0; return 0; - } - Module["_clock_time_get"] = _clock_time_get; - _clock_time_get.sig = 'iijp'; + ; + } + Module['_clock_time_get'] = _clock_time_get; + _clock_time_get.sig = 'iiiip'; - - function _clock_res_get(clk_id, pres) { + var _clock_res_get = (clk_id, pres) => { if (!checkWasiClock(clk_id)) { return 28; } @@ -19748,8 +20876,8 @@ var ASM_CONSTS = { HEAP32[((pres)>>2)] = nsec >>> 0; HEAP32[(((pres)+(4))>>2)] = (nsec / Math.pow(2, 32)) >>> 0; return 0; - } - Module["_clock_res_get"] = _clock_res_get; + }; + Module['_clock_res_get'] = _clock_res_get; _clock_res_get.sig = 'iip'; @@ -19760,103 +20888,99 @@ var ASM_CONSTS = { + var wasiRightsToMuslOFlags = (rights) => { + if ((rights & 2) && (rights & 64)) { + return 2; + } + if (rights & 2) { + return 0; + } + if (rights & 64) { + return 1; + } + throw new FS.ErrnoError(28); + }; + Module['wasiRightsToMuslOFlags'] = wasiRightsToMuslOFlags; + var wasiOFlagsToMuslOFlags = (oflags) => { + var musl_oflags = 0; + if (oflags & 1) { + musl_oflags |= 64; + } + if (oflags & 8) { + musl_oflags |= 512; + } + if (oflags & 2) { + musl_oflags |= 65536; + } + if (oflags & 4) { + musl_oflags |= 128; + } + return musl_oflags; + }; + Module['wasiOFlagsToMuslOFlags'] = wasiOFlagsToMuslOFlags; - - - - - - - - - - - - - - - - - - - - function __dlsym_catchup_js(handle, symbolIndex) { - var lib = LDSO.loadedLibsByHandle[handle]; - var symDict = lib.exports; - var symName = Object.keys(symDict)[symbolIndex]; - var sym = symDict[symName]; - var result = addFunction(sym, sym.sig); - return result; - } - Module["__dlsym_catchup_js"] = __dlsym_catchup_js; - __dlsym_catchup_js.sig = 'ppp'; - - - - function _emscripten_unwind_to_js_event_loop() { + var _emscripten_unwind_to_js_event_loop = () => { throw 'unwind'; - } - Module["_emscripten_unwind_to_js_event_loop"] = _emscripten_unwind_to_js_event_loop; + }; + Module['_emscripten_unwind_to_js_event_loop'] = _emscripten_unwind_to_js_event_loop; + _emscripten_unwind_to_js_event_loop.sig = 'v'; - function setImmediateWrapped(func) { - if (!setImmediateWrapped.mapping) setImmediateWrapped.mapping = []; + + var setImmediateWrapped = (func) => { + setImmediateWrapped.mapping ||= []; var id = setImmediateWrapped.mapping.length; setImmediateWrapped.mapping[id] = setImmediate(() => { setImmediateWrapped.mapping[id] = undefined; func(); }); return id; - } - Module["setImmediateWrapped"] = setImmediateWrapped; + }; + Module['setImmediateWrapped'] = setImmediateWrapped; - function clearImmediateWrapped(id) { + var clearImmediateWrapped = (id) => { assert(id); assert(setImmediateWrapped.mapping[id]); clearImmediate(setImmediateWrapped.mapping[id]); setImmediateWrapped.mapping[id] = undefined; - } - Module["clearImmediateWrapped"] = clearImmediateWrapped; + }; + Module['clearImmediateWrapped'] = clearImmediateWrapped; - function polyfillSetImmediate() { + var polyfillSetImmediate = () => { // nop, used for its postset to ensure setImmediate() polyfill is // not duplicated between emscripten_set_immediate() and // emscripten_set_immediate_loop() if application links to both of them. - } - Module["polyfillSetImmediate"] = polyfillSetImmediate; + }; + Module['polyfillSetImmediate'] = polyfillSetImmediate; - function _emscripten_set_immediate(cb, userData) { - polyfillSetImmediate(); + var _emscripten_set_immediate = (cb, userData) => { - return emSetImmediate(function() { + return emSetImmediate(() => { - callUserCallback(function() { - getWasmTableEntry(cb)(userData); - }); + callUserCallback(() => getWasmTableEntry(cb)(userData)); }); - } - Module["_emscripten_set_immediate"] = _emscripten_set_immediate; + }; + Module['_emscripten_set_immediate'] = _emscripten_set_immediate; _emscripten_set_immediate.sig = 'ipp'; - function _emscripten_clear_immediate(id) { + var _emscripten_clear_immediate = (id) => { emClearImmediate(id); - } - Module["_emscripten_clear_immediate"] = _emscripten_clear_immediate; + }; + Module['_emscripten_clear_immediate'] = _emscripten_clear_immediate; _emscripten_clear_immediate.sig = 'vi'; - function _emscripten_set_immediate_loop(cb, userData) { - polyfillSetImmediate(); + var _emscripten_set_immediate_loop = (cb, userData) => { function tick() { - callUserCallback(function() { + callUserCallback(() => { if (getWasmTableEntry(cb)(userData)) { emSetImmediate(tick); } else { @@ -19866,74 +20990,84 @@ var ASM_CONSTS = { } emSetImmediate(tick); - } - Module["_emscripten_set_immediate_loop"] = _emscripten_set_immediate_loop; - _emscripten_set_immediate_loop.sig = 'ipp'; + }; + Module['_emscripten_set_immediate_loop'] = _emscripten_set_immediate_loop; + _emscripten_set_immediate_loop.sig = 'vpp'; - function _emscripten_set_timeout(cb, msecs, userData) { - return safeSetTimeout(() => getWasmTableEntry(cb)(userData), msecs); - } - Module["_emscripten_set_timeout"] = _emscripten_set_timeout; + var _emscripten_set_timeout = (cb, msecs, userData) => + safeSetTimeout(() => getWasmTableEntry(cb)(userData), msecs); + Module['_emscripten_set_timeout'] = _emscripten_set_timeout; _emscripten_set_timeout.sig = 'ipdp'; - function _emscripten_clear_timeout(id) { - clearTimeout(id); - } - Module["_emscripten_clear_timeout"] = _emscripten_clear_timeout; + var _emscripten_clear_timeout = clearTimeout; + Module['_emscripten_clear_timeout'] = _emscripten_clear_timeout; _emscripten_clear_timeout.sig = 'vi'; - function _emscripten_set_timeout_loop(cb, msecs, userData) { + + var _emscripten_set_timeout_loop = (cb, msecs, userData) => { function tick() { - var t = performance.now(); + var t = _emscripten_get_now(); var n = t + msecs; - callUserCallback(function() { + callUserCallback(() => { if (getWasmTableEntry(cb)(t, userData)) { // Save a little bit of code space: modern browsers should treat // negative setTimeout as timeout of 0 // (https://stackoverflow.com/questions/8430966/is-calling-settimeout-with-a-negative-delay-ok) - setTimeout(tick, n - performance.now()); + setTimeout(tick, n - _emscripten_get_now()); } }); } return setTimeout(tick, 0); - } - Module["_emscripten_set_timeout_loop"] = _emscripten_set_timeout_loop; + }; + Module['_emscripten_set_timeout_loop'] = _emscripten_set_timeout_loop; _emscripten_set_timeout_loop.sig = 'vpdp'; - function _emscripten_set_interval(cb, msecs, userData) { + var _emscripten_set_interval = (cb, msecs, userData) => { - return setInterval(function() { - callUserCallback(function() { - getWasmTableEntry(cb)(userData) - }); + return setInterval(() => { + callUserCallback(() => getWasmTableEntry(cb)(userData)); }, msecs); - } - Module["_emscripten_set_interval"] = _emscripten_set_interval; + }; + Module['_emscripten_set_interval'] = _emscripten_set_interval; _emscripten_set_interval.sig = 'ipdp'; - function _emscripten_clear_interval(id) { + var _emscripten_clear_interval = (id) => { clearInterval(id); - } - Module["_emscripten_clear_interval"] = _emscripten_clear_interval; + }; + Module['_emscripten_clear_interval'] = _emscripten_clear_interval; _emscripten_clear_interval.sig = 'vi'; + + var idsToPromises = (idBuf, size) => { + var promises = []; + for (var i = 0; i < size; i++) { + var id = HEAP32[(((idBuf)+(i*4))>>2)]; + promises[i] = getPromise(id); + } + return promises; + }; + Module['idsToPromises'] = idsToPromises; + - function makePromiseCallback(callback, userData) { + + + + var makePromiseCallback = (callback, userData) => { return (value) => { ; var stack = stackSave(); @@ -19973,15 +21107,12 @@ var ASM_CONSTS = { } abort("unexpected promise callback result " + result); }; - } - Module["makePromiseCallback"] = makePromiseCallback; + }; + Module['makePromiseCallback'] = makePromiseCallback; - function _emscripten_promise_then(id, - onFulfilled, - onRejected, - userData) { + var _emscripten_promise_then = (id, onFulfilled, onRejected, userData) => { ; var promise = getPromise(id); var newId = promiseMap.allocate({ @@ -19989,17 +21120,13 @@ var ASM_CONSTS = { makePromiseCallback(onRejected, userData)) }); return newId; - } - Module["_emscripten_promise_then"] = _emscripten_promise_then; + }; + Module['_emscripten_promise_then'] = _emscripten_promise_then; _emscripten_promise_then.sig = 'ppppp'; - function _emscripten_promise_all(idBuf, resultBuf, size) { - var promises = []; - for (var i = 0; i < size; i++) { - var id = HEAP32[(((idBuf)+(i*4))>>2)]; - promises[i] = getPromise(id); - } + var _emscripten_promise_all = (idBuf, resultBuf, size) => { + var promises = idsToPromises(idBuf, size); var id = promiseMap.allocate({ promise: Promise.all(promises).then((results) => { if (resultBuf) { @@ -20012,43 +21139,152 @@ var ASM_CONSTS = { }) }); return id; - } - Module["_emscripten_promise_all"] = _emscripten_promise_all; + }; + Module['_emscripten_promise_all'] = _emscripten_promise_all; _emscripten_promise_all.sig = 'pppp'; + var setPromiseResult = (ptr, fulfill, value) => { + assert(typeof value == 'undefined' || typeof value === 'number', `native promises can only handle numeric results (${value} ${typeof value})`); + var result = fulfill ? 0 : 3 + HEAP32[((ptr)>>2)] = result; + HEAPU32[(((ptr)+(4))>>2)] = value; + }; + Module['setPromiseResult'] = setPromiseResult; + + + var _emscripten_promise_all_settled = (idBuf, resultBuf, size) => { + var promises = idsToPromises(idBuf, size); + var id = promiseMap.allocate({ + promise: Promise.allSettled(promises).then((results) => { + if (resultBuf) { + var offset = resultBuf; + for (var i = 0; i < size; i++, offset += 8) { + if (results[i].status === 'fulfilled') { + setPromiseResult(offset, true, results[i].value); + } else { + setPromiseResult(offset, false, results[i].reason); + } + } + } + return resultBuf; + }) + }); + return id; + }; + Module['_emscripten_promise_all_settled'] = _emscripten_promise_all_settled; + _emscripten_promise_all_settled.sig = 'pppp'; - var exceptionCaught = []; - Module["exceptionCaught"] = exceptionCaught; + + var _emscripten_promise_any = (idBuf, errorBuf, size) => { + var promises = idsToPromises(idBuf, size); + assert(typeof Promise.any !== 'undefined', "Promise.any does not exist"); + var id = promiseMap.allocate({ + promise: Promise.any(promises).catch((err) => { + if (errorBuf) { + for (var i = 0; i < size; i++) { + HEAPU32[(((errorBuf)+(i*4))>>2)] = err.errors[i]; + } + } + throw errorBuf; + }) + }); + return id; + }; + Module['_emscripten_promise_any'] = _emscripten_promise_any; + _emscripten_promise_any.sig = 'pppp'; + + var _emscripten_promise_race = (idBuf, size) => { + var promises = idsToPromises(idBuf, size); + var id = promiseMap.allocate({ + promise: Promise.race(promises) + }); + return id; + }; + Module['_emscripten_promise_race'] = _emscripten_promise_race; + _emscripten_promise_race.sig = 'ppp'; - function exception_addRef(info) { - info.add_ref(); - } - Module["exception_addRef"] = exception_addRef; + + var _emscripten_promise_await = (returnValuePtr, id) => { + abort('emscripten_promise_await is only available with ASYNCIFY'); + }; + Module['_emscripten_promise_await'] = _emscripten_promise_await; + _emscripten_promise_await.sig = 'vpp'; - function exception_decRef(info) { - // A rethrown exception can reach refcount 0; it must not be discarded - // Its next handler will clear the rethrown flag and addRef it, prior to - // final decRef and destruction here - if (info.release_ref() && !info.get_rethrown()) { - var destructor = info.get_destructor(); - if (destructor) { - // In Wasm, destructors return 'this' as in ARM - getWasmTableEntry(destructor)(info.excPtr); + + var ___resumeException = (ptr) => { + if (!exceptionLast) { + exceptionLast = ptr; + } + assert(false, 'Exception thrown, but exception catching is not enabled. Compile with -sNO_DISABLE_EXCEPTION_CATCHING or -sEXCEPTION_CATCHING_ALLOWED=[..] to catch. (note: in dynamic linking, if a side module wants exceptions, the main module must be built with that support)'); + }; + Module['___resumeException'] = ___resumeException; + ___resumeException.sig = 'vp'; + + + var findMatchingCatch = (args) => { + var thrown = + exceptionLast; + if (!thrown) { + // just pass through the null ptr + setTempRet0(0); + return 0; + } + var info = new ExceptionInfo(thrown); + info.set_adjusted_ptr(thrown); + var thrownType = info.get_type(); + if (!thrownType) { + // just pass through the thrown ptr + setTempRet0(0); + return thrown; + } + + // can_catch receives a **, add indirection + // The different catch blocks are denoted by different types. + // Due to inheritance, those types may not precisely match the + // type of the thrown object. Find one which matches, and + // return the type of the catch block which should be called. + for (var arg in args) { + var caughtType = args[arg]; + + if (caughtType === 0 || caughtType === thrownType) { + // Catch all clause matched or exactly the same type is caught + break; + } + var adjusted_ptr_addr = info.ptr + 16; + if (___cxa_can_catch(caughtType, thrownType, adjusted_ptr_addr)) { + setTempRet0(caughtType); + return thrown; } - ___cxa_free_exception(info.excPtr); } - } - Module["exception_decRef"] = exception_decRef; + setTempRet0(thrownType); + return thrown; + }; + Module['findMatchingCatch'] = findMatchingCatch; + var ___cxa_find_matching_catch_2 = () => findMatchingCatch([]); + Module['___cxa_find_matching_catch_2'] = ___cxa_find_matching_catch_2; + ___cxa_find_matching_catch_2.sig = 'p'; + + var ___cxa_find_matching_catch_3 = (arg0) => findMatchingCatch([arg0]); + Module['___cxa_find_matching_catch_3'] = ___cxa_find_matching_catch_3; + ___cxa_find_matching_catch_3.sig = 'pp'; + var ___cxa_find_matching_catch_4 = (arg0,arg1) => findMatchingCatch([arg0,arg1]); + Module['___cxa_find_matching_catch_4'] = ___cxa_find_matching_catch_4; + ___cxa_find_matching_catch_4.sig = 'ppp'; + + + + var exceptionCaught = []; + Module['exceptionCaught'] = exceptionCaught; - function ___cxa_rethrow() { + var ___cxa_rethrow = () => { var info = exceptionCaught.pop(); if (!info) { abort('no exception to throw'); @@ -20062,20 +21298,18 @@ var ASM_CONSTS = { uncaughtExceptionCount++; } exceptionLast = ptr; - throw ptr + " - Exception catching is disabled, this exception cannot be caught. Compile with -sNO_DISABLE_EXCEPTION_CATCHING or -sEXCEPTION_CATCHING_ALLOWED=[..] to catch." + " (note: in dynamic linking, if a side module wants exceptions, the main module must be built with that support)"; - } - Module["___cxa_rethrow"] = ___cxa_rethrow; + assert(false, 'Exception thrown, but exception catching is not enabled. Compile with -sNO_DISABLE_EXCEPTION_CATCHING or -sEXCEPTION_CATCHING_ALLOWED=[..] to catch. (note: in dynamic linking, if a side module wants exceptions, the main module must be built with that support)'); + }; + Module['___cxa_rethrow'] = ___cxa_rethrow; ___cxa_rethrow.sig = 'v'; - function _llvm_eh_typeid_for(type) { - return type; - } - Module["_llvm_eh_typeid_for"] = _llvm_eh_typeid_for; - _llvm_eh_typeid_for.sig = 'ip'; + var _llvm_eh_typeid_for = (type) => type; + Module['_llvm_eh_typeid_for'] = _llvm_eh_typeid_for; + _llvm_eh_typeid_for.sig = 'vp'; - function ___cxa_begin_catch(ptr) { + var ___cxa_begin_catch = (ptr) => { var info = new ExceptionInfo(ptr); if (!info.get_caught()) { info.set_caught(true); @@ -20083,96 +21317,49 @@ var ASM_CONSTS = { } info.set_rethrown(false); exceptionCaught.push(info); - exception_addRef(info); + ___cxa_increment_exception_refcount(info.excPtr); return info.get_exception_ptr(); - } - Module["___cxa_begin_catch"] = ___cxa_begin_catch; + }; + Module['___cxa_begin_catch'] = ___cxa_begin_catch; ___cxa_begin_catch.sig = 'pp'; - function ___cxa_end_catch() { + + var ___cxa_end_catch = () => { // Clear state flag. - _setThrew(0); + _setThrew(0, 0); assert(exceptionCaught.length > 0); // Call destructor if one is registered then clear it. var info = exceptionCaught.pop(); - exception_decRef(info); + ___cxa_decrement_exception_refcount(info.excPtr); exceptionLast = 0; // XXX in decRef? - } - Module["___cxa_end_catch"] = ___cxa_end_catch; + }; + Module['___cxa_end_catch'] = ___cxa_end_catch; ___cxa_end_catch.sig = 'v'; - function ___cxa_get_exception_ptr(ptr) { - return new ExceptionInfo(ptr).get_exception_ptr(); - } - Module["___cxa_get_exception_ptr"] = ___cxa_get_exception_ptr; + var ___cxa_get_exception_ptr = (ptr) => { + var rtn = new ExceptionInfo(ptr).get_exception_ptr(); + return rtn; + }; + Module['___cxa_get_exception_ptr'] = ___cxa_get_exception_ptr; ___cxa_get_exception_ptr.sig = 'pp'; - function ___cxa_call_unexpected(exception) { - err('Unexpected exception thrown, this is not properly supported - aborting'); - ABORT = true; - throw exception; - } - Module["___cxa_call_unexpected"] = ___cxa_call_unexpected; + var ___cxa_call_unexpected = (exception) => abort('Unexpected exception thrown, this is not properly supported - aborting'); + Module['___cxa_call_unexpected'] = ___cxa_call_unexpected; + ___cxa_call_unexpected.sig = 'vp'; - - - function ___resumeException(ptr) { - if (!exceptionLast) { exceptionLast = ptr; } - throw ptr + " - Exception catching is disabled, this exception cannot be caught. Compile with -sNO_DISABLE_EXCEPTION_CATCHING or -sEXCEPTION_CATCHING_ALLOWED=[..] to catch." + " (note: in dynamic linking, if a side module wants exceptions, the main module must be built with that support)"; - } - Module["___resumeException"] = ___resumeException; - ___resumeException.sig = 'vp'; - - - function ___cxa_find_matching_catch() { - var thrown = exceptionLast; - if (!thrown) { - // just pass through the null ptr - setTempRet0(0); - return 0; - } - var info = new ExceptionInfo(thrown); - info.set_adjusted_ptr(thrown); - var thrownType = info.get_type(); - if (!thrownType) { - // just pass through the thrown ptr - setTempRet0(0); - return thrown; - } - - // can_catch receives a **, add indirection - // The different catch blocks are denoted by different types. - // Due to inheritance, those types may not precisely match the - // type of the thrown object. Find one which matches, and - // return the type of the catch block which should be called. - for (var i = 0; i < arguments.length; i++) { - var caughtType = arguments[i]; - if (caughtType === 0 || caughtType === thrownType) { - // Catch all clause matched or exactly the same type is caught - break; - } - var adjusted_ptr_addr = info.ptr + 16; - if (___cxa_can_catch(caughtType, thrownType, adjusted_ptr_addr)) { - setTempRet0(caughtType); - return thrown; - } - } - setTempRet0(thrownType); - return thrown; - } - Module["___cxa_find_matching_catch"] = ___cxa_find_matching_catch; - function _emscripten_run_preload_plugins(file, onload, onerror) { + + var _emscripten_run_preload_plugins = (file, onload, onerror) => { var _file = UTF8ToString(file); @@ -20181,6 +21368,8 @@ var ASM_CONSTS = { FS.createPreloadedFile( PATH.dirname(_file), PATH.basename(_file), + // TODO: This copy is not needed if the contents are already a Uint8Array, + // which they often are (and always are in WasmFS). new Uint8Array(data.object.contents), true, true, () => { @@ -20193,25 +21382,27 @@ var ASM_CONSTS = { true // don'tCreateFile - it's already there ); return 0; - } - Module["_emscripten_run_preload_plugins"] = _emscripten_run_preload_plugins; - _emscripten_run_preload_plugins.sig = 'iiii'; + }; + Module['_emscripten_run_preload_plugins'] = _emscripten_run_preload_plugins; + _emscripten_run_preload_plugins.sig = 'ippp'; + var Browser_asyncPrepareDataCounter = 0; + Module['Browser_asyncPrepareDataCounter'] = Browser_asyncPrepareDataCounter; + + - function _emscripten_run_preload_plugins_data(data, size, suffix, arg, onload, onerror) { + + var _emscripten_run_preload_plugins_data = (data, size, suffix, arg, onload, onerror) => { var _suffix = UTF8ToString(suffix); - if (!Browser.asyncPrepareDataCounter) Browser.asyncPrepareDataCounter = 0; - var name = 'prepare_data_' + (Browser.asyncPrepareDataCounter++) + '.' + _suffix; - var lengthAsUTF8 = lengthBytesUTF8(name); - var cname = _malloc(lengthAsUTF8+1); - stringToUTF8(name, cname, lengthAsUTF8+1); + var name = 'prepare_data_' + (Browser_asyncPrepareDataCounter++) + '.' + _suffix; + var cname = stringToNewUTF8(name); FS.createPreloadedFile( '/', name, - HEAPU8.subarray((data), (data + size)), + HEAPU8.subarray((data), data + size), true, true, () => { @@ -20223,30 +21414,31 @@ var ASM_CONSTS = { }, true // don'tCreateFile - it's already there ); - } - Module["_emscripten_run_preload_plugins_data"] = _emscripten_run_preload_plugins_data; - _emscripten_run_preload_plugins_data.sig = 'viiiiii'; + }; + Module['_emscripten_run_preload_plugins_data'] = _emscripten_run_preload_plugins_data; + _emscripten_run_preload_plugins_data.sig = 'vpipppp'; - function _emscripten_async_run_script(script, millis) { + var _emscripten_async_run_script = (script, millis) => { // TODO: cache these to avoid generating garbage - safeSetTimeout(function() { - _emscripten_run_script(script); - }, millis); - } - Module["_emscripten_async_run_script"] = _emscripten_async_run_script; + safeSetTimeout(() => _emscripten_run_script(script), millis); + }; + Module['_emscripten_async_run_script'] = _emscripten_async_run_script; + _emscripten_async_run_script.sig = 'vpi'; - function _emscripten_async_load_script(url, onload, onerror) { + + + var _emscripten_async_load_script = (url, onload, onerror) => { + url = UTF8ToString(url); onload = getWasmTableEntry(onload); onerror = getWasmTableEntry(onerror); + assert(runDependencies === 0, 'async_load_script must be run when no other dependencies are active'); - assert(runDependencies === 0, 'async_load_script must be run when no other dependencies are active'); - var script = document.createElement('script'); - script.onload = function script_onload() { + var loadDone = () => { if (onload) { if (runDependencies > 0) { @@ -20255,91 +21447,109 @@ var ASM_CONSTS = { onload(); } } - }; - script.onerror = () => { + } + + var loadError = () => { - if (onerror) onerror(); + onerror?.(); }; - script.src = UTF8ToString(url); + + if (ENVIRONMENT_IS_NODE) { + readAsync(url, (data) => { + eval(data); + loadDone(); + }, loadError, false); + return; + } + + var script = document.createElement('script'); + script.onload = loadDone; + script.onerror = loadError; + script.src = url; document.body.appendChild(script); - } - Module["_emscripten_async_load_script"] = _emscripten_async_load_script; + }; + Module['_emscripten_async_load_script'] = _emscripten_async_load_script; + _emscripten_async_load_script.sig = 'vppp'; - function _emscripten_get_main_loop_timing(mode, value) { + var _emscripten_get_main_loop_timing = (mode, value) => { if (mode) HEAP32[((mode)>>2)] = Browser.mainLoop.timingMode; if (value) HEAP32[((value)>>2)] = Browser.mainLoop.timingValue; - } - Module["_emscripten_get_main_loop_timing"] = _emscripten_get_main_loop_timing; - _emscripten_get_main_loop_timing.sig = 'vii'; + }; + Module['_emscripten_get_main_loop_timing'] = _emscripten_get_main_loop_timing; + _emscripten_get_main_loop_timing.sig = 'vpp'; - function _emscripten_set_main_loop(func, fps, simulateInfiniteLoop) { + var _emscripten_set_main_loop = (func, fps, simulateInfiniteLoop) => { var browserIterationFunc = getWasmTableEntry(func); setMainLoop(browserIterationFunc, fps, simulateInfiniteLoop); - } - Module["_emscripten_set_main_loop"] = _emscripten_set_main_loop; - _emscripten_set_main_loop.sig = 'viii'; + }; + Module['_emscripten_set_main_loop'] = _emscripten_set_main_loop; + _emscripten_set_main_loop.sig = 'vpii'; - function _emscripten_set_main_loop_arg(func, arg, fps, simulateInfiniteLoop) { + var _emscripten_set_main_loop_arg = (func, arg, fps, simulateInfiniteLoop) => { var browserIterationFunc = () => getWasmTableEntry(func)(arg); setMainLoop(browserIterationFunc, fps, simulateInfiniteLoop, arg); - } - Module["_emscripten_set_main_loop_arg"] = _emscripten_set_main_loop_arg; - _emscripten_set_main_loop_arg.sig = 'viiii'; + }; + Module['_emscripten_set_main_loop_arg'] = _emscripten_set_main_loop_arg; + _emscripten_set_main_loop_arg.sig = 'vppii'; - function _emscripten_cancel_main_loop() { + var _emscripten_cancel_main_loop = () => { Browser.mainLoop.pause(); Browser.mainLoop.func = null; - } - Module["_emscripten_cancel_main_loop"] = _emscripten_cancel_main_loop; + }; + Module['_emscripten_cancel_main_loop'] = _emscripten_cancel_main_loop; _emscripten_cancel_main_loop.sig = 'v'; - function _emscripten_pause_main_loop() { + var _emscripten_pause_main_loop = () => { Browser.mainLoop.pause(); - } - Module["_emscripten_pause_main_loop"] = _emscripten_pause_main_loop; + }; + Module['_emscripten_pause_main_loop'] = _emscripten_pause_main_loop; _emscripten_pause_main_loop.sig = 'v'; - function _emscripten_resume_main_loop() { + var _emscripten_resume_main_loop = () => { Browser.mainLoop.resume(); - } - Module["_emscripten_resume_main_loop"] = _emscripten_resume_main_loop; + }; + Module['_emscripten_resume_main_loop'] = _emscripten_resume_main_loop; _emscripten_resume_main_loop.sig = 'v'; - function __emscripten_push_main_loop_blocker(func, arg, name) { - Browser.mainLoop.queue.push({ func: function() { + + var __emscripten_push_main_loop_blocker = (func, arg, name) => { + Browser.mainLoop.queue.push({ func: () => { getWasmTableEntry(func)(arg); }, name: UTF8ToString(name), counted: true }); Browser.mainLoop.updateStatus(); - } - Module["__emscripten_push_main_loop_blocker"] = __emscripten_push_main_loop_blocker; + }; + Module['__emscripten_push_main_loop_blocker'] = __emscripten_push_main_loop_blocker; + __emscripten_push_main_loop_blocker.sig = 'vppp'; - function __emscripten_push_uncounted_main_loop_blocker(func, arg, name) { - Browser.mainLoop.queue.push({ func: function() { + + var __emscripten_push_uncounted_main_loop_blocker = (func, arg, name) => { + Browser.mainLoop.queue.push({ func: () => { getWasmTableEntry(func)(arg); }, name: UTF8ToString(name), counted: false }); Browser.mainLoop.updateStatus(); - } - Module["__emscripten_push_uncounted_main_loop_blocker"] = __emscripten_push_uncounted_main_loop_blocker; + }; + Module['__emscripten_push_uncounted_main_loop_blocker'] = __emscripten_push_uncounted_main_loop_blocker; + __emscripten_push_uncounted_main_loop_blocker.sig = 'vppp'; - function _emscripten_set_main_loop_expected_blockers(num) { + var _emscripten_set_main_loop_expected_blockers = (num) => { Browser.mainLoop.expectedBlockers = num; Browser.mainLoop.remainingBlockers = num; Browser.mainLoop.updateStatus(); - } - Module["_emscripten_set_main_loop_expected_blockers"] = _emscripten_set_main_loop_expected_blockers; + }; + Module['_emscripten_set_main_loop_expected_blockers'] = _emscripten_set_main_loop_expected_blockers; _emscripten_set_main_loop_expected_blockers.sig = 'vi'; - function _emscripten_async_call(func, arg, millis) { + var _emscripten_async_call = (func, arg, millis) => { function wrapper() { getWasmTableEntry(func)(arg); } @@ -20352,11 +21562,11 @@ var ASM_CONSTS = { } else { Browser.safeRequestAnimationFrame(wrapper); } - } - Module["_emscripten_async_call"] = _emscripten_async_call; + }; + Module['_emscripten_async_call'] = _emscripten_async_call; _emscripten_async_call.sig = 'vppi'; - function _emscripten_get_window_title() { + var _emscripten_get_window_title = () => { var buflen = 256; if (!_emscripten_get_window_title.buffer) { @@ -20366,24 +21576,23 @@ var ASM_CONSTS = { stringToUTF8(document.title, _emscripten_get_window_title.buffer, buflen); return _emscripten_get_window_title.buffer; - } - Module["_emscripten_get_window_title"] = _emscripten_get_window_title; - _emscripten_get_window_title.sig = 'iv'; + }; + Module['_emscripten_get_window_title'] = _emscripten_get_window_title; + _emscripten_get_window_title.sig = 'p'; - function _emscripten_set_window_title(title) { - setWindowTitle(UTF8ToString(title)); - } - Module["_emscripten_set_window_title"] = _emscripten_set_window_title; - _emscripten_set_window_title.sig = 'vi'; + + var _emscripten_set_window_title = (title) => document.title = UTF8ToString(title); + Module['_emscripten_set_window_title'] = _emscripten_set_window_title; + _emscripten_set_window_title.sig = 'vp'; - function _emscripten_get_screen_size(width, height) { + var _emscripten_get_screen_size = (width, height) => { HEAP32[((width)>>2)] = screen.width; HEAP32[((height)>>2)] = screen.height; - } - Module["_emscripten_get_screen_size"] = _emscripten_get_screen_size; - _emscripten_get_screen_size.sig = 'vii'; + }; + Module['_emscripten_get_screen_size'] = _emscripten_get_screen_size; + _emscripten_get_screen_size.sig = 'vpp'; - function _emscripten_hide_mouse() { + var _emscripten_hide_mouse = () => { var styleSheet = document.styleSheets[0]; var rules = styleSheet.cssRules; for (var i = 0; i < rules.length; i++) { @@ -20393,26 +21602,30 @@ var ASM_CONSTS = { } } styleSheet.insertRule('canvas.emscripten { border: 1px solid black; cursor: none; }', 0); - } - Module["_emscripten_hide_mouse"] = _emscripten_hide_mouse; + }; + Module['_emscripten_hide_mouse'] = _emscripten_hide_mouse; _emscripten_hide_mouse.sig = 'v'; - function _emscripten_set_canvas_size(width, height) { + var _emscripten_set_canvas_size = (width, height) => { Browser.setCanvasSize(width, height); - } - Module["_emscripten_set_canvas_size"] = _emscripten_set_canvas_size; + }; + Module['_emscripten_set_canvas_size'] = _emscripten_set_canvas_size; _emscripten_set_canvas_size.sig = 'vii'; - function _emscripten_get_canvas_size(width, height, isFullscreen) { + var _emscripten_get_canvas_size = (width, height, isFullscreen) => { var canvas = Module['canvas']; HEAP32[((width)>>2)] = canvas.width; HEAP32[((height)>>2)] = canvas.height; HEAP32[((isFullscreen)>>2)] = Browser.isFullscreen ? 1 : 0; - } - Module["_emscripten_get_canvas_size"] = _emscripten_get_canvas_size; - _emscripten_get_canvas_size.sig = 'viii'; + }; + Module['_emscripten_get_canvas_size'] = _emscripten_get_canvas_size; + _emscripten_get_canvas_size.sig = 'vppp'; - function _emscripten_create_worker(url) { + + + + + var _emscripten_create_worker = (url) => { url = UTF8ToString(url); var id = Browser.workers.length; var info = { @@ -20451,21 +21664,23 @@ var ASM_CONSTS = { }; Browser.workers.push(info); return id; - } - Module["_emscripten_create_worker"] = _emscripten_create_worker; - _emscripten_create_worker.sig = 'ii'; + }; + Module['_emscripten_create_worker'] = _emscripten_create_worker; + _emscripten_create_worker.sig = 'ip'; - function _emscripten_destroy_worker(id) { + + var _emscripten_destroy_worker = (id) => { var info = Browser.workers[id]; info.worker.terminate(); if (info.buffer) _free(info.buffer); Browser.workers[id] = null; - } - Module["_emscripten_destroy_worker"] = _emscripten_destroy_worker; + }; + Module['_emscripten_destroy_worker'] = _emscripten_destroy_worker; _emscripten_destroy_worker.sig = 'vi'; - function _emscripten_call_worker(id, funcName, data, size, callback, arg) { + + var _emscripten_call_worker = (id, funcName, data, size, callback, arg) => { funcName = UTF8ToString(funcName); var info = Browser.workers[id]; var callbackId = -1; @@ -20478,77 +21693,85 @@ var ASM_CONSTS = { callbackId = info.callbacks.length; info.callbacks.push({ func: getWasmTableEntry(callback), - arg: arg + arg }); info.awaited++; } var transferObject = { 'funcName': funcName, 'callbackId': callbackId, - 'data': data ? new Uint8Array(HEAPU8.subarray((data), (data + size))) : 0 + 'data': data ? new Uint8Array(HEAPU8.subarray((data), data + size)) : 0 }; if (data) { info.worker.postMessage(transferObject, [transferObject.data.buffer]); } else { info.worker.postMessage(transferObject); } - } - Module["_emscripten_call_worker"] = _emscripten_call_worker; - _emscripten_call_worker.sig = 'viiiiii'; + }; + Module['_emscripten_call_worker'] = _emscripten_call_worker; + _emscripten_call_worker.sig = 'vippipp'; - function _emscripten_get_worker_queue_size(id) { + var _emscripten_get_worker_queue_size = (id) => { var info = Browser.workers[id]; if (!info) return -1; return info.awaited; - } - Module["_emscripten_get_worker_queue_size"] = _emscripten_get_worker_queue_size; - _emscripten_get_worker_queue_size.sig = 'i'; + }; + Module['_emscripten_get_worker_queue_size'] = _emscripten_get_worker_queue_size; + _emscripten_get_worker_queue_size.sig = 'ii'; + var getPreloadedImageData = (path, w, h) => { + path = PATH_FS.resolve(path); + var canvas = /** @type {HTMLCanvasElement} */(preloadedImages[path]); + if (!canvas) return 0; - function _emscripten_get_preloaded_image_data(path, w, h) { - if ((path | 0) === path) path = UTF8ToString(path); + var ctx = canvas.getContext("2d"); + var image = ctx.getImageData(0, 0, canvas.width, canvas.height); + var buf = _malloc(canvas.width * canvas.height * 4); - path = PATH_FS.resolve(path); + HEAPU8.set(image.data, buf); - var canvas = /** @type {HTMLCanvasElement} */(preloadedImages[path]); - if (canvas) { - var ctx = canvas.getContext("2d"); - var image = ctx.getImageData(0, 0, canvas.width, canvas.height); - var buf = _malloc(canvas.width * canvas.height * 4); + HEAP32[((w)>>2)] = canvas.width; + HEAP32[((h)>>2)] = canvas.height; + return buf; + }; + Module['getPreloadedImageData'] = getPreloadedImageData; - HEAPU8.set(image.data, buf); - HEAP32[((w)>>2)] = canvas.width; - HEAP32[((h)>>2)] = canvas.height; - return buf; - } - return 0; - } - Module["_emscripten_get_preloaded_image_data"] = _emscripten_get_preloaded_image_data; - _emscripten_get_preloaded_image_data.sig = 'iiii'; + var _emscripten_get_preloaded_image_data = (path, w, h) => getPreloadedImageData(UTF8ToString(path), w, h); + Module['_emscripten_get_preloaded_image_data'] = _emscripten_get_preloaded_image_data; + _emscripten_get_preloaded_image_data.sig = 'pppp'; + + var getPreloadedImageData__data = ["$PATH_FS","malloc"]; + Module['getPreloadedImageData__data'] = getPreloadedImageData__data; + - function _emscripten_get_preloaded_image_data_from_FILE(file, w, h) { + var _emscripten_get_preloaded_image_data_from_FILE = (file, w, h) => { var fd = _fileno(file); var stream = FS.getStream(fd); if (stream) { - return _emscripten_get_preloaded_image_data(stream.path, w, h); + return getPreloadedImageData(stream.path, w, h); } return 0; - } - Module["_emscripten_get_preloaded_image_data_from_FILE"] = _emscripten_get_preloaded_image_data_from_FILE; - _emscripten_get_preloaded_image_data_from_FILE.sig = 'iiii'; - - var wget = {wgetRequests:{},nextWgetRequestHandle:0,getNextWgetRequestHandle:function() { + }; + Module['_emscripten_get_preloaded_image_data_from_FILE'] = _emscripten_get_preloaded_image_data_from_FILE; + _emscripten_get_preloaded_image_data_from_FILE.sig = 'pppp'; + + var wget = { + wgetRequests:{ + }, + nextWgetRequestHandle:0, + getNextWgetRequestHandle() { var handle = wget.nextWgetRequestHandle; wget.nextWgetRequestHandle++; return handle; - }}; - Module["wget"] = wget; + }, + }; + Module['wget'] = wget; @@ -20556,7 +21779,20 @@ var ASM_CONSTS = { - function _emscripten_async_wget(url, file, onload, onerror) { + + /** + * @param {number=} mode Optionally, the mode to create in. Uses mkdir's + * default if not set. + */ + var FS_mkdirTree = (path, mode) => FS.mkdirTree(path, mode); + Module['FS_mkdirTree'] = FS_mkdirTree; + + + var FS_unlink = (path) => FS.unlink(path); + Module['FS_unlink'] = FS_unlink; + + + var _emscripten_async_wget = (url, file, onload, onerror) => { var _url = UTF8ToString(url); @@ -20565,70 +21801,68 @@ var ASM_CONSTS = { function doCallback(callback) { if (callback) { - callUserCallback(function() { - withStackSave(function() { - getWasmTableEntry(callback)(allocateUTF8OnStack(_file)); + callUserCallback(() => { + withStackSave(() => { + getWasmTableEntry(callback)(stringToUTF8OnStack(_file)); }); }); } } var destinationDirectory = PATH.dirname(_file); - FS.createPreloadedFile( + FS_createPreloadedFile( destinationDirectory, PATH.basename(_file), _url, true, true, - function() { - doCallback(onload); - }, - function() { - doCallback(onerror); - }, + () => doCallback(onload), + () => doCallback(onerror), false, // dontCreateFile false, // canOwn - function() { // preFinish + () => { // preFinish // if a file exists there, we overwrite it try { - FS.unlink(_file); + FS_unlink(_file); } catch (e) {} // if the destination directory does not yet exist, create it - FS.mkdirTree(destinationDirectory); + FS_mkdirTree(destinationDirectory); } ); - } - Module["_emscripten_async_wget"] = _emscripten_async_wget; - _emscripten_async_wget.sig = 'viiii'; + }; + Module['_emscripten_async_wget'] = _emscripten_async_wget; + _emscripten_async_wget.sig = 'vpppp'; - function _emscripten_async_wget_data(url, arg, onload, onerror) { + + var _emscripten_async_wget_data = (url, userdata, onload, onerror) => { - asyncLoad(UTF8ToString(url), function(byteArray) { + asyncLoad(UTF8ToString(url), (byteArray) => { - callUserCallback(function() { + callUserCallback(() => { var buffer = _malloc(byteArray.length); HEAPU8.set(byteArray, buffer); - getWasmTableEntry(onload)(arg, buffer, byteArray.length); + getWasmTableEntry(onload)(userdata, buffer, byteArray.length); _free(buffer); }); - }, function() { + }, () => { if (onerror) { - callUserCallback(function() { - getWasmTableEntry(onerror)(arg); + callUserCallback(() => { + getWasmTableEntry(onerror)(userdata); }); } }, true /* no need for run dependency, this is async but will not do any prepare etc. step */ ); - } - Module["_emscripten_async_wget_data"] = _emscripten_async_wget_data; - _emscripten_async_wget_data.sig = 'viiii'; + }; + Module['_emscripten_async_wget_data'] = _emscripten_async_wget_data; + _emscripten_async_wget_data.sig = 'vpppp'; - function _emscripten_async_wget2(url, file, request, param, arg, onload, onerror, onprogress) { + + var _emscripten_async_wget2 = (url, file, request, param, userdata, onload, onerror, onprogress) => { var _url = UTF8ToString(url); @@ -20647,7 +21881,7 @@ var ASM_CONSTS = { var destinationDirectory = PATH.dirname(_file); // LOAD - http.onload = function http_onload(e) { + http.onload = (e) => { if (http.status >= 200 && http.status < 300) { // if a file exists there, we overwrite it @@ -20659,34 +21893,34 @@ var ASM_CONSTS = { FS.createDataFile( _file.substr(0, index), _file.substr(index + 1), new Uint8Array(/** @type{ArrayBuffer}*/(http.response)), true, true, false); if (onload) { - withStackSave(function() { - getWasmTableEntry(onload)(handle, arg, allocateUTF8OnStack(_file)); + withStackSave(() => { + getWasmTableEntry(onload)(handle, userdata, stringToUTF8OnStack(_file)); }); } } else { - if (onerror) getWasmTableEntry(onerror)(handle, arg, http.status); + if (onerror) getWasmTableEntry(onerror)(handle, userdata, http.status); } delete wget.wgetRequests[handle]; }; // ERROR - http.onerror = function http_onerror(e) { + http.onerror = (e) => { - if (onerror) getWasmTableEntry(onerror)(handle, arg, http.status); + if (onerror) getWasmTableEntry(onerror)(handle, userdata, http.status); delete wget.wgetRequests[handle]; }; // PROGRESS - http.onprogress = function http_onprogress(e) { + http.onprogress = (e) => { if (e.lengthComputable || (e.lengthComputable === undefined && e.total != 0)) { var percentComplete = (e.loaded / e.total)*100; - if (onprogress) getWasmTableEntry(onprogress)(handle, arg, percentComplete); + if (onprogress) getWasmTableEntry(onprogress)(handle, userdata, percentComplete); } }; // ABORT - http.onabort = function http_onabort(e) { + http.onabort = (e) => { delete wget.wgetRequests[handle]; }; @@ -20702,14 +21936,15 @@ var ASM_CONSTS = { wget.wgetRequests[handle] = http; return handle; - } - Module["_emscripten_async_wget2"] = _emscripten_async_wget2; - _emscripten_async_wget2.sig = 'iiiiiiiii'; + }; + Module['_emscripten_async_wget2'] = _emscripten_async_wget2; + _emscripten_async_wget2.sig = 'ipppppppp'; - function _emscripten_async_wget2_data(url, request, param, arg, free, onload, onerror, onprogress) { + + var _emscripten_async_wget2_data = (url, request, param, userdata, free, onload, onerror, onprogress) => { var _url = UTF8ToString(url); var _request = UTF8ToString(request); var _param = UTF8ToString(param); @@ -20722,23 +21957,23 @@ var ASM_CONSTS = { function onerrorjs() { if (onerror) { - var statusText = 0; - if (http.statusText) { - var len = lengthBytesUTF8(http.statusText) + 1; - statusText = stackAlloc(len); - stringToUTF8(http.statusText, statusText, len); - } - getWasmTableEntry(onerror)(handle, arg, http.status, statusText); + withStackSave(() => { + var statusText = 0; + if (http.statusText) { + statusText = stringToUTF8OnStack(http.statusText); + } + getWasmTableEntry(onerror)(handle, userdata, http.status, statusText); + }); } } // LOAD - http.onload = function http_onload(e) { + http.onload = (e) => { if (http.status >= 200 && http.status < 300 || (http.status === 0 && _url.substr(0,4).toLowerCase() != "http")) { var byteArray = new Uint8Array(/** @type{ArrayBuffer} */(http.response)); var buffer = _malloc(byteArray.length); HEAPU8.set(byteArray, buffer); - if (onload) getWasmTableEntry(onload)(handle, arg, buffer, byteArray.length); + if (onload) getWasmTableEntry(onload)(handle, userdata, buffer, byteArray.length); if (free) _free(buffer); } else { onerrorjs(); @@ -20747,18 +21982,18 @@ var ASM_CONSTS = { }; // ERROR - http.onerror = function http_onerror(e) { + http.onerror = (e) => { onerrorjs(); delete wget.wgetRequests[handle]; }; // PROGRESS - http.onprogress = function http_onprogress(e) { - if (onprogress) getWasmTableEntry(onprogress)(handle, arg, e.loaded, e.lengthComputable || e.lengthComputable === undefined ? e.total : 0); + http.onprogress = (e) => { + if (onprogress) getWasmTableEntry(onprogress)(handle, userdata, e.loaded, e.lengthComputable || e.lengthComputable === undefined ? e.total : 0); }; // ABORT - http.onabort = function http_onabort(e) { + http.onabort = (e) => { delete wget.wgetRequests[handle]; }; @@ -20773,17 +22008,15 @@ var ASM_CONSTS = { wget.wgetRequests[handle] = http; return handle; - } - Module["_emscripten_async_wget2_data"] = _emscripten_async_wget2_data; - _emscripten_async_wget2_data.sig = 'iiiiiiiii'; + }; + Module['_emscripten_async_wget2_data'] = _emscripten_async_wget2_data; + _emscripten_async_wget2_data.sig = 'ippppippp'; - function _emscripten_async_wget2_abort(handle) { + var _emscripten_async_wget2_abort = (handle) => { var http = wget.wgetRequests[handle]; - if (http) { - http.abort(); - } - } - Module["_emscripten_async_wget2_abort"] = _emscripten_async_wget2_abort; + http?.abort(); + }; + Module['_emscripten_async_wget2_abort'] = _emscripten_async_wget2_abort; _emscripten_async_wget2_abort.sig = 'vi'; @@ -20791,14 +22024,117 @@ var ASM_CONSTS = { + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + var __dlsym_catchup_js = (handle, symbolIndex) => { + var lib = LDSO.loadedLibsByHandle[handle]; + var symDict = lib.exports; + var symName = Object.keys(symDict)[symbolIndex]; + var sym = symDict[symName]; + var result = addFunction(sym, sym.sig); + return result; + }; + Module['__dlsym_catchup_js'] = __dlsym_catchup_js; + __dlsym_catchup_js.sig = 'ppi'; + + + + + + + + + + + + + + + + + - function _setNetworkCallback(event, userData, callback) { + var _setNetworkCallback = (event, userData, callback) => { function _callback(data) { try { if (event === 'error') { withStackSave(function() { - var msg = allocateUTF8OnStack(data[2]); + var msg = stringToUTF8OnStack(data[2]); getWasmTableEntry(callback)(data[0], data[1], msg, userData); }); } else { @@ -20816,38 +22152,44 @@ var ASM_CONSTS = { // runtime alive indefinitely. Module['websocket']['on'](event, callback ? _callback : null); - } - Module["_setNetworkCallback"] = _setNetworkCallback; + }; + Module['_setNetworkCallback'] = _setNetworkCallback; - function _emscripten_set_socket_error_callback(userData, callback) { + var _emscripten_set_socket_error_callback = (userData, callback) => { _setNetworkCallback('error', userData, callback); - } - Module["_emscripten_set_socket_error_callback"] = _emscripten_set_socket_error_callback; + }; + Module['_emscripten_set_socket_error_callback'] = _emscripten_set_socket_error_callback; + _emscripten_set_socket_error_callback.sig = 'vpp'; - function _emscripten_set_socket_open_callback(userData, callback) { + var _emscripten_set_socket_open_callback = (userData, callback) => { _setNetworkCallback('open', userData, callback); - } - Module["_emscripten_set_socket_open_callback"] = _emscripten_set_socket_open_callback; + }; + Module['_emscripten_set_socket_open_callback'] = _emscripten_set_socket_open_callback; + _emscripten_set_socket_open_callback.sig = 'vpp'; - function _emscripten_set_socket_listen_callback(userData, callback) { + var _emscripten_set_socket_listen_callback = (userData, callback) => { _setNetworkCallback('listen', userData, callback); - } - Module["_emscripten_set_socket_listen_callback"] = _emscripten_set_socket_listen_callback; + }; + Module['_emscripten_set_socket_listen_callback'] = _emscripten_set_socket_listen_callback; + _emscripten_set_socket_listen_callback.sig = 'vpp'; - function _emscripten_set_socket_connection_callback(userData, callback) { + var _emscripten_set_socket_connection_callback = (userData, callback) => { _setNetworkCallback('connection', userData, callback); - } - Module["_emscripten_set_socket_connection_callback"] = _emscripten_set_socket_connection_callback; + }; + Module['_emscripten_set_socket_connection_callback'] = _emscripten_set_socket_connection_callback; + _emscripten_set_socket_connection_callback.sig = 'vpp'; - function _emscripten_set_socket_message_callback(userData, callback) { + var _emscripten_set_socket_message_callback = (userData, callback) => { _setNetworkCallback('message', userData, callback); - } - Module["_emscripten_set_socket_message_callback"] = _emscripten_set_socket_message_callback; + }; + Module['_emscripten_set_socket_message_callback'] = _emscripten_set_socket_message_callback; + _emscripten_set_socket_message_callback.sig = 'vpp'; - function _emscripten_set_socket_close_callback(userData, callback) { + var _emscripten_set_socket_close_callback = (userData, callback) => { _setNetworkCallback('close', userData, callback); - } - Module["_emscripten_set_socket_close_callback"] = _emscripten_set_socket_close_callback; + }; + Module['_emscripten_set_socket_close_callback'] = _emscripten_set_socket_close_callback; + _emscripten_set_socket_close_callback.sig = 'vpp'; @@ -20856,1856 +22198,421 @@ var ASM_CONSTS = { - function _emscripten_webgl_enable_ANGLE_instanced_arrays(ctx) { - return __webgl_enable_ANGLE_instanced_arrays(GL.contexts[ctx].GLctx); - } - Module["_emscripten_webgl_enable_ANGLE_instanced_arrays"] = _emscripten_webgl_enable_ANGLE_instanced_arrays; + var _emscripten_webgl_enable_ANGLE_instanced_arrays = (ctx) => webgl_enable_ANGLE_instanced_arrays(GL.contexts[ctx].GLctx); + Module['_emscripten_webgl_enable_ANGLE_instanced_arrays'] = _emscripten_webgl_enable_ANGLE_instanced_arrays; + _emscripten_webgl_enable_ANGLE_instanced_arrays.sig = 'ip'; - function _emscripten_webgl_enable_OES_vertex_array_object(ctx) { - return __webgl_enable_OES_vertex_array_object(GL.contexts[ctx].GLctx); - } - Module["_emscripten_webgl_enable_OES_vertex_array_object"] = _emscripten_webgl_enable_OES_vertex_array_object; + var _emscripten_webgl_enable_OES_vertex_array_object = (ctx) => webgl_enable_OES_vertex_array_object(GL.contexts[ctx].GLctx); + Module['_emscripten_webgl_enable_OES_vertex_array_object'] = _emscripten_webgl_enable_OES_vertex_array_object; + _emscripten_webgl_enable_OES_vertex_array_object.sig = 'ip'; - function _emscripten_webgl_enable_WEBGL_draw_buffers(ctx) { - return __webgl_enable_WEBGL_draw_buffers(GL.contexts[ctx].GLctx); - } - Module["_emscripten_webgl_enable_WEBGL_draw_buffers"] = _emscripten_webgl_enable_WEBGL_draw_buffers; + var _emscripten_webgl_enable_WEBGL_draw_buffers = (ctx) => webgl_enable_WEBGL_draw_buffers(GL.contexts[ctx].GLctx); + Module['_emscripten_webgl_enable_WEBGL_draw_buffers'] = _emscripten_webgl_enable_WEBGL_draw_buffers; + _emscripten_webgl_enable_WEBGL_draw_buffers.sig = 'ip'; - function _emscripten_webgl_enable_WEBGL_multi_draw(ctx) { - return __webgl_enable_WEBGL_multi_draw(GL.contexts[ctx].GLctx); - } - Module["_emscripten_webgl_enable_WEBGL_multi_draw"] = _emscripten_webgl_enable_WEBGL_multi_draw; + var _emscripten_webgl_enable_WEBGL_multi_draw = (ctx) => webgl_enable_WEBGL_multi_draw(GL.contexts[ctx].GLctx); + Module['_emscripten_webgl_enable_WEBGL_multi_draw'] = _emscripten_webgl_enable_WEBGL_multi_draw; + _emscripten_webgl_enable_WEBGL_multi_draw.sig = 'ip'; - function _glPixelStorei(pname, param) { - if (pname == 0xCF5 /* GL_UNPACK_ALIGNMENT */) { - GL.unpackAlignment = param; - } - GLctx.pixelStorei(pname, param); - } - Module["_glPixelStorei"] = _glPixelStorei; - _glPixelStorei.sig = 'vii'; - - function _glGetString(name_) { - var ret = GL.stringCache[name_]; - if (!ret) { - switch (name_) { - case 0x1F03 /* GL_EXTENSIONS */: - var exts = GLctx.getSupportedExtensions() || []; // .getSupportedExtensions() can return null if context is lost, so coerce to empty array. - exts = exts.concat(exts.map(function(e) { return "GL_" + e; })); - ret = stringToNewUTF8(exts.join(' ')); - break; - case 0x1F00 /* GL_VENDOR */: - case 0x1F01 /* GL_RENDERER */: - case 0x9245 /* UNMASKED_VENDOR_WEBGL */: - case 0x9246 /* UNMASKED_RENDERER_WEBGL */: - var s = GLctx.getParameter(name_); - if (!s) { - GL.recordError(0x500/*GL_INVALID_ENUM*/); - } - ret = s && stringToNewUTF8(s); - break; - - case 0x1F02 /* GL_VERSION */: - var glVersion = GLctx.getParameter(0x1F02 /*GL_VERSION*/); - // return GLES version string corresponding to the version of the WebGL context - { - glVersion = 'OpenGL ES 2.0 (' + glVersion + ')'; - } - ret = stringToNewUTF8(glVersion); - break; - case 0x8B8C /* GL_SHADING_LANGUAGE_VERSION */: - var glslVersion = GLctx.getParameter(0x8B8C /*GL_SHADING_LANGUAGE_VERSION*/); - // extract the version number 'N.M' from the string 'WebGL GLSL ES N.M ...' - var ver_re = /^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/; - var ver_num = glslVersion.match(ver_re); - if (ver_num !== null) { - if (ver_num[1].length == 3) ver_num[1] = ver_num[1] + '0'; // ensure minor version has 2 digits - glslVersion = 'OpenGL ES GLSL ES ' + ver_num[1] + ' (' + glslVersion + ')'; - } - ret = stringToNewUTF8(glslVersion); - break; - default: - GL.recordError(0x500/*GL_INVALID_ENUM*/); - // fall through - } - GL.stringCache[name_] = ret; - } - return ret; - } - Module["_glGetString"] = _glGetString; - _glGetString.sig = 'ii'; - - function _glGetIntegerv(name_, p) { - emscriptenWebGLGet(name_, p, 0); - } - Module["_glGetIntegerv"] = _glGetIntegerv; - _glGetIntegerv.sig = 'vii'; - - function _glGetFloatv(name_, p) { - emscriptenWebGLGet(name_, p, 2); - } - Module["_glGetFloatv"] = _glGetFloatv; - _glGetFloatv.sig = 'vii'; - - function _glGetBooleanv(name_, p) { - emscriptenWebGLGet(name_, p, 4); - } - Module["_glGetBooleanv"] = _glGetBooleanv; - _glGetBooleanv.sig = 'vii'; - function _glDeleteTextures(n, textures) { - for (var i = 0; i < n; i++) { - var id = HEAP32[(((textures)+(i*4))>>2)]; - var texture = GL.textures[id]; - if (!texture) continue; // GL spec: "glDeleteTextures silently ignores 0s and names that do not correspond to existing textures". - GLctx.deleteTexture(texture); - texture.name = 0; - GL.textures[id] = null; - } - } - Module["_glDeleteTextures"] = _glDeleteTextures; - _glDeleteTextures.sig = 'vii'; - function _glCompressedTexImage2D(target, level, internalFormat, width, height, border, imageSize, data) { - GLctx['compressedTexImage2D'](target, level, internalFormat, width, height, border, data ? HEAPU8.subarray((data), (data+imageSize)) : null); - } - Module["_glCompressedTexImage2D"] = _glCompressedTexImage2D; - _glCompressedTexImage2D.sig = 'viiiiiiii'; - function _glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data) { - GLctx['compressedTexSubImage2D'](target, level, xoffset, yoffset, width, height, format, data ? HEAPU8.subarray((data), (data+imageSize)) : null); - } - Module["_glCompressedTexSubImage2D"] = _glCompressedTexSubImage2D; - _glCompressedTexSubImage2D.sig = 'viiiiiiiii'; - - function _glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels) { - GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, internalFormat) : null); - } - Module["_glTexImage2D"] = _glTexImage2D; - _glTexImage2D.sig = 'viiiiiiiii'; - - function _glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels) { - var pixelData = null; - if (pixels) pixelData = emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, 0); - GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixelData); - } - Module["_glTexSubImage2D"] = _glTexSubImage2D; - _glTexSubImage2D.sig = 'viiiiiiiii'; - - function _glReadPixels(x, y, width, height, format, type, pixels) { - var pixelData = emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, format); - if (!pixelData) { - GL.recordError(0x500/*GL_INVALID_ENUM*/); - return; - } - GLctx.readPixels(x, y, width, height, format, type, pixelData); - } - Module["_glReadPixels"] = _glReadPixels; - _glReadPixels.sig = 'viiiiiii'; - function _glBindTexture(target, texture) { - GLctx.bindTexture(target, GL.textures[texture]); - } - Module["_glBindTexture"] = _glBindTexture; - _glBindTexture.sig = 'vii'; - function _glGetTexParameterfv(target, pname, params) { - if (!params) { - // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense - // if p == null, issue a GL error to notify user about it. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - HEAPF32[((params)>>2)] = GLctx.getTexParameter(target, pname); - } - Module["_glGetTexParameterfv"] = _glGetTexParameterfv; - _glGetTexParameterfv.sig = 'viii'; - function _glGetTexParameteriv(target, pname, params) { - if (!params) { - // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense - // if p == null, issue a GL error to notify user about it. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - HEAP32[((params)>>2)] = GLctx.getTexParameter(target, pname); - } - Module["_glGetTexParameteriv"] = _glGetTexParameteriv; - _glGetTexParameteriv.sig = 'viii'; - function _glTexParameterfv(target, pname, params) { - var param = HEAPF32[((params)>>2)]; - GLctx.texParameterf(target, pname, param); - } - Module["_glTexParameterfv"] = _glTexParameterfv; - _glTexParameterfv.sig = 'viii'; - function _glTexParameteriv(target, pname, params) { - var param = HEAP32[((params)>>2)]; - GLctx.texParameteri(target, pname, param); - } - Module["_glTexParameteriv"] = _glTexParameteriv; - _glTexParameteriv.sig = 'viii'; - function _glIsTexture(id) { - var texture = GL.textures[id]; - if (!texture) return 0; - return GLctx.isTexture(texture); - } - Module["_glIsTexture"] = _glIsTexture; - _glIsTexture.sig = 'ii'; - - function _glGenBuffers(n, buffers) { - __glGenObject(n, buffers, 'createBuffer', GL.buffers - ); - } - Module["_glGenBuffers"] = _glGenBuffers; - _glGenBuffers.sig = 'vii'; - - function _glGenTextures(n, textures) { - __glGenObject(n, textures, 'createTexture', GL.textures - ); - } - Module["_glGenTextures"] = _glGenTextures; - _glGenTextures.sig = 'vii'; - function _glDeleteBuffers(n, buffers) { - for (var i = 0; i < n; i++) { - var id = HEAP32[(((buffers)+(i*4))>>2)]; - var buffer = GL.buffers[id]; - - // From spec: "glDeleteBuffers silently ignores 0's and names that do not - // correspond to existing buffer objects." - if (!buffer) continue; - - GLctx.deleteBuffer(buffer); - buffer.name = 0; - GL.buffers[id] = null; - - } - } - Module["_glDeleteBuffers"] = _glDeleteBuffers; - _glDeleteBuffers.sig = 'vii'; - function _glGetBufferParameteriv(target, value, data) { - if (!data) { - // GLES2 specification does not specify how to behave if data is a null pointer. Since calling this function does not make sense - // if data == null, issue a GL error to notify user about it. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - HEAP32[((data)>>2)] = GLctx.getBufferParameter(target, value); - } - Module["_glGetBufferParameteriv"] = _glGetBufferParameteriv; - _glGetBufferParameteriv.sig = 'viii'; - function _glBufferData(target, size, data, usage) { - - // N.b. here first form specifies a heap subarray, second form an integer size, so the ?: code here is polymorphic. It is advised to avoid - // randomly mixing both uses in calling code, to avoid any potential JS engine JIT issues. - GLctx.bufferData(target, data ? HEAPU8.subarray(data, data+size) : size, usage); - } - Module["_glBufferData"] = _glBufferData; - _glBufferData.sig = 'viiii'; - function _glBufferSubData(target, offset, size, data) { - GLctx.bufferSubData(target, offset, HEAPU8.subarray(data, data+size)); - } - Module["_glBufferSubData"] = _glBufferSubData; - _glBufferSubData.sig = 'viiii'; - function _glGenQueriesEXT(n, ids) { - for (var i = 0; i < n; i++) { - var query = GLctx.disjointTimerQueryExt['createQueryEXT'](); - if (!query) { - GL.recordError(0x502 /* GL_INVALID_OPERATION */); - while (i < n) HEAP32[(((ids)+(i++*4))>>2)] = 0; - return; - } - var id = GL.getNewId(GL.queries); - query.name = id; - GL.queries[id] = query; - HEAP32[(((ids)+(i*4))>>2)] = id; - } - } - Module["_glGenQueriesEXT"] = _glGenQueriesEXT; - _glGenQueriesEXT.sig = 'vii'; - function _glDeleteQueriesEXT(n, ids) { - for (var i = 0; i < n; i++) { - var id = HEAP32[(((ids)+(i*4))>>2)]; - var query = GL.queries[id]; - if (!query) continue; // GL spec: "unused names in ids are ignored, as is the name zero." - GLctx.disjointTimerQueryExt['deleteQueryEXT'](query); - GL.queries[id] = null; - } - } - Module["_glDeleteQueriesEXT"] = _glDeleteQueriesEXT; - _glDeleteQueriesEXT.sig = 'vii'; - function _glIsQueryEXT(id) { - var query = GL.queries[id]; - if (!query) return 0; - return GLctx.disjointTimerQueryExt['isQueryEXT'](query); - } - Module["_glIsQueryEXT"] = _glIsQueryEXT; - _glIsQueryEXT.sig = 'ii'; - function _glBeginQueryEXT(target, id) { - GLctx.disjointTimerQueryExt['beginQueryEXT'](target, GL.queries[id]); - } - Module["_glBeginQueryEXT"] = _glBeginQueryEXT; - _glBeginQueryEXT.sig = 'vii'; - function _glEndQueryEXT(target) { - GLctx.disjointTimerQueryExt['endQueryEXT'](target); - } - Module["_glEndQueryEXT"] = _glEndQueryEXT; - _glEndQueryEXT.sig = 'vi'; - function _glQueryCounterEXT(id, target) { - GLctx.disjointTimerQueryExt['queryCounterEXT'](GL.queries[id], target); - } - Module["_glQueryCounterEXT"] = _glQueryCounterEXT; - _glQueryCounterEXT.sig = 'vii'; - function _glGetQueryivEXT(target, pname, params) { - if (!params) { - // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense - // if p == null, issue a GL error to notify user about it. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - HEAP32[((params)>>2)] = GLctx.disjointTimerQueryExt['getQueryEXT'](target, pname); - } - Module["_glGetQueryivEXT"] = _glGetQueryivEXT; - _glGetQueryivEXT.sig = 'viii'; - function _glGetQueryObjectivEXT(id, pname, params) { - if (!params) { - // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense - // if p == null, issue a GL error to notify user about it. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - var query = GL.queries[id]; - var param = GLctx.disjointTimerQueryExt['getQueryObjectEXT'](query, pname); - var ret; - if (typeof param == 'boolean') { - ret = param ? 1 : 0; - } else { - ret = param; - } - HEAP32[((params)>>2)] = ret; - } - Module["_glGetQueryObjectivEXT"] = _glGetQueryObjectivEXT; - _glGetQueryObjectivEXT.sig = 'viii'; - function _glGetQueryObjectuivEXT(id, pname, params) { - if (!params) { - // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense - // if p == null, issue a GL error to notify user about it. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - var query = GL.queries[id]; - var param = GLctx.disjointTimerQueryExt['getQueryObjectEXT'](query, pname); - var ret; - if (typeof param == 'boolean') { - ret = param ? 1 : 0; - } else { - ret = param; - } - HEAP32[((params)>>2)] = ret; - } - Module["_glGetQueryObjectuivEXT"] = _glGetQueryObjectuivEXT; - _glGetQueryObjectuivEXT.sig = 'viii'; - - function _glGetQueryObjecti64vEXT(id, pname, params) { - if (!params) { - // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense - // if p == null, issue a GL error to notify user about it. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - var query = GL.queries[id]; - var param; - { - param = GLctx.disjointTimerQueryExt['getQueryObjectEXT'](query, pname); - } - var ret; - if (typeof param == 'boolean') { - ret = param ? 1 : 0; - } else { - ret = param; - } - writeI53ToI64(params, ret); - } - Module["_glGetQueryObjecti64vEXT"] = _glGetQueryObjecti64vEXT; - _glGetQueryObjecti64vEXT.sig = 'viii'; - - function _glGetQueryObjectui64vEXT(id, pname, params) { - if (!params) { - // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense - // if p == null, issue a GL error to notify user about it. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - var query = GL.queries[id]; - var param; - { - param = GLctx.disjointTimerQueryExt['getQueryObjectEXT'](query, pname); - } - var ret; - if (typeof param == 'boolean') { - ret = param ? 1 : 0; - } else { - ret = param; - } - writeI53ToI64(params, ret); - } - Module["_glGetQueryObjectui64vEXT"] = _glGetQueryObjectui64vEXT; - _glGetQueryObjectui64vEXT.sig = 'viii'; - function _glIsBuffer(buffer) { - var b = GL.buffers[buffer]; - if (!b) return 0; - return GLctx.isBuffer(b); - } - Module["_glIsBuffer"] = _glIsBuffer; - _glIsBuffer.sig = 'ii'; - - function _glGenRenderbuffers(n, renderbuffers) { - __glGenObject(n, renderbuffers, 'createRenderbuffer', GL.renderbuffers - ); - } - Module["_glGenRenderbuffers"] = _glGenRenderbuffers; - _glGenRenderbuffers.sig = 'vii'; - function _glDeleteRenderbuffers(n, renderbuffers) { - for (var i = 0; i < n; i++) { - var id = HEAP32[(((renderbuffers)+(i*4))>>2)]; - var renderbuffer = GL.renderbuffers[id]; - if (!renderbuffer) continue; // GL spec: "glDeleteRenderbuffers silently ignores 0s and names that do not correspond to existing renderbuffer objects". - GLctx.deleteRenderbuffer(renderbuffer); - renderbuffer.name = 0; - GL.renderbuffers[id] = null; - } - } - Module["_glDeleteRenderbuffers"] = _glDeleteRenderbuffers; - _glDeleteRenderbuffers.sig = 'vii'; - function _glBindRenderbuffer(target, renderbuffer) { - GLctx.bindRenderbuffer(target, GL.renderbuffers[renderbuffer]); - } - Module["_glBindRenderbuffer"] = _glBindRenderbuffer; - _glBindRenderbuffer.sig = 'vii'; - function _glGetRenderbufferParameteriv(target, pname, params) { - if (!params) { - // GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense - // if params == null, issue a GL error to notify user about it. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - HEAP32[((params)>>2)] = GLctx.getRenderbufferParameter(target, pname); - } - Module["_glGetRenderbufferParameteriv"] = _glGetRenderbufferParameteriv; - _glGetRenderbufferParameteriv.sig = 'viii'; - function _glIsRenderbuffer(renderbuffer) { - var rb = GL.renderbuffers[renderbuffer]; - if (!rb) return 0; - return GLctx.isRenderbuffer(rb); - } - Module["_glIsRenderbuffer"] = _glIsRenderbuffer; - _glIsRenderbuffer.sig = 'ii'; - - function _glGetUniformfv(program, location, params) { - emscriptenWebGLGetUniform(program, location, params, 2); - } - Module["_glGetUniformfv"] = _glGetUniformfv; - _glGetUniformfv.sig = 'viii'; - - function _glGetUniformiv(program, location, params) { - emscriptenWebGLGetUniform(program, location, params, 0); - } - Module["_glGetUniformiv"] = _glGetUniformiv; - _glGetUniformiv.sig = 'viii'; - - - - function _glGetUniformLocation(program, name) { - - name = UTF8ToString(name); - - if (program = GL.programs[program]) { - webglPrepareUniformLocationsBeforeFirstUse(program); - var uniformLocsById = program.uniformLocsById; // Maps GLuint -> WebGLUniformLocation - var arrayIndex = 0; - var uniformBaseName = name; - - // Invariant: when populating integer IDs for uniform locations, we must maintain the precondition that - // arrays reside in contiguous addresses, i.e. for a 'vec4 colors[10];', colors[4] must be at location colors[0]+4. - // However, user might call glGetUniformLocation(program, "colors") for an array, so we cannot discover based on the user - // input arguments whether the uniform we are dealing with is an array. The only way to discover which uniforms are arrays - // is to enumerate over all the active uniforms in the program. - var leftBrace = webglGetLeftBracePos(name); - - // If user passed an array accessor "[index]", parse the array index off the accessor. - if (leftBrace > 0) { - arrayIndex = jstoi_q(name.slice(leftBrace + 1)) >>> 0; // "index]", coerce parseInt(']') with >>>0 to treat "foo[]" as "foo[0]" and foo[-1] as unsigned out-of-bounds. - uniformBaseName = name.slice(0, leftBrace); - } - - // Have we cached the location of this uniform before? - var sizeAndId = program.uniformSizeAndIdsByName[uniformBaseName]; // A pair [array length, GLint of the uniform location] - - // If an uniform with this name exists, and if its index is within the array limits (if it's even an array), - // query the WebGLlocation, or return an existing cached location. - if (sizeAndId && arrayIndex < sizeAndId[0]) { - arrayIndex += sizeAndId[1]; // Add the base location of the uniform to the array index offset. - if ((uniformLocsById[arrayIndex] = uniformLocsById[arrayIndex] || GLctx.getUniformLocation(program, name))) { - return arrayIndex; - } - } - } - else { - // N.b. we are currently unable to distinguish between GL program IDs that never existed vs GL program IDs that have been deleted, - // so report GL_INVALID_VALUE in both cases. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - } - return -1; - } - Module["_glGetUniformLocation"] = _glGetUniformLocation; - _glGetUniformLocation.sig = 'iii'; - - function _glGetVertexAttribfv(index, pname, params) { - // N.B. This function may only be called if the vertex attribute was specified using the function glVertexAttrib*f(), - // otherwise the results are undefined. (GLES3 spec 6.1.12) - emscriptenWebGLGetVertexAttrib(index, pname, params, 2); - } - Module["_glGetVertexAttribfv"] = _glGetVertexAttribfv; - _glGetVertexAttribfv.sig = 'viii'; - - function _glGetVertexAttribiv(index, pname, params) { - // N.B. This function may only be called if the vertex attribute was specified using the function glVertexAttrib*f(), - // otherwise the results are undefined. (GLES3 spec 6.1.12) - emscriptenWebGLGetVertexAttrib(index, pname, params, 5); - } - Module["_glGetVertexAttribiv"] = _glGetVertexAttribiv; - _glGetVertexAttribiv.sig = 'viii'; - function _glGetVertexAttribPointerv(index, pname, pointer) { - if (!pointer) { - // GLES2 specification does not specify how to behave if pointer is a null pointer. Since calling this function does not make sense - // if pointer == null, issue a GL error to notify user about it. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - HEAP32[((pointer)>>2)] = GLctx.getVertexAttribOffset(index, pname); - } - Module["_glGetVertexAttribPointerv"] = _glGetVertexAttribPointerv; - _glGetVertexAttribPointerv.sig = 'viii'; - - function _glUniform1f(location, v0) { - GLctx.uniform1f(webglGetUniformLocation(location), v0); - } - Module["_glUniform1f"] = _glUniform1f; - _glUniform1f.sig = 'vif'; - - function _glUniform2f(location, v0, v1) { - GLctx.uniform2f(webglGetUniformLocation(location), v0, v1); - } - Module["_glUniform2f"] = _glUniform2f; - _glUniform2f.sig = 'viff'; - - function _glUniform3f(location, v0, v1, v2) { - GLctx.uniform3f(webglGetUniformLocation(location), v0, v1, v2); - } - Module["_glUniform3f"] = _glUniform3f; - _glUniform3f.sig = 'vifff'; - - function _glUniform4f(location, v0, v1, v2, v3) { - GLctx.uniform4f(webglGetUniformLocation(location), v0, v1, v2, v3); - } - Module["_glUniform4f"] = _glUniform4f; - _glUniform4f.sig = 'viffff'; - - function _glUniform1i(location, v0) { - GLctx.uniform1i(webglGetUniformLocation(location), v0); - } - Module["_glUniform1i"] = _glUniform1i; - _glUniform1i.sig = 'vii'; - - function _glUniform2i(location, v0, v1) { - GLctx.uniform2i(webglGetUniformLocation(location), v0, v1); - } - Module["_glUniform2i"] = _glUniform2i; - _glUniform2i.sig = 'viii'; - - function _glUniform3i(location, v0, v1, v2) { - GLctx.uniform3i(webglGetUniformLocation(location), v0, v1, v2); - } - Module["_glUniform3i"] = _glUniform3i; - _glUniform3i.sig = 'viiii'; - - function _glUniform4i(location, v0, v1, v2, v3) { - GLctx.uniform4i(webglGetUniformLocation(location), v0, v1, v2, v3); - } - Module["_glUniform4i"] = _glUniform4i; - _glUniform4i.sig = 'viiiii'; - - - function _glUniform1iv(location, count, value) { - - if (count <= 288) { - // avoid allocation when uploading few enough uniforms - var view = __miniTempWebGLIntBuffers[count-1]; - for (var i = 0; i < count; ++i) { - view[i] = HEAP32[(((value)+(4*i))>>2)]; - } - } else - { - var view = HEAP32.subarray((value)>>2, (value+count*4)>>2); - } - GLctx.uniform1iv(webglGetUniformLocation(location), view); - } - Module["_glUniform1iv"] = _glUniform1iv; - _glUniform1iv.sig = 'viii'; - - - function _glUniform2iv(location, count, value) { - - if (count <= 144) { - // avoid allocation when uploading few enough uniforms - var view = __miniTempWebGLIntBuffers[2*count-1]; - for (var i = 0; i < 2*count; i += 2) { - view[i] = HEAP32[(((value)+(4*i))>>2)]; - view[i+1] = HEAP32[(((value)+(4*i+4))>>2)]; - } - } else - { - var view = HEAP32.subarray((value)>>2, (value+count*8)>>2); - } - GLctx.uniform2iv(webglGetUniformLocation(location), view); - } - Module["_glUniform2iv"] = _glUniform2iv; - _glUniform2iv.sig = 'viii'; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + var _glVertexPointer = (size, type, stride, ptr) => { + throw 'Legacy GL function (glVertexPointer) called. If you want legacy GL emulation, you need to compile with -sLEGACY_GL_EMULATION to enable legacy GL emulation.'; + }; + Module['_glVertexPointer'] = _glVertexPointer; + _glVertexPointer.sig = 'viiip'; + + var _glMatrixMode = () => { + throw 'Legacy GL function (glMatrixMode) called. If you want legacy GL emulation, you need to compile with -sLEGACY_GL_EMULATION to enable legacy GL emulation.'; + }; + Module['_glMatrixMode'] = _glMatrixMode; + _glMatrixMode.sig = 'vi'; + + var _glBegin = () => { + throw 'Legacy GL function (glBegin) called. If you want legacy GL emulation, you need to compile with -sLEGACY_GL_EMULATION to enable legacy GL emulation.'; + }; + Module['_glBegin'] = _glBegin; + _glBegin.sig = 'vi'; + + var _glLoadIdentity = () => { + throw 'Legacy GL function (glLoadIdentity) called. If you want legacy GL emulation, you need to compile with -sLEGACY_GL_EMULATION to enable legacy GL emulation.'; + }; + Module['_glLoadIdentity'] = _glLoadIdentity; + _glLoadIdentity.sig = 'v'; + + + + + + + + + + + + + + + - - function _glUniform3iv(location, count, value) { - - if (count <= 96) { - // avoid allocation when uploading few enough uniforms - var view = __miniTempWebGLIntBuffers[3*count-1]; - for (var i = 0; i < 3*count; i += 3) { - view[i] = HEAP32[(((value)+(4*i))>>2)]; - view[i+1] = HEAP32[(((value)+(4*i+4))>>2)]; - view[i+2] = HEAP32[(((value)+(4*i+8))>>2)]; - } - } else - { - var view = HEAP32.subarray((value)>>2, (value+count*12)>>2); - } - GLctx.uniform3iv(webglGetUniformLocation(location), view); - } - Module["_glUniform3iv"] = _glUniform3iv; - _glUniform3iv.sig = 'viii'; + var _glVertexAttribDivisorNV = _glVertexAttribDivisor; + Module['_glVertexAttribDivisorNV'] = _glVertexAttribDivisorNV; + var _glDrawArraysInstancedNV = _glDrawArraysInstanced; + Module['_glDrawArraysInstancedNV'] = _glDrawArraysInstancedNV; + - function _glUniform4iv(location, count, value) { + var _glDrawElementsInstancedNV = _glDrawElementsInstanced; + Module['_glDrawElementsInstancedNV'] = _glDrawElementsInstancedNV; + - if (count <= 72) { - // avoid allocation when uploading few enough uniforms - var view = __miniTempWebGLIntBuffers[4*count-1]; - for (var i = 0; i < 4*count; i += 4) { - view[i] = HEAP32[(((value)+(4*i))>>2)]; - view[i+1] = HEAP32[(((value)+(4*i+4))>>2)]; - view[i+2] = HEAP32[(((value)+(4*i+8))>>2)]; - view[i+3] = HEAP32[(((value)+(4*i+12))>>2)]; - } - } else - { - var view = HEAP32.subarray((value)>>2, (value+count*16)>>2); - } - GLctx.uniform4iv(webglGetUniformLocation(location), view); - } - Module["_glUniform4iv"] = _glUniform4iv; - _glUniform4iv.sig = 'viii'; + var _glVertexAttribDivisorEXT = _glVertexAttribDivisor; + Module['_glVertexAttribDivisorEXT'] = _glVertexAttribDivisorEXT; + var _glDrawArraysInstancedEXT = _glDrawArraysInstanced; + Module['_glDrawArraysInstancedEXT'] = _glDrawArraysInstancedEXT; + - function _glUniform1fv(location, count, value) { + var _glDrawElementsInstancedEXT = _glDrawElementsInstanced; + Module['_glDrawElementsInstancedEXT'] = _glDrawElementsInstancedEXT; + - if (count <= 288) { - // avoid allocation when uploading few enough uniforms - var view = miniTempWebGLFloatBuffers[count-1]; - for (var i = 0; i < count; ++i) { - view[i] = HEAPF32[(((value)+(4*i))>>2)]; - } - } else - { - var view = HEAPF32.subarray((value)>>2, (value+count*4)>>2); - } - GLctx.uniform1fv(webglGetUniformLocation(location), view); - } - Module["_glUniform1fv"] = _glUniform1fv; - _glUniform1fv.sig = 'viii'; + var _glVertexAttribDivisorARB = _glVertexAttribDivisor; + Module['_glVertexAttribDivisorARB'] = _glVertexAttribDivisorARB; + var _glDrawArraysInstancedARB = _glDrawArraysInstanced; + Module['_glDrawArraysInstancedARB'] = _glDrawArraysInstancedARB; + - function _glUniform2fv(location, count, value) { + var _glDrawElementsInstancedARB = _glDrawElementsInstanced; + Module['_glDrawElementsInstancedARB'] = _glDrawElementsInstancedARB; + + + + + - if (count <= 144) { - // avoid allocation when uploading few enough uniforms - var view = miniTempWebGLFloatBuffers[2*count-1]; - for (var i = 0; i < 2*count; i += 2) { - view[i] = HEAPF32[(((value)+(4*i))>>2)]; - view[i+1] = HEAPF32[(((value)+(4*i+4))>>2)]; - } - } else - { - var view = HEAPF32.subarray((value)>>2, (value+count*8)>>2); - } - GLctx.uniform2fv(webglGetUniformLocation(location), view); - } - Module["_glUniform2fv"] = _glUniform2fv; - _glUniform2fv.sig = 'viii'; + var _glDrawBuffersEXT = _glDrawBuffers; + Module['_glDrawBuffersEXT'] = _glDrawBuffersEXT; + + + + + /** @suppress {duplicate } */ + var _glMultiDrawArraysWEBGL = (mode, firsts, counts, drawcount) => { + GLctx.multiDrawWebgl['multiDrawArraysWEBGL']( + mode, + HEAP32, + ((firsts)>>2), + HEAP32, + ((counts)>>2), + drawcount); + }; + Module['_glMultiDrawArraysWEBGL'] = _glMultiDrawArraysWEBGL; + _glMultiDrawArraysWEBGL.sig = 'vippi'; + var _glMultiDrawArrays = _glMultiDrawArraysWEBGL; + Module['_glMultiDrawArrays'] = _glMultiDrawArrays; + _glMultiDrawArrays.sig = 'vippi'; + - function _glUniform3fv(location, count, value) { + var _glMultiDrawArraysANGLE = _glMultiDrawArraysWEBGL; + Module['_glMultiDrawArraysANGLE'] = _glMultiDrawArraysANGLE; + + - if (count <= 96) { - // avoid allocation when uploading few enough uniforms - var view = miniTempWebGLFloatBuffers[3*count-1]; - for (var i = 0; i < 3*count; i += 3) { - view[i] = HEAPF32[(((value)+(4*i))>>2)]; - view[i+1] = HEAPF32[(((value)+(4*i+4))>>2)]; - view[i+2] = HEAPF32[(((value)+(4*i+8))>>2)]; - } - } else - { - var view = HEAPF32.subarray((value)>>2, (value+count*12)>>2); - } - GLctx.uniform3fv(webglGetUniformLocation(location), view); - } - Module["_glUniform3fv"] = _glUniform3fv; - _glUniform3fv.sig = 'viii'; + /** @suppress {duplicate } */ + var _glMultiDrawArraysInstancedWEBGL = (mode, firsts, counts, instanceCounts, drawcount) => { + GLctx.multiDrawWebgl['multiDrawArraysInstancedWEBGL']( + mode, + HEAP32, + ((firsts)>>2), + HEAP32, + ((counts)>>2), + HEAP32, + ((instanceCounts)>>2), + drawcount); + }; + Module['_glMultiDrawArraysInstancedWEBGL'] = _glMultiDrawArraysInstancedWEBGL; + _glMultiDrawArraysInstancedWEBGL.sig = 'vipppi'; + var _glMultiDrawArraysInstancedANGLE = _glMultiDrawArraysInstancedWEBGL; + Module['_glMultiDrawArraysInstancedANGLE'] = _glMultiDrawArraysInstancedANGLE; + + /** @suppress {duplicate } */ + var _glMultiDrawElementsWEBGL = (mode, counts, type, offsets, drawcount) => { + GLctx.multiDrawWebgl['multiDrawElementsWEBGL']( + mode, + HEAP32, + ((counts)>>2), + type, + HEAP32, + ((offsets)>>2), + drawcount); + }; + Module['_glMultiDrawElementsWEBGL'] = _glMultiDrawElementsWEBGL; + _glMultiDrawElementsWEBGL.sig = 'vipipi'; + var _glMultiDrawElements = _glMultiDrawElementsWEBGL; + Module['_glMultiDrawElements'] = _glMultiDrawElements; + _glMultiDrawElements.sig = 'vipipi'; + - function _glUniform4fv(location, count, value) { + var _glMultiDrawElementsANGLE = _glMultiDrawElementsWEBGL; + Module['_glMultiDrawElementsANGLE'] = _glMultiDrawElementsANGLE; + + - if (count <= 72) { - // avoid allocation when uploading few enough uniforms - var view = miniTempWebGLFloatBuffers[4*count-1]; - // hoist the heap out of the loop for size and for pthreads+growth. - var heap = HEAPF32; - value >>= 2; - for (var i = 0; i < 4 * count; i += 4) { - var dst = value + i; - view[i] = heap[dst]; - view[i + 1] = heap[dst + 1]; - view[i + 2] = heap[dst + 2]; - view[i + 3] = heap[dst + 3]; - } - } else - { - var view = HEAPF32.subarray((value)>>2, (value+count*16)>>2); - } - GLctx.uniform4fv(webglGetUniformLocation(location), view); - } - Module["_glUniform4fv"] = _glUniform4fv; - _glUniform4fv.sig = 'viii'; + /** @suppress {duplicate } */ + var _glMultiDrawElementsInstancedWEBGL = (mode, counts, type, offsets, instanceCounts, drawcount) => { + GLctx.multiDrawWebgl['multiDrawElementsInstancedWEBGL']( + mode, + HEAP32, + ((counts)>>2), + type, + HEAP32, + ((offsets)>>2), + HEAP32, + ((instanceCounts)>>2), + drawcount); + }; + Module['_glMultiDrawElementsInstancedWEBGL'] = _glMultiDrawElementsInstancedWEBGL; + _glMultiDrawElementsInstancedWEBGL.sig = 'vipippi'; + var _glMultiDrawElementsInstancedANGLE = _glMultiDrawElementsInstancedWEBGL; + Module['_glMultiDrawElementsInstancedANGLE'] = _glMultiDrawElementsInstancedANGLE; - - - function _glUniformMatrix2fv(location, count, transpose, value) { - - if (count <= 72) { - // avoid allocation when uploading few enough uniforms - var view = miniTempWebGLFloatBuffers[4*count-1]; - for (var i = 0; i < 4*count; i += 4) { - view[i] = HEAPF32[(((value)+(4*i))>>2)]; - view[i+1] = HEAPF32[(((value)+(4*i+4))>>2)]; - view[i+2] = HEAPF32[(((value)+(4*i+8))>>2)]; - view[i+3] = HEAPF32[(((value)+(4*i+12))>>2)]; - } - } else - { - var view = HEAPF32.subarray((value)>>2, (value+count*16)>>2); - } - GLctx.uniformMatrix2fv(webglGetUniformLocation(location), !!transpose, view); - } - Module["_glUniformMatrix2fv"] = _glUniformMatrix2fv; - _glUniformMatrix2fv.sig = 'viiii'; - - - function _glUniformMatrix3fv(location, count, transpose, value) { - - if (count <= 32) { - // avoid allocation when uploading few enough uniforms - var view = miniTempWebGLFloatBuffers[9*count-1]; - for (var i = 0; i < 9*count; i += 9) { - view[i] = HEAPF32[(((value)+(4*i))>>2)]; - view[i+1] = HEAPF32[(((value)+(4*i+4))>>2)]; - view[i+2] = HEAPF32[(((value)+(4*i+8))>>2)]; - view[i+3] = HEAPF32[(((value)+(4*i+12))>>2)]; - view[i+4] = HEAPF32[(((value)+(4*i+16))>>2)]; - view[i+5] = HEAPF32[(((value)+(4*i+20))>>2)]; - view[i+6] = HEAPF32[(((value)+(4*i+24))>>2)]; - view[i+7] = HEAPF32[(((value)+(4*i+28))>>2)]; - view[i+8] = HEAPF32[(((value)+(4*i+32))>>2)]; - } - } else - { - var view = HEAPF32.subarray((value)>>2, (value+count*36)>>2); - } - GLctx.uniformMatrix3fv(webglGetUniformLocation(location), !!transpose, view); - } - Module["_glUniformMatrix3fv"] = _glUniformMatrix3fv; - _glUniformMatrix3fv.sig = 'viiii'; - - - function _glUniformMatrix4fv(location, count, transpose, value) { - - if (count <= 18) { - // avoid allocation when uploading few enough uniforms - var view = miniTempWebGLFloatBuffers[16*count-1]; - // hoist the heap out of the loop for size and for pthreads+growth. - var heap = HEAPF32; - value >>= 2; - for (var i = 0; i < 16 * count; i += 16) { - var dst = value + i; - view[i] = heap[dst]; - view[i + 1] = heap[dst + 1]; - view[i + 2] = heap[dst + 2]; - view[i + 3] = heap[dst + 3]; - view[i + 4] = heap[dst + 4]; - view[i + 5] = heap[dst + 5]; - view[i + 6] = heap[dst + 6]; - view[i + 7] = heap[dst + 7]; - view[i + 8] = heap[dst + 8]; - view[i + 9] = heap[dst + 9]; - view[i + 10] = heap[dst + 10]; - view[i + 11] = heap[dst + 11]; - view[i + 12] = heap[dst + 12]; - view[i + 13] = heap[dst + 13]; - view[i + 14] = heap[dst + 14]; - view[i + 15] = heap[dst + 15]; - } - } else - { - var view = HEAPF32.subarray((value)>>2, (value+count*64)>>2); - } - GLctx.uniformMatrix4fv(webglGetUniformLocation(location), !!transpose, view); - } - Module["_glUniformMatrix4fv"] = _glUniformMatrix4fv; - _glUniformMatrix4fv.sig = 'viiii'; - function _glBindBuffer(target, buffer) { - - GLctx.bindBuffer(target, GL.buffers[buffer]); - } - Module["_glBindBuffer"] = _glBindBuffer; - _glBindBuffer.sig = 'vii'; + var _glClearDepth = (x0) => GLctx.clearDepth(x0); + Module['_glClearDepth'] = _glClearDepth; + _glClearDepth.sig = 'vd'; - function _glVertexAttrib1fv(index, v) { - - GLctx.vertexAttrib1f(index, HEAPF32[v>>2]); - } - Module["_glVertexAttrib1fv"] = _glVertexAttrib1fv; - _glVertexAttrib1fv.sig = 'vii'; - function _glVertexAttrib2fv(index, v) { - - GLctx.vertexAttrib2f(index, HEAPF32[v>>2], HEAPF32[v+4>>2]); - } - Module["_glVertexAttrib2fv"] = _glVertexAttrib2fv; - _glVertexAttrib2fv.sig = 'vii'; - function _glVertexAttrib3fv(index, v) { - - GLctx.vertexAttrib3f(index, HEAPF32[v>>2], HEAPF32[v+4>>2], HEAPF32[v+8>>2]); - } - Module["_glVertexAttrib3fv"] = _glVertexAttrib3fv; - _glVertexAttrib3fv.sig = 'vii'; - function _glVertexAttrib4fv(index, v) { - - GLctx.vertexAttrib4f(index, HEAPF32[v>>2], HEAPF32[v+4>>2], HEAPF32[v+8>>2], HEAPF32[v+12>>2]); - } - Module["_glVertexAttrib4fv"] = _glVertexAttrib4fv; - _glVertexAttrib4fv.sig = 'vii'; - function _glGetAttribLocation(program, name) { - return GLctx.getAttribLocation(GL.programs[program], UTF8ToString(name)); - } - Module["_glGetAttribLocation"] = _glGetAttribLocation; - _glGetAttribLocation.sig = 'iii'; - - function _glGetActiveAttrib(program, index, bufSize, length, size, type, name) { - __glGetActiveAttribOrUniform('getActiveAttrib', program, index, bufSize, length, size, type, name); - } - Module["_glGetActiveAttrib"] = _glGetActiveAttrib; - _glGetActiveAttrib.sig = 'viiiiiii'; - - function _glGetActiveUniform(program, index, bufSize, length, size, type, name) { - __glGetActiveAttribOrUniform('getActiveUniform', program, index, bufSize, length, size, type, name); - } - Module["_glGetActiveUniform"] = _glGetActiveUniform; - _glGetActiveUniform.sig = 'viiiiiii'; - function _glCreateShader(shaderType) { - var id = GL.getNewId(GL.shaders); - GL.shaders[id] = GLctx.createShader(shaderType); - - return id; - } - Module["_glCreateShader"] = _glCreateShader; - _glCreateShader.sig = 'ii'; - function _glDeleteShader(id) { - if (!id) return; - var shader = GL.shaders[id]; - if (!shader) { // glDeleteShader actually signals an error when deleting a nonexisting object, unlike some other GL delete functions. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - GLctx.deleteShader(shader); - GL.shaders[id] = null; - } - Module["_glDeleteShader"] = _glDeleteShader; - _glDeleteShader.sig = 'vi'; - function _glGetAttachedShaders(program, maxCount, count, shaders) { - var result = GLctx.getAttachedShaders(GL.programs[program]); - var len = result.length; - if (len > maxCount) { - len = maxCount; - } - HEAP32[((count)>>2)] = len; - for (var i = 0; i < len; ++i) { - var id = GL.shaders.indexOf(result[i]); - HEAP32[(((shaders)+(i*4))>>2)] = id; - } - } - Module["_glGetAttachedShaders"] = _glGetAttachedShaders; - _glGetAttachedShaders.sig = 'viiii'; - function _glShaderSource(shader, count, string, length) { - var source = GL.getSource(shader, count, string, length); - - GLctx.shaderSource(GL.shaders[shader], source); - } - Module["_glShaderSource"] = _glShaderSource; - _glShaderSource.sig = 'viiii'; - function _glGetShaderSource(shader, bufSize, length, source) { - var result = GLctx.getShaderSource(GL.shaders[shader]); - if (!result) return; // If an error occurs, nothing will be written to length or source. - var numBytesWrittenExclNull = (bufSize > 0 && source) ? stringToUTF8(result, source, bufSize) : 0; - if (length) HEAP32[((length)>>2)] = numBytesWrittenExclNull; - } - Module["_glGetShaderSource"] = _glGetShaderSource; - _glGetShaderSource.sig = 'viiii'; - function _glCompileShader(shader) { - GLctx.compileShader(GL.shaders[shader]); - } - Module["_glCompileShader"] = _glCompileShader; - _glCompileShader.sig = 'vi'; - function _glGetShaderInfoLog(shader, maxLength, length, infoLog) { - var log = GLctx.getShaderInfoLog(GL.shaders[shader]); - if (log === null) log = '(unknown error)'; - var numBytesWrittenExclNull = (maxLength > 0 && infoLog) ? stringToUTF8(log, infoLog, maxLength) : 0; - if (length) HEAP32[((length)>>2)] = numBytesWrittenExclNull; - } - Module["_glGetShaderInfoLog"] = _glGetShaderInfoLog; - _glGetShaderInfoLog.sig = 'viiii'; - function _glGetShaderiv(shader, pname, p) { - if (!p) { - // GLES2 specification does not specify how to behave if p is a null pointer. Since calling this function does not make sense - // if p == null, issue a GL error to notify user about it. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - if (pname == 0x8B84) { // GL_INFO_LOG_LENGTH - var log = GLctx.getShaderInfoLog(GL.shaders[shader]); - if (log === null) log = '(unknown error)'; - // The GLES2 specification says that if the shader has an empty info log, - // a value of 0 is returned. Otherwise the log has a null char appended. - // (An empty string is falsey, so we can just check that instead of - // looking at log.length.) - var logLength = log ? log.length + 1 : 0; - HEAP32[((p)>>2)] = logLength; - } else if (pname == 0x8B88) { // GL_SHADER_SOURCE_LENGTH - var source = GLctx.getShaderSource(GL.shaders[shader]); - // source may be a null, or the empty string, both of which are falsey - // values that we report a 0 length for. - var sourceLength = source ? source.length + 1 : 0; - HEAP32[((p)>>2)] = sourceLength; - } else { - HEAP32[((p)>>2)] = GLctx.getShaderParameter(GL.shaders[shader], pname); - } - } - Module["_glGetShaderiv"] = _glGetShaderiv; - _glGetShaderiv.sig = 'viii'; - function _glGetProgramiv(program, pname, p) { - if (!p) { - // GLES2 specification does not specify how to behave if p is a null pointer. Since calling this function does not make sense - // if p == null, issue a GL error to notify user about it. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - - if (program >= GL.counter) { - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - - program = GL.programs[program]; - - if (pname == 0x8B84) { // GL_INFO_LOG_LENGTH - var log = GLctx.getProgramInfoLog(program); - if (log === null) log = '(unknown error)'; - HEAP32[((p)>>2)] = log.length + 1; - } else if (pname == 0x8B87 /* GL_ACTIVE_UNIFORM_MAX_LENGTH */) { - if (!program.maxUniformLength) { - for (var i = 0; i < GLctx.getProgramParameter(program, 0x8B86/*GL_ACTIVE_UNIFORMS*/); ++i) { - program.maxUniformLength = Math.max(program.maxUniformLength, GLctx.getActiveUniform(program, i).name.length+1); - } - } - HEAP32[((p)>>2)] = program.maxUniformLength; - } else if (pname == 0x8B8A /* GL_ACTIVE_ATTRIBUTE_MAX_LENGTH */) { - if (!program.maxAttributeLength) { - for (var i = 0; i < GLctx.getProgramParameter(program, 0x8B89/*GL_ACTIVE_ATTRIBUTES*/); ++i) { - program.maxAttributeLength = Math.max(program.maxAttributeLength, GLctx.getActiveAttrib(program, i).name.length+1); - } - } - HEAP32[((p)>>2)] = program.maxAttributeLength; - } else if (pname == 0x8A35 /* GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH */) { - if (!program.maxUniformBlockNameLength) { - for (var i = 0; i < GLctx.getProgramParameter(program, 0x8A36/*GL_ACTIVE_UNIFORM_BLOCKS*/); ++i) { - program.maxUniformBlockNameLength = Math.max(program.maxUniformBlockNameLength, GLctx.getActiveUniformBlockName(program, i).length+1); - } - } - HEAP32[((p)>>2)] = program.maxUniformBlockNameLength; - } else { - HEAP32[((p)>>2)] = GLctx.getProgramParameter(program, pname); - } - } - Module["_glGetProgramiv"] = _glGetProgramiv; - _glGetProgramiv.sig = 'viii'; - function _glIsShader(shader) { - var s = GL.shaders[shader]; - if (!s) return 0; - return GLctx.isShader(s); - } - Module["_glIsShader"] = _glIsShader; - _glIsShader.sig = 'ii'; + var _glDepthRange = (x0, x1) => GLctx.depthRange(x0, x1); + Module['_glDepthRange'] = _glDepthRange; + _glDepthRange.sig = 'vdd'; - function _glCreateProgram() { - var id = GL.getNewId(GL.programs); - var program = GLctx.createProgram(); - // Store additional information needed for each shader program: - program.name = id; - // Lazy cache results of glGetProgramiv(GL_ACTIVE_UNIFORM_MAX_LENGTH/GL_ACTIVE_ATTRIBUTE_MAX_LENGTH/GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH) - program.maxUniformLength = program.maxAttributeLength = program.maxUniformBlockNameLength = 0; - program.uniformIdCounter = 1; - GL.programs[id] = program; - return id; - } - Module["_glCreateProgram"] = _glCreateProgram; - _glCreateProgram.sig = 'i'; - function _glDeleteProgram(id) { - if (!id) return; - var program = GL.programs[id]; - if (!program) { // glDeleteProgram actually signals an error when deleting a nonexisting object, unlike some other GL delete functions. - GL.recordError(0x501 /* GL_INVALID_VALUE */); - return; - } - GLctx.deleteProgram(program); - program.name = 0; - GL.programs[id] = null; - } - Module["_glDeleteProgram"] = _glDeleteProgram; - _glDeleteProgram.sig = 'vi'; - function _glAttachShader(program, shader) { - GLctx.attachShader(GL.programs[program], GL.shaders[shader]); - } - Module["_glAttachShader"] = _glAttachShader; - _glAttachShader.sig = 'vii'; - function _glDetachShader(program, shader) { - GLctx.detachShader(GL.programs[program], GL.shaders[shader]); - } - Module["_glDetachShader"] = _glDetachShader; - _glDetachShader.sig = 'vii'; - function _glGetShaderPrecisionFormat(shaderType, precisionType, range, precision) { - var result = GLctx.getShaderPrecisionFormat(shaderType, precisionType); - HEAP32[((range)>>2)] = result.rangeMin; - HEAP32[(((range)+(4))>>2)] = result.rangeMax; - HEAP32[((precision)>>2)] = result.precision; - } - Module["_glGetShaderPrecisionFormat"] = _glGetShaderPrecisionFormat; - _glGetShaderPrecisionFormat.sig = 'viiii'; - function _glLinkProgram(program) { - program = GL.programs[program]; - GLctx.linkProgram(program); - // Invalidate earlier computed uniform->ID mappings, those have now become stale - program.uniformLocsById = 0; // Mark as null-like so that glGetUniformLocation() knows to populate this again. - program.uniformSizeAndIdsByName = {}; - - } - Module["_glLinkProgram"] = _glLinkProgram; - _glLinkProgram.sig = 'vi'; - function _glGetProgramInfoLog(program, maxLength, length, infoLog) { - var log = GLctx.getProgramInfoLog(GL.programs[program]); - if (log === null) log = '(unknown error)'; - var numBytesWrittenExclNull = (maxLength > 0 && infoLog) ? stringToUTF8(log, infoLog, maxLength) : 0; - if (length) HEAP32[((length)>>2)] = numBytesWrittenExclNull; - } - Module["_glGetProgramInfoLog"] = _glGetProgramInfoLog; - _glGetProgramInfoLog.sig = 'viiii'; - function _glUseProgram(program) { - program = GL.programs[program]; - GLctx.useProgram(program); - // Record the currently active program so that we can access the uniform - // mapping table of that program. - GLctx.currentProgram = program; - } - Module["_glUseProgram"] = _glUseProgram; - _glUseProgram.sig = 'vi'; - function _glValidateProgram(program) { - GLctx.validateProgram(GL.programs[program]); - } - Module["_glValidateProgram"] = _glValidateProgram; - _glValidateProgram.sig = 'vi'; - function _glIsProgram(program) { - program = GL.programs[program]; - if (!program) return 0; - return GLctx.isProgram(program); - } - Module["_glIsProgram"] = _glIsProgram; - _glIsProgram.sig = 'ii'; - function _glBindAttribLocation(program, index, name) { - GLctx.bindAttribLocation(GL.programs[program], index, UTF8ToString(name)); - } - Module["_glBindAttribLocation"] = _glBindAttribLocation; - _glBindAttribLocation.sig = 'viii'; - function _glBindFramebuffer(target, framebuffer) { - - GLctx.bindFramebuffer(target, GL.framebuffers[framebuffer]); - - } - Module["_glBindFramebuffer"] = _glBindFramebuffer; - _glBindFramebuffer.sig = 'vii'; - - function _glGenFramebuffers(n, ids) { - __glGenObject(n, ids, 'createFramebuffer', GL.framebuffers - ); - } - Module["_glGenFramebuffers"] = _glGenFramebuffers; - _glGenFramebuffers.sig = 'vii'; - function _glDeleteFramebuffers(n, framebuffers) { - for (var i = 0; i < n; ++i) { - var id = HEAP32[(((framebuffers)+(i*4))>>2)]; - var framebuffer = GL.framebuffers[id]; - if (!framebuffer) continue; // GL spec: "glDeleteFramebuffers silently ignores 0s and names that do not correspond to existing framebuffer objects". - GLctx.deleteFramebuffer(framebuffer); - framebuffer.name = 0; - GL.framebuffers[id] = null; - } - } - Module["_glDeleteFramebuffers"] = _glDeleteFramebuffers; - _glDeleteFramebuffers.sig = 'vii'; - function _glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer) { - GLctx.framebufferRenderbuffer(target, attachment, renderbuffertarget, - GL.renderbuffers[renderbuffer]); - } - Module["_glFramebufferRenderbuffer"] = _glFramebufferRenderbuffer; - _glFramebufferRenderbuffer.sig = 'viiii'; - function _glFramebufferTexture2D(target, attachment, textarget, texture, level) { - GLctx.framebufferTexture2D(target, attachment, textarget, - GL.textures[texture], level); - } - Module["_glFramebufferTexture2D"] = _glFramebufferTexture2D; - _glFramebufferTexture2D.sig = 'viiiii'; - function _glGetFramebufferAttachmentParameteriv(target, attachment, pname, params) { - var result = GLctx.getFramebufferAttachmentParameter(target, attachment, pname); - if (result instanceof WebGLRenderbuffer || - result instanceof WebGLTexture) { - result = result.name | 0; - } - HEAP32[((params)>>2)] = result; - } - Module["_glGetFramebufferAttachmentParameteriv"] = _glGetFramebufferAttachmentParameteriv; - _glGetFramebufferAttachmentParameteriv.sig = 'viiii'; - function _glIsFramebuffer(framebuffer) { - var fb = GL.framebuffers[framebuffer]; - if (!fb) return 0; - return GLctx.isFramebuffer(fb); - } - Module["_glIsFramebuffer"] = _glIsFramebuffer; - _glIsFramebuffer.sig = 'ii'; - - function _glGenVertexArrays(n, arrays) { - __glGenObject(n, arrays, 'createVertexArray', GL.vaos - ); - } - Module["_glGenVertexArrays"] = _glGenVertexArrays; - _glGenVertexArrays.sig = 'vii'; - function _glDeleteVertexArrays(n, vaos) { - for (var i = 0; i < n; i++) { - var id = HEAP32[(((vaos)+(i*4))>>2)]; - GLctx['deleteVertexArray'](GL.vaos[id]); - GL.vaos[id] = null; - } - } - Module["_glDeleteVertexArrays"] = _glDeleteVertexArrays; - _glDeleteVertexArrays.sig = 'vii'; - function _glBindVertexArray(vao) { - GLctx['bindVertexArray'](GL.vaos[vao]); - } - Module["_glBindVertexArray"] = _glBindVertexArray; - _glBindVertexArray.sig = 'vi'; - function _glIsVertexArray(array) { - - var vao = GL.vaos[array]; - if (!vao) return 0; - return GLctx['isVertexArray'](vao); - } - Module["_glIsVertexArray"] = _glIsVertexArray; - _glIsVertexArray.sig = 'ii'; - function _glVertexPointer(){ throw 'Legacy GL function (glVertexPointer) called. If you want legacy GL emulation, you need to compile with -sLEGACY_GL_EMULATION to enable legacy GL emulation.'; } - Module["_glVertexPointer"] = _glVertexPointer; - function _glMatrixMode(){ throw 'Legacy GL function (glMatrixMode) called. If you want legacy GL emulation, you need to compile with -sLEGACY_GL_EMULATION to enable legacy GL emulation.'; } - Module["_glMatrixMode"] = _glMatrixMode; - function _glBegin(){ throw 'Legacy GL function (glBegin) called. If you want legacy GL emulation, you need to compile with -sLEGACY_GL_EMULATION to enable legacy GL emulation.'; } - Module["_glBegin"] = _glBegin; - function _glLoadIdentity(){ throw 'Legacy GL function (glLoadIdentity) called. If you want legacy GL emulation, you need to compile with -sLEGACY_GL_EMULATION to enable legacy GL emulation.'; } - Module["_glLoadIdentity"] = _glLoadIdentity; - - function _glGenVertexArraysOES(n, arrays) { - __glGenObject(n, arrays, 'createVertexArray', GL.vaos - ); - } - Module["_glGenVertexArraysOES"] = _glGenVertexArraysOES; - _glGenVertexArraysOES.sig = 'vii'; - function _glDeleteVertexArraysOES(n, vaos) { - for (var i = 0; i < n; i++) { - var id = HEAP32[(((vaos)+(i*4))>>2)]; - GLctx['deleteVertexArray'](GL.vaos[id]); - GL.vaos[id] = null; - } - } - Module["_glDeleteVertexArraysOES"] = _glDeleteVertexArraysOES; - _glDeleteVertexArraysOES.sig = 'vii'; - function _glBindVertexArrayOES(vao) { - GLctx['bindVertexArray'](GL.vaos[vao]); - } - Module["_glBindVertexArrayOES"] = _glBindVertexArrayOES; - _glBindVertexArrayOES.sig = 'vi'; - function _glIsVertexArrayOES(array) { - - var vao = GL.vaos[array]; - if (!vao) return 0; - return GLctx['isVertexArray'](vao); - } - Module["_glIsVertexArrayOES"] = _glIsVertexArrayOES; - _glIsVertexArrayOES.sig = 'ii'; - function _glVertexAttribPointer(index, size, type, normalized, stride, ptr) { - GLctx.vertexAttribPointer(index, size, type, !!normalized, stride, ptr); - } - Module["_glVertexAttribPointer"] = _glVertexAttribPointer; - _glVertexAttribPointer.sig = 'viiiiii'; - function _glEnableVertexAttribArray(index) { - GLctx.enableVertexAttribArray(index); - } - Module["_glEnableVertexAttribArray"] = _glEnableVertexAttribArray; - _glEnableVertexAttribArray.sig = 'vi'; - function _glDisableVertexAttribArray(index) { - GLctx.disableVertexAttribArray(index); - } - Module["_glDisableVertexAttribArray"] = _glDisableVertexAttribArray; - _glDisableVertexAttribArray.sig = 'vi'; - function _glDrawArrays(mode, first, count) { - - GLctx.drawArrays(mode, first, count); - - } - Module["_glDrawArrays"] = _glDrawArrays; - _glDrawArrays.sig = 'viii'; - function _glDrawElements(mode, count, type, indices) { - - GLctx.drawElements(mode, count, type, indices); - - } - Module["_glDrawElements"] = _glDrawElements; - _glDrawElements.sig = 'viiii'; - function _glShaderBinary() { - GL.recordError(0x500/*GL_INVALID_ENUM*/); - } - Module["_glShaderBinary"] = _glShaderBinary; - _glShaderBinary.sig = 'v'; - function _glReleaseShaderCompiler() { - // NOP (as allowed by GLES 2.0 spec) - } - Module["_glReleaseShaderCompiler"] = _glReleaseShaderCompiler; - _glReleaseShaderCompiler.sig = 'v'; - function _glGetError() { - var error = GLctx.getError() || GL.lastError; - GL.lastError = 0/*GL_NO_ERROR*/; - return error; - } - Module["_glGetError"] = _glGetError; - _glGetError.sig = 'i'; - function _glVertexAttribDivisor(index, divisor) { - GLctx['vertexAttribDivisor'](index, divisor); - } - Module["_glVertexAttribDivisor"] = _glVertexAttribDivisor; - _glVertexAttribDivisor.sig = 'vii'; - function _glDrawArraysInstanced(mode, first, count, primcount) { - GLctx['drawArraysInstanced'](mode, first, count, primcount); - } - Module["_glDrawArraysInstanced"] = _glDrawArraysInstanced; - _glDrawArraysInstanced.sig = 'viiii'; - function _glDrawElementsInstanced(mode, count, type, indices, primcount) { - GLctx['drawElementsInstanced'](mode, count, type, indices, primcount); - } - Module["_glDrawElementsInstanced"] = _glDrawElementsInstanced; - _glDrawElementsInstanced.sig = 'viiiii'; - function _glVertexAttribDivisorNV(index, divisor) { - GLctx['vertexAttribDivisor'](index, divisor); - } - Module["_glVertexAttribDivisorNV"] = _glVertexAttribDivisorNV; - _glVertexAttribDivisorNV.sig = 'vii'; - function _glDrawArraysInstancedNV(mode, first, count, primcount) { - GLctx['drawArraysInstanced'](mode, first, count, primcount); - } - Module["_glDrawArraysInstancedNV"] = _glDrawArraysInstancedNV; - _glDrawArraysInstancedNV.sig = 'viiii'; - function _glDrawElementsInstancedNV(mode, count, type, indices, primcount) { - GLctx['drawElementsInstanced'](mode, count, type, indices, primcount); - } - Module["_glDrawElementsInstancedNV"] = _glDrawElementsInstancedNV; - _glDrawElementsInstancedNV.sig = 'viiiii'; - function _glVertexAttribDivisorEXT(index, divisor) { - GLctx['vertexAttribDivisor'](index, divisor); - } - Module["_glVertexAttribDivisorEXT"] = _glVertexAttribDivisorEXT; - _glVertexAttribDivisorEXT.sig = 'vii'; - function _glDrawArraysInstancedEXT(mode, first, count, primcount) { - GLctx['drawArraysInstanced'](mode, first, count, primcount); - } - Module["_glDrawArraysInstancedEXT"] = _glDrawArraysInstancedEXT; - _glDrawArraysInstancedEXT.sig = 'viiii'; - function _glDrawElementsInstancedEXT(mode, count, type, indices, primcount) { - GLctx['drawElementsInstanced'](mode, count, type, indices, primcount); - } - Module["_glDrawElementsInstancedEXT"] = _glDrawElementsInstancedEXT; - _glDrawElementsInstancedEXT.sig = 'viiiii'; - function _glVertexAttribDivisorARB(index, divisor) { - GLctx['vertexAttribDivisor'](index, divisor); - } - Module["_glVertexAttribDivisorARB"] = _glVertexAttribDivisorARB; - _glVertexAttribDivisorARB.sig = 'vii'; - function _glDrawArraysInstancedARB(mode, first, count, primcount) { - GLctx['drawArraysInstanced'](mode, first, count, primcount); - } - Module["_glDrawArraysInstancedARB"] = _glDrawArraysInstancedARB; - _glDrawArraysInstancedARB.sig = 'viiii'; - function _glDrawElementsInstancedARB(mode, count, type, indices, primcount) { - GLctx['drawElementsInstanced'](mode, count, type, indices, primcount); - } - Module["_glDrawElementsInstancedARB"] = _glDrawElementsInstancedARB; - _glDrawElementsInstancedARB.sig = 'viiiii'; - function _glVertexAttribDivisorANGLE(index, divisor) { - GLctx['vertexAttribDivisor'](index, divisor); - } - Module["_glVertexAttribDivisorANGLE"] = _glVertexAttribDivisorANGLE; - _glVertexAttribDivisorANGLE.sig = 'vii'; - function _glDrawArraysInstancedANGLE(mode, first, count, primcount) { - GLctx['drawArraysInstanced'](mode, first, count, primcount); - } - Module["_glDrawArraysInstancedANGLE"] = _glDrawArraysInstancedANGLE; - _glDrawArraysInstancedANGLE.sig = 'viiii'; - function _glDrawElementsInstancedANGLE(mode, count, type, indices, primcount) { - GLctx['drawElementsInstanced'](mode, count, type, indices, primcount); - } - Module["_glDrawElementsInstancedANGLE"] = _glDrawElementsInstancedANGLE; - _glDrawElementsInstancedANGLE.sig = 'viiiii'; - - function _glDrawBuffers(n, bufs) { - - var bufArray = tempFixedLengthArray[n]; - for (var i = 0; i < n; i++) { - bufArray[i] = HEAP32[(((bufs)+(i*4))>>2)]; - } - - GLctx['drawBuffers'](bufArray); - } - Module["_glDrawBuffers"] = _glDrawBuffers; - _glDrawBuffers.sig = 'vii'; - - function _glDrawBuffersEXT(n, bufs) { - - var bufArray = tempFixedLengthArray[n]; - for (var i = 0; i < n; i++) { - bufArray[i] = HEAP32[(((bufs)+(i*4))>>2)]; - } - - GLctx['drawBuffers'](bufArray); - } - Module["_glDrawBuffersEXT"] = _glDrawBuffersEXT; - _glDrawBuffersEXT.sig = 'vii'; - - function _glDrawBuffersWEBGL(n, bufs) { - - var bufArray = tempFixedLengthArray[n]; - for (var i = 0; i < n; i++) { - bufArray[i] = HEAP32[(((bufs)+(i*4))>>2)]; - } - - GLctx['drawBuffers'](bufArray); - } - Module["_glDrawBuffersWEBGL"] = _glDrawBuffersWEBGL; - _glDrawBuffersWEBGL.sig = 'vii'; - function _glColorMask(red, green, blue, alpha) { - GLctx.colorMask(!!red, !!green, !!blue, !!alpha); - } - Module["_glColorMask"] = _glColorMask; - _glColorMask.sig = 'viiii'; - function _glDepthMask(flag) { - GLctx.depthMask(!!flag); - } - Module["_glDepthMask"] = _glDepthMask; - _glDepthMask.sig = 'vi'; - function _glSampleCoverage(value, invert) { - GLctx.sampleCoverage(value, !!invert); - } - Module["_glSampleCoverage"] = _glSampleCoverage; - _glSampleCoverage.sig = 'vii'; - function _glMultiDrawArrays(mode, firsts, counts, drawcount) { - GLctx.multiDrawWebgl['multiDrawArraysWEBGL']( - mode, - HEAP32, - firsts >> 2, - HEAP32, - counts >> 2, - drawcount); - } - Module["_glMultiDrawArrays"] = _glMultiDrawArrays; - _glMultiDrawArrays.sig = 'viiii'; - function _glMultiDrawArraysANGLE(mode, firsts, counts, drawcount) { - GLctx.multiDrawWebgl['multiDrawArraysWEBGL']( - mode, - HEAP32, - firsts >> 2, - HEAP32, - counts >> 2, - drawcount); - } - Module["_glMultiDrawArraysANGLE"] = _glMultiDrawArraysANGLE; - _glMultiDrawArraysANGLE.sig = 'viiii'; - function _glMultiDrawArraysWEBGL(mode, firsts, counts, drawcount) { - GLctx.multiDrawWebgl['multiDrawArraysWEBGL']( - mode, - HEAP32, - firsts >> 2, - HEAP32, - counts >> 2, - drawcount); - } - Module["_glMultiDrawArraysWEBGL"] = _glMultiDrawArraysWEBGL; - _glMultiDrawArraysWEBGL.sig = 'viiii'; - function _glMultiDrawArraysInstancedANGLE(mode, firsts, counts, instanceCounts, drawcount) { - GLctx.multiDrawWebgl['multiDrawArraysInstancedWEBGL']( - mode, - HEAP32, - firsts >> 2, - HEAP32, - counts >> 2, - HEAP32, - instanceCounts >> 2, - drawcount); - } - Module["_glMultiDrawArraysInstancedANGLE"] = _glMultiDrawArraysInstancedANGLE; - _glMultiDrawArraysInstancedANGLE.sig = 'viiiii'; - function _glMultiDrawArraysInstancedWEBGL(mode, firsts, counts, instanceCounts, drawcount) { - GLctx.multiDrawWebgl['multiDrawArraysInstancedWEBGL']( - mode, - HEAP32, - firsts >> 2, - HEAP32, - counts >> 2, - HEAP32, - instanceCounts >> 2, - drawcount); - } - Module["_glMultiDrawArraysInstancedWEBGL"] = _glMultiDrawArraysInstancedWEBGL; - _glMultiDrawArraysInstancedWEBGL.sig = 'viiiii'; - function _glMultiDrawElements(mode, counts, type, offsets, drawcount) { - GLctx.multiDrawWebgl['multiDrawElementsWEBGL']( - mode, - HEAP32, - counts >> 2, - type, - HEAP32, - offsets >> 2, - drawcount); - } - Module["_glMultiDrawElements"] = _glMultiDrawElements; - _glMultiDrawElements.sig = 'viiiii'; - function _glMultiDrawElementsANGLE(mode, counts, type, offsets, drawcount) { - GLctx.multiDrawWebgl['multiDrawElementsWEBGL']( - mode, - HEAP32, - counts >> 2, - type, - HEAP32, - offsets >> 2, - drawcount); - } - Module["_glMultiDrawElementsANGLE"] = _glMultiDrawElementsANGLE; - _glMultiDrawElementsANGLE.sig = 'viiiii'; - function _glMultiDrawElementsWEBGL(mode, counts, type, offsets, drawcount) { - GLctx.multiDrawWebgl['multiDrawElementsWEBGL']( - mode, - HEAP32, - counts >> 2, - type, - HEAP32, - offsets >> 2, - drawcount); - } - Module["_glMultiDrawElementsWEBGL"] = _glMultiDrawElementsWEBGL; - _glMultiDrawElementsWEBGL.sig = 'viiiii'; - function _glMultiDrawElementsInstancedANGLE(mode, counts, type, offsets, instanceCounts, drawcount) { - GLctx.multiDrawWebgl['multiDrawElementsInstancedWEBGL']( - mode, - HEAP32, - counts >> 2, - type, - HEAP32, - offsets >> 2, - HEAP32, - instanceCounts >> 2, - drawcount); - } - Module["_glMultiDrawElementsInstancedANGLE"] = _glMultiDrawElementsInstancedANGLE; - _glMultiDrawElementsInstancedANGLE.sig = 'viiiiii'; - function _glMultiDrawElementsInstancedWEBGL(mode, counts, type, offsets, instanceCounts, drawcount) { - GLctx.multiDrawWebgl['multiDrawElementsInstancedWEBGL']( - mode, - HEAP32, - counts >> 2, - type, - HEAP32, - offsets >> 2, - HEAP32, - instanceCounts >> 2, - drawcount); - } - Module["_glMultiDrawElementsInstancedWEBGL"] = _glMultiDrawElementsInstancedWEBGL; - _glMultiDrawElementsInstancedWEBGL.sig = 'viiiiii'; - function _glFinish() { GLctx['finish']() } - Module["_glFinish"] = _glFinish; - _glFinish.sig = 'v'; - function _glFlush() { GLctx['flush']() } - Module["_glFlush"] = _glFlush; - _glFlush.sig = 'v'; - function _glClearDepth(x0) { GLctx['clearDepth'](x0) } - Module["_glClearDepth"] = _glClearDepth; - _glClearDepth.sig = 'vi'; - function _glClearDepthf(x0) { GLctx['clearDepth'](x0) } - Module["_glClearDepthf"] = _glClearDepthf; - _glClearDepthf.sig = 'vf'; - function _glDepthFunc(x0) { GLctx['depthFunc'](x0) } - Module["_glDepthFunc"] = _glDepthFunc; - _glDepthFunc.sig = 'vi'; - function _glEnable(x0) { GLctx['enable'](x0) } - Module["_glEnable"] = _glEnable; - _glEnable.sig = 'vi'; - function _glDisable(x0) { GLctx['disable'](x0) } - Module["_glDisable"] = _glDisable; - _glDisable.sig = 'vi'; - function _glFrontFace(x0) { GLctx['frontFace'](x0) } - Module["_glFrontFace"] = _glFrontFace; - _glFrontFace.sig = 'vi'; - function _glCullFace(x0) { GLctx['cullFace'](x0) } - Module["_glCullFace"] = _glCullFace; - _glCullFace.sig = 'vi'; - - function _glClear(x0) { GLctx['clear'](x0) } - Module["_glClear"] = _glClear; - _glClear.sig = 'vi'; - - function _glLineWidth(x0) { GLctx['lineWidth'](x0) } - Module["_glLineWidth"] = _glLineWidth; - _glLineWidth.sig = 'vf'; - - function _glClearStencil(x0) { GLctx['clearStencil'](x0) } - Module["_glClearStencil"] = _glClearStencil; - _glClearStencil.sig = 'vi'; - - function _glStencilMask(x0) { GLctx['stencilMask'](x0) } - Module["_glStencilMask"] = _glStencilMask; - _glStencilMask.sig = 'vi'; - - function _glCheckFramebufferStatus(x0) { return GLctx['checkFramebufferStatus'](x0) } - Module["_glCheckFramebufferStatus"] = _glCheckFramebufferStatus; - _glCheckFramebufferStatus.sig = 'ii'; - - function _glGenerateMipmap(x0) { GLctx['generateMipmap'](x0) } - Module["_glGenerateMipmap"] = _glGenerateMipmap; - _glGenerateMipmap.sig = 'vi'; - - function _glActiveTexture(x0) { GLctx['activeTexture'](x0) } - Module["_glActiveTexture"] = _glActiveTexture; - _glActiveTexture.sig = 'vi'; - - function _glBlendEquation(x0) { GLctx['blendEquation'](x0) } - Module["_glBlendEquation"] = _glBlendEquation; - _glBlendEquation.sig = 'vi'; - - function _glIsEnabled(x0) { return GLctx['isEnabled'](x0) } - Module["_glIsEnabled"] = _glIsEnabled; - _glIsEnabled.sig = 'ii'; - - function _glBlendFunc(x0, x1) { GLctx['blendFunc'](x0, x1) } - Module["_glBlendFunc"] = _glBlendFunc; - _glBlendFunc.sig = 'vii'; - - function _glBlendEquationSeparate(x0, x1) { GLctx['blendEquationSeparate'](x0, x1) } - Module["_glBlendEquationSeparate"] = _glBlendEquationSeparate; - _glBlendEquationSeparate.sig = 'vii'; - - function _glDepthRange(x0, x1) { GLctx['depthRange'](x0, x1) } - Module["_glDepthRange"] = _glDepthRange; - _glDepthRange.sig = 'vii'; - - function _glDepthRangef(x0, x1) { GLctx['depthRange'](x0, x1) } - Module["_glDepthRangef"] = _glDepthRangef; - _glDepthRangef.sig = 'vii'; - - function _glStencilMaskSeparate(x0, x1) { GLctx['stencilMaskSeparate'](x0, x1) } - Module["_glStencilMaskSeparate"] = _glStencilMaskSeparate; - _glStencilMaskSeparate.sig = 'vii'; - - function _glHint(x0, x1) { GLctx['hint'](x0, x1) } - Module["_glHint"] = _glHint; - _glHint.sig = 'vii'; - - function _glPolygonOffset(x0, x1) { GLctx['polygonOffset'](x0, x1) } - Module["_glPolygonOffset"] = _glPolygonOffset; - _glPolygonOffset.sig = 'vff'; - - function _glVertexAttrib1f(x0, x1) { GLctx['vertexAttrib1f'](x0, x1) } - Module["_glVertexAttrib1f"] = _glVertexAttrib1f; - _glVertexAttrib1f.sig = 'vif'; - - function _glTexParameteri(x0, x1, x2) { GLctx['texParameteri'](x0, x1, x2) } - Module["_glTexParameteri"] = _glTexParameteri; - _glTexParameteri.sig = 'viii'; - - function _glTexParameterf(x0, x1, x2) { GLctx['texParameterf'](x0, x1, x2) } - Module["_glTexParameterf"] = _glTexParameterf; - _glTexParameterf.sig = 'viii'; - - function _glVertexAttrib2f(x0, x1, x2) { GLctx['vertexAttrib2f'](x0, x1, x2) } - Module["_glVertexAttrib2f"] = _glVertexAttrib2f; - _glVertexAttrib2f.sig = 'viff'; - - function _glStencilFunc(x0, x1, x2) { GLctx['stencilFunc'](x0, x1, x2) } - Module["_glStencilFunc"] = _glStencilFunc; - _glStencilFunc.sig = 'viii'; - - function _glStencilOp(x0, x1, x2) { GLctx['stencilOp'](x0, x1, x2) } - Module["_glStencilOp"] = _glStencilOp; - _glStencilOp.sig = 'viii'; - - function _glViewport(x0, x1, x2, x3) { GLctx['viewport'](x0, x1, x2, x3) } - Module["_glViewport"] = _glViewport; - _glViewport.sig = 'viiii'; - - function _glClearColor(x0, x1, x2, x3) { GLctx['clearColor'](x0, x1, x2, x3) } - Module["_glClearColor"] = _glClearColor; - _glClearColor.sig = 'vffff'; - - function _glScissor(x0, x1, x2, x3) { GLctx['scissor'](x0, x1, x2, x3) } - Module["_glScissor"] = _glScissor; - _glScissor.sig = 'viiii'; - - function _glVertexAttrib3f(x0, x1, x2, x3) { GLctx['vertexAttrib3f'](x0, x1, x2, x3) } - Module["_glVertexAttrib3f"] = _glVertexAttrib3f; - _glVertexAttrib3f.sig = 'vifff'; - - function _glRenderbufferStorage(x0, x1, x2, x3) { GLctx['renderbufferStorage'](x0, x1, x2, x3) } - Module["_glRenderbufferStorage"] = _glRenderbufferStorage; - _glRenderbufferStorage.sig = 'viiii'; - - function _glBlendFuncSeparate(x0, x1, x2, x3) { GLctx['blendFuncSeparate'](x0, x1, x2, x3) } - Module["_glBlendFuncSeparate"] = _glBlendFuncSeparate; - _glBlendFuncSeparate.sig = 'viiii'; - - function _glBlendColor(x0, x1, x2, x3) { GLctx['blendColor'](x0, x1, x2, x3) } - Module["_glBlendColor"] = _glBlendColor; - _glBlendColor.sig = 'vffff'; - - function _glStencilFuncSeparate(x0, x1, x2, x3) { GLctx['stencilFuncSeparate'](x0, x1, x2, x3) } - Module["_glStencilFuncSeparate"] = _glStencilFuncSeparate; - _glStencilFuncSeparate.sig = 'viiii'; - - function _glStencilOpSeparate(x0, x1, x2, x3) { GLctx['stencilOpSeparate'](x0, x1, x2, x3) } - Module["_glStencilOpSeparate"] = _glStencilOpSeparate; - _glStencilOpSeparate.sig = 'viiii'; - - function _glVertexAttrib4f(x0, x1, x2, x3, x4) { GLctx['vertexAttrib4f'](x0, x1, x2, x3, x4) } - Module["_glVertexAttrib4f"] = _glVertexAttrib4f; - _glVertexAttrib4f.sig = 'viffff'; - - function _glCopyTexImage2D(x0, x1, x2, x3, x4, x5, x6, x7) { GLctx['copyTexImage2D'](x0, x1, x2, x3, x4, x5, x6, x7) } - Module["_glCopyTexImage2D"] = _glCopyTexImage2D; - _glCopyTexImage2D.sig = 'viiiiiiii'; - - function _glCopyTexSubImage2D(x0, x1, x2, x3, x4, x5, x6, x7) { GLctx['copyTexSubImage2D'](x0, x1, x2, x3, x4, x5, x6, x7) } - Module["_glCopyTexSubImage2D"] = _glCopyTexSubImage2D; - _glCopyTexSubImage2D.sig = 'viiiiiiii'; @@ -22752,106 +22659,37 @@ var ASM_CONSTS = { + var _emscripten_glGenVertexArrays = _glGenVertexArrays; + Module['_emscripten_glGenVertexArrays'] = _emscripten_glGenVertexArrays; + _emscripten_glGenVertexArrays.sig = 'vip'; + var _emscripten_glDeleteVertexArrays = _glDeleteVertexArrays; + Module['_emscripten_glDeleteVertexArrays'] = _emscripten_glDeleteVertexArrays; + _emscripten_glDeleteVertexArrays.sig = 'vip'; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - function _emscripten_glGenVertexArrays(n, arrays) { - __glGenObject(n, arrays, 'createVertexArray', GL.vaos - ); - } - Module["_emscripten_glGenVertexArrays"] = _emscripten_glGenVertexArrays; - _emscripten_glGenVertexArrays.sig = 'vii'; - - function _emscripten_glDeleteVertexArrays(n, vaos) { - for (var i = 0; i < n; i++) { - var id = HEAP32[(((vaos)+(i*4))>>2)]; - GLctx['deleteVertexArray'](GL.vaos[id]); - GL.vaos[id] = null; - } - } - Module["_emscripten_glDeleteVertexArrays"] = _emscripten_glDeleteVertexArrays; - _emscripten_glDeleteVertexArrays.sig = 'vii'; - - function _emscripten_glBindVertexArray(vao) { - GLctx['bindVertexArray'](GL.vaos[vao]); - } - Module["_emscripten_glBindVertexArray"] = _emscripten_glBindVertexArray; + var _emscripten_glBindVertexArray = _glBindVertexArray; + Module['_emscripten_glBindVertexArray'] = _emscripten_glBindVertexArray; _emscripten_glBindVertexArray.sig = 'vi'; - function _emscripten_glIsVertexArray(array) { - - var vao = GL.vaos[array]; - if (!vao) return 0; - return GLctx['isVertexArray'](vao); - } - Module["_emscripten_glIsVertexArray"] = _emscripten_glIsVertexArray; + var _emscripten_glIsVertexArray = _glIsVertexArray; + Module['_emscripten_glIsVertexArray'] = _emscripten_glIsVertexArray; _emscripten_glIsVertexArray.sig = 'ii'; - function _emscripten_glVertexPointer(){ throw 'Legacy GL function (glVertexPointer) called. If you want legacy GL emulation, you need to compile with -sLEGACY_GL_EMULATION to enable legacy GL emulation.'; } - Module["_emscripten_glVertexPointer"] = _emscripten_glVertexPointer; + var _emscripten_glVertexPointer = _glVertexPointer; + Module['_emscripten_glVertexPointer'] = _emscripten_glVertexPointer; + _emscripten_glVertexPointer.sig = 'viiip'; - function _emscripten_glMatrixMode(){ throw 'Legacy GL function (glMatrixMode) called. If you want legacy GL emulation, you need to compile with -sLEGACY_GL_EMULATION to enable legacy GL emulation.'; } - Module["_emscripten_glMatrixMode"] = _emscripten_glMatrixMode; + var _emscripten_glMatrixMode = _glMatrixMode; + Module['_emscripten_glMatrixMode'] = _emscripten_glMatrixMode; + _emscripten_glMatrixMode.sig = 'vi'; - function _emscripten_glBegin(){ throw 'Legacy GL function (glBegin) called. If you want legacy GL emulation, you need to compile with -sLEGACY_GL_EMULATION to enable legacy GL emulation.'; } - Module["_emscripten_glBegin"] = _emscripten_glBegin; + var _emscripten_glBegin = _glBegin; + Module['_emscripten_glBegin'] = _emscripten_glBegin; + _emscripten_glBegin.sig = 'vi'; - function _emscripten_glLoadIdentity(){ throw 'Legacy GL function (glLoadIdentity) called. If you want legacy GL emulation, you need to compile with -sLEGACY_GL_EMULATION to enable legacy GL emulation.'; } - Module["_emscripten_glLoadIdentity"] = _emscripten_glLoadIdentity; + var _emscripten_glLoadIdentity = _glLoadIdentity; + Module['_emscripten_glLoadIdentity'] = _emscripten_glLoadIdentity; + _emscripten_glLoadIdentity.sig = 'v'; @@ -22865,249 +22703,96 @@ var ASM_CONSTS = { - function _emscripten_glVertexAttribDivisor(index, divisor) { - GLctx['vertexAttribDivisor'](index, divisor); - } - Module["_emscripten_glVertexAttribDivisor"] = _emscripten_glVertexAttribDivisor; + var _emscripten_glVertexAttribDivisor = _glVertexAttribDivisor; + Module['_emscripten_glVertexAttribDivisor'] = _emscripten_glVertexAttribDivisor; _emscripten_glVertexAttribDivisor.sig = 'vii'; - function _emscripten_glDrawArraysInstanced(mode, first, count, primcount) { - GLctx['drawArraysInstanced'](mode, first, count, primcount); - } - Module["_emscripten_glDrawArraysInstanced"] = _emscripten_glDrawArraysInstanced; + var _emscripten_glDrawArraysInstanced = _glDrawArraysInstanced; + Module['_emscripten_glDrawArraysInstanced'] = _emscripten_glDrawArraysInstanced; _emscripten_glDrawArraysInstanced.sig = 'viiii'; - function _emscripten_glDrawElementsInstanced(mode, count, type, indices, primcount) { - GLctx['drawElementsInstanced'](mode, count, type, indices, primcount); - } - Module["_emscripten_glDrawElementsInstanced"] = _emscripten_glDrawElementsInstanced; - _emscripten_glDrawElementsInstanced.sig = 'viiiii'; + var _emscripten_glDrawElementsInstanced = _glDrawElementsInstanced; + Module['_emscripten_glDrawElementsInstanced'] = _emscripten_glDrawElementsInstanced; + _emscripten_glDrawElementsInstanced.sig = 'viiipi'; - function _emscripten_glVertexAttribDivisorNV(index, divisor) { - GLctx['vertexAttribDivisor'](index, divisor); - } - Module["_emscripten_glVertexAttribDivisorNV"] = _emscripten_glVertexAttribDivisorNV; - _emscripten_glVertexAttribDivisorNV.sig = 'vii'; + var _emscripten_glVertexAttribDivisorNV = _glVertexAttribDivisorNV; + Module['_emscripten_glVertexAttribDivisorNV'] = _emscripten_glVertexAttribDivisorNV; - function _emscripten_glDrawArraysInstancedNV(mode, first, count, primcount) { - GLctx['drawArraysInstanced'](mode, first, count, primcount); - } - Module["_emscripten_glDrawArraysInstancedNV"] = _emscripten_glDrawArraysInstancedNV; - _emscripten_glDrawArraysInstancedNV.sig = 'viiii'; + var _emscripten_glDrawArraysInstancedNV = _glDrawArraysInstancedNV; + Module['_emscripten_glDrawArraysInstancedNV'] = _emscripten_glDrawArraysInstancedNV; - function _emscripten_glDrawElementsInstancedNV(mode, count, type, indices, primcount) { - GLctx['drawElementsInstanced'](mode, count, type, indices, primcount); - } - Module["_emscripten_glDrawElementsInstancedNV"] = _emscripten_glDrawElementsInstancedNV; - _emscripten_glDrawElementsInstancedNV.sig = 'viiiii'; + var _emscripten_glDrawElementsInstancedNV = _glDrawElementsInstancedNV; + Module['_emscripten_glDrawElementsInstancedNV'] = _emscripten_glDrawElementsInstancedNV; - function _emscripten_glVertexAttribDivisorEXT(index, divisor) { - GLctx['vertexAttribDivisor'](index, divisor); - } - Module["_emscripten_glVertexAttribDivisorEXT"] = _emscripten_glVertexAttribDivisorEXT; - _emscripten_glVertexAttribDivisorEXT.sig = 'vii'; + var _emscripten_glVertexAttribDivisorEXT = _glVertexAttribDivisorEXT; + Module['_emscripten_glVertexAttribDivisorEXT'] = _emscripten_glVertexAttribDivisorEXT; - function _emscripten_glDrawArraysInstancedEXT(mode, first, count, primcount) { - GLctx['drawArraysInstanced'](mode, first, count, primcount); - } - Module["_emscripten_glDrawArraysInstancedEXT"] = _emscripten_glDrawArraysInstancedEXT; - _emscripten_glDrawArraysInstancedEXT.sig = 'viiii'; + var _emscripten_glDrawArraysInstancedEXT = _glDrawArraysInstancedEXT; + Module['_emscripten_glDrawArraysInstancedEXT'] = _emscripten_glDrawArraysInstancedEXT; - function _emscripten_glDrawElementsInstancedEXT(mode, count, type, indices, primcount) { - GLctx['drawElementsInstanced'](mode, count, type, indices, primcount); - } - Module["_emscripten_glDrawElementsInstancedEXT"] = _emscripten_glDrawElementsInstancedEXT; - _emscripten_glDrawElementsInstancedEXT.sig = 'viiiii'; + var _emscripten_glDrawElementsInstancedEXT = _glDrawElementsInstancedEXT; + Module['_emscripten_glDrawElementsInstancedEXT'] = _emscripten_glDrawElementsInstancedEXT; - function _emscripten_glVertexAttribDivisorARB(index, divisor) { - GLctx['vertexAttribDivisor'](index, divisor); - } - Module["_emscripten_glVertexAttribDivisorARB"] = _emscripten_glVertexAttribDivisorARB; - _emscripten_glVertexAttribDivisorARB.sig = 'vii'; + var _emscripten_glVertexAttribDivisorARB = _glVertexAttribDivisorARB; + Module['_emscripten_glVertexAttribDivisorARB'] = _emscripten_glVertexAttribDivisorARB; - function _emscripten_glDrawArraysInstancedARB(mode, first, count, primcount) { - GLctx['drawArraysInstanced'](mode, first, count, primcount); - } - Module["_emscripten_glDrawArraysInstancedARB"] = _emscripten_glDrawArraysInstancedARB; - _emscripten_glDrawArraysInstancedARB.sig = 'viiii'; + var _emscripten_glDrawArraysInstancedARB = _glDrawArraysInstancedARB; + Module['_emscripten_glDrawArraysInstancedARB'] = _emscripten_glDrawArraysInstancedARB; - function _emscripten_glDrawElementsInstancedARB(mode, count, type, indices, primcount) { - GLctx['drawElementsInstanced'](mode, count, type, indices, primcount); - } - Module["_emscripten_glDrawElementsInstancedARB"] = _emscripten_glDrawElementsInstancedARB; - _emscripten_glDrawElementsInstancedARB.sig = 'viiiii'; + var _emscripten_glDrawElementsInstancedARB = _glDrawElementsInstancedARB; + Module['_emscripten_glDrawElementsInstancedARB'] = _emscripten_glDrawElementsInstancedARB; - - function _emscripten_glDrawBuffers(n, bufs) { - - var bufArray = tempFixedLengthArray[n]; - for (var i = 0; i < n; i++) { - bufArray[i] = HEAP32[(((bufs)+(i*4))>>2)]; - } - - GLctx['drawBuffers'](bufArray); - } - Module["_emscripten_glDrawBuffers"] = _emscripten_glDrawBuffers; - _emscripten_glDrawBuffers.sig = 'vii'; + var _emscripten_glDrawBuffers = _glDrawBuffers; + Module['_emscripten_glDrawBuffers'] = _emscripten_glDrawBuffers; + _emscripten_glDrawBuffers.sig = 'vip'; - - function _emscripten_glDrawBuffersEXT(n, bufs) { - - var bufArray = tempFixedLengthArray[n]; - for (var i = 0; i < n; i++) { - bufArray[i] = HEAP32[(((bufs)+(i*4))>>2)]; - } - - GLctx['drawBuffers'](bufArray); - } - Module["_emscripten_glDrawBuffersEXT"] = _emscripten_glDrawBuffersEXT; - _emscripten_glDrawBuffersEXT.sig = 'vii'; + var _emscripten_glDrawBuffersEXT = _glDrawBuffersEXT; + Module['_emscripten_glDrawBuffersEXT'] = _emscripten_glDrawBuffersEXT; - function _emscripten_glMultiDrawArrays(mode, firsts, counts, drawcount) { - GLctx.multiDrawWebgl['multiDrawArraysWEBGL']( - mode, - HEAP32, - firsts >> 2, - HEAP32, - counts >> 2, - drawcount); - } - Module["_emscripten_glMultiDrawArrays"] = _emscripten_glMultiDrawArrays; - _emscripten_glMultiDrawArrays.sig = 'viiii'; + var _emscripten_glMultiDrawArrays = _glMultiDrawArrays; + Module['_emscripten_glMultiDrawArrays'] = _emscripten_glMultiDrawArrays; + _emscripten_glMultiDrawArrays.sig = 'vippi'; - function _emscripten_glMultiDrawArraysANGLE(mode, firsts, counts, drawcount) { - GLctx.multiDrawWebgl['multiDrawArraysWEBGL']( - mode, - HEAP32, - firsts >> 2, - HEAP32, - counts >> 2, - drawcount); - } - Module["_emscripten_glMultiDrawArraysANGLE"] = _emscripten_glMultiDrawArraysANGLE; - _emscripten_glMultiDrawArraysANGLE.sig = 'viiii'; + var _emscripten_glMultiDrawArraysANGLE = _glMultiDrawArraysANGLE; + Module['_emscripten_glMultiDrawArraysANGLE'] = _emscripten_glMultiDrawArraysANGLE; - function _emscripten_glMultiDrawArraysWEBGL(mode, firsts, counts, drawcount) { - GLctx.multiDrawWebgl['multiDrawArraysWEBGL']( - mode, - HEAP32, - firsts >> 2, - HEAP32, - counts >> 2, - drawcount); - } - Module["_emscripten_glMultiDrawArraysWEBGL"] = _emscripten_glMultiDrawArraysWEBGL; - _emscripten_glMultiDrawArraysWEBGL.sig = 'viiii'; + var _emscripten_glMultiDrawArraysWEBGL = _glMultiDrawArraysWEBGL; + Module['_emscripten_glMultiDrawArraysWEBGL'] = _emscripten_glMultiDrawArraysWEBGL; - function _emscripten_glMultiDrawArraysInstancedANGLE(mode, firsts, counts, instanceCounts, drawcount) { - GLctx.multiDrawWebgl['multiDrawArraysInstancedWEBGL']( - mode, - HEAP32, - firsts >> 2, - HEAP32, - counts >> 2, - HEAP32, - instanceCounts >> 2, - drawcount); - } - Module["_emscripten_glMultiDrawArraysInstancedANGLE"] = _emscripten_glMultiDrawArraysInstancedANGLE; - _emscripten_glMultiDrawArraysInstancedANGLE.sig = 'viiiii'; + var _emscripten_glMultiDrawArraysInstancedANGLE = _glMultiDrawArraysInstancedANGLE; + Module['_emscripten_glMultiDrawArraysInstancedANGLE'] = _emscripten_glMultiDrawArraysInstancedANGLE; - function _emscripten_glMultiDrawArraysInstancedWEBGL(mode, firsts, counts, instanceCounts, drawcount) { - GLctx.multiDrawWebgl['multiDrawArraysInstancedWEBGL']( - mode, - HEAP32, - firsts >> 2, - HEAP32, - counts >> 2, - HEAP32, - instanceCounts >> 2, - drawcount); - } - Module["_emscripten_glMultiDrawArraysInstancedWEBGL"] = _emscripten_glMultiDrawArraysInstancedWEBGL; - _emscripten_glMultiDrawArraysInstancedWEBGL.sig = 'viiiii'; + var _emscripten_glMultiDrawArraysInstancedWEBGL = _glMultiDrawArraysInstancedWEBGL; + Module['_emscripten_glMultiDrawArraysInstancedWEBGL'] = _emscripten_glMultiDrawArraysInstancedWEBGL; - function _emscripten_glMultiDrawElements(mode, counts, type, offsets, drawcount) { - GLctx.multiDrawWebgl['multiDrawElementsWEBGL']( - mode, - HEAP32, - counts >> 2, - type, - HEAP32, - offsets >> 2, - drawcount); - } - Module["_emscripten_glMultiDrawElements"] = _emscripten_glMultiDrawElements; - _emscripten_glMultiDrawElements.sig = 'viiiii'; + var _emscripten_glMultiDrawElements = _glMultiDrawElements; + Module['_emscripten_glMultiDrawElements'] = _emscripten_glMultiDrawElements; + _emscripten_glMultiDrawElements.sig = 'vipipi'; - function _emscripten_glMultiDrawElementsANGLE(mode, counts, type, offsets, drawcount) { - GLctx.multiDrawWebgl['multiDrawElementsWEBGL']( - mode, - HEAP32, - counts >> 2, - type, - HEAP32, - offsets >> 2, - drawcount); - } - Module["_emscripten_glMultiDrawElementsANGLE"] = _emscripten_glMultiDrawElementsANGLE; - _emscripten_glMultiDrawElementsANGLE.sig = 'viiiii'; + var _emscripten_glMultiDrawElementsANGLE = _glMultiDrawElementsANGLE; + Module['_emscripten_glMultiDrawElementsANGLE'] = _emscripten_glMultiDrawElementsANGLE; - function _emscripten_glMultiDrawElementsWEBGL(mode, counts, type, offsets, drawcount) { - GLctx.multiDrawWebgl['multiDrawElementsWEBGL']( - mode, - HEAP32, - counts >> 2, - type, - HEAP32, - offsets >> 2, - drawcount); - } - Module["_emscripten_glMultiDrawElementsWEBGL"] = _emscripten_glMultiDrawElementsWEBGL; - _emscripten_glMultiDrawElementsWEBGL.sig = 'viiiii'; + var _emscripten_glMultiDrawElementsWEBGL = _glMultiDrawElementsWEBGL; + Module['_emscripten_glMultiDrawElementsWEBGL'] = _emscripten_glMultiDrawElementsWEBGL; - function _emscripten_glMultiDrawElementsInstancedANGLE(mode, counts, type, offsets, instanceCounts, drawcount) { - GLctx.multiDrawWebgl['multiDrawElementsInstancedWEBGL']( - mode, - HEAP32, - counts >> 2, - type, - HEAP32, - offsets >> 2, - HEAP32, - instanceCounts >> 2, - drawcount); - } - Module["_emscripten_glMultiDrawElementsInstancedANGLE"] = _emscripten_glMultiDrawElementsInstancedANGLE; - _emscripten_glMultiDrawElementsInstancedANGLE.sig = 'viiiiii'; + var _emscripten_glMultiDrawElementsInstancedANGLE = _glMultiDrawElementsInstancedANGLE; + Module['_emscripten_glMultiDrawElementsInstancedANGLE'] = _emscripten_glMultiDrawElementsInstancedANGLE; - function _emscripten_glMultiDrawElementsInstancedWEBGL(mode, counts, type, offsets, instanceCounts, drawcount) { - GLctx.multiDrawWebgl['multiDrawElementsInstancedWEBGL']( - mode, - HEAP32, - counts >> 2, - type, - HEAP32, - offsets >> 2, - HEAP32, - instanceCounts >> 2, - drawcount); - } - Module["_emscripten_glMultiDrawElementsInstancedWEBGL"] = _emscripten_glMultiDrawElementsInstancedWEBGL; - _emscripten_glMultiDrawElementsInstancedWEBGL.sig = 'viiiiii'; + var _emscripten_glMultiDrawElementsInstancedWEBGL = _glMultiDrawElementsInstancedWEBGL; + Module['_emscripten_glMultiDrawElementsInstancedWEBGL'] = _emscripten_glMultiDrawElementsInstancedWEBGL; - function _emscripten_glClearDepth(x0) { GLctx['clearDepth'](x0) } - Module["_emscripten_glClearDepth"] = _emscripten_glClearDepth; - _emscripten_glClearDepth.sig = 'vi'; + var _emscripten_glClearDepth = _glClearDepth; + Module['_emscripten_glClearDepth'] = _emscripten_glClearDepth; + _emscripten_glClearDepth.sig = 'vd'; @@ -23126,9 +22811,9 @@ var ASM_CONSTS = { - function _emscripten_glDepthRange(x0, x1) { GLctx['depthRange'](x0, x1) } - Module["_emscripten_glDepthRange"] = _emscripten_glDepthRange; - _emscripten_glDepthRange.sig = 'vii'; + var _emscripten_glDepthRange = _glDepthRange; + Module['_emscripten_glDepthRange'] = _emscripten_glDepthRange; + _emscripten_glDepthRange.sig = 'vdd'; @@ -23152,46 +22837,33 @@ var ASM_CONSTS = { - function writeGLArray(arr, dst, dstLength, heapType) { + var writeGLArray = (arr, dst, dstLength, heapType) => { assert(arr); assert(typeof arr.length != 'undefined'); var len = arr.length; var writeLength = dstLength < len ? dstLength : len; var heap = heapType ? HEAPF32 : HEAP32; + // Works because HEAPF32 and HEAP32 have the same bytes-per-element + dst = ((dst)>>2); for (var i = 0; i < writeLength; ++i) { - heap[(dst >> 2) + i] = arr[i]; + heap[dst + i] = arr[i]; } return len; - } - Module["writeGLArray"] = writeGLArray; - - function _emscripten_webgl_init_context_attributes(attributes) { - assert(attributes); - var a = attributes >> 2; - for (var i = 0; i < (56>>2); ++i) { - HEAP32[a+i] = 0; - } - - HEAP32[a + (0>>2)] = - HEAP32[a + (4>>2)] = - HEAP32[a + (12>>2)] = - HEAP32[a + (16>>2)] = - HEAP32[a + (32>>2)] = - HEAP32[a + (40>>2)] = 1; - - } - Module["_emscripten_webgl_init_context_attributes"] = _emscripten_webgl_init_context_attributes; + }; + Module['writeGLArray'] = writeGLArray; - var __emscripten_webgl_power_preferences = ['default', 'low-power', 'high-performance']; - Module["__emscripten_webgl_power_preferences"] = __emscripten_webgl_power_preferences; + var webglPowerPreferences = ["default","low-power","high-performance"]; + Module['webglPowerPreferences'] = webglPowerPreferences; - function _emscripten_webgl_do_create_context(target, attributes) { + + /** @suppress {duplicate } */ + var _emscripten_webgl_do_create_context = (target, attributes) => { assert(attributes); - var a = attributes >> 2; + var a = ((attributes)>>2); var powerPreference = HEAP32[a + (24>>2)]; var contextAttributes = { 'alpha': !!HEAP32[a + (0>>2)], @@ -23200,7 +22872,7 @@ var ASM_CONSTS = { 'antialias': !!HEAP32[a + (12>>2)], 'premultipliedAlpha': !!HEAP32[a + (16>>2)], 'preserveDrawingBuffer': !!HEAP32[a + (20>>2)], - 'powerPreference': __emscripten_webgl_power_preferences[powerPreference], + 'powerPreference': webglPowerPreferences[powerPreference], 'failIfMajorPerformanceCaveat': !!HEAP32[a + (28>>2)], // The following are not predefined WebGL context attributes in the WebGL specification, so the property names can be minified by Closure. majorVersion: HEAP32[a + (32>>2)], @@ -23223,22 +22895,25 @@ var ASM_CONSTS = { var contextHandle = GL.createContext(canvas, contextAttributes); return contextHandle; - } - Module["_emscripten_webgl_do_create_context"] = _emscripten_webgl_do_create_context; - _emscripten_webgl_do_create_context.sig = 'iii'; + }; + Module['_emscripten_webgl_do_create_context'] = _emscripten_webgl_do_create_context; + _emscripten_webgl_do_create_context.sig = 'ppp'; var _emscripten_webgl_create_context = _emscripten_webgl_do_create_context; - Module["_emscripten_webgl_create_context"] = _emscripten_webgl_create_context; - _emscripten_webgl_create_context.sig = 'iii'; + Module['_emscripten_webgl_create_context'] = _emscripten_webgl_create_context; + _emscripten_webgl_create_context.sig = 'ppp'; - function _emscripten_webgl_do_get_current_context() { - return GL.currentContext ? GL.currentContext.handle : 0; - } - Module["_emscripten_webgl_do_get_current_context"] = _emscripten_webgl_do_get_current_context; + + /** @suppress {duplicate } */ + var _emscripten_webgl_do_get_current_context = () => GL.currentContext ? GL.currentContext.handle : 0; + Module['_emscripten_webgl_do_get_current_context'] = _emscripten_webgl_do_get_current_context; + _emscripten_webgl_do_get_current_context.sig = 'p'; var _emscripten_webgl_get_current_context = _emscripten_webgl_do_get_current_context; - Module["_emscripten_webgl_get_current_context"] = _emscripten_webgl_get_current_context; - _emscripten_webgl_get_current_context.sig = 'i'; + Module['_emscripten_webgl_get_current_context'] = _emscripten_webgl_get_current_context; + _emscripten_webgl_get_current_context.sig = 'p'; - function _emscripten_webgl_do_commit_frame() { + + /** @suppress {duplicate } */ + var _emscripten_webgl_do_commit_frame = () => { if (!GL.currentContext || !GL.currentContext.GLctx) { return -3; } @@ -23250,23 +22925,23 @@ var ASM_CONSTS = { // in browsers has removed it - swap is implicit, so this function is a no-op for now // (until/unless the spec changes). return 0; - } - Module["_emscripten_webgl_do_commit_frame"] = _emscripten_webgl_do_commit_frame; + }; + Module['_emscripten_webgl_do_commit_frame'] = _emscripten_webgl_do_commit_frame; _emscripten_webgl_do_commit_frame.sig = 'i'; var _emscripten_webgl_commit_frame = _emscripten_webgl_do_commit_frame; - Module["_emscripten_webgl_commit_frame"] = _emscripten_webgl_commit_frame; + Module['_emscripten_webgl_commit_frame'] = _emscripten_webgl_commit_frame; _emscripten_webgl_commit_frame.sig = 'i'; - function _emscripten_webgl_make_context_current(contextHandle) { + var _emscripten_webgl_make_context_current = (contextHandle) => { var success = GL.makeContextCurrent(contextHandle); return success ? 0 : -5; - } - Module["_emscripten_webgl_make_context_current"] = _emscripten_webgl_make_context_current; - _emscripten_webgl_make_context_current.sig = 'ii'; + }; + Module['_emscripten_webgl_make_context_current'] = _emscripten_webgl_make_context_current; + _emscripten_webgl_make_context_current.sig = 'ip'; - function _emscripten_webgl_get_drawing_buffer_size(contextHandle, width, height) { + var _emscripten_webgl_get_drawing_buffer_size = (contextHandle, width, height) => { var GLContext = GL.getContext(contextHandle); if (!GLContext || !GLContext.GLctx || !width || !height) { @@ -23275,12 +22950,13 @@ var ASM_CONSTS = { HEAP32[((width)>>2)] = GLContext.GLctx.drawingBufferWidth; HEAP32[((height)>>2)] = GLContext.GLctx.drawingBufferHeight; return 0; - } - Module["_emscripten_webgl_get_drawing_buffer_size"] = _emscripten_webgl_get_drawing_buffer_size; - _emscripten_webgl_get_drawing_buffer_size.sig = 'iiii'; + }; + Module['_emscripten_webgl_get_drawing_buffer_size'] = _emscripten_webgl_get_drawing_buffer_size; + _emscripten_webgl_get_drawing_buffer_size.sig = 'ippp'; - function _emscripten_webgl_get_context_attributes(c, a) { + + var _emscripten_webgl_get_context_attributes = (c, a) => { if (!a) return -5; c = GL.contexts[c]; if (!c) return -3; @@ -23294,28 +22970,31 @@ var ASM_CONSTS = { HEAP32[(((a)+(12))>>2)] = t.antialias; HEAP32[(((a)+(16))>>2)] = t.premultipliedAlpha; HEAP32[(((a)+(20))>>2)] = t.preserveDrawingBuffer; - var power = t['powerPreference'] && __emscripten_webgl_power_preferences.indexOf(t['powerPreference']); + var power = t['powerPreference'] && webglPowerPreferences.indexOf(t['powerPreference']); HEAP32[(((a)+(24))>>2)] = power; HEAP32[(((a)+(28))>>2)] = t.failIfMajorPerformanceCaveat; HEAP32[(((a)+(32))>>2)] = c.version; HEAP32[(((a)+(36))>>2)] = 0; HEAP32[(((a)+(40))>>2)] = c.attributes.enableExtensionsByDefault; return 0; - } - Module["_emscripten_webgl_get_context_attributes"] = _emscripten_webgl_get_context_attributes; - _emscripten_webgl_get_context_attributes.sig = 'iii'; + }; + Module['_emscripten_webgl_get_context_attributes'] = _emscripten_webgl_get_context_attributes; + _emscripten_webgl_get_context_attributes.sig = 'ipp'; - function _emscripten_webgl_destroy_context(contextHandle) { + + var _emscripten_webgl_destroy_context = (contextHandle) => { if (GL.currentContext == contextHandle) GL.currentContext = 0; GL.deleteContext(contextHandle); - } - Module["_emscripten_webgl_destroy_context"] = _emscripten_webgl_destroy_context; - _emscripten_webgl_destroy_context.sig = 'vi'; + }; + Module['_emscripten_webgl_destroy_context'] = _emscripten_webgl_destroy_context; + _emscripten_webgl_destroy_context.sig = 'ip'; - function _emscripten_webgl_enable_extension(contextHandle, extension) { + + + var _emscripten_webgl_enable_extension = (contextHandle, extension) => { var context = GL.getContext(contextHandle); var extString = UTF8ToString(extension); if (extString.startsWith('GL_')) extString = extString.substr(3); // Allow enabling extensions both with "GL_" prefix and without. @@ -23324,162 +23003,158 @@ var ASM_CONSTS = { // Build with -sGL_SUPPORT_SIMPLE_ENABLE_EXTENSIONS=0 to avoid this. // Obtain function entry points to WebGL 1 extension related functions. - if (extString == 'ANGLE_instanced_arrays') __webgl_enable_ANGLE_instanced_arrays(GLctx); - if (extString == 'OES_vertex_array_object') __webgl_enable_OES_vertex_array_object(GLctx); - if (extString == 'WEBGL_draw_buffers') __webgl_enable_WEBGL_draw_buffers(GLctx); + if (extString == 'ANGLE_instanced_arrays') webgl_enable_ANGLE_instanced_arrays(GLctx); + if (extString == 'OES_vertex_array_object') webgl_enable_OES_vertex_array_object(GLctx); + if (extString == 'WEBGL_draw_buffers') webgl_enable_WEBGL_draw_buffers(GLctx); - if (extString == 'WEBGL_multi_draw') __webgl_enable_WEBGL_multi_draw(GLctx); + if (extString == 'WEBGL_multi_draw') webgl_enable_WEBGL_multi_draw(GLctx); var ext = context.GLctx.getExtension(extString); return !!ext; - } - Module["_emscripten_webgl_enable_extension"] = _emscripten_webgl_enable_extension; - _emscripten_webgl_enable_extension.sig = 'iii'; + }; + Module['_emscripten_webgl_enable_extension'] = _emscripten_webgl_enable_extension; + _emscripten_webgl_enable_extension.sig = 'ipp'; - function _emscripten_supports_offscreencanvas() { + var _emscripten_supports_offscreencanvas = () => // TODO: Add a new build mode, e.g. OFFSCREENCANVAS_SUPPORT=2, which // necessitates OffscreenCanvas support at build time, and "return 1;" here in that build mode. - return 0; - } - Module["_emscripten_supports_offscreencanvas"] = _emscripten_supports_offscreencanvas; + 0; + Module['_emscripten_supports_offscreencanvas'] = _emscripten_supports_offscreencanvas; + _emscripten_supports_offscreencanvas.sig = 'i'; - function __registerWebGlEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) { - var webGlEventHandlerFunc = function(e = event) { + var registerWebGlEventCallback = (target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) => { + + var webGlEventHandlerFunc = (e = event) => { if (getWasmTableEntry(callbackfunc)(eventTypeId, 0, userData)) e.preventDefault(); }; var eventHandler = { target: findEventTarget(target), - eventTypeString: eventTypeString, - callbackfunc: callbackfunc, + eventTypeString, + callbackfunc, handlerFunc: webGlEventHandlerFunc, - useCapture: useCapture + useCapture }; JSEvents.registerOrRemoveHandler(eventHandler); - } - Module["__registerWebGlEventCallback"] = __registerWebGlEventCallback; + }; + Module['registerWebGlEventCallback'] = registerWebGlEventCallback; - function _emscripten_set_webglcontextlost_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { - __registerWebGlEventCallback(target, userData, useCapture, callbackfunc, 31, "webglcontextlost", targetThread); + + var _emscripten_set_webglcontextlost_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => { + registerWebGlEventCallback(target, userData, useCapture, callbackfunc, 31, "webglcontextlost", targetThread); return 0; - } - Module["_emscripten_set_webglcontextlost_callback_on_thread"] = _emscripten_set_webglcontextlost_callback_on_thread; - _emscripten_set_webglcontextlost_callback_on_thread.sig = 'iiiiii'; + }; + Module['_emscripten_set_webglcontextlost_callback_on_thread'] = _emscripten_set_webglcontextlost_callback_on_thread; + _emscripten_set_webglcontextlost_callback_on_thread.sig = 'ippipp'; - function _emscripten_set_webglcontextrestored_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) { - __registerWebGlEventCallback(target, userData, useCapture, callbackfunc, 32, "webglcontextrestored", targetThread); + + var _emscripten_set_webglcontextrestored_callback_on_thread = (target, userData, useCapture, callbackfunc, targetThread) => { + registerWebGlEventCallback(target, userData, useCapture, callbackfunc, 32, "webglcontextrestored", targetThread); return 0; - } - Module["_emscripten_set_webglcontextrestored_callback_on_thread"] = _emscripten_set_webglcontextrestored_callback_on_thread; - _emscripten_set_webglcontextrestored_callback_on_thread.sig = 'iiiiii'; + }; + Module['_emscripten_set_webglcontextrestored_callback_on_thread'] = _emscripten_set_webglcontextrestored_callback_on_thread; + _emscripten_set_webglcontextrestored_callback_on_thread.sig = 'ippipp'; - function _emscripten_is_webgl_context_lost(contextHandle) { + var _emscripten_is_webgl_context_lost = (contextHandle) => { return !GL.contexts[contextHandle] || GL.contexts[contextHandle].GLctx.isContextLost(); // No context ~> lost context. - } - Module["_emscripten_is_webgl_context_lost"] = _emscripten_is_webgl_context_lost; - _emscripten_is_webgl_context_lost.sig = 'ii'; + }; + Module['_emscripten_is_webgl_context_lost'] = _emscripten_is_webgl_context_lost; + _emscripten_is_webgl_context_lost.sig = 'ip'; - function _emscripten_webgl_get_supported_extensions() { - return stringToNewUTF8(GLctx.getSupportedExtensions().join(' ')); - } - Module["_emscripten_webgl_get_supported_extensions"] = _emscripten_webgl_get_supported_extensions; - _emscripten_webgl_get_supported_extensions.sig = 'i'; + + var _emscripten_webgl_get_supported_extensions = () => + stringToNewUTF8(GLctx.getSupportedExtensions().join(' ')); + Module['_emscripten_webgl_get_supported_extensions'] = _emscripten_webgl_get_supported_extensions; + _emscripten_webgl_get_supported_extensions.sig = 'p'; - function _emscripten_webgl_get_program_parameter_d(program, param) { - return GLctx.getProgramParameter(GL.programs[program], param); - } - Module["_emscripten_webgl_get_program_parameter_d"] = _emscripten_webgl_get_program_parameter_d; - _emscripten_webgl_get_program_parameter_d.sig = 'fii'; + var _emscripten_webgl_get_program_parameter_d = (program, param) => + GLctx.getProgramParameter(GL.programs[program], param); + Module['_emscripten_webgl_get_program_parameter_d'] = _emscripten_webgl_get_program_parameter_d; + _emscripten_webgl_get_program_parameter_d.sig = 'dii'; - function _emscripten_webgl_get_program_info_log_utf8(program) { - return stringToNewUTF8(GLctx.getProgramInfoLog(GL.programs[program])); - } - Module["_emscripten_webgl_get_program_info_log_utf8"] = _emscripten_webgl_get_program_info_log_utf8; - _emscripten_webgl_get_program_info_log_utf8.sig = 'ii'; + + var _emscripten_webgl_get_program_info_log_utf8 = (program) => + stringToNewUTF8(GLctx.getProgramInfoLog(GL.programs[program])); + Module['_emscripten_webgl_get_program_info_log_utf8'] = _emscripten_webgl_get_program_info_log_utf8; + _emscripten_webgl_get_program_info_log_utf8.sig = 'pi'; - function _emscripten_webgl_get_shader_parameter_d(shader, param) { - return GLctx.getShaderParameter(GL.shaders[shader], param); - } - Module["_emscripten_webgl_get_shader_parameter_d"] = _emscripten_webgl_get_shader_parameter_d; - _emscripten_webgl_get_shader_parameter_d.sig = 'fii'; + var _emscripten_webgl_get_shader_parameter_d = (shader, param) => + GLctx.getShaderParameter(GL.shaders[shader], param); + Module['_emscripten_webgl_get_shader_parameter_d'] = _emscripten_webgl_get_shader_parameter_d; + _emscripten_webgl_get_shader_parameter_d.sig = 'dii'; - function _emscripten_webgl_get_shader_info_log_utf8(shader) { - return stringToNewUTF8(GLctx.getShaderInfoLog(GL.shaders[shader])); - } - Module["_emscripten_webgl_get_shader_info_log_utf8"] = _emscripten_webgl_get_shader_info_log_utf8; - _emscripten_webgl_get_shader_info_log_utf8.sig = 'ii'; + + var _emscripten_webgl_get_shader_info_log_utf8 = (shader) => + stringToNewUTF8(GLctx.getShaderInfoLog(GL.shaders[shader])); + Module['_emscripten_webgl_get_shader_info_log_utf8'] = _emscripten_webgl_get_shader_info_log_utf8; + _emscripten_webgl_get_shader_info_log_utf8.sig = 'pi'; - function _emscripten_webgl_get_shader_source_utf8(shader) { - return stringToNewUTF8(GLctx.getShaderSource(GL.shaders[shader])); - } - Module["_emscripten_webgl_get_shader_source_utf8"] = _emscripten_webgl_get_shader_source_utf8; - _emscripten_webgl_get_shader_source_utf8.sig = 'ii'; + + var _emscripten_webgl_get_shader_source_utf8 = (shader) => + stringToNewUTF8(GLctx.getShaderSource(GL.shaders[shader])); + Module['_emscripten_webgl_get_shader_source_utf8'] = _emscripten_webgl_get_shader_source_utf8; + _emscripten_webgl_get_shader_source_utf8.sig = 'pi'; - function _emscripten_webgl_get_vertex_attrib_d(index, param) { - return GLctx.getVertexAttrib(index, param); - } - Module["_emscripten_webgl_get_vertex_attrib_d"] = _emscripten_webgl_get_vertex_attrib_d; - _emscripten_webgl_get_vertex_attrib_d.sig = 'iii'; + var _emscripten_webgl_get_vertex_attrib_d = (index, param) => + GLctx.getVertexAttrib(index, param); + Module['_emscripten_webgl_get_vertex_attrib_d'] = _emscripten_webgl_get_vertex_attrib_d; + _emscripten_webgl_get_vertex_attrib_d.sig = 'dii'; - function _emscripten_webgl_get_vertex_attrib_o(index, param) { + var _emscripten_webgl_get_vertex_attrib_o = (index, param) => { var obj = GLctx.getVertexAttrib(index, param); - return obj && obj.name; - } - Module["_emscripten_webgl_get_vertex_attrib_o"] = _emscripten_webgl_get_vertex_attrib_o; + return obj?.name; + }; + Module['_emscripten_webgl_get_vertex_attrib_o'] = _emscripten_webgl_get_vertex_attrib_o; _emscripten_webgl_get_vertex_attrib_o.sig = 'iii'; - function _emscripten_webgl_get_vertex_attrib_v(index, param, dst, dstLength, dstType) { - return writeGLArray(GLctx.getVertexAttrib(index, param), dst, dstLength, dstType); - } - Module["_emscripten_webgl_get_vertex_attrib_v"] = _emscripten_webgl_get_vertex_attrib_v; - _emscripten_webgl_get_vertex_attrib_v.sig = 'iiiiii'; + + var _emscripten_webgl_get_vertex_attrib_v = (index, param, dst, dstLength, dstType) => + writeGLArray(GLctx.getVertexAttrib(index, param), dst, dstLength, dstType); + Module['_emscripten_webgl_get_vertex_attrib_v'] = _emscripten_webgl_get_vertex_attrib_v; + _emscripten_webgl_get_vertex_attrib_v.sig = 'iiipii'; - function _emscripten_webgl_get_uniform_d(program, location) { - return GLctx.getUniform(GL.programs[program], webglGetUniformLocation(location)); - } - Module["_emscripten_webgl_get_uniform_d"] = _emscripten_webgl_get_uniform_d; - _emscripten_webgl_get_uniform_d.sig = 'fii'; + + var _emscripten_webgl_get_uniform_d = (program, location) => + GLctx.getUniform(GL.programs[program], webglGetUniformLocation(location)); + Module['_emscripten_webgl_get_uniform_d'] = _emscripten_webgl_get_uniform_d; + _emscripten_webgl_get_uniform_d.sig = 'dii'; - function _emscripten_webgl_get_uniform_v(program, location, dst, dstLength, dstType) { - return writeGLArray(GLctx.getUniform(GL.programs[program], webglGetUniformLocation(location)), dst, dstLength, dstType); - } - Module["_emscripten_webgl_get_uniform_v"] = _emscripten_webgl_get_uniform_v; - _emscripten_webgl_get_uniform_v.sig = 'iiiiii'; + + var _emscripten_webgl_get_uniform_v = (program, location, dst, dstLength, dstType) => + writeGLArray(GLctx.getUniform(GL.programs[program], webglGetUniformLocation(location)), dst, dstLength, dstType); + Module['_emscripten_webgl_get_uniform_v'] = _emscripten_webgl_get_uniform_v; + _emscripten_webgl_get_uniform_v.sig = 'iiipii'; - function _emscripten_webgl_get_parameter_v(param, dst, dstLength, dstType) { - return writeGLArray(GLctx.getParameter(param), dst, dstLength, dstType); - } - Module["_emscripten_webgl_get_parameter_v"] = _emscripten_webgl_get_parameter_v; - _emscripten_webgl_get_parameter_v.sig = 'iiiii'; + + var _emscripten_webgl_get_parameter_v = (param, dst, dstLength, dstType) => + writeGLArray(GLctx.getParameter(param), dst, dstLength, dstType); + Module['_emscripten_webgl_get_parameter_v'] = _emscripten_webgl_get_parameter_v; + _emscripten_webgl_get_parameter_v.sig = 'iipii'; - function _emscripten_webgl_get_parameter_d(param) { - return GLctx.getParameter(param); - } - Module["_emscripten_webgl_get_parameter_d"] = _emscripten_webgl_get_parameter_d; - _emscripten_webgl_get_parameter_d.sig = 'fi'; + var _emscripten_webgl_get_parameter_d = (param) => GLctx.getParameter(param); + Module['_emscripten_webgl_get_parameter_d'] = _emscripten_webgl_get_parameter_d; + _emscripten_webgl_get_parameter_d.sig = 'di'; - function _emscripten_webgl_get_parameter_o(param) { + var _emscripten_webgl_get_parameter_o = (param) => { var obj = GLctx.getParameter(param); - return obj && obj.name; - } - Module["_emscripten_webgl_get_parameter_o"] = _emscripten_webgl_get_parameter_o; + return obj?.name; + }; + Module['_emscripten_webgl_get_parameter_o'] = _emscripten_webgl_get_parameter_o; _emscripten_webgl_get_parameter_o.sig = 'ii'; - function _emscripten_webgl_get_parameter_utf8(param) { - return stringToNewUTF8(GLctx.getParameter(param)); - } - Module["_emscripten_webgl_get_parameter_utf8"] = _emscripten_webgl_get_parameter_utf8; - _emscripten_webgl_get_parameter_utf8.sig = 'ii'; + + var _emscripten_webgl_get_parameter_utf8 = (param) => stringToNewUTF8(GLctx.getParameter(param)); + Module['_emscripten_webgl_get_parameter_utf8'] = _emscripten_webgl_get_parameter_utf8; + _emscripten_webgl_get_parameter_utf8.sig = 'pi'; - function _emscripten_webgl_get_parameter_i64v(param, dst) { - writeI53ToI64(dst, GLctx.getParameter(param)); - } - Module["_emscripten_webgl_get_parameter_i64v"] = _emscripten_webgl_get_parameter_i64v; - _emscripten_webgl_get_parameter_i64v.sig = 'vii'; + + var _emscripten_webgl_get_parameter_i64v = (param, dst) => writeI53ToI64(dst, GLctx.getParameter(param)); + Module['_emscripten_webgl_get_parameter_i64v'] = _emscripten_webgl_get_parameter_i64v; + _emscripten_webgl_get_parameter_i64v.sig = 'vip'; @@ -23579,6350 +23254,5587 @@ var ASM_CONSTS = { - - function _SDL_GetTicks() { - return (Date.now() - SDL.startTime)|0; - } - Module["_SDL_GetTicks"] = _SDL_GetTicks; - _SDL_GetTicks.sig = 'i'; - - function _SDL_LockSurface(surf) { - var surfData = SDL.surfaces[surf]; - - surfData.locked++; - if (surfData.locked > 1) return 0; - - if (!surfData.buffer) { - surfData.buffer = _malloc(surfData.width * surfData.height * 4); - HEAPU32[(((surf)+(20))>>2)] = surfData.buffer; + var _glutPostRedisplay = () => { + if (GLUT.displayFunc && !GLUT.requestedAnimationFrame) { + GLUT.requestedAnimationFrame = true; + Browser.requestAnimationFrame(function() { + GLUT.requestedAnimationFrame = false; + Browser.mainLoop.runIter(function() { + getWasmTableEntry(GLUT.displayFunc)(); + }); + }); } + }; + Module['_glutPostRedisplay'] = _glutPostRedisplay; + _glutPostRedisplay.sig = 'v'; - // Mark in C/C++-accessible SDL structure - // SDL_Surface has the following fields: Uint32 flags, SDL_PixelFormat *format; int w, h; Uint16 pitch; void *pixels; ... - // So we have fields all of the same size, and 5 of them before us. - // TODO: Use macros like in library.js - HEAPU32[(((surf)+(20))>>2)] = surfData.buffer; - - if (surf == SDL.screen && Module.screenIsReadOnly && surfData.image) return 0; - if (SDL.defaults.discardOnLock) { - if (!surfData.image) { - surfData.image = surfData.ctx.createImageData(surfData.width, surfData.height); - } - if (!SDL.defaults.opaqueFrontBuffer) return; - } else { - surfData.image = surfData.ctx.getImageData(0, 0, surfData.width, surfData.height); - } + var GLUT = { + initTime:null, + idleFunc:null, + displayFunc:null, + keyboardFunc:null, + keyboardUpFunc:null, + specialFunc:null, + specialUpFunc:null, + reshapeFunc:null, + motionFunc:null, + passiveMotionFunc:null, + mouseFunc:null, + buttons:0, + modifiers:0, + initWindowWidth:256, + initWindowHeight:256, + initDisplayMode:18, + windowX:0, + windowY:0, + windowWidth:0, + windowHeight:0, + requestedAnimationFrame:false, + saveModifiers:(event) => { + GLUT.modifiers = 0; + if (event['shiftKey']) + GLUT.modifiers += 1; /* GLUT_ACTIVE_SHIFT */ + if (event['ctrlKey']) + GLUT.modifiers += 2; /* GLUT_ACTIVE_CTRL */ + if (event['altKey']) + GLUT.modifiers += 4; /* GLUT_ACTIVE_ALT */ + }, + onMousemove:(event) => { + /* Send motion event only if the motion changed, prevents + * spamming our app with uncessary callback call. It does happen in + * Chrome on Windows. + */ + var lastX = Browser.mouseX; + var lastY = Browser.mouseY; + Browser.calculateMouseEvent(event); + var newX = Browser.mouseX; + var newY = Browser.mouseY; + if (newX == lastX && newY == lastY) return; - // Emulate desktop behavior and kill alpha values on the locked surface. (very costly!) Set SDL.defaults.opaqueFrontBuffer = false - // if you don't want this. - if (surf == SDL.screen && SDL.defaults.opaqueFrontBuffer) { - var data = surfData.image.data; - var num = data.length; - for (var i = 0; i < num/4; i++) { - data[i*4+3] = 255; // opacity, as canvases blend alpha + if (GLUT.buttons == 0 && event.target == Module["canvas"] && GLUT.passiveMotionFunc) { + event.preventDefault(); + GLUT.saveModifiers(event); + getWasmTableEntry(GLUT.passiveMotionFunc)(lastX, lastY); + } else if (GLUT.buttons != 0 && GLUT.motionFunc) { + event.preventDefault(); + GLUT.saveModifiers(event); + getWasmTableEntry(GLUT.motionFunc)(lastX, lastY); } - } + }, + getSpecialKey:(keycode) => { + var key = null; + switch (keycode) { + case 8: key = 120 /* backspace */; break; + case 46: key = 111 /* delete */; break; - if (SDL.defaults.copyOnLock && !SDL.defaults.discardOnLock) { - // Copy pixel data to somewhere accessible to 'C/C++' - if (surfData.isFlagSet(0x00200000 /* SDL_HWPALETTE */)) { - // If this is neaded then - // we should compact the data from 32bpp to 8bpp index. - // I think best way to implement this is use - // additional colorMap hash (color->index). - // Something like this: - // - // var size = surfData.width * surfData.height; - // var data = ''; - // for (var i = 0; i>0)] = index; - // } - throw 'CopyOnLock is not supported for SDL_LockSurface with SDL_HWPALETTE flag set' + new Error().stack; - } else { - HEAPU8.set(surfData.image.data, surfData.buffer); - } - } + case 0x70 /*DOM_VK_F1*/: key = 1 /* GLUT_KEY_F1 */; break; + case 0x71 /*DOM_VK_F2*/: key = 2 /* GLUT_KEY_F2 */; break; + case 0x72 /*DOM_VK_F3*/: key = 3 /* GLUT_KEY_F3 */; break; + case 0x73 /*DOM_VK_F4*/: key = 4 /* GLUT_KEY_F4 */; break; + case 0x74 /*DOM_VK_F5*/: key = 5 /* GLUT_KEY_F5 */; break; + case 0x75 /*DOM_VK_F6*/: key = 6 /* GLUT_KEY_F6 */; break; + case 0x76 /*DOM_VK_F7*/: key = 7 /* GLUT_KEY_F7 */; break; + case 0x77 /*DOM_VK_F8*/: key = 8 /* GLUT_KEY_F8 */; break; + case 0x78 /*DOM_VK_F9*/: key = 9 /* GLUT_KEY_F9 */; break; + case 0x79 /*DOM_VK_F10*/: key = 10 /* GLUT_KEY_F10 */; break; + case 0x7a /*DOM_VK_F11*/: key = 11 /* GLUT_KEY_F11 */; break; + case 0x7b /*DOM_VK_F12*/: key = 12 /* GLUT_KEY_F12 */; break; + case 0x25 /*DOM_VK_LEFT*/: key = 100 /* GLUT_KEY_LEFT */; break; + case 0x26 /*DOM_VK_UP*/: key = 101 /* GLUT_KEY_UP */; break; + case 0x27 /*DOM_VK_RIGHT*/: key = 102 /* GLUT_KEY_RIGHT */; break; + case 0x28 /*DOM_VK_DOWN*/: key = 103 /* GLUT_KEY_DOWN */; break; + case 0x21 /*DOM_VK_PAGE_UP*/: key = 104 /* GLUT_KEY_PAGE_UP */; break; + case 0x22 /*DOM_VK_PAGE_DOWN*/: key = 105 /* GLUT_KEY_PAGE_DOWN */; break; + case 0x24 /*DOM_VK_HOME*/: key = 106 /* GLUT_KEY_HOME */; break; + case 0x23 /*DOM_VK_END*/: key = 107 /* GLUT_KEY_END */; break; + case 0x2d /*DOM_VK_INSERT*/: key = 108 /* GLUT_KEY_INSERT */; break; - return 0; - } - Module["_SDL_LockSurface"] = _SDL_LockSurface; - _SDL_LockSurface.sig = 'ii'; + case 16 /*DOM_VK_SHIFT*/: + case 0x05 /*DOM_VK_LEFT_SHIFT*/: + key = 112 /* GLUT_KEY_SHIFT_L */; + break; + case 0x06 /*DOM_VK_RIGHT_SHIFT*/: + key = 113 /* GLUT_KEY_SHIFT_R */; + break; + case 17 /*DOM_VK_CONTROL*/: + case 0x03 /*DOM_VK_LEFT_CONTROL*/: + key = 114 /* GLUT_KEY_CONTROL_L */; + break; + case 0x04 /*DOM_VK_RIGHT_CONTROL*/: + key = 115 /* GLUT_KEY_CONTROL_R */; + break; - /** @suppress{missingProperties} */ - function SDL_ttfContext() { return SDL.ttfContext; } - Module["SDL_ttfContext"] = SDL_ttfContext; + case 18 /*DOM_VK_ALT*/: + case 0x02 /*DOM_VK_LEFT_ALT*/: + key = 116 /* GLUT_KEY_ALT_L */; + break; + case 0x01 /*DOM_VK_RIGHT_ALT*/: + key = 117 /* GLUT_KEY_ALT_R */; + break; + }; + return key; + }, + getASCIIKey:(event) => { + if (event['ctrlKey'] || event['altKey'] || event['metaKey']) return null; - /** @suppress{missingProperties} */ - function SDL_audio() { return SDL.audio; } - Module["SDL_audio"] = SDL_audio; + var keycode = event['keyCode']; + /* The exact list is soooo hard to find in a canonical place! */ - var SDL = {defaults:{width:320,height:200,copyOnLock:true,discardOnLock:false,opaqueFrontBuffer:true},version:null,surfaces:{},canvasPool:[],events:[],fonts:[null],audios:[null],rwops:[null],music:{audio:null,volume:1},mixerFrequency:22050,mixerFormat:32784,mixerNumChannels:2,mixerChunkSize:1024,channelMinimumNumber:0,GL:false,glAttributes:{0:3,1:3,2:2,3:0,4:0,5:1,6:16,7:0,8:0,9:0,10:0,11:0,12:0,13:0,14:0,15:1,16:0,17:0,18:0},keyboardState:null,keyboardMap:{},canRequestFullscreen:false,isRequestingFullscreen:false,textInput:false,startTime:null,initFlags:0,buttonState:0,modState:0,DOMButtons:[0,0,0],DOMEventToSDLEvent:{},TOUCH_DEFAULT_ID:0,eventHandler:null,eventHandlerContext:null,eventHandlerTemp:0,keyCodes:{16:1249,17:1248,18:1250,20:1081,33:1099,34:1102,35:1101,36:1098,37:1104,38:1106,39:1103,40:1105,44:316,45:1097,46:127,91:1251,93:1125,96:1122,97:1113,98:1114,99:1115,100:1116,101:1117,102:1118,103:1119,104:1120,105:1121,106:1109,107:1111,109:1110,110:1123,111:1108,112:1082,113:1083,114:1084,115:1085,116:1086,117:1087,118:1088,119:1089,120:1090,121:1091,122:1092,123:1093,124:1128,125:1129,126:1130,127:1131,128:1132,129:1133,130:1134,131:1135,132:1136,133:1137,134:1138,135:1139,144:1107,160:94,161:33,162:34,163:35,164:36,165:37,166:38,167:95,168:40,169:41,170:42,171:43,172:124,173:45,174:123,175:125,176:126,181:127,182:129,183:128,188:44,190:46,191:47,192:96,219:91,220:92,221:93,222:39,224:1251},scanCodes:{8:42,9:43,13:40,27:41,32:44,35:204,39:53,44:54,46:55,47:56,48:39,49:30,50:31,51:32,52:33,53:34,54:35,55:36,56:37,57:38,58:203,59:51,61:46,91:47,92:49,93:48,96:52,97:4,98:5,99:6,100:7,101:8,102:9,103:10,104:11,105:12,106:13,107:14,108:15,109:16,110:17,111:18,112:19,113:20,114:21,115:22,116:23,117:24,118:25,119:26,120:27,121:28,122:29,127:76,305:224,308:226,316:70},loadRect:function(rect) { - return { - x: HEAP32[((rect + 0)>>2)], - y: HEAP32[((rect + 4)>>2)], - w: HEAP32[((rect + 8)>>2)], - h: HEAP32[((rect + 12)>>2)] - }; - },updateRect:function(rect, r) { - HEAP32[((rect)>>2)] = r.x; - HEAP32[(((rect)+(4))>>2)] = r.y; - HEAP32[(((rect)+(8))>>2)] = r.w; - HEAP32[(((rect)+(12))>>2)] = r.h; - },intersectionOfRects:function(first, second) { - var leftX = Math.max(first.x, second.x); - var leftY = Math.max(first.y, second.y); - var rightX = Math.min(first.x + first.w, second.x + second.w); - var rightY = Math.min(first.y + first.h, second.y + second.h); + if (48 <= keycode && keycode <= 57) + return keycode; // numeric TODO handle shift? + if (65 <= keycode && keycode <= 90) + return event['shiftKey'] ? keycode : keycode + 32; + if (96 <= keycode && keycode <= 105) + return keycode - 48; // numpad numbers + if (106 <= keycode && keycode <= 111) + return keycode - 106 + 42; // *,+-./ TODO handle shift? - return { - x: leftX, - y: leftY, - w: Math.max(leftX, rightX) - leftX, - h: Math.max(leftY, rightY) - leftY - } - },checkPixelFormat:function(fmt) { - // Canvas screens are always RGBA. - var format = HEAP32[((fmt)>>2)]; - if (format != -2042224636) { - warnOnce('Unsupported pixel format!'); + switch (keycode) { + case 9: // tab key + case 13: // return key + case 27: // escape + case 32: // space + case 61: // equal + return keycode; } - },loadColorToCSSRGB:function(color) { - var rgba = HEAP32[((color)>>2)]; - return 'rgb(' + (rgba&255) + ',' + ((rgba >> 8)&255) + ',' + ((rgba >> 16)&255) + ')'; - },loadColorToCSSRGBA:function(color) { - var rgba = HEAP32[((color)>>2)]; - return 'rgba(' + (rgba&255) + ',' + ((rgba >> 8)&255) + ',' + ((rgba >> 16)&255) + ',' + (((rgba >> 24)&255)/255) + ')'; - },translateColorToCSSRGBA:function(rgba) { - return 'rgba(' + (rgba&0xff) + ',' + (rgba>>8 & 0xff) + ',' + (rgba>>16 & 0xff) + ',' + (rgba>>>24)/0xff + ')'; - },translateRGBAToCSSRGBA:function(r, g, b, a) { - return 'rgba(' + (r&0xff) + ',' + (g&0xff) + ',' + (b&0xff) + ',' + (a&0xff)/255 + ')'; - },translateRGBAToColor:function(r, g, b, a) { - return r | g << 8 | b << 16 | a << 24; - },makeSurface:function(width, height, flags, usePageCanvas, source, rmask, gmask, bmask, amask) { - var is_SDL_HWSURFACE = flags & 0x00000001; - var is_SDL_HWPALETTE = flags & 0x00200000; - var is_SDL_OPENGL = flags & 0x04000000; - var surf = _malloc(60); - var pixelFormat = _malloc(44); - //surface with SDL_HWPALETTE flag is 8bpp surface (1 byte) - var bpp = is_SDL_HWPALETTE ? 1 : 4; - var buffer = 0; + var s = event['shiftKey']; + switch (keycode) { + case 186: return s ? 58 : 59; // colon / semi-colon + case 187: return s ? 43 : 61; // add / equal (these two may be wrong) + case 188: return s ? 60 : 44; // less-than / comma + case 189: return s ? 95 : 45; // dash + case 190: return s ? 62 : 46; // greater-than / period + case 191: return s ? 63 : 47; // forward slash + case 219: return s ? 123 : 91; // open bracket + case 220: return s ? 124 : 47; // back slash + case 221: return s ? 125 : 93; // close bracket + case 222: return s ? 34 : 39; // single quote + } - // preemptively initialize this for software surfaces, - // otherwise it will be lazily initialized inside of SDL_LockSurface - if (!is_SDL_HWSURFACE && !is_SDL_OPENGL) { - buffer = _malloc(width * height * 4); - } - - HEAP32[((surf)>>2)] = flags; - HEAPU32[(((surf)+(4))>>2)] = pixelFormat; - HEAP32[(((surf)+(8))>>2)] = width; - HEAP32[(((surf)+(12))>>2)] = height; - HEAP32[(((surf)+(16))>>2)] = width * bpp; // assuming RGBA or indexed for now, - // since that is what ImageData gives us in browsers - HEAPU32[(((surf)+(20))>>2)] = buffer; - - HEAP32[(((surf)+(36))>>2)] = 0; - HEAP32[(((surf)+(40))>>2)] = 0; - HEAP32[(((surf)+(44))>>2)] = Module["canvas"].width; - HEAP32[(((surf)+(48))>>2)] = Module["canvas"].height; - - HEAP32[(((surf)+(56))>>2)] = 1; - - HEAP32[((pixelFormat)>>2)] = -2042224636; - HEAP32[(((pixelFormat)+(4))>>2)] = 0;// TODO - HEAP8[(((pixelFormat)+(8))>>0)] = bpp * 8; - HEAP8[(((pixelFormat)+(9))>>0)] = bpp; - - HEAP32[(((pixelFormat)+(12))>>2)] = rmask || 0x000000ff; - HEAP32[(((pixelFormat)+(16))>>2)] = gmask || 0x0000ff00; - HEAP32[(((pixelFormat)+(20))>>2)] = bmask || 0x00ff0000; - HEAP32[(((pixelFormat)+(24))>>2)] = amask || 0xff000000; - - // Decide if we want to use WebGL or not - SDL.GL = SDL.GL || is_SDL_OPENGL; - var canvas; - if (!usePageCanvas) { - if (SDL.canvasPool.length > 0) { - canvas = SDL.canvasPool.pop(); + return null; + }, + onKeydown:(event) => { + if (GLUT.specialFunc || GLUT.keyboardFunc) { + var key = GLUT.getSpecialKey(event['keyCode']); + if (key !== null) { + if (GLUT.specialFunc) { + event.preventDefault(); + GLUT.saveModifiers(event); + getWasmTableEntry(GLUT.specialFunc)(key, Browser.mouseX, Browser.mouseY); + } } else { - canvas = document.createElement('canvas'); + key = GLUT.getASCIIKey(event); + if (key !== null && GLUT.keyboardFunc) { + event.preventDefault(); + GLUT.saveModifiers(event); + getWasmTableEntry(GLUT.keyboardFunc)(key, Browser.mouseX, Browser.mouseY); + } } - canvas.width = width; - canvas.height = height; - } else { - canvas = Module['canvas']; } - - var webGLContextAttributes = { - antialias: ((SDL.glAttributes[13 /*SDL_GL_MULTISAMPLEBUFFERS*/] != 0) && (SDL.glAttributes[14 /*SDL_GL_MULTISAMPLESAMPLES*/] > 1)), - depth: (SDL.glAttributes[6 /*SDL_GL_DEPTH_SIZE*/] > 0), - stencil: (SDL.glAttributes[7 /*SDL_GL_STENCIL_SIZE*/] > 0), - alpha: (SDL.glAttributes[3 /*SDL_GL_ALPHA_SIZE*/] > 0) - }; - - var ctx = Browser.createContext(canvas, is_SDL_OPENGL, usePageCanvas, webGLContextAttributes); - - SDL.surfaces[surf] = { - width: width, - height: height, - canvas: canvas, - ctx: ctx, - surf: surf, - buffer: buffer, - pixelFormat: pixelFormat, - alpha: 255, - flags: flags, - locked: 0, - usePageCanvas: usePageCanvas, - source: source, - - isFlagSet: function(flag) { - return flags & flag; + }, + onKeyup:(event) => { + if (GLUT.specialUpFunc || GLUT.keyboardUpFunc) { + var key = GLUT.getSpecialKey(event['keyCode']); + if (key !== null) { + if (GLUT.specialUpFunc) { + event.preventDefault (); + GLUT.saveModifiers(event); + getWasmTableEntry(GLUT.specialUpFunc)(key, Browser.mouseX, Browser.mouseY); + } + } else { + key = GLUT.getASCIIKey(event); + if (key !== null && GLUT.keyboardUpFunc) { + event.preventDefault (); + GLUT.saveModifiers(event); + getWasmTableEntry(GLUT.keyboardUpFunc)(key, Browser.mouseX, Browser.mouseY); + } } - }; - - return surf; - },copyIndexedColorData:function(surfData, rX, rY, rW, rH) { - // HWPALETTE works with palette - // setted by SDL_SetColors - if (!surfData.colors) { + } + }, + touchHandler:(event) => { + if (event.target != Module['canvas']) { return; } - var fullWidth = Module['canvas'].width; - var fullHeight = Module['canvas'].height; + var touches = event.changedTouches, + main = touches[0], + type = ""; - var startX = rX || 0; - var startY = rY || 0; - var endX = (rW || (fullWidth - startX)) + startX; - var endY = (rH || (fullHeight - startY)) + startY; + switch (event.type) { + case "touchstart": type = "mousedown"; break; + case "touchmove": type = "mousemove"; break; + case "touchend": type = "mouseup"; break; + default: return; + } - var buffer = surfData.buffer; + var simulatedEvent = document.createEvent("MouseEvent"); + simulatedEvent.initMouseEvent(type, true, true, window, 1, + main.screenX, main.screenY, + main.clientX, main.clientY, false, + false, false, false, 0/*main*/, null); - if (!surfData.image.data32) { - surfData.image.data32 = new Uint32Array(surfData.image.data.buffer); - } - var data32 = surfData.image.data32; + main.target.dispatchEvent(simulatedEvent); + event.preventDefault(); + }, + onMouseButtonDown:(event) => { + Browser.calculateMouseEvent(event); - var colors32 = surfData.colors32; + GLUT.buttons |= (1 << event['button']); - for (var y = startY; y < endY; ++y) { - var base = y * fullWidth; - for (var x = startX; x < endX; ++x) { - data32[base + x] = colors32[HEAPU8[((buffer + base + x)>>0)]]; - } - } - },freeSurface:function(surf) { - var refcountPointer = surf + 56; - var refcount = HEAP32[((refcountPointer)>>2)]; - if (refcount > 1) { - HEAP32[((refcountPointer)>>2)] = refcount - 1; - return; + if (event.target == Module["canvas"] && GLUT.mouseFunc) { + try { + event.target.setCapture(); + } catch (e) {} + event.preventDefault(); + GLUT.saveModifiers(event); + getWasmTableEntry(GLUT.mouseFunc)(event['button'], 0/*GLUT_DOWN*/, Browser.mouseX, Browser.mouseY); } + }, + onMouseButtonUp:(event) => { + Browser.calculateMouseEvent(event); - var info = SDL.surfaces[surf]; - if (!info.usePageCanvas && info.canvas) SDL.canvasPool.push(info.canvas); - if (info.buffer) _free(info.buffer); - _free(info.pixelFormat); - _free(surf); - SDL.surfaces[surf] = null; + GLUT.buttons &= ~(1 << event['button']); - if (surf === SDL.screen) { - SDL.screen = null; - } - },blitSurface:function(src, srcrect, dst, dstrect, scale) { - var srcData = SDL.surfaces[src]; - var dstData = SDL.surfaces[dst]; - var sr, dr; - if (srcrect) { - sr = SDL.loadRect(srcrect); - } else { - sr = { x: 0, y: 0, w: srcData.width, h: srcData.height }; - } - if (dstrect) { - dr = SDL.loadRect(dstrect); - } else { - dr = { x: 0, y: 0, w: srcData.width, h: srcData.height }; + if (GLUT.mouseFunc) { + event.preventDefault(); + GLUT.saveModifiers(event); + getWasmTableEntry(GLUT.mouseFunc)(event['button'], 1/*GLUT_UP*/, Browser.mouseX, Browser.mouseY); } - if (dstData.clipRect) { - var widthScale = (!scale || sr.w === 0) ? 1 : sr.w / dr.w; - var heightScale = (!scale || sr.h === 0) ? 1 : sr.h / dr.h; + }, + onMouseWheel:(event) => { + Browser.calculateMouseEvent(event); - dr = SDL.intersectionOfRects(dstData.clipRect, dr); + // cross-browser wheel delta + var e = window.event || event; // old IE support + // Note the minus sign that flips browser wheel direction (positive direction scrolls page down) to native wheel direction (positive direction is mouse wheel up) + var delta = -Browser.getMouseWheelDelta(event); + delta = (delta == 0) ? 0 : (delta > 0 ? Math.max(delta, 1) : Math.min(delta, -1)); // Quantize to integer so that minimum scroll is at least +/- 1. - sr.w = dr.w * widthScale; - sr.h = dr.h * heightScale; + var button = 3; // wheel up + if (delta < 0) { + button = 4; // wheel down + } - if (dstrect) { - SDL.updateRect(dstrect, dr); - } + if (GLUT.mouseFunc) { + event.preventDefault(); + GLUT.saveModifiers(event); + getWasmTableEntry(GLUT.mouseFunc)(button, 0/*GLUT_DOWN*/, Browser.mouseX, Browser.mouseY); } - var blitw, blith; - if (scale) { - blitw = dr.w; blith = dr.h; + }, + onFullscreenEventChange:(event) => { + var width; + var height; + if (document["fullscreen"] || document["fullScreen"] || document["mozFullScreen"] || document["webkitIsFullScreen"]) { + width = screen["width"]; + height = screen["height"]; } else { - blitw = sr.w; blith = sr.h; - } - if (sr.w === 0 || sr.h === 0 || blitw === 0 || blith === 0) { - return 0; + width = GLUT.windowWidth; + height = GLUT.windowHeight; + // TODO set position + document.removeEventListener('fullscreenchange', GLUT.onFullscreenEventChange, true); + document.removeEventListener('mozfullscreenchange', GLUT.onFullscreenEventChange, true); + document.removeEventListener('webkitfullscreenchange', GLUT.onFullscreenEventChange, true); } - var oldAlpha = dstData.ctx.globalAlpha; - dstData.ctx.globalAlpha = srcData.alpha/255; - dstData.ctx.drawImage(srcData.canvas, sr.x, sr.y, sr.w, sr.h, dr.x, dr.y, blitw, blith); - dstData.ctx.globalAlpha = oldAlpha; - if (dst != SDL.screen) { - // XXX As in IMG_Load, for compatibility we write out |pixels| - warnOnce('WARNING: copying canvas data to memory for compatibility'); - _SDL_LockSurface(dst); - dstData.locked--; // The surface is not actually locked in this hack + Browser.setCanvasSize(width, height, true); // N.B. GLUT.reshapeFunc is also registered as a canvas resize callback. + // Just call it once here. + /* Can't call _glutReshapeWindow as that requests cancelling fullscreen. */ + if (GLUT.reshapeFunc) { + // out("GLUT.reshapeFunc (from FS): " + width + ", " + height); + getWasmTableEntry(GLUT.reshapeFunc)(width, height); } - return 0; - },downFingers:{},savedKeydown:null,receiveEvent:function(event) { - function unpressAllPressedKeys() { - // Un-press all pressed keys: TODO - for (var code in SDL.keyboardMap) { - SDL.events.push({ - type: 'keyup', - keyCode: SDL.keyboardMap[code] - }); - } - }; - switch (event.type) { - case 'touchstart': case 'touchmove': { - event.preventDefault(); + _glutPostRedisplay(); + }, + }; + Module['GLUT'] = GLUT; + + var _glutGetModifiers = () => GLUT.modifiers; + Module['_glutGetModifiers'] = _glutGetModifiers; + _glutGetModifiers.sig = 'i'; + - var touches = []; - // Clear out any touchstart events that we've already processed - if (event.type === 'touchstart') { - for (var i = 0; i < event.touches.length; i++) { - var touch = event.touches[i]; - if (SDL.downFingers[touch.identifier] != true) { - SDL.downFingers[touch.identifier] = true; - touches.push(touch); - } - } - } else { - touches = event.touches; - } + var _glutInit = (argcp, argv) => { + // Ignore arguments + GLUT.initTime = Date.now(); - var firstTouch = touches[0]; - if (firstTouch) { - if (event.type == 'touchstart') { - SDL.DOMButtons[0] = 1; - } - var mouseEventType; - switch (event.type) { - case 'touchstart': mouseEventType = 'mousedown'; break; - case 'touchmove': mouseEventType = 'mousemove'; break; - } - var mouseEvent = { - type: mouseEventType, - button: 0, - pageX: firstTouch.clientX, - pageY: firstTouch.clientY - }; - SDL.events.push(mouseEvent); - } + var isTouchDevice = 'ontouchstart' in document.documentElement; + if (isTouchDevice) { + // onMouseButtonDown, onMouseButtonUp and onMousemove handlers + // depend on Browser.mouseX / Browser.mouseY fields. Those fields + // don't get updated by touch events. So register a touchHandler + // function that translates the touch events to mouse events. - for (var i = 0; i < touches.length; i++) { - var touch = touches[i]; - SDL.events.push({ - type: event.type, - touch: touch - }); - }; - break; - } - case 'touchend': { - event.preventDefault(); + // GLUT doesn't support touch, mouse only, so from touch events we + // are only looking at single finger touches to emulate left click, + // so we can use workaround and convert all touch events in mouse + // events. See touchHandler. + window.addEventListener("touchmove", GLUT.touchHandler, true); + window.addEventListener("touchstart", GLUT.touchHandler, true); + window.addEventListener("touchend", GLUT.touchHandler, true); + } - // Remove the entry in the SDL.downFingers hash - // because the finger is no longer down. - for (var i = 0; i < event.changedTouches.length; i++) { - var touch = event.changedTouches[i]; - if (SDL.downFingers[touch.identifier] === true) { - delete SDL.downFingers[touch.identifier]; - } - } + window.addEventListener("keydown", GLUT.onKeydown, true); + window.addEventListener("keyup", GLUT.onKeyup, true); + window.addEventListener("mousemove", GLUT.onMousemove, true); + window.addEventListener("mousedown", GLUT.onMouseButtonDown, true); + window.addEventListener("mouseup", GLUT.onMouseButtonUp, true); + // IE9, Chrome, Safari, Opera + window.addEventListener("mousewheel", GLUT.onMouseWheel, true); + // Firefox + window.addEventListener("DOMMouseScroll", GLUT.onMouseWheel, true); - var mouseEvent = { - type: 'mouseup', - button: 0, - pageX: event.changedTouches[0].clientX, - pageY: event.changedTouches[0].clientY - }; - SDL.DOMButtons[0] = 0; - SDL.events.push(mouseEvent); + Browser.resizeListeners.push(function(width, height) { + if (GLUT.reshapeFunc) { + getWasmTableEntry(GLUT.reshapeFunc)(width, height); + } + }); - for (var i = 0; i < event.changedTouches.length; i++) { - var touch = event.changedTouches[i]; - SDL.events.push({ - type: 'touchend', - touch: touch - }); - }; - break; - } - case 'DOMMouseScroll': case 'mousewheel': case 'wheel': - var delta = -Browser.getMouseWheelDelta(event); // Flip the wheel direction to translate from browser wheel direction (+:down) to SDL direction (+:up) - delta = (delta == 0) ? 0 : (delta > 0 ? Math.max(delta, 1) : Math.min(delta, -1)); // Quantize to integer so that minimum scroll is at least +/- 1. + __ATEXIT__.push(function() { + if (isTouchDevice) { + window.removeEventListener("touchmove", GLUT.touchHandler, true); + window.removeEventListener("touchstart", GLUT.touchHandler, true); + window.removeEventListener("touchend", GLUT.touchHandler, true); + } - // Simulate old-style SDL events representing mouse wheel input as buttons - var button = delta > 0 ? 3 /*SDL_BUTTON_WHEELUP-1*/ : 4 /*SDL_BUTTON_WHEELDOWN-1*/; // Subtract one since JS->C marshalling is defined to add one back. - SDL.events.push({ type: 'mousedown', button: button, pageX: event.pageX, pageY: event.pageY }); - SDL.events.push({ type: 'mouseup', button: button, pageX: event.pageX, pageY: event.pageY }); + window.removeEventListener("keydown", GLUT.onKeydown, true); + window.removeEventListener("keyup", GLUT.onKeyup, true); + window.removeEventListener("mousemove", GLUT.onMousemove, true); + window.removeEventListener("mousedown", GLUT.onMouseButtonDown, true); + window.removeEventListener("mouseup", GLUT.onMouseButtonUp, true); + // IE9, Chrome, Safari, Opera + window.removeEventListener("mousewheel", GLUT.onMouseWheel, true); + // Firefox + window.removeEventListener("DOMMouseScroll", GLUT.onMouseWheel, true); - // Pass a delta motion event. - SDL.events.push({ type: 'wheel', deltaX: 0, deltaY: delta }); - event.preventDefault(); // If we don't prevent this, then 'wheel' event will be sent again by the browser as 'DOMMouseScroll' and we will receive this same event the second time. - break; - case 'mousemove': - if (SDL.DOMButtons[0] === 1) { - SDL.events.push({ - type: 'touchmove', - touch: { - identifier: 0, - deviceID: -1, - pageX: event.pageX, - pageY: event.pageY - } - }); - } - if (Browser.pointerLock) { - // workaround for firefox bug 750111 - if ('mozMovementX' in event) { - event['movementX'] = event['mozMovementX']; - event['movementY'] = event['mozMovementY']; - } - // workaround for Firefox bug 782777 - if (event['movementX'] == 0 && event['movementY'] == 0) { - // ignore a mousemove event if it doesn't contain any movement info - // (without pointer lock, we infer movement from pageX/pageY, so this check is unnecessary) - event.preventDefault(); - return; - } - } - // fall through - case 'keydown': case 'keyup': case 'keypress': case 'mousedown': case 'mouseup': - // If we preventDefault on keydown events, the subsequent keypress events - // won't fire. However, it's fine (and in some cases necessary) to - // preventDefault for keys that don't generate a character. Otherwise, - // preventDefault is the right thing to do in general. - if (event.type !== 'keydown' || (!SDL_unicode() && !SDL.textInput) || (event.keyCode === 8 /* backspace */ || event.keyCode === 9 /* tab */)) { - event.preventDefault(); - } + Module["canvas"].width = Module["canvas"].height = 1; + }); + }; + Module['_glutInit'] = _glutInit; + _glutInit.sig = 'vpp'; + + var _glutInitWindowSize = (width, height) => { + Browser.setCanvasSize( GLUT.initWindowWidth = width, + GLUT.initWindowHeight = height ); + }; + Module['_glutInitWindowSize'] = _glutInitWindowSize; + _glutInitWindowSize.sig = 'vii'; + + var _glutInitWindowPosition = (x, y) => {}; + Module['_glutInitWindowPosition'] = _glutInitWindowPosition; + _glutInitWindowPosition.sig = 'vii'; + + var _glutGet = (type) => { + switch (type) { + case 100: /* GLUT_WINDOW_X */ + return 0; /* TODO */ + case 101: /* GLUT_WINDOW_Y */ + return 0; /* TODO */ + case 102: /* GLUT_WINDOW_WIDTH */ + return Module['canvas'].width; + case 103: /* GLUT_WINDOW_HEIGHT */ + return Module['canvas'].height; + case 200: /* GLUT_SCREEN_WIDTH */ + return Module['canvas'].width; + case 201: /* GLUT_SCREEN_HEIGHT */ + return Module['canvas'].height; + case 500: /* GLUT_INIT_WINDOW_X */ + return 0; /* TODO */ + case 501: /* GLUT_INIT_WINDOW_Y */ + return 0; /* TODO */ + case 502: /* GLUT_INIT_WINDOW_WIDTH */ + return GLUT.initWindowWidth; + case 503: /* GLUT_INIT_WINDOW_HEIGHT */ + return GLUT.initWindowHeight; + case 700: /* GLUT_ELAPSED_TIME */ + var now = Date.now(); + return now - GLUT.initTime; + case 0x0069: /* GLUT_WINDOW_STENCIL_SIZE */ + return Module.ctx.getContextAttributes().stencil ? 8 : 0; + case 0x006A: /* GLUT_WINDOW_DEPTH_SIZE */ + return Module.ctx.getContextAttributes().depth ? 8 : 0; + case 0x006E: /* GLUT_WINDOW_ALPHA_SIZE */ + return Module.ctx.getContextAttributes().alpha ? 8 : 0; + case 0x0078: /* GLUT_WINDOW_NUM_SAMPLES */ + return Module.ctx.getContextAttributes().antialias ? 1 : 0; - if (event.type == 'mousedown') { - SDL.DOMButtons[event.button] = 1; - SDL.events.push({ - type: 'touchstart', - touch: { - identifier: 0, - deviceID: -1, - pageX: event.pageX, - pageY: event.pageY - } - }); - } else if (event.type == 'mouseup') { - // ignore extra ups, can happen if we leave the canvas while pressing down, then return, - // since we add a mouseup in that case - if (!SDL.DOMButtons[event.button]) { - return; - } + default: + throw "glutGet(" + type + ") not implemented yet"; + } + }; + Module['_glutGet'] = _glutGet; + _glutGet.sig = 'ii'; + - SDL.events.push({ - type: 'touchend', - touch: { - identifier: 0, - deviceID: -1, - pageX: event.pageX, - pageY: event.pageY - } - }); - SDL.DOMButtons[event.button] = 0; - } - // We can only request fullscreen as the result of user input. - // Due to this limitation, we toggle a boolean on keydown which - // SDL_WM_ToggleFullScreen will check and subsequently set another - // flag indicating for us to request fullscreen on the following - // keyup. This isn't perfect, but it enables SDL_WM_ToggleFullScreen - // to work as the result of a keypress (which is an extremely - // common use case). - if (event.type === 'keydown' || event.type === 'mousedown') { - SDL.canRequestFullscreen = true; - } else if (event.type === 'keyup' || event.type === 'mouseup') { - if (SDL.isRequestingFullscreen) { - Module['requestFullscreen'](/*lockPointer=*/true, /*resizeCanvas=*/true); - SDL.isRequestingFullscreen = false; - } - SDL.canRequestFullscreen = false; - } + var _glutIdleFunc = (func) => { + function callback() { + if (GLUT.idleFunc) { + getWasmTableEntry(GLUT.idleFunc)(); + safeSetTimeout(callback, 4); // HTML spec specifies a 4ms minimum delay on the main thread; workers might get more, but we standardize here + } + } + if (!GLUT.idleFunc) { + safeSetTimeout(callback, 0); + } + GLUT.idleFunc = func; + }; + Module['_glutIdleFunc'] = _glutIdleFunc; + _glutIdleFunc.sig = 'vp'; + - // SDL expects a unicode character to be passed to its keydown events. - // Unfortunately, the browser APIs only provide a charCode property on - // keypress events, so we must backfill in keydown events with their - // subsequent keypress event's charCode. - if (event.type === 'keypress' && SDL.savedKeydown) { - // charCode is read-only - SDL.savedKeydown.keypressCharCode = event.charCode; - SDL.savedKeydown = null; - } else if (event.type === 'keydown') { - SDL.savedKeydown = event; - } - // Don't push keypress events unless SDL_StartTextInput has been called. - if (event.type !== 'keypress' || SDL.textInput) { - SDL.events.push(event); - } - break; - case 'mouseout': - // Un-press all pressed mouse buttons, because we might miss the release outside of the canvas - for (var i = 0; i < 3; i++) { - if (SDL.DOMButtons[i]) { - SDL.events.push({ - type: 'mouseup', - button: i, - pageX: event.pageX, - pageY: event.pageY - }); - SDL.DOMButtons[i] = 0; - } - } - event.preventDefault(); - break; - case 'focus': - SDL.events.push(event); - event.preventDefault(); - break; - case 'blur': - SDL.events.push(event); - unpressAllPressedKeys(); - event.preventDefault(); - break; - case 'visibilitychange': - SDL.events.push({ - type: 'visibilitychange', - visible: !document.hidden - }); - unpressAllPressedKeys(); - event.preventDefault(); - break; - case 'unload': - if (Browser.mainLoop.runner) { - SDL.events.push(event); - // Force-run a main event loop, since otherwise this event will never be caught! - Browser.mainLoop.runner(); - } - return; - case 'resize': - SDL.events.push(event); - // manually triggered resize event doesn't have a preventDefault member - if (event.preventDefault) { - event.preventDefault(); - } - break; - } - if (SDL.events.length >= 10000) { - err('SDL event queue full, dropping events'); - SDL.events = SDL.events.slice(0, 10000); - } - // If we have a handler installed, this will push the events to the app - // instead of the app polling for them. - SDL.flushEventsToHandler(); - return; - },lookupKeyCodeForEvent:function(event) { - var code = event.keyCode; - if (code >= 65 && code <= 90) { - code += 32; // make lowercase for SDL - } else { - code = SDL.keyCodes[event.keyCode] || event.keyCode; - // If this is one of the modifier keys (224 | 1<<10 - 227 | 1<<10), and the event specifies that it is - // a right key, add 4 to get the right key SDL key code. - if (event.location === 2 /*KeyboardEvent.DOM_KEY_LOCATION_RIGHT*/ && code >= (224 | 1<<10) && code <= (227 | 1<<10)) { - code += 4; - } - } - return code; - },handleEvent:function(event) { - if (event.handled) return; - event.handled = true; - - switch (event.type) { - case 'touchstart': case 'touchend': case 'touchmove': { - Browser.calculateMouseEvent(event); - break; - } - case 'keydown': case 'keyup': { - var down = event.type === 'keydown'; - var code = SDL.lookupKeyCodeForEvent(event); - // Assigning a boolean to HEAP8, that's alright but Closure would like to warn about it. - // TODO(https://github.com/emscripten-core/emscripten/issues/16311): - // This is kind of ugly hack. Perhaps we can find a better way? - /** @suppress{checkTypes} */ - HEAP8[(((SDL.keyboardState)+(code))>>0)] = down; - // TODO: lmeta, rmeta, numlock, capslock, KMOD_MODE, KMOD_RESERVED - SDL.modState = (HEAP8[(((SDL.keyboardState)+(1248))>>0)] ? 0x0040 : 0) | // KMOD_LCTRL - (HEAP8[(((SDL.keyboardState)+(1249))>>0)] ? 0x0001 : 0) | // KMOD_LSHIFT - (HEAP8[(((SDL.keyboardState)+(1250))>>0)] ? 0x0100 : 0) | // KMOD_LALT - (HEAP8[(((SDL.keyboardState)+(1252))>>0)] ? 0x0080 : 0) | // KMOD_RCTRL - (HEAP8[(((SDL.keyboardState)+(1253))>>0)] ? 0x0002 : 0) | // KMOD_RSHIFT - (HEAP8[(((SDL.keyboardState)+(1254))>>0)] ? 0x0200 : 0); // KMOD_RALT - if (down) { - SDL.keyboardMap[code] = event.keyCode; // save the DOM input, which we can use to unpress it during blur - } else { - delete SDL.keyboardMap[code]; - } - - break; - } - case 'mousedown': case 'mouseup': - if (event.type == 'mousedown') { - // SDL_BUTTON(x) is defined as (1 << ((x)-1)). SDL buttons are 1-3, - // and DOM buttons are 0-2, so this means that the below formula is - // correct. - SDL.buttonState |= 1 << event.button; - } else if (event.type == 'mouseup') { - SDL.buttonState &= ~(1 << event.button); - } - // fall through - case 'mousemove': { - Browser.calculateMouseEvent(event); - break; - } - } - },flushEventsToHandler:function() { - if (!SDL.eventHandler) return; - - while (SDL.pollEvent(SDL.eventHandlerTemp)) { - getWasmTableEntry(SDL.eventHandler)(SDL.eventHandlerContext, SDL.eventHandlerTemp); - } - },pollEvent:function(ptr) { - if (SDL.initFlags & 0x200 && SDL.joystickEventState) { - // If SDL_INIT_JOYSTICK was supplied AND the joystick system is configured - // to automatically query for events, query for joystick events. - SDL.queryJoysticks(); - } - if (ptr) { - while (SDL.events.length > 0) { - if (SDL.makeCEvent(SDL.events.shift(), ptr) !== false) return 1; - } - return 0; - } - // XXX: somewhat risky in that we do not check if the event is real or not (makeCEvent returns false) if no pointer supplied - return SDL.events.length > 0; - },makeCEvent:function(event, ptr) { - if (typeof event == 'number') { - // This is a pointer to a copy of a native C event that was SDL_PushEvent'ed - _memcpy(ptr, event, 28); - _free(event); // the copy is no longer needed - return; - } - - SDL.handleEvent(event); - - switch (event.type) { - case 'keydown': case 'keyup': { - var down = event.type === 'keydown'; - //out('Received key event: ' + event.keyCode); - var key = SDL.lookupKeyCodeForEvent(event); - var scan; - if (key >= 1024) { - scan = key - 1024; - } else { - scan = SDL.scanCodes[key] || key; - } - - HEAP32[((ptr)>>2)] = SDL.DOMEventToSDLEvent[event.type]; - HEAP8[(((ptr)+(8))>>0)] = down ? 1 : 0; - HEAP8[(((ptr)+(9))>>0)] = 0; // TODO - HEAP32[(((ptr)+(12))>>2)] = scan; - HEAP32[(((ptr)+(16))>>2)] = key; - HEAP16[(((ptr)+(20))>>1)] = SDL.modState; - // some non-character keys (e.g. backspace and tab) won't have keypressCharCode set, fill in with the keyCode. - HEAP32[(((ptr)+(24))>>2)] = event.keypressCharCode || key; - - break; - } - case 'keypress': { - HEAP32[((ptr)>>2)] = SDL.DOMEventToSDLEvent[event.type]; - // Not filling in windowID for now - var cStr = intArrayFromString(String.fromCharCode(event.charCode)); - for (var i = 0; i < cStr.length; ++i) { - HEAP8[(((ptr)+(8 + i))>>0)] = cStr[i]; - } - break; - } - case 'mousedown': case 'mouseup': case 'mousemove': { - if (event.type != 'mousemove') { - var down = event.type === 'mousedown'; - HEAP32[((ptr)>>2)] = SDL.DOMEventToSDLEvent[event.type]; - HEAP32[(((ptr)+(4))>>2)] = 0; - HEAP32[(((ptr)+(8))>>2)] = 0; - HEAP32[(((ptr)+(12))>>2)] = 0; - HEAP8[(((ptr)+(16))>>0)] = event.button+1; // DOM buttons are 0-2, SDL 1-3 - HEAP8[(((ptr)+(17))>>0)] = down ? 1 : 0; - HEAP32[(((ptr)+(20))>>2)] = Browser.mouseX; - HEAP32[(((ptr)+(24))>>2)] = Browser.mouseY; - } else { - HEAP32[((ptr)>>2)] = SDL.DOMEventToSDLEvent[event.type]; - HEAP32[(((ptr)+(4))>>2)] = 0; - HEAP32[(((ptr)+(8))>>2)] = 0; - HEAP32[(((ptr)+(12))>>2)] = 0; - HEAP32[(((ptr)+(16))>>2)] = SDL.buttonState; - HEAP32[(((ptr)+(20))>>2)] = Browser.mouseX; - HEAP32[(((ptr)+(24))>>2)] = Browser.mouseY; - HEAP32[(((ptr)+(28))>>2)] = Browser.mouseMovementX; - HEAP32[(((ptr)+(32))>>2)] = Browser.mouseMovementY; - } - break; - } - case 'wheel': { - HEAP32[((ptr)>>2)] = SDL.DOMEventToSDLEvent[event.type]; - HEAP32[(((ptr)+(16))>>2)] = event.deltaX; - HEAP32[(((ptr)+(20))>>2)] = event.deltaY; - break; - } - case 'touchstart': case 'touchend': case 'touchmove': { - var touch = event.touch; - if (!Browser.touches[touch.identifier]) break; - var w = Module['canvas'].width; - var h = Module['canvas'].height; - var x = Browser.touches[touch.identifier].x / w; - var y = Browser.touches[touch.identifier].y / h; - var lx = Browser.lastTouches[touch.identifier].x / w; - var ly = Browser.lastTouches[touch.identifier].y / h; - var dx = x - lx; - var dy = y - ly; - if (touch['deviceID'] === undefined) touch.deviceID = SDL.TOUCH_DEFAULT_ID; - if (dx === 0 && dy === 0 && event.type === 'touchmove') return false; // don't send these if nothing happened - HEAP32[((ptr)>>2)] = SDL.DOMEventToSDLEvent[event.type]; - HEAP32[(((ptr)+(4))>>2)] = _SDL_GetTicks(); - (tempI64 = [touch.deviceID>>>0,(tempDouble=touch.deviceID,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((ptr)+(8))>>2)] = tempI64[0],HEAP32[(((ptr)+(12))>>2)] = tempI64[1]); - (tempI64 = [touch.identifier>>>0,(tempDouble=touch.identifier,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((ptr)+(16))>>2)] = tempI64[0],HEAP32[(((ptr)+(20))>>2)] = tempI64[1]); - HEAPF32[(((ptr)+(24))>>2)] = x; - HEAPF32[(((ptr)+(28))>>2)] = y; - HEAPF32[(((ptr)+(32))>>2)] = dx; - HEAPF32[(((ptr)+(36))>>2)] = dy; - if (touch.force !== undefined) { - HEAPF32[(((ptr)+(40))>>2)] = touch.force; - } else { // No pressure data, send a digital 0/1 pressure. - HEAPF32[(((ptr)+(40))>>2)] = event.type == "touchend" ? 0 : 1; - } - break; - } - case 'unload': { - HEAP32[((ptr)>>2)] = SDL.DOMEventToSDLEvent[event.type]; - break; - } - case 'resize': { - HEAP32[((ptr)>>2)] = SDL.DOMEventToSDLEvent[event.type]; - HEAP32[(((ptr)+(4))>>2)] = event.w; - HEAP32[(((ptr)+(8))>>2)] = event.h; - break; - } - case 'joystick_button_up': case 'joystick_button_down': { - var state = event.type === 'joystick_button_up' ? 0 : 1; - HEAP32[((ptr)>>2)] = SDL.DOMEventToSDLEvent[event.type]; - HEAP8[(((ptr)+(4))>>0)] = event.index; - HEAP8[(((ptr)+(5))>>0)] = event.button; - HEAP8[(((ptr)+(6))>>0)] = state; - break; - } - case 'joystick_axis_motion': { - HEAP32[((ptr)>>2)] = SDL.DOMEventToSDLEvent[event.type]; - HEAP8[(((ptr)+(4))>>0)] = event.index; - HEAP8[(((ptr)+(5))>>0)] = event.axis; - HEAP32[(((ptr)+(8))>>2)] = SDL.joystickAxisValueConversion(event.value); - break; - } - case 'focus': { - var SDL_WINDOWEVENT_FOCUS_GAINED = 12 /* SDL_WINDOWEVENT_FOCUS_GAINED */; - HEAP32[((ptr)>>2)] = SDL.DOMEventToSDLEvent[event.type]; - HEAP32[(((ptr)+(4))>>2)] = 0; - HEAP8[(((ptr)+(8))>>0)] = SDL_WINDOWEVENT_FOCUS_GAINED; - break; - } - case 'blur': { - var SDL_WINDOWEVENT_FOCUS_LOST = 13 /* SDL_WINDOWEVENT_FOCUS_LOST */; - HEAP32[((ptr)>>2)] = SDL.DOMEventToSDLEvent[event.type]; - HEAP32[(((ptr)+(4))>>2)] = 0; - HEAP8[(((ptr)+(8))>>0)] = SDL_WINDOWEVENT_FOCUS_LOST; - break; - } - case 'visibilitychange': { - var SDL_WINDOWEVENT_SHOWN = 1 /* SDL_WINDOWEVENT_SHOWN */; - var SDL_WINDOWEVENT_HIDDEN = 2 /* SDL_WINDOWEVENT_HIDDEN */; - var visibilityEventID = event.visible ? SDL_WINDOWEVENT_SHOWN : SDL_WINDOWEVENT_HIDDEN; - HEAP32[((ptr)>>2)] = SDL.DOMEventToSDLEvent[event.type]; - HEAP32[(((ptr)+(4))>>2)] = 0; - HEAP8[(((ptr)+(8))>>0)] = visibilityEventID; - break; - } - default: throw 'Unhandled SDL event: ' + event.type; - } - },makeFontString:function(height, fontName) { - if (fontName.charAt(0) != "'" && fontName.charAt(0) != '"') { - // https://developer.mozilla.org/ru/docs/Web/CSS/font-family - // Font family names containing whitespace should be quoted. - // BTW, quote all font names is easier than searching spaces - fontName = '"' + fontName + '"'; - } - return height + 'px ' + fontName + ', serif'; - },estimateTextWidth:function(fontData, text) { - var h = fontData.size; - var fontString = SDL.makeFontString(h, fontData.name); - var tempCtx = SDL_ttfContext(); - assert(tempCtx, 'TTF_Init must have been called'); - tempCtx.font = fontString; - var ret = tempCtx.measureText(text).width | 0; - return ret; - },allocateChannels:function(num) { // called from Mix_AllocateChannels and init - if (SDL.numChannels && SDL.numChannels >= num && num != 0) return; - SDL.numChannels = num; - SDL.channels = []; - for (var i = 0; i < num; i++) { - SDL.channels[i] = { - audio: null, - volume: 1.0 - }; - } - },setGetVolume:function(info, volume) { - if (!info) return 0; - var ret = info.volume * 128; // MIX_MAX_VOLUME - if (volume != -1) { - info.volume = Math.min(Math.max(volume, 0), 128) / 128; - if (info.audio) { - try { - info.audio.volume = info.volume; // For