Repository: gpujs/gpu.js Branch: develop Commit: f66631c4fc1b Files: 432 Total size: 2.9 MB Directory structure: gitextract_g_im5cfv/ ├── .gitignore ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE.md ├── LICENSE ├── README.md ├── dist/ │ ├── gpu-browser-core.js │ └── gpu-browser.js ├── examples/ │ ├── advanced-typescript.ts │ ├── cat-image/ │ │ └── index.html │ ├── fluid.html │ ├── internal-variable-precision.html │ ├── json-saving.js │ ├── mandelbrot-set.html │ ├── mandelbulb.html │ ├── parallel-raytracer.html │ ├── random.html │ ├── raster-globe/ │ │ └── index.html │ ├── raytracer.html │ ├── simple-javascript.js │ ├── simple-typescript.ts │ ├── slow-fade.html │ └── video/ │ └── index.html ├── gulpfile.js ├── package.json ├── src/ │ ├── alias.js │ ├── backend/ │ │ ├── cpu/ │ │ │ ├── function-node.js │ │ │ ├── kernel-string.js │ │ │ └── kernel.js │ │ ├── function-builder.js │ │ ├── function-node.js │ │ ├── function-tracer.js │ │ ├── gl/ │ │ │ ├── kernel-string.js │ │ │ ├── kernel.js │ │ │ └── texture/ │ │ │ ├── array-2-float-2d.js │ │ │ ├── array-2-float-3d.js │ │ │ ├── array-2-float.js │ │ │ ├── array-3-float-2d.js │ │ │ ├── array-3-float-3d.js │ │ │ ├── array-3-float.js │ │ │ ├── array-4-float-2d.js │ │ │ ├── array-4-float-3d.js │ │ │ ├── array-4-float.js │ │ │ ├── float-2d.js │ │ │ ├── float-3d.js │ │ │ ├── float.js │ │ │ ├── graphical.js │ │ │ ├── index.js │ │ │ ├── memory-optimized-2d.js │ │ │ ├── memory-optimized-3d.js │ │ │ ├── memory-optimized.js │ │ │ ├── unsigned-2d.js │ │ │ ├── unsigned-3d.js │ │ │ └── unsigned.js │ │ ├── headless-gl/ │ │ │ └── kernel.js │ │ ├── kernel-value.js │ │ ├── kernel.js │ │ ├── web-gl/ │ │ │ ├── fragment-shader.js │ │ │ ├── function-node.js │ │ │ ├── kernel-value/ │ │ │ │ ├── array.js │ │ │ │ ├── array2.js │ │ │ │ ├── array3.js │ │ │ │ ├── array4.js │ │ │ │ ├── boolean.js │ │ │ │ ├── dynamic-html-image.js │ │ │ │ ├── dynamic-html-video.js │ │ │ │ ├── dynamic-memory-optimized-number-texture.js │ │ │ │ ├── dynamic-number-texture.js │ │ │ │ ├── dynamic-single-array.js │ │ │ │ ├── dynamic-single-array1d-i.js │ │ │ │ ├── dynamic-single-array2d-i.js │ │ │ │ ├── dynamic-single-array3d-i.js │ │ │ │ ├── dynamic-single-input.js │ │ │ │ ├── dynamic-unsigned-array.js │ │ │ │ ├── dynamic-unsigned-input.js │ │ │ │ ├── float.js │ │ │ │ ├── html-image.js │ │ │ │ ├── html-video.js │ │ │ │ ├── index.js │ │ │ │ ├── integer.js │ │ │ │ ├── memory-optimized-number-texture.js │ │ │ │ ├── number-texture.js │ │ │ │ ├── single-array.js │ │ │ │ ├── single-array1d-i.js │ │ │ │ ├── single-array2d-i.js │ │ │ │ ├── single-array3d-i.js │ │ │ │ ├── single-input.js │ │ │ │ ├── unsigned-array.js │ │ │ │ └── unsigned-input.js │ │ │ ├── kernel-value-maps.js │ │ │ ├── kernel.js │ │ │ └── vertex-shader.js │ │ └── web-gl2/ │ │ ├── fragment-shader.js │ │ ├── function-node.js │ │ ├── kernel-value/ │ │ │ ├── array2.js │ │ │ ├── array3.js │ │ │ ├── array4.js │ │ │ ├── boolean.js │ │ │ ├── dynamic-html-image-array.js │ │ │ ├── dynamic-html-image.js │ │ │ ├── dynamic-html-video.js │ │ │ ├── dynamic-memory-optimized-number-texture.js │ │ │ ├── dynamic-number-texture.js │ │ │ ├── dynamic-single-array.js │ │ │ ├── dynamic-single-array1d-i.js │ │ │ ├── dynamic-single-array2d-i.js │ │ │ ├── dynamic-single-array3d-i.js │ │ │ ├── dynamic-single-input.js │ │ │ ├── dynamic-unsigned-array.js │ │ │ ├── dynamic-unsigned-input.js │ │ │ ├── float.js │ │ │ ├── html-image-array.js │ │ │ ├── html-image.js │ │ │ ├── html-video.js │ │ │ ├── integer.js │ │ │ ├── memory-optimized-number-texture.js │ │ │ ├── number-texture.js │ │ │ ├── single-array.js │ │ │ ├── single-array1d-i.js │ │ │ ├── single-array2d-i.js │ │ │ ├── single-array3d-i.js │ │ │ ├── single-input.js │ │ │ ├── unsigned-array.js │ │ │ └── unsigned-input.js │ │ ├── kernel-value-maps.js │ │ ├── kernel.js │ │ └── vertex-shader.js │ ├── browser-header.txt │ ├── browser.js │ ├── gpu.js │ ├── index.d.ts │ ├── index.js │ ├── input.js │ ├── kernel-run-shortcut.js │ ├── plugins/ │ │ ├── math-random-triangle-noise.js │ │ └── math-random-uniformly-distributed.js │ ├── texture.js │ └── utils.js └── test/ ├── all-template.html ├── all.html ├── benchmark-faster.js ├── benchmark.js ├── browser-test-utils.js ├── features/ │ ├── add-custom-function.js │ ├── add-custom-native-function.js │ ├── add-typed-functions.js │ ├── argument-array-types.js │ ├── argument-array1d-types.js │ ├── argument-array2d-types.js │ ├── argument-array3d-types.js │ ├── arithmetic-operators.js │ ├── assignment-operators.js │ ├── basic-math.js │ ├── bitwise-operators.js │ ├── boolean-from-expression.js │ ├── canvas.js │ ├── clear-textures.js │ ├── clone-textures.js │ ├── combine-kernels.js │ ├── constants-array.js │ ├── constants-bool.js │ ├── constants-canvas.js │ ├── constants-float.js │ ├── constants-image-array.js │ ├── constants-image.js │ ├── constants-integer.js │ ├── constants-texture.js │ ├── cpu-with-textures.js │ ├── create-kernel-map.js │ ├── demo.js │ ├── destroy.js │ ├── destructured-assignment.js │ ├── dev-mode.js │ ├── dynamic-arguments.js │ ├── dynamic-output.js │ ├── function-return.js │ ├── get-canvas.js │ ├── get-pixels.js │ ├── if-else.js │ ├── image-array.js │ ├── image.js │ ├── infinity.js │ ├── inject-native.js │ ├── input.js │ ├── internally-defined-matrices.js │ ├── json.js │ ├── legacy-encoder.js │ ├── loops.js │ ├── math-object.js │ ├── nested-function.js │ ├── offscreen-canvas.js │ ├── optimize-float-memory.js │ ├── output.js │ ├── promise-api.js │ ├── raw-output.js │ ├── read-color-texture.js │ ├── read-from-texture.js │ ├── read-image-bitmap.js │ ├── read-image-data.js │ ├── read-offscreen-canvas.js │ ├── return-arrays.js │ ├── single-precision-textures.js │ ├── single-precision.js │ ├── switches.js │ ├── tactic.js │ ├── ternary.js │ ├── to-string/ │ │ ├── as-file.js │ │ └── precision/ │ │ ├── single/ │ │ │ ├── arguments/ │ │ │ │ ├── array.js │ │ │ │ ├── array2.js │ │ │ │ ├── array2d.js │ │ │ │ ├── array2d2.js │ │ │ │ ├── array2d3.js │ │ │ │ ├── array3.js │ │ │ │ ├── array3d.js │ │ │ │ ├── array4.js │ │ │ │ ├── boolean.js │ │ │ │ ├── float.js │ │ │ │ ├── html-canvas.js │ │ │ │ ├── html-image-array.js │ │ │ │ ├── html-image.js │ │ │ │ ├── html-video.js │ │ │ │ ├── input.js │ │ │ │ ├── integer.js │ │ │ │ ├── memory-optimized-number-texture.js │ │ │ │ └── number-texture.js │ │ │ ├── constants/ │ │ │ │ ├── array.js │ │ │ │ ├── array2.js │ │ │ │ ├── array2d.js │ │ │ │ ├── array3.js │ │ │ │ ├── array3d.js │ │ │ │ ├── array4.js │ │ │ │ ├── boolean.js │ │ │ │ ├── float.js │ │ │ │ ├── html-canvas.js │ │ │ │ ├── html-image-array.js │ │ │ │ ├── html-image.js │ │ │ │ ├── input.js │ │ │ │ ├── integer.js │ │ │ │ ├── memory-optimized-number-texture.js │ │ │ │ └── number-texture.js │ │ │ ├── graphical.js │ │ │ ├── kernel-map/ │ │ │ │ ├── array/ │ │ │ │ │ ├── array.js │ │ │ │ │ ├── array2d.js │ │ │ │ │ ├── array3d.js │ │ │ │ │ ├── memory-optimized-number-texture.js │ │ │ │ │ └── number-texture.js │ │ │ │ └── object/ │ │ │ │ ├── array.js │ │ │ │ ├── array2d.js │ │ │ │ ├── array3d.js │ │ │ │ ├── memory-optimized-number-texture.js │ │ │ │ └── number-texture.js │ │ │ └── returns/ │ │ │ ├── array.js │ │ │ ├── array2d.js │ │ │ ├── array3d.js │ │ │ └── texture.js │ │ └── unsigned/ │ │ ├── arguments/ │ │ │ ├── array.js │ │ │ ├── array2.js │ │ │ ├── array2d.js │ │ │ ├── array3.js │ │ │ ├── array3d.js │ │ │ ├── array4.js │ │ │ ├── boolean.js │ │ │ ├── float.js │ │ │ ├── html-canvas.js │ │ │ ├── html-image-array.js │ │ │ ├── html-image.js │ │ │ ├── html-video.js │ │ │ ├── input.js │ │ │ ├── integer.js │ │ │ ├── memory-optimized-number-texture.js │ │ │ └── number-texture.js │ │ ├── constants/ │ │ │ ├── array.js │ │ │ ├── array2.js │ │ │ ├── array2d.js │ │ │ ├── array3.js │ │ │ ├── array3d.js │ │ │ ├── array4.js │ │ │ ├── boolean.js │ │ │ ├── float.js │ │ │ ├── html-canvas.js │ │ │ ├── html-image-array.js │ │ │ ├── html-image.js │ │ │ ├── input.js │ │ │ ├── integer.js │ │ │ ├── memory-optimized-number-texture.js │ │ │ └── number-texture.js │ │ ├── graphical.js │ │ ├── kernel-map/ │ │ │ ├── array/ │ │ │ │ ├── array.js │ │ │ │ ├── array2d.js │ │ │ │ ├── array3d.js │ │ │ │ ├── memory-optimized-number-texture.js │ │ │ │ └── number-texture.js │ │ │ └── object/ │ │ │ ├── array.js │ │ │ ├── array2d.js │ │ │ ├── array3d.js │ │ │ ├── memory-optimized-number-texture.js │ │ │ └── number-texture.js │ │ └── returns/ │ │ ├── array.js │ │ ├── array2d.js │ │ ├── array3d.js │ │ └── texture.js │ ├── type-management.js │ ├── unsigned-precision-textures.js │ └── video.js ├── index.js ├── internal/ │ ├── argument-texture-switching.js │ ├── backend/ │ │ ├── cpu-kernel.js │ │ ├── function-node/ │ │ │ ├── isSafe.js │ │ │ └── isSafeDependencies.js │ │ ├── gl-kernel.js │ │ ├── headless-gl/ │ │ │ └── kernel/ │ │ │ └── index.js │ │ ├── web-gl/ │ │ │ ├── function-node/ │ │ │ │ ├── astBinaryExpression.js │ │ │ │ ├── astCallExpression.js │ │ │ │ ├── astForStatement.js │ │ │ │ ├── astVariableDeclaration.js │ │ │ │ ├── contexts.js │ │ │ │ ├── firstAvailableTypeFromAst.js │ │ │ │ ├── getVariableSignature.js │ │ │ │ └── getVariableType.js │ │ │ ├── kernel/ │ │ │ │ ├── index.js │ │ │ │ ├── setupArguments.js │ │ │ │ └── setupConstants.js │ │ │ └── kernel-value/ │ │ │ ├── dynamic-html-image.js │ │ │ ├── dynamic-memory-optimized-number-texture.js │ │ │ ├── dynamic-number-texture.js │ │ │ ├── dynamic-single-array.js │ │ │ ├── dynamic-single-array1d-i.js │ │ │ ├── dynamic-single-array2d-i.js │ │ │ ├── dynamic-single-array3d-i.js │ │ │ ├── dynamic-single-input.js │ │ │ ├── dynamic-unsigned-array.js │ │ │ ├── dynamic-unsigned-input.js │ │ │ ├── html-image.js │ │ │ ├── memory-optimized-number-texture.js │ │ │ ├── number-texture.js │ │ │ ├── single-array.js │ │ │ ├── single-array1d-i.js │ │ │ ├── single-array2d-i.js │ │ │ ├── single-array3d-i.js │ │ │ ├── single-input.js │ │ │ ├── unsigned-array.js │ │ │ └── unsigned-input.js │ │ └── web-gl2/ │ │ ├── kernel/ │ │ │ ├── index.js │ │ │ ├── setupArguments.js │ │ │ └── setupConstants.js │ │ └── kernel-value/ │ │ ├── dynamic-html-image-array.js │ │ ├── dynamic-single-array.js │ │ ├── dynamic-single-input.js │ │ ├── html-image-array.js │ │ └── single-input.js │ ├── boolean.js │ ├── casting.js │ ├── constants-texture-switching.js │ ├── constructor-features.js │ ├── context-inheritance.js │ ├── deep-types.js │ ├── deprecated.js │ ├── different-texture-cloning.js │ ├── function-builder.js │ ├── function-composition.js │ ├── function-node.js │ ├── function-return-type-detection.js │ ├── function-tracer.js │ ├── gpu-methods.js │ ├── implied-else.js │ ├── kernel-run-shortcut.js │ ├── kernel.js │ ├── loop-int.js │ ├── loop-max.js │ ├── math.random.js │ ├── matrix-multiply-precision.js │ ├── mixed-memory-optimize.js │ ├── modes.js │ ├── overloading.js │ ├── precision.js │ ├── recycling.js │ ├── texture-index.js │ ├── underscores.js │ └── utils.js ├── issues/ │ ├── 114-create-kernel-map-run-second-time.js │ ├── 116-multiple-kernels-run-again.js │ ├── 130-typed-array.js │ ├── 147-missing-constant.js │ ├── 152-for-vars.js │ ├── 159-3d.js │ ├── 174-webgl-context-warning.js │ ├── 195-read-from-texture2d.js │ ├── 207-same-function-reuse.js │ ├── 212-funky-function-support.js │ ├── 233-kernel-map-single-precision.js │ ├── 241-CPU-vs-GPU-maps-output-differently.js │ ├── 259-atan2.js │ ├── 263-to-string.js │ ├── 267-immutable-sub-kernels.js │ ├── 270-cache.js │ ├── 279-wrong-canvas-size.js │ ├── 300-nested-array-index.js │ ├── 31-nested-var-declare-test.js │ ├── 313-variable-lookup.js │ ├── 314-large-input-array-addressing.js │ ├── 335-missing-z-index-issue.js │ ├── 346-uint8array-converted.js │ ├── 349-division-by-factors-of-3.js │ ├── 357-modulus-issue.js │ ├── 359-addfunction-params-wrong.js │ ├── 378-only-first-iteration.js │ ├── 382-bad-constant.js │ ├── 390-thread-assignment.js │ ├── 396-combine-kernels-example.js │ ├── 399-double-definition.js │ ├── 401-cpu-canvas-check.js │ ├── 410-if-statement.js │ ├── 422-warnings.js │ ├── 470-modulus-wrong.js │ ├── 471-canvas-issue.js │ ├── 472-compilation-issue.js │ ├── 473-4-pixels.js │ ├── 487-dynamic-arguments.js │ ├── 493-strange-literal.js │ ├── 500-sticky-arrays.js │ ├── 519-sanitize-names.js │ ├── 553-permanent-flip.js │ ├── 556-minify-for-loop.js │ ├── 560-minification-madness.js │ ├── 564-boolean.js │ ├── 567-wrong-modulus.js │ ├── 585-inaccurate-lookups.js │ ├── 586-unable-to-resize.js │ ├── 608-rewritten-arrays.js │ ├── 91-create-kernel-map-array.js │ └── 96-param-names.js ├── jellyfish.webm └── test-utils.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Logs logs *.log npm-debug.log* # Runtime data pids *.pid *.seed # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage # node-waf configuration .lock-wscript # Dependency directory node_modules # Optional npm cache directory .npm # Optional REPL history .node_repl_history # intellij .idea #yarn yarn.lock # OSX .DS_Store .DS_Store ================================================ FILE: CONTRIBUTING.md ================================================ Thanks for taking the time to contribute to gpu.js. Follow these guidelines to make the process smoother: 1. One feature per pull request. Each PR should have one focus, and all the code changes should be supporting that one feature or bug fix. Using a [separate branch](https://guides.github.com/introduction/flow/index.html) for each feature should help you manage developing multiple features at once. 2. Follow the style of the file when it comes to syntax like curly braces and indents. 3. Add a test for the feature or fix, if possible. See the `test` directory for existing tests and README describing how to run these tests. ================================================ FILE: ISSUE_TEMPLATE.md ================================================ ![A GIF or MEME to give some spice of the internet](url) ## *What* is wrong? ## *Where* does it happen? ## *How* do we replicate the issue? ## *How* important is this (1-5)? ## Expected behavior (i.e. solution) ## Other Comments ================================================ FILE: LICENSE ================================================ The MIT License Copyright (c) 2019 gpu.js Team 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. ================================================ FILE: README.md ================================================ [Logo](http://gpu.rocks/) # GPU.js GPU.js is a JavaScript Acceleration library for GPGPU (General purpose computing on GPUs) in JavaScript for Web and Node. GPU.js automatically transpiles simple JavaScript functions into shader language and compiles them so they run on your GPU. In case a GPU is not available, the functions will still run in regular JavaScript. For some more quick concepts, see [Quick Concepts](https://github.com/gpujs/gpu.js/wiki/Quick-Concepts) on the wiki. [![Join the chat at https://gitter.im/gpujs/gpu.js](https://badges.gitter.im/gpujs/gpu.js.svg)](https://gitter.im/gpujs/gpu.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Slack](https://slack.bri.im/badge.svg)](https://slack.bri.im) # What is this sorcery? Creates a GPU accelerated kernel transpiled from a javascript function that computes a single element in the 512 x 512 matrix (2D array). The kernel functions are ran in tandem on the GPU often resulting in very fast computations! You can run a benchmark of this [here](http://gpu.rocks). Typically, it will run 1-15x faster depending on your hardware. Matrix multiplication (perform matrix multiplication on 2 matrices of size 512 x 512) written in GPU.js: ## Browser ```html ``` ## CDN ``` https://unpkg.com/gpu.js@latest/dist/gpu-browser.min.js https://cdn.jsdelivr.net/npm/gpu.js@latest/dist/gpu-browser.min.js ``` ## Node ```js const { GPU } = require('gpu.js'); const gpu = new GPU(); const multiplyMatrix = gpu.createKernel(function(a, b) { let sum = 0; for (let i = 0; i < 512; i++) { sum += a[this.thread.y][i] * b[i][this.thread.x]; } return sum; }).setOutput([512, 512]); const c = multiplyMatrix(a, b); ``` ## Typescript ```typescript import { GPU } from 'gpu.js'; const gpu = new GPU(); const multiplyMatrix = gpu.createKernel(function(a: number[][], b: number[][]) { let sum = 0; for (let i = 0; i < 512; i++) { sum += a[this.thread.y][i] * b[i][this.thread.x]; } return sum; }).setOutput([512, 512]); const c = multiplyMatrix(a, b) as number[][]; ``` [Click here](/examples) for more typescript examples. # Table of Contents Notice documentation is off? We do try our hardest, but if you find something, [please bring it to our attention](https://github.com/gpujs/gpu.js/issues), or _[become a contributor](#contributors)_! * [Demos](#demos) * [Installation](#installation) * [`GPU` Settings](#gpu-settings) * [`gpu.createKernel` Settings](#gpucreatekernel-settings) * [Declaring variables/functions within kernels](#declaring-variablesfunctions-within-kernels) * [Creating and Running Functions](#creating-and-running-functions) * [Debugging](#debugging) * [Accepting Input](#accepting-input) * [Graphical Output](#graphical-output) * [Combining Kernels](#combining-kernels) * [Create Kernel Map](#create-kernel-map) * [Adding Custom Functions](#adding-custom-functions) * [Adding Custom Functions Directly to Kernel](#adding-custom-functions-directly-to-kernel) * [Types](#types) * [Loops](#loops) * [Pipelining](#pipelining) * [Cloning Textures](#cloning-textures-new-in-v2) * [Cleanup pipeline texture memory](#cleanup-pipeline-texture-memory-new-in-v24) * [Offscreen Canvas](#offscreen-canvas) * [Cleanup](#cleanup) * [Flattened typed array support](#flattened-typed-array-support) * [Precompiled and Lighter Weight Kernels](#precompiled-and-lighter-weight-kernels) * [using JSON](#using-json) * [Exporting kernel](#exporting-kernel) * [Supported Math functions](#supported-math-functions) * [How to check what is supported](#how-to-check-what-is-supported) * [Typescript Typings](#typescript-typings) * [Destructured Assignments](#destructured-assignments-new-in-v2) * [Dealing With Transpilation](#dealing-with-transpilation) * [Full API reference](#full-api-reference) * [How possible in node](#how-possible-in-node) * [Testing](#testing) * [Building](#building) * [Contributors](#contributors) * [Contributing](#contributing) * [Terms Explained](#terms-explained) * [License](#license) ## Demos GPU.js in the wild, all around the net. Add yours here! * [Temperature interpolation using GPU.js](https://observablehq.com/@rveciana/temperature-interpolation-using-gpu-js) * [Julia Set Fractal using GPU.js](https://observablehq.com/@ukabuer/julia-set-fractal-using-gpu-js) * [Hello, gpu.js v2](https://observablehq.com/@fil/hello-gpu-js-v2) * [Basic gpu.js canvas example](https://observablehq.com/@rveciana/basic-gpu-js-canvas-example) * [Raster projection with GPU.js](https://observablehq.com/@fil/raster-projection-with-gpu-js) * [GPU.js Example: Slow Fade](https://observablehq.com/@robertleeplummerjr/gpu-js-example-slow-fade) * [GPU.JS CA Proof of Concept](https://observablehq.com/@alexlamb/gpu-js-ca-proof-of-concept) * [Image Convolution using GPU.js](https://observablehq.com/@ukabuer/image-convolution-using-gpu-js) * [Leaflet + gpu.js canvas](https://observablehq.com/@rveciana/leaflet-gpu-js-canvas) * [Image to GPU.js](https://observablehq.com/@fil/image-to-gpu) * [GPU Accelerated Heatmap using gpu.js](https://observablehq.com/@tracyhenry/gpu-accelerated-heatmap-using-gpu-js) * [Dijkstra’s algorithm in gpu.js](https://observablehq.com/@fil/dijkstras-algorithm-in-gpu-js) * [Voronoi with gpu.js](https://observablehq.com/@fil/voronoi-with-gpu-js) * [The gpu.js loop](https://observablehq.com/@fil/the-gpu-js-loop) * [GPU.js Example: Mandelbrot Set](https://observablehq.com/@robertleeplummerjr/gpu-js-example-mandelbrot-set) * [GPU.js Example: Mandelbulb](https://observablehq.com/@robertleeplummerjr/gpu-js-example-mandelbulb) * [Inverse of the distance with gpu.js](https://observablehq.com/@rveciana/inverse-of-the-distance-with-gpu-js) * [gpu.js laser detection v2](https://observablehq.com/@robertleeplummerjr/gpu-js-laser-detection-v2) * [GPU.js Canvas](https://observablehq.com/@hubgit/gpu-js-canvas) * [Video Convolution using GPU.js](https://observablehq.com/@robertleeplummerjr/video-convolution-using-gpu-js) * [GPU Rock Paper Scissors](https://observablehq.com/@alexlamb/gpu-rock-paper-scissors) * [Shaded relief with gpujs and d3js](https://observablehq.com/@rveciana/shaded-relief-with-gpujs-and-d3js/2) * [Caesar Cipher GPU.js Example](https://observablehq.com/@robertleeplummerjr/caesar-cipher-gpu-js-example) * [Matrix Multiplication GPU.js + Angular Example](https://ng-gpu.surge.sh/) * [Conway's game of life](https://observablehq.com/@brakdag/conway-game-of-life-gpu-js) ## Installation On Linux, ensure you have the correct header files installed: `sudo apt install mesa-common-dev libxi-dev` (adjust for your distribution) ### npm ```bash npm install gpu.js --save ``` ### yarn ```bash yarn add gpu.js ``` [npm package](https://www.npmjs.com/package/gpu.js) ### Node ```js const { GPU } = require('gpu.js'); const gpu = new GPU(); ``` ### Node Typescript **New in V2!** ```js import { GPU } from 'gpu.js'; const gpu = new GPU(); ``` ### Browser Download the latest version of GPU.js and include the files in your HTML page using the following tags: ```html ``` ## `GPU` Settings Settings are an object used to create an instance of `GPU`. Example: `new GPU(settings)` * `canvas`: `HTMLCanvasElement`. Optional. For sharing canvas. Example: use THREE.js and GPU.js on same canvas. * `context`: `WebGL2RenderingContext` or `WebGLRenderingContext`. For sharing rendering context. Example: use THREE.js and GPU.js on same rendering context. * `mode`: Defaults to 'gpu', other values generally for debugging: * 'dev' **New in V2!**: VERY IMPORTANT! Use this so you can breakpoint and debug your kernel! This wraps your javascript in loops but DOES NOT transpile your code, so debugging is much easier. * 'webgl': Use the `WebGLKernel` for transpiling a kernel * 'webgl2': Use the `WebGL2Kernel` for transpiling a kernel * 'headlessgl' **New in V2!**: Use the `HeadlessGLKernel` for transpiling a kernel * 'cpu': Use the `CPUKernel` for transpiling a kernel * `onIstanbulCoverageVariable`: Removed in v2.11.0, use v8 coverage * `removeIstanbulCoverage`: Removed in v2.11.0, use v8 coverage ## `gpu.createKernel` Settings Settings are an object used to create a `kernel` or `kernelMap`. Example: `gpu.createKernel(settings)` * `output` or `kernel.setOutput(output)`: `array` or `object` that describes the output of kernel. When using `kernel.setOutput()` you _can_ call it after the kernel has compiled if `kernel.dynamicOutput` is `true`, to resize your output. Example: * as array: `[width]`, `[width, height]`, or `[width, height, depth]` * as object: `{ x: width, y: height, z: depth }` * `pipeline` or `kernel.setPipeline(true)` **New in V2!**: boolean, default = `false` * Causes `kernel()` calls to output a `Texture`. To get array's from a `Texture`, use: ```js const result = kernel(); result.toArray(); ``` * Can be passed _directly_ into kernels, and is preferred: ```js kernel(texture); ``` * `graphical` or `kernel.setGraphical(boolean)`: boolean, default = `false` * `loopMaxIterations` or `kernel.setLoopMaxIterations(number)`: number, default = 1000 * `constants` or `kernel.setConstants(object)`: object, default = null * `dynamicOutput` or `kernel.setDynamicOutput(boolean)`: boolean, default = false - turns dynamic output on or off * `dynamicArguments` or `kernel.setDynamicArguments(boolean)`: boolean, default = false - turns dynamic arguments (use different size arrays and textures) on or off * `optimizeFloatMemory` or `kernel.setOptimizeFloatMemory(boolean)` **New in V2!**: boolean - causes a float32 texture to use all 4 channels rather than 1, using less memory, but consuming more GPU. * `precision` or `kernel.setPrecision('unsigned' | 'single')` **New in V2!**: 'single' or 'unsigned' - if 'single' output texture uses float32 for each colour channel rather than 8 * `fixIntegerDivisionAccuracy` or `kernel.setFixIntegerDivisionAccuracy(boolean)` : boolean - some cards have accuracy issues dividing by factors of three and some other primes (most apple kit?). Default on for affected cards, disable if accuracy not required. * `functions` or `kernel.setFunctions(array)`: array, array of functions to be used inside kernel. If undefined, inherits from `GPU` instance. Can also be an array of `{ source: function, argumentTypes: object, returnType: string }`. * `nativeFunctions` or `kernel.setNativeFunctions(array)`: object, defined as: `{ name: string, source: string, settings: object }`. This is generally set via using GPU.addNativeFunction() * VERY IMPORTANT! - Use this to add special native functions to your environment when you need specific functionality is needed. * `injectedNative` or `kernel.setInjectedNative(string)` **New in V2!**: string, defined as: `{ functionName: functionSource }`. This is for injecting native code before translated kernel functions. * `subKernels` or `kernel.setSubKernels(array)`: array, generally inherited from `GPU` instance. * `immutable` or `kernel.setImmutable(boolean)`: boolean, default = `false` * VERY IMPORTANT! - This was removed in v2.4.0 - v2.7.0, and brought back in v2.8.0 [by popular demand](https://github.com/gpujs/gpu.js/issues/572), please upgrade to get the feature * `strictIntegers` or `kernel.setStrictIntegers(boolean)`: boolean, default = `false` - allows undefined argumentTypes and function return values to use strict integer declarations. * `useLegacyEncoder` or `kernel.setUseLegacyEncoder(boolean)`: boolean, default `false` - more info [here](https://github.com/gpujs/gpu.js/wiki/Encoder-details). * `tactic` or `kernel.setTactic('speed' | 'balanced' | 'precision')` **New in V2!**: Set the kernel's tactic for compilation. Allows for compilation to better fit how GPU.js is being used (internally uses `lowp` for 'speed', `mediump` for 'balanced', and `highp` for 'precision'). Default is lowest resolution supported for output. ## Creating and Running Functions Depending on your output type, specify the intended size of your output. You cannot have an accelerated function that does not specify any output size. Output size | How to specify output size | How to reference in kernel --------------|-------------------------------|-------------------------------- 1D | `[length]` | `value[this.thread.x]` 2D | `[width, height]` | `value[this.thread.y][this.thread.x]` 3D | `[width, height, depth]` | `value[this.thread.z][this.thread.y][this.thread.x]` ```js const settings = { output: [100] }; ``` or ```js // You can also use x, y, and z const settings = { output: { x: 100 } }; ``` Create the function you want to run on the GPU. The first input parameter to `createKernel` is a kernel function which will compute a single number in the output. The thread identifiers, `this.thread.x`, `this.thread.y` or `this.thread.z` will allow you to specify the appropriate behavior of the kernel function at specific positions of the output. ```js const kernel = gpu.createKernel(function() { return this.thread.x; }, settings); ``` The created function is a regular JavaScript function, and you can use it like one. ```js kernel(); // Result: Float32Array[0, 1, 2, 3, ... 99] ``` Note: Instead of creating an object, you can use the chainable shortcut methods as a neater way of specifying settings. ```js const kernel = gpu.createKernel(function() { return this.thread.x; }).setOutput([100]); kernel(); // Result: Float32Array[0, 1, 2, 3, ... 99] ``` ### Declaring variables/functions within kernels GPU.js makes variable declaration inside kernel functions easy. Variable types supported are: * `Number` (Integer or Number), example: `let value = 1` or `let value = 1.1` * `Boolean`, example: `let value = true` * `Array(2)`, example: `let value = [1, 1]` * `Array(3)`, example: `let value = [1, 1, 1]` * `Array(4)`, example: `let value = [1, 1, 1, 1]` * `private Function`, example: `function myFunction(value) { return value + 1; }` `Number` kernel example: ```js const kernel = gpu.createKernel(function() { const i = 1; const j = 0.89; return i + j; }).setOutput([100]); ``` `Boolean` kernel example: ```js const kernel = gpu.createKernel(function() { const i = true; if (i) return 1; return 0; }).setOutput([100]); ``` `Array(2)` kernel examples: Using declaration ```js const kernel = gpu.createKernel(function() { const array2 = [0.08, 2]; return array2; }).setOutput([100]); ``` Directly returned ```js const kernel = gpu.createKernel(function() { return [0.08, 2]; }).setOutput([100]); ``` `Array(3)` kernel example: Using declaration ```js const kernel = gpu.createKernel(function() { const array2 = [0.08, 2, 0.1]; return array2; }).setOutput([100]); ``` Directly returned ```js const kernel = gpu.createKernel(function() { return [0.08, 2, 0.1]; }).setOutput([100]); ``` `Array(4)` kernel example: Using declaration ```js const kernel = gpu.createKernel(function() { const array2 = [0.08, 2, 0.1, 3]; return array2; }).setOutput([100]); ``` Directly returned ```js const kernel = gpu.createKernel(function() { return [0.08, 2, 0.1, 3]; }).setOutput([100]); ``` `private Function` kernel example: ```js const kernel = gpu.createKernel(function() { function myPrivateFunction() { return [0.08, 2, 0.1, 3]; } return myPrivateFunction(); // <-- type inherited here }).setOutput([100]); ``` ## Debugging Debugging can be done in a variety of ways, and there are different levels of debugging. * Debugging kernels with breakpoints can be done with `new GPU({ mode: 'dev' })` * This puts `GPU.js` into development mode. Here you can insert breakpoints, and be somewhat liberal in how your kernel is developed. * This mode _does not_ actually "compile" (parse, and eval) a kernel, it simply iterates on your code. * You can break a lot of rules here, because your kernel's function still has context of the state it came from. * PLEASE NOTE: Mapped kernels are not supported in this mode. They simply cannot work because of context. * Example: ```js const gpu = new GPU({ mode: 'dev' }); const kernel = gpu.createKernel(function(arg1, time) { // put a breakpoint on the next line, and watch it get hit const v = arg1[this.thread.y][this.thread.x * time]; return v; }, { output: [100, 100] }); ``` * Debugging actual kernels on CPU with `debugger`: * This will cause "breakpoint" like behaviour, but in an actual CPU kernel. You'll peer into the compiled kernel here, for a CPU. * Example: ```js const gpu = new GPU({ mode: 'cpu' }); const kernel = gpu.createKernel(function(arg1, time) { debugger; // <--NOTICE THIS, IMPORTANT! const v = arg1[this.thread.y][this.thread.x * time]; return v; }, { output: [100, 100] }); ``` * Debugging an actual GPU kernel: * There are no breakpoints available on the GPU, period. By providing the same level of abstraction and logic, the above methods should give you enough insight to debug, but sometimes we just need to see what is on the GPU. * Be VERY specific and deliberate, and use the kernel to your advantage, rather than just getting frustrated or giving up. * Example: ```js const gpu = new GPU({ mode: 'cpu' }); const kernel = gpu.createKernel(function(arg1, time) { const x = this.thread.x * time; return x; // <--NOTICE THIS, IMPORTANT! const v = arg1[this.thread.y][x]; return v; }, { output: [100, 100] }); ``` In this example, we return early the value of x, to see exactly what it is. The rest of the logic is ignored, but now you can see the value that is calculated from `x`, and debug it. This is an overly simplified problem. * Sometimes you need to solve graphical problems, that can be done similarly. * Example: ```js const gpu = new GPU({ mode: 'cpu' }); const kernel = gpu.createKernel(function(arg1, time) { const x = this.thread.x * time; if (x < 4 || x > 2) { // RED this.color(1, 0, 0); // <--NOTICE THIS, IMPORTANT! return; } if (x > 6 && x < 12) { // GREEN this.color(0, 1, 0); // <--NOTICE THIS, IMPORTANT! return; } const v = arg1[this.thread.y][x]; return v; }, { output: [100, 100], graphical: true }); ``` Here we are making the canvas red or green depending on the value of `x`. ## Accepting Input ### Supported Input Types * Numbers * 1d,2d, or 3d Array of numbers * Arrays of `Array`, `Float32Array`, `Int16Array`, `Int8Array`, `Uint16Array`, `uInt8Array` * Pre-flattened 2d or 3d Arrays using 'Input', for faster upload of arrays * Example: ```js const { input } = require('gpu.js'); const value = input(flattenedArray, [width, height, depth]); ``` * HTML Image * Array of HTML Images * Video Element **New in V2!** To define an argument, simply add it to the kernel function like regular JavaScript. ### Input Examples ```js const kernel = gpu.createKernel(function(x) { return x; }).setOutput([100]); kernel(42); // Result: Float32Array[42, 42, 42, 42, ... 42] ``` Similarly, with array inputs: ```js const kernel = gpu.createKernel(function(x) { return x[this.thread.x % 3]; }).setOutput([100]); kernel([1, 2, 3]); // Result: Float32Array[1, 2, 3, 1, ... 1 ] ``` An HTML Image: ```js const kernel = gpu.createKernel(function(image) { const pixel = image[this.thread.y][this.thread.x]; this.color(pixel[0], pixel[1], pixel[2], pixel[3]); }) .setGraphical(true) .setOutput([100, 100]); const image = document.createElement('img'); image.src = 'my/image/source.png'; image.onload = () => { kernel(image); // Result: colorful image document.getElementsByTagName('body')[0].appendChild(kernel.canvas); }; ``` An Array of HTML Images: ```js const kernel = gpu.createKernel(function(image) { const pixel = image[this.thread.z][this.thread.y][this.thread.x]; this.color(pixel[0], pixel[1], pixel[2], pixel[3]); }) .setGraphical(true) .setOutput([100, 100]); const image1 = document.createElement('img'); image1.src = 'my/image/source1.png'; image1.onload = onload; const image2 = document.createElement('img'); image2.src = 'my/image/source2.png'; image2.onload = onload; const image3 = document.createElement('img'); image3.src = 'my/image/source3.png'; image3.onload = onload; const totalImages = 3; let loadedImages = 0; function onload() { loadedImages++; if (loadedImages === totalImages) { kernel([image1, image2, image3]); // Result: colorful image composed of many images document.getElementsByTagName('body')[0].appendChild(kernel.canvas); } }; ``` An HTML Video: **New in V2!** ```js const kernel = gpu.createKernel(function(videoFrame) { const pixel = videoFrame[this.thread.y][this.thread.x]; this.color(pixel[0], pixel[1], pixel[2], pixel[3]); }) .setGraphical(true) .setOutput([100, 100]); const video = new document.createElement('video'); video.src = 'my/video/source.webm'; kernel(image); //note, try and use requestAnimationFrame, and the video should be ready or playing // Result: video frame ``` ## Graphical Output Sometimes, you want to produce a `canvas` image instead of doing numeric computations. To achieve this, set the `graphical` flag to `true` and the output dimensions to `[width, height]`. The thread identifiers will now refer to the `x` and `y` coordinate of the pixel you are producing. Inside your kernel function, use `this.color(r,g,b)` or `this.color(r,g,b,a)` to specify the color of the pixel. For performance reasons, the return value of your function will no longer be anything useful. Instead, to display the image, retrieve the `canvas` DOM node and insert it into your page. ```js const render = gpu.createKernel(function() { this.color(0, 0, 0, 1); }) .setOutput([20, 20]) .setGraphical(true); render(); const canvas = render.canvas; document.getElementsByTagName('body')[0].appendChild(canvas); ``` Note: To animate the rendering, use `requestAnimationFrame` instead of `setTimeout` for optimal performance. For more information, see [this](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame). ### .getPixels() **New in V2!** To make it easier to get pixels from a context, use `kernel.getPixels()`, which returns a flat array similar to what you get from WebGL's `readPixels` method. A note on why: webgl's `readPixels` returns an array ordered differently from javascript's `getImageData`. This makes them behave similarly. While the values may be somewhat different, because of graphical precision available in the kernel, and alpha, this allows us to easily get pixel data in unified way. Example: ```js const render = gpu.createKernel(function() { this.color(0, 0, 0, 1); }) .setOutput([20, 20]) .setGraphical(true); render(); const pixels = render.getPixels(); // [r,g,b,a, r,g,b,a... ``` ### Alpha Currently, if you need alpha do something like enabling `premultipliedAlpha` with your own gl context: ```js const canvas = DOM.canvas(500, 500); const gl = canvas.getContext('webgl2', { premultipliedAlpha: false }); const gpu = new GPU({ canvas, context: gl }); const krender = gpu.createKernel(function(x) { this.color(this.thread.x / 500, this.thread.y / 500, x[0], x[1]); }) .setOutput([500, 500]) .setGraphical(true); ``` ## Combining kernels Sometimes you want to do multiple math operations on the gpu without the round trip penalty of data transfer from cpu to gpu to cpu to gpu, etc. To aid this there is the `combineKernels` method. _**Note:**_ Kernels can have different output sizes. ```js const add = gpu.createKernel(function(a, b) { return a[this.thread.x] + b[this.thread.x]; }).setOutput([20]); const multiply = gpu.createKernel(function(a, b) { return a[this.thread.x] * b[this.thread.x]; }).setOutput([20]); const superKernel = gpu.combineKernels(add, multiply, function(a, b, c) { return multiply(add(a, b), c); }); superKernel(a, b, c); ``` This gives you the flexibility of using multiple transformations but without the performance penalty, resulting in a much much MUCH faster operation. ## Create Kernel Map Sometimes you want to do multiple math operations in one kernel, and save the output of each of those operations. An example is **Machine Learning** where the previous output is required for back propagation. To aid this there is the `createKernelMap` method. ### object outputs ```js const megaKernel = gpu.createKernelMap({ addResult: function add(a, b) { return a + b; }, multiplyResult: function multiply(a, b) { return a * b; }, }, function(a, b, c) { return multiply(add(a[this.thread.x], b[this.thread.x]), c[this.thread.x]); }, { output: [10] }); megaKernel(a, b, c); // Result: { addResult: Float32Array, multiplyResult: Float32Array, result: Float32Array } ``` ### array outputs ```js const megaKernel = gpu.createKernelMap([ function add(a, b) { return a + b; }, function multiply(a, b) { return a * b; } ], function(a, b, c) { return multiply(add(a[this.thread.x], b[this.thread.x]), c[this.thread.x]); }, { output: [10] }); megaKernel(a, b, c); // Result: { 0: Float32Array, 1: Float32Array, result: Float32Array } ``` This gives you the flexibility of using parts of a single transformation without the performance penalty, resulting in much much _MUCH_ faster operation. ## Adding custom functions ### To `GPU` instance use `gpu.addFunction(function() {}, settings)` for adding custom functions to all kernels. Needs to be called BEFORE `gpu.createKernel`. Example: ```js gpu.addFunction(function mySuperFunction(a, b) { return a - b; }); function anotherFunction(value) { return value + 1; } gpu.addFunction(anotherFunction); const kernel = gpu.createKernel(function(a, b) { return anotherFunction(mySuperFunction(a[this.thread.x], b[this.thread.x])); }).setOutput([20]); ``` ### To `Kernel` instance use `kernel.addFunction(function() {}, settings)` for adding custom functions to all kernels. Example: ```js kernel.addFunction(function mySuperFunction(a, b) { return a - b; }); function anotherFunction(value) { return value + 1; } kernel.addFunction(anotherFunction); const kernel = gpu.createKernel(function(a, b) { return anotherFunction(mySuperFunction(a[this.thread.x], b[this.thread.x])); }).setOutput([20]); ``` ### Adding strongly typed functions To manually strongly type a function you may use settings. By setting this value, it makes the build step of the kernel less resource intensive. Settings take an optional hash values: * `returnType`: optional, defaults to inference from `FunctionBuilder`, the value you'd like to return from the function. * `argumentTypes`: optional, defaults to inference from `FunctionBuilder` for each param, a hash of param names with values of the return types. Example on `GPU` instance: ```js gpu.addFunction(function mySuperFunction(a, b) { return [a - b[1], b[0] - a]; }, { argumentTypes: { a: 'Number', b: 'Array(2)'}, returnType: 'Array(2)' }); ``` Example on `Kernel` instance: ```js kernel.addFunction(function mySuperFunction(a, b) { return [a - b[1], b[0] - a]; }, { argumentTypes: { a: 'Number', b: 'Array(2)'}, returnType: 'Array(2)' }); ``` NOTE: GPU.js infers types if they are not defined and is generally able to detect the types you need, however 'Array(2)', 'Array(3)', and 'Array(4)' are exceptions, at least on the kernel level. Also, it is nice to have power over the automatic type inference system. ## Adding custom functions directly to kernel ```js function mySuperFunction(a, b) { return a - b; } const kernel = gpu.createKernel(function(a, b) { return mySuperFunction(a[this.thread.x], b[this.thread.x]); }) .setOutput([20]) .setFunctions([mySuperFunction]); ``` ## Types GPU.js does type inference when types are not defined, so even if you code weak type, you are typing strongly typed. This is needed because c++, which glsl is a subset of, is, of course, strongly typed. Types that can be used with GPU.js are as follows: ### Argument Types * 'Array' * 'Array(2)' **New in V2!** * 'Array(3)' **New in V2!** * 'Array(4)' **New in V2!** * 'Array1D(2)' **New in V2!** * 'Array1D(3)' **New in V2!** * 'Array1D(4)' **New in V2!** * 'Array2D(2)' **New in V2!** * 'Array2D(3)' **New in V2!** * 'Array2D(4)' **New in V2!** * 'Array3D(2)' **New in V2!** * 'Array3D(3)' **New in V2!** * 'Array3D(4)' **New in V2!** * 'HTMLCanvas' **New in V2.6** * 'OffscreenCanvas' **New in V2.13** * 'HTMLImage' * 'ImageBitmap' **New in V2.14** * 'ImageData' **New in V2.15** * 'HTMLImageArray' * 'HTMLVideo' **New in V2!** * 'Number' * 'Float' * 'Integer' * 'Boolean' **New in V2!** ### Return Types NOTE: These refer the the return type of the kernel function, the actual result will always be a collection in the size of the defined `output` * 'Array(2)' * 'Array(3)' * 'Array(4)' * 'Number' * 'Float' * 'Integer' ### Internal Types Types generally used in the `Texture` class, for #pipelining or for advanced usage. * 'ArrayTexture(1)' **New in V2!** * 'ArrayTexture(2)' **New in V2!** * 'ArrayTexture(3)' **New in V2!** * 'ArrayTexture(4)' **New in V2!** * 'NumberTexture' * 'MemoryOptimizedNumberTexture' **New in V2!** ## Loops * Any loops defined inside the kernel must have a maximum iteration count defined by the loopMaxIterations setting. * Other than defining the iterations by a constant or fixed value as shown [Dynamic sized via constants](dynamic-sized-via-constants), you can also simply pass the number of iterations as a variable to the kernel ### Dynamic sized via constants ```js const matMult = gpu.createKernel(function(a, b) { var sum = 0; for (var i = 0; i < this.constants.size; i++) { sum += a[this.thread.y][i] * b[i][this.thread.x]; } return sum; }, { constants: { size: 512 }, output: [512, 512], }); ``` ### Fixed sized ```js const matMult = gpu.createKernel(function(a, b) { var sum = 0; for (var i = 0; i < 512; i++) { sum += a[this.thread.y][i] * b[i][this.thread.x]; } return sum; }).setOutput([512, 512]); ``` ## Pipelining [Pipeline](https://en.wikipedia.org/wiki/Pipeline_(computing)) is a feature where values are sent directly from kernel to kernel via a texture. This results in extremely fast computing. This is achieved with the kernel setting `pipeline: boolean` or by calling `kernel.setPipeline(true)` In an effort to make the CPU and GPU work similarly, pipeline on CPU and GPU modes causes the kernel result to be reused when `immutable: false` (which is default). If you'd like to keep kernel results around, use `immutable: true` and ensure you cleanup memory: * In gpu mode using `texture.delete()` when appropriate. * In cpu mode allowing values to go out of context ### Cloning Textures **New in V2!** When using pipeline mode the outputs from kernels can be cloned using `texture.clone()`. ```js const kernel1 = gpu.createKernel(function(v) { return v[this.thread.x]; }) .setPipeline(true) .setOutput([100]); const kernel2 = gpu.createKernel(function(v) { return v[this.thread.x]; }) .setOutput([100]); const result1 = kernel1(array); // Result: Texture console.log(result1.toArray()); // Result: Float32Array[0, 1, 2, 3, ... 99] const result2 = kernel2(result1); // Result: Float32Array[0, 1, 2, 3, ... 99] ``` ### Cleanup pipeline texture memory **New in V2.4!** When using `kernel.immutable = true` recycling GPU memory is handled internally, but a good practice is to clean up memory you no longer need it. Cleanup kernel outputs by using `texture.delete()` to keep GPU memory as small as possible. NOTE: Internally textures will only release from memory if there are no references to them. When using pipeline mode on a kernel `K` the output for each call will be a newly allocated texture `T`. If, after getting texture `T` as an output, `T.delete()` is called, the next call to K will reuse `T` as its output texture. Alternatively, if you'd like to clear out a `texture` and yet keep it in memory, you may use `texture.clear()`, which will cause the `texture` to persist in memory, but its internal values to become all zeros. ## Offscreen Canvas GPU.js supports offscreen canvas where available. Here is an example of how to use it with two files, `gpu-worker.js`, and `index.js`: file: `gpu-worker.js` ```js importScripts('path/to/gpu.js'); onmessage = function() { // define gpu instance const gpu = new GPU(); // input values const a = [1,2,3]; const b = [3,2,1]; // setup kernel const kernel = gpu.createKernel(function(a, b) { return a[this.thread.x] - b[this.thread.x]; }) .setOutput([3]); // output some results! postMessage(kernel(a, b)); }; ``` file: `index.js` ```js var worker = new Worker('gpu-worker.js'); worker.onmessage = function(e) { var result = e.data; console.log(result); }; ``` ## Cleanup * for instances of `GPU` use the `destroy` method. Example: `gpu.destroy()` * for instances of `Kernel` use the `destroy` method. Example: `kernel.destroy()` * for instances of `Texture` use the `delete` method. Example: `texture.delete()` * for instances of `Texture` that you might want to reuse/reset to zeros, use the `clear` method. Example: `texture.clear()` ## Flattened typed array support To use the useful `x`, `y`, `z` `thread` lookup api inside of GPU.js, and yet use flattened arrays, there is the `Input` type. This is generally much faster for when sending values to the gpu, especially with larger data sets. Usage example: ```js const { GPU, input, Input } = require('gpu.js'); const gpu = new GPU(); const kernel = gpu.createKernel(function(a, b) { return a[this.thread.y][this.thread.x] + b[this.thread.y][this.thread.x]; }).setOutput([3,3]); kernel( input( new Float32Array([1,2,3,4,5,6,7,8,9]), [3, 3] ), input( new Float32Array([1,2,3,4,5,6,7,8,9]), [3, 3] ) ); ``` Note: `input(value, size)` is a simple pointer for `new Input(value, size)` ## Precompiled and Lighter Weight Kernels ### using JSON GPU.js packs a lot of functionality into a single file, such as a complete javascript parse, which may not be needed in some cases. To aid in keeping your kernels lightweight, the `kernel.toJSON()` method was added. This allows you to reuse a previously built kernel, without the need to re-parse the javascript. Here is an example: ```js const gpu = new GPU(); const kernel = gpu.createKernel(function() { return [1,2,3,4]; }, { output: [1] }); console.log(kernel()); // [Float32Array([1,2,3,4])]; const json = kernel.toJSON(); const newKernelFromJson = gpu.createKernel(json); console.log(newKernelFromJSON()); // [Float32Array([1,2,3,4])]; ``` NOTE: There is lighter weight, pre-built, version of GPU.js to assist with serializing from to and from json in the dist folder of the project, which include: * [dist/gpu-browser-core.js](dist/gpu-browser-core.js) * [dist/gpu-browser-core.min.js](dist/gpu-browser-core.min.js) ### Exporting kernel GPU.js supports seeing exactly how it is interacting with the graphics processor by means of the `kernel.toString(...)` method. This method, when called, creates a kernel that executes _exactly the instruction set given to the GPU (or CPU)_ *as a very tiny reusable function* that instantiates a kernel. NOTE: When exporting a kernel and using `constants` the following constants are *not changeable*: * `Array(2)` * `Array(3)` * `Array(4)` * `Integer` * `Number` * `Float` * `Boolean` Here is an example used to/from file: ```js import { GPU } from 'gpu.js'; import * as fs from 'fs'; const gpu = new GPU(); const kernel = gpu.createKernel(function(v) { return this.thread.x + v + this.constants.v1; }, { output: [10], constants: { v1: 100 } }); const result = kernel(1); const kernelString = kernel.toString(1); fs.writeFileSync('./my-exported-kernel.js', 'module.exports = ' + kernelString); import * as MyExportedKernel from './my-exported-kernel'; import gl from 'gl'; const myExportedKernel = MyExportedKernel({ context: gl(1,1), constants: { v1: 100 } }); ``` Here is an example for just-in-time function creation: ```js const gpu = new GPU(); const kernel = gpu.createKernel(function(a) { let sum = 0; for (let i = 0; i < 6; i++) { sum += a[this.thread.x][i]; } return sum; }, { output: [6] }); kernel(input(a, [6, 6])); const kernelString = kernel.toString(input(a, [6, 6])); const newKernel = new Function('return ' + kernelString)()({ context }); newKernel(input(a, [6, 6])); ``` #### using constants with `kernel.toString(...args)` You can assign _some_ new constants when using the function output from `.toString()`, ## Supported Math functions Since the code running in the kernel is actually compiled to GLSL code, not all functions from the JavaScript Math module are supported. This is a list of the supported ones: * `Math.abs()` * `Math.acos()` * `Math.acosh()` * `Math.asin()` * `Math.asinh()` * `Math.atan()` * `Math.atanh()` * `Math.atan2()` * `Math.cbrt()` * `Math.ceil()` * `Math.cos()` * `Math.cosh()` * `Math.exp()` * `Math.expm1()` * `Math.floor()` * `Math.fround()` * `Math.imul()` * `Math.log()` * `Math.log10()` * `Math.log1p()` * `Math.log2()` * `Math.max()` * `Math.min()` * `Math.pow()` * `Math.random()` * A note on random. We use [a plugin](src/plugins/math-random-uniformly-distributed.js) to generate random. Random seeded _and_ generated, _both from the GPU_, is not as good as random from the CPU as there are more things that the CPU can seed random from. However, we seed random on the GPU, _from a random value in the CPU_. We then seed the subsequent randoms from the previous random value. So we seed from CPU, and generate from GPU. Which is still not as good as CPU, but closer. While this isn't perfect, it should suffice in most scenarios. In any case, we must give thanks to [RandomPower](https://www.randompower.eu/), and this [issue](https://github.com/gpujs/gpu.js/issues/498), for assisting in improving our implementation of random. * `Math.round()` * `Math.sign()` * `Math.sin()` * `Math.sinh()` * `Math.sqrt()` * `Math.tan()` * `Math.tanh()` * `Math.trunc()` This is a list and reasons of unsupported ones: * `Math.clz32` - bits directly are hard * `Math.hypot` - dynamically sized ## How to check what is supported To assist with mostly unit tests, but perhaps in scenarios outside of GPU.js, there are the following logical checks to determine what support level the system executing a GPU.js kernel may have: * `GPU.disableValidation()` - turn off all kernel validation * `GPU.enableValidation()` - turn on all kernel validation * `GPU.isGPUSupported`: `boolean` - checks if GPU is in-fact supported * `GPU.isKernelMapSupported`: `boolean` - checks if kernel maps are supported * `GPU.isOffscreenCanvasSupported`: `boolean` - checks if offscreen canvas is supported * `GPU.isWebGLSupported`: `boolean` - checks if WebGL v1 is supported * `GPU.isWebGL2Supported`: `boolean` - checks if WebGL v2 is supported * `GPU.isHeadlessGLSupported`: `boolean` - checks if headlessgl is supported * `GPU.isCanvasSupported`: `boolean` - checks if canvas is supported * `GPU.isGPUHTMLImageArraySupported`: `boolean` - checks if the platform supports HTMLImageArray's * `GPU.isSinglePrecisionSupported`: `boolean` - checks if the system supports single precision float 32 values ## Typescript Typings Typescript is supported! Typings can be found [here](src/index.d.ts)! For strongly typed kernels: ```typescript import { GPU, IKernelFunctionThis } from 'gpu.js'; const gpu = new GPU(); function kernelFunction(this: IKernelFunctionThis): number { return 1 + this.thread.x; } const kernelMap = gpu.createKernel(kernelFunction) .setOutput([3,3,3]); const result = kernelMap(); console.log(result as number[][][]); ``` For strongly typed mapped kernels: ```typescript import { GPU, Texture, IKernelFunctionThis } from 'gpu.js'; const gpu = new GPU(); function kernelFunction(this: IKernelFunctionThis): [number, number] { return [1, 1]; } function subKernel(): [number, number] { return [1, 1]; } const kernelMap = gpu.createKernelMap({ test: subKernel, }, kernelFunction) .setOutput([1]) .setPipeline(true); const result = kernelMap(); console.log((result.test as Texture).toArray() as [number, number][]); ``` For extending constants: ```typescript import { GPU, IKernelFunctionThis } from 'gpu.js'; const gpu = new GPU(); interface IConstants { screen: [number, number]; } type This = { constants: IConstants } & IKernelFunctionThis; function kernelFunction(this: This): number { const { screen } = this.constants; return 1 + screen[0]; } const kernelMap = gpu.createKernel(kernelFunction) .setOutput([3,3,3]) .setConstants({ screen: [1, 1] }); const result = kernelMap(); console.log(result as number[][][]); ``` [Click here](/examples) for more typescript examples. ## Destructured Assignments **New in V2!** Destructured Objects and Arrays work in GPU.js. * Object destructuring ```js const gpu = new GPU(); const kernel = gpu.createKernel(function() { const { thread: {x, y} } = this; return x + y; }, { output: [2] }); console.log(kernel()); ``` * Array destructuring ```js const gpu = new GPU(); const kernel = gpu.createKernel(function(array) { const [first, second] = array; return first + second; }, { output: [2], argumentTypes: { array: 'Array(2)' } }); console.log(kernel([1, 2])); ``` ## Dealing With Transpilation Transpilation doesn't do the best job of keeping code beautiful. To aid in this endeavor GPU.js can handle some scenarios to still aid you harnessing the GPU in less than ideal circumstances. Here is a list of a few things that GPU.js does to fix transpilation: * When a transpiler such as [Babel](https://babeljs.io/) changes `myCall()` to `(0, _myCall.myCall)`, it is gracefully handled. ## Full API Reference You can find a [complete API reference here](https://doxdox.org/gpujs/gpu.js/). ## How possible in node? GPU.js uses [HeadlessGL](https://github.com/stackgl/headless-gl) in node for GPU acceleration. GPU.js is written in such a way, you can introduce your own backend. Have a suggestion? We'd love to hear it! ## Terms Explained * Kernel - A function that is tightly coupled to program that runs on the Graphic Processor * Texture - A graphical artifact that is packed with data, in the case of GPU.js, bit shifted parts of a 32 bit floating point decimal ## Testing Testing is done (right now) manually, (help wanted [here](https://github.com/gpujs/gpu.js/issues/515) if you can!), using the following: * For browser, setup a webserver on the root of the gpu.js project and visit http://url/test/all.html * For node, run either of the 3 commands: * `yarn test test/features` * `yarn test test/internal` * `yarn test test/issues` ## Building Building isn't required on node, but is for browser. To build the browser's files, run: `yarn make` # Get Involved! ## Contributing Contributors are welcome! Create a merge request to the `develop` branch and we will gladly review it. If you wish to get write access to the repository, please email us and we will review your application and grant you access to the `develop` branch. We promise never to pass off your code as ours. ### Issues If you have an issue, either a bug or a feature you think would benefit your project let us know and we will do our best. Create issues [here](https://github.com/gpujs/gpu.js/issues) and follow the template. ### Contributors This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)]. ### Backers Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/gpujs#backer)] ### Sponsors Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/gpujs#sponsor)] ![](https://www.leadergpu.com/assets/main/logo_leadergpu-a8cacac0c90d204b7f7f6c8420c6a149e71ebe53f3f28f3fc94a01cd05c0bd93.png) Sponsored NodeJS GPU environment from [LeaderGPU](https://www.leadergpu.com) - These guys rock! ![](https://3fxtqy18kygf3on3bu39kh93-wpengine.netdna-ssl.com/wp-content/themes/browserstack/img/browserstack-logo.svg) Sponsored Browser GPU environment's from [BrowserStack](https://browserstack.com) - Second to none! ## [License](LICENSE) ================================================ FILE: dist/gpu-browser-core.js ================================================ /** * gpu.js * http://gpu.rocks/ * * GPU Accelerated JavaScript * * @version 2.16.0 * @date Thu Feb 13 2025 11:46:48 GMT-0800 (Pacific Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2025 gpu.js Team */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.GPU = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i 0) { recording.pop(); } } function insertVariable(name, value) { variables[name] = value; } function getEntity(value) { const name = entityNames[value]; if (name) { return contextName + '.' + name; } return value; } function setIndent(spaces) { indent = ' '.repeat(spaces); } function addVariable(value, source) { const variableName = `${contextName}Variable${contextVariables.length}`; recording.push(`${indent}const ${variableName} = ${source};`); contextVariables.push(value); return variableName; } function writePPM(width, height) { const sourceVariable = `${contextName}Variable${contextVariables.length}`; const imageVariable = `imageDatum${imageCount}`; recording.push(`${indent}let ${imageVariable} = ["P3\\n# ${readPixelsFile}.ppm\\n", ${width}, ' ', ${height}, "\\n255\\n"].join("");`); recording.push(`${indent}for (let i = 0; i < ${imageVariable}.length; i += 4) {`); recording.push(`${indent} ${imageVariable} += ${sourceVariable}[i] + ' ' + ${sourceVariable}[i + 1] + ' ' + ${sourceVariable}[i + 2] + ' ';`); recording.push(`${indent}}`); recording.push(`${indent}if (typeof require !== "undefined") {`); recording.push(`${indent} require('fs').writeFileSync('./${readPixelsFile}.ppm', ${imageVariable});`); recording.push(`${indent}}`); imageCount++; } function addComment(value) { recording.push(`${indent}// ${value}`); } function checkThrowError() { recording.push(`${indent}(() => { ${indent}const error = ${contextName}.getError(); ${indent}if (error !== ${contextName}.NONE) { ${indent} const names = Object.getOwnPropertyNames(gl); ${indent} for (let i = 0; i < names.length; i++) { ${indent} const name = names[i]; ${indent} if (${contextName}[name] === error) { ${indent} throw new Error('${contextName} threw ' + name); ${indent} } ${indent} } ${indent}} ${indent}})();`); } function methodCallToString(method, args) { return `${contextName}.${method}(${argumentsToString(args, { contextName, contextVariables, getEntity, addVariable, variables, onUnrecognizedArgumentLookup })})`; } function getVariableName(value) { if (variables) { for (const name in variables) { if (variables[name] === value) { return name; } } } return null; } function getContextVariableName(value) { const i = contextVariables.indexOf(value); if (i !== -1) { return `${contextName}Variable${i}`; } return null; } } function glExtensionWiretap(extension, options) { const proxy = new Proxy(extension, { get: listen }); const extensionEntityNames = {}; const { contextName, contextVariables, getEntity, useTrackablePrimitives, recording, variables, indent, onUnrecognizedArgumentLookup, } = options; return proxy; function listen(obj, property) { if (typeof obj[property] === 'function') { return function() { switch (property) { case 'drawBuffersWEBGL': recording.push(`${indent}${contextName}.drawBuffersWEBGL([${argumentsToString(arguments[0], { contextName, contextVariables, getEntity: getExtensionEntity, addVariable, variables, onUnrecognizedArgumentLookup })}]);`); return extension.drawBuffersWEBGL(arguments[0]); } let result = extension[property].apply(extension, arguments); switch (typeof result) { case 'undefined': recording.push(`${indent}${methodCallToString(property, arguments)};`); return; case 'number': case 'boolean': if (useTrackablePrimitives && contextVariables.indexOf(trackablePrimitive(result)) === -1) { recording.push(`${indent}const ${contextName}Variable${contextVariables.length} = ${methodCallToString(property, arguments)};`); contextVariables.push(result = trackablePrimitive(result)); } else { recording.push(`${indent}const ${contextName}Variable${contextVariables.length} = ${methodCallToString(property, arguments)};`); contextVariables.push(result); } break; default: if (result === null) { recording.push(`${methodCallToString(property, arguments)};`); } else { recording.push(`${indent}const ${contextName}Variable${contextVariables.length} = ${methodCallToString(property, arguments)};`); } contextVariables.push(result); } return result; }; } extensionEntityNames[extension[property]] = property; return extension[property]; } function getExtensionEntity(value) { if (extensionEntityNames.hasOwnProperty(value)) { return `${contextName}.${extensionEntityNames[value]}`; } return getEntity(value); } function methodCallToString(method, args) { return `${contextName}.${method}(${argumentsToString(args, { contextName, contextVariables, getEntity: getExtensionEntity, addVariable, variables, onUnrecognizedArgumentLookup })})`; } function addVariable(value, source) { const variableName = `${contextName}Variable${contextVariables.length}`; contextVariables.push(value); recording.push(`${indent}const ${variableName} = ${source};`); return variableName; } } function argumentsToString(args, options) { const { variables, onUnrecognizedArgumentLookup } = options; return (Array.from(args).map((arg) => { const variableName = getVariableName(arg); if (variableName) { return variableName; } return argumentToString(arg, options); }).join(', ')); function getVariableName(value) { if (variables) { for (const name in variables) { if (!variables.hasOwnProperty(name)) continue; if (variables[name] === value) { return name; } } } if (onUnrecognizedArgumentLookup) { return onUnrecognizedArgumentLookup(value); } return null; } } function argumentToString(arg, options) { const { contextName, contextVariables, getEntity, addVariable, onUnrecognizedArgumentLookup } = options; if (typeof arg === 'undefined') { return 'undefined'; } if (arg === null) { return 'null'; } const i = contextVariables.indexOf(arg); if (i > -1) { return `${contextName}Variable${i}`; } switch (arg.constructor.name) { case 'String': const hasLines = /\n/.test(arg); const hasSingleQuotes = /'/.test(arg); const hasDoubleQuotes = /"/.test(arg); if (hasLines) { return '`' + arg + '`'; } else if (hasSingleQuotes && !hasDoubleQuotes) { return '"' + arg + '"'; } else if (!hasSingleQuotes && hasDoubleQuotes) { return "'" + arg + "'"; } else { return '\'' + arg + '\''; } case 'Number': return getEntity(arg); case 'Boolean': return getEntity(arg); case 'Array': return addVariable(arg, `new ${arg.constructor.name}([${Array.from(arg).join(',')}])`); case 'Float32Array': case 'Uint8Array': case 'Uint16Array': case 'Int32Array': return addVariable(arg, `new ${arg.constructor.name}(${JSON.stringify(Array.from(arg))})`); default: if (onUnrecognizedArgumentLookup) { const instantiationString = onUnrecognizedArgumentLookup(arg); if (instantiationString) { return instantiationString; } } throw new Error(`unrecognized argument type ${arg.constructor.name}`); } } function trackablePrimitive(value) { return new value.constructor(value); } if (typeof module !== 'undefined') { module.exports = { glWiretap, glExtensionWiretap }; } if (typeof window !== 'undefined') { glWiretap.glExtensionWiretap = glExtensionWiretap; window.glWiretap = glWiretap; } },{}],3:[function(require,module,exports){ function setupArguments(args) { const newArguments = new Array(args.length); for (let i = 0; i < args.length; i++) { const arg = args[i]; if (arg.toArray) { newArguments[i] = arg.toArray(); } else { newArguments[i] = arg; } } return newArguments; } function mock1D() { const args = setupArguments(arguments); const row = new Float32Array(this.output.x); for (let x = 0; x < this.output.x; x++) { this.thread.x = x; this.thread.y = 0; this.thread.z = 0; row[x] = this._fn.apply(this, args); } return row; } function mock2D() { const args = setupArguments(arguments); const matrix = new Array(this.output.y); for (let y = 0; y < this.output.y; y++) { const row = new Float32Array(this.output.x); for (let x = 0; x < this.output.x; x++) { this.thread.x = x; this.thread.y = y; this.thread.z = 0; row[x] = this._fn.apply(this, args); } matrix[y] = row; } return matrix; } function mock2DGraphical() { const args = setupArguments(arguments); for (let y = 0; y < this.output.y; y++) { for (let x = 0; x < this.output.x; x++) { this.thread.x = x; this.thread.y = y; this.thread.z = 0; this._fn.apply(this, args); } } } function mock3D() { const args = setupArguments(arguments); const cube = new Array(this.output.z); for (let z = 0; z < this.output.z; z++) { const matrix = new Array(this.output.y); for (let y = 0; y < this.output.y; y++) { const row = new Float32Array(this.output.x); for (let x = 0; x < this.output.x; x++) { this.thread.x = x; this.thread.y = y; this.thread.z = z; row[x] = this._fn.apply(this, args); } matrix[y] = row; } cube[z] = matrix; } return cube; } function apiDecorate(kernel) { kernel.setOutput = (output) => { kernel.output = setupOutput(output); if (kernel.graphical) { setupGraphical(kernel); } }; kernel.toJSON = () => { throw new Error('Not usable with gpuMock'); }; kernel.setConstants = (flag) => { kernel.constants = flag; return kernel; }; kernel.setGraphical = (flag) => { kernel.graphical = flag; return kernel; }; kernel.setCanvas = (flag) => { kernel.canvas = flag; return kernel; }; kernel.setContext = (flag) => { kernel.context = flag; return kernel; }; kernel.destroy = () => {}; kernel.validateSettings = () => {}; if (kernel.graphical && kernel.output) { setupGraphical(kernel); } kernel.exec = function() { return new Promise((resolve, reject) => { try { resolve(kernel.apply(kernel, arguments)); } catch(e) { reject(e); } }); }; kernel.getPixels = (flip) => { const {x, y} = kernel.output; return flip ? flipPixels(kernel._imageData.data, x, y) : kernel._imageData.data.slice(0); }; kernel.color = function(r, g, b, a) { if (typeof a === 'undefined') { a = 1; } r = Math.floor(r * 255); g = Math.floor(g * 255); b = Math.floor(b * 255); a = Math.floor(a * 255); const width = kernel.output.x; const height = kernel.output.y; const x = kernel.thread.x; const y = height - kernel.thread.y - 1; const index = x + y * width; kernel._colorData[index * 4 + 0] = r; kernel._colorData[index * 4 + 1] = g; kernel._colorData[index * 4 + 2] = b; kernel._colorData[index * 4 + 3] = a; }; const mockMethod = () => kernel; const methods = [ 'setWarnVarUsage', 'setArgumentTypes', 'setTactic', 'setOptimizeFloatMemory', 'setDebug', 'setLoopMaxIterations', 'setConstantTypes', 'setFunctions', 'setNativeFunctions', 'setInjectedNative', 'setPipeline', 'setPrecision', 'setOutputToTexture', 'setImmutable', 'setStrictIntegers', 'setDynamicOutput', 'setHardcodeConstants', 'setDynamicArguments', 'setUseLegacyEncoder', 'setWarnVarUsage', 'addSubKernel', ]; for (let i = 0; i < methods.length; i++) { kernel[methods[i]] = mockMethod; } return kernel; } function setupGraphical(kernel) { const {x, y} = kernel.output; if (kernel.context && kernel.context.createImageData) { const data = new Uint8ClampedArray(x * y * 4); kernel._imageData = kernel.context.createImageData(x, y); kernel._colorData = data; } else { const data = new Uint8ClampedArray(x * y * 4); kernel._imageData = { data }; kernel._colorData = data; } } function setupOutput(output) { let result = null; if (output.length) { if (output.length === 3) { const [x,y,z] = output; result = { x, y, z }; } else if (output.length === 2) { const [x,y] = output; result = { x, y }; } else { const [x] = output; result = { x }; } } else { result = output; } return result; } function gpuMock(fn, settings = {}) { const output = settings.output ? setupOutput(settings.output) : null; function kernel() { if (kernel.output.z) { return mock3D.apply(kernel, arguments); } else if (kernel.output.y) { if (kernel.graphical) { return mock2DGraphical.apply(kernel, arguments); } return mock2D.apply(kernel, arguments); } else { return mock1D.apply(kernel, arguments); } } kernel._fn = fn; kernel.constants = settings.constants || null; kernel.context = settings.context || null; kernel.canvas = settings.canvas || null; kernel.graphical = settings.graphical || false; kernel._imageData = null; kernel._colorData = null; kernel.output = output; kernel.thread = { x: 0, y: 0, z: 0 }; return apiDecorate(kernel); } function flipPixels(pixels, width, height) { const halfHeight = height / 2 | 0; const bytesPerRow = width * 4; const temp = new Uint8ClampedArray(width * 4); const result = pixels.slice(0); for (let y = 0; y < halfHeight; ++y) { const topOffset = y * bytesPerRow; const bottomOffset = (height - y - 1) * bytesPerRow; temp.set(result.subarray(topOffset, topOffset + bytesPerRow)); result.copyWithin(topOffset, bottomOffset, bottomOffset + bytesPerRow); result.set(temp, bottomOffset); } return result; } module.exports = { gpuMock }; },{}],4:[function(require,module,exports){ const { utils } = require('./utils'); function alias(name, source) { const fnString = source.toString(); return new Function(`return function ${ name } (${ utils.getArgumentNamesFromString(fnString).join(', ') }) { ${ utils.getFunctionBodyFromString(fnString) } }`)(); } module.exports = { alias }; },{"./utils":113}],5:[function(require,module,exports){ const { FunctionNode } = require('../function-node'); class CPUFunctionNode extends FunctionNode { astFunction(ast, retArr) { if (!this.isRootKernel) { retArr.push('function'); retArr.push(' '); retArr.push(this.name); retArr.push('('); for (let i = 0; i < this.argumentNames.length; ++i) { const argumentName = this.argumentNames[i]; if (i > 0) { retArr.push(', '); } retArr.push('user_'); retArr.push(argumentName); } retArr.push(') {\n'); } for (let i = 0; i < ast.body.body.length; ++i) { this.astGeneric(ast.body.body[i], retArr); retArr.push('\n'); } if (!this.isRootKernel) { retArr.push('}\n'); } return retArr; } astReturnStatement(ast, retArr) { const type = this.returnType || this.getType(ast.argument); if (!this.returnType) { this.returnType = type; } if (this.isRootKernel) { retArr.push(this.leadingReturnStatement); this.astGeneric(ast.argument, retArr); retArr.push(';\n'); retArr.push(this.followingReturnStatement); retArr.push('continue;\n'); } else if (this.isSubKernel) { retArr.push(`subKernelResult_${ this.name } = `); this.astGeneric(ast.argument, retArr); retArr.push(';'); retArr.push(`return subKernelResult_${ this.name };`); } else { retArr.push('return '); this.astGeneric(ast.argument, retArr); retArr.push(';'); } return retArr; } astLiteral(ast, retArr) { if (isNaN(ast.value)) { throw this.astErrorOutput( 'Non-numeric literal not supported : ' + ast.value, ast ); } retArr.push(ast.value); return retArr; } astBinaryExpression(ast, retArr) { retArr.push('('); this.astGeneric(ast.left, retArr); retArr.push(ast.operator); this.astGeneric(ast.right, retArr); retArr.push(')'); return retArr; } astIdentifierExpression(idtNode, retArr) { if (idtNode.type !== 'Identifier') { throw this.astErrorOutput( 'IdentifierExpression - not an Identifier', idtNode ); } switch (idtNode.name) { case 'Infinity': retArr.push('Infinity'); break; default: if (this.constants && this.constants.hasOwnProperty(idtNode.name)) { retArr.push('constants_' + idtNode.name); } else { retArr.push('user_' + idtNode.name); } } return retArr; } astForStatement(forNode, retArr) { if (forNode.type !== 'ForStatement') { throw this.astErrorOutput('Invalid for statement', forNode); } const initArr = []; const testArr = []; const updateArr = []; const bodyArr = []; let isSafe = null; if (forNode.init) { this.pushState('in-for-loop-init'); this.astGeneric(forNode.init, initArr); for (let i = 0; i < initArr.length; i++) { if (initArr[i].includes && initArr[i].includes(',')) { isSafe = false; } } this.popState('in-for-loop-init'); } else { isSafe = false; } if (forNode.test) { this.astGeneric(forNode.test, testArr); } else { isSafe = false; } if (forNode.update) { this.astGeneric(forNode.update, updateArr); } else { isSafe = false; } if (forNode.body) { this.pushState('loop-body'); this.astGeneric(forNode.body, bodyArr); this.popState('loop-body'); } if (isSafe === null) { isSafe = this.isSafe(forNode.init) && this.isSafe(forNode.test); } if (isSafe) { retArr.push(`for (${initArr.join('')};${testArr.join('')};${updateArr.join('')}){\n`); retArr.push(bodyArr.join('')); retArr.push('}\n'); } else { const iVariableName = this.getInternalVariableName('safeI'); if (initArr.length > 0) { retArr.push(initArr.join(''), ';\n'); } retArr.push(`for (let ${iVariableName}=0;${iVariableName} 0) { retArr.push(`if (!${testArr.join('')}) break;\n`); } retArr.push(bodyArr.join('')); retArr.push(`\n${updateArr.join('')};`); retArr.push('}\n'); } return retArr; } astWhileStatement(whileNode, retArr) { if (whileNode.type !== 'WhileStatement') { throw this.astErrorOutput( 'Invalid while statement', whileNode ); } retArr.push('for (let i = 0; i < LOOP_MAX; i++) {'); retArr.push('if ('); this.astGeneric(whileNode.test, retArr); retArr.push(') {\n'); this.astGeneric(whileNode.body, retArr); retArr.push('} else {\n'); retArr.push('break;\n'); retArr.push('}\n'); retArr.push('}\n'); return retArr; } astDoWhileStatement(doWhileNode, retArr) { if (doWhileNode.type !== 'DoWhileStatement') { throw this.astErrorOutput( 'Invalid while statement', doWhileNode ); } retArr.push('for (let i = 0; i < LOOP_MAX; i++) {'); this.astGeneric(doWhileNode.body, retArr); retArr.push('if (!'); this.astGeneric(doWhileNode.test, retArr); retArr.push(') {\n'); retArr.push('break;\n'); retArr.push('}\n'); retArr.push('}\n'); return retArr; } astAssignmentExpression(assNode, retArr) { const declaration = this.getDeclaration(assNode.left); if (declaration && !declaration.assignable) { throw this.astErrorOutput(`Variable ${assNode.left.name} is not assignable here`, assNode); } this.astGeneric(assNode.left, retArr); retArr.push(assNode.operator); this.astGeneric(assNode.right, retArr); return retArr; } astBlockStatement(bNode, retArr) { if (this.isState('loop-body')) { this.pushState('block-body'); for (let i = 0; i < bNode.body.length; i++) { this.astGeneric(bNode.body[i], retArr); } this.popState('block-body'); } else { retArr.push('{\n'); for (let i = 0; i < bNode.body.length; i++) { this.astGeneric(bNode.body[i], retArr); } retArr.push('}\n'); } return retArr; } astVariableDeclaration(varDecNode, retArr) { retArr.push(`${varDecNode.kind} `); const { declarations } = varDecNode; for (let i = 0; i < declarations.length; i++) { if (i > 0) { retArr.push(','); } const declaration = declarations[i]; const info = this.getDeclaration(declaration.id); if (!info.valueType) { info.valueType = this.getType(declaration.init); } this.astGeneric(declaration, retArr); } if (!this.isState('in-for-loop-init')) { retArr.push(';'); } return retArr; } astIfStatement(ifNode, retArr) { retArr.push('if ('); this.astGeneric(ifNode.test, retArr); retArr.push(')'); if (ifNode.consequent.type === 'BlockStatement') { this.astGeneric(ifNode.consequent, retArr); } else { retArr.push(' {\n'); this.astGeneric(ifNode.consequent, retArr); retArr.push('\n}\n'); } if (ifNode.alternate) { retArr.push('else '); if (ifNode.alternate.type === 'BlockStatement' || ifNode.alternate.type === 'IfStatement') { this.astGeneric(ifNode.alternate, retArr); } else { retArr.push(' {\n'); this.astGeneric(ifNode.alternate, retArr); retArr.push('\n}\n'); } } return retArr; } astSwitchStatement(ast, retArr) { const { discriminant, cases } = ast; retArr.push('switch ('); this.astGeneric(discriminant, retArr); retArr.push(') {\n'); for (let i = 0; i < cases.length; i++) { if (cases[i].test === null) { retArr.push('default:\n'); this.astGeneric(cases[i].consequent, retArr); if (cases[i].consequent && cases[i].consequent.length > 0) { retArr.push('break;\n'); } continue; } retArr.push('case '); this.astGeneric(cases[i].test, retArr); retArr.push(':\n'); if (cases[i].consequent && cases[i].consequent.length > 0) { this.astGeneric(cases[i].consequent, retArr); retArr.push('break;\n'); } } retArr.push('\n}'); } astThisExpression(tNode, retArr) { retArr.push('_this'); return retArr; } astMemberExpression(mNode, retArr) { const { signature, type, property, xProperty, yProperty, zProperty, name, origin } = this.getMemberExpressionDetails(mNode); switch (signature) { case 'this.thread.value': retArr.push(`_this.thread.${ name }`); return retArr; case 'this.output.value': switch (name) { case 'x': retArr.push('outputX'); break; case 'y': retArr.push('outputY'); break; case 'z': retArr.push('outputZ'); break; default: throw this.astErrorOutput('Unexpected expression', mNode); } return retArr; case 'value': throw this.astErrorOutput('Unexpected expression', mNode); case 'value[]': case 'value[][]': case 'value[][][]': case 'value.value': if (origin === 'Math') { retArr.push(Math[name]); return retArr; } switch (property) { case 'r': retArr.push(`user_${ name }[0]`); return retArr; case 'g': retArr.push(`user_${ name }[1]`); return retArr; case 'b': retArr.push(`user_${ name }[2]`); return retArr; case 'a': retArr.push(`user_${ name }[3]`); return retArr; } break; case 'this.constants.value': case 'this.constants.value[]': case 'this.constants.value[][]': case 'this.constants.value[][][]': break; case 'fn()[]': this.astGeneric(mNode.object, retArr); retArr.push('['); this.astGeneric(mNode.property, retArr); retArr.push(']'); return retArr; case 'fn()[][]': this.astGeneric(mNode.object.object, retArr); retArr.push('['); this.astGeneric(mNode.object.property, retArr); retArr.push(']'); retArr.push('['); this.astGeneric(mNode.property, retArr); retArr.push(']'); return retArr; default: throw this.astErrorOutput('Unexpected expression', mNode); } if (!mNode.computed) { switch (type) { case 'Number': case 'Integer': case 'Float': case 'Boolean': retArr.push(`${origin}_${name}`); return retArr; } } const markupName = `${origin}_${name}`; switch (type) { case 'Array(2)': case 'Array(3)': case 'Array(4)': case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': case 'HTMLImageArray': case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': case 'HTMLImage': default: let size; let isInput; if (origin === 'constants') { const constant = this.constants[name]; isInput = this.constantTypes[name] === 'Input'; size = isInput ? constant.size : null; } else { isInput = this.isInput(name); size = isInput ? this.argumentSizes[this.argumentNames.indexOf(name)] : null; } retArr.push(`${ markupName }`); if (zProperty && yProperty) { if (isInput) { retArr.push('[('); this.astGeneric(zProperty, retArr); retArr.push(`*${ this.dynamicArguments ? '(outputY * outputX)' : size[1] * size[0] })+(`); this.astGeneric(yProperty, retArr); retArr.push(`*${ this.dynamicArguments ? 'outputX' : size[0] })+`); this.astGeneric(xProperty, retArr); retArr.push(']'); } else { retArr.push('['); this.astGeneric(zProperty, retArr); retArr.push(']'); retArr.push('['); this.astGeneric(yProperty, retArr); retArr.push(']'); retArr.push('['); this.astGeneric(xProperty, retArr); retArr.push(']'); } } else if (yProperty) { if (isInput) { retArr.push('[('); this.astGeneric(yProperty, retArr); retArr.push(`*${ this.dynamicArguments ? 'outputX' : size[0] })+`); this.astGeneric(xProperty, retArr); retArr.push(']'); } else { retArr.push('['); this.astGeneric(yProperty, retArr); retArr.push(']'); retArr.push('['); this.astGeneric(xProperty, retArr); retArr.push(']'); } } else if (typeof xProperty !== 'undefined') { retArr.push('['); this.astGeneric(xProperty, retArr); retArr.push(']'); } } return retArr; } astCallExpression(ast, retArr) { if (ast.type !== 'CallExpression') { throw this.astErrorOutput('Unknown CallExpression', ast); } let functionName = this.astMemberExpressionUnroll(ast.callee); if (this.calledFunctions.indexOf(functionName) < 0) { this.calledFunctions.push(functionName); } const isMathFunction = this.isAstMathFunction(ast); if (this.onFunctionCall) { this.onFunctionCall(this.name, functionName, ast.arguments); } retArr.push(functionName); retArr.push('('); const targetTypes = this.lookupFunctionArgumentTypes(functionName) || []; for (let i = 0; i < ast.arguments.length; ++i) { const argument = ast.arguments[i]; let argumentType = this.getType(argument); if (!targetTypes[i]) { this.triggerImplyArgumentType(functionName, i, argumentType, this); } if (i > 0) { retArr.push(', '); } this.astGeneric(argument, retArr); } retArr.push(')'); return retArr; } astArrayExpression(arrNode, retArr) { const returnType = this.getType(arrNode); const arrLen = arrNode.elements.length; const elements = []; for (let i = 0; i < arrLen; ++i) { const element = []; this.astGeneric(arrNode.elements[i], element); elements.push(element.join('')); } switch (returnType) { case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': retArr.push(`[${elements.join(', ')}]`); break; default: retArr.push(`new Float32Array([${elements.join(', ')}])`); } return retArr; } astDebuggerStatement(arrNode, retArr) { retArr.push('debugger;'); return retArr; } } module.exports = { CPUFunctionNode }; },{"../function-node":9}],6:[function(require,module,exports){ const { utils } = require('../../utils'); function constantsToString(constants, types) { const results = []; for (const name in types) { if (!types.hasOwnProperty(name)) continue; const type = types[name]; const constant = constants[name]; switch (type) { case 'Number': case 'Integer': case 'Float': case 'Boolean': results.push(`${name}:${constant}`); break; case 'Array(2)': case 'Array(3)': case 'Array(4)': case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': results.push(`${name}:new ${constant.constructor.name}(${JSON.stringify(Array.from(constant))})`); break; } } return `{ ${ results.join() } }`; } function cpuKernelString(cpuKernel, name) { const header = []; const thisProperties = []; const beforeReturn = []; const useFunctionKeyword = !/^function/.test(cpuKernel.color.toString()); header.push( ' const { context, canvas, constants: incomingConstants } = settings;', ` const output = new Int32Array(${JSON.stringify(Array.from(cpuKernel.output))});`, ` const _constantTypes = ${JSON.stringify(cpuKernel.constantTypes)};`, ` const _constants = ${constantsToString(cpuKernel.constants, cpuKernel.constantTypes)};` ); thisProperties.push( ' constants: _constants,', ' context,', ' output,', ' thread: {x: 0, y: 0, z: 0},' ); if (cpuKernel.graphical) { header.push(` const _imageData = context.createImageData(${cpuKernel.output[0]}, ${cpuKernel.output[1]});`); header.push(` const _colorData = new Uint8ClampedArray(${cpuKernel.output[0]} * ${cpuKernel.output[1]} * 4);`); const colorFn = utils.flattenFunctionToString((useFunctionKeyword ? 'function ' : '') + cpuKernel.color.toString(), { thisLookup: (propertyName) => { switch (propertyName) { case '_colorData': return '_colorData'; case '_imageData': return '_imageData'; case 'output': return 'output'; case 'thread': return 'this.thread'; } return JSON.stringify(cpuKernel[propertyName]); }, findDependency: (object, name) => { return null; } }); const getPixelsFn = utils.flattenFunctionToString((useFunctionKeyword ? 'function ' : '') + cpuKernel.getPixels.toString(), { thisLookup: (propertyName) => { switch (propertyName) { case '_colorData': return '_colorData'; case '_imageData': return '_imageData'; case 'output': return 'output'; case 'thread': return 'this.thread'; } return JSON.stringify(cpuKernel[propertyName]); }, findDependency: () => { return null; } }); thisProperties.push( ' _imageData,', ' _colorData,', ` color: ${colorFn},` ); beforeReturn.push( ` kernel.getPixels = ${getPixelsFn};` ); } const constantTypes = []; const constantKeys = Object.keys(cpuKernel.constantTypes); for (let i = 0; i < constantKeys.length; i++) { constantTypes.push(cpuKernel.constantTypes[constantKeys]); } if (cpuKernel.argumentTypes.indexOf('HTMLImageArray') !== -1 || constantTypes.indexOf('HTMLImageArray') !== -1) { const flattenedImageTo3DArray = utils.flattenFunctionToString((useFunctionKeyword ? 'function ' : '') + cpuKernel._imageTo3DArray.toString(), { doNotDefine: ['canvas'], findDependency: (object, name) => { if (object === 'this') { return (useFunctionKeyword ? 'function ' : '') + cpuKernel[name].toString(); } return null; }, thisLookup: (propertyName) => { switch (propertyName) { case 'canvas': return; case 'context': return 'context'; } } }); beforeReturn.push(flattenedImageTo3DArray); thisProperties.push(` _mediaTo2DArray,`); thisProperties.push(` _imageTo3DArray,`); } else if (cpuKernel.argumentTypes.indexOf('HTMLImage') !== -1 || constantTypes.indexOf('HTMLImage') !== -1) { const flattenedImageTo2DArray = utils.flattenFunctionToString((useFunctionKeyword ? 'function ' : '') + cpuKernel._mediaTo2DArray.toString(), { findDependency: (object, name) => { return null; }, thisLookup: (propertyName) => { switch (propertyName) { case 'canvas': return 'settings.canvas'; case 'context': return 'settings.context'; } throw new Error('unhandled thisLookup'); } }); beforeReturn.push(flattenedImageTo2DArray); thisProperties.push(` _mediaTo2DArray,`); } return `function(settings) { ${ header.join('\n') } for (const p in _constantTypes) { if (!_constantTypes.hasOwnProperty(p)) continue; const type = _constantTypes[p]; switch (type) { case 'Number': case 'Integer': case 'Float': case 'Boolean': case 'Array(2)': case 'Array(3)': case 'Array(4)': case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': if (incomingConstants.hasOwnProperty(p)) { console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned'); } continue; } if (!incomingConstants.hasOwnProperty(p)) { throw new Error('constant ' + p + ' not found'); } _constants[p] = incomingConstants[p]; } const kernel = (function() { ${cpuKernel._kernelString} }) .apply({ ${thisProperties.join('\n')} }); ${ beforeReturn.join('\n') } return kernel; }`; } module.exports = { cpuKernelString }; },{"../../utils":113}],7:[function(require,module,exports){ const { Kernel } = require('../kernel'); const { FunctionBuilder } = require('../function-builder'); const { CPUFunctionNode } = require('./function-node'); const { utils } = require('../../utils'); const { cpuKernelString } = require('./kernel-string'); class CPUKernel extends Kernel { static getFeatures() { return this.features; } static get features() { return Object.freeze({ kernelMap: true, isIntegerDivisionAccurate: true }); } static get isSupported() { return true; } static isContextMatch(context) { return false; } static get mode() { return 'cpu'; } static nativeFunctionArguments() { return null; } static nativeFunctionReturnType() { throw new Error(`Looking up native function return type not supported on ${this.name}`); } static combineKernels(combinedKernel) { return combinedKernel; } static getSignature(kernel, argumentTypes) { return 'cpu' + (argumentTypes.length > 0 ? ':' + argumentTypes.join(',') : ''); } constructor(source, settings) { super(source, settings); this.mergeSettings(source.settings || settings); this._imageData = null; this._colorData = null; this._kernelString = null; this._prependedString = []; this.thread = { x: 0, y: 0, z: 0 }; this.translatedSources = null; } initCanvas() { if (typeof document !== 'undefined') { return document.createElement('canvas'); } else if (typeof OffscreenCanvas !== 'undefined') { return new OffscreenCanvas(0, 0); } } initContext() { if (!this.canvas) return null; return this.canvas.getContext('2d'); } initPlugins(settings) { return []; } validateSettings(args) { if (!this.output || this.output.length === 0) { if (args.length !== 1) { throw new Error('Auto output only supported for kernels with only one input'); } const argType = utils.getVariableType(args[0], this.strictIntegers); if (argType === 'Array') { this.output = utils.getDimensions(argType); } else if (argType === 'NumberTexture' || argType === 'ArrayTexture(4)') { this.output = args[0].output; } else { throw new Error('Auto output not supported for input type: ' + argType); } } if (this.graphical) { if (this.output.length !== 2) { throw new Error('Output must have 2 dimensions on graphical mode'); } } this.checkOutput(); } translateSource() { this.leadingReturnStatement = this.output.length > 1 ? 'resultX[x] = ' : 'result[x] = '; if (this.subKernels) { const followingReturnStatement = []; for (let i = 0; i < this.subKernels.length; i++) { const { name } = this.subKernels[i]; followingReturnStatement.push(this.output.length > 1 ? `resultX_${ name }[x] = subKernelResult_${ name };\n` : `result_${ name }[x] = subKernelResult_${ name };\n`); } this.followingReturnStatement = followingReturnStatement.join(''); } const functionBuilder = FunctionBuilder.fromKernel(this, CPUFunctionNode); this.translatedSources = functionBuilder.getPrototypes('kernel'); if (!this.graphical && !this.returnType) { this.returnType = functionBuilder.getKernelResultType(); } } build() { if (this.built) return; this.setupConstants(); this.setupArguments(arguments); this.validateSettings(arguments); this.translateSource(); if (this.graphical) { const { canvas, output } = this; if (!canvas) { throw new Error('no canvas available for using graphical output'); } const width = output[0]; const height = output[1] || 1; canvas.width = width; canvas.height = height; this._imageData = this.context.createImageData(width, height); this._colorData = new Uint8ClampedArray(width * height * 4); } const kernelString = this.getKernelString(); this.kernelString = kernelString; if (this.debug) { console.log('Function output:'); console.log(kernelString); } try { this.run = new Function([], kernelString).bind(this)(); } catch (e) { console.error('An error occurred compiling the javascript: ', e); } this.buildSignature(arguments); this.built = true; } color(r, g, b, a) { if (typeof a === 'undefined') { a = 1; } r = Math.floor(r * 255); g = Math.floor(g * 255); b = Math.floor(b * 255); a = Math.floor(a * 255); const width = this.output[0]; const height = this.output[1]; const x = this.thread.x; const y = height - this.thread.y - 1; const index = x + y * width; this._colorData[index * 4 + 0] = r; this._colorData[index * 4 + 1] = g; this._colorData[index * 4 + 2] = b; this._colorData[index * 4 + 3] = a; } getKernelString() { if (this._kernelString !== null) return this._kernelString; let kernelThreadString = null; let { translatedSources } = this; if (translatedSources.length > 1) { translatedSources = translatedSources.filter(fn => { if (/^function/.test(fn)) return fn; kernelThreadString = fn; return false; }); } else { kernelThreadString = translatedSources.shift(); } return this._kernelString = ` const LOOP_MAX = ${ this._getLoopMaxString() }; ${ this.injectedNative || '' } const _this = this; ${ this._resultKernelHeader() } ${ this._processConstants() } return (${ this.argumentNames.map(argumentName => 'user_' + argumentName).join(', ') }) => { ${ this._prependedString.join('') } ${ this._earlyThrows() } ${ this._processArguments() } ${ this.graphical ? this._graphicalKernelBody(kernelThreadString) : this._resultKernelBody(kernelThreadString) } ${ translatedSources.length > 0 ? translatedSources.join('\n') : '' } };`; } toString() { return cpuKernelString(this); } _getLoopMaxString() { return ( this.loopMaxIterations ? ` ${ parseInt(this.loopMaxIterations) };` : ' 1000;' ); } _processConstants() { if (!this.constants) return ''; const result = []; for (let p in this.constants) { const type = this.constantTypes[p]; switch (type) { case 'HTMLCanvas': case 'OffscreenCanvas': case 'HTMLImage': case 'ImageBitmap': case 'ImageData': case 'HTMLVideo': result.push(` const constants_${p} = this._mediaTo2DArray(this.constants.${p});\n`); break; case 'HTMLImageArray': result.push(` const constants_${p} = this._imageTo3DArray(this.constants.${p});\n`); break; case 'Input': result.push(` const constants_${p} = this.constants.${p}.value;\n`); break; default: result.push(` const constants_${p} = this.constants.${p};\n`); } } return result.join(''); } _earlyThrows() { if (this.graphical) return ''; if (this.immutable) return ''; if (!this.pipeline) return ''; const arrayArguments = []; for (let i = 0; i < this.argumentTypes.length; i++) { if (this.argumentTypes[i] === 'Array') { arrayArguments.push(this.argumentNames[i]); } } if (arrayArguments.length === 0) return ''; const checks = []; for (let i = 0; i < arrayArguments.length; i++) { const argumentName = arrayArguments[i]; const checkSubKernels = this._mapSubKernels(subKernel => `user_${argumentName} === result_${subKernel.name}`).join(' || '); checks.push(`user_${argumentName} === result${checkSubKernels ? ` || ${checkSubKernels}` : ''}`); } return `if (${checks.join(' || ')}) throw new Error('Source and destination arrays are the same. Use immutable = true');`; } _processArguments() { const result = []; for (let i = 0; i < this.argumentTypes.length; i++) { const variableName = `user_${this.argumentNames[i]}`; switch (this.argumentTypes[i]) { case 'HTMLCanvas': case 'OffscreenCanvas': case 'HTMLImage': case 'ImageBitmap': case 'ImageData': case 'HTMLVideo': result.push(` ${variableName} = this._mediaTo2DArray(${variableName});\n`); break; case 'HTMLImageArray': result.push(` ${variableName} = this._imageTo3DArray(${variableName});\n`); break; case 'Input': result.push(` ${variableName} = ${variableName}.value;\n`); break; case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': case 'NumberTexture': case 'MemoryOptimizedNumberTexture': result.push(` if (${variableName}.toArray) { if (!_this.textureCache) { _this.textureCache = []; _this.arrayCache = []; } const textureIndex = _this.textureCache.indexOf(${variableName}); if (textureIndex !== -1) { ${variableName} = _this.arrayCache[textureIndex]; } else { _this.textureCache.push(${variableName}); ${variableName} = ${variableName}.toArray(); _this.arrayCache.push(${variableName}); } }`); break; } } return result.join(''); } _mediaTo2DArray(media) { const canvas = this.canvas; const width = media.width > 0 ? media.width : media.videoWidth; const height = media.height > 0 ? media.height : media.videoHeight; if (canvas.width < width) { canvas.width = width; } if (canvas.height < height) { canvas.height = height; } const ctx = this.context; let pixelsData; if (media.constructor === ImageData) { pixelsData = media.data; } else { ctx.drawImage(media, 0, 0, width, height); pixelsData = ctx.getImageData(0, 0, width, height).data; } const imageArray = new Array(height); let index = 0; for (let y = height - 1; y >= 0; y--) { const row = imageArray[y] = new Array(width); for (let x = 0; x < width; x++) { const pixel = new Float32Array(4); pixel[0] = pixelsData[index++] / 255; pixel[1] = pixelsData[index++] / 255; pixel[2] = pixelsData[index++] / 255; pixel[3] = pixelsData[index++] / 255; row[x] = pixel; } } return imageArray; } getPixels(flip) { const [width, height] = this.output; return flip ? utils.flipPixels(this._imageData.data, width, height) : this._imageData.data.slice(0); } _imageTo3DArray(images) { const imagesArray = new Array(images.length); for (let i = 0; i < images.length; i++) { imagesArray[i] = this._mediaTo2DArray(images[i]); } return imagesArray; } _resultKernelHeader() { if (this.graphical) return ''; if (this.immutable) return ''; if (!this.pipeline) return ''; switch (this.output.length) { case 1: return this._mutableKernel1DResults(); case 2: return this._mutableKernel2DResults(); case 3: return this._mutableKernel3DResults(); } } _resultKernelBody(kernelString) { switch (this.output.length) { case 1: return (!this.immutable && this.pipeline ? this._resultMutableKernel1DLoop(kernelString) : this._resultImmutableKernel1DLoop(kernelString)) + this._kernelOutput(); case 2: return (!this.immutable && this.pipeline ? this._resultMutableKernel2DLoop(kernelString) : this._resultImmutableKernel2DLoop(kernelString)) + this._kernelOutput(); case 3: return (!this.immutable && this.pipeline ? this._resultMutableKernel3DLoop(kernelString) : this._resultImmutableKernel3DLoop(kernelString)) + this._kernelOutput(); default: throw new Error('unsupported size kernel'); } } _graphicalKernelBody(kernelThreadString) { switch (this.output.length) { case 2: return this._graphicalKernel2DLoop(kernelThreadString) + this._graphicalOutput(); default: throw new Error('unsupported size kernel'); } } _graphicalOutput() { return ` this._imageData.data.set(this._colorData); this.context.putImageData(this._imageData, 0, 0); return;` } _getKernelResultTypeConstructorString() { switch (this.returnType) { case 'LiteralInteger': case 'Number': case 'Integer': case 'Float': return 'Float32Array'; case 'Array(2)': case 'Array(3)': case 'Array(4)': return 'Array'; default: if (this.graphical) { return 'Float32Array'; } throw new Error(`unhandled returnType ${ this.returnType }`); } } _resultImmutableKernel1DLoop(kernelString) { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const result = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new ${constructorString}(outputX);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') } for (let x = 0; x < outputX; x++) { this.thread.x = x; this.thread.y = 0; this.thread.z = 0; ${ kernelString } }`; } _mutableKernel1DResults() { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const result = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new ${constructorString}(outputX);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') }`; } _resultMutableKernel1DLoop(kernelString) { return ` const outputX = _this.output[0]; for (let x = 0; x < outputX; x++) { this.thread.x = x; this.thread.y = 0; this.thread.z = 0; ${ kernelString } }`; } _resultImmutableKernel2DLoop(kernelString) { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const outputY = _this.output[1]; const result = new Array(outputY); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new Array(outputY);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') } for (let y = 0; y < outputY; y++) { this.thread.z = 0; this.thread.y = y; const resultX = result[y] = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const resultX_${ subKernel.name } = result_${subKernel.name}[y] = new ${constructorString}(outputX);\n`).join('') } for (let x = 0; x < outputX; x++) { this.thread.x = x; ${ kernelString } } }`; } _mutableKernel2DResults() { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const outputY = _this.output[1]; const result = new Array(outputY); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new Array(outputY);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') } for (let y = 0; y < outputY; y++) { const resultX = result[y] = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const resultX_${ subKernel.name } = result_${subKernel.name}[y] = new ${constructorString}(outputX);\n`).join('') } }`; } _resultMutableKernel2DLoop(kernelString) { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const outputY = _this.output[1]; for (let y = 0; y < outputY; y++) { this.thread.z = 0; this.thread.y = y; const resultX = result[y]; ${ this._mapSubKernels(subKernel => `const resultX_${ subKernel.name } = result_${subKernel.name}[y] = new ${constructorString}(outputX);\n`).join('') } for (let x = 0; x < outputX; x++) { this.thread.x = x; ${ kernelString } } }`; } _graphicalKernel2DLoop(kernelString) { return ` const outputX = _this.output[0]; const outputY = _this.output[1]; for (let y = 0; y < outputY; y++) { this.thread.z = 0; this.thread.y = y; for (let x = 0; x < outputX; x++) { this.thread.x = x; ${ kernelString } } }`; } _resultImmutableKernel3DLoop(kernelString) { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const outputY = _this.output[1]; const outputZ = _this.output[2]; const result = new Array(outputZ); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new Array(outputZ);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') } for (let z = 0; z < outputZ; z++) { this.thread.z = z; const resultY = result[z] = new Array(outputY); ${ this._mapSubKernels(subKernel => `const resultY_${ subKernel.name } = result_${subKernel.name}[z] = new Array(outputY);\n`).join(' ') } for (let y = 0; y < outputY; y++) { this.thread.y = y; const resultX = resultY[y] = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const resultX_${ subKernel.name } = resultY_${subKernel.name}[y] = new ${constructorString}(outputX);\n`).join(' ') } for (let x = 0; x < outputX; x++) { this.thread.x = x; ${ kernelString } } } }`; } _mutableKernel3DResults() { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const outputY = _this.output[1]; const outputZ = _this.output[2]; const result = new Array(outputZ); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new Array(outputZ);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') } for (let z = 0; z < outputZ; z++) { const resultY = result[z] = new Array(outputY); ${ this._mapSubKernels(subKernel => `const resultY_${ subKernel.name } = result_${subKernel.name}[z] = new Array(outputY);\n`).join(' ') } for (let y = 0; y < outputY; y++) { const resultX = resultY[y] = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const resultX_${ subKernel.name } = resultY_${subKernel.name}[y] = new ${constructorString}(outputX);\n`).join(' ') } } }`; } _resultMutableKernel3DLoop(kernelString) { return ` const outputX = _this.output[0]; const outputY = _this.output[1]; const outputZ = _this.output[2]; for (let z = 0; z < outputZ; z++) { this.thread.z = z; const resultY = result[z]; for (let y = 0; y < outputY; y++) { this.thread.y = y; const resultX = resultY[y]; for (let x = 0; x < outputX; x++) { this.thread.x = x; ${ kernelString } } } }`; } _kernelOutput() { if (!this.subKernels) { return '\n return result;'; } return `\n return { result: result, ${ this.subKernels.map(subKernel => `${ subKernel.property }: result_${ subKernel.name }`).join(',\n ') } };`; } _mapSubKernels(fn) { return this.subKernels === null ? [''] : this.subKernels.map(fn); } destroy(removeCanvasReference) { if (removeCanvasReference) { delete this.canvas; } } static destroyContext(context) {} toJSON() { const json = super.toJSON(); json.functionNodes = FunctionBuilder.fromKernel(this, CPUFunctionNode).toJSON(); return json; } setOutput(output) { super.setOutput(output); const [width, height] = this.output; if (this.graphical) { this._imageData = this.context.createImageData(width, height); this._colorData = new Uint8ClampedArray(width * height * 4); } } prependString(value) { if (this._kernelString) throw new Error('Kernel already built'); this._prependedString.push(value); } hasPrependString(value) { return this._prependedString.indexOf(value) > -1; } } module.exports = { CPUKernel }; },{"../../utils":113,"../function-builder":8,"../kernel":35,"./function-node":5,"./kernel-string":6}],8:[function(require,module,exports){ class FunctionBuilder { static fromKernel(kernel, FunctionNode, extraNodeOptions) { const { kernelArguments, kernelConstants, argumentNames, argumentSizes, argumentBitRatios, constants, constantBitRatios, debug, loopMaxIterations, nativeFunctions, output, optimizeFloatMemory, precision, plugins, source, subKernels, functions, leadingReturnStatement, followingReturnStatement, dynamicArguments, dynamicOutput, } = kernel; const argumentTypes = new Array(kernelArguments.length); const constantTypes = {}; for (let i = 0; i < kernelArguments.length; i++) { argumentTypes[i] = kernelArguments[i].type; } for (let i = 0; i < kernelConstants.length; i++) { const kernelConstant = kernelConstants[i]; constantTypes[kernelConstant.name] = kernelConstant.type; } const needsArgumentType = (functionName, index) => { return functionBuilder.needsArgumentType(functionName, index); }; const assignArgumentType = (functionName, index, type) => { functionBuilder.assignArgumentType(functionName, index, type); }; const lookupReturnType = (functionName, ast, requestingNode) => { return functionBuilder.lookupReturnType(functionName, ast, requestingNode); }; const lookupFunctionArgumentTypes = (functionName) => { return functionBuilder.lookupFunctionArgumentTypes(functionName); }; const lookupFunctionArgumentName = (functionName, argumentIndex) => { return functionBuilder.lookupFunctionArgumentName(functionName, argumentIndex); }; const lookupFunctionArgumentBitRatio = (functionName, argumentName) => { return functionBuilder.lookupFunctionArgumentBitRatio(functionName, argumentName); }; const triggerImplyArgumentType = (functionName, i, argumentType, requestingNode) => { functionBuilder.assignArgumentType(functionName, i, argumentType, requestingNode); }; const triggerImplyArgumentBitRatio = (functionName, argumentName, calleeFunctionName, argumentIndex) => { functionBuilder.assignArgumentBitRatio(functionName, argumentName, calleeFunctionName, argumentIndex); }; const onFunctionCall = (functionName, calleeFunctionName, args) => { functionBuilder.trackFunctionCall(functionName, calleeFunctionName, args); }; const onNestedFunction = (ast, source) => { const argumentNames = []; for (let i = 0; i < ast.params.length; i++) { argumentNames.push(ast.params[i].name); } const nestedFunction = new FunctionNode(source, Object.assign({}, nodeOptions, { returnType: null, ast, name: ast.id.name, argumentNames, lookupReturnType, lookupFunctionArgumentTypes, lookupFunctionArgumentName, lookupFunctionArgumentBitRatio, needsArgumentType, assignArgumentType, triggerImplyArgumentType, triggerImplyArgumentBitRatio, onFunctionCall, })); nestedFunction.traceFunctionAST(ast); functionBuilder.addFunctionNode(nestedFunction); }; const nodeOptions = Object.assign({ isRootKernel: false, onNestedFunction, lookupReturnType, lookupFunctionArgumentTypes, lookupFunctionArgumentName, lookupFunctionArgumentBitRatio, needsArgumentType, assignArgumentType, triggerImplyArgumentType, triggerImplyArgumentBitRatio, onFunctionCall, optimizeFloatMemory, precision, constants, constantTypes, constantBitRatios, debug, loopMaxIterations, output, plugins, dynamicArguments, dynamicOutput, }, extraNodeOptions || {}); const rootNodeOptions = Object.assign({}, nodeOptions, { isRootKernel: true, name: 'kernel', argumentNames, argumentTypes, argumentSizes, argumentBitRatios, leadingReturnStatement, followingReturnStatement, }); if (typeof source === 'object' && source.functionNodes) { return new FunctionBuilder().fromJSON(source.functionNodes, FunctionNode); } const rootNode = new FunctionNode(source, rootNodeOptions); let functionNodes = null; if (functions) { functionNodes = functions.map((fn) => new FunctionNode(fn.source, { returnType: fn.returnType, argumentTypes: fn.argumentTypes, output, plugins, constants, constantTypes, constantBitRatios, optimizeFloatMemory, precision, lookupReturnType, lookupFunctionArgumentTypes, lookupFunctionArgumentName, lookupFunctionArgumentBitRatio, needsArgumentType, assignArgumentType, triggerImplyArgumentType, triggerImplyArgumentBitRatio, onFunctionCall, onNestedFunction, })); } let subKernelNodes = null; if (subKernels) { subKernelNodes = subKernels.map((subKernel) => { const { name, source } = subKernel; return new FunctionNode(source, Object.assign({}, nodeOptions, { name, isSubKernel: true, isRootKernel: false, })); }); } const functionBuilder = new FunctionBuilder({ kernel, rootNode, functionNodes, nativeFunctions, subKernelNodes }); return functionBuilder; } constructor(settings) { settings = settings || {}; this.kernel = settings.kernel; this.rootNode = settings.rootNode; this.functionNodes = settings.functionNodes || []; this.subKernelNodes = settings.subKernelNodes || []; this.nativeFunctions = settings.nativeFunctions || []; this.functionMap = {}; this.nativeFunctionNames = []; this.lookupChain = []; this.functionNodeDependencies = {}; this.functionCalls = {}; if (this.rootNode) { this.functionMap['kernel'] = this.rootNode; } if (this.functionNodes) { for (let i = 0; i < this.functionNodes.length; i++) { this.functionMap[this.functionNodes[i].name] = this.functionNodes[i]; } } if (this.subKernelNodes) { for (let i = 0; i < this.subKernelNodes.length; i++) { this.functionMap[this.subKernelNodes[i].name] = this.subKernelNodes[i]; } } if (this.nativeFunctions) { for (let i = 0; i < this.nativeFunctions.length; i++) { const nativeFunction = this.nativeFunctions[i]; this.nativeFunctionNames.push(nativeFunction.name); } } } addFunctionNode(functionNode) { if (!functionNode.name) throw new Error('functionNode.name needs set'); this.functionMap[functionNode.name] = functionNode; if (functionNode.isRootKernel) { this.rootNode = functionNode; } } traceFunctionCalls(functionName, retList) { functionName = functionName || 'kernel'; retList = retList || []; if (this.nativeFunctionNames.indexOf(functionName) > -1) { const nativeFunctionIndex = retList.indexOf(functionName); if (nativeFunctionIndex === -1) { retList.push(functionName); } else { const dependantNativeFunctionName = retList.splice(nativeFunctionIndex, 1)[0]; retList.push(dependantNativeFunctionName); } return retList; } const functionNode = this.functionMap[functionName]; if (functionNode) { const functionIndex = retList.indexOf(functionName); if (functionIndex === -1) { retList.push(functionName); functionNode.toString(); for (let i = 0; i < functionNode.calledFunctions.length; ++i) { this.traceFunctionCalls(functionNode.calledFunctions[i], retList); } } else { const dependantFunctionName = retList.splice(functionIndex, 1)[0]; retList.push(dependantFunctionName); } } return retList; } getPrototypeString(functionName) { return this.getPrototypes(functionName).join('\n'); } getPrototypes(functionName) { if (this.rootNode) { this.rootNode.toString(); } if (functionName) { return this.getPrototypesFromFunctionNames(this.traceFunctionCalls(functionName, []).reverse()); } return this.getPrototypesFromFunctionNames(Object.keys(this.functionMap)); } getStringFromFunctionNames(functionList) { const ret = []; for (let i = 0; i < functionList.length; ++i) { const node = this.functionMap[functionList[i]]; if (node) { ret.push(this.functionMap[functionList[i]].toString()); } } return ret.join('\n'); } getPrototypesFromFunctionNames(functionList) { const ret = []; for (let i = 0; i < functionList.length; ++i) { const functionName = functionList[i]; const functionIndex = this.nativeFunctionNames.indexOf(functionName); if (functionIndex > -1) { ret.push(this.nativeFunctions[functionIndex].source); continue; } const node = this.functionMap[functionName]; if (node) { ret.push(node.toString()); } } return ret; } toJSON() { return this.traceFunctionCalls(this.rootNode.name).reverse().map(name => { const nativeIndex = this.nativeFunctions.indexOf(name); if (nativeIndex > -1) { return { name, source: this.nativeFunctions[nativeIndex].source }; } else if (this.functionMap[name]) { return this.functionMap[name].toJSON(); } else { throw new Error(`function ${ name } not found`); } }); } fromJSON(jsonFunctionNodes, FunctionNode) { this.functionMap = {}; for (let i = 0; i < jsonFunctionNodes.length; i++) { const jsonFunctionNode = jsonFunctionNodes[i]; this.functionMap[jsonFunctionNode.settings.name] = new FunctionNode(jsonFunctionNode.ast, jsonFunctionNode.settings); } return this; } getString(functionName) { if (functionName) { return this.getStringFromFunctionNames(this.traceFunctionCalls(functionName).reverse()); } return this.getStringFromFunctionNames(Object.keys(this.functionMap)); } lookupReturnType(functionName, ast, requestingNode) { if (ast.type !== 'CallExpression') { throw new Error(`expected ast type of "CallExpression", but is ${ ast.type }`); } if (this._isNativeFunction(functionName)) { return this._lookupNativeFunctionReturnType(functionName); } else if (this._isFunction(functionName)) { const node = this._getFunction(functionName); if (node.returnType) { return node.returnType; } else { for (let i = 0; i < this.lookupChain.length; i++) { if (this.lookupChain[i].ast === ast) { if (node.argumentTypes.length === 0 && ast.arguments.length > 0) { const args = ast.arguments; for (let j = 0; j < args.length; j++) { this.lookupChain.push({ name: requestingNode.name, ast: args[i], requestingNode }); node.argumentTypes[j] = requestingNode.getType(args[j]); this.lookupChain.pop(); } return node.returnType = node.getType(node.getJsAST()); } throw new Error('circlical logic detected!'); } } this.lookupChain.push({ name: requestingNode.name, ast, requestingNode }); const type = node.getType(node.getJsAST()); this.lookupChain.pop(); return node.returnType = type; } } return null; } _getFunction(functionName) { if (!this._isFunction(functionName)) { new Error(`Function ${functionName} not found`); } return this.functionMap[functionName]; } _isFunction(functionName) { return Boolean(this.functionMap[functionName]); } _getNativeFunction(functionName) { for (let i = 0; i < this.nativeFunctions.length; i++) { if (this.nativeFunctions[i].name === functionName) return this.nativeFunctions[i]; } return null; } _isNativeFunction(functionName) { return Boolean(this._getNativeFunction(functionName)); } _lookupNativeFunctionReturnType(functionName) { let nativeFunction = this._getNativeFunction(functionName); if (nativeFunction) { return nativeFunction.returnType; } throw new Error(`Native function ${ functionName } not found`); } lookupFunctionArgumentTypes(functionName) { if (this._isNativeFunction(functionName)) { return this._getNativeFunction(functionName).argumentTypes; } else if (this._isFunction(functionName)) { return this._getFunction(functionName).argumentTypes; } return null; } lookupFunctionArgumentName(functionName, argumentIndex) { return this._getFunction(functionName).argumentNames[argumentIndex]; } lookupFunctionArgumentBitRatio(functionName, argumentName) { if (!this._isFunction(functionName)) { throw new Error('function not found'); } if (this.rootNode.name === functionName) { const i = this.rootNode.argumentNames.indexOf(argumentName); if (i !== -1) { return this.rootNode.argumentBitRatios[i]; } } const node = this._getFunction(functionName); const i = node.argumentNames.indexOf(argumentName); if (i === -1) { throw new Error('argument not found'); } const bitRatio = node.argumentBitRatios[i]; if (typeof bitRatio !== 'number') { throw new Error('argument bit ratio not found'); } return bitRatio; } needsArgumentType(functionName, i) { if (!this._isFunction(functionName)) return false; const fnNode = this._getFunction(functionName); return !fnNode.argumentTypes[i]; } assignArgumentType(functionName, i, argumentType, requestingNode) { if (!this._isFunction(functionName)) return; const fnNode = this._getFunction(functionName); if (!fnNode.argumentTypes[i]) { fnNode.argumentTypes[i] = argumentType; } } assignArgumentBitRatio(functionName, argumentName, calleeFunctionName, argumentIndex) { const node = this._getFunction(functionName); if (this._isNativeFunction(calleeFunctionName)) return null; const calleeNode = this._getFunction(calleeFunctionName); const i = node.argumentNames.indexOf(argumentName); if (i === -1) { throw new Error(`Argument ${argumentName} not found in arguments from function ${functionName}`); } const bitRatio = node.argumentBitRatios[i]; if (typeof bitRatio !== 'number') { throw new Error(`Bit ratio for argument ${argumentName} not found in function ${functionName}`); } if (!calleeNode.argumentBitRatios) { calleeNode.argumentBitRatios = new Array(calleeNode.argumentNames.length); } const calleeBitRatio = calleeNode.argumentBitRatios[i]; if (typeof calleeBitRatio === 'number') { if (calleeBitRatio !== bitRatio) { throw new Error(`Incompatible bit ratio found at function ${functionName} at argument ${argumentName}`); } return calleeBitRatio; } calleeNode.argumentBitRatios[i] = bitRatio; return bitRatio; } trackFunctionCall(functionName, calleeFunctionName, args) { if (!this.functionNodeDependencies[functionName]) { this.functionNodeDependencies[functionName] = new Set(); this.functionCalls[functionName] = []; } this.functionNodeDependencies[functionName].add(calleeFunctionName); this.functionCalls[functionName].push(args); } getKernelResultType() { return this.rootNode.returnType || this.rootNode.getType(this.rootNode.ast); } getSubKernelResultType(index) { const subKernelNode = this.subKernelNodes[index]; let called = false; for (let functionCallIndex = 0; functionCallIndex < this.rootNode.functionCalls.length; functionCallIndex++) { const functionCall = this.rootNode.functionCalls[functionCallIndex]; if (functionCall.ast.callee.name === subKernelNode.name) { called = true; } } if (!called) { throw new Error(`SubKernel ${ subKernelNode.name } never called by kernel`); } return subKernelNode.returnType || subKernelNode.getType(subKernelNode.getJsAST()); } getReturnTypes() { const result = { [this.rootNode.name]: this.rootNode.getType(this.rootNode.ast), }; const list = this.traceFunctionCalls(this.rootNode.name); for (let i = 0; i < list.length; i++) { const functionName = list[i]; const functionNode = this.functionMap[functionName]; result[functionName] = functionNode.getType(functionNode.ast); } return result; } } module.exports = { FunctionBuilder }; },{}],9:[function(require,module,exports){ const acorn = require('acorn'); const { utils } = require('../utils'); const { FunctionTracer } = require('./function-tracer'); class FunctionNode { constructor(source, settings) { if (!source && !settings.ast) { throw new Error('source parameter is missing'); } settings = settings || {}; this.source = source; this.ast = null; this.name = typeof source === 'string' ? settings.isRootKernel ? 'kernel' : (settings.name || utils.getFunctionNameFromString(source)) : null; this.calledFunctions = []; this.constants = {}; this.constantTypes = {}; this.constantBitRatios = {}; this.isRootKernel = false; this.isSubKernel = false; this.debug = null; this.functions = null; this.identifiers = null; this.contexts = null; this.functionCalls = null; this.states = []; this.needsArgumentType = null; this.assignArgumentType = null; this.lookupReturnType = null; this.lookupFunctionArgumentTypes = null; this.lookupFunctionArgumentBitRatio = null; this.triggerImplyArgumentType = null; this.triggerImplyArgumentBitRatio = null; this.onNestedFunction = null; this.onFunctionCall = null; this.optimizeFloatMemory = null; this.precision = null; this.loopMaxIterations = null; this.argumentNames = (typeof this.source === 'string' ? utils.getArgumentNamesFromString(this.source) : null); this.argumentTypes = []; this.argumentSizes = []; this.argumentBitRatios = null; this.returnType = null; this.output = []; this.plugins = null; this.leadingReturnStatement = null; this.followingReturnStatement = null; this.dynamicOutput = null; this.dynamicArguments = null; this.strictTypingChecking = false; this.fixIntegerDivisionAccuracy = null; if (settings) { for (const p in settings) { if (!settings.hasOwnProperty(p)) continue; if (!this.hasOwnProperty(p)) continue; this[p] = settings[p]; } } this.literalTypes = {}; this.validate(); this._string = null; this._internalVariableNames = {}; } validate() { if (typeof this.source !== 'string' && !this.ast) { throw new Error('this.source not a string'); } if (!this.ast && !utils.isFunctionString(this.source)) { throw new Error('this.source not a function string'); } if (!this.name) { throw new Error('this.name could not be set'); } if (this.argumentTypes.length > 0 && this.argumentTypes.length !== this.argumentNames.length) { throw new Error(`argumentTypes count of ${ this.argumentTypes.length } exceeds ${ this.argumentNames.length }`); } if (this.output.length < 1) { throw new Error('this.output is not big enough'); } } isIdentifierConstant(name) { if (!this.constants) return false; return this.constants.hasOwnProperty(name); } isInput(argumentName) { return this.argumentTypes[this.argumentNames.indexOf(argumentName)] === 'Input'; } pushState(state) { this.states.push(state); } popState(state) { if (this.state !== state) { throw new Error(`Cannot popState ${ state } when in ${ this.state }`); } this.states.pop(); } isState(state) { return this.state === state; } get state() { return this.states[this.states.length - 1]; } astMemberExpressionUnroll(ast) { if (ast.type === 'Identifier') { return ast.name; } else if (ast.type === 'ThisExpression') { return 'this'; } if (ast.type === 'MemberExpression') { if (ast.object && ast.property) { if (ast.object.hasOwnProperty('name') && ast.object.name !== 'Math') { return this.astMemberExpressionUnroll(ast.property); } return ( this.astMemberExpressionUnroll(ast.object) + '.' + this.astMemberExpressionUnroll(ast.property) ); } } if (ast.hasOwnProperty('expressions')) { const firstExpression = ast.expressions[0]; if (firstExpression.type === 'Literal' && firstExpression.value === 0 && ast.expressions.length === 2) { return this.astMemberExpressionUnroll(ast.expressions[1]); } } throw this.astErrorOutput('Unknown astMemberExpressionUnroll', ast); } getJsAST(inParser) { if (this.ast) { return this.ast; } if (typeof this.source === 'object') { this.traceFunctionAST(this.source); return this.ast = this.source; } inParser = inParser || acorn; if (inParser === null) { throw new Error('Missing JS to AST parser'); } const ast = Object.freeze(inParser.parse(`const parser_${ this.name } = ${ this.source };`, { locations: true })); const functionAST = ast.body[0].declarations[0].init; this.traceFunctionAST(functionAST); if (!ast) { throw new Error('Failed to parse JS code'); } return this.ast = functionAST; } traceFunctionAST(ast) { const { contexts, declarations, functions, identifiers, functionCalls } = new FunctionTracer(ast); this.contexts = contexts; this.identifiers = identifiers; this.functionCalls = functionCalls; this.functions = functions; for (let i = 0; i < declarations.length; i++) { const declaration = declarations[i]; const { ast, inForLoopInit, inForLoopTest } = declaration; const { init } = ast; const dependencies = this.getDependencies(init); let valueType = null; if (inForLoopInit && inForLoopTest) { valueType = 'Integer'; } else { if (init) { const realType = this.getType(init); switch (realType) { case 'Integer': case 'Float': case 'Number': if (init.type === 'MemberExpression') { valueType = realType; } else { valueType = 'Number'; } break; case 'LiteralInteger': valueType = 'Number'; break; default: valueType = realType; } } } declaration.valueType = valueType; declaration.dependencies = dependencies; declaration.isSafe = this.isSafeDependencies(dependencies); } for (let i = 0; i < functions.length; i++) { this.onNestedFunction(functions[i], this.source); } } getDeclaration(ast) { for (let i = 0; i < this.identifiers.length; i++) { const identifier = this.identifiers[i]; if (ast === identifier.ast) { return identifier.declaration; } } return null; } getVariableType(ast) { if (ast.type !== 'Identifier') { throw new Error(`ast of ${ast.type} not "Identifier"`); } let type = null; const argumentIndex = this.argumentNames.indexOf(ast.name); if (argumentIndex === -1) { const declaration = this.getDeclaration(ast); if (declaration) { return declaration.valueType; } } else { const argumentType = this.argumentTypes[argumentIndex]; if (argumentType) { type = argumentType; } } if (!type && this.strictTypingChecking) { throw new Error(`Declaration of ${name} not found`); } return type; } getLookupType(type) { if (!typeLookupMap.hasOwnProperty(type)) { throw new Error(`unknown typeLookupMap ${ type }`); } return typeLookupMap[type]; } getConstantType(constantName) { if (this.constantTypes[constantName]) { const type = this.constantTypes[constantName]; if (type === 'Float') { return 'Number'; } else { return type; } } throw new Error(`Type for constant "${ constantName }" not declared`); } toString() { if (this._string) return this._string; return this._string = this.astGeneric(this.getJsAST(), []).join('').trim(); } toJSON() { const settings = { source: this.source, name: this.name, constants: this.constants, constantTypes: this.constantTypes, isRootKernel: this.isRootKernel, isSubKernel: this.isSubKernel, debug: this.debug, output: this.output, loopMaxIterations: this.loopMaxIterations, argumentNames: this.argumentNames, argumentTypes: this.argumentTypes, argumentSizes: this.argumentSizes, returnType: this.returnType, leadingReturnStatement: this.leadingReturnStatement, followingReturnStatement: this.followingReturnStatement, }; return { ast: this.ast, settings }; } getType(ast) { if (Array.isArray(ast)) { return this.getType(ast[ast.length - 1]); } switch (ast.type) { case 'BlockStatement': return this.getType(ast.body); case 'ArrayExpression': const childType = this.getType(ast.elements[0]); switch (childType) { case 'Array(2)': case 'Array(3)': case 'Array(4)': return `Matrix(${ast.elements.length})`; } return `Array(${ ast.elements.length })`; case 'Literal': const literalKey = this.astKey(ast); if (this.literalTypes[literalKey]) { return this.literalTypes[literalKey]; } if (Number.isInteger(ast.value)) { return 'LiteralInteger'; } else if (ast.value === true || ast.value === false) { return 'Boolean'; } else { return 'Number'; } case 'AssignmentExpression': return this.getType(ast.left); case 'CallExpression': if (this.isAstMathFunction(ast)) { return 'Number'; } if (!ast.callee || !ast.callee.name) { if (ast.callee.type === 'SequenceExpression' && ast.callee.expressions[ast.callee.expressions.length - 1].property.name) { const functionName = ast.callee.expressions[ast.callee.expressions.length - 1].property.name; this.inferArgumentTypesIfNeeded(functionName, ast.arguments); return this.lookupReturnType(functionName, ast, this); } if (this.getVariableSignature(ast.callee, true) === 'this.color') { return null; } if (ast.callee.type === 'MemberExpression' && ast.callee.object && ast.callee.property && ast.callee.property.name && ast.arguments) { const functionName = ast.callee.property.name; this.inferArgumentTypesIfNeeded(functionName, ast.arguments); return this.lookupReturnType(functionName, ast, this); } throw this.astErrorOutput('Unknown call expression', ast); } if (ast.callee && ast.callee.name) { const functionName = ast.callee.name; this.inferArgumentTypesIfNeeded(functionName, ast.arguments); return this.lookupReturnType(functionName, ast, this); } throw this.astErrorOutput(`Unhandled getType Type "${ ast.type }"`, ast); case 'LogicalExpression': return 'Boolean'; case 'BinaryExpression': switch (ast.operator) { case '%': case '/': if (this.fixIntegerDivisionAccuracy) { return 'Number'; } else { break; } case '>': case '<': return 'Boolean'; case '&': case '|': case '^': case '<<': case '>>': case '>>>': return 'Integer'; } const type = this.getType(ast.left); if (this.isState('skip-literal-correction')) return type; if (type === 'LiteralInteger') { const rightType = this.getType(ast.right); if (rightType === 'LiteralInteger') { if (ast.left.value % 1 === 0) { return 'Integer'; } else { return 'Float'; } } return rightType; } return typeLookupMap[type] || type; case 'UpdateExpression': return this.getType(ast.argument); case 'UnaryExpression': if (ast.operator === '~') { return 'Integer'; } return this.getType(ast.argument); case 'VariableDeclaration': { const declarations = ast.declarations; let lastType; for (let i = 0; i < declarations.length; i++) { const declaration = declarations[i]; lastType = this.getType(declaration); } if (!lastType) { throw this.astErrorOutput(`Unable to find type for declaration`, ast); } return lastType; } case 'VariableDeclarator': const declaration = this.getDeclaration(ast.id); if (!declaration) { throw this.astErrorOutput(`Unable to find declarator`, ast); } if (!declaration.valueType) { throw this.astErrorOutput(`Unable to find declarator valueType`, ast); } return declaration.valueType; case 'Identifier': if (ast.name === 'Infinity') { return 'Number'; } if (this.isAstVariable(ast)) { const signature = this.getVariableSignature(ast); if (signature === 'value') { return this.getCheckVariableType(ast); } } const origin = this.findIdentifierOrigin(ast); if (origin && origin.init) { return this.getType(origin.init); } return null; case 'ReturnStatement': return this.getType(ast.argument); case 'MemberExpression': if (this.isAstMathFunction(ast)) { switch (ast.property.name) { case 'ceil': return 'Integer'; case 'floor': return 'Integer'; case 'round': return 'Integer'; } return 'Number'; } if (this.isAstVariable(ast)) { const variableSignature = this.getVariableSignature(ast); switch (variableSignature) { case 'value[]': return this.getLookupType(this.getCheckVariableType(ast.object)); case 'value[][]': return this.getLookupType(this.getCheckVariableType(ast.object.object)); case 'value[][][]': return this.getLookupType(this.getCheckVariableType(ast.object.object.object)); case 'value[][][][]': return this.getLookupType(this.getCheckVariableType(ast.object.object.object.object)); case 'value.thread.value': case 'this.thread.value': return 'Integer'; case 'this.output.value': return this.dynamicOutput ? 'Integer' : 'LiteralInteger'; case 'this.constants.value': return this.getConstantType(ast.property.name); case 'this.constants.value[]': return this.getLookupType(this.getConstantType(ast.object.property.name)); case 'this.constants.value[][]': return this.getLookupType(this.getConstantType(ast.object.object.property.name)); case 'this.constants.value[][][]': return this.getLookupType(this.getConstantType(ast.object.object.object.property.name)); case 'this.constants.value[][][][]': return this.getLookupType(this.getConstantType(ast.object.object.object.object.property.name)); case 'fn()[]': case 'fn()[][]': case 'fn()[][][]': return this.getLookupType(this.getType(ast.object)); case 'value.value': if (this.isAstMathVariable(ast)) { return 'Number'; } switch (ast.property.name) { case 'r': case 'g': case 'b': case 'a': return this.getLookupType(this.getCheckVariableType(ast.object)); } case '[][]': return 'Number'; } throw this.astErrorOutput('Unhandled getType MemberExpression', ast); } throw this.astErrorOutput('Unhandled getType MemberExpression', ast); case 'ConditionalExpression': return this.getType(ast.consequent); case 'FunctionDeclaration': case 'FunctionExpression': const lastReturn = this.findLastReturn(ast.body); if (lastReturn) { return this.getType(lastReturn); } return null; case 'IfStatement': return this.getType(ast.consequent); case 'SequenceExpression': return this.getType(ast.expressions[ast.expressions.length - 1]); default: throw this.astErrorOutput(`Unhandled getType Type "${ ast.type }"`, ast); } } getCheckVariableType(ast) { const type = this.getVariableType(ast); if (!type) { throw this.astErrorOutput(`${ast.type} is not defined`, ast); } return type; } inferArgumentTypesIfNeeded(functionName, args) { for (let i = 0; i < args.length; i++) { if (!this.needsArgumentType(functionName, i)) continue; const type = this.getType(args[i]); if (!type) { throw this.astErrorOutput(`Unable to infer argument ${i}`, args[i]); } this.assignArgumentType(functionName, i, type); } } isAstMathVariable(ast) { const mathProperties = [ 'E', 'PI', 'SQRT2', 'SQRT1_2', 'LN2', 'LN10', 'LOG2E', 'LOG10E', ]; return ast.type === 'MemberExpression' && ast.object && ast.object.type === 'Identifier' && ast.object.name === 'Math' && ast.property && ast.property.type === 'Identifier' && mathProperties.indexOf(ast.property.name) > -1; } isAstMathFunction(ast) { const mathFunctions = [ 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'clz32', 'cos', 'cosh', 'expm1', 'exp', 'floor', 'fround', 'imul', 'log', 'log2', 'log10', 'log1p', 'max', 'min', 'pow', 'random', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc', ]; return ast.type === 'CallExpression' && ast.callee && ast.callee.type === 'MemberExpression' && ast.callee.object && ast.callee.object.type === 'Identifier' && ast.callee.object.name === 'Math' && ast.callee.property && ast.callee.property.type === 'Identifier' && mathFunctions.indexOf(ast.callee.property.name) > -1; } isAstVariable(ast) { return ast.type === 'Identifier' || ast.type === 'MemberExpression'; } isSafe(ast) { return this.isSafeDependencies(this.getDependencies(ast)); } isSafeDependencies(dependencies) { return dependencies && dependencies.every ? dependencies.every(dependency => dependency.isSafe) : true; } getDependencies(ast, dependencies, isNotSafe) { if (!dependencies) { dependencies = []; } if (!ast) return null; if (Array.isArray(ast)) { for (let i = 0; i < ast.length; i++) { this.getDependencies(ast[i], dependencies, isNotSafe); } return dependencies; } switch (ast.type) { case 'AssignmentExpression': this.getDependencies(ast.left, dependencies, isNotSafe); this.getDependencies(ast.right, dependencies, isNotSafe); return dependencies; case 'ConditionalExpression': this.getDependencies(ast.test, dependencies, isNotSafe); this.getDependencies(ast.alternate, dependencies, isNotSafe); this.getDependencies(ast.consequent, dependencies, isNotSafe); return dependencies; case 'Literal': dependencies.push({ origin: 'literal', value: ast.value, isSafe: isNotSafe === true ? false : ast.value > -Infinity && ast.value < Infinity && !isNaN(ast.value) }); break; case 'VariableDeclarator': return this.getDependencies(ast.init, dependencies, isNotSafe); case 'Identifier': const declaration = this.getDeclaration(ast); if (declaration) { dependencies.push({ name: ast.name, origin: 'declaration', isSafe: isNotSafe ? false : this.isSafeDependencies(declaration.dependencies), }); } else if (this.argumentNames.indexOf(ast.name) > -1) { dependencies.push({ name: ast.name, origin: 'argument', isSafe: false, }); } else if (this.strictTypingChecking) { throw new Error(`Cannot find identifier origin "${ast.name}"`); } break; case 'FunctionDeclaration': return this.getDependencies(ast.body.body[ast.body.body.length - 1], dependencies, isNotSafe); case 'ReturnStatement': return this.getDependencies(ast.argument, dependencies); case 'BinaryExpression': case 'LogicalExpression': isNotSafe = (ast.operator === '/' || ast.operator === '*'); this.getDependencies(ast.left, dependencies, isNotSafe); this.getDependencies(ast.right, dependencies, isNotSafe); return dependencies; case 'UnaryExpression': case 'UpdateExpression': return this.getDependencies(ast.argument, dependencies, isNotSafe); case 'VariableDeclaration': return this.getDependencies(ast.declarations, dependencies, isNotSafe); case 'ArrayExpression': dependencies.push({ origin: 'declaration', isSafe: true, }); return dependencies; case 'CallExpression': dependencies.push({ origin: 'function', isSafe: true, }); return dependencies; case 'MemberExpression': const details = this.getMemberExpressionDetails(ast); switch (details.signature) { case 'value[]': this.getDependencies(ast.object, dependencies, isNotSafe); break; case 'value[][]': this.getDependencies(ast.object.object, dependencies, isNotSafe); break; case 'value[][][]': this.getDependencies(ast.object.object.object, dependencies, isNotSafe); break; case 'this.output.value': if (this.dynamicOutput) { dependencies.push({ name: details.name, origin: 'output', isSafe: false, }); } break; } if (details) { if (details.property) { this.getDependencies(details.property, dependencies, isNotSafe); } if (details.xProperty) { this.getDependencies(details.xProperty, dependencies, isNotSafe); } if (details.yProperty) { this.getDependencies(details.yProperty, dependencies, isNotSafe); } if (details.zProperty) { this.getDependencies(details.zProperty, dependencies, isNotSafe); } return dependencies; } case 'SequenceExpression': return this.getDependencies(ast.expressions, dependencies, isNotSafe); default: throw this.astErrorOutput(`Unhandled type ${ ast.type } in getDependencies`, ast); } return dependencies; } getVariableSignature(ast, returnRawValue) { if (!this.isAstVariable(ast)) { throw new Error(`ast of type "${ ast.type }" is not a variable signature`); } if (ast.type === 'Identifier') { return 'value'; } const signature = []; while (true) { if (!ast) break; if (ast.computed) { signature.push('[]'); } else if (ast.type === 'ThisExpression') { signature.unshift('this'); } else if (ast.property && ast.property.name) { if ( ast.property.name === 'x' || ast.property.name === 'y' || ast.property.name === 'z' ) { signature.unshift(returnRawValue ? '.' + ast.property.name : '.value'); } else if ( ast.property.name === 'constants' || ast.property.name === 'thread' || ast.property.name === 'output' ) { signature.unshift('.' + ast.property.name); } else { signature.unshift(returnRawValue ? '.' + ast.property.name : '.value'); } } else if (ast.name) { signature.unshift(returnRawValue ? ast.name : 'value'); } else if (ast.callee && ast.callee.name) { signature.unshift(returnRawValue ? ast.callee.name + '()' : 'fn()'); } else if (ast.elements) { signature.unshift('[]'); } else { signature.unshift('unknown'); } ast = ast.object; } const signatureString = signature.join(''); if (returnRawValue) { return signatureString; } const allowedExpressions = [ 'value', 'value[]', 'value[][]', 'value[][][]', 'value[][][][]', 'value.value', 'value.thread.value', 'this.thread.value', 'this.output.value', 'this.constants.value', 'this.constants.value[]', 'this.constants.value[][]', 'this.constants.value[][][]', 'this.constants.value[][][][]', 'fn()[]', 'fn()[][]', 'fn()[][][]', '[][]', ]; if (allowedExpressions.indexOf(signatureString) > -1) { return signatureString; } return null; } build() { return this.toString().length > 0; } astGeneric(ast, retArr) { if (ast === null) { throw this.astErrorOutput('NULL ast', ast); } else { if (Array.isArray(ast)) { for (let i = 0; i < ast.length; i++) { this.astGeneric(ast[i], retArr); } return retArr; } switch (ast.type) { case 'FunctionDeclaration': return this.astFunctionDeclaration(ast, retArr); case 'FunctionExpression': return this.astFunctionExpression(ast, retArr); case 'ReturnStatement': return this.astReturnStatement(ast, retArr); case 'Literal': return this.astLiteral(ast, retArr); case 'BinaryExpression': return this.astBinaryExpression(ast, retArr); case 'Identifier': return this.astIdentifierExpression(ast, retArr); case 'AssignmentExpression': return this.astAssignmentExpression(ast, retArr); case 'ExpressionStatement': return this.astExpressionStatement(ast, retArr); case 'EmptyStatement': return this.astEmptyStatement(ast, retArr); case 'BlockStatement': return this.astBlockStatement(ast, retArr); case 'IfStatement': return this.astIfStatement(ast, retArr); case 'SwitchStatement': return this.astSwitchStatement(ast, retArr); case 'BreakStatement': return this.astBreakStatement(ast, retArr); case 'ContinueStatement': return this.astContinueStatement(ast, retArr); case 'ForStatement': return this.astForStatement(ast, retArr); case 'WhileStatement': return this.astWhileStatement(ast, retArr); case 'DoWhileStatement': return this.astDoWhileStatement(ast, retArr); case 'VariableDeclaration': return this.astVariableDeclaration(ast, retArr); case 'VariableDeclarator': return this.astVariableDeclarator(ast, retArr); case 'ThisExpression': return this.astThisExpression(ast, retArr); case 'SequenceExpression': return this.astSequenceExpression(ast, retArr); case 'UnaryExpression': return this.astUnaryExpression(ast, retArr); case 'UpdateExpression': return this.astUpdateExpression(ast, retArr); case 'LogicalExpression': return this.astLogicalExpression(ast, retArr); case 'MemberExpression': return this.astMemberExpression(ast, retArr); case 'CallExpression': return this.astCallExpression(ast, retArr); case 'ArrayExpression': return this.astArrayExpression(ast, retArr); case 'DebuggerStatement': return this.astDebuggerStatement(ast, retArr); case 'ConditionalExpression': return this.astConditionalExpression(ast, retArr); } throw this.astErrorOutput('Unknown ast type : ' + ast.type, ast); } } astErrorOutput(error, ast) { if (typeof this.source !== 'string') { return new Error(error); } const debugString = utils.getAstString(this.source, ast); const leadingSource = this.source.substr(ast.start); const splitLines = leadingSource.split(/\n/); const lineBefore = splitLines.length > 0 ? splitLines[splitLines.length - 1] : 0; return new Error(`${error} on line ${ splitLines.length }, position ${ lineBefore.length }:\n ${ debugString }`); } astDebuggerStatement(arrNode, retArr) { return retArr; } astConditionalExpression(ast, retArr) { if (ast.type !== 'ConditionalExpression') { throw this.astErrorOutput('Not a conditional expression', ast); } retArr.push('('); this.astGeneric(ast.test, retArr); retArr.push('?'); this.astGeneric(ast.consequent, retArr); retArr.push(':'); this.astGeneric(ast.alternate, retArr); retArr.push(')'); return retArr; } astFunction(ast, retArr) { throw new Error(`"astFunction" not defined on ${ this.constructor.name }`); } astFunctionDeclaration(ast, retArr) { if (this.isChildFunction(ast)) { return retArr; } return this.astFunction(ast, retArr); } astFunctionExpression(ast, retArr) { if (this.isChildFunction(ast)) { return retArr; } return this.astFunction(ast, retArr); } isChildFunction(ast) { for (let i = 0; i < this.functions.length; i++) { if (this.functions[i] === ast) { return true; } } return false; } astReturnStatement(ast, retArr) { return retArr; } astLiteral(ast, retArr) { this.literalTypes[this.astKey(ast)] = 'Number'; return retArr; } astBinaryExpression(ast, retArr) { return retArr; } astIdentifierExpression(ast, retArr) { return retArr; } astAssignmentExpression(ast, retArr) { return retArr; } astExpressionStatement(esNode, retArr) { this.astGeneric(esNode.expression, retArr); retArr.push(';'); return retArr; } astEmptyStatement(eNode, retArr) { return retArr; } astBlockStatement(ast, retArr) { return retArr; } astIfStatement(ast, retArr) { return retArr; } astSwitchStatement(ast, retArr) { return retArr; } astBreakStatement(brNode, retArr) { retArr.push('break;'); return retArr; } astContinueStatement(crNode, retArr) { retArr.push('continue;\n'); return retArr; } astForStatement(ast, retArr) { return retArr; } astWhileStatement(ast, retArr) { return retArr; } astDoWhileStatement(ast, retArr) { return retArr; } astVariableDeclarator(iVarDecNode, retArr) { this.astGeneric(iVarDecNode.id, retArr); if (iVarDecNode.init !== null) { retArr.push('='); this.astGeneric(iVarDecNode.init, retArr); } return retArr; } astThisExpression(ast, retArr) { return retArr; } astSequenceExpression(sNode, retArr) { const { expressions } = sNode; const sequenceResult = []; for (let i = 0; i < expressions.length; i++) { const expression = expressions[i]; const expressionResult = []; this.astGeneric(expression, expressionResult); sequenceResult.push(expressionResult.join('')); } if (sequenceResult.length > 1) { retArr.push('(', sequenceResult.join(','), ')'); } else { retArr.push(sequenceResult[0]); } return retArr; } astUnaryExpression(uNode, retArr) { const unaryResult = this.checkAndUpconvertBitwiseUnary(uNode, retArr); if (unaryResult) { return retArr; } if (uNode.prefix) { retArr.push(uNode.operator); this.astGeneric(uNode.argument, retArr); } else { this.astGeneric(uNode.argument, retArr); retArr.push(uNode.operator); } return retArr; } checkAndUpconvertBitwiseUnary(uNode, retArr) {} astUpdateExpression(uNode, retArr) { if (uNode.prefix) { retArr.push(uNode.operator); this.astGeneric(uNode.argument, retArr); } else { this.astGeneric(uNode.argument, retArr); retArr.push(uNode.operator); } return retArr; } astLogicalExpression(logNode, retArr) { retArr.push('('); this.astGeneric(logNode.left, retArr); retArr.push(logNode.operator); this.astGeneric(logNode.right, retArr); retArr.push(')'); return retArr; } astMemberExpression(ast, retArr) { return retArr; } astCallExpression(ast, retArr) { return retArr; } astArrayExpression(ast, retArr) { return retArr; } getMemberExpressionDetails(ast) { if (ast.type !== 'MemberExpression') { throw this.astErrorOutput(`Expression ${ ast.type } not a MemberExpression`, ast); } let name = null; let type = null; const variableSignature = this.getVariableSignature(ast); switch (variableSignature) { case 'value': return null; case 'value.thread.value': case 'this.thread.value': case 'this.output.value': return { signature: variableSignature, type: 'Integer', name: ast.property.name }; case 'value[]': if (typeof ast.object.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.name; return { name, origin: 'user', signature: variableSignature, type: this.getVariableType(ast.object), xProperty: ast.property }; case 'value[][]': if (typeof ast.object.object.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.object.name; return { name, origin: 'user', signature: variableSignature, type: this.getVariableType(ast.object.object), yProperty: ast.object.property, xProperty: ast.property, }; case 'value[][][]': if (typeof ast.object.object.object.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.object.object.name; return { name, origin: 'user', signature: variableSignature, type: this.getVariableType(ast.object.object.object), zProperty: ast.object.object.property, yProperty: ast.object.property, xProperty: ast.property, }; case 'value[][][][]': if (typeof ast.object.object.object.object.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.object.object.object.name; return { name, origin: 'user', signature: variableSignature, type: this.getVariableType(ast.object.object.object.object), zProperty: ast.object.object.property, yProperty: ast.object.property, xProperty: ast.property, }; case 'value.value': if (typeof ast.property.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } if (this.isAstMathVariable(ast)) { name = ast.property.name; return { name, origin: 'Math', type: 'Number', signature: variableSignature, }; } switch (ast.property.name) { case 'r': case 'g': case 'b': case 'a': name = ast.object.name; return { name, property: ast.property.name, origin: 'user', signature: variableSignature, type: 'Number' }; default: throw this.astErrorOutput('Unexpected expression', ast); } case 'this.constants.value': if (typeof ast.property.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.property.name; type = this.getConstantType(name); if (!type) { throw this.astErrorOutput('Constant has no type', ast); } return { name, type, origin: 'constants', signature: variableSignature, }; case 'this.constants.value[]': if (typeof ast.object.property.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.property.name; type = this.getConstantType(name); if (!type) { throw this.astErrorOutput('Constant has no type', ast); } return { name, type, origin: 'constants', signature: variableSignature, xProperty: ast.property, }; case 'this.constants.value[][]': { if (typeof ast.object.object.property.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.object.property.name; type = this.getConstantType(name); if (!type) { throw this.astErrorOutput('Constant has no type', ast); } return { name, type, origin: 'constants', signature: variableSignature, yProperty: ast.object.property, xProperty: ast.property, }; } case 'this.constants.value[][][]': { if (typeof ast.object.object.object.property.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.object.object.property.name; type = this.getConstantType(name); if (!type) { throw this.astErrorOutput('Constant has no type', ast); } return { name, type, origin: 'constants', signature: variableSignature, zProperty: ast.object.object.property, yProperty: ast.object.property, xProperty: ast.property, }; } case 'fn()[]': case 'fn()[][]': case '[][]': return { signature: variableSignature, property: ast.property, }; default: throw this.astErrorOutput('Unexpected expression', ast); } } findIdentifierOrigin(astToFind) { const stack = [this.ast]; while (stack.length > 0) { const atNode = stack[0]; if (atNode.type === 'VariableDeclarator' && atNode.id && atNode.id.name && atNode.id.name === astToFind.name) { return atNode; } stack.shift(); if (atNode.argument) { stack.push(atNode.argument); } else if (atNode.body) { stack.push(atNode.body); } else if (atNode.declarations) { stack.push(atNode.declarations); } else if (Array.isArray(atNode)) { for (let i = 0; i < atNode.length; i++) { stack.push(atNode[i]); } } } return null; } findLastReturn(ast) { const stack = [ast || this.ast]; while (stack.length > 0) { const atNode = stack.pop(); if (atNode.type === 'ReturnStatement') { return atNode; } if (atNode.type === 'FunctionDeclaration') { continue; } if (atNode.argument) { stack.push(atNode.argument); } else if (atNode.body) { stack.push(atNode.body); } else if (atNode.declarations) { stack.push(atNode.declarations); } else if (Array.isArray(atNode)) { for (let i = 0; i < atNode.length; i++) { stack.push(atNode[i]); } } else if (atNode.consequent) { stack.push(atNode.consequent); } else if (atNode.cases) { stack.push(atNode.cases); } } return null; } getInternalVariableName(name) { if (!this._internalVariableNames.hasOwnProperty(name)) { this._internalVariableNames[name] = 0; } this._internalVariableNames[name]++; if (this._internalVariableNames[name] === 1) { return name; } return name + this._internalVariableNames[name]; } astKey(ast, separator = ',') { if (!ast.start || !ast.end) throw new Error('AST start and end needed'); return `${ast.start}${separator}${ast.end}`; } } const typeLookupMap = { 'Number': 'Number', 'Float': 'Float', 'Integer': 'Integer', 'Array': 'Number', 'Array(2)': 'Number', 'Array(3)': 'Number', 'Array(4)': 'Number', 'Matrix(2)': 'Number', 'Matrix(3)': 'Number', 'Matrix(4)': 'Number', 'Array2D': 'Number', 'Array3D': 'Number', 'Input': 'Number', 'HTMLCanvas': 'Array(4)', 'OffscreenCanvas': 'Array(4)', 'HTMLImage': 'Array(4)', 'ImageBitmap': 'Array(4)', 'ImageData': 'Array(4)', 'HTMLVideo': 'Array(4)', 'HTMLImageArray': 'Array(4)', 'NumberTexture': 'Number', 'MemoryOptimizedNumberTexture': 'Number', 'Array1D(2)': 'Array(2)', 'Array1D(3)': 'Array(3)', 'Array1D(4)': 'Array(4)', 'Array2D(2)': 'Array(2)', 'Array2D(3)': 'Array(3)', 'Array2D(4)': 'Array(4)', 'Array3D(2)': 'Array(2)', 'Array3D(3)': 'Array(3)', 'Array3D(4)': 'Array(4)', 'ArrayTexture(1)': 'Number', 'ArrayTexture(2)': 'Array(2)', 'ArrayTexture(3)': 'Array(3)', 'ArrayTexture(4)': 'Array(4)', }; module.exports = { FunctionNode }; },{"../utils":113,"./function-tracer":10,"acorn":1}],10:[function(require,module,exports){ const { utils } = require('../utils'); function last(array) { return array.length > 0 ? array[array.length - 1] : null; } const states = { trackIdentifiers: 'trackIdentifiers', memberExpression: 'memberExpression', inForLoopInit: 'inForLoopInit' }; class FunctionTracer { constructor(ast) { this.runningContexts = []; this.functionContexts = []; this.contexts = []; this.functionCalls = []; this.declarations = []; this.identifiers = []; this.functions = []; this.returnStatements = []; this.trackedIdentifiers = null; this.states = []; this.newFunctionContext(); this.scan(ast); } isState(state) { return this.states[this.states.length - 1] === state; } hasState(state) { return this.states.indexOf(state) > -1; } pushState(state) { this.states.push(state); } popState(state) { if (this.isState(state)) { this.states.pop(); } else { throw new Error(`Cannot pop the non-active state "${state}"`); } } get currentFunctionContext() { return last(this.functionContexts); } get currentContext() { return last(this.runningContexts); } newFunctionContext() { const newContext = { '@contextType': 'function' }; this.contexts.push(newContext); this.functionContexts.push(newContext); } newContext(run) { const newContext = Object.assign({ '@contextType': 'const/let' }, this.currentContext); this.contexts.push(newContext); this.runningContexts.push(newContext); run(); const { currentFunctionContext } = this; for (const p in currentFunctionContext) { if (!currentFunctionContext.hasOwnProperty(p) || newContext.hasOwnProperty(p)) continue; newContext[p] = currentFunctionContext[p]; } this.runningContexts.pop(); return newContext; } useFunctionContext(run) { const functionContext = last(this.functionContexts); this.runningContexts.push(functionContext); run(); this.runningContexts.pop(); } getIdentifiers(run) { const trackedIdentifiers = this.trackedIdentifiers = []; this.pushState(states.trackIdentifiers); run(); this.trackedIdentifiers = null; this.popState(states.trackIdentifiers); return trackedIdentifiers; } getDeclaration(name) { const { currentContext, currentFunctionContext, runningContexts } = this; const declaration = currentContext[name] || currentFunctionContext[name] || null; if ( !declaration && currentContext === currentFunctionContext && runningContexts.length > 0 ) { const previousRunningContext = runningContexts[runningContexts.length - 2]; if (previousRunningContext[name]) { return previousRunningContext[name]; } } return declaration; } scan(ast) { if (!ast) return; if (Array.isArray(ast)) { for (let i = 0; i < ast.length; i++) { this.scan(ast[i]); } return; } switch (ast.type) { case 'Program': this.useFunctionContext(() => { this.scan(ast.body); }); break; case 'BlockStatement': this.newContext(() => { this.scan(ast.body); }); break; case 'AssignmentExpression': case 'LogicalExpression': this.scan(ast.left); this.scan(ast.right); break; case 'BinaryExpression': this.scan(ast.left); this.scan(ast.right); break; case 'UpdateExpression': if (ast.operator === '++') { const declaration = this.getDeclaration(ast.argument.name); if (declaration) { declaration.suggestedType = 'Integer'; } } this.scan(ast.argument); break; case 'UnaryExpression': this.scan(ast.argument); break; case 'VariableDeclaration': if (ast.kind === 'var') { this.useFunctionContext(() => { ast.declarations = utils.normalizeDeclarations(ast); this.scan(ast.declarations); }); } else { ast.declarations = utils.normalizeDeclarations(ast); this.scan(ast.declarations); } break; case 'VariableDeclarator': { const { currentContext } = this; const inForLoopInit = this.hasState(states.inForLoopInit); const declaration = { ast: ast, context: currentContext, name: ast.id.name, origin: 'declaration', inForLoopInit, inForLoopTest: null, assignable: currentContext === this.currentFunctionContext || (!inForLoopInit && !currentContext.hasOwnProperty(ast.id.name)), suggestedType: null, valueType: null, dependencies: null, isSafe: null, }; if (!currentContext[ast.id.name]) { currentContext[ast.id.name] = declaration; } this.declarations.push(declaration); this.scan(ast.id); this.scan(ast.init); break; } case 'FunctionExpression': case 'FunctionDeclaration': if (this.runningContexts.length === 0) { this.scan(ast.body); } else { this.functions.push(ast); } break; case 'IfStatement': this.scan(ast.test); this.scan(ast.consequent); if (ast.alternate) this.scan(ast.alternate); break; case 'ForStatement': { let testIdentifiers; const context = this.newContext(() => { this.pushState(states.inForLoopInit); this.scan(ast.init); this.popState(states.inForLoopInit); testIdentifiers = this.getIdentifiers(() => { this.scan(ast.test); }); this.scan(ast.update); this.newContext(() => { this.scan(ast.body); }); }); if (testIdentifiers) { for (const p in context) { if (p === '@contextType') continue; if (testIdentifiers.indexOf(p) > -1) { context[p].inForLoopTest = true; } } } break; } case 'DoWhileStatement': case 'WhileStatement': this.newContext(() => { this.scan(ast.body); this.scan(ast.test); }); break; case 'Identifier': { if (this.isState(states.trackIdentifiers)) { this.trackedIdentifiers.push(ast.name); } this.identifiers.push({ context: this.currentContext, declaration: this.getDeclaration(ast.name), ast, }); break; } case 'ReturnStatement': this.returnStatements.push(ast); this.scan(ast.argument); break; case 'MemberExpression': this.pushState(states.memberExpression); this.scan(ast.object); this.scan(ast.property); this.popState(states.memberExpression); break; case 'ExpressionStatement': this.scan(ast.expression); break; case 'SequenceExpression': this.scan(ast.expressions); break; case 'CallExpression': this.functionCalls.push({ context: this.currentContext, ast, }); this.scan(ast.arguments); break; case 'ArrayExpression': this.scan(ast.elements); break; case 'ConditionalExpression': this.scan(ast.test); this.scan(ast.alternate); this.scan(ast.consequent); break; case 'SwitchStatement': this.scan(ast.discriminant); this.scan(ast.cases); break; case 'SwitchCase': this.scan(ast.test); this.scan(ast.consequent); break; case 'ThisExpression': case 'Literal': case 'DebuggerStatement': case 'EmptyStatement': case 'BreakStatement': case 'ContinueStatement': break; default: throw new Error(`unhandled type "${ast.type}"`); } } } module.exports = { FunctionTracer, }; },{"../utils":113}],11:[function(require,module,exports){ const { glWiretap } = require('gl-wiretap'); const { utils } = require('../../utils'); function toStringWithoutUtils(fn) { return fn.toString() .replace('=>', '') .replace(/^function /, '') .replace(/utils[.]/g, '/*utils.*/'); } function glKernelString(Kernel, args, originKernel, setupContextString, destroyContextString) { if (!originKernel.built) { originKernel.build.apply(originKernel, args); } args = args ? Array.from(args).map(arg => { switch (typeof arg) { case 'boolean': return new Boolean(arg); case 'number': return new Number(arg); default: return arg; } }) : null; const uploadedValues = []; const postResult = []; const context = glWiretap(originKernel.context, { useTrackablePrimitives: true, onReadPixels: (targetName) => { if (kernel.subKernels) { if (!subKernelsResultVariableSetup) { postResult.push(` const result = { result: ${getRenderString(targetName, kernel)} };`); subKernelsResultVariableSetup = true; } else { const property = kernel.subKernels[subKernelsResultIndex++].property; postResult.push(` result${isNaN(property) ? '.' + property : `[${property}]`} = ${getRenderString(targetName, kernel)};`); } if (subKernelsResultIndex === kernel.subKernels.length) { postResult.push(' return result;'); } return; } if (targetName) { postResult.push(` return ${getRenderString(targetName, kernel)};`); } else { postResult.push(` return null;`); } }, onUnrecognizedArgumentLookup: (argument) => { const argumentName = findKernelValue(argument, kernel.kernelArguments, [], context, uploadedValues); if (argumentName) { return argumentName; } const constantName = findKernelValue(argument, kernel.kernelConstants, constants ? Object.keys(constants).map(key => constants[key]) : [], context, uploadedValues); if (constantName) { return constantName; } return null; } }); let subKernelsResultVariableSetup = false; let subKernelsResultIndex = 0; const { source, canvas, output, pipeline, graphical, loopMaxIterations, constants, optimizeFloatMemory, precision, fixIntegerDivisionAccuracy, functions, nativeFunctions, subKernels, immutable, argumentTypes, constantTypes, kernelArguments, kernelConstants, tactic, } = originKernel; const kernel = new Kernel(source, { canvas, context, checkContext: false, output, pipeline, graphical, loopMaxIterations, constants, optimizeFloatMemory, precision, fixIntegerDivisionAccuracy, functions, nativeFunctions, subKernels, immutable, argumentTypes, constantTypes, tactic, }); let result = []; context.setIndent(2); kernel.build.apply(kernel, args); result.push(context.toString()); context.reset(); kernel.kernelArguments.forEach((kernelArgument, i) => { switch (kernelArgument.type) { case 'Integer': case 'Boolean': case 'Number': case 'Float': case 'Array': case 'Array(2)': case 'Array(3)': case 'Array(4)': case 'HTMLCanvas': case 'HTMLImage': case 'HTMLVideo': context.insertVariable(`uploadValue_${kernelArgument.name}`, kernelArgument.uploadValue); break; case 'HTMLImageArray': for (let imageIndex = 0; imageIndex < args[i].length; imageIndex++) { const arg = args[i]; context.insertVariable(`uploadValue_${kernelArgument.name}[${imageIndex}]`, arg[imageIndex]); } break; case 'Input': context.insertVariable(`uploadValue_${kernelArgument.name}`, kernelArgument.uploadValue); break; case 'MemoryOptimizedNumberTexture': case 'NumberTexture': case 'Array1D(2)': case 'Array1D(3)': case 'Array1D(4)': case 'Array2D(2)': case 'Array2D(3)': case 'Array2D(4)': case 'Array3D(2)': case 'Array3D(3)': case 'Array3D(4)': case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': context.insertVariable(`uploadValue_${kernelArgument.name}`, args[i].texture); break; default: throw new Error(`unhandled kernelArgumentType insertion for glWiretap of type ${kernelArgument.type}`); } }); result.push('/** start of injected functions **/'); result.push(`function ${toStringWithoutUtils(utils.flattenTo)}`); result.push(`function ${toStringWithoutUtils(utils.flatten2dArrayTo)}`); result.push(`function ${toStringWithoutUtils(utils.flatten3dArrayTo)}`); result.push(`function ${toStringWithoutUtils(utils.flatten4dArrayTo)}`); result.push(`function ${toStringWithoutUtils(utils.isArray)}`); if (kernel.renderOutput !== kernel.renderTexture && kernel.formatValues) { result.push( ` const renderOutput = function ${toStringWithoutUtils(kernel.formatValues)};` ); } result.push('/** end of injected functions **/'); result.push(` const innerKernel = function (${kernel.kernelArguments.map(kernelArgument => kernelArgument.varName).join(', ')}) {`); context.setIndent(4); kernel.run.apply(kernel, args); if (kernel.renderKernels) { kernel.renderKernels(); } else if (kernel.renderOutput) { kernel.renderOutput(); } result.push(' /** start setup uploads for kernel values **/'); kernel.kernelArguments.forEach(kernelArgument => { result.push(' ' + kernelArgument.getStringValueHandler().split('\n').join('\n ')); }); result.push(' /** end setup uploads for kernel values **/'); result.push(context.toString()); if (kernel.renderOutput === kernel.renderTexture) { context.reset(); const framebufferName = context.getContextVariableName(kernel.framebuffer); if (kernel.renderKernels) { const results = kernel.renderKernels(); const textureName = context.getContextVariableName(kernel.texture.texture); result.push(` return { result: { texture: ${ textureName }, type: '${ results.result.type }', toArray: ${ getToArrayString(results.result, textureName, framebufferName) } },`); const { subKernels, mappedTextures } = kernel; for (let i = 0; i < subKernels.length; i++) { const texture = mappedTextures[i]; const subKernel = subKernels[i]; const subKernelResult = results[subKernel.property]; const subKernelTextureName = context.getContextVariableName(texture.texture); result.push(` ${subKernel.property}: { texture: ${ subKernelTextureName }, type: '${ subKernelResult.type }', toArray: ${ getToArrayString(subKernelResult, subKernelTextureName, framebufferName) } },`); } result.push(` };`); } else { const rendered = kernel.renderOutput(); const textureName = context.getContextVariableName(kernel.texture.texture); result.push(` return { texture: ${ textureName }, type: '${ rendered.type }', toArray: ${ getToArrayString(rendered, textureName, framebufferName) } };`); } } result.push(` ${destroyContextString ? '\n' + destroyContextString + ' ': ''}`); result.push(postResult.join('\n')); result.push(' };'); if (kernel.graphical) { result.push(getGetPixelsString(kernel)); result.push(` innerKernel.getPixels = getPixels;`); } result.push(' return innerKernel;'); let constantsUpload = []; kernelConstants.forEach((kernelConstant) => { constantsUpload.push(`${kernelConstant.getStringValueHandler()}`); }); return `function kernel(settings) { const { context, constants } = settings; ${constantsUpload.join('')} ${setupContextString ? setupContextString : ''} ${result.join('\n')} }`; } function getRenderString(targetName, kernel) { const readBackValue = kernel.precision === 'single' ? targetName : `new Float32Array(${targetName}.buffer)`; if (kernel.output[2]) { return `renderOutput(${readBackValue}, ${kernel.output[0]}, ${kernel.output[1]}, ${kernel.output[2]})`; } if (kernel.output[1]) { return `renderOutput(${readBackValue}, ${kernel.output[0]}, ${kernel.output[1]})`; } return `renderOutput(${readBackValue}, ${kernel.output[0]})`; } function getGetPixelsString(kernel) { const getPixels = kernel.getPixels.toString(); const useFunctionKeyword = !/^function/.test(getPixels); return utils.flattenFunctionToString(`${useFunctionKeyword ? 'function ' : ''}${ getPixels }`, { findDependency: (object, name) => { if (object === 'utils') { return `const ${name} = ${utils[name].toString()};`; } return null; }, thisLookup: (property) => { if (property === 'context') { return null; } if (kernel.hasOwnProperty(property)) { return JSON.stringify(kernel[property]); } throw new Error(`unhandled thisLookup ${ property }`); } }); } function getToArrayString(kernelResult, textureName, framebufferName) { const toArray = kernelResult.toArray.toString(); const useFunctionKeyword = !/^function/.test(toArray); const flattenedFunctions = utils.flattenFunctionToString(`${useFunctionKeyword ? 'function ' : ''}${ toArray }`, { findDependency: (object, name) => { if (object === 'utils') { return `const ${name} = ${utils[name].toString()};`; } else if (object === 'this') { if (name === 'framebuffer') { return ''; } return `${useFunctionKeyword ? 'function ' : ''}${kernelResult[name].toString()}`; } else { throw new Error('unhandled fromObject'); } }, thisLookup: (property, isDeclaration) => { if (property === 'texture') { return textureName; } if (property === 'context') { if (isDeclaration) return null; return 'gl'; } if (kernelResult.hasOwnProperty(property)) { return JSON.stringify(kernelResult[property]); } throw new Error(`unhandled thisLookup ${ property }`); } }); return `() => { function framebuffer() { return ${framebufferName}; }; ${flattenedFunctions} return toArray(); }`; } function findKernelValue(argument, kernelValues, values, context, uploadedValues) { if (argument === null) return null; if (kernelValues === null) return null; switch (typeof argument) { case 'boolean': case 'number': return null; } if ( typeof HTMLImageElement !== 'undefined' && argument instanceof HTMLImageElement ) { for (let i = 0; i < kernelValues.length; i++) { const kernelValue = kernelValues[i]; if (kernelValue.type !== 'HTMLImageArray' && kernelValue) continue; if (kernelValue.uploadValue !== argument) continue; const variableIndex = values[i].indexOf(argument); if (variableIndex === -1) continue; const variableName = `uploadValue_${kernelValue.name}[${variableIndex}]`; context.insertVariable(variableName, argument); return variableName; } } for (let i = 0; i < kernelValues.length; i++) { const kernelValue = kernelValues[i]; if (argument !== kernelValue.uploadValue) continue; const variable = `uploadValue_${kernelValue.name}`; context.insertVariable(variable, kernelValue); return variable; } return null; } module.exports = { glKernelString }; },{"../../utils":113,"gl-wiretap":2}],12:[function(require,module,exports){ const { Kernel } = require('../kernel'); const { utils } = require('../../utils'); const { GLTextureArray2Float } = require('./texture/array-2-float'); const { GLTextureArray2Float2D } = require('./texture/array-2-float-2d'); const { GLTextureArray2Float3D } = require('./texture/array-2-float-3d'); const { GLTextureArray3Float } = require('./texture/array-3-float'); const { GLTextureArray3Float2D } = require('./texture/array-3-float-2d'); const { GLTextureArray3Float3D } = require('./texture/array-3-float-3d'); const { GLTextureArray4Float } = require('./texture/array-4-float'); const { GLTextureArray4Float2D } = require('./texture/array-4-float-2d'); const { GLTextureArray4Float3D } = require('./texture/array-4-float-3d'); const { GLTextureFloat } = require('./texture/float'); const { GLTextureFloat2D } = require('./texture/float-2d'); const { GLTextureFloat3D } = require('./texture/float-3d'); const { GLTextureMemoryOptimized } = require('./texture/memory-optimized'); const { GLTextureMemoryOptimized2D } = require('./texture/memory-optimized-2d'); const { GLTextureMemoryOptimized3D } = require('./texture/memory-optimized-3d'); const { GLTextureUnsigned } = require('./texture/unsigned'); const { GLTextureUnsigned2D } = require('./texture/unsigned-2d'); const { GLTextureUnsigned3D } = require('./texture/unsigned-3d'); const { GLTextureGraphical } = require('./texture/graphical'); class GLKernel extends Kernel { static get mode() { return 'gpu'; } static getIsFloatRead() { const kernelString = `function kernelFunction() { return 1; }`; const kernel = new this(kernelString, { context: this.testContext, canvas: this.testCanvas, validate: false, output: [1], precision: 'single', returnType: 'Number', tactic: 'speed', }); kernel.build(); kernel.run(); const result = kernel.renderOutput(); kernel.destroy(true); return result[0] === 1; } static getIsIntegerDivisionAccurate() { function kernelFunction(v1, v2) { return v1[this.thread.x] / v2[this.thread.x]; } const kernel = new this(kernelFunction.toString(), { context: this.testContext, canvas: this.testCanvas, validate: false, output: [2], returnType: 'Number', precision: 'unsigned', tactic: 'speed', }); const args = [ [6, 6030401], [3, 3991] ]; kernel.build.apply(kernel, args); kernel.run.apply(kernel, args); const result = kernel.renderOutput(); kernel.destroy(true); return result[0] === 2 && result[1] === 1511; } static getIsSpeedTacticSupported() { function kernelFunction(value) { return value[this.thread.x]; } const kernel = new this(kernelFunction.toString(), { context: this.testContext, canvas: this.testCanvas, validate: false, output: [4], returnType: 'Number', precision: 'unsigned', tactic: 'speed', }); const args = [ [0, 1, 2, 3] ]; kernel.build.apply(kernel, args); kernel.run.apply(kernel, args); const result = kernel.renderOutput(); kernel.destroy(true); return Math.round(result[0]) === 0 && Math.round(result[1]) === 1 && Math.round(result[2]) === 2 && Math.round(result[3]) === 3; } static get testCanvas() { throw new Error(`"testCanvas" not defined on ${ this.name }`); } static get testContext() { throw new Error(`"testContext" not defined on ${ this.name }`); } static getFeatures() { const gl = this.testContext; const isDrawBuffers = this.getIsDrawBuffers(); return Object.freeze({ isFloatRead: this.getIsFloatRead(), isIntegerDivisionAccurate: this.getIsIntegerDivisionAccurate(), isSpeedTacticSupported: this.getIsSpeedTacticSupported(), isTextureFloat: this.getIsTextureFloat(), isDrawBuffers, kernelMap: isDrawBuffers, channelCount: this.getChannelCount(), maxTextureSize: this.getMaxTextureSize(), lowIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT), lowFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT), mediumIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT), mediumFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT), highIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT), highFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT), }); } static setupFeatureChecks() { throw new Error(`"setupFeatureChecks" not defined on ${ this.name }`); } static getSignature(kernel, argumentTypes) { return kernel.getVariablePrecisionString() + (argumentTypes.length > 0 ? ':' + argumentTypes.join(',') : ''); } setFixIntegerDivisionAccuracy(fix) { this.fixIntegerDivisionAccuracy = fix; return this; } setPrecision(flag) { this.precision = flag; return this; } setFloatTextures(flag) { utils.warnDeprecated('method', 'setFloatTextures', 'setOptimizeFloatMemory'); this.floatTextures = flag; return this; } static nativeFunctionArguments(source) { const argumentTypes = []; const argumentNames = []; const states = []; const isStartingVariableName = /^[a-zA-Z_]/; const isVariableChar = /[a-zA-Z_0-9]/; let i = 0; let argumentName = null; let argumentType = null; while (i < source.length) { const char = source[i]; const nextChar = source[i + 1]; const state = states.length > 0 ? states[states.length - 1] : null; if (state === 'FUNCTION_ARGUMENTS' && char === '/' && nextChar === '*') { states.push('MULTI_LINE_COMMENT'); i += 2; continue; } else if (state === 'MULTI_LINE_COMMENT' && char === '*' && nextChar === '/') { states.pop(); i += 2; continue; } else if (state === 'FUNCTION_ARGUMENTS' && char === '/' && nextChar === '/') { states.push('COMMENT'); i += 2; continue; } else if (state === 'COMMENT' && char === '\n') { states.pop(); i++; continue; } else if (state === null && char === '(') { states.push('FUNCTION_ARGUMENTS'); i++; continue; } else if (state === 'FUNCTION_ARGUMENTS') { if (char === ')') { states.pop(); break; } if (char === 'f' && nextChar === 'l' && source[i + 2] === 'o' && source[i + 3] === 'a' && source[i + 4] === 't' && source[i + 5] === ' ') { states.push('DECLARE_VARIABLE'); argumentType = 'float'; argumentName = ''; i += 6; continue; } else if (char === 'i' && nextChar === 'n' && source[i + 2] === 't' && source[i + 3] === ' ') { states.push('DECLARE_VARIABLE'); argumentType = 'int'; argumentName = ''; i += 4; continue; } else if (char === 'v' && nextChar === 'e' && source[i + 2] === 'c' && source[i + 3] === '2' && source[i + 4] === ' ') { states.push('DECLARE_VARIABLE'); argumentType = 'vec2'; argumentName = ''; i += 5; continue; } else if (char === 'v' && nextChar === 'e' && source[i + 2] === 'c' && source[i + 3] === '3' && source[i + 4] === ' ') { states.push('DECLARE_VARIABLE'); argumentType = 'vec3'; argumentName = ''; i += 5; continue; } else if (char === 'v' && nextChar === 'e' && source[i + 2] === 'c' && source[i + 3] === '4' && source[i + 4] === ' ') { states.push('DECLARE_VARIABLE'); argumentType = 'vec4'; argumentName = ''; i += 5; continue; } } else if (state === 'DECLARE_VARIABLE') { if (argumentName === '') { if (char === ' ') { i++; continue; } if (!isStartingVariableName.test(char)) { throw new Error('variable name is not expected string'); } } argumentName += char; if (!isVariableChar.test(nextChar)) { states.pop(); argumentNames.push(argumentName); argumentTypes.push(typeMap[argumentType]); } } i++; } if (states.length > 0) { throw new Error('GLSL function was not parsable'); } return { argumentNames, argumentTypes, }; } static nativeFunctionReturnType(source) { return typeMap[source.match(/int|float|vec[2-4]/)[0]]; } static combineKernels(combinedKernel, lastKernel) { combinedKernel.apply(null, arguments); const { texSize, context, threadDim } = lastKernel.texSize; let result; if (lastKernel.precision === 'single') { const w = texSize[0]; const h = Math.ceil(texSize[1] / 4); result = new Float32Array(w * h * 4 * 4); context.readPixels(0, 0, w, h * 4, context.RGBA, context.FLOAT, result); } else { const bytes = new Uint8Array(texSize[0] * texSize[1] * 4); context.readPixels(0, 0, texSize[0], texSize[1], context.RGBA, context.UNSIGNED_BYTE, bytes); result = new Float32Array(bytes.buffer); } result = result.subarray(0, threadDim[0] * threadDim[1] * threadDim[2]); if (lastKernel.output.length === 1) { return result; } else if (lastKernel.output.length === 2) { return utils.splitArray(result, lastKernel.output[0]); } else if (lastKernel.output.length === 3) { const cube = utils.splitArray(result, lastKernel.output[0] * lastKernel.output[1]); return cube.map(function(x) { return utils.splitArray(x, lastKernel.output[0]); }); } } constructor(source, settings) { super(source, settings); this.transferValues = null; this.formatValues = null; this.TextureConstructor = null; this.renderOutput = null; this.renderRawOutput = null; this.texSize = null; this.translatedSource = null; this.compiledFragmentShader = null; this.compiledVertexShader = null; this.switchingKernels = null; this._textureSwitched = null; this._mappedTextureSwitched = null; } checkTextureSize() { const { features } = this.constructor; if (this.texSize[0] > features.maxTextureSize || this.texSize[1] > features.maxTextureSize) { throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${features.maxTextureSize},${features.maxTextureSize}]`); } } translateSource() { throw new Error(`"translateSource" not defined on ${this.constructor.name}`); } pickRenderStrategy(args) { if (this.graphical) { this.renderRawOutput = this.readPackedPixelsToUint8Array; this.transferValues = (pixels) => pixels; this.TextureConstructor = GLTextureGraphical; return null; } if (this.precision === 'unsigned') { this.renderRawOutput = this.readPackedPixelsToUint8Array; this.transferValues = this.readPackedPixelsToFloat32Array; if (this.pipeline) { this.renderOutput = this.renderTexture; if (this.subKernels !== null) { this.renderKernels = this.renderKernelsToTextures; } switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': if (this.output[2] > 0) { this.TextureConstructor = GLTextureUnsigned3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureUnsigned2D; return null; } else { this.TextureConstructor = GLTextureUnsigned; return null; } case 'Array(2)': case 'Array(3)': case 'Array(4)': return this.requestFallback(args); } } else { if (this.subKernels !== null) { this.renderKernels = this.renderKernelsToArrays; } switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': this.renderOutput = this.renderValues; if (this.output[2] > 0) { this.TextureConstructor = GLTextureUnsigned3D; this.formatValues = utils.erect3DPackedFloat; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureUnsigned2D; this.formatValues = utils.erect2DPackedFloat; return null; } else { this.TextureConstructor = GLTextureUnsigned; this.formatValues = utils.erectPackedFloat; return null; } case 'Array(2)': case 'Array(3)': case 'Array(4)': return this.requestFallback(args); } } } else if (this.precision === 'single') { this.renderRawOutput = this.readFloatPixelsToFloat32Array; this.transferValues = this.readFloatPixelsToFloat32Array; if (this.pipeline) { this.renderOutput = this.renderTexture; if (this.subKernels !== null) { this.renderKernels = this.renderKernelsToTextures; } switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': { if (this.optimizeFloatMemory) { if (this.output[2] > 0) { this.TextureConstructor = GLTextureMemoryOptimized3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureMemoryOptimized2D; return null; } else { this.TextureConstructor = GLTextureMemoryOptimized; return null; } } else { if (this.output[2] > 0) { this.TextureConstructor = GLTextureFloat3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureFloat2D; return null; } else { this.TextureConstructor = GLTextureFloat; return null; } } } case 'Array(2)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray2Float3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray2Float2D; return null; } else { this.TextureConstructor = GLTextureArray2Float; return null; } } case 'Array(3)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray3Float3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray3Float2D; return null; } else { this.TextureConstructor = GLTextureArray3Float; return null; } } case 'Array(4)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray4Float3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray4Float2D; return null; } else { this.TextureConstructor = GLTextureArray4Float; return null; } } } } this.renderOutput = this.renderValues; if (this.subKernels !== null) { this.renderKernels = this.renderKernelsToArrays; } if (this.optimizeFloatMemory) { switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureMemoryOptimized3D; this.formatValues = utils.erectMemoryOptimized3DFloat; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureMemoryOptimized2D; this.formatValues = utils.erectMemoryOptimized2DFloat; return null; } else { this.TextureConstructor = GLTextureMemoryOptimized; this.formatValues = utils.erectMemoryOptimizedFloat; return null; } } case 'Array(2)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray2Float3D; this.formatValues = utils.erect3DArray2; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray2Float2D; this.formatValues = utils.erect2DArray2; return null; } else { this.TextureConstructor = GLTextureArray2Float; this.formatValues = utils.erectArray2; return null; } } case 'Array(3)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray3Float3D; this.formatValues = utils.erect3DArray3; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray3Float2D; this.formatValues = utils.erect2DArray3; return null; } else { this.TextureConstructor = GLTextureArray3Float; this.formatValues = utils.erectArray3; return null; } } case 'Array(4)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray4Float3D; this.formatValues = utils.erect3DArray4; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray4Float2D; this.formatValues = utils.erect2DArray4; return null; } else { this.TextureConstructor = GLTextureArray4Float; this.formatValues = utils.erectArray4; return null; } } } } else { switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureFloat3D; this.formatValues = utils.erect3DFloat; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureFloat2D; this.formatValues = utils.erect2DFloat; return null; } else { this.TextureConstructor = GLTextureFloat; this.formatValues = utils.erectFloat; return null; } } case 'Array(2)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray2Float3D; this.formatValues = utils.erect3DArray2; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray2Float2D; this.formatValues = utils.erect2DArray2; return null; } else { this.TextureConstructor = GLTextureArray2Float; this.formatValues = utils.erectArray2; return null; } } case 'Array(3)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray3Float3D; this.formatValues = utils.erect3DArray3; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray3Float2D; this.formatValues = utils.erect2DArray3; return null; } else { this.TextureConstructor = GLTextureArray3Float; this.formatValues = utils.erectArray3; return null; } } case 'Array(4)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray4Float3D; this.formatValues = utils.erect3DArray4; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray4Float2D; this.formatValues = utils.erect2DArray4; return null; } else { this.TextureConstructor = GLTextureArray4Float; this.formatValues = utils.erectArray4; return null; } } } } } else { throw new Error(`unhandled precision of "${this.precision}"`); } throw new Error(`unhandled return type "${this.returnType}"`); } getKernelString() { throw new Error(`abstract method call`); } getMainResultTexture() { switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Integer': case 'Number': return this.getMainResultNumberTexture(); case 'Array(2)': return this.getMainResultArray2Texture(); case 'Array(3)': return this.getMainResultArray3Texture(); case 'Array(4)': return this.getMainResultArray4Texture(); default: throw new Error(`unhandled returnType type ${ this.returnType }`); } } getMainResultKernelNumberTexture() { throw new Error(`abstract method call`); } getMainResultSubKernelNumberTexture() { throw new Error(`abstract method call`); } getMainResultKernelArray2Texture() { throw new Error(`abstract method call`); } getMainResultSubKernelArray2Texture() { throw new Error(`abstract method call`); } getMainResultKernelArray3Texture() { throw new Error(`abstract method call`); } getMainResultSubKernelArray3Texture() { throw new Error(`abstract method call`); } getMainResultKernelArray4Texture() { throw new Error(`abstract method call`); } getMainResultSubKernelArray4Texture() { throw new Error(`abstract method call`); } getMainResultGraphical() { throw new Error(`abstract method call`); } getMainResultMemoryOptimizedFloats() { throw new Error(`abstract method call`); } getMainResultPackedPixels() { throw new Error(`abstract method call`); } getMainResultString() { if (this.graphical) { return this.getMainResultGraphical(); } else if (this.precision === 'single') { if (this.optimizeFloatMemory) { return this.getMainResultMemoryOptimizedFloats(); } return this.getMainResultTexture(); } else { return this.getMainResultPackedPixels(); } } getMainResultNumberTexture() { return utils.linesToString(this.getMainResultKernelNumberTexture()) + utils.linesToString(this.getMainResultSubKernelNumberTexture()); } getMainResultArray2Texture() { return utils.linesToString(this.getMainResultKernelArray2Texture()) + utils.linesToString(this.getMainResultSubKernelArray2Texture()); } getMainResultArray3Texture() { return utils.linesToString(this.getMainResultKernelArray3Texture()) + utils.linesToString(this.getMainResultSubKernelArray3Texture()); } getMainResultArray4Texture() { return utils.linesToString(this.getMainResultKernelArray4Texture()) + utils.linesToString(this.getMainResultSubKernelArray4Texture()); } getFloatTacticDeclaration() { const variablePrecision = this.getVariablePrecisionString(this.texSize, this.tactic); return `precision ${variablePrecision} float;\n`; } getIntTacticDeclaration() { return `precision ${this.getVariablePrecisionString(this.texSize, this.tactic, true)} int;\n`; } getSampler2DTacticDeclaration() { return `precision ${this.getVariablePrecisionString(this.texSize, this.tactic)} sampler2D;\n`; } getSampler2DArrayTacticDeclaration() { return `precision ${this.getVariablePrecisionString(this.texSize, this.tactic)} sampler2DArray;\n`; } renderTexture() { return this.immutable ? this.texture.clone() : this.texture; } readPackedPixelsToUint8Array() { if (this.precision !== 'unsigned') throw new Error('Requires this.precision to be "unsigned"'); const { texSize, context: gl } = this; const result = new Uint8Array(texSize[0] * texSize[1] * 4); gl.readPixels(0, 0, texSize[0], texSize[1], gl.RGBA, gl.UNSIGNED_BYTE, result); return result; } readPackedPixelsToFloat32Array() { return new Float32Array(this.readPackedPixelsToUint8Array().buffer); } readFloatPixelsToFloat32Array() { if (this.precision !== 'single') throw new Error('Requires this.precision to be "single"'); const { texSize, context: gl } = this; const w = texSize[0]; const h = texSize[1]; const result = new Float32Array(w * h * 4); gl.readPixels(0, 0, w, h, gl.RGBA, gl.FLOAT, result); return result; } getPixels(flip) { const { context: gl, output } = this; const [width, height] = output; const pixels = new Uint8Array(width * height * 4); gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); return new Uint8ClampedArray((flip ? pixels : utils.flipPixels(pixels, width, height)).buffer); } renderKernelsToArrays() { const result = { result: this.renderOutput(), }; for (let i = 0; i < this.subKernels.length; i++) { result[this.subKernels[i].property] = this.mappedTextures[i].toArray(); } return result; } renderKernelsToTextures() { const result = { result: this.renderOutput(), }; if (this.immutable) { for (let i = 0; i < this.subKernels.length; i++) { result[this.subKernels[i].property] = this.mappedTextures[i].clone(); } } else { for (let i = 0; i < this.subKernels.length; i++) { result[this.subKernels[i].property] = this.mappedTextures[i]; } } return result; } resetSwitchingKernels() { const existingValue = this.switchingKernels; this.switchingKernels = null; return existingValue; } setOutput(output) { const newOutput = this.toKernelOutput(output); if (this.program) { if (!this.dynamicOutput) { throw new Error('Resizing a kernel with dynamicOutput: false is not possible'); } const newThreadDim = [newOutput[0], newOutput[1] || 1, newOutput[2] || 1]; const newTexSize = utils.getKernelTextureSize({ optimizeFloatMemory: this.optimizeFloatMemory, precision: this.precision, }, newThreadDim); const oldTexSize = this.texSize; if (oldTexSize) { const oldPrecision = this.getVariablePrecisionString(oldTexSize, this.tactic); const newPrecision = this.getVariablePrecisionString(newTexSize, this.tactic); if (oldPrecision !== newPrecision) { if (this.debug) { console.warn('Precision requirement changed, asking GPU instance to recompile'); } this.switchKernels({ type: 'outputPrecisionMismatch', precision: newPrecision, needed: output }); return; } } this.output = newOutput; this.threadDim = newThreadDim; this.texSize = newTexSize; const { context: gl } = this; gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); this.updateMaxTexSize(); this.framebuffer.width = this.texSize[0]; this.framebuffer.height = this.texSize[1]; gl.viewport(0, 0, this.maxTexSize[0], this.maxTexSize[1]); this.canvas.width = this.maxTexSize[0]; this.canvas.height = this.maxTexSize[1]; if (this.texture) { this.texture.delete(); } this.texture = null; this._setupOutputTexture(); if (this.mappedTextures && this.mappedTextures.length > 0) { for (let i = 0; i < this.mappedTextures.length; i++) { this.mappedTextures[i].delete(); } this.mappedTextures = null; this._setupSubOutputTextures(); } } else { this.output = newOutput; } return this; } renderValues() { return this.formatValues( this.transferValues(), this.output[0], this.output[1], this.output[2] ); } switchKernels(reason) { if (this.switchingKernels) { this.switchingKernels.push(reason); } else { this.switchingKernels = [reason]; } } getVariablePrecisionString(textureSize = this.texSize, tactic = this.tactic, isInt = false) { if (!tactic) { if (!this.constructor.features.isSpeedTacticSupported) return 'highp'; const low = this.constructor.features[isInt ? 'lowIntPrecision' : 'lowFloatPrecision']; const medium = this.constructor.features[isInt ? 'mediumIntPrecision' : 'mediumFloatPrecision']; const high = this.constructor.features[isInt ? 'highIntPrecision' : 'highFloatPrecision']; const requiredSize = Math.log2(textureSize[0] * textureSize[1]); if (requiredSize <= low.rangeMax) { return 'lowp'; } else if (requiredSize <= medium.rangeMax) { return 'mediump'; } else if (requiredSize <= high.rangeMax) { return 'highp'; } else { throw new Error(`The required size exceeds that of the ability of your system`); } } switch (tactic) { case 'speed': return 'lowp'; case 'balanced': return 'mediump'; case 'precision': return 'highp'; default: throw new Error(`Unknown tactic "${tactic}" use "speed", "balanced", "precision", or empty for auto`); } } updateTextureArgumentRefs(kernelValue, arg) { if (!this.immutable) return; if (this.texture.texture === arg.texture) { const { prevArg } = kernelValue; if (prevArg) { if (prevArg.texture._refs === 1) { this.texture.delete(); this.texture = prevArg.clone(); this._textureSwitched = true; } prevArg.delete(); } kernelValue.prevArg = arg.clone(); } else if (this.mappedTextures && this.mappedTextures.length > 0) { const { mappedTextures } = this; for (let i = 0; i < mappedTextures.length; i++) { const mappedTexture = mappedTextures[i]; if (mappedTexture.texture === arg.texture) { const { prevArg } = kernelValue; if (prevArg) { if (prevArg.texture._refs === 1) { mappedTexture.delete(); mappedTextures[i] = prevArg.clone(); this._mappedTextureSwitched[i] = true; } prevArg.delete(); } kernelValue.prevArg = arg.clone(); return; } } } } onActivate(previousKernel) { this._textureSwitched = true; this.texture = previousKernel.texture; if (this.mappedTextures) { for (let i = 0; i < this.mappedTextures.length; i++) { this._mappedTextureSwitched[i] = true; } this.mappedTextures = previousKernel.mappedTextures; } } initCanvas() {} } const typeMap = { int: 'Integer', float: 'Number', vec2: 'Array(2)', vec3: 'Array(3)', vec4: 'Array(4)', }; module.exports = { GLKernel }; },{"../../utils":113,"../kernel":35,"./texture/array-2-float":15,"./texture/array-2-float-2d":13,"./texture/array-2-float-3d":14,"./texture/array-3-float":18,"./texture/array-3-float-2d":16,"./texture/array-3-float-3d":17,"./texture/array-4-float":21,"./texture/array-4-float-2d":19,"./texture/array-4-float-3d":20,"./texture/float":24,"./texture/float-2d":22,"./texture/float-3d":23,"./texture/graphical":25,"./texture/memory-optimized":29,"./texture/memory-optimized-2d":27,"./texture/memory-optimized-3d":28,"./texture/unsigned":32,"./texture/unsigned-2d":30,"./texture/unsigned-3d":31}],13:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray2Float2D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(2)'; } toArray() { return utils.erect2DArray2(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureArray2Float2D }; },{"../../../utils":113,"./float":24}],14:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray2Float3D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(2)'; } toArray() { return utils.erect3DArray2(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureArray2Float3D }; },{"../../../utils":113,"./float":24}],15:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray2Float extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(2)'; } toArray() { return utils.erectArray2(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureArray2Float }; },{"../../../utils":113,"./float":24}],16:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray3Float2D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(3)'; } toArray() { return utils.erect2DArray3(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureArray3Float2D }; },{"../../../utils":113,"./float":24}],17:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray3Float3D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(3)'; } toArray() { return utils.erect3DArray3(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureArray3Float3D }; },{"../../../utils":113,"./float":24}],18:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray3Float extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(3)'; } toArray() { return utils.erectArray3(this.renderValues(), this.output[0]); } } module.exports = { GLTextureArray3Float }; },{"../../../utils":113,"./float":24}],19:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray4Float2D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(4)'; } toArray() { return utils.erect2DArray4(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureArray4Float2D }; },{"../../../utils":113,"./float":24}],20:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray4Float3D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(4)'; } toArray() { return utils.erect3DArray4(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureArray4Float3D }; },{"../../../utils":113,"./float":24}],21:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray4Float extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(4)'; } toArray() { return utils.erectArray4(this.renderValues(), this.output[0]); } } module.exports = { GLTextureArray4Float }; },{"../../../utils":113,"./float":24}],22:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureFloat2D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(1)'; } toArray() { return utils.erect2DFloat(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureFloat2D }; },{"../../../utils":113,"./float":24}],23:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureFloat3D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(1)'; } toArray() { return utils.erect3DFloat(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureFloat3D }; },{"../../../utils":113,"./float":24}],24:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTexture } = require('./index'); class GLTextureFloat extends GLTexture { get textureType() { return this.context.FLOAT; } constructor(settings) { super(settings); this.type = 'ArrayTexture(1)'; } renderRawOutput() { const gl = this.context; const size = this.size; gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer()); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0 ); const result = new Float32Array(size[0] * size[1] * 4); gl.readPixels(0, 0, size[0], size[1], gl.RGBA, gl.FLOAT, result); return result; } renderValues() { if (this._deleted) return null; return this.renderRawOutput(); } toArray() { return utils.erectFloat(this.renderValues(), this.output[0]); } } module.exports = { GLTextureFloat }; },{"../../../utils":113,"./index":26}],25:[function(require,module,exports){ const { GLTextureUnsigned } = require('./unsigned'); class GLTextureGraphical extends GLTextureUnsigned { constructor(settings) { super(settings); this.type = 'ArrayTexture(4)'; } toArray() { return this.renderValues(); } } module.exports = { GLTextureGraphical }; },{"./unsigned":32}],26:[function(require,module,exports){ const { Texture } = require('../../../texture'); class GLTexture extends Texture { get textureType() { throw new Error(`"textureType" not implemented on ${ this.name }`); } clone() { return new this.constructor(this); } beforeMutate() { if (this.texture._refs > 1) { this.newTexture(); return true; } return false; } cloneTexture() { this.texture._refs--; const { context: gl, size, texture, kernel } = this; if (kernel.debug) { console.warn('cloning internal texture'); } gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer()); selectTexture(gl, texture); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); const target = gl.createTexture(); selectTexture(gl, target); gl.texImage2D(gl.TEXTURE_2D, 0, this.internalFormat, size[0], size[1], 0, this.textureFormat, this.textureType, null); gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 0, 0, size[0], size[1]); target._refs = 1; this.texture = target; } newTexture() { this.texture._refs--; const gl = this.context; const size = this.size; const kernel = this.kernel; if (kernel.debug) { console.warn('new internal texture'); } const target = gl.createTexture(); selectTexture(gl, target); gl.texImage2D(gl.TEXTURE_2D, 0, this.internalFormat, size[0], size[1], 0, this.textureFormat, this.textureType, null); target._refs = 1; this.texture = target; } clear() { if (this.texture._refs) { this.texture._refs--; const gl = this.context; const target = this.texture = gl.createTexture(); selectTexture(gl, target); const size = this.size; target._refs = 1; gl.texImage2D(gl.TEXTURE_2D, 0, this.internalFormat, size[0], size[1], 0, this.textureFormat, this.textureType, null); } const { context: gl, texture } = this; gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer()); gl.bindTexture(gl.TEXTURE_2D, texture); selectTexture(gl, texture); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); } delete() { if (this._deleted) return; this._deleted = true; if (this.texture._refs) { this.texture._refs--; if (this.texture._refs) return; } this.context.deleteTexture(this.texture); } framebuffer() { if (!this._framebuffer) { this._framebuffer = this.kernel.getRawValueFramebuffer(this.size[0], this.size[1]); } return this._framebuffer; } } function selectTexture(gl, texture) { gl.activeTexture(gl.TEXTURE15); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); } module.exports = { GLTexture }; },{"../../../texture":112}],27:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureMemoryOptimized2D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'MemoryOptimizedNumberTexture'; } toArray() { return utils.erectMemoryOptimized2DFloat(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureMemoryOptimized2D }; },{"../../../utils":113,"./float":24}],28:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureMemoryOptimized3D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'MemoryOptimizedNumberTexture'; } toArray() { return utils.erectMemoryOptimized3DFloat(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureMemoryOptimized3D }; },{"../../../utils":113,"./float":24}],29:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureMemoryOptimized extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'MemoryOptimizedNumberTexture'; } toArray() { return utils.erectMemoryOptimizedFloat(this.renderValues(), this.output[0]); } } module.exports = { GLTextureMemoryOptimized }; },{"../../../utils":113,"./float":24}],30:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureUnsigned } = require('./unsigned'); class GLTextureUnsigned2D extends GLTextureUnsigned { constructor(settings) { super(settings); this.type = 'NumberTexture'; } toArray() { return utils.erect2DPackedFloat(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureUnsigned2D }; },{"../../../utils":113,"./unsigned":32}],31:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureUnsigned } = require('./unsigned'); class GLTextureUnsigned3D extends GLTextureUnsigned { constructor(settings) { super(settings); this.type = 'NumberTexture'; } toArray() { return utils.erect3DPackedFloat(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureUnsigned3D }; },{"../../../utils":113,"./unsigned":32}],32:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTexture } = require('./index'); class GLTextureUnsigned extends GLTexture { get textureType() { return this.context.UNSIGNED_BYTE; } constructor(settings) { super(settings); this.type = 'NumberTexture'; } renderRawOutput() { const { context: gl } = this; gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer()); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0 ); const result = new Uint8Array(this.size[0] * this.size[1] * 4); gl.readPixels(0, 0, this.size[0], this.size[1], gl.RGBA, gl.UNSIGNED_BYTE, result); return result; } renderValues() { if (this._deleted) return null; return new Float32Array(this.renderRawOutput().buffer); } toArray() { return utils.erectPackedFloat(this.renderValues(), this.output[0]); } } module.exports = { GLTextureUnsigned }; },{"../../../utils":113,"./index":26}],33:[function(require,module,exports){ const getContext = require('gl'); const { WebGLKernel } = require('../web-gl/kernel'); const { glKernelString } = require('../gl/kernel-string'); let isSupported = null; let testCanvas = null; let testContext = null; let testExtensions = null; let features = null; class HeadlessGLKernel extends WebGLKernel { static get isSupported() { if (isSupported !== null) return isSupported; this.setupFeatureChecks(); isSupported = testContext !== null; return isSupported; } static setupFeatureChecks() { testCanvas = null; testExtensions = null; if (typeof getContext !== 'function') return; try { testContext = getContext(2, 2, { preserveDrawingBuffer: true }); if (!testContext || !testContext.getExtension) return; testExtensions = { STACKGL_resize_drawingbuffer: testContext.getExtension('STACKGL_resize_drawingbuffer'), STACKGL_destroy_context: testContext.getExtension('STACKGL_destroy_context'), OES_texture_float: testContext.getExtension('OES_texture_float'), OES_texture_float_linear: testContext.getExtension('OES_texture_float_linear'), OES_element_index_uint: testContext.getExtension('OES_element_index_uint'), WEBGL_draw_buffers: testContext.getExtension('WEBGL_draw_buffers'), WEBGL_color_buffer_float: testContext.getExtension('WEBGL_color_buffer_float'), }; features = this.getFeatures(); } catch (e) { console.warn(e); } } static isContextMatch(context) { try { return context.getParameter(context.RENDERER) === 'ANGLE'; } catch (e) { return false; } } static getIsTextureFloat() { return Boolean(testExtensions.OES_texture_float); } static getIsDrawBuffers() { return Boolean(testExtensions.WEBGL_draw_buffers); } static getChannelCount() { return testExtensions.WEBGL_draw_buffers ? testContext.getParameter(testExtensions.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL) : 1; } static getMaxTextureSize() { return testContext.getParameter(testContext.MAX_TEXTURE_SIZE); } static get testCanvas() { return testCanvas; } static get testContext() { return testContext; } static get features() { return features; } initCanvas() { return {}; } initContext() { return getContext(2, 2, { preserveDrawingBuffer: true }); } initExtensions() { this.extensions = { STACKGL_resize_drawingbuffer: this.context.getExtension('STACKGL_resize_drawingbuffer'), STACKGL_destroy_context: this.context.getExtension('STACKGL_destroy_context'), OES_texture_float: this.context.getExtension('OES_texture_float'), OES_texture_float_linear: this.context.getExtension('OES_texture_float_linear'), OES_element_index_uint: this.context.getExtension('OES_element_index_uint'), WEBGL_draw_buffers: this.context.getExtension('WEBGL_draw_buffers'), }; } build() { super.build.apply(this, arguments); if (!this.fallbackRequested) { this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0], this.maxTexSize[1]); } } destroyExtensions() { this.extensions.STACKGL_resize_drawingbuffer = null; this.extensions.STACKGL_destroy_context = null; this.extensions.OES_texture_float = null; this.extensions.OES_texture_float_linear = null; this.extensions.OES_element_index_uint = null; this.extensions.WEBGL_draw_buffers = null; } static destroyContext(context) { const extension = context.getExtension('STACKGL_destroy_context'); if (extension && extension.destroy) { extension.destroy(); } } toString() { const setupContextString = `const gl = context || require('gl')(1, 1);\n`; const destroyContextString = ` if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n`; return glKernelString(this.constructor, arguments, this, setupContextString, destroyContextString); } setOutput(output) { super.setOutput(output); if (this.graphical && this.extensions.STACKGL_resize_drawingbuffer) { this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0], this.maxTexSize[1]); } return this; } } module.exports = { HeadlessGLKernel }; },{"../gl/kernel-string":11,"../web-gl/kernel":69,"gl":1}],34:[function(require,module,exports){ class KernelValue { constructor(value, settings) { const { name, kernel, context, checkContext, onRequestContextHandle, onUpdateValueMismatch, origin, strictIntegers, type, tactic, } = settings; if (!name) { throw new Error('name not set'); } if (!type) { throw new Error('type not set'); } if (!origin) { throw new Error('origin not set'); } if (origin !== 'user' && origin !== 'constants') { throw new Error(`origin must be "user" or "constants" value is "${ origin }"`); } if (!onRequestContextHandle) { throw new Error('onRequestContextHandle is not set'); } this.name = name; this.origin = origin; this.tactic = tactic; this.varName = origin === 'constants' ? `constants.${name}` : name; this.kernel = kernel; this.strictIntegers = strictIntegers; this.type = value.type || type; this.size = value.size || null; this.index = null; this.context = context; this.checkContext = checkContext !== null && checkContext !== undefined ? checkContext : true; this.contextHandle = null; this.onRequestContextHandle = onRequestContextHandle; this.onUpdateValueMismatch = onUpdateValueMismatch; this.forceUploadEachRun = null; } get id() { return `${this.origin}_${name}`; } getSource() { throw new Error(`"getSource" not defined on ${ this.constructor.name }`); } updateValue(value) { throw new Error(`"updateValue" not defined on ${ this.constructor.name }`); } } module.exports = { KernelValue }; },{}],35:[function(require,module,exports){ const { utils } = require('../utils'); const { Input } = require('../input'); class Kernel { static get isSupported() { throw new Error(`"isSupported" not implemented on ${ this.name }`); } static isContextMatch(context) { throw new Error(`"isContextMatch" not implemented on ${ this.name }`); } static getFeatures() { throw new Error(`"getFeatures" not implemented on ${ this.name }`); } static destroyContext(context) { throw new Error(`"destroyContext" called on ${ this.name }`); } static nativeFunctionArguments() { throw new Error(`"nativeFunctionArguments" called on ${ this.name }`); } static nativeFunctionReturnType() { throw new Error(`"nativeFunctionReturnType" called on ${ this.name }`); } static combineKernels() { throw new Error(`"combineKernels" called on ${ this.name }`); } constructor(source, settings) { if (typeof source !== 'object') { if (typeof source !== 'string') { throw new Error('source not a string'); } if (!utils.isFunctionString(source)) { throw new Error('source not a function string'); } } this.useLegacyEncoder = false; this.fallbackRequested = false; this.onRequestFallback = null; this.argumentNames = typeof source === 'string' ? utils.getArgumentNamesFromString(source) : null; this.argumentTypes = null; this.argumentSizes = null; this.argumentBitRatios = null; this.kernelArguments = null; this.kernelConstants = null; this.forceUploadKernelConstants = null; this.source = source; this.output = null; this.debug = false; this.graphical = false; this.loopMaxIterations = 0; this.constants = null; this.constantTypes = null; this.constantBitRatios = null; this.dynamicArguments = false; this.dynamicOutput = false; this.canvas = null; this.context = null; this.checkContext = null; this.gpu = null; this.functions = null; this.nativeFunctions = null; this.injectedNative = null; this.subKernels = null; this.validate = true; this.immutable = false; this.pipeline = false; this.precision = null; this.tactic = null; this.plugins = null; this.returnType = null; this.leadingReturnStatement = null; this.followingReturnStatement = null; this.optimizeFloatMemory = null; this.strictIntegers = false; this.fixIntegerDivisionAccuracy = null; this.built = false; this.signature = null; } mergeSettings(settings) { for (let p in settings) { if (!settings.hasOwnProperty(p) || !this.hasOwnProperty(p)) continue; switch (p) { case 'output': if (!Array.isArray(settings.output)) { this.setOutput(settings.output); continue; } break; case 'functions': this.functions = []; for (let i = 0; i < settings.functions.length; i++) { this.addFunction(settings.functions[i]); } continue; case 'graphical': if (settings[p] && !settings.hasOwnProperty('precision')) { this.precision = 'unsigned'; } this[p] = settings[p]; continue; case 'nativeFunctions': if (!settings.nativeFunctions) continue; this.nativeFunctions = []; for (let i = 0; i < settings.nativeFunctions.length; i++) { const s = settings.nativeFunctions[i]; const { name, source } = s; this.addNativeFunction(name, source, s); } continue; } this[p] = settings[p]; } if (!this.canvas) this.canvas = this.initCanvas(); if (!this.context) this.context = this.initContext(); if (!this.plugins) this.plugins = this.initPlugins(settings); } build() { throw new Error(`"build" not defined on ${ this.constructor.name }`); } run() { throw new Error(`"run" not defined on ${ this.constructor.name }`) } initCanvas() { throw new Error(`"initCanvas" not defined on ${ this.constructor.name }`); } initContext() { throw new Error(`"initContext" not defined on ${ this.constructor.name }`); } initPlugins(settings) { throw new Error(`"initPlugins" not defined on ${ this.constructor.name }`); } addFunction(source, settings = {}) { if (source.name && source.source && source.argumentTypes && 'returnType' in source) { this.functions.push(source); } else if ('settings' in source && 'source' in source) { this.functions.push(this.functionToIGPUFunction(source.source, source.settings)); } else if (typeof source === 'string' || typeof source === 'function') { this.functions.push(this.functionToIGPUFunction(source, settings)); } else { throw new Error(`function not properly defined`); } return this; } addNativeFunction(name, source, settings = {}) { const { argumentTypes, argumentNames } = settings.argumentTypes ? splitArgumentTypes(settings.argumentTypes) : this.constructor.nativeFunctionArguments(source) || {}; this.nativeFunctions.push({ name, source, settings, argumentTypes, argumentNames, returnType: settings.returnType || this.constructor.nativeFunctionReturnType(source) }); return this; } setupArguments(args) { this.kernelArguments = []; if (!this.argumentTypes) { if (!this.argumentTypes) { this.argumentTypes = []; for (let i = 0; i < args.length; i++) { const argType = utils.getVariableType(args[i], this.strictIntegers); const type = argType === 'Integer' ? 'Number' : argType; this.argumentTypes.push(type); this.kernelArguments.push({ type }); } } } else { for (let i = 0; i < this.argumentTypes.length; i++) { this.kernelArguments.push({ type: this.argumentTypes[i] }); } } this.argumentSizes = new Array(args.length); this.argumentBitRatios = new Int32Array(args.length); for (let i = 0; i < args.length; i++) { const arg = args[i]; this.argumentSizes[i] = arg.constructor === Input ? arg.size : null; this.argumentBitRatios[i] = this.getBitRatio(arg); } if (this.argumentNames.length !== args.length) { throw new Error(`arguments are miss-aligned`); } } setupConstants() { this.kernelConstants = []; let needsConstantTypes = this.constantTypes === null; if (needsConstantTypes) { this.constantTypes = {}; } this.constantBitRatios = {}; if (this.constants) { for (let name in this.constants) { if (needsConstantTypes) { const type = utils.getVariableType(this.constants[name], this.strictIntegers); this.constantTypes[name] = type; this.kernelConstants.push({ name, type }); } else { this.kernelConstants.push({ name, type: this.constantTypes[name] }); } this.constantBitRatios[name] = this.getBitRatio(this.constants[name]); } } } setOptimizeFloatMemory(flag) { this.optimizeFloatMemory = flag; return this; } toKernelOutput(output) { if (output.hasOwnProperty('x')) { if (output.hasOwnProperty('y')) { if (output.hasOwnProperty('z')) { return [output.x, output.y, output.z]; } else { return [output.x, output.y]; } } else { return [output.x]; } } else { return output; } } setOutput(output) { this.output = this.toKernelOutput(output); return this; } setDebug(flag) { this.debug = flag; return this; } setGraphical(flag) { this.graphical = flag; this.precision = 'unsigned'; return this; } setLoopMaxIterations(max) { this.loopMaxIterations = max; return this; } setConstants(constants) { this.constants = constants; return this; } setConstantTypes(constantTypes) { this.constantTypes = constantTypes; return this; } setFunctions(functions) { for (let i = 0; i < functions.length; i++) { this.addFunction(functions[i]); } return this; } setNativeFunctions(nativeFunctions) { for (let i = 0; i < nativeFunctions.length; i++) { const settings = nativeFunctions[i]; const { name, source } = settings; this.addNativeFunction(name, source, settings); } return this; } setInjectedNative(injectedNative) { this.injectedNative = injectedNative; return this; } setPipeline(flag) { this.pipeline = flag; return this; } setPrecision(flag) { this.precision = flag; return this; } setDimensions(flag) { utils.warnDeprecated('method', 'setDimensions', 'setOutput'); this.output = flag; return this; } setOutputToTexture(flag) { utils.warnDeprecated('method', 'setOutputToTexture', 'setPipeline'); this.pipeline = flag; return this; } setImmutable(flag) { this.immutable = flag; return this; } setCanvas(canvas) { this.canvas = canvas; return this; } setStrictIntegers(flag) { this.strictIntegers = flag; return this; } setDynamicOutput(flag) { this.dynamicOutput = flag; return this; } setHardcodeConstants(flag) { utils.warnDeprecated('method', 'setHardcodeConstants'); this.setDynamicOutput(flag); this.setDynamicArguments(flag); return this; } setDynamicArguments(flag) { this.dynamicArguments = flag; return this; } setUseLegacyEncoder(flag) { this.useLegacyEncoder = flag; return this; } setWarnVarUsage(flag) { utils.warnDeprecated('method', 'setWarnVarUsage'); return this; } getCanvas() { utils.warnDeprecated('method', 'getCanvas'); return this.canvas; } getWebGl() { utils.warnDeprecated('method', 'getWebGl'); return this.context; } setContext(context) { this.context = context; return this; } setArgumentTypes(argumentTypes) { if (Array.isArray(argumentTypes)) { this.argumentTypes = argumentTypes; } else { this.argumentTypes = []; for (const p in argumentTypes) { if (!argumentTypes.hasOwnProperty(p)) continue; const argumentIndex = this.argumentNames.indexOf(p); if (argumentIndex === -1) throw new Error(`unable to find argument ${ p }`); this.argumentTypes[argumentIndex] = argumentTypes[p]; } } return this; } setTactic(tactic) { this.tactic = tactic; return this; } requestFallback(args) { if (!this.onRequestFallback) { throw new Error(`"onRequestFallback" not defined on ${ this.constructor.name }`); } this.fallbackRequested = true; return this.onRequestFallback(args); } validateSettings() { throw new Error(`"validateSettings" not defined on ${ this.constructor.name }`); } addSubKernel(subKernel) { if (this.subKernels === null) { this.subKernels = []; } if (!subKernel.source) throw new Error('subKernel missing "source" property'); if (!subKernel.property && isNaN(subKernel.property)) throw new Error('subKernel missing "property" property'); if (!subKernel.name) throw new Error('subKernel missing "name" property'); this.subKernels.push(subKernel); return this; } destroy(removeCanvasReferences) { throw new Error(`"destroy" called on ${ this.constructor.name }`); } getBitRatio(value) { if (this.precision === 'single') { return 4; } else if (Array.isArray(value[0])) { return this.getBitRatio(value[0]); } else if (value.constructor === Input) { return this.getBitRatio(value.value); } switch (value.constructor) { case Uint8ClampedArray: case Uint8Array: case Int8Array: return 1; case Uint16Array: case Int16Array: return 2; case Float32Array: case Int32Array: default: return 4; } } getPixels(flip) { throw new Error(`"getPixels" called on ${ this.constructor.name }`); } checkOutput() { if (!this.output || !utils.isArray(this.output)) throw new Error('kernel.output not an array'); if (this.output.length < 1) throw new Error('kernel.output is empty, needs at least 1 value'); for (let i = 0; i < this.output.length; i++) { if (isNaN(this.output[i]) || this.output[i] < 1) { throw new Error(`${ this.constructor.name }.output[${ i }] incorrectly defined as \`${ this.output[i] }\`, needs to be numeric, and greater than 0`); } } } prependString(value) { throw new Error(`"prependString" called on ${ this.constructor.name }`); } hasPrependString(value) { throw new Error(`"hasPrependString" called on ${ this.constructor.name }`); } toJSON() { return { settings: { output: this.output, pipeline: this.pipeline, argumentNames: this.argumentNames, argumentsTypes: this.argumentTypes, constants: this.constants, pluginNames: this.plugins ? this.plugins.map(plugin => plugin.name) : null, returnType: this.returnType, } }; } buildSignature(args) { const Constructor = this.constructor; this.signature = Constructor.getSignature(this, Constructor.getArgumentTypes(this, args)); } static getArgumentTypes(kernel, args) { const argumentTypes = new Array(args.length); for (let i = 0; i < args.length; i++) { const arg = args[i]; const type = kernel.argumentTypes[i]; if (arg.type) { argumentTypes[i] = arg.type; } else { switch (type) { case 'Number': case 'Integer': case 'Float': case 'ArrayTexture(1)': argumentTypes[i] = utils.getVariableType(arg); break; default: argumentTypes[i] = type; } } } return argumentTypes; } static getSignature(kernel, argumentTypes) { throw new Error(`"getSignature" not implemented on ${ this.name }`); } functionToIGPUFunction(source, settings = {}) { if (typeof source !== 'string' && typeof source !== 'function') throw new Error('source not a string or function'); const sourceString = typeof source === 'string' ? source : source.toString(); let argumentTypes = []; if (Array.isArray(settings.argumentTypes)) { argumentTypes = settings.argumentTypes; } else if (typeof settings.argumentTypes === 'object') { argumentTypes = utils.getArgumentNamesFromString(sourceString) .map(name => settings.argumentTypes[name]) || []; } else { argumentTypes = settings.argumentTypes || []; } return { name: utils.getFunctionNameFromString(sourceString) || null, source: sourceString, argumentTypes, returnType: settings.returnType || null, }; } onActivate(previousKernel) {} } function splitArgumentTypes(argumentTypesObject) { const argumentNames = Object.keys(argumentTypesObject); const argumentTypes = []; for (let i = 0; i < argumentNames.length; i++) { const argumentName = argumentNames[i]; argumentTypes.push(argumentTypesObject[argumentName]); } return { argumentTypes, argumentNames }; } module.exports = { Kernel }; },{"../input":109,"../utils":113}],36:[function(require,module,exports){ const fragmentShader = `__HEADER__; __FLOAT_TACTIC_DECLARATION__; __INT_TACTIC_DECLARATION__; __SAMPLER_2D_TACTIC_DECLARATION__; const int LOOP_MAX = __LOOP_MAX__; __PLUGINS__; __CONSTANTS__; varying vec2 vTexCoord; float acosh(float x) { return log(x + sqrt(x * x - 1.0)); } float sinh(float x) { return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0; } float asinh(float x) { return log(x + sqrt(x * x + 1.0)); } float atan2(float v1, float v2) { if (v1 == 0.0 || v2 == 0.0) return 0.0; return atan(v1 / v2); } float atanh(float x) { x = (x + 1.0) / (x - 1.0); if (x < 0.0) { return 0.5 * log(-x); } return 0.5 * log(x); } float cbrt(float x) { if (x >= 0.0) { return pow(x, 1.0 / 3.0); } else { return -pow(x, 1.0 / 3.0); } } float cosh(float x) { return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; } float expm1(float x) { return pow(${Math.E}, x) - 1.0; } float fround(highp float x) { return x; } float imul(float v1, float v2) { return float(int(v1) * int(v2)); } float log10(float x) { return log2(x) * (1.0 / log2(10.0)); } float log1p(float x) { return log(1.0 + x); } float _pow(float v1, float v2) { if (v2 == 0.0) return 1.0; return pow(v1, v2); } float tanh(float x) { float e = exp(2.0 * x); return (e - 1.0) / (e + 1.0); } float trunc(float x) { if (x >= 0.0) { return floor(x); } else { return ceil(x); } } vec4 _round(vec4 x) { return floor(x + 0.5); } float _round(float x) { return floor(x + 0.5); } const int BIT_COUNT = 32; int modi(int x, int y) { return x - y * (x / y); } int bitwiseOr(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 || b > 0)) { break; } } return result; } int bitwiseXOR(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 || b > 0)) { break; } } return result; } int bitwiseAnd(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 && b > 0)) { break; } } return result; } int bitwiseNot(int a) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if (modi(a, 2) == 0) { result += n; } a = a / 2; n = n * 2; } return result; } int bitwiseZeroFillLeftShift(int n, int shift) { int maxBytes = BIT_COUNT; for (int i = 0; i < BIT_COUNT; i++) { if (maxBytes >= n) { break; } maxBytes *= 2; } for (int i = 0; i < BIT_COUNT; i++) { if (i >= shift) { break; } n *= 2; } int result = 0; int byteVal = 1; for (int i = 0; i < BIT_COUNT; i++) { if (i >= maxBytes) break; if (modi(n, 2) > 0) { result += byteVal; } n = int(n / 2); byteVal *= 2; } return result; } int bitwiseSignedRightShift(int num, int shifts) { return int(floor(float(num) / pow(2.0, float(shifts)))); } int bitwiseZeroFillRightShift(int n, int shift) { int maxBytes = BIT_COUNT; for (int i = 0; i < BIT_COUNT; i++) { if (maxBytes >= n) { break; } maxBytes *= 2; } for (int i = 0; i < BIT_COUNT; i++) { if (i >= shift) { break; } n /= 2; } int result = 0; int byteVal = 1; for (int i = 0; i < BIT_COUNT; i++) { if (i >= maxBytes) break; if (modi(n, 2) > 0) { result += byteVal; } n = int(n / 2); byteVal *= 2; } return result; } vec2 integerMod(vec2 x, float y) { vec2 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } vec3 integerMod(vec3 x, float y) { vec3 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } vec4 integerMod(vec4 x, vec4 y) { vec4 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } float integerMod(float x, float y) { float res = floor(mod(x, y)); return res * (res > floor(y) - 1.0 ? 0.0 : 1.0); } int integerMod(int x, int y) { return x - (y * int(x / y)); } __DIVIDE_WITH_INTEGER_CHECK__; // Here be dragons! // DO NOT OPTIMIZE THIS CODE // YOU WILL BREAK SOMETHING ON SOMEBODY\'S MACHINE // LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME const vec2 MAGIC_VEC = vec2(1.0, -256.0); const vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0); const vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536 float decode32(vec4 texel) { __DECODE32_ENDIANNESS__; texel *= 255.0; vec2 gte128; gte128.x = texel.b >= 128.0 ? 1.0 : 0.0; gte128.y = texel.a >= 128.0 ? 1.0 : 0.0; float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC); float res = exp2(_round(exponent)); texel.b = texel.b - 128.0 * gte128.x; res = dot(texel, SCALE_FACTOR) * exp2(_round(exponent-23.0)) + res; res *= gte128.y * -2.0 + 1.0; return res; } float decode16(vec4 texel, int index) { int channel = integerMod(index, 2); if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0; if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0; return 0.0; } float decode8(vec4 texel, int index) { int channel = integerMod(index, 4); if (channel == 0) return texel.r * 255.0; if (channel == 1) return texel.g * 255.0; if (channel == 2) return texel.b * 255.0; if (channel == 3) return texel.a * 255.0; return 0.0; } vec4 legacyEncode32(float f) { float F = abs(f); float sign = f < 0.0 ? 1.0 : 0.0; float exponent = floor(log2(F)); float mantissa = (exp2(-exponent) * F); // exponent += floor(log2(mantissa)); vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV; texel.rg = integerMod(texel.rg, 256.0); texel.b = integerMod(texel.b, 128.0); texel.a = exponent*0.5 + 63.5; texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0; texel = floor(texel); texel *= 0.003921569; // 1/255 __ENCODE32_ENDIANNESS__; return texel; } // https://github.com/gpujs/gpu.js/wiki/Encoder-details vec4 encode32(float value) { if (value == 0.0) return vec4(0, 0, 0, 0); float exponent; float mantissa; vec4 result; float sgn; sgn = step(0.0, -value); value = abs(value); exponent = floor(log2(value)); mantissa = value*pow(2.0, -exponent)-1.0; exponent = exponent+127.0; result = vec4(0,0,0,0); result.a = floor(exponent/2.0); exponent = exponent - result.a*2.0; result.a = result.a + 128.0*sgn; result.b = floor(mantissa * 128.0); mantissa = mantissa - result.b / 128.0; result.b = result.b + exponent*128.0; result.g = floor(mantissa*32768.0); mantissa = mantissa - result.g/32768.0; result.r = floor(mantissa*8388608.0); return result/255.0; } // Dragons end here int index; ivec3 threadId; ivec3 indexTo3D(int idx, ivec3 texDim) { int z = int(idx / (texDim.x * texDim.y)); idx -= z * int(texDim.x * texDim.y); int y = int(idx / texDim.x); int x = int(integerMod(idx, texDim.x)); return ivec3(x, y, z); } float get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize)); return decode32(texel); } float get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x * 2; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y)); return decode16(texel, index); } float get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x * 4; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y)); return decode8(texel, index); } float getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int channel = integerMod(index, 4); index = index / 4; int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize)); if (channel == 0) return texel.r; if (channel == 1) return texel.g; if (channel == 2) return texel.b; if (channel == 3) return texel.a; return 0.0; } vec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; return texture2D(tex, st / vec2(texSize)); } float getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return result[0]; } vec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return vec2(result[0], result[1]); } vec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + (texDim.x * (y + (texDim.y * z))); int channel = integerMod(index, 2); index = index / 2; int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize)); if (channel == 0) return vec2(texel.r, texel.g); if (channel == 1) return vec2(texel.b, texel.a); return vec2(0.0, 0.0); } vec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return vec3(result[0], result[1], result[2]); } vec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z)); int vectorIndex = fieldIndex / 4; int vectorOffset = fieldIndex - vectorIndex * 4; int readY = vectorIndex / texSize.x; int readX = vectorIndex - readY * texSize.x; vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize)); if (vectorOffset == 0) { return tex1.xyz; } else if (vectorOffset == 1) { return tex1.yzw; } else { readX++; if (readX >= texSize.x) { readX = 0; readY++; } vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize)); if (vectorOffset == 2) { return vec3(tex1.z, tex1.w, tex2.x); } else { return vec3(tex1.w, tex2.x, tex2.y); } } } vec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { return getImage2D(tex, texSize, texDim, z, y, x); } vec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int channel = integerMod(index, 2); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize)); return vec4(texel.r, texel.g, texel.b, texel.a); } vec4 actualColor; void color(float r, float g, float b, float a) { actualColor = vec4(r,g,b,a); } void color(float r, float g, float b) { color(r,g,b,1.0); } void color(sampler2D image) { actualColor = texture2D(image, vTexCoord); } float modulo(float number, float divisor) { if (number < 0.0) { number = abs(number); if (divisor < 0.0) { divisor = abs(divisor); } return -mod(number, divisor); } if (divisor < 0.0) { divisor = abs(divisor); } return mod(number, divisor); } __INJECTED_NATIVE__; __MAIN_CONSTANTS__; __MAIN_ARGUMENTS__; __KERNEL__; void main(void) { index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x; __MAIN_RESULT__; }`; module.exports = { fragmentShader }; },{}],37:[function(require,module,exports){ const { utils } = require('../../utils'); const { FunctionNode } = require('../function-node'); class WebGLFunctionNode extends FunctionNode { constructor(source, settings) { super(source, settings); if (settings && settings.hasOwnProperty('fixIntegerDivisionAccuracy')) { this.fixIntegerDivisionAccuracy = settings.fixIntegerDivisionAccuracy; } } astConditionalExpression(ast, retArr) { if (ast.type !== 'ConditionalExpression') { throw this.astErrorOutput('Not a conditional expression', ast); } const consequentType = this.getType(ast.consequent); const alternateType = this.getType(ast.alternate); if (consequentType === null && alternateType === null) { retArr.push('if ('); this.astGeneric(ast.test, retArr); retArr.push(') {'); this.astGeneric(ast.consequent, retArr); retArr.push(';'); retArr.push('} else {'); this.astGeneric(ast.alternate, retArr); retArr.push(';'); retArr.push('}'); return retArr; } retArr.push('('); this.astGeneric(ast.test, retArr); retArr.push('?'); this.astGeneric(ast.consequent, retArr); retArr.push(':'); this.astGeneric(ast.alternate, retArr); retArr.push(')'); return retArr; } astFunction(ast, retArr) { if (this.isRootKernel) { retArr.push('void'); } else { if (!this.returnType) { const lastReturn = this.findLastReturn(); if (lastReturn) { this.returnType = this.getType(ast.body); if (this.returnType === 'LiteralInteger') { this.returnType = 'Number'; } } } const { returnType } = this; if (!returnType) { retArr.push('void'); } else { const type = typeMap[returnType]; if (!type) { throw new Error(`unknown type ${returnType}`); } retArr.push(type); } } retArr.push(' '); retArr.push(this.name); retArr.push('('); if (!this.isRootKernel) { for (let i = 0; i < this.argumentNames.length; ++i) { const argumentName = this.argumentNames[i]; if (i > 0) { retArr.push(', '); } let argumentType = this.argumentTypes[this.argumentNames.indexOf(argumentName)]; if (!argumentType) { throw this.astErrorOutput(`Unknown argument ${argumentName} type`, ast); } if (argumentType === 'LiteralInteger') { this.argumentTypes[i] = argumentType = 'Number'; } const type = typeMap[argumentType]; if (!type) { throw this.astErrorOutput('Unexpected expression', ast); } const name = utils.sanitizeName(argumentName); if (type === 'sampler2D' || type === 'sampler2DArray') { retArr.push(`${type} user_${name},ivec2 user_${name}Size,ivec3 user_${name}Dim`); } else { retArr.push(`${type} user_${name}`); } } } retArr.push(') {\n'); for (let i = 0; i < ast.body.body.length; ++i) { this.astGeneric(ast.body.body[i], retArr); retArr.push('\n'); } retArr.push('}\n'); return retArr; } astReturnStatement(ast, retArr) { if (!ast.argument) throw this.astErrorOutput('Unexpected return statement', ast); this.pushState('skip-literal-correction'); const type = this.getType(ast.argument); this.popState('skip-literal-correction'); const result = []; if (!this.returnType) { if (type === 'LiteralInteger' || type === 'Integer') { this.returnType = 'Number'; } else { this.returnType = type; } } switch (this.returnType) { case 'LiteralInteger': case 'Number': case 'Float': switch (type) { case 'Integer': result.push('float('); this.astGeneric(ast.argument, result); result.push(')'); break; case 'LiteralInteger': this.castLiteralToFloat(ast.argument, result); if (this.getType(ast) === 'Integer') { result.unshift('float('); result.push(')'); } break; default: this.astGeneric(ast.argument, result); } break; case 'Integer': switch (type) { case 'Float': case 'Number': this.castValueToInteger(ast.argument, result); break; case 'LiteralInteger': this.castLiteralToInteger(ast.argument, result); break; default: this.astGeneric(ast.argument, result); } break; case 'Array(4)': case 'Array(3)': case 'Array(2)': case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': case 'Input': this.astGeneric(ast.argument, result); break; default: throw this.astErrorOutput(`unhandled return type ${this.returnType}`, ast); } if (this.isRootKernel) { retArr.push(`kernelResult = ${ result.join('') };`); retArr.push('return;'); } else if (this.isSubKernel) { retArr.push(`subKernelResult_${ this.name } = ${ result.join('') };`); retArr.push(`return subKernelResult_${ this.name };`); } else { retArr.push(`return ${ result.join('') };`); } return retArr; } astLiteral(ast, retArr) { if (isNaN(ast.value)) { throw this.astErrorOutput( 'Non-numeric literal not supported : ' + ast.value, ast ); } const key = this.astKey(ast); if (Number.isInteger(ast.value)) { if (this.isState('casting-to-integer') || this.isState('building-integer')) { this.literalTypes[key] = 'Integer'; retArr.push(`${ast.value}`); } else if (this.isState('casting-to-float') || this.isState('building-float')) { this.literalTypes[key] = 'Number'; retArr.push(`${ast.value}.0`); } else { this.literalTypes[key] = 'Number'; retArr.push(`${ast.value}.0`); } } else if (this.isState('casting-to-integer') || this.isState('building-integer')) { this.literalTypes[key] = 'Integer'; retArr.push(Math.round(ast.value)); } else { this.literalTypes[key] = 'Number'; retArr.push(`${ast.value}`); } return retArr; } astBinaryExpression(ast, retArr) { if (this.checkAndUpconvertOperator(ast, retArr)) { return retArr; } if (this.fixIntegerDivisionAccuracy && ast.operator === '/') { retArr.push('divWithIntCheck('); this.pushState('building-float'); switch (this.getType(ast.left)) { case 'Integer': this.castValueToFloat(ast.left, retArr); break; case 'LiteralInteger': this.castLiteralToFloat(ast.left, retArr); break; default: this.astGeneric(ast.left, retArr); } retArr.push(', '); switch (this.getType(ast.right)) { case 'Integer': this.castValueToFloat(ast.right, retArr); break; case 'LiteralInteger': this.castLiteralToFloat(ast.right, retArr); break; default: this.astGeneric(ast.right, retArr); } this.popState('building-float'); retArr.push(')'); return retArr; } retArr.push('('); const leftType = this.getType(ast.left) || 'Number'; const rightType = this.getType(ast.right) || 'Number'; if (!leftType || !rightType) { throw this.astErrorOutput(`Unhandled binary expression`, ast); } const key = leftType + ' & ' + rightType; switch (key) { case 'Integer & Integer': this.pushState('building-integer'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-integer'); break; case 'Number & Float': case 'Float & Number': case 'Float & Float': case 'Number & Number': this.pushState('building-float'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-float'); break; case 'LiteralInteger & LiteralInteger': if (this.isState('casting-to-integer') || this.isState('building-integer')) { this.pushState('building-integer'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-integer'); } else { this.pushState('building-float'); this.castLiteralToFloat(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castLiteralToFloat(ast.right, retArr); this.popState('building-float'); } break; case 'Integer & Float': case 'Integer & Number': if (ast.operator === '>' || ast.operator === '<' && ast.right.type === 'Literal') { if (!Number.isInteger(ast.right.value)) { this.pushState('building-float'); this.castValueToFloat(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-float'); break; } } this.pushState('building-integer'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.pushState('casting-to-integer'); if (ast.right.type === 'Literal') { const literalResult = []; this.astGeneric(ast.right, literalResult); const literalType = this.getType(ast.right); if (literalType === 'Integer') { retArr.push(literalResult.join('')); } else { throw this.astErrorOutput(`Unhandled binary expression with literal`, ast); } } else { retArr.push('int('); this.astGeneric(ast.right, retArr); retArr.push(')'); } this.popState('casting-to-integer'); this.popState('building-integer'); break; case 'Integer & LiteralInteger': this.pushState('building-integer'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castLiteralToInteger(ast.right, retArr); this.popState('building-integer'); break; case 'Number & Integer': this.pushState('building-float'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castValueToFloat(ast.right, retArr); this.popState('building-float'); break; case 'Float & LiteralInteger': case 'Number & LiteralInteger': this.pushState('building-float'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castLiteralToFloat(ast.right, retArr); this.popState('building-float'); break; case 'LiteralInteger & Float': case 'LiteralInteger & Number': if (this.isState('casting-to-integer')) { this.pushState('building-integer'); this.castLiteralToInteger(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castValueToInteger(ast.right, retArr); this.popState('building-integer'); } else { this.pushState('building-float'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.pushState('casting-to-float'); this.astGeneric(ast.right, retArr); this.popState('casting-to-float'); this.popState('building-float'); } break; case 'LiteralInteger & Integer': this.pushState('building-integer'); this.castLiteralToInteger(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-integer'); break; case 'Boolean & Boolean': this.pushState('building-boolean'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-boolean'); break; case 'Float & Integer': this.pushState('building-float'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castValueToFloat(ast.right, retArr); this.popState('building-float'); break; default: throw this.astErrorOutput(`Unhandled binary expression between ${key}`, ast); } retArr.push(')'); return retArr; } checkAndUpconvertOperator(ast, retArr) { const bitwiseResult = this.checkAndUpconvertBitwiseOperators(ast, retArr); if (bitwiseResult) { return bitwiseResult; } const upconvertableOperators = { '%': this.fixIntegerDivisionAccuracy ? 'integerCorrectionModulo' : 'modulo', '**': 'pow', }; const foundOperator = upconvertableOperators[ast.operator]; if (!foundOperator) return null; retArr.push(foundOperator); retArr.push('('); switch (this.getType(ast.left)) { case 'Integer': this.castValueToFloat(ast.left, retArr); break; case 'LiteralInteger': this.castLiteralToFloat(ast.left, retArr); break; default: this.astGeneric(ast.left, retArr); } retArr.push(','); switch (this.getType(ast.right)) { case 'Integer': this.castValueToFloat(ast.right, retArr); break; case 'LiteralInteger': this.castLiteralToFloat(ast.right, retArr); break; default: this.astGeneric(ast.right, retArr); } retArr.push(')'); return retArr; } checkAndUpconvertBitwiseOperators(ast, retArr) { const upconvertableOperators = { '&': 'bitwiseAnd', '|': 'bitwiseOr', '^': 'bitwiseXOR', '<<': 'bitwiseZeroFillLeftShift', '>>': 'bitwiseSignedRightShift', '>>>': 'bitwiseZeroFillRightShift', }; const foundOperator = upconvertableOperators[ast.operator]; if (!foundOperator) return null; retArr.push(foundOperator); retArr.push('('); const leftType = this.getType(ast.left); switch (leftType) { case 'Number': case 'Float': this.castValueToInteger(ast.left, retArr); break; case 'LiteralInteger': this.castLiteralToInteger(ast.left, retArr); break; default: this.astGeneric(ast.left, retArr); } retArr.push(','); const rightType = this.getType(ast.right); switch (rightType) { case 'Number': case 'Float': this.castValueToInteger(ast.right, retArr); break; case 'LiteralInteger': this.castLiteralToInteger(ast.right, retArr); break; default: this.astGeneric(ast.right, retArr); } retArr.push(')'); return retArr; } checkAndUpconvertBitwiseUnary(ast, retArr) { const upconvertableOperators = { '~': 'bitwiseNot', }; const foundOperator = upconvertableOperators[ast.operator]; if (!foundOperator) return null; retArr.push(foundOperator); retArr.push('('); switch (this.getType(ast.argument)) { case 'Number': case 'Float': this.castValueToInteger(ast.argument, retArr); break; case 'LiteralInteger': this.castLiteralToInteger(ast.argument, retArr); break; default: this.astGeneric(ast.argument, retArr); } retArr.push(')'); return retArr; } castLiteralToInteger(ast, retArr) { this.pushState('casting-to-integer'); this.astGeneric(ast, retArr); this.popState('casting-to-integer'); return retArr; } castLiteralToFloat(ast, retArr) { this.pushState('casting-to-float'); this.astGeneric(ast, retArr); this.popState('casting-to-float'); return retArr; } castValueToInteger(ast, retArr) { this.pushState('casting-to-integer'); retArr.push('int('); this.astGeneric(ast, retArr); retArr.push(')'); this.popState('casting-to-integer'); return retArr; } castValueToFloat(ast, retArr) { this.pushState('casting-to-float'); retArr.push('float('); this.astGeneric(ast, retArr); retArr.push(')'); this.popState('casting-to-float'); return retArr; } astIdentifierExpression(idtNode, retArr) { if (idtNode.type !== 'Identifier') { throw this.astErrorOutput('IdentifierExpression - not an Identifier', idtNode); } const type = this.getType(idtNode); const name = utils.sanitizeName(idtNode.name); if (idtNode.name === 'Infinity') { retArr.push('3.402823466e+38'); } else if (type === 'Boolean') { if (this.argumentNames.indexOf(name) > -1) { retArr.push(`bool(user_${name})`); } else { retArr.push(`user_${name}`); } } else { retArr.push(`user_${name}`); } return retArr; } astForStatement(forNode, retArr) { if (forNode.type !== 'ForStatement') { throw this.astErrorOutput('Invalid for statement', forNode); } const initArr = []; const testArr = []; const updateArr = []; const bodyArr = []; let isSafe = null; if (forNode.init) { const { declarations } = forNode.init; if (declarations.length > 1) { isSafe = false; } this.astGeneric(forNode.init, initArr); for (let i = 0; i < declarations.length; i++) { if (declarations[i].init && declarations[i].init.type !== 'Literal') { isSafe = false; } } } else { isSafe = false; } if (forNode.test) { this.astGeneric(forNode.test, testArr); } else { isSafe = false; } if (forNode.update) { this.astGeneric(forNode.update, updateArr); } else { isSafe = false; } if (forNode.body) { this.pushState('loop-body'); this.astGeneric(forNode.body, bodyArr); this.popState('loop-body'); } if (isSafe === null) { isSafe = this.isSafe(forNode.init) && this.isSafe(forNode.test); } if (isSafe) { const initString = initArr.join(''); const initNeedsSemiColon = initString[initString.length - 1] !== ';'; retArr.push(`for (${initString}${initNeedsSemiColon ? ';' : ''}${testArr.join('')};${updateArr.join('')}){\n`); retArr.push(bodyArr.join('')); retArr.push('}\n'); } else { const iVariableName = this.getInternalVariableName('safeI'); if (initArr.length > 0) { retArr.push(initArr.join(''), '\n'); } retArr.push(`for (int ${iVariableName}=0;${iVariableName} 0) { retArr.push(`if (!${testArr.join('')}) break;\n`); } retArr.push(bodyArr.join('')); retArr.push(`\n${updateArr.join('')};`); retArr.push('}\n'); } return retArr; } astWhileStatement(whileNode, retArr) { if (whileNode.type !== 'WhileStatement') { throw this.astErrorOutput('Invalid while statement', whileNode); } const iVariableName = this.getInternalVariableName('safeI'); retArr.push(`for (int ${iVariableName}=0;${iVariableName} 0) { declarationSets.push(declarationSet.join(',')); } result.push(declarationSets.join(';')); retArr.push(result.join('')); retArr.push(';'); return retArr; } astIfStatement(ifNode, retArr) { retArr.push('if ('); this.astGeneric(ifNode.test, retArr); retArr.push(')'); if (ifNode.consequent.type === 'BlockStatement') { this.astGeneric(ifNode.consequent, retArr); } else { retArr.push(' {\n'); this.astGeneric(ifNode.consequent, retArr); retArr.push('\n}\n'); } if (ifNode.alternate) { retArr.push('else '); if (ifNode.alternate.type === 'BlockStatement' || ifNode.alternate.type === 'IfStatement') { this.astGeneric(ifNode.alternate, retArr); } else { retArr.push(' {\n'); this.astGeneric(ifNode.alternate, retArr); retArr.push('\n}\n'); } } return retArr; } astSwitchStatement(ast, retArr) { if (ast.type !== 'SwitchStatement') { throw this.astErrorOutput('Invalid switch statement', ast); } const { discriminant, cases } = ast; const type = this.getType(discriminant); const varName = `switchDiscriminant${this.astKey(ast, '_')}`; switch (type) { case 'Float': case 'Number': retArr.push(`float ${varName} = `); this.astGeneric(discriminant, retArr); retArr.push(';\n'); break; case 'Integer': retArr.push(`int ${varName} = `); this.astGeneric(discriminant, retArr); retArr.push(';\n'); break; } if (cases.length === 1 && !cases[0].test) { this.astGeneric(cases[0].consequent, retArr); return retArr; } let fallingThrough = false; let defaultResult = []; let movingDefaultToEnd = false; let pastFirstIf = false; for (let i = 0; i < cases.length; i++) { if (!cases[i].test) { if (cases.length > i + 1) { movingDefaultToEnd = true; this.astGeneric(cases[i].consequent, defaultResult); continue; } else { retArr.push(' else {\n'); } } else { if (i === 0 || !pastFirstIf) { pastFirstIf = true; retArr.push(`if (${varName} == `); } else { if (fallingThrough) { retArr.push(`${varName} == `); fallingThrough = false; } else { retArr.push(` else if (${varName} == `); } } if (type === 'Integer') { const testType = this.getType(cases[i].test); switch (testType) { case 'Number': case 'Float': this.castValueToInteger(cases[i].test, retArr); break; case 'LiteralInteger': this.castLiteralToInteger(cases[i].test, retArr); break; } } else if (type === 'Float') { const testType = this.getType(cases[i].test); switch (testType) { case 'LiteralInteger': this.castLiteralToFloat(cases[i].test, retArr); break; case 'Integer': this.castValueToFloat(cases[i].test, retArr); break; } } else { throw new Error('unhanlded'); } if (!cases[i].consequent || cases[i].consequent.length === 0) { fallingThrough = true; retArr.push(' || '); continue; } retArr.push(`) {\n`); } this.astGeneric(cases[i].consequent, retArr); retArr.push('\n}'); } if (movingDefaultToEnd) { retArr.push(' else {'); retArr.push(defaultResult.join('')); retArr.push('}'); } return retArr; } astThisExpression(tNode, retArr) { retArr.push('this'); return retArr; } astMemberExpression(mNode, retArr) { const { property, name, signature, origin, type, xProperty, yProperty, zProperty } = this.getMemberExpressionDetails(mNode); switch (signature) { case 'value.thread.value': case 'this.thread.value': if (name !== 'x' && name !== 'y' && name !== 'z') { throw this.astErrorOutput('Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`', mNode); } retArr.push(`threadId.${name}`); return retArr; case 'this.output.value': if (this.dynamicOutput) { switch (name) { case 'x': if (this.isState('casting-to-float')) { retArr.push('float(uOutputDim.x)'); } else { retArr.push('uOutputDim.x'); } break; case 'y': if (this.isState('casting-to-float')) { retArr.push('float(uOutputDim.y)'); } else { retArr.push('uOutputDim.y'); } break; case 'z': if (this.isState('casting-to-float')) { retArr.push('float(uOutputDim.z)'); } else { retArr.push('uOutputDim.z'); } break; default: throw this.astErrorOutput('Unexpected expression', mNode); } } else { switch (name) { case 'x': if (this.isState('casting-to-integer')) { retArr.push(this.output[0]); } else { retArr.push(this.output[0], '.0'); } break; case 'y': if (this.isState('casting-to-integer')) { retArr.push(this.output[1]); } else { retArr.push(this.output[1], '.0'); } break; case 'z': if (this.isState('casting-to-integer')) { retArr.push(this.output[2]); } else { retArr.push(this.output[2], '.0'); } break; default: throw this.astErrorOutput('Unexpected expression', mNode); } } return retArr; case 'value': throw this.astErrorOutput('Unexpected expression', mNode); case 'value[]': case 'value[][]': case 'value[][][]': case 'value[][][][]': case 'value.value': if (origin === 'Math') { retArr.push(Math[name]); return retArr; } const cleanName = utils.sanitizeName(name); switch (property) { case 'r': retArr.push(`user_${ cleanName }.r`); return retArr; case 'g': retArr.push(`user_${ cleanName }.g`); return retArr; case 'b': retArr.push(`user_${ cleanName }.b`); return retArr; case 'a': retArr.push(`user_${ cleanName }.a`); return retArr; } break; case 'this.constants.value': if (typeof xProperty === 'undefined') { switch (type) { case 'Array(2)': case 'Array(3)': case 'Array(4)': retArr.push(`constants_${ utils.sanitizeName(name) }`); return retArr; } } case 'this.constants.value[]': case 'this.constants.value[][]': case 'this.constants.value[][][]': case 'this.constants.value[][][][]': break; case 'fn()[]': this.astCallExpression(mNode.object, retArr); retArr.push('['); retArr.push(this.memberExpressionPropertyMarkup(property)); retArr.push(']'); return retArr; case 'fn()[][]': this.astCallExpression(mNode.object.object, retArr); retArr.push('['); retArr.push(this.memberExpressionPropertyMarkup(mNode.object.property)); retArr.push(']'); retArr.push('['); retArr.push(this.memberExpressionPropertyMarkup(mNode.property)); retArr.push(']'); return retArr; case '[][]': this.astArrayExpression(mNode.object, retArr); retArr.push('['); retArr.push(this.memberExpressionPropertyMarkup(property)); retArr.push(']'); return retArr; default: throw this.astErrorOutput('Unexpected expression', mNode); } if (mNode.computed === false) { switch (type) { case 'Number': case 'Integer': case 'Float': case 'Boolean': retArr.push(`${origin}_${utils.sanitizeName(name)}`); return retArr; } } const markupName = `${origin}_${utils.sanitizeName(name)}`; switch (type) { case 'Array(2)': case 'Array(3)': case 'Array(4)': this.astGeneric(mNode.object, retArr); retArr.push('['); retArr.push(this.memberExpressionPropertyMarkup(xProperty)); retArr.push(']'); break; case 'HTMLImageArray': retArr.push(`getImage3D(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'ArrayTexture(1)': retArr.push(`getFloatFromSampler2D(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'Array1D(2)': case 'Array2D(2)': case 'Array3D(2)': retArr.push(`getMemoryOptimizedVec2(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'ArrayTexture(2)': retArr.push(`getVec2FromSampler2D(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'Array1D(3)': case 'Array2D(3)': case 'Array3D(3)': retArr.push(`getMemoryOptimizedVec3(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'ArrayTexture(3)': retArr.push(`getVec3FromSampler2D(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'Array1D(4)': case 'Array2D(4)': case 'Array3D(4)': retArr.push(`getMemoryOptimizedVec4(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'ArrayTexture(4)': case 'HTMLCanvas': case 'OffscreenCanvas': case 'HTMLImage': case 'ImageBitmap': case 'ImageData': case 'HTMLVideo': retArr.push(`getVec4FromSampler2D(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'NumberTexture': case 'Array': case 'Array2D': case 'Array3D': case 'Array4D': case 'Input': case 'Number': case 'Float': case 'Integer': if (this.precision === 'single') { retArr.push(`getMemoryOptimized32(${markupName}, ${markupName}Size, ${markupName}Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); } else { const bitRatio = (origin === 'user' ? this.lookupFunctionArgumentBitRatio(this.name, name) : this.constantBitRatios[name] ); switch (bitRatio) { case 1: retArr.push(`get8(${markupName}, ${markupName}Size, ${markupName}Dim, `); break; case 2: retArr.push(`get16(${markupName}, ${markupName}Size, ${markupName}Dim, `); break; case 4: case 0: retArr.push(`get32(${markupName}, ${markupName}Size, ${markupName}Dim, `); break; default: throw new Error(`unhandled bit ratio of ${bitRatio}`); } this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); } break; case 'MemoryOptimizedNumberTexture': retArr.push(`getMemoryOptimized32(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': retArr.push(`${markupName}[${this.memberExpressionPropertyMarkup(yProperty)}]`); if (yProperty) { retArr.push(`[${this.memberExpressionPropertyMarkup(xProperty)}]`); } break; default: throw new Error(`unhandled member expression "${ type }"`); } return retArr; } astCallExpression(ast, retArr) { if (!ast.callee) { throw this.astErrorOutput('Unknown CallExpression', ast); } let functionName = null; const isMathFunction = this.isAstMathFunction(ast); if (isMathFunction || (ast.callee.object && ast.callee.object.type === 'ThisExpression')) { functionName = ast.callee.property.name; } else if (ast.callee.type === 'SequenceExpression' && ast.callee.expressions[0].type === 'Literal' && !isNaN(ast.callee.expressions[0].raw)) { functionName = ast.callee.expressions[1].property.name; } else { functionName = ast.callee.name; } if (!functionName) { throw this.astErrorOutput(`Unhandled function, couldn't find name`, ast); } switch (functionName) { case 'pow': functionName = '_pow'; break; case 'round': functionName = '_round'; break; } if (this.calledFunctions.indexOf(functionName) < 0) { this.calledFunctions.push(functionName); } if (functionName === 'random' && this.plugins && this.plugins.length > 0) { for (let i = 0; i < this.plugins.length; i++) { const plugin = this.plugins[i]; if (plugin.functionMatch === 'Math.random()' && plugin.functionReplace) { retArr.push(plugin.functionReplace); return retArr; } } } if (this.onFunctionCall) { this.onFunctionCall(this.name, functionName, ast.arguments); } retArr.push(functionName); retArr.push('('); if (isMathFunction) { for (let i = 0; i < ast.arguments.length; ++i) { const argument = ast.arguments[i]; const argumentType = this.getType(argument); if (i > 0) { retArr.push(', '); } switch (argumentType) { case 'Integer': this.castValueToFloat(argument, retArr); break; default: this.astGeneric(argument, retArr); break; } } } else { const targetTypes = this.lookupFunctionArgumentTypes(functionName) || []; for (let i = 0; i < ast.arguments.length; ++i) { const argument = ast.arguments[i]; let targetType = targetTypes[i]; if (i > 0) { retArr.push(', '); } const argumentType = this.getType(argument); if (!targetType) { this.triggerImplyArgumentType(functionName, i, argumentType, this); targetType = argumentType; } switch (argumentType) { case 'Boolean': this.astGeneric(argument, retArr); continue; case 'Number': case 'Float': if (targetType === 'Integer') { retArr.push('int('); this.astGeneric(argument, retArr); retArr.push(')'); continue; } else if (targetType === 'Number' || targetType === 'Float') { this.astGeneric(argument, retArr); continue; } else if (targetType === 'LiteralInteger') { this.castLiteralToFloat(argument, retArr); continue; } break; case 'Integer': if (targetType === 'Number' || targetType === 'Float') { retArr.push('float('); this.astGeneric(argument, retArr); retArr.push(')'); continue; } else if (targetType === 'Integer') { this.astGeneric(argument, retArr); continue; } break; case 'LiteralInteger': if (targetType === 'Integer') { this.castLiteralToInteger(argument, retArr); continue; } else if (targetType === 'Number' || targetType === 'Float') { this.castLiteralToFloat(argument, retArr); continue; } else if (targetType === 'LiteralInteger') { this.astGeneric(argument, retArr); continue; } break; case 'Array(2)': case 'Array(3)': case 'Array(4)': if (targetType === argumentType) { if (argument.type === 'Identifier') { retArr.push(`user_${utils.sanitizeName(argument.name)}`); } else if (argument.type === 'ArrayExpression' || argument.type === 'MemberExpression' || argument.type === 'CallExpression') { this.astGeneric(argument, retArr); } else { throw this.astErrorOutput(`Unhandled argument type ${ argument.type }`, ast); } continue; } break; case 'HTMLCanvas': case 'OffscreenCanvas': case 'HTMLImage': case 'ImageBitmap': case 'ImageData': case 'HTMLImageArray': case 'HTMLVideo': case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': case 'Array': case 'Input': if (targetType === argumentType) { if (argument.type !== 'Identifier') throw this.astErrorOutput(`Unhandled argument type ${ argument.type }`, ast); this.triggerImplyArgumentBitRatio(this.name, argument.name, functionName, i); const name = utils.sanitizeName(argument.name); retArr.push(`user_${name},user_${name}Size,user_${name}Dim`); continue; } break; } throw this.astErrorOutput(`Unhandled argument combination of ${ argumentType } and ${ targetType } for argument named "${ argument.name }"`, ast); } } retArr.push(')'); return retArr; } astArrayExpression(arrNode, retArr) { const returnType = this.getType(arrNode); const arrLen = arrNode.elements.length; switch (returnType) { case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': retArr.push(`mat${arrLen}(`); break; default: retArr.push(`vec${arrLen}(`); } for (let i = 0; i < arrLen; ++i) { if (i > 0) { retArr.push(', '); } const subNode = arrNode.elements[i]; this.astGeneric(subNode, retArr) } retArr.push(')'); return retArr; } memberExpressionXYZ(x, y, z, retArr) { if (z) { retArr.push(this.memberExpressionPropertyMarkup(z), ', '); } else { retArr.push('0, '); } if (y) { retArr.push(this.memberExpressionPropertyMarkup(y), ', '); } else { retArr.push('0, '); } retArr.push(this.memberExpressionPropertyMarkup(x)); return retArr; } memberExpressionPropertyMarkup(property) { if (!property) { throw new Error('Property not set'); } const type = this.getType(property); const result = []; switch (type) { case 'Number': case 'Float': this.castValueToInteger(property, result); break; case 'LiteralInteger': this.castLiteralToInteger(property, result); break; default: this.astGeneric(property, result); } return result.join(''); } } const typeMap = { 'Array': 'sampler2D', 'Array(2)': 'vec2', 'Array(3)': 'vec3', 'Array(4)': 'vec4', 'Matrix(2)': 'mat2', 'Matrix(3)': 'mat3', 'Matrix(4)': 'mat4', 'Array2D': 'sampler2D', 'Array3D': 'sampler2D', 'Boolean': 'bool', 'Float': 'float', 'Input': 'sampler2D', 'Integer': 'int', 'Number': 'float', 'LiteralInteger': 'float', 'NumberTexture': 'sampler2D', 'MemoryOptimizedNumberTexture': 'sampler2D', 'ArrayTexture(1)': 'sampler2D', 'ArrayTexture(2)': 'sampler2D', 'ArrayTexture(3)': 'sampler2D', 'ArrayTexture(4)': 'sampler2D', 'HTMLVideo': 'sampler2D', 'HTMLCanvas': 'sampler2D', 'OffscreenCanvas': 'sampler2D', 'HTMLImage': 'sampler2D', 'ImageBitmap': 'sampler2D', 'ImageData': 'sampler2D', 'HTMLImageArray': 'sampler2DArray', }; const operatorMap = { '===': '==', '!==': '!=' }; module.exports = { WebGLFunctionNode }; },{"../../utils":113,"../function-node":9}],38:[function(require,module,exports){ const { WebGLKernelValueBoolean } = require('./kernel-value/boolean'); const { WebGLKernelValueFloat } = require('./kernel-value/float'); const { WebGLKernelValueInteger } = require('./kernel-value/integer'); const { WebGLKernelValueHTMLImage } = require('./kernel-value/html-image'); const { WebGLKernelValueDynamicHTMLImage } = require('./kernel-value/dynamic-html-image'); const { WebGLKernelValueHTMLVideo } = require('./kernel-value/html-video'); const { WebGLKernelValueDynamicHTMLVideo } = require('./kernel-value/dynamic-html-video'); const { WebGLKernelValueSingleInput } = require('./kernel-value/single-input'); const { WebGLKernelValueDynamicSingleInput } = require('./kernel-value/dynamic-single-input'); const { WebGLKernelValueUnsignedInput } = require('./kernel-value/unsigned-input'); const { WebGLKernelValueDynamicUnsignedInput } = require('./kernel-value/dynamic-unsigned-input'); const { WebGLKernelValueMemoryOptimizedNumberTexture } = require('./kernel-value/memory-optimized-number-texture'); const { WebGLKernelValueDynamicMemoryOptimizedNumberTexture } = require('./kernel-value/dynamic-memory-optimized-number-texture'); const { WebGLKernelValueNumberTexture } = require('./kernel-value/number-texture'); const { WebGLKernelValueDynamicNumberTexture } = require('./kernel-value/dynamic-number-texture'); const { WebGLKernelValueSingleArray } = require('./kernel-value/single-array'); const { WebGLKernelValueDynamicSingleArray } = require('./kernel-value/dynamic-single-array'); const { WebGLKernelValueSingleArray1DI } = require('./kernel-value/single-array1d-i'); const { WebGLKernelValueDynamicSingleArray1DI } = require('./kernel-value/dynamic-single-array1d-i'); const { WebGLKernelValueSingleArray2DI } = require('./kernel-value/single-array2d-i'); const { WebGLKernelValueDynamicSingleArray2DI } = require('./kernel-value/dynamic-single-array2d-i'); const { WebGLKernelValueSingleArray3DI } = require('./kernel-value/single-array3d-i'); const { WebGLKernelValueDynamicSingleArray3DI } = require('./kernel-value/dynamic-single-array3d-i'); const { WebGLKernelValueArray2 } = require('./kernel-value/array2'); const { WebGLKernelValueArray3 } = require('./kernel-value/array3'); const { WebGLKernelValueArray4 } = require('./kernel-value/array4'); const { WebGLKernelValueUnsignedArray } = require('./kernel-value/unsigned-array'); const { WebGLKernelValueDynamicUnsignedArray } = require('./kernel-value/dynamic-unsigned-array'); const kernelValueMaps = { unsigned: { dynamic: { 'Boolean': WebGLKernelValueBoolean, 'Integer': WebGLKernelValueInteger, 'Float': WebGLKernelValueFloat, 'Array': WebGLKernelValueDynamicUnsignedArray, 'Array(2)': WebGLKernelValueArray2, 'Array(3)': WebGLKernelValueArray3, 'Array(4)': WebGLKernelValueArray4, 'Array1D(2)': false, 'Array1D(3)': false, 'Array1D(4)': false, 'Array2D(2)': false, 'Array2D(3)': false, 'Array2D(4)': false, 'Array3D(2)': false, 'Array3D(3)': false, 'Array3D(4)': false, 'Input': WebGLKernelValueDynamicUnsignedInput, 'NumberTexture': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(1)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(2)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(3)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(4)': WebGLKernelValueDynamicNumberTexture, 'MemoryOptimizedNumberTexture': WebGLKernelValueDynamicMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGLKernelValueDynamicHTMLImage, 'OffscreenCanvas': WebGLKernelValueDynamicHTMLImage, 'HTMLImage': WebGLKernelValueDynamicHTMLImage, 'ImageBitmap': WebGLKernelValueDynamicHTMLImage, 'ImageData': WebGLKernelValueDynamicHTMLImage, 'HTMLImageArray': false, 'HTMLVideo': WebGLKernelValueDynamicHTMLVideo, }, static: { 'Boolean': WebGLKernelValueBoolean, 'Float': WebGLKernelValueFloat, 'Integer': WebGLKernelValueInteger, 'Array': WebGLKernelValueUnsignedArray, 'Array(2)': WebGLKernelValueArray2, 'Array(3)': WebGLKernelValueArray3, 'Array(4)': WebGLKernelValueArray4, 'Array1D(2)': false, 'Array1D(3)': false, 'Array1D(4)': false, 'Array2D(2)': false, 'Array2D(3)': false, 'Array2D(4)': false, 'Array3D(2)': false, 'Array3D(3)': false, 'Array3D(4)': false, 'Input': WebGLKernelValueUnsignedInput, 'NumberTexture': WebGLKernelValueNumberTexture, 'ArrayTexture(1)': WebGLKernelValueNumberTexture, 'ArrayTexture(2)': WebGLKernelValueNumberTexture, 'ArrayTexture(3)': WebGLKernelValueNumberTexture, 'ArrayTexture(4)': WebGLKernelValueNumberTexture, 'MemoryOptimizedNumberTexture': WebGLKernelValueMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGLKernelValueHTMLImage, 'OffscreenCanvas': WebGLKernelValueHTMLImage, 'HTMLImage': WebGLKernelValueHTMLImage, 'ImageBitmap': WebGLKernelValueHTMLImage, 'ImageData': WebGLKernelValueHTMLImage, 'HTMLImageArray': false, 'HTMLVideo': WebGLKernelValueHTMLVideo, } }, single: { dynamic: { 'Boolean': WebGLKernelValueBoolean, 'Integer': WebGLKernelValueInteger, 'Float': WebGLKernelValueFloat, 'Array': WebGLKernelValueDynamicSingleArray, 'Array(2)': WebGLKernelValueArray2, 'Array(3)': WebGLKernelValueArray3, 'Array(4)': WebGLKernelValueArray4, 'Array1D(2)': WebGLKernelValueDynamicSingleArray1DI, 'Array1D(3)': WebGLKernelValueDynamicSingleArray1DI, 'Array1D(4)': WebGLKernelValueDynamicSingleArray1DI, 'Array2D(2)': WebGLKernelValueDynamicSingleArray2DI, 'Array2D(3)': WebGLKernelValueDynamicSingleArray2DI, 'Array2D(4)': WebGLKernelValueDynamicSingleArray2DI, 'Array3D(2)': WebGLKernelValueDynamicSingleArray3DI, 'Array3D(3)': WebGLKernelValueDynamicSingleArray3DI, 'Array3D(4)': WebGLKernelValueDynamicSingleArray3DI, 'Input': WebGLKernelValueDynamicSingleInput, 'NumberTexture': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(1)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(2)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(3)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(4)': WebGLKernelValueDynamicNumberTexture, 'MemoryOptimizedNumberTexture': WebGLKernelValueDynamicMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGLKernelValueDynamicHTMLImage, 'OffscreenCanvas': WebGLKernelValueDynamicHTMLImage, 'HTMLImage': WebGLKernelValueDynamicHTMLImage, 'ImageBitmap': WebGLKernelValueDynamicHTMLImage, 'ImageData': WebGLKernelValueDynamicHTMLImage, 'HTMLImageArray': false, 'HTMLVideo': WebGLKernelValueDynamicHTMLVideo, }, static: { 'Boolean': WebGLKernelValueBoolean, 'Float': WebGLKernelValueFloat, 'Integer': WebGLKernelValueInteger, 'Array': WebGLKernelValueSingleArray, 'Array(2)': WebGLKernelValueArray2, 'Array(3)': WebGLKernelValueArray3, 'Array(4)': WebGLKernelValueArray4, 'Array1D(2)': WebGLKernelValueSingleArray1DI, 'Array1D(3)': WebGLKernelValueSingleArray1DI, 'Array1D(4)': WebGLKernelValueSingleArray1DI, 'Array2D(2)': WebGLKernelValueSingleArray2DI, 'Array2D(3)': WebGLKernelValueSingleArray2DI, 'Array2D(4)': WebGLKernelValueSingleArray2DI, 'Array3D(2)': WebGLKernelValueSingleArray3DI, 'Array3D(3)': WebGLKernelValueSingleArray3DI, 'Array3D(4)': WebGLKernelValueSingleArray3DI, 'Input': WebGLKernelValueSingleInput, 'NumberTexture': WebGLKernelValueNumberTexture, 'ArrayTexture(1)': WebGLKernelValueNumberTexture, 'ArrayTexture(2)': WebGLKernelValueNumberTexture, 'ArrayTexture(3)': WebGLKernelValueNumberTexture, 'ArrayTexture(4)': WebGLKernelValueNumberTexture, 'MemoryOptimizedNumberTexture': WebGLKernelValueMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGLKernelValueHTMLImage, 'OffscreenCanvas': WebGLKernelValueHTMLImage, 'HTMLImage': WebGLKernelValueHTMLImage, 'ImageBitmap': WebGLKernelValueHTMLImage, 'ImageData': WebGLKernelValueHTMLImage, 'HTMLImageArray': false, 'HTMLVideo': WebGLKernelValueHTMLVideo, } }, }; function lookupKernelValueType(type, dynamic, precision, value) { if (!type) { throw new Error('type missing'); } if (!dynamic) { throw new Error('dynamic missing'); } if (!precision) { throw new Error('precision missing'); } if (value.type) { type = value.type; } const types = kernelValueMaps[precision][dynamic]; if (types[type] === false) { return null; } else if (types[type] === undefined) { throw new Error(`Could not find a KernelValue for ${ type }`); } return types[type]; } module.exports = { lookupKernelValueType, kernelValueMaps, }; },{"./kernel-value/array2":40,"./kernel-value/array3":41,"./kernel-value/array4":42,"./kernel-value/boolean":43,"./kernel-value/dynamic-html-image":44,"./kernel-value/dynamic-html-video":45,"./kernel-value/dynamic-memory-optimized-number-texture":46,"./kernel-value/dynamic-number-texture":47,"./kernel-value/dynamic-single-array":48,"./kernel-value/dynamic-single-array1d-i":49,"./kernel-value/dynamic-single-array2d-i":50,"./kernel-value/dynamic-single-array3d-i":51,"./kernel-value/dynamic-single-input":52,"./kernel-value/dynamic-unsigned-array":53,"./kernel-value/dynamic-unsigned-input":54,"./kernel-value/float":55,"./kernel-value/html-image":56,"./kernel-value/html-video":57,"./kernel-value/integer":59,"./kernel-value/memory-optimized-number-texture":60,"./kernel-value/number-texture":61,"./kernel-value/single-array":62,"./kernel-value/single-array1d-i":63,"./kernel-value/single-array2d-i":64,"./kernel-value/single-array3d-i":65,"./kernel-value/single-input":66,"./kernel-value/unsigned-array":67,"./kernel-value/unsigned-input":68}],39:[function(require,module,exports){ const { WebGLKernelValue } = require('./index'); const { Input } = require('../../../input'); class WebGLKernelArray extends WebGLKernelValue { checkSize(width, height) { if (!this.kernel.validate) return; const { maxTextureSize } = this.kernel.constructor.features; if (width > maxTextureSize || height > maxTextureSize) { if (width > height) { throw new Error(`Argument texture width of ${width} larger than maximum size of ${maxTextureSize} for your GPU`); } else if (width < height) { throw new Error(`Argument texture height of ${height} larger than maximum size of ${maxTextureSize} for your GPU`); } else { throw new Error(`Argument texture height and width of ${height} larger than maximum size of ${maxTextureSize} for your GPU`); } } } setup() { this.requestTexture(); this.setupTexture(); this.defineTexture(); } requestTexture() { this.texture = this.onRequestTexture(); } defineTexture() { const { context: gl } = this; gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); } setupTexture() { this.contextHandle = this.onRequestContextHandle(); this.index = this.onRequestIndex(); this.dimensionsId = this.id + 'Dim'; this.sizeId = this.id + 'Size'; } getBitRatio(value) { if (Array.isArray(value[0])) { return this.getBitRatio(value[0]); } else if (value.constructor === Input) { return this.getBitRatio(value.value); } switch (value.constructor) { case Uint8ClampedArray: case Uint8Array: case Int8Array: return 1; case Uint16Array: case Int16Array: return 2; case Float32Array: case Int32Array: default: return 4; } } destroy() { if (this.prevArg) { this.prevArg.delete(); } this.context.deleteTexture(this.texture); } } module.exports = { WebGLKernelArray }; },{"../../../input":109,"./index":58}],40:[function(require,module,exports){ const { WebGLKernelValue } = require('./index'); class WebGLKernelValueArray2 extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getSource(value) { if (this.origin === 'constants') { return `const vec2 ${this.id} = vec2(${value[0]},${value[1]});\n`; } return `uniform vec2 ${this.id};\n`; } getStringValueHandler() { if (this.origin === 'constants') return ''; return `const uploadValue_${this.name} = ${this.varName};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform2fv(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueArray2 }; },{"./index":58}],41:[function(require,module,exports){ const { WebGLKernelValue } = require('./index'); class WebGLKernelValueArray3 extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getSource(value) { if (this.origin === 'constants') { return `const vec3 ${this.id} = vec3(${value[0]},${value[1]},${value[2]});\n`; } return `uniform vec3 ${this.id};\n`; } getStringValueHandler() { if (this.origin === 'constants') return ''; return `const uploadValue_${this.name} = ${this.varName};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform3fv(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueArray3 }; },{"./index":58}],42:[function(require,module,exports){ const { WebGLKernelValue } = require('./index'); class WebGLKernelValueArray4 extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getSource(value) { if (this.origin === 'constants') { return `const vec4 ${this.id} = vec4(${value[0]},${value[1]},${value[2]},${value[3]});\n`; } return `uniform vec4 ${this.id};\n`; } getStringValueHandler() { if (this.origin === 'constants') return ''; return `const uploadValue_${this.name} = ${this.varName};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform4fv(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueArray4 }; },{"./index":58}],43:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValue } = require('./index'); class WebGLKernelValueBoolean extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getSource(value) { if (this.origin === 'constants') { return `const bool ${this.id} = ${value};\n`; } return `uniform bool ${this.id};\n`; } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform1i(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueBoolean }; },{"../../../utils":113,"./index":58}],44:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueHTMLImage } = require('./html-image'); class WebGLKernelValueDynamicHTMLImage extends WebGLKernelValueHTMLImage { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { const { width, height } = value; this.checkSize(width, height); this.dimensions = [width, height, 1]; this.textureSize = [width, height]; this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicHTMLImage }; },{"../../../utils":113,"./html-image":56}],45:[function(require,module,exports){ const { WebGLKernelValueDynamicHTMLImage } = require('./dynamic-html-image'); class WebGLKernelValueDynamicHTMLVideo extends WebGLKernelValueDynamicHTMLImage {} module.exports = { WebGLKernelValueDynamicHTMLVideo }; },{"./dynamic-html-image":44}],46:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueMemoryOptimizedNumberTexture } = require('./memory-optimized-number-texture'); class WebGLKernelValueDynamicMemoryOptimizedNumberTexture extends WebGLKernelValueMemoryOptimizedNumberTexture { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(inputTexture) { this.dimensions = inputTexture.dimensions; this.checkSize(inputTexture.size[0], inputTexture.size[1]); this.textureSize = inputTexture.size; this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(inputTexture); } } module.exports = { WebGLKernelValueDynamicMemoryOptimizedNumberTexture }; },{"../../../utils":113,"./memory-optimized-number-texture":60}],47:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueNumberTexture } = require('./number-texture'); class WebGLKernelValueDynamicNumberTexture extends WebGLKernelValueNumberTexture { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.dimensions = value.dimensions; this.checkSize(value.size[0], value.size[1]); this.textureSize = value.size; this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicNumberTexture }; },{"../../../utils":113,"./number-texture":61}],48:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray } = require('./single-array'); class WebGLKernelValueDynamicSingleArray extends WebGLKernelValueSingleArray { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.dimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicSingleArray }; },{"../../../utils":113,"./single-array":62}],49:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray1DI } = require('./single-array1d-i'); class WebGLKernelValueDynamicSingleArray1DI extends WebGLKernelValueSingleArray1DI { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicSingleArray1DI }; },{"../../../utils":113,"./single-array1d-i":63}],50:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray2DI } = require('./single-array2d-i'); class WebGLKernelValueDynamicSingleArray2DI extends WebGLKernelValueSingleArray2DI { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicSingleArray2DI }; },{"../../../utils":113,"./single-array2d-i":64}],51:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray3DI } = require('./single-array3d-i'); class WebGLKernelValueDynamicSingleArray3DI extends WebGLKernelValueSingleArray3DI { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicSingleArray3DI }; },{"../../../utils":113,"./single-array3d-i":65}],52:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleInput } = require('./single-input'); class WebGLKernelValueDynamicSingleInput extends WebGLKernelValueSingleInput { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { let [w, h, d] = value.size; this.dimensions = new Int32Array([w || 1, h || 1, d || 1]); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicSingleInput }; },{"../../../utils":113,"./single-input":66}],53:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueUnsignedArray } = require('./unsigned-array'); class WebGLKernelValueDynamicUnsignedArray extends WebGLKernelValueUnsignedArray { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.dimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedPackedTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * (4 / this.bitRatio); this.checkSize(this.textureSize[0], this.textureSize[1]); const Type = this.getTransferArrayType(value); this.preUploadValue = new Type(this.uploadArrayLength); this.uploadValue = new Uint8Array(this.preUploadValue.buffer); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicUnsignedArray }; },{"../../../utils":113,"./unsigned-array":67}],54:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueUnsignedInput } = require('./unsigned-input'); class WebGLKernelValueDynamicUnsignedInput extends WebGLKernelValueUnsignedInput { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { let [w, h, d] = value.size; this.dimensions = new Int32Array([w || 1, h || 1, d || 1]); this.textureSize = utils.getMemoryOptimizedPackedTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * (4 / this.bitRatio); this.checkSize(this.textureSize[0], this.textureSize[1]); const Type = this.getTransferArrayType(value.value); this.preUploadValue = new Type(this.uploadArrayLength); this.uploadValue = new Uint8Array(this.preUploadValue.buffer); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicUnsignedInput }; },{"../../../utils":113,"./unsigned-input":68}],55:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValue } = require('./index'); class WebGLKernelValueFloat extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName};\n`; } getSource(value) { if (this.origin === 'constants') { if (Number.isInteger(value)) { return `const float ${this.id} = ${value}.0;\n`; } return `const float ${this.id} = ${value};\n`; } return `uniform float ${this.id};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform1f(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueFloat }; },{"../../../utils":113,"./index":58}],56:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueHTMLImage extends WebGLKernelArray { constructor(value, settings) { super(value, settings); const { width, height } = value; this.checkSize(width, height); this.dimensions = [width, height, 1]; this.textureSize = [width, height]; this.uploadValue = value; } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName};\n`; } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(inputImage) { if (inputImage.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(inputImage.constructor); return; } const { context: gl } = this; gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.uploadValue = inputImage); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueHTMLImage }; },{"../../../utils":113,"./array":39}],57:[function(require,module,exports){ const { WebGLKernelValueHTMLImage } = require('./html-image'); class WebGLKernelValueHTMLVideo extends WebGLKernelValueHTMLImage {} module.exports = { WebGLKernelValueHTMLVideo }; },{"./html-image":56}],58:[function(require,module,exports){ const { utils } = require('../../../utils'); const { KernelValue } = require('../../kernel-value'); class WebGLKernelValue extends KernelValue { constructor(value, settings) { super(value, settings); this.dimensionsId = null; this.sizeId = null; this.initialValueConstructor = value.constructor; this.onRequestTexture = settings.onRequestTexture; this.onRequestIndex = settings.onRequestIndex; this.uploadValue = null; this.textureSize = null; this.bitRatio = null; this.prevArg = null; } get id() { return `${this.origin}_${utils.sanitizeName(this.name)}`; } setup() {} getTransferArrayType(value) { if (Array.isArray(value[0])) { return this.getTransferArrayType(value[0]); } switch (value.constructor) { case Array: case Int32Array: case Int16Array: case Int8Array: return Float32Array; case Uint8ClampedArray: case Uint8Array: case Uint16Array: case Uint32Array: case Float32Array: case Float64Array: return value.constructor; } console.warn('Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros'); return value.constructor; } getStringValueHandler() { throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`); } getVariablePrecisionString() { return this.kernel.getVariablePrecisionString(this.textureSize || undefined, this.tactic || undefined); } destroy() {} } module.exports = { WebGLKernelValue }; },{"../../../utils":113,"../../kernel-value":34}],59:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValue } = require('./index'); class WebGLKernelValueInteger extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName};\n`; } getSource(value) { if (this.origin === 'constants') { return `const int ${this.id} = ${ parseInt(value) };\n`; } return `uniform int ${this.id};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform1i(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueInteger }; },{"../../../utils":113,"./index":58}],60:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); const sameError = `Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()`; class WebGLKernelValueMemoryOptimizedNumberTexture extends WebGLKernelArray { constructor(value, settings) { super(value, settings); const [width, height] = value.size; this.checkSize(width, height); this.dimensions = value.dimensions; this.textureSize = value.size; this.uploadValue = value.texture; this.forceUploadEachRun = true; } setup() { this.setupTexture(); } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName}.texture;\n`; } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(inputTexture) { if (inputTexture.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(inputTexture.constructor); return; } if (this.checkContext && inputTexture.context !== this.context) { throw new Error(`Value ${this.name} (${this.type}) must be from same context`); } const { kernel, context: gl } = this; if (kernel.pipeline) { if (kernel.immutable) { kernel.updateTextureArgumentRefs(this, inputTexture); } else { if (kernel.texture && kernel.texture.texture === inputTexture.texture) { throw new Error(sameError); } else if (kernel.mappedTextures) { const { mappedTextures } = kernel; for (let i = 0; i < mappedTextures.length; i++) { if (mappedTextures[i].texture === inputTexture.texture) { throw new Error(sameError); } } } } } gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.uploadValue = inputTexture.texture); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueMemoryOptimizedNumberTexture, sameError }; },{"../../../utils":113,"./array":39}],61:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); const { sameError } = require('./memory-optimized-number-texture'); class WebGLKernelValueNumberTexture extends WebGLKernelArray { constructor(value, settings) { super(value, settings); const [width, height] = value.size; this.checkSize(width, height); const { size: textureSize, dimensions } = value; this.bitRatio = this.getBitRatio(value); this.dimensions = dimensions; this.textureSize = textureSize; this.uploadValue = value.texture; this.forceUploadEachRun = true; } setup() { this.setupTexture(); } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName}.texture;\n`; } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(inputTexture) { if (inputTexture.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(inputTexture.constructor); return; } if (this.checkContext && inputTexture.context !== this.context) { throw new Error(`Value ${this.name} (${this.type}) must be from same context`); } const { kernel, context: gl } = this; if (kernel.pipeline) { if (kernel.immutable) { kernel.updateTextureArgumentRefs(this, inputTexture); } else { if (kernel.texture && kernel.texture.texture === inputTexture.texture) { throw new Error(sameError); } else if (kernel.mappedTextures) { const { mappedTextures } = kernel; for (let i = 0; i < mappedTextures.length; i++) { if (mappedTextures[i].texture === inputTexture.texture) { throw new Error(sameError); } } } } } gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.uploadValue = inputTexture.texture); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueNumberTexture }; },{"../../../utils":113,"./array":39,"./memory-optimized-number-texture":60}],62:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueSingleArray extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = 4; this.dimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); } getStringValueHandler() { return utils.linesToString([ `const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`, `flattenTo(${this.varName}, uploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueSingleArray }; },{"../../../utils":113,"./array":39}],63:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueSingleArray1DI extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = 4; this.setShape(value); } setShape(value) { const valueDimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(valueDimensions, this.bitRatio); this.dimensions = new Int32Array([valueDimensions[1], 1, 1]); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); } getStringValueHandler() { return utils.linesToString([ `const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`, `flattenTo(${this.varName}, uploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flatten2dArrayTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueSingleArray1DI }; },{"../../../utils":113,"./array":39}],64:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueSingleArray2DI extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = 4; this.setShape(value); } setShape(value) { const valueDimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(valueDimensions, this.bitRatio); this.dimensions = new Int32Array([valueDimensions[1], valueDimensions[2], 1]); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); } getStringValueHandler() { return utils.linesToString([ `const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`, `flattenTo(${this.varName}, uploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flatten3dArrayTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueSingleArray2DI }; },{"../../../utils":113,"./array":39}],65:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueSingleArray3DI extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = 4; this.setShape(value); } setShape(value) { const valueDimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(valueDimensions, this.bitRatio); this.dimensions = new Int32Array([valueDimensions[1], valueDimensions[2], valueDimensions[3]]); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); } getStringValueHandler() { return utils.linesToString([ `const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`, `flattenTo(${this.varName}, uploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flatten4dArrayTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueSingleArray3DI }; },{"../../../utils":113,"./array":39}],66:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueSingleInput extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = 4; let [w, h, d] = value.size; this.dimensions = new Int32Array([w || 1, h || 1, d || 1]); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); } getStringValueHandler() { return utils.linesToString([ `const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`, `flattenTo(${this.varName}.value, uploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(input) { if (input.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(input.constructor); return; } const { context: gl } = this; utils.flattenTo(input.value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueSingleInput }; },{"../../../utils":113,"./array":39}],67:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueUnsignedArray extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = this.getBitRatio(value); this.dimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedPackedTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * (4 / this.bitRatio); this.checkSize(this.textureSize[0], this.textureSize[1]); this.TranserArrayType = this.getTransferArrayType(value); this.preUploadValue = new this.TranserArrayType(this.uploadArrayLength); this.uploadValue = new Uint8Array(this.preUploadValue.buffer); } getStringValueHandler() { return utils.linesToString([ `const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`, `const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`, `flattenTo(${this.varName}, preUploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.preUploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueUnsignedArray }; },{"../../../utils":113,"./array":39}],68:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueUnsignedInput extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = this.getBitRatio(value); const [w, h, d] = value.size; this.dimensions = new Int32Array([w || 1, h || 1, d || 1]); this.textureSize = utils.getMemoryOptimizedPackedTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * (4 / this.bitRatio); this.checkSize(this.textureSize[0], this.textureSize[1]); this.TranserArrayType = this.getTransferArrayType(value.value); this.preUploadValue = new this.TranserArrayType(this.uploadArrayLength); this.uploadValue = new Uint8Array(this.preUploadValue.buffer); } getStringValueHandler() { return utils.linesToString([ `const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`, `const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`, `flattenTo(${this.varName}.value, preUploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(input) { if (input.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(input.value, this.preUploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueUnsignedInput }; },{"../../../utils":113,"./array":39}],69:[function(require,module,exports){ const { GLKernel } = require('../gl/kernel'); const { FunctionBuilder } = require('../function-builder'); const { WebGLFunctionNode } = require('./function-node'); const { utils } = require('../../utils'); const mrud = require('../../plugins/math-random-uniformly-distributed'); const { fragmentShader } = require('./fragment-shader'); const { vertexShader } = require('./vertex-shader'); const { glKernelString } = require('../gl/kernel-string'); const { lookupKernelValueType } = require('./kernel-value-maps'); let isSupported = null; let testCanvas = null; let testContext = null; let testExtensions = null; let features = null; const plugins = [mrud]; const canvases = []; const maxTexSizes = {}; class WebGLKernel extends GLKernel { static get isSupported() { if (isSupported !== null) { return isSupported; } this.setupFeatureChecks(); isSupported = this.isContextMatch(testContext); return isSupported; } static setupFeatureChecks() { if (typeof document !== 'undefined') { testCanvas = document.createElement('canvas'); } else if (typeof OffscreenCanvas !== 'undefined') { testCanvas = new OffscreenCanvas(0, 0); } if (!testCanvas) return; testContext = testCanvas.getContext('webgl') || testCanvas.getContext('experimental-webgl'); if (!testContext || !testContext.getExtension) return; testExtensions = { OES_texture_float: testContext.getExtension('OES_texture_float'), OES_texture_float_linear: testContext.getExtension('OES_texture_float_linear'), OES_element_index_uint: testContext.getExtension('OES_element_index_uint'), WEBGL_draw_buffers: testContext.getExtension('WEBGL_draw_buffers'), }; features = this.getFeatures(); } static isContextMatch(context) { if (typeof WebGLRenderingContext !== 'undefined') { return context instanceof WebGLRenderingContext; } return false; } static getIsTextureFloat() { return Boolean(testExtensions.OES_texture_float); } static getIsDrawBuffers() { return Boolean(testExtensions.WEBGL_draw_buffers); } static getChannelCount() { return testExtensions.WEBGL_draw_buffers ? testContext.getParameter(testExtensions.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL) : 1; } static getMaxTextureSize() { return testContext.getParameter(testContext.MAX_TEXTURE_SIZE); } static lookupKernelValueType(type, dynamic, precision, value) { return lookupKernelValueType(type, dynamic, precision, value); } static get testCanvas() { return testCanvas; } static get testContext() { return testContext; } static get features() { return features; } static get fragmentShader() { return fragmentShader; } static get vertexShader() { return vertexShader; } constructor(source, settings) { super(source, settings); this.program = null; this.pipeline = settings.pipeline; this.endianness = utils.systemEndianness(); this.extensions = {}; this.argumentTextureCount = 0; this.constantTextureCount = 0; this.fragShader = null; this.vertShader = null; this.drawBuffersMap = null; this.maxTexSize = null; this.onRequestSwitchKernel = null; this.texture = null; this.mappedTextures = null; this.mergeSettings(source.settings || settings); this.threadDim = null; this.framebuffer = null; this.buffer = null; this.textureCache = []; this.programUniformLocationCache = {}; this.uniform1fCache = {}; this.uniform1iCache = {}; this.uniform2fCache = {}; this.uniform2fvCache = {}; this.uniform2ivCache = {}; this.uniform3fvCache = {}; this.uniform3ivCache = {}; this.uniform4fvCache = {}; this.uniform4ivCache = {}; } initCanvas() { if (typeof document !== 'undefined') { const canvas = document.createElement('canvas'); canvas.width = 2; canvas.height = 2; return canvas; } else if (typeof OffscreenCanvas !== 'undefined') { return new OffscreenCanvas(0, 0); } } initContext() { const settings = { alpha: false, depth: false, antialias: false }; return this.canvas.getContext('webgl', settings) || this.canvas.getContext('experimental-webgl', settings); } initPlugins(settings) { const pluginsToUse = []; const { source } = this; if (typeof source === 'string') { for (let i = 0; i < plugins.length; i++) { const plugin = plugins[i]; if (source.match(plugin.functionMatch)) { pluginsToUse.push(plugin); } } } else if (typeof source === 'object') { if (settings.pluginNames) { for (let i = 0; i < plugins.length; i++) { const plugin = plugins[i]; const usePlugin = settings.pluginNames.some(pluginName => pluginName === plugin.name); if (usePlugin) { pluginsToUse.push(plugin); } } } } return pluginsToUse; } initExtensions() { this.extensions = { OES_texture_float: this.context.getExtension('OES_texture_float'), OES_texture_float_linear: this.context.getExtension('OES_texture_float_linear'), OES_element_index_uint: this.context.getExtension('OES_element_index_uint'), WEBGL_draw_buffers: this.context.getExtension('WEBGL_draw_buffers'), WEBGL_color_buffer_float: this.context.getExtension('WEBGL_color_buffer_float'), }; } validateSettings(args) { if (!this.validate) { this.texSize = utils.getKernelTextureSize({ optimizeFloatMemory: this.optimizeFloatMemory, precision: this.precision, }, this.output); return; } const { features } = this.constructor; if (this.optimizeFloatMemory === true && !features.isTextureFloat) { throw new Error('Float textures are not supported'); } else if (this.precision === 'single' && !features.isFloatRead) { throw new Error('Single precision not supported'); } else if (!this.graphical && this.precision === null && features.isTextureFloat) { this.precision = features.isFloatRead ? 'single' : 'unsigned'; } if (this.subKernels && this.subKernels.length > 0 && !this.extensions.WEBGL_draw_buffers) { throw new Error('could not instantiate draw buffers extension'); } if (this.fixIntegerDivisionAccuracy === null) { this.fixIntegerDivisionAccuracy = !features.isIntegerDivisionAccurate; } else if (this.fixIntegerDivisionAccuracy && features.isIntegerDivisionAccurate) { this.fixIntegerDivisionAccuracy = false; } this.checkOutput(); if (!this.output || this.output.length === 0) { if (args.length !== 1) { throw new Error('Auto output only supported for kernels with only one input'); } const argType = utils.getVariableType(args[0], this.strictIntegers); switch (argType) { case 'Array': this.output = utils.getDimensions(argType); break; case 'NumberTexture': case 'MemoryOptimizedNumberTexture': case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': this.output = args[0].output; break; default: throw new Error('Auto output not supported for input type: ' + argType); } } if (this.graphical) { if (this.output.length !== 2) { throw new Error('Output must have 2 dimensions on graphical mode'); } if (this.precision === 'precision') { this.precision = 'unsigned'; console.warn('Cannot use graphical mode and single precision at the same time'); } this.texSize = utils.clone(this.output); return; } else if (this.precision === null && features.isTextureFloat) { this.precision = 'single'; } this.texSize = utils.getKernelTextureSize({ optimizeFloatMemory: this.optimizeFloatMemory, precision: this.precision, }, this.output); this.checkTextureSize(); } updateMaxTexSize() { const { texSize, canvas } = this; if (this.maxTexSize === null) { let canvasIndex = canvases.indexOf(canvas); if (canvasIndex === -1) { canvasIndex = canvases.length; canvases.push(canvas); maxTexSizes[canvasIndex] = [texSize[0], texSize[1]]; } this.maxTexSize = maxTexSizes[canvasIndex]; } if (this.maxTexSize[0] < texSize[0]) { this.maxTexSize[0] = texSize[0]; } if (this.maxTexSize[1] < texSize[1]) { this.maxTexSize[1] = texSize[1]; } } setupArguments(args) { this.kernelArguments = []; this.argumentTextureCount = 0; const needsArgumentTypes = this.argumentTypes === null; if (needsArgumentTypes) { this.argumentTypes = []; } this.argumentSizes = []; this.argumentBitRatios = []; if (args.length < this.argumentNames.length) { throw new Error('not enough arguments for kernel'); } else if (args.length > this.argumentNames.length) { throw new Error('too many arguments for kernel'); } const { context: gl } = this; let textureIndexes = 0; const onRequestTexture = () => { return this.createTexture(); }; const onRequestIndex = () => { return this.constantTextureCount + textureIndexes++; }; const onUpdateValueMismatch = (constructor) => { this.switchKernels({ type: 'argumentMismatch', needed: constructor }); }; const onRequestContextHandle = () => { return gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount++; }; for (let index = 0; index < args.length; index++) { const value = args[index]; const name = this.argumentNames[index]; let type; if (needsArgumentTypes) { type = utils.getVariableType(value, this.strictIntegers); this.argumentTypes.push(type); } else { type = this.argumentTypes[index]; } const KernelValue = this.constructor.lookupKernelValueType(type, this.dynamicArguments ? 'dynamic' : 'static', this.precision, args[index]); if (KernelValue === null) { return this.requestFallback(args); } const kernelArgument = new KernelValue(value, { name, type, tactic: this.tactic, origin: 'user', context: gl, checkContext: this.checkContext, kernel: this, strictIntegers: this.strictIntegers, onRequestTexture, onRequestIndex, onUpdateValueMismatch, onRequestContextHandle, }); this.kernelArguments.push(kernelArgument); kernelArgument.setup(); this.argumentSizes.push(kernelArgument.textureSize); this.argumentBitRatios[index] = kernelArgument.bitRatio; } } createTexture() { const texture = this.context.createTexture(); this.textureCache.push(texture); return texture; } setupConstants(args) { const { context: gl } = this; this.kernelConstants = []; this.forceUploadKernelConstants = []; let needsConstantTypes = this.constantTypes === null; if (needsConstantTypes) { this.constantTypes = {}; } this.constantBitRatios = {}; let textureIndexes = 0; for (const name in this.constants) { const value = this.constants[name]; let type; if (needsConstantTypes) { type = utils.getVariableType(value, this.strictIntegers); this.constantTypes[name] = type; } else { type = this.constantTypes[name]; } const KernelValue = this.constructor.lookupKernelValueType(type, 'static', this.precision, value); if (KernelValue === null) { return this.requestFallback(args); } const kernelValue = new KernelValue(value, { name, type, tactic: this.tactic, origin: 'constants', context: this.context, checkContext: this.checkContext, kernel: this, strictIntegers: this.strictIntegers, onRequestTexture: () => { return this.createTexture(); }, onRequestIndex: () => { return textureIndexes++; }, onRequestContextHandle: () => { return gl.TEXTURE0 + this.constantTextureCount++; } }); this.constantBitRatios[name] = kernelValue.bitRatio; this.kernelConstants.push(kernelValue); kernelValue.setup(); if (kernelValue.forceUploadEachRun) { this.forceUploadKernelConstants.push(kernelValue); } } } build() { if (this.built) return; this.initExtensions(); this.validateSettings(arguments); this.setupConstants(arguments); if (this.fallbackRequested) return; this.setupArguments(arguments); if (this.fallbackRequested) return; this.updateMaxTexSize(); this.translateSource(); const failureResult = this.pickRenderStrategy(arguments); if (failureResult) { return failureResult; } const { texSize, context: gl, canvas } = this; gl.enable(gl.SCISSOR_TEST); if (this.pipeline && this.precision === 'single') { gl.viewport(0, 0, this.maxTexSize[0], this.maxTexSize[1]); canvas.width = this.maxTexSize[0]; canvas.height = this.maxTexSize[1]; } else { gl.viewport(0, 0, this.maxTexSize[0], this.maxTexSize[1]); canvas.width = this.maxTexSize[0]; canvas.height = this.maxTexSize[1]; } const threadDim = this.threadDim = Array.from(this.output); while (threadDim.length < 3) { threadDim.push(1); } const compiledVertexShader = this.getVertexShader(arguments); const vertShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertShader, compiledVertexShader); gl.compileShader(vertShader); this.vertShader = vertShader; const compiledFragmentShader = this.getFragmentShader(arguments); const fragShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragShader, compiledFragmentShader); gl.compileShader(fragShader); this.fragShader = fragShader; if (this.debug) { console.log('GLSL Shader Output:'); console.log(compiledFragmentShader); } if (!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) { throw new Error('Error compiling vertex shader: ' + gl.getShaderInfoLog(vertShader)); } if (!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) { throw new Error('Error compiling fragment shader: ' + gl.getShaderInfoLog(fragShader)); } const program = this.program = gl.createProgram(); gl.attachShader(program, vertShader); gl.attachShader(program, fragShader); gl.linkProgram(program); this.framebuffer = gl.createFramebuffer(); this.framebuffer.width = texSize[0]; this.framebuffer.height = texSize[1]; this.rawValueFramebuffers = {}; const vertices = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1 ]); const texCoords = new Float32Array([ 0, 0, 1, 0, 0, 1, 1, 1 ]); const texCoordOffset = vertices.byteLength; let buffer = this.buffer; if (!buffer) { buffer = this.buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, vertices.byteLength + texCoords.byteLength, gl.STATIC_DRAW); } else { gl.bindBuffer(gl.ARRAY_BUFFER, buffer); } gl.bufferSubData(gl.ARRAY_BUFFER, 0, vertices); gl.bufferSubData(gl.ARRAY_BUFFER, texCoordOffset, texCoords); const aPosLoc = gl.getAttribLocation(this.program, 'aPos'); gl.enableVertexAttribArray(aPosLoc); gl.vertexAttribPointer(aPosLoc, 2, gl.FLOAT, false, 0, 0); const aTexCoordLoc = gl.getAttribLocation(this.program, 'aTexCoord'); gl.enableVertexAttribArray(aTexCoordLoc); gl.vertexAttribPointer(aTexCoordLoc, 2, gl.FLOAT, false, 0, texCoordOffset); gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); let i = 0; gl.useProgram(this.program); for (let p in this.constants) { this.kernelConstants[i++].updateValue(this.constants[p]); } this._setupOutputTexture(); if ( this.subKernels !== null && this.subKernels.length > 0 ) { this._mappedTextureSwitched = {}; this._setupSubOutputTextures(); } this.buildSignature(arguments); this.built = true; } translateSource() { const functionBuilder = FunctionBuilder.fromKernel(this, WebGLFunctionNode, { fixIntegerDivisionAccuracy: this.fixIntegerDivisionAccuracy }); this.translatedSource = functionBuilder.getPrototypeString('kernel'); this.setupReturnTypes(functionBuilder); } setupReturnTypes(functionBuilder) { if (!this.graphical && !this.returnType) { this.returnType = functionBuilder.getKernelResultType(); } if (this.subKernels && this.subKernels.length > 0) { for (let i = 0; i < this.subKernels.length; i++) { const subKernel = this.subKernels[i]; if (!subKernel.returnType) { subKernel.returnType = functionBuilder.getSubKernelResultType(i); } } } } run() { const { kernelArguments, texSize, forceUploadKernelConstants, context: gl } = this; gl.useProgram(this.program); gl.scissor(0, 0, texSize[0], texSize[1]); if (this.dynamicOutput) { this.setUniform3iv('uOutputDim', new Int32Array(this.threadDim)); this.setUniform2iv('uTexSize', texSize); } this.setUniform2f('ratio', texSize[0] / this.maxTexSize[0], texSize[1] / this.maxTexSize[1]); for (let i = 0; i < forceUploadKernelConstants.length; i++) { const constant = forceUploadKernelConstants[i]; constant.updateValue(this.constants[constant.name]); if (this.switchingKernels) return; } for (let i = 0; i < kernelArguments.length; i++) { kernelArguments[i].updateValue(arguments[i]); if (this.switchingKernels) return; } if (this.plugins) { for (let i = 0; i < this.plugins.length; i++) { const plugin = this.plugins[i]; if (plugin.onBeforeRun) { plugin.onBeforeRun(this); } } } if (this.graphical) { if (this.pipeline) { gl.bindRenderbuffer(gl.RENDERBUFFER, null); gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); if (this.immutable) { this._replaceOutputTexture(); } gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); return this.immutable ? this.texture.clone() : this.texture; } gl.bindRenderbuffer(gl.RENDERBUFFER, null); gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); return; } gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); if (this.immutable) { this._replaceOutputTexture(); } if (this.subKernels !== null) { if (this.immutable) { this._replaceSubOutputTextures(); } this.drawBuffers(); } gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); } drawBuffers() { this.extensions.WEBGL_draw_buffers.drawBuffersWEBGL(this.drawBuffersMap); } getInternalFormat() { return this.context.RGBA; } getTextureFormat() { const { context: gl } = this; switch (this.getInternalFormat()) { case gl.RGBA: return gl.RGBA; default: throw new Error('Unknown internal format'); } } _replaceOutputTexture() { if (this.texture.beforeMutate() || this._textureSwitched) { const gl = this.context; gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); this._textureSwitched = false; } } _setupOutputTexture() { const gl = this.context; const texSize = this.texSize; if (this.texture) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); return; } const texture = this.createTexture(); gl.activeTexture(gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); const format = this.getInternalFormat(); if (this.precision === 'single') { gl.texImage2D(gl.TEXTURE_2D, 0, format, texSize[0], texSize[1], 0, gl.RGBA, gl.FLOAT, null); } else { gl.texImage2D(gl.TEXTURE_2D, 0, format, texSize[0], texSize[1], 0, format, gl.UNSIGNED_BYTE, null); } gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); this.texture = new this.TextureConstructor({ texture, size: texSize, dimensions: this.threadDim, output: this.output, context: this.context, internalFormat: this.getInternalFormat(), textureFormat: this.getTextureFormat(), kernel: this, }); } _replaceSubOutputTextures() { const gl = this.context; for (let i = 0; i < this.mappedTextures.length; i++) { const mappedTexture = this.mappedTextures[i]; if (mappedTexture.beforeMutate() || this._mappedTextureSwitched[i]) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, mappedTexture.texture, 0); this._mappedTextureSwitched[i] = false; } } } _setupSubOutputTextures() { const gl = this.context; if (this.mappedTextures) { for (let i = 0; i < this.subKernels.length; i++) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, this.mappedTextures[i].texture, 0); } return; } const texSize = this.texSize; this.drawBuffersMap = [gl.COLOR_ATTACHMENT0]; this.mappedTextures = []; for (let i = 0; i < this.subKernels.length; i++) { const texture = this.createTexture(); this.drawBuffersMap.push(gl.COLOR_ATTACHMENT0 + i + 1); gl.activeTexture(gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount + i); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); if (this.precision === 'single') { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize[0], texSize[1], 0, gl.RGBA, gl.FLOAT, null); } else { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize[0], texSize[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, texture, 0); this.mappedTextures.push(new this.TextureConstructor({ texture, size: texSize, dimensions: this.threadDim, output: this.output, context: this.context, internalFormat: this.getInternalFormat(), textureFormat: this.getTextureFormat(), kernel: this, })); } } setUniform1f(name, value) { if (this.uniform1fCache.hasOwnProperty(name)) { const cache = this.uniform1fCache[name]; if (value === cache) { return; } } this.uniform1fCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform1f(loc, value); } setUniform1i(name, value) { if (this.uniform1iCache.hasOwnProperty(name)) { const cache = this.uniform1iCache[name]; if (value === cache) { return; } } this.uniform1iCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform1i(loc, value); } setUniform2f(name, value1, value2) { if (this.uniform2fCache.hasOwnProperty(name)) { const cache = this.uniform2fCache[name]; if ( value1 === cache[0] && value2 === cache[1] ) { return; } } this.uniform2fCache[name] = [value1, value2]; const loc = this.getUniformLocation(name); this.context.uniform2f(loc, value1, value2); } setUniform2fv(name, value) { if (this.uniform2fvCache.hasOwnProperty(name)) { const cache = this.uniform2fvCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] ) { return; } } this.uniform2fvCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform2fv(loc, value); } setUniform2iv(name, value) { if (this.uniform2ivCache.hasOwnProperty(name)) { const cache = this.uniform2ivCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] ) { return; } } this.uniform2ivCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform2iv(loc, value); } setUniform3fv(name, value) { if (this.uniform3fvCache.hasOwnProperty(name)) { const cache = this.uniform3fvCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] && value[2] === cache[2] ) { return; } } this.uniform3fvCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform3fv(loc, value); } setUniform3iv(name, value) { if (this.uniform3ivCache.hasOwnProperty(name)) { const cache = this.uniform3ivCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] && value[2] === cache[2] ) { return; } } this.uniform3ivCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform3iv(loc, value); } setUniform4fv(name, value) { if (this.uniform4fvCache.hasOwnProperty(name)) { const cache = this.uniform4fvCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] && value[2] === cache[2] && value[3] === cache[3] ) { return; } } this.uniform4fvCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform4fv(loc, value); } setUniform4iv(name, value) { if (this.uniform4ivCache.hasOwnProperty(name)) { const cache = this.uniform4ivCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] && value[2] === cache[2] && value[3] === cache[3] ) { return; } } this.uniform4ivCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform4iv(loc, value); } getUniformLocation(name) { if (this.programUniformLocationCache.hasOwnProperty(name)) { return this.programUniformLocationCache[name]; } return this.programUniformLocationCache[name] = this.context.getUniformLocation(this.program, name); } _getFragShaderArtifactMap(args) { return { HEADER: this._getHeaderString(), LOOP_MAX: this._getLoopMaxString(), PLUGINS: this._getPluginsString(), CONSTANTS: this._getConstantsString(), DECODE32_ENDIANNESS: this._getDecode32EndiannessString(), ENCODE32_ENDIANNESS: this._getEncode32EndiannessString(), DIVIDE_WITH_INTEGER_CHECK: this._getDivideWithIntegerCheckString(), INJECTED_NATIVE: this._getInjectedNative(), MAIN_CONSTANTS: this._getMainConstantsString(), MAIN_ARGUMENTS: this._getMainArgumentsString(args), KERNEL: this.getKernelString(), MAIN_RESULT: this.getMainResultString(), FLOAT_TACTIC_DECLARATION: this.getFloatTacticDeclaration(), INT_TACTIC_DECLARATION: this.getIntTacticDeclaration(), SAMPLER_2D_TACTIC_DECLARATION: this.getSampler2DTacticDeclaration(), SAMPLER_2D_ARRAY_TACTIC_DECLARATION: this.getSampler2DArrayTacticDeclaration(), }; } _getVertShaderArtifactMap(args) { return { FLOAT_TACTIC_DECLARATION: this.getFloatTacticDeclaration(), INT_TACTIC_DECLARATION: this.getIntTacticDeclaration(), SAMPLER_2D_TACTIC_DECLARATION: this.getSampler2DTacticDeclaration(), SAMPLER_2D_ARRAY_TACTIC_DECLARATION: this.getSampler2DArrayTacticDeclaration(), }; } _getHeaderString() { return ( this.subKernels !== null ? '#extension GL_EXT_draw_buffers : require\n' : '' ); } _getLoopMaxString() { return ( this.loopMaxIterations ? ` ${parseInt(this.loopMaxIterations)};\n` : ' 1000;\n' ); } _getPluginsString() { if (!this.plugins) return '\n'; return this.plugins.map(plugin => plugin.source && this.source.match(plugin.functionMatch) ? plugin.source : '').join('\n'); } _getConstantsString() { const result = []; const { threadDim, texSize } = this; if (this.dynamicOutput) { result.push( 'uniform ivec3 uOutputDim', 'uniform ivec2 uTexSize' ); } else { result.push( `ivec3 uOutputDim = ivec3(${threadDim[0]}, ${threadDim[1]}, ${threadDim[2]})`, `ivec2 uTexSize = ivec2(${texSize[0]}, ${texSize[1]})` ); } return utils.linesToString(result); } _getTextureCoordinate() { const subKernels = this.subKernels; if (subKernels === null || subKernels.length < 1) { return 'varying vec2 vTexCoord;\n'; } else { return 'out vec2 vTexCoord;\n'; } } _getDecode32EndiannessString() { return ( this.endianness === 'LE' ? '' : ' texel.rgba = texel.abgr;\n' ); } _getEncode32EndiannessString() { return ( this.endianness === 'LE' ? '' : ' texel.rgba = texel.abgr;\n' ); } _getDivideWithIntegerCheckString() { return this.fixIntegerDivisionAccuracy ? `float divWithIntCheck(float x, float y) { if (floor(x) == x && floor(y) == y && integerMod(x, y) == 0.0) { return float(int(x) / int(y)); } return x / y; } float integerCorrectionModulo(float number, float divisor) { if (number < 0.0) { number = abs(number); if (divisor < 0.0) { divisor = abs(divisor); } return -(number - (divisor * floor(divWithIntCheck(number, divisor)))); } if (divisor < 0.0) { divisor = abs(divisor); } return number - (divisor * floor(divWithIntCheck(number, divisor))); }` : ''; } _getMainArgumentsString(args) { const results = []; const { argumentNames } = this; for (let i = 0; i < argumentNames.length; i++) { results.push(this.kernelArguments[i].getSource(args[i])); } return results.join(''); } _getInjectedNative() { return this.injectedNative || ''; } _getMainConstantsString() { const result = []; const { constants } = this; if (constants) { let i = 0; for (const name in constants) { if (!this.constants.hasOwnProperty(name)) continue; result.push(this.kernelConstants[i++].getSource(this.constants[name])); } } return result.join(''); } getRawValueFramebuffer(width, height) { if (!this.rawValueFramebuffers[width]) { this.rawValueFramebuffers[width] = {}; } if (!this.rawValueFramebuffers[width][height]) { const framebuffer = this.context.createFramebuffer(); framebuffer.width = width; framebuffer.height = height; this.rawValueFramebuffers[width][height] = framebuffer; } return this.rawValueFramebuffers[width][height]; } getKernelResultDeclaration() { switch (this.returnType) { case 'Array(2)': return 'vec2 kernelResult'; case 'Array(3)': return 'vec3 kernelResult'; case 'Array(4)': return 'vec4 kernelResult'; case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': return 'float kernelResult'; default: if (this.graphical) { return 'float kernelResult'; } else { throw new Error(`unrecognized output type "${ this.returnType }"`); } } } getKernelString() { const result = [this.getKernelResultDeclaration()]; const { subKernels } = this; if (subKernels !== null) { switch (this.returnType) { case 'Number': case 'Float': case 'Integer': for (let i = 0; i < subKernels.length; i++) { const subKernel = subKernels[i]; result.push( subKernel.returnType === 'Integer' ? `int subKernelResult_${ subKernel.name } = 0` : `float subKernelResult_${ subKernel.name } = 0.0` ); } break; case 'Array(2)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec2 subKernelResult_${ subKernels[i].name }` ); } break; case 'Array(3)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec3 subKernelResult_${ subKernels[i].name }` ); } break; case 'Array(4)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec4 subKernelResult_${ subKernels[i].name }` ); } break; } } return utils.linesToString(result) + this.translatedSource; } getMainResultGraphical() { return utils.linesToString([ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' gl_FragColor = actualColor', ]); } getMainResultPackedPixels() { switch (this.returnType) { case 'LiteralInteger': case 'Number': case 'Integer': case 'Float': return this.getMainResultKernelPackedPixels() + this.getMainResultSubKernelPackedPixels(); default: throw new Error(`packed output only usable with Numbers, "${this.returnType}" specified`); } } getMainResultKernelPackedPixels() { return utils.linesToString([ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ` gl_FragData[0] = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(kernelResult)` ]); } getMainResultSubKernelPackedPixels() { const result = []; if (!this.subKernels) return ''; for (let i = 0; i < this.subKernels.length; i++) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` gl_FragData[${i + 1}] = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(float(subKernelResult_${this.subKernels[i].name}))` ); } else { result.push( ` gl_FragData[${i + 1}] = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(subKernelResult_${this.subKernels[i].name})` ); } } return utils.linesToString(result); } getMainResultMemoryOptimizedFloats() { const result = [ ' index *= 4', ]; switch (this.returnType) { case 'Number': case 'Integer': case 'Float': const channels = ['r', 'g', 'b', 'a']; for (let i = 0; i < channels.length; i++) { const channel = channels[i]; this.getMainResultKernelMemoryOptimizedFloats(result, channel); this.getMainResultSubKernelMemoryOptimizedFloats(result, channel); if (i + 1 < channels.length) { result.push(' index += 1'); } } break; default: throw new Error(`optimized output only usable with Numbers, ${this.returnType} specified`); } return utils.linesToString(result); } getMainResultKernelMemoryOptimizedFloats(result, channel) { result.push( ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ` gl_FragData[0].${channel} = kernelResult` ); } getMainResultSubKernelMemoryOptimizedFloats(result, channel) { if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; i++) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` gl_FragData[${i + 1}].${channel} = float(subKernelResult_${this.subKernels[i].name})` ); } else { result.push( ` gl_FragData[${i + 1}].${channel} = subKernelResult_${this.subKernels[i].name}` ); } } } getMainResultKernelNumberTexture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' gl_FragData[0][0] = kernelResult', ]; } getMainResultSubKernelNumberTexture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` gl_FragData[${i + 1}][0] = float(subKernelResult_${subKernel.name})` ); } else { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${subKernel.name}` ); } } return result; } getMainResultKernelArray2Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' gl_FragData[0][0] = kernelResult[0]', ' gl_FragData[0][1] = kernelResult[1]', ]; } getMainResultSubKernelArray2Texture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${this.subKernels[i].name}[0]`, ` gl_FragData[${i + 1}][1] = subKernelResult_${this.subKernels[i].name}[1]` ); } return result; } getMainResultKernelArray3Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' gl_FragData[0][0] = kernelResult[0]', ' gl_FragData[0][1] = kernelResult[1]', ' gl_FragData[0][2] = kernelResult[2]', ]; } getMainResultSubKernelArray3Texture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${this.subKernels[i].name}[0]`, ` gl_FragData[${i + 1}][1] = subKernelResult_${this.subKernels[i].name}[1]`, ` gl_FragData[${i + 1}][2] = subKernelResult_${this.subKernels[i].name}[2]` ); } return result; } getMainResultKernelArray4Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' gl_FragData[0] = kernelResult', ]; } getMainResultSubKernelArray4Texture() { const result = []; if (!this.subKernels) return result; switch (this.returnType) { case 'Number': case 'Float': case 'Integer': for (let i = 0; i < this.subKernels.length; ++i) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` gl_FragData[${i + 1}] = float(subKernelResult_${this.subKernels[i].name})` ); } else { result.push( ` gl_FragData[${i + 1}] = subKernelResult_${this.subKernels[i].name}` ); } } break; case 'Array(2)': for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${this.subKernels[i].name}[0]`, ` gl_FragData[${i + 1}][1] = subKernelResult_${this.subKernels[i].name}[1]` ); } break; case 'Array(3)': for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${this.subKernels[i].name}[0]`, ` gl_FragData[${i + 1}][1] = subKernelResult_${this.subKernels[i].name}[1]`, ` gl_FragData[${i + 1}][2] = subKernelResult_${this.subKernels[i].name}[2]` ); } break; case 'Array(4)': for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${this.subKernels[i].name}[0]`, ` gl_FragData[${i + 1}][1] = subKernelResult_${this.subKernels[i].name}[1]`, ` gl_FragData[${i + 1}][2] = subKernelResult_${this.subKernels[i].name}[2]`, ` gl_FragData[${i + 1}][3] = subKernelResult_${this.subKernels[i].name}[3]` ); } break; } return result; } replaceArtifacts(src, map) { return src.replace(/[ ]*__([A-Z]+[0-9]*([_]?[A-Z]*[0-9]?)*)__;\n/g, (match, artifact) => { if (map.hasOwnProperty(artifact)) { return map[artifact]; } throw `unhandled artifact ${artifact}`; }); } getFragmentShader(args) { if (this.compiledFragmentShader !== null) { return this.compiledFragmentShader; } return this.compiledFragmentShader = this.replaceArtifacts(this.constructor.fragmentShader, this._getFragShaderArtifactMap(args)); } getVertexShader(args) { if (this.compiledVertexShader !== null) { return this.compiledVertexShader; } return this.compiledVertexShader = this.replaceArtifacts(this.constructor.vertexShader, this._getVertShaderArtifactMap(args)); } toString() { const setupContextString = utils.linesToString([ `const gl = context`, ]); return glKernelString(this.constructor, arguments, this, setupContextString); } destroy(removeCanvasReferences) { if (!this.context) return; if (this.buffer) { this.context.deleteBuffer(this.buffer); } if (this.framebuffer) { this.context.deleteFramebuffer(this.framebuffer); } for (const width in this.rawValueFramebuffers) { for (const height in this.rawValueFramebuffers[width]) { this.context.deleteFramebuffer(this.rawValueFramebuffers[width][height]); delete this.rawValueFramebuffers[width][height]; } delete this.rawValueFramebuffers[width]; } if (this.vertShader) { this.context.deleteShader(this.vertShader); } if (this.fragShader) { this.context.deleteShader(this.fragShader); } if (this.program) { this.context.deleteProgram(this.program); } if (this.texture) { this.texture.delete(); const textureCacheIndex = this.textureCache.indexOf(this.texture.texture); if (textureCacheIndex > -1) { this.textureCache.splice(textureCacheIndex, 1); } this.texture = null; } if (this.mappedTextures && this.mappedTextures.length) { for (let i = 0; i < this.mappedTextures.length; i++) { const mappedTexture = this.mappedTextures[i]; mappedTexture.delete(); const textureCacheIndex = this.textureCache.indexOf(mappedTexture.texture); if (textureCacheIndex > -1) { this.textureCache.splice(textureCacheIndex, 1); } } this.mappedTextures = null; } if (this.kernelArguments) { for (let i = 0; i < this.kernelArguments.length; i++) { this.kernelArguments[i].destroy(); } } if (this.kernelConstants) { for (let i = 0; i < this.kernelConstants.length; i++) { this.kernelConstants[i].destroy(); } } while (this.textureCache.length > 0) { const texture = this.textureCache.pop(); this.context.deleteTexture(texture); } if (removeCanvasReferences) { const idx = canvases.indexOf(this.canvas); if (idx >= 0) { canvases[idx] = null; maxTexSizes[idx] = null; } } this.destroyExtensions(); delete this.context; delete this.canvas; if (!this.gpu) return; const i = this.gpu.kernels.indexOf(this); if (i === -1) return; this.gpu.kernels.splice(i, 1); } destroyExtensions() { this.extensions.OES_texture_float = null; this.extensions.OES_texture_float_linear = null; this.extensions.OES_element_index_uint = null; this.extensions.WEBGL_draw_buffers = null; } static destroyContext(context) { const extension = context.getExtension('WEBGL_lose_context'); if (extension) { extension.loseContext(); } } toJSON() { const json = super.toJSON(); json.functionNodes = FunctionBuilder.fromKernel(this, WebGLFunctionNode).toJSON(); json.settings.threadDim = this.threadDim; return json; } } module.exports = { WebGLKernel }; },{"../../plugins/math-random-uniformly-distributed":111,"../../utils":113,"../function-builder":8,"../gl/kernel":12,"../gl/kernel-string":11,"./fragment-shader":36,"./function-node":37,"./kernel-value-maps":38,"./vertex-shader":70}],70:[function(require,module,exports){ const vertexShader = `__FLOAT_TACTIC_DECLARATION__; __INT_TACTIC_DECLARATION__; __SAMPLER_2D_TACTIC_DECLARATION__; attribute vec2 aPos; attribute vec2 aTexCoord; varying vec2 vTexCoord; uniform vec2 ratio; void main(void) { gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1); vTexCoord = aTexCoord; }`; module.exports = { vertexShader }; },{}],71:[function(require,module,exports){ const fragmentShader = `#version 300 es __HEADER__; __FLOAT_TACTIC_DECLARATION__; __INT_TACTIC_DECLARATION__; __SAMPLER_2D_TACTIC_DECLARATION__; __SAMPLER_2D_ARRAY_TACTIC_DECLARATION__; const int LOOP_MAX = __LOOP_MAX__; __PLUGINS__; __CONSTANTS__; in vec2 vTexCoord; float atan2(float v1, float v2) { if (v1 == 0.0 || v2 == 0.0) return 0.0; return atan(v1 / v2); } float cbrt(float x) { if (x >= 0.0) { return pow(x, 1.0 / 3.0); } else { return -pow(x, 1.0 / 3.0); } } float expm1(float x) { return pow(${Math.E}, x) - 1.0; } float fround(highp float x) { return x; } float imul(float v1, float v2) { return float(int(v1) * int(v2)); } float log10(float x) { return log2(x) * (1.0 / log2(10.0)); } float log1p(float x) { return log(1.0 + x); } float _pow(float v1, float v2) { if (v2 == 0.0) return 1.0; return pow(v1, v2); } float _round(float x) { return floor(x + 0.5); } const int BIT_COUNT = 32; int modi(int x, int y) { return x - y * (x / y); } int bitwiseOr(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 || b > 0)) { break; } } return result; } int bitwiseXOR(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 || b > 0)) { break; } } return result; } int bitwiseAnd(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 && b > 0)) { break; } } return result; } int bitwiseNot(int a) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if (modi(a, 2) == 0) { result += n; } a = a / 2; n = n * 2; } return result; } int bitwiseZeroFillLeftShift(int n, int shift) { int maxBytes = BIT_COUNT; for (int i = 0; i < BIT_COUNT; i++) { if (maxBytes >= n) { break; } maxBytes *= 2; } for (int i = 0; i < BIT_COUNT; i++) { if (i >= shift) { break; } n *= 2; } int result = 0; int byteVal = 1; for (int i = 0; i < BIT_COUNT; i++) { if (i >= maxBytes) break; if (modi(n, 2) > 0) { result += byteVal; } n = int(n / 2); byteVal *= 2; } return result; } int bitwiseSignedRightShift(int num, int shifts) { return int(floor(float(num) / pow(2.0, float(shifts)))); } int bitwiseZeroFillRightShift(int n, int shift) { int maxBytes = BIT_COUNT; for (int i = 0; i < BIT_COUNT; i++) { if (maxBytes >= n) { break; } maxBytes *= 2; } for (int i = 0; i < BIT_COUNT; i++) { if (i >= shift) { break; } n /= 2; } int result = 0; int byteVal = 1; for (int i = 0; i < BIT_COUNT; i++) { if (i >= maxBytes) break; if (modi(n, 2) > 0) { result += byteVal; } n = int(n / 2); byteVal *= 2; } return result; } vec2 integerMod(vec2 x, float y) { vec2 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } vec3 integerMod(vec3 x, float y) { vec3 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } vec4 integerMod(vec4 x, vec4 y) { vec4 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } float integerMod(float x, float y) { float res = floor(mod(x, y)); return res * (res > floor(y) - 1.0 ? 0.0 : 1.0); } int integerMod(int x, int y) { return x - (y * int(x/y)); } __DIVIDE_WITH_INTEGER_CHECK__; // Here be dragons! // DO NOT OPTIMIZE THIS CODE // YOU WILL BREAK SOMETHING ON SOMEBODY\'S MACHINE // LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME const vec2 MAGIC_VEC = vec2(1.0, -256.0); const vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0); const vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536 float decode32(vec4 texel) { __DECODE32_ENDIANNESS__; texel *= 255.0; vec2 gte128; gte128.x = texel.b >= 128.0 ? 1.0 : 0.0; gte128.y = texel.a >= 128.0 ? 1.0 : 0.0; float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC); float res = exp2(round(exponent)); texel.b = texel.b - 128.0 * gte128.x; res = dot(texel, SCALE_FACTOR) * exp2(round(exponent-23.0)) + res; res *= gte128.y * -2.0 + 1.0; return res; } float decode16(vec4 texel, int index) { int channel = integerMod(index, 2); return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0; } float decode8(vec4 texel, int index) { int channel = integerMod(index, 4); return texel[channel] * 255.0; } vec4 legacyEncode32(float f) { float F = abs(f); float sign = f < 0.0 ? 1.0 : 0.0; float exponent = floor(log2(F)); float mantissa = (exp2(-exponent) * F); // exponent += floor(log2(mantissa)); vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV; texel.rg = integerMod(texel.rg, 256.0); texel.b = integerMod(texel.b, 128.0); texel.a = exponent*0.5 + 63.5; texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0; texel = floor(texel); texel *= 0.003921569; // 1/255 __ENCODE32_ENDIANNESS__; return texel; } // https://github.com/gpujs/gpu.js/wiki/Encoder-details vec4 encode32(float value) { if (value == 0.0) return vec4(0, 0, 0, 0); float exponent; float mantissa; vec4 result; float sgn; sgn = step(0.0, -value); value = abs(value); exponent = floor(log2(value)); mantissa = value*pow(2.0, -exponent)-1.0; exponent = exponent+127.0; result = vec4(0,0,0,0); result.a = floor(exponent/2.0); exponent = exponent - result.a*2.0; result.a = result.a + 128.0*sgn; result.b = floor(mantissa * 128.0); mantissa = mantissa - result.b / 128.0; result.b = result.b + exponent*128.0; result.g = floor(mantissa*32768.0); mantissa = mantissa - result.g/32768.0; result.r = floor(mantissa*8388608.0); return result/255.0; } // Dragons end here int index; ivec3 threadId; ivec3 indexTo3D(int idx, ivec3 texDim) { int z = int(idx / (texDim.x * texDim.y)); idx -= z * int(texDim.x * texDim.y); int y = int(idx / texDim.x); int x = int(integerMod(idx, texDim.x)); return ivec3(x, y, z); } float get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture(tex, st / vec2(texSize)); return decode32(texel); } float get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + (texDim.x * (y + (texDim.y * z))); int w = texSize.x * 2; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y)); return decode16(texel, index); } float get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + (texDim.x * (y + (texDim.y * z))); int w = texSize.x * 4; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y)); return decode8(texel, index); } float getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + (texDim.x * (y + (texDim.y * z))); int channel = integerMod(index, 4); index = index / 4; int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; index = index / 4; vec4 texel = texture(tex, st / vec2(texSize)); return texel[channel]; } vec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; return texture(tex, st / vec2(texSize)); } vec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; return texture(tex, vec3(st / vec2(texSize), z)); } float getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return result[0]; } vec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return vec2(result[0], result[1]); } vec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int channel = integerMod(index, 2); index = index / 2; int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture(tex, st / vec2(texSize)); if (channel == 0) return vec2(texel.r, texel.g); if (channel == 1) return vec2(texel.b, texel.a); return vec2(0.0, 0.0); } vec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return vec3(result[0], result[1], result[2]); } vec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z)); int vectorIndex = fieldIndex / 4; int vectorOffset = fieldIndex - vectorIndex * 4; int readY = vectorIndex / texSize.x; int readX = vectorIndex - readY * texSize.x; vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize)); if (vectorOffset == 0) { return tex1.xyz; } else if (vectorOffset == 1) { return tex1.yzw; } else { readX++; if (readX >= texSize.x) { readX = 0; readY++; } vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize)); if (vectorOffset == 2) { return vec3(tex1.z, tex1.w, tex2.x); } else { return vec3(tex1.w, tex2.x, tex2.y); } } } vec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { return getImage2D(tex, texSize, texDim, z, y, x); } vec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int channel = integerMod(index, 2); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture(tex, st / vec2(texSize)); return vec4(texel.r, texel.g, texel.b, texel.a); } vec4 actualColor; void color(float r, float g, float b, float a) { actualColor = vec4(r,g,b,a); } void color(float r, float g, float b) { color(r,g,b,1.0); } float modulo(float number, float divisor) { if (number < 0.0) { number = abs(number); if (divisor < 0.0) { divisor = abs(divisor); } return -mod(number, divisor); } if (divisor < 0.0) { divisor = abs(divisor); } return mod(number, divisor); } __INJECTED_NATIVE__; __MAIN_CONSTANTS__; __MAIN_ARGUMENTS__; __KERNEL__; void main(void) { index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x; __MAIN_RESULT__; }`; module.exports = { fragmentShader }; },{}],72:[function(require,module,exports){ const { utils } = require('../../utils'); const { WebGLFunctionNode } = require('../web-gl/function-node'); class WebGL2FunctionNode extends WebGLFunctionNode { astIdentifierExpression(idtNode, retArr) { if (idtNode.type !== 'Identifier') { throw this.astErrorOutput( 'IdentifierExpression - not an Identifier', idtNode ); } const type = this.getType(idtNode); const name = utils.sanitizeName(idtNode.name); if (idtNode.name === 'Infinity') { retArr.push('intBitsToFloat(2139095039)'); } else if (type === 'Boolean') { if (this.argumentNames.indexOf(name) > -1) { retArr.push(`bool(user_${name})`); } else { retArr.push(`user_${name}`); } } else { retArr.push(`user_${name}`); } return retArr; } } module.exports = { WebGL2FunctionNode }; },{"../../utils":113,"../web-gl/function-node":37}],73:[function(require,module,exports){ const { WebGL2KernelValueBoolean } = require('./kernel-value/boolean'); const { WebGL2KernelValueFloat } = require('./kernel-value/float'); const { WebGL2KernelValueInteger } = require('./kernel-value/integer'); const { WebGL2KernelValueHTMLImage } = require('./kernel-value/html-image'); const { WebGL2KernelValueDynamicHTMLImage } = require('./kernel-value/dynamic-html-image'); const { WebGL2KernelValueHTMLImageArray } = require('./kernel-value/html-image-array'); const { WebGL2KernelValueDynamicHTMLImageArray } = require('./kernel-value/dynamic-html-image-array'); const { WebGL2KernelValueHTMLVideo } = require('./kernel-value/html-video'); const { WebGL2KernelValueDynamicHTMLVideo } = require('./kernel-value/dynamic-html-video'); const { WebGL2KernelValueSingleInput } = require('./kernel-value/single-input'); const { WebGL2KernelValueDynamicSingleInput } = require('./kernel-value/dynamic-single-input'); const { WebGL2KernelValueUnsignedInput } = require('./kernel-value/unsigned-input'); const { WebGL2KernelValueDynamicUnsignedInput } = require('./kernel-value/dynamic-unsigned-input'); const { WebGL2KernelValueMemoryOptimizedNumberTexture } = require('./kernel-value/memory-optimized-number-texture'); const { WebGL2KernelValueDynamicMemoryOptimizedNumberTexture } = require('./kernel-value/dynamic-memory-optimized-number-texture'); const { WebGL2KernelValueNumberTexture } = require('./kernel-value/number-texture'); const { WebGL2KernelValueDynamicNumberTexture } = require('./kernel-value/dynamic-number-texture'); const { WebGL2KernelValueSingleArray } = require('./kernel-value/single-array'); const { WebGL2KernelValueDynamicSingleArray } = require('./kernel-value/dynamic-single-array'); const { WebGL2KernelValueSingleArray1DI } = require('./kernel-value/single-array1d-i'); const { WebGL2KernelValueDynamicSingleArray1DI } = require('./kernel-value/dynamic-single-array1d-i'); const { WebGL2KernelValueSingleArray2DI } = require('./kernel-value/single-array2d-i'); const { WebGL2KernelValueDynamicSingleArray2DI } = require('./kernel-value/dynamic-single-array2d-i'); const { WebGL2KernelValueSingleArray3DI } = require('./kernel-value/single-array3d-i'); const { WebGL2KernelValueDynamicSingleArray3DI } = require('./kernel-value/dynamic-single-array3d-i'); const { WebGL2KernelValueArray2 } = require('./kernel-value/array2'); const { WebGL2KernelValueArray3 } = require('./kernel-value/array3'); const { WebGL2KernelValueArray4 } = require('./kernel-value/array4'); const { WebGL2KernelValueUnsignedArray } = require('./kernel-value/unsigned-array'); const { WebGL2KernelValueDynamicUnsignedArray } = require('./kernel-value/dynamic-unsigned-array'); const kernelValueMaps = { unsigned: { dynamic: { 'Boolean': WebGL2KernelValueBoolean, 'Integer': WebGL2KernelValueInteger, 'Float': WebGL2KernelValueFloat, 'Array': WebGL2KernelValueDynamicUnsignedArray, 'Array(2)': WebGL2KernelValueArray2, 'Array(3)': WebGL2KernelValueArray3, 'Array(4)': WebGL2KernelValueArray4, 'Array1D(2)': false, 'Array1D(3)': false, 'Array1D(4)': false, 'Array2D(2)': false, 'Array2D(3)': false, 'Array2D(4)': false, 'Array3D(2)': false, 'Array3D(3)': false, 'Array3D(4)': false, 'Input': WebGL2KernelValueDynamicUnsignedInput, 'NumberTexture': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(1)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(2)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(3)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(4)': WebGL2KernelValueDynamicNumberTexture, 'MemoryOptimizedNumberTexture': WebGL2KernelValueDynamicMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGL2KernelValueDynamicHTMLImage, 'OffscreenCanvas': WebGL2KernelValueDynamicHTMLImage, 'HTMLImage': WebGL2KernelValueDynamicHTMLImage, 'ImageBitmap': WebGL2KernelValueDynamicHTMLImage, 'ImageData': WebGL2KernelValueDynamicHTMLImage, 'HTMLImageArray': WebGL2KernelValueDynamicHTMLImageArray, 'HTMLVideo': WebGL2KernelValueDynamicHTMLVideo, }, static: { 'Boolean': WebGL2KernelValueBoolean, 'Float': WebGL2KernelValueFloat, 'Integer': WebGL2KernelValueInteger, 'Array': WebGL2KernelValueUnsignedArray, 'Array(2)': WebGL2KernelValueArray2, 'Array(3)': WebGL2KernelValueArray3, 'Array(4)': WebGL2KernelValueArray4, 'Array1D(2)': false, 'Array1D(3)': false, 'Array1D(4)': false, 'Array2D(2)': false, 'Array2D(3)': false, 'Array2D(4)': false, 'Array3D(2)': false, 'Array3D(3)': false, 'Array3D(4)': false, 'Input': WebGL2KernelValueUnsignedInput, 'NumberTexture': WebGL2KernelValueNumberTexture, 'ArrayTexture(1)': WebGL2KernelValueNumberTexture, 'ArrayTexture(2)': WebGL2KernelValueNumberTexture, 'ArrayTexture(3)': WebGL2KernelValueNumberTexture, 'ArrayTexture(4)': WebGL2KernelValueNumberTexture, 'MemoryOptimizedNumberTexture': WebGL2KernelValueDynamicMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGL2KernelValueHTMLImage, 'OffscreenCanvas': WebGL2KernelValueHTMLImage, 'HTMLImage': WebGL2KernelValueHTMLImage, 'ImageBitmap': WebGL2KernelValueHTMLImage, 'ImageData': WebGL2KernelValueHTMLImage, 'HTMLImageArray': WebGL2KernelValueHTMLImageArray, 'HTMLVideo': WebGL2KernelValueHTMLVideo, } }, single: { dynamic: { 'Boolean': WebGL2KernelValueBoolean, 'Integer': WebGL2KernelValueInteger, 'Float': WebGL2KernelValueFloat, 'Array': WebGL2KernelValueDynamicSingleArray, 'Array(2)': WebGL2KernelValueArray2, 'Array(3)': WebGL2KernelValueArray3, 'Array(4)': WebGL2KernelValueArray4, 'Array1D(2)': WebGL2KernelValueDynamicSingleArray1DI, 'Array1D(3)': WebGL2KernelValueDynamicSingleArray1DI, 'Array1D(4)': WebGL2KernelValueDynamicSingleArray1DI, 'Array2D(2)': WebGL2KernelValueDynamicSingleArray2DI, 'Array2D(3)': WebGL2KernelValueDynamicSingleArray2DI, 'Array2D(4)': WebGL2KernelValueDynamicSingleArray2DI, 'Array3D(2)': WebGL2KernelValueDynamicSingleArray3DI, 'Array3D(3)': WebGL2KernelValueDynamicSingleArray3DI, 'Array3D(4)': WebGL2KernelValueDynamicSingleArray3DI, 'Input': WebGL2KernelValueDynamicSingleInput, 'NumberTexture': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(1)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(2)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(3)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(4)': WebGL2KernelValueDynamicNumberTexture, 'MemoryOptimizedNumberTexture': WebGL2KernelValueDynamicMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGL2KernelValueDynamicHTMLImage, 'OffscreenCanvas': WebGL2KernelValueDynamicHTMLImage, 'HTMLImage': WebGL2KernelValueDynamicHTMLImage, 'ImageBitmap': WebGL2KernelValueDynamicHTMLImage, 'ImageData': WebGL2KernelValueDynamicHTMLImage, 'HTMLImageArray': WebGL2KernelValueDynamicHTMLImageArray, 'HTMLVideo': WebGL2KernelValueDynamicHTMLVideo, }, static: { 'Boolean': WebGL2KernelValueBoolean, 'Float': WebGL2KernelValueFloat, 'Integer': WebGL2KernelValueInteger, 'Array': WebGL2KernelValueSingleArray, 'Array(2)': WebGL2KernelValueArray2, 'Array(3)': WebGL2KernelValueArray3, 'Array(4)': WebGL2KernelValueArray4, 'Array1D(2)': WebGL2KernelValueSingleArray1DI, 'Array1D(3)': WebGL2KernelValueSingleArray1DI, 'Array1D(4)': WebGL2KernelValueSingleArray1DI, 'Array2D(2)': WebGL2KernelValueSingleArray2DI, 'Array2D(3)': WebGL2KernelValueSingleArray2DI, 'Array2D(4)': WebGL2KernelValueSingleArray2DI, 'Array3D(2)': WebGL2KernelValueSingleArray3DI, 'Array3D(3)': WebGL2KernelValueSingleArray3DI, 'Array3D(4)': WebGL2KernelValueSingleArray3DI, 'Input': WebGL2KernelValueSingleInput, 'NumberTexture': WebGL2KernelValueNumberTexture, 'ArrayTexture(1)': WebGL2KernelValueNumberTexture, 'ArrayTexture(2)': WebGL2KernelValueNumberTexture, 'ArrayTexture(3)': WebGL2KernelValueNumberTexture, 'ArrayTexture(4)': WebGL2KernelValueNumberTexture, 'MemoryOptimizedNumberTexture': WebGL2KernelValueMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGL2KernelValueHTMLImage, 'OffscreenCanvas': WebGL2KernelValueHTMLImage, 'HTMLImage': WebGL2KernelValueHTMLImage, 'ImageBitmap': WebGL2KernelValueHTMLImage, 'ImageData': WebGL2KernelValueHTMLImage, 'HTMLImageArray': WebGL2KernelValueHTMLImageArray, 'HTMLVideo': WebGL2KernelValueHTMLVideo, } }, }; function lookupKernelValueType(type, dynamic, precision, value) { if (!type) { throw new Error('type missing'); } if (!dynamic) { throw new Error('dynamic missing'); } if (!precision) { throw new Error('precision missing'); } if (value.type) { type = value.type; } const types = kernelValueMaps[precision][dynamic]; if (types[type] === false) { return null; } else if (types[type] === undefined) { throw new Error(`Could not find a KernelValue for ${ type }`); } return types[type]; } module.exports = { kernelValueMaps, lookupKernelValueType }; },{"./kernel-value/array2":74,"./kernel-value/array3":75,"./kernel-value/array4":76,"./kernel-value/boolean":77,"./kernel-value/dynamic-html-image":79,"./kernel-value/dynamic-html-image-array":78,"./kernel-value/dynamic-html-video":80,"./kernel-value/dynamic-memory-optimized-number-texture":81,"./kernel-value/dynamic-number-texture":82,"./kernel-value/dynamic-single-array":83,"./kernel-value/dynamic-single-array1d-i":84,"./kernel-value/dynamic-single-array2d-i":85,"./kernel-value/dynamic-single-array3d-i":86,"./kernel-value/dynamic-single-input":87,"./kernel-value/dynamic-unsigned-array":88,"./kernel-value/dynamic-unsigned-input":89,"./kernel-value/float":90,"./kernel-value/html-image":92,"./kernel-value/html-image-array":91,"./kernel-value/html-video":93,"./kernel-value/integer":94,"./kernel-value/memory-optimized-number-texture":95,"./kernel-value/number-texture":96,"./kernel-value/single-array":97,"./kernel-value/single-array1d-i":98,"./kernel-value/single-array2d-i":99,"./kernel-value/single-array3d-i":100,"./kernel-value/single-input":101,"./kernel-value/unsigned-array":102,"./kernel-value/unsigned-input":103}],74:[function(require,module,exports){ const { WebGLKernelValueArray2 } = require('../../web-gl/kernel-value/array2'); class WebGL2KernelValueArray2 extends WebGLKernelValueArray2 {} module.exports = { WebGL2KernelValueArray2 }; },{"../../web-gl/kernel-value/array2":40}],75:[function(require,module,exports){ const { WebGLKernelValueArray3 } = require('../../web-gl/kernel-value/array3'); class WebGL2KernelValueArray3 extends WebGLKernelValueArray3 {} module.exports = { WebGL2KernelValueArray3 }; },{"../../web-gl/kernel-value/array3":41}],76:[function(require,module,exports){ const { WebGLKernelValueArray4 } = require('../../web-gl/kernel-value/array4'); class WebGL2KernelValueArray4 extends WebGLKernelValueArray4 {} module.exports = { WebGL2KernelValueArray4 }; },{"../../web-gl/kernel-value/array4":42}],77:[function(require,module,exports){ const { WebGLKernelValueBoolean } = require('../../web-gl/kernel-value/boolean'); class WebGL2KernelValueBoolean extends WebGLKernelValueBoolean {} module.exports = { WebGL2KernelValueBoolean }; },{"../../web-gl/kernel-value/boolean":43}],78:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueHTMLImageArray } = require('./html-image-array'); class WebGL2KernelValueDynamicHTMLImageArray extends WebGL2KernelValueHTMLImageArray { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2DArray ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(images) { const { width, height } = images[0]; this.checkSize(width, height); this.dimensions = [width, height, images.length]; this.textureSize = [width, height]; this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(images); } } module.exports = { WebGL2KernelValueDynamicHTMLImageArray }; },{"../../../utils":113,"./html-image-array":91}],79:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueDynamicHTMLImage } = require('../../web-gl/kernel-value/dynamic-html-image'); class WebGL2KernelValueDynamicHTMLImage extends WebGLKernelValueDynamicHTMLImage { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } } module.exports = { WebGL2KernelValueDynamicHTMLImage }; },{"../../../utils":113,"../../web-gl/kernel-value/dynamic-html-image":44}],80:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueDynamicHTMLImage } = require('./dynamic-html-image'); class WebGL2KernelValueDynamicHTMLVideo extends WebGL2KernelValueDynamicHTMLImage {} module.exports = { WebGL2KernelValueDynamicHTMLVideo }; },{"../../../utils":113,"./dynamic-html-image":79}],81:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueDynamicMemoryOptimizedNumberTexture } = require('../../web-gl/kernel-value/dynamic-memory-optimized-number-texture'); class WebGL2KernelValueDynamicMemoryOptimizedNumberTexture extends WebGLKernelValueDynamicMemoryOptimizedNumberTexture { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } } module.exports = { WebGL2KernelValueDynamicMemoryOptimizedNumberTexture }; },{"../../../utils":113,"../../web-gl/kernel-value/dynamic-memory-optimized-number-texture":46}],82:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueDynamicNumberTexture } = require('../../web-gl/kernel-value/dynamic-number-texture'); class WebGL2KernelValueDynamicNumberTexture extends WebGLKernelValueDynamicNumberTexture { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } } module.exports = { WebGL2KernelValueDynamicNumberTexture }; },{"../../../utils":113,"../../web-gl/kernel-value/dynamic-number-texture":47}],83:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueSingleArray } = require('../../web-gl2/kernel-value/single-array'); class WebGL2KernelValueDynamicSingleArray extends WebGL2KernelValueSingleArray { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.dimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGL2KernelValueDynamicSingleArray }; },{"../../../utils":113,"../../web-gl2/kernel-value/single-array":97}],84:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueSingleArray1DI } = require('../../web-gl2/kernel-value/single-array1d-i'); class WebGL2KernelValueDynamicSingleArray1DI extends WebGL2KernelValueSingleArray1DI { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGL2KernelValueDynamicSingleArray1DI }; },{"../../../utils":113,"../../web-gl2/kernel-value/single-array1d-i":98}],85:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueSingleArray2DI } = require('../../web-gl2/kernel-value/single-array2d-i'); class WebGL2KernelValueDynamicSingleArray2DI extends WebGL2KernelValueSingleArray2DI { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGL2KernelValueDynamicSingleArray2DI }; },{"../../../utils":113,"../../web-gl2/kernel-value/single-array2d-i":99}],86:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueSingleArray3DI } = require('../../web-gl2/kernel-value/single-array3d-i'); class WebGL2KernelValueDynamicSingleArray3DI extends WebGL2KernelValueSingleArray3DI { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGL2KernelValueDynamicSingleArray3DI }; },{"../../../utils":113,"../../web-gl2/kernel-value/single-array3d-i":100}],87:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueSingleInput } = require('../../web-gl2/kernel-value/single-input'); class WebGL2KernelValueDynamicSingleInput extends WebGL2KernelValueSingleInput { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { let [w, h, d] = value.size; this.dimensions = new Int32Array([w || 1, h || 1, d || 1]); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGL2KernelValueDynamicSingleInput }; },{"../../../utils":113,"../../web-gl2/kernel-value/single-input":101}],88:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueDynamicUnsignedArray } = require('../../web-gl/kernel-value/dynamic-unsigned-array'); class WebGL2KernelValueDynamicUnsignedArray extends WebGLKernelValueDynamicUnsignedArray { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } } module.exports = { WebGL2KernelValueDynamicUnsignedArray }; },{"../../../utils":113,"../../web-gl/kernel-value/dynamic-unsigned-array":53}],89:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueDynamicUnsignedInput } = require('../../web-gl/kernel-value/dynamic-unsigned-input'); class WebGL2KernelValueDynamicUnsignedInput extends WebGLKernelValueDynamicUnsignedInput { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } } module.exports = { WebGL2KernelValueDynamicUnsignedInput }; },{"../../../utils":113,"../../web-gl/kernel-value/dynamic-unsigned-input":54}],90:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueFloat } = require('../../web-gl/kernel-value/float'); class WebGL2KernelValueFloat extends WebGLKernelValueFloat {} module.exports = { WebGL2KernelValueFloat }; },{"../../../utils":113,"../../web-gl/kernel-value/float":55}],91:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('../../web-gl/kernel-value/array'); class WebGL2KernelValueHTMLImageArray extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.checkSize(value[0].width, value[0].height); this.dimensions = [value[0].width, value[0].height, value.length]; this.textureSize = [value[0].width, value[0].height]; } defineTexture() { const { context: gl } = this; gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.texture); gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MIN_FILTER, gl.NEAREST); } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName};\n`; } getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2DArray ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(images) { const { context: gl } = this; gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.texImage3D( gl.TEXTURE_2D_ARRAY, 0, gl.RGBA, images[0].width, images[0].height, images.length, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); for (let i = 0; i < images.length; i++) { const xOffset = 0; const yOffset = 0; const imageDepth = 1; gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, xOffset, yOffset, i, images[i].width, images[i].height, imageDepth, gl.RGBA, gl.UNSIGNED_BYTE, this.uploadValue = images[i] ); } this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueHTMLImageArray }; },{"../../../utils":113,"../../web-gl/kernel-value/array":39}],92:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueHTMLImage } = require('../../web-gl/kernel-value/html-image'); class WebGL2KernelValueHTMLImage extends WebGLKernelValueHTMLImage { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } } module.exports = { WebGL2KernelValueHTMLImage }; },{"../../../utils":113,"../../web-gl/kernel-value/html-image":56}],93:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueHTMLImage } = require('./html-image'); class WebGL2KernelValueHTMLVideo extends WebGL2KernelValueHTMLImage {} module.exports = { WebGL2KernelValueHTMLVideo }; },{"../../../utils":113,"./html-image":92}],94:[function(require,module,exports){ const { WebGLKernelValueInteger } = require('../../web-gl/kernel-value/integer'); class WebGL2KernelValueInteger extends WebGLKernelValueInteger { getSource(value) { const variablePrecision = this.getVariablePrecisionString(); if (this.origin === 'constants') { return `const ${ variablePrecision } int ${this.id} = ${ parseInt(value) };\n`; } return `uniform ${ variablePrecision } int ${this.id};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform1i(this.id, this.uploadValue = value); } } module.exports = { WebGL2KernelValueInteger }; },{"../../web-gl/kernel-value/integer":59}],95:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueMemoryOptimizedNumberTexture } = require('../../web-gl/kernel-value/memory-optimized-number-texture'); class WebGL2KernelValueMemoryOptimizedNumberTexture extends WebGLKernelValueMemoryOptimizedNumberTexture { getSource() { const { id, sizeId, textureSize, dimensionsId, dimensions } = this; const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform sampler2D ${id}`, `${ variablePrecision } ivec2 ${sizeId} = ivec2(${textureSize[0]}, ${textureSize[1]})`, `${ variablePrecision } ivec3 ${dimensionsId} = ivec3(${dimensions[0]}, ${dimensions[1]}, ${dimensions[2]})`, ]); } } module.exports = { WebGL2KernelValueMemoryOptimizedNumberTexture }; },{"../../../utils":113,"../../web-gl/kernel-value/memory-optimized-number-texture":60}],96:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueNumberTexture } = require('../../web-gl/kernel-value/number-texture'); class WebGL2KernelValueNumberTexture extends WebGLKernelValueNumberTexture { getSource() { const { id, sizeId, textureSize, dimensionsId, dimensions } = this; const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${id}`, `${ variablePrecision } ivec2 ${sizeId} = ivec2(${textureSize[0]}, ${textureSize[1]})`, `${ variablePrecision } ivec3 ${dimensionsId} = ivec3(${dimensions[0]}, ${dimensions[1]}, ${dimensions[2]})`, ]); } } module.exports = { WebGL2KernelValueNumberTexture }; },{"../../../utils":113,"../../web-gl/kernel-value/number-texture":61}],97:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray } = require('../../web-gl/kernel-value/single-array'); class WebGL2KernelValueSingleArray extends WebGLKernelValueSingleArray { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueSingleArray }; },{"../../../utils":113,"../../web-gl/kernel-value/single-array":62}],98:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray1DI } = require('../../web-gl/kernel-value/single-array1d-i'); class WebGL2KernelValueSingleArray1DI extends WebGLKernelValueSingleArray1DI { updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueSingleArray1DI }; },{"../../../utils":113,"../../web-gl/kernel-value/single-array1d-i":63}],99:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray2DI } = require('../../web-gl/kernel-value/single-array2d-i'); class WebGL2KernelValueSingleArray2DI extends WebGLKernelValueSingleArray2DI { updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueSingleArray2DI }; },{"../../../utils":113,"../../web-gl/kernel-value/single-array2d-i":64}],100:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray3DI } = require('../../web-gl/kernel-value/single-array3d-i'); class WebGL2KernelValueSingleArray3DI extends WebGLKernelValueSingleArray3DI { updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueSingleArray3DI }; },{"../../../utils":113,"../../web-gl/kernel-value/single-array3d-i":65}],101:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleInput } = require('../../web-gl/kernel-value/single-input'); class WebGL2KernelValueSingleInput extends WebGLKernelValueSingleInput { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(input) { const { context: gl } = this; utils.flattenTo(input.value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueSingleInput }; },{"../../../utils":113,"../../web-gl/kernel-value/single-input":66}],102:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueUnsignedArray } = require('../../web-gl/kernel-value/unsigned-array'); class WebGL2KernelValueUnsignedArray extends WebGLKernelValueUnsignedArray { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } } module.exports = { WebGL2KernelValueUnsignedArray }; },{"../../../utils":113,"../../web-gl/kernel-value/unsigned-array":67}],103:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueUnsignedInput } = require('../../web-gl/kernel-value/unsigned-input'); class WebGL2KernelValueUnsignedInput extends WebGLKernelValueUnsignedInput { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } } module.exports = { WebGL2KernelValueUnsignedInput }; },{"../../../utils":113,"../../web-gl/kernel-value/unsigned-input":68}],104:[function(require,module,exports){ const { WebGLKernel } = require('../web-gl/kernel'); const { WebGL2FunctionNode } = require('./function-node'); const { FunctionBuilder } = require('../function-builder'); const { utils } = require('../../utils'); const { fragmentShader } = require('./fragment-shader'); const { vertexShader } = require('./vertex-shader'); const { lookupKernelValueType } = require('./kernel-value-maps'); let isSupported = null; let testCanvas = null; let testContext = null; let testExtensions = null; let features = null; class WebGL2Kernel extends WebGLKernel { static get isSupported() { if (isSupported !== null) { return isSupported; } this.setupFeatureChecks(); isSupported = this.isContextMatch(testContext); return isSupported; } static setupFeatureChecks() { if (typeof document !== 'undefined') { testCanvas = document.createElement('canvas'); } else if (typeof OffscreenCanvas !== 'undefined') { testCanvas = new OffscreenCanvas(0, 0); } if (!testCanvas) return; testContext = testCanvas.getContext('webgl2'); if (!testContext || !testContext.getExtension) return; testExtensions = { EXT_color_buffer_float: testContext.getExtension('EXT_color_buffer_float'), OES_texture_float_linear: testContext.getExtension('OES_texture_float_linear'), }; features = this.getFeatures(); } static isContextMatch(context) { if (typeof WebGL2RenderingContext !== 'undefined') { return context instanceof WebGL2RenderingContext; } return false; } static getFeatures() { const gl = this.testContext; return Object.freeze({ isFloatRead: this.getIsFloatRead(), isIntegerDivisionAccurate: this.getIsIntegerDivisionAccurate(), isSpeedTacticSupported: this.getIsSpeedTacticSupported(), kernelMap: true, isTextureFloat: true, isDrawBuffers: true, channelCount: this.getChannelCount(), maxTextureSize: this.getMaxTextureSize(), lowIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT), lowFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT), mediumIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT), mediumFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT), highIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT), highFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT), }); } static getIsTextureFloat() { return true; } static getChannelCount() { return testContext.getParameter(testContext.MAX_DRAW_BUFFERS); } static getMaxTextureSize() { return testContext.getParameter(testContext.MAX_TEXTURE_SIZE); } static lookupKernelValueType(type, dynamic, precision, value) { return lookupKernelValueType(type, dynamic, precision, value); } static get testCanvas() { return testCanvas; } static get testContext() { return testContext; } static get features() { return features; } static get fragmentShader() { return fragmentShader; } static get vertexShader() { return vertexShader; } initContext() { const settings = { alpha: false, depth: false, antialias: false }; return this.canvas.getContext('webgl2', settings); } initExtensions() { this.extensions = { EXT_color_buffer_float: this.context.getExtension('EXT_color_buffer_float'), OES_texture_float_linear: this.context.getExtension('OES_texture_float_linear'), }; } validateSettings(args) { if (!this.validate) { this.texSize = utils.getKernelTextureSize({ optimizeFloatMemory: this.optimizeFloatMemory, precision: this.precision, }, this.output); return; } const { features } = this.constructor; if (this.precision === 'single' && !features.isFloatRead) { throw new Error('Float texture outputs are not supported'); } else if (!this.graphical && this.precision === null) { this.precision = features.isFloatRead ? 'single' : 'unsigned'; } if (this.fixIntegerDivisionAccuracy === null) { this.fixIntegerDivisionAccuracy = !features.isIntegerDivisionAccurate; } else if (this.fixIntegerDivisionAccuracy && features.isIntegerDivisionAccurate) { this.fixIntegerDivisionAccuracy = false; } this.checkOutput(); if (!this.output || this.output.length === 0) { if (args.length !== 1) { throw new Error('Auto output only supported for kernels with only one input'); } const argType = utils.getVariableType(args[0], this.strictIntegers); switch (argType) { case 'Array': this.output = utils.getDimensions(argType); break; case 'NumberTexture': case 'MemoryOptimizedNumberTexture': case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': this.output = args[0].output; break; default: throw new Error('Auto output not supported for input type: ' + argType); } } if (this.graphical) { if (this.output.length !== 2) { throw new Error('Output must have 2 dimensions on graphical mode'); } if (this.precision === 'single') { console.warn('Cannot use graphical mode and single precision at the same time'); this.precision = 'unsigned'; } this.texSize = utils.clone(this.output); return; } else if (!this.graphical && this.precision === null && features.isTextureFloat) { this.precision = 'single'; } this.texSize = utils.getKernelTextureSize({ optimizeFloatMemory: this.optimizeFloatMemory, precision: this.precision, }, this.output); this.checkTextureSize(); } translateSource() { const functionBuilder = FunctionBuilder.fromKernel(this, WebGL2FunctionNode, { fixIntegerDivisionAccuracy: this.fixIntegerDivisionAccuracy }); this.translatedSource = functionBuilder.getPrototypeString('kernel'); this.setupReturnTypes(functionBuilder); } drawBuffers() { this.context.drawBuffers(this.drawBuffersMap); } getTextureFormat() { const { context: gl } = this; switch (this.getInternalFormat()) { case gl.R32F: return gl.RED; case gl.RG32F: return gl.RG; case gl.RGBA32F: return gl.RGBA; case gl.RGBA: return gl.RGBA; default: throw new Error('Unknown internal format'); } } getInternalFormat() { const { context: gl } = this; if (this.precision === 'single') { if (this.pipeline) { switch (this.returnType) { case 'Number': case 'Float': case 'Integer': if (this.optimizeFloatMemory) { return gl.RGBA32F; } else { return gl.R32F; } case 'Array(2)': return gl.RG32F; case 'Array(3)': case 'Array(4)': return gl.RGBA32F; default: throw new Error('Unhandled return type'); } } return gl.RGBA32F; } return gl.RGBA; } _setupOutputTexture() { const gl = this.context; if (this.texture) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); return; } gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); const texture = gl.createTexture(); const texSize = this.texSize; gl.activeTexture(gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); const format = this.getInternalFormat(); if (this.precision === 'single') { gl.texStorage2D(gl.TEXTURE_2D, 1, format, texSize[0], texSize[1]); } else { gl.texImage2D(gl.TEXTURE_2D, 0, format, texSize[0], texSize[1], 0, format, gl.UNSIGNED_BYTE, null); } gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); this.texture = new this.TextureConstructor({ texture, size: texSize, dimensions: this.threadDim, output: this.output, context: this.context, internalFormat: this.getInternalFormat(), textureFormat: this.getTextureFormat(), kernel: this, }); } _setupSubOutputTextures() { const gl = this.context; if (this.mappedTextures) { for (let i = 0; i < this.subKernels.length; i++) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, this.mappedTextures[i].texture, 0); } return; } const texSize = this.texSize; this.drawBuffersMap = [gl.COLOR_ATTACHMENT0]; this.mappedTextures = []; for (let i = 0; i < this.subKernels.length; i++) { const texture = this.createTexture(); this.drawBuffersMap.push(gl.COLOR_ATTACHMENT0 + i + 1); gl.activeTexture(gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount + i); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); const format = this.getInternalFormat(); if (this.precision === 'single') { gl.texStorage2D(gl.TEXTURE_2D, 1, format, texSize[0], texSize[1]); } else { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize[0], texSize[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, texture, 0); this.mappedTextures.push(new this.TextureConstructor({ texture, size: texSize, dimensions: this.threadDim, output: this.output, context: this.context, internalFormat: this.getInternalFormat(), textureFormat: this.getTextureFormat(), kernel: this, })); } } _getHeaderString() { return ''; } _getTextureCoordinate() { const subKernels = this.subKernels; const variablePrecision = this.getVariablePrecisionString(this.texSize, this.tactic); if (subKernels === null || subKernels.length < 1) { return `in ${ variablePrecision } vec2 vTexCoord;\n`; } else { return `out ${ variablePrecision } vec2 vTexCoord;\n`; } } _getMainArgumentsString(args) { const result = []; const argumentNames = this.argumentNames; for (let i = 0; i < argumentNames.length; i++) { result.push(this.kernelArguments[i].getSource(args[i])); } return result.join(''); } getKernelString() { const result = [this.getKernelResultDeclaration()]; const subKernels = this.subKernels; if (subKernels !== null) { result.push( 'layout(location = 0) out vec4 data0' ); switch (this.returnType) { case 'Number': case 'Float': case 'Integer': for (let i = 0; i < subKernels.length; i++) { const subKernel = subKernels[i]; result.push( subKernel.returnType === 'Integer' ? `int subKernelResult_${ subKernel.name } = 0` : `float subKernelResult_${ subKernel.name } = 0.0`, `layout(location = ${ i + 1 }) out vec4 data${ i + 1 }` ); } break; case 'Array(2)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec2 subKernelResult_${ subKernels[i].name }`, `layout(location = ${ i + 1 }) out vec4 data${ i + 1 }` ); } break; case 'Array(3)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec3 subKernelResult_${ subKernels[i].name }`, `layout(location = ${ i + 1 }) out vec4 data${ i + 1 }` ); } break; case 'Array(4)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec4 subKernelResult_${ subKernels[i].name }`, `layout(location = ${ i + 1 }) out vec4 data${ i + 1 }` ); } break; } } else { result.push( 'out vec4 data0' ); } return utils.linesToString(result) + this.translatedSource; } getMainResultGraphical() { return utils.linesToString([ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' data0 = actualColor', ]); } getMainResultPackedPixels() { switch (this.returnType) { case 'LiteralInteger': case 'Number': case 'Integer': case 'Float': return this.getMainResultKernelPackedPixels() + this.getMainResultSubKernelPackedPixels(); default: throw new Error(`packed output only usable with Numbers, "${this.returnType}" specified`); } } getMainResultKernelPackedPixels() { return utils.linesToString([ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ` data0 = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(kernelResult)` ]); } getMainResultSubKernelPackedPixels() { const result = []; if (!this.subKernels) return ''; for (let i = 0; i < this.subKernels.length; i++) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` data${i + 1} = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(float(subKernelResult_${this.subKernels[i].name}))` ); } else { result.push( ` data${i + 1} = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(subKernelResult_${this.subKernels[i].name})` ); } } return utils.linesToString(result); } getMainResultKernelMemoryOptimizedFloats(result, channel) { result.push( ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ` data0.${channel} = kernelResult` ); } getMainResultSubKernelMemoryOptimizedFloats(result, channel) { if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; i++) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` data${i + 1}.${channel} = float(subKernelResult_${subKernel.name})` ); } else { result.push( ` data${i + 1}.${channel} = subKernelResult_${subKernel.name}` ); } } } getMainResultKernelNumberTexture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' data0[0] = kernelResult', ]; } getMainResultSubKernelNumberTexture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` data${i + 1}[0] = float(subKernelResult_${subKernel.name})` ); } else { result.push( ` data${i + 1}[0] = subKernelResult_${subKernel.name}` ); } } return result; } getMainResultKernelArray2Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' data0[0] = kernelResult[0]', ' data0[1] = kernelResult[1]', ]; } getMainResultSubKernelArray2Texture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { const subKernel = this.subKernels[i]; result.push( ` data${i + 1}[0] = subKernelResult_${subKernel.name}[0]`, ` data${i + 1}[1] = subKernelResult_${subKernel.name}[1]` ); } return result; } getMainResultKernelArray3Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' data0[0] = kernelResult[0]', ' data0[1] = kernelResult[1]', ' data0[2] = kernelResult[2]', ]; } getMainResultSubKernelArray3Texture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { const subKernel = this.subKernels[i]; result.push( ` data${i + 1}[0] = subKernelResult_${subKernel.name}[0]`, ` data${i + 1}[1] = subKernelResult_${subKernel.name}[1]`, ` data${i + 1}[2] = subKernelResult_${subKernel.name}[2]` ); } return result; } getMainResultKernelArray4Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' data0 = kernelResult', ]; } getMainResultSubKernelArray4Texture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` data${i + 1} = subKernelResult_${this.subKernels[i].name}` ); } return result; } destroyExtensions() { this.extensions.EXT_color_buffer_float = null; this.extensions.OES_texture_float_linear = null; } toJSON() { const json = super.toJSON(); json.functionNodes = FunctionBuilder.fromKernel(this, WebGL2FunctionNode).toJSON(); json.settings.threadDim = this.threadDim; return json; } } module.exports = { WebGL2Kernel }; },{"../../utils":113,"../function-builder":8,"../web-gl/kernel":69,"./fragment-shader":71,"./function-node":72,"./kernel-value-maps":73,"./vertex-shader":105}],105:[function(require,module,exports){ const vertexShader = `#version 300 es __FLOAT_TACTIC_DECLARATION__; __INT_TACTIC_DECLARATION__; __SAMPLER_2D_TACTIC_DECLARATION__; in vec2 aPos; in vec2 aTexCoord; out vec2 vTexCoord; uniform vec2 ratio; void main(void) { gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1); vTexCoord = aTexCoord; }`; module.exports = { vertexShader }; },{}],106:[function(require,module,exports){ const lib = require('./index'); const GPU = lib.GPU; for (const p in lib) { if (!lib.hasOwnProperty(p)) continue; if (p === 'GPU') continue; GPU[p] = lib[p]; } if (typeof window !== 'undefined') { bindTo(window); } if (typeof self !== 'undefined') { bindTo(self); } function bindTo(target) { if (target.GPU) return; Object.defineProperty(target, 'GPU', { get() { return GPU; } }); } module.exports = lib; },{"./index":108}],107:[function(require,module,exports){ const { gpuMock } = require('gpu-mock.js'); const { utils } = require('./utils'); const { Kernel } = require('./backend/kernel'); const { CPUKernel } = require('./backend/cpu/kernel'); const { HeadlessGLKernel } = require('./backend/headless-gl/kernel'); const { WebGL2Kernel } = require('./backend/web-gl2/kernel'); const { WebGLKernel } = require('./backend/web-gl/kernel'); const { kernelRunShortcut } = require('./kernel-run-shortcut'); const kernelOrder = [HeadlessGLKernel, WebGL2Kernel, WebGLKernel]; const kernelTypes = ['gpu', 'cpu']; const internalKernels = { 'headlessgl': HeadlessGLKernel, 'webgl2': WebGL2Kernel, 'webgl': WebGLKernel, }; let validate = true; class GPU { static disableValidation() { validate = false; } static enableValidation() { validate = true; } static get isGPUSupported() { return kernelOrder.some(Kernel => Kernel.isSupported); } static get isKernelMapSupported() { return kernelOrder.some(Kernel => Kernel.isSupported && Kernel.features.kernelMap); } static get isOffscreenCanvasSupported() { return (typeof Worker !== 'undefined' && typeof OffscreenCanvas !== 'undefined') || typeof importScripts !== 'undefined'; } static get isWebGLSupported() { return WebGLKernel.isSupported; } static get isWebGL2Supported() { return WebGL2Kernel.isSupported; } static get isHeadlessGLSupported() { return HeadlessGLKernel.isSupported; } static get isCanvasSupported() { return typeof HTMLCanvasElement !== 'undefined'; } static get isGPUHTMLImageArraySupported() { return WebGL2Kernel.isSupported; } static get isSinglePrecisionSupported() { return kernelOrder.some(Kernel => Kernel.isSupported && Kernel.features.isFloatRead && Kernel.features.isTextureFloat); } constructor(settings) { settings = settings || {}; this.canvas = settings.canvas || null; this.context = settings.context || null; this.mode = settings.mode; this.Kernel = null; this.kernels = []; this.functions = []; this.nativeFunctions = []; this.injectedNative = null; if (this.mode === 'dev') return; this.chooseKernel(); if (settings.functions) { for (let i = 0; i < settings.functions.length; i++) { this.addFunction(settings.functions[i]); } } if (settings.nativeFunctions) { for (const p in settings.nativeFunctions) { if (!settings.nativeFunctions.hasOwnProperty(p)) continue; const s = settings.nativeFunctions[p]; const { name, source } = s; this.addNativeFunction(name, source, s); } } } chooseKernel() { if (this.Kernel) return; let Kernel = null; if (this.context) { for (let i = 0; i < kernelOrder.length; i++) { const ExternalKernel = kernelOrder[i]; if (ExternalKernel.isContextMatch(this.context)) { if (!ExternalKernel.isSupported) { throw new Error(`Kernel type ${ExternalKernel.name} not supported`); } Kernel = ExternalKernel; break; } } if (Kernel === null) { throw new Error('unknown Context'); } } else if (this.mode) { if (this.mode in internalKernels) { if (!validate || internalKernels[this.mode].isSupported) { Kernel = internalKernels[this.mode]; } } else if (this.mode === 'gpu') { for (let i = 0; i < kernelOrder.length; i++) { if (kernelOrder[i].isSupported) { Kernel = kernelOrder[i]; break; } } } else if (this.mode === 'cpu') { Kernel = CPUKernel; } if (!Kernel) { throw new Error(`A requested mode of "${this.mode}" and is not supported`); } } else { for (let i = 0; i < kernelOrder.length; i++) { if (kernelOrder[i].isSupported) { Kernel = kernelOrder[i]; break; } } if (!Kernel) { Kernel = CPUKernel; } } if (!this.mode) { this.mode = Kernel.mode; } this.Kernel = Kernel; } createKernel(source, settings) { if (typeof source === 'undefined') { throw new Error('Missing source parameter'); } if (typeof source !== 'object' && !utils.isFunction(source) && typeof source !== 'string') { throw new Error('source parameter not a function'); } const kernels = this.kernels; if (this.mode === 'dev') { const devKernel = gpuMock(source, upgradeDeprecatedCreateKernelSettings(settings)); kernels.push(devKernel); return devKernel; } source = typeof source === 'function' ? source.toString() : source; const switchableKernels = {}; const settingsCopy = upgradeDeprecatedCreateKernelSettings(settings) || {}; if (settings && typeof settings.argumentTypes === 'object') { settingsCopy.argumentTypes = Object.keys(settings.argumentTypes).map(argumentName => settings.argumentTypes[argumentName]); } function onRequestFallback(args) { console.warn('Falling back to CPU'); const fallbackKernel = new CPUKernel(source, { argumentTypes: kernelRun.argumentTypes, constantTypes: kernelRun.constantTypes, graphical: kernelRun.graphical, loopMaxIterations: kernelRun.loopMaxIterations, constants: kernelRun.constants, dynamicOutput: kernelRun.dynamicOutput, dynamicArgument: kernelRun.dynamicArguments, output: kernelRun.output, precision: kernelRun.precision, pipeline: kernelRun.pipeline, immutable: kernelRun.immutable, optimizeFloatMemory: kernelRun.optimizeFloatMemory, fixIntegerDivisionAccuracy: kernelRun.fixIntegerDivisionAccuracy, functions: kernelRun.functions, nativeFunctions: kernelRun.nativeFunctions, injectedNative: kernelRun.injectedNative, subKernels: kernelRun.subKernels, strictIntegers: kernelRun.strictIntegers, debug: kernelRun.debug, }); fallbackKernel.build.apply(fallbackKernel, args); const result = fallbackKernel.run.apply(fallbackKernel, args); kernelRun.replaceKernel(fallbackKernel); return result; } function onRequestSwitchKernel(reasons, args, _kernel) { if (_kernel.debug) { console.warn('Switching kernels'); } let newOutput = null; if (_kernel.signature && !switchableKernels[_kernel.signature]) { switchableKernels[_kernel.signature] = _kernel; } if (_kernel.dynamicOutput) { for (let i = reasons.length - 1; i >= 0; i--) { const reason = reasons[i]; if (reason.type === 'outputPrecisionMismatch') { newOutput = reason.needed; } } } const Constructor = _kernel.constructor; const argumentTypes = Constructor.getArgumentTypes(_kernel, args); const signature = Constructor.getSignature(_kernel, argumentTypes); const existingKernel = switchableKernels[signature]; if (existingKernel) { existingKernel.onActivate(_kernel); return existingKernel; } const newKernel = switchableKernels[signature] = new Constructor(source, { argumentTypes, constantTypes: _kernel.constantTypes, graphical: _kernel.graphical, loopMaxIterations: _kernel.loopMaxIterations, constants: _kernel.constants, dynamicOutput: _kernel.dynamicOutput, dynamicArgument: _kernel.dynamicArguments, context: _kernel.context, canvas: _kernel.canvas, output: newOutput || _kernel.output, precision: _kernel.precision, pipeline: _kernel.pipeline, immutable: _kernel.immutable, optimizeFloatMemory: _kernel.optimizeFloatMemory, fixIntegerDivisionAccuracy: _kernel.fixIntegerDivisionAccuracy, functions: _kernel.functions, nativeFunctions: _kernel.nativeFunctions, injectedNative: _kernel.injectedNative, subKernels: _kernel.subKernels, strictIntegers: _kernel.strictIntegers, debug: _kernel.debug, gpu: _kernel.gpu, validate, returnType: _kernel.returnType, tactic: _kernel.tactic, onRequestFallback, onRequestSwitchKernel, texture: _kernel.texture, mappedTextures: _kernel.mappedTextures, drawBuffersMap: _kernel.drawBuffersMap, }); newKernel.build.apply(newKernel, args); kernelRun.replaceKernel(newKernel); kernels.push(newKernel); return newKernel; } const mergedSettings = Object.assign({ context: this.context, canvas: this.canvas, functions: this.functions, nativeFunctions: this.nativeFunctions, injectedNative: this.injectedNative, gpu: this, validate, onRequestFallback, onRequestSwitchKernel }, settingsCopy); const kernel = new this.Kernel(source, mergedSettings); const kernelRun = kernelRunShortcut(kernel); if (!this.canvas) { this.canvas = kernel.canvas; } if (!this.context) { this.context = kernel.context; } kernels.push(kernel); return kernelRun; } createKernelMap() { let fn; let settings; const argument2Type = typeof arguments[arguments.length - 2]; if (argument2Type === 'function' || argument2Type === 'string') { fn = arguments[arguments.length - 2]; settings = arguments[arguments.length - 1]; } else { fn = arguments[arguments.length - 1]; } if (this.mode !== 'dev') { if (!this.Kernel.isSupported || !this.Kernel.features.kernelMap) { if (this.mode && kernelTypes.indexOf(this.mode) < 0) { throw new Error(`kernelMap not supported on ${this.Kernel.name}`); } } } const settingsCopy = upgradeDeprecatedCreateKernelSettings(settings); if (settings && typeof settings.argumentTypes === 'object') { settingsCopy.argumentTypes = Object.keys(settings.argumentTypes).map(argumentName => settings.argumentTypes[argumentName]); } if (Array.isArray(arguments[0])) { settingsCopy.subKernels = []; const functions = arguments[0]; for (let i = 0; i < functions.length; i++) { const source = functions[i].toString(); const name = utils.getFunctionNameFromString(source); settingsCopy.subKernels.push({ name, source, property: i, }); } } else { settingsCopy.subKernels = []; const functions = arguments[0]; for (let p in functions) { if (!functions.hasOwnProperty(p)) continue; const source = functions[p].toString(); const name = utils.getFunctionNameFromString(source); settingsCopy.subKernels.push({ name: name || p, source, property: p, }); } } return this.createKernel(fn, settingsCopy); } combineKernels() { const firstKernel = arguments[0]; const combinedKernel = arguments[arguments.length - 1]; if (firstKernel.kernel.constructor.mode === 'cpu') return combinedKernel; const canvas = arguments[0].canvas; const context = arguments[0].context; const max = arguments.length - 1; for (let i = 0; i < max; i++) { arguments[i] .setCanvas(canvas) .setContext(context) .setPipeline(true); } return function() { const texture = combinedKernel.apply(this, arguments); if (texture.toArray) { return texture.toArray(); } return texture; }; } setFunctions(functions) { this.functions = functions; return this; } setNativeFunctions(nativeFunctions) { this.nativeFunctions = nativeFunctions; return this; } addFunction(source, settings) { this.functions.push({ source, settings }); return this; } addNativeFunction(name, source, settings) { if (this.kernels.length > 0) { throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.'); } this.nativeFunctions.push(Object.assign({ name, source }, settings)); return this; } injectNative(source) { this.injectedNative = source; return this; } destroy() { return new Promise((resolve, reject) => { if (!this.kernels) { resolve(); } setTimeout(() => { try { for (let i = 0; i < this.kernels.length; i++) { this.kernels[i].destroy(true); } let firstKernel = this.kernels[0]; if (firstKernel) { if (firstKernel.kernel) { firstKernel = firstKernel.kernel; } if (firstKernel.constructor.destroyContext) { firstKernel.constructor.destroyContext(this.context); } } } catch (e) { reject(e); } resolve(); }, 0); }); } } function upgradeDeprecatedCreateKernelSettings(settings) { if (!settings) { return {}; } const upgradedSettings = Object.assign({}, settings); if (settings.hasOwnProperty('floatOutput')) { utils.warnDeprecated('setting', 'floatOutput', 'precision'); upgradedSettings.precision = settings.floatOutput ? 'single' : 'unsigned'; } if (settings.hasOwnProperty('outputToTexture')) { utils.warnDeprecated('setting', 'outputToTexture', 'pipeline'); upgradedSettings.pipeline = Boolean(settings.outputToTexture); } if (settings.hasOwnProperty('outputImmutable')) { utils.warnDeprecated('setting', 'outputImmutable', 'immutable'); upgradedSettings.immutable = Boolean(settings.outputImmutable); } if (settings.hasOwnProperty('floatTextures')) { utils.warnDeprecated('setting', 'floatTextures', 'optimizeFloatMemory'); upgradedSettings.optimizeFloatMemory = Boolean(settings.floatTextures); } return upgradedSettings; } module.exports = { GPU, kernelOrder, kernelTypes }; },{"./backend/cpu/kernel":7,"./backend/headless-gl/kernel":33,"./backend/kernel":35,"./backend/web-gl/kernel":69,"./backend/web-gl2/kernel":104,"./kernel-run-shortcut":110,"./utils":113,"gpu-mock.js":3}],108:[function(require,module,exports){ const { GPU } = require('./gpu'); const { alias } = require('./alias'); const { utils } = require('./utils'); const { Input, input } = require('./input'); const { Texture } = require('./texture'); const { FunctionBuilder } = require('./backend/function-builder'); const { FunctionNode } = require('./backend/function-node'); const { CPUFunctionNode } = require('./backend/cpu/function-node'); const { CPUKernel } = require('./backend/cpu/kernel'); const { HeadlessGLKernel } = require('./backend/headless-gl/kernel'); const { WebGLFunctionNode } = require('./backend/web-gl/function-node'); const { WebGLKernel } = require('./backend/web-gl/kernel'); const { kernelValueMaps: webGLKernelValueMaps } = require('./backend/web-gl/kernel-value-maps'); const { WebGL2FunctionNode } = require('./backend/web-gl2/function-node'); const { WebGL2Kernel } = require('./backend/web-gl2/kernel'); const { kernelValueMaps: webGL2KernelValueMaps } = require('./backend/web-gl2/kernel-value-maps'); const { GLKernel } = require('./backend/gl/kernel'); const { Kernel } = require('./backend/kernel'); const { FunctionTracer } = require('./backend/function-tracer'); const mathRandom = require('./plugins/math-random-uniformly-distributed'); module.exports = { alias, CPUFunctionNode, CPUKernel, GPU, FunctionBuilder, FunctionNode, HeadlessGLKernel, Input, input, Texture, utils, WebGL2FunctionNode, WebGL2Kernel, webGL2KernelValueMaps, WebGLFunctionNode, WebGLKernel, webGLKernelValueMaps, GLKernel, Kernel, FunctionTracer, plugins: { mathRandom } }; },{"./alias":4,"./backend/cpu/function-node":5,"./backend/cpu/kernel":7,"./backend/function-builder":8,"./backend/function-node":9,"./backend/function-tracer":10,"./backend/gl/kernel":12,"./backend/headless-gl/kernel":33,"./backend/kernel":35,"./backend/web-gl/function-node":37,"./backend/web-gl/kernel":69,"./backend/web-gl/kernel-value-maps":38,"./backend/web-gl2/function-node":72,"./backend/web-gl2/kernel":104,"./backend/web-gl2/kernel-value-maps":73,"./gpu":107,"./input":109,"./plugins/math-random-uniformly-distributed":111,"./texture":112,"./utils":113}],109:[function(require,module,exports){ class Input { constructor(value, size) { this.value = value; if (Array.isArray(size)) { this.size = size; } else { this.size = new Int32Array(3); if (size.z) { this.size = new Int32Array([size.x, size.y, size.z]); } else if (size.y) { this.size = new Int32Array([size.x, size.y]); } else { this.size = new Int32Array([size.x]); } } const [w, h, d] = this.size; if (d) { if (this.value.length !== (w * h * d)) { throw new Error(`Input size ${this.value.length} does not match ${w} * ${h} * ${d} = ${(h * w * d)}`); } } else if (h) { if (this.value.length !== (w * h)) { throw new Error(`Input size ${this.value.length} does not match ${w} * ${h} = ${(h * w)}`); } } else { if (this.value.length !== w) { throw new Error(`Input size ${this.value.length} does not match ${w}`); } } } toArray() { const { utils } = require('./utils'); const [w, h, d] = this.size; if (d) { return utils.erectMemoryOptimized3DFloat(this.value.subarray ? this.value : new Float32Array(this.value), w, h, d); } else if (h) { return utils.erectMemoryOptimized2DFloat(this.value.subarray ? this.value : new Float32Array(this.value), w, h); } else { return this.value; } } } function input(value, size) { return new Input(value, size); } module.exports = { Input, input }; },{"./utils":113}],110:[function(require,module,exports){ const { utils } = require('./utils'); function kernelRunShortcut(kernel) { let run = function() { kernel.build.apply(kernel, arguments); run = function() { let result = kernel.run.apply(kernel, arguments); if (kernel.switchingKernels) { const reasons = kernel.resetSwitchingKernels(); const newKernel = kernel.onRequestSwitchKernel(reasons, arguments, kernel); shortcut.kernel = kernel = newKernel; result = newKernel.run.apply(newKernel, arguments); } if (kernel.renderKernels) { return kernel.renderKernels(); } else if (kernel.renderOutput) { return kernel.renderOutput(); } else { return result; } }; return run.apply(kernel, arguments); }; const shortcut = function() { return run.apply(kernel, arguments); }; shortcut.exec = function() { return new Promise((accept, reject) => { try { accept(run.apply(this, arguments)); } catch (e) { reject(e); } }); }; shortcut.replaceKernel = function(replacementKernel) { kernel = replacementKernel; bindKernelToShortcut(kernel, shortcut); }; bindKernelToShortcut(kernel, shortcut); return shortcut; } function bindKernelToShortcut(kernel, shortcut) { if (shortcut.kernel) { shortcut.kernel = kernel; return; } const properties = utils.allPropertiesOf(kernel); for (let i = 0; i < properties.length; i++) { const property = properties[i]; if (property[0] === '_' && property[1] === '_') continue; if (typeof kernel[property] === 'function') { if (property.substring(0, 3) === 'add' || property.substring(0, 3) === 'set') { shortcut[property] = function() { shortcut.kernel[property].apply(shortcut.kernel, arguments); return shortcut; }; } else { shortcut[property] = function() { return shortcut.kernel[property].apply(shortcut.kernel, arguments); }; } } else { shortcut.__defineGetter__(property, () => shortcut.kernel[property]); shortcut.__defineSetter__(property, (value) => { shortcut.kernel[property] = value; }); } } shortcut.kernel = kernel; } module.exports = { kernelRunShortcut }; },{"./utils":113}],111:[function(require,module,exports){ const source = `// https://www.shadertoy.com/view/4t2SDh //note: uniformly distributed, normalized rand, [0,1] highp float randomSeedShift = 1.0; highp float slide = 1.0; uniform highp float randomSeed1; uniform highp float randomSeed2; highp float nrand(highp vec2 n) { highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453); randomSeedShift = result; if (randomSeedShift > 0.5) { slide += 0.00009; } else { slide += 0.0009; } return result; }`; const name = 'math-random-uniformly-distributed'; const functionMatch = `Math.random()`; const functionReplace = `nrand(vTexCoord)`; const functionReturnType = 'Number'; const onBeforeRun = (kernel) => { kernel.setUniform1f('randomSeed1', Math.random()); kernel.setUniform1f('randomSeed2', Math.random()); }; const plugin = { name, onBeforeRun, functionMatch, functionReplace, functionReturnType, source }; module.exports = plugin; },{}],112:[function(require,module,exports){ class Texture { constructor(settings) { const { texture, size, dimensions, output, context, type = 'NumberTexture', kernel, internalFormat, textureFormat } = settings; if (!output) throw new Error('settings property "output" required.'); if (!context) throw new Error('settings property "context" required.'); if (!texture) throw new Error('settings property "texture" required.'); if (!kernel) throw new Error('settings property "kernel" required.'); this.texture = texture; if (texture._refs) { texture._refs++; } else { texture._refs = 1; } this.size = size; this.dimensions = dimensions; this.output = output; this.context = context; this.kernel = kernel; this.type = type; this._deleted = false; this.internalFormat = internalFormat; this.textureFormat = textureFormat; } toArray() { throw new Error(`Not implemented on ${this.constructor.name}`); } clone() { throw new Error(`Not implemented on ${this.constructor.name}`); } delete() { throw new Error(`Not implemented on ${this.constructor.name}`); } clear() { throw new Error(`Not implemented on ${this.constructor.name}`); } } module.exports = { Texture }; },{}],113:[function(require,module,exports){ const acorn = require('acorn'); const { Input } = require('./input'); const { Texture } = require('./texture'); const FUNCTION_NAME = /function ([^(]*)/; const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; const ARGUMENT_NAMES = /([^\s,]+)/g; const utils = { systemEndianness() { return _systemEndianness; }, getSystemEndianness() { const b = new ArrayBuffer(4); const a = new Uint32Array(b); const c = new Uint8Array(b); a[0] = 0xdeadbeef; if (c[0] === 0xef) return 'LE'; if (c[0] === 0xde) return 'BE'; throw new Error('unknown endianness'); }, isFunction(funcObj) { return typeof(funcObj) === 'function'; }, isFunctionString(fn) { if (typeof fn === 'string') { return (fn .slice(0, 'function'.length) .toLowerCase() === 'function'); } return false; }, getFunctionNameFromString(funcStr) { const result = FUNCTION_NAME.exec(funcStr); if (!result || result.length === 0) return null; return result[1].trim(); }, getFunctionBodyFromString(funcStr) { return funcStr.substring(funcStr.indexOf('{') + 1, funcStr.lastIndexOf('}')); }, getArgumentNamesFromString(fn) { const fnStr = fn.replace(STRIP_COMMENTS, ''); let result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES); if (result === null) { result = []; } return result; }, clone(obj) { if (obj === null || typeof obj !== 'object' || obj.hasOwnProperty('isActiveClone')) return obj; const temp = obj.constructor(); for (let key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { obj.isActiveClone = null; temp[key] = utils.clone(obj[key]); delete obj.isActiveClone; } } return temp; }, isArray(array) { return !isNaN(array.length); }, getVariableType(value, strictIntegers) { if (utils.isArray(value)) { if (value.length > 0 && value[0].nodeName === 'IMG') { return 'HTMLImageArray'; } return 'Array'; } switch (value.constructor) { case Boolean: return 'Boolean'; case Number: if (strictIntegers && Number.isInteger(value)) { return 'Integer'; } return 'Float'; case Texture: return value.type; case Input: return 'Input'; } if ('nodeName' in value) { switch (value.nodeName) { case 'IMG': return 'HTMLImage'; case 'CANVAS': return 'HTMLImage'; case 'VIDEO': return 'HTMLVideo'; } } else if (value.hasOwnProperty('type')) { return value.type; } else if (typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas) { return 'OffscreenCanvas'; } else if (typeof ImageBitmap !== 'undefined' && value instanceof ImageBitmap) { return 'ImageBitmap'; } else if (typeof ImageData !== 'undefined' && value instanceof ImageData) { return 'ImageData'; } return 'Unknown'; }, getKernelTextureSize(settings, dimensions) { let [w, h, d] = dimensions; let texelCount = (w || 1) * (h || 1) * (d || 1); if (settings.optimizeFloatMemory && settings.precision === 'single') { w = texelCount = Math.ceil(texelCount / 4); } if (h > 1 && w * h === texelCount) { return new Int32Array([w, h]); } return utils.closestSquareDimensions(texelCount); }, closestSquareDimensions(length) { const sqrt = Math.sqrt(length); let high = Math.ceil(sqrt); let low = Math.floor(sqrt); while (high * low < length) { high--; low = Math.ceil(length / high); } return new Int32Array([low, Math.ceil(length / low)]); }, getMemoryOptimizedFloatTextureSize(dimensions, bitRatio) { const totalArea = utils.roundTo((dimensions[0] || 1) * (dimensions[1] || 1) * (dimensions[2] || 1) * (dimensions[3] || 1), 4); const texelCount = totalArea / bitRatio; return utils.closestSquareDimensions(texelCount); }, getMemoryOptimizedPackedTextureSize(dimensions, bitRatio) { const [w, h, d] = dimensions; const totalArea = utils.roundTo((w || 1) * (h || 1) * (d || 1), 4); const texelCount = totalArea / (4 / bitRatio); return utils.closestSquareDimensions(texelCount); }, roundTo(n, d) { return Math.floor((n + d - 1) / d) * d; }, getDimensions(x, pad) { let ret; if (utils.isArray(x)) { const dim = []; let temp = x; while (utils.isArray(temp)) { dim.push(temp.length); temp = temp[0]; } ret = dim.reverse(); } else if (x instanceof Texture) { ret = x.output; } else if (x instanceof Input) { ret = x.size; } else { throw new Error(`Unknown dimensions of ${x}`); } if (pad) { ret = Array.from(ret); while (ret.length < 3) { ret.push(1); } } return new Int32Array(ret); }, flatten2dArrayTo(array, target) { let offset = 0; for (let y = 0; y < array.length; y++) { target.set(array[y], offset); offset += array[y].length; } }, flatten3dArrayTo(array, target) { let offset = 0; for (let z = 0; z < array.length; z++) { for (let y = 0; y < array[z].length; y++) { target.set(array[z][y], offset); offset += array[z][y].length; } } }, flatten4dArrayTo(array, target) { let offset = 0; for (let l = 0; l < array.length; l++) { for (let z = 0; z < array[l].length; z++) { for (let y = 0; y < array[l][z].length; y++) { target.set(array[l][z][y], offset); offset += array[l][z][y].length; } } } }, flattenTo(array, target) { if (utils.isArray(array[0])) { if (utils.isArray(array[0][0])) { if (utils.isArray(array[0][0][0])) { utils.flatten4dArrayTo(array, target); } else { utils.flatten3dArrayTo(array, target); } } else { utils.flatten2dArrayTo(array, target); } } else { target.set(array); } }, splitArray(array, part) { const result = []; for (let i = 0; i < array.length; i += part) { result.push(new array.constructor(array.buffer, i * 4 + array.byteOffset, part)); } return result; }, getAstString(source, ast) { const lines = Array.isArray(source) ? source : source.split(/\r?\n/g); const start = ast.loc.start; const end = ast.loc.end; const result = []; if (start.line === end.line) { result.push(lines[start.line - 1].substring(start.column, end.column)); } else { result.push(lines[start.line - 1].slice(start.column)); for (let i = start.line; i < end.line; i++) { result.push(lines[i]); } result.push(lines[end.line - 1].slice(0, end.column)); } return result.join('\n'); }, allPropertiesOf(obj) { const props = []; do { props.push.apply(props, Object.getOwnPropertyNames(obj)); } while (obj = Object.getPrototypeOf(obj)); return props; }, linesToString(lines) { if (lines.length > 0) { return lines.join(';\n') + ';\n'; } else { return '\n'; } }, warnDeprecated(type, oldName, newName) { if (newName) { console.warn(`You are using a deprecated ${ type } "${ oldName }". It has been replaced with "${ newName }". Fixing, but please upgrade as it will soon be removed.`); } else { console.warn(`You are using a deprecated ${ type } "${ oldName }". It has been removed. Fixing, but please upgrade as it will soon be removed.`); } }, flipPixels: (pixels, width, height) => { const halfHeight = height / 2 | 0; const bytesPerRow = width * 4; const temp = new Uint8ClampedArray(width * 4); const result = pixels.slice(0); for (let y = 0; y < halfHeight; ++y) { const topOffset = y * bytesPerRow; const bottomOffset = (height - y - 1) * bytesPerRow; temp.set(result.subarray(topOffset, topOffset + bytesPerRow)); result.copyWithin(topOffset, bottomOffset, bottomOffset + bytesPerRow); result.set(temp, bottomOffset); } return result; }, erectPackedFloat: (array, width) => { return array.subarray(0, width); }, erect2DPackedFloat: (array, width, height) => { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xStart = y * width; const xEnd = xStart + width; yResults[y] = array.subarray(xStart, xEnd); } return yResults; }, erect3DPackedFloat: (array, width, height, depth) => { const zResults = new Array(depth); for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xStart = (z * height * width) + y * width; const xEnd = xStart + width; yResults[y] = array.subarray(xStart, xEnd); } zResults[z] = yResults; } return zResults; }, erectMemoryOptimizedFloat: (array, width) => { return array.subarray(0, width); }, erectMemoryOptimized2DFloat: (array, width, height) => { const yResults = new Array(height); for (let y = 0; y < height; y++) { const offset = y * width; yResults[y] = array.subarray(offset, offset + width); } return yResults; }, erectMemoryOptimized3DFloat: (array, width, height, depth) => { const zResults = new Array(depth); for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const offset = (z * height * width) + (y * width); yResults[y] = array.subarray(offset, offset + width); } zResults[z] = yResults; } return zResults; }, erectFloat: (array, width) => { const xResults = new Float32Array(width); let i = 0; for (let x = 0; x < width; x++) { xResults[x] = array[i]; i += 4; } return xResults; }, erect2DFloat: (array, width, height) => { const yResults = new Array(height); let i = 0; for (let y = 0; y < height; y++) { const xResults = new Float32Array(width); for (let x = 0; x < width; x++) { xResults[x] = array[i]; i += 4; } yResults[y] = xResults; } return yResults; }, erect3DFloat: (array, width, height, depth) => { const zResults = new Array(depth); let i = 0; for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Float32Array(width); for (let x = 0; x < width; x++) { xResults[x] = array[i]; i += 4; } yResults[y] = xResults; } zResults[z] = yResults; } return zResults; }, erectArray2: (array, width) => { const xResults = new Array(width); const xResultsMax = width * 4; let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x, x + 2); } return xResults; }, erect2DArray2: (array, width, height) => { const yResults = new Array(height); const XResultsMax = width * 4; for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = y * XResultsMax; let i = 0; for (let x = 0; x < XResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 2); } yResults[y] = xResults; } return yResults; }, erect3DArray2: (array, width, height, depth) => { const xResultsMax = width * 4; const zResults = new Array(depth); for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = (z * xResultsMax * height) + (y * xResultsMax); let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 2); } yResults[y] = xResults; } zResults[z] = yResults; } return zResults; }, erectArray3: (array, width) => { const xResults = new Array(width); const xResultsMax = width * 4; let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x, x + 3); } return xResults; }, erect2DArray3: (array, width, height) => { const xResultsMax = width * 4; const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = y * xResultsMax; let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 3); } yResults[y] = xResults; } return yResults; }, erect3DArray3: (array, width, height, depth) => { const xResultsMax = width * 4; const zResults = new Array(depth); for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = (z * xResultsMax * height) + (y * xResultsMax); let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 3); } yResults[y] = xResults; } zResults[z] = yResults; } return zResults; }, erectArray4: (array, width) => { const xResults = new Array(array); const xResultsMax = width * 4; let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x, x + 4); } return xResults; }, erect2DArray4: (array, width, height) => { const xResultsMax = width * 4; const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = y * xResultsMax; let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 4); } yResults[y] = xResults; } return yResults; }, erect3DArray4: (array, width, height, depth) => { const xResultsMax = width * 4; const zResults = new Array(depth); for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = (z * xResultsMax * height) + (y * xResultsMax); let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 4); } yResults[y] = xResults; } zResults[z] = yResults; } return zResults; }, flattenFunctionToString: (source, settings) => { const { findDependency, thisLookup, doNotDefine } = settings; let flattened = settings.flattened; if (!flattened) { flattened = settings.flattened = {}; } const ast = acorn.parse(source); const functionDependencies = []; let indent = 0; function flatten(ast) { if (Array.isArray(ast)) { const results = []; for (let i = 0; i < ast.length; i++) { results.push(flatten(ast[i])); } return results.join(''); } switch (ast.type) { case 'Program': return flatten(ast.body) + (ast.body[0].type === 'VariableDeclaration' ? ';' : ''); case 'FunctionDeclaration': return `function ${ast.id.name}(${ast.params.map(flatten).join(', ')}) ${ flatten(ast.body) }`; case 'BlockStatement': { const result = []; indent += 2; for (let i = 0; i < ast.body.length; i++) { const flat = flatten(ast.body[i]); if (flat) { result.push(' '.repeat(indent) + flat, ';\n'); } } indent -= 2; return `{\n${result.join('')}}`; } case 'VariableDeclaration': const declarations = utils.normalizeDeclarations(ast) .map(flatten) .filter(r => r !== null); if (declarations.length < 1) { return ''; } else { return `${ast.kind} ${declarations.join(',')}`; } case 'VariableDeclarator': if (ast.init.object && ast.init.object.type === 'ThisExpression') { const lookup = thisLookup(ast.init.property.name, true); if (lookup) { return `${ast.id.name} = ${flatten(ast.init)}`; } else { return null; } } else { return `${ast.id.name} = ${flatten(ast.init)}`; } case 'CallExpression': { if (ast.callee.property.name === 'subarray') { return `${flatten(ast.callee.object)}.${flatten(ast.callee.property)}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } if (ast.callee.object.name === 'gl' || ast.callee.object.name === 'context') { return `${flatten(ast.callee.object)}.${flatten(ast.callee.property)}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } if (ast.callee.object.type === 'ThisExpression') { functionDependencies.push(findDependency('this', ast.callee.property.name)); return `${ast.callee.property.name}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } else if (ast.callee.object.name) { const foundSource = findDependency(ast.callee.object.name, ast.callee.property.name); if (foundSource === null) { return `${ast.callee.object.name}.${ast.callee.property.name}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } else { functionDependencies.push(foundSource); return `${ast.callee.property.name}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } } else if (ast.callee.object.type === 'MemberExpression') { return `${flatten(ast.callee.object)}.${ast.callee.property.name}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } else { throw new Error('unknown ast.callee'); } } case 'ReturnStatement': return `return ${flatten(ast.argument)}`; case 'BinaryExpression': return `(${flatten(ast.left)}${ast.operator}${flatten(ast.right)})`; case 'UnaryExpression': if (ast.prefix) { return `${ast.operator} ${flatten(ast.argument)}`; } else { return `${flatten(ast.argument)} ${ast.operator}`; } case 'ExpressionStatement': return `${flatten(ast.expression)}`; case 'SequenceExpression': return `(${flatten(ast.expressions)})`; case 'ArrowFunctionExpression': return `(${ast.params.map(flatten).join(', ')}) => ${flatten(ast.body)}`; case 'Literal': return ast.raw; case 'Identifier': return ast.name; case 'MemberExpression': if (ast.object.type === 'ThisExpression') { return thisLookup(ast.property.name); } if (ast.computed) { return `${flatten(ast.object)}[${flatten(ast.property)}]`; } return flatten(ast.object) + '.' + flatten(ast.property); case 'ThisExpression': return 'this'; case 'NewExpression': return `new ${flatten(ast.callee)}(${ast.arguments.map(value => flatten(value)).join(', ')})`; case 'ForStatement': return `for (${flatten(ast.init)};${flatten(ast.test)};${flatten(ast.update)}) ${flatten(ast.body)}`; case 'AssignmentExpression': return `${flatten(ast.left)}${ast.operator}${flatten(ast.right)}`; case 'UpdateExpression': return `${flatten(ast.argument)}${ast.operator}`; case 'IfStatement': return `if (${flatten(ast.test)}) ${flatten(ast.consequent)}`; case 'ThrowStatement': return `throw ${flatten(ast.argument)}`; case 'ObjectPattern': return ast.properties.map(flatten).join(', '); case 'ArrayPattern': return ast.elements.map(flatten).join(', '); case 'DebuggerStatement': return 'debugger;'; case 'ConditionalExpression': return `${flatten(ast.test)}?${flatten(ast.consequent)}:${flatten(ast.alternate)}`; case 'Property': if (ast.kind === 'init') { return flatten(ast.key); } } throw new Error(`unhandled ast.type of ${ ast.type }`); } const result = flatten(ast); if (functionDependencies.length > 0) { const flattenedFunctionDependencies = []; for (let i = 0; i < functionDependencies.length; i++) { const functionDependency = functionDependencies[i]; if (!flattened[functionDependency]) { flattened[functionDependency] = true; } functionDependency ? flattenedFunctionDependencies.push(utils.flattenFunctionToString(functionDependency, settings) + '\n') : ''; } return flattenedFunctionDependencies.join('') + result; } return result; }, normalizeDeclarations: (ast) => { if (ast.type !== 'VariableDeclaration') throw new Error('Ast is not of type "VariableDeclaration"'); const normalizedDeclarations = []; for (let declarationIndex = 0; declarationIndex < ast.declarations.length; declarationIndex++) { const declaration = ast.declarations[declarationIndex]; if (declaration.id && declaration.id.type === 'ObjectPattern' && declaration.id.properties) { const { properties } = declaration.id; for (let propertyIndex = 0; propertyIndex < properties.length; propertyIndex++) { const property = properties[propertyIndex]; if (property.value.type === 'ObjectPattern' && property.value.properties) { for (let subPropertyIndex = 0; subPropertyIndex < property.value.properties.length; subPropertyIndex++) { const subProperty = property.value.properties[subPropertyIndex]; if (subProperty.type === 'Property') { normalizedDeclarations.push({ type: 'VariableDeclarator', id: { type: 'Identifier', name: subProperty.key.name }, init: { type: 'MemberExpression', object: { type: 'MemberExpression', object: declaration.init, property: { type: 'Identifier', name: property.key.name }, computed: false }, property: { type: 'Identifier', name: subProperty.key.name }, computed: false } }); } else { throw new Error('unexpected state'); } } } else if (property.value.type === 'Identifier') { normalizedDeclarations.push({ type: 'VariableDeclarator', id: { type: 'Identifier', name: property.value && property.value.name ? property.value.name : property.key.name }, init: { type: 'MemberExpression', object: declaration.init, property: { type: 'Identifier', name: property.key.name }, computed: false } }); } else { throw new Error('unexpected state'); } } } else if (declaration.id && declaration.id.type === 'ArrayPattern' && declaration.id.elements) { const { elements } = declaration.id; for (let elementIndex = 0; elementIndex < elements.length; elementIndex++) { const element = elements[elementIndex]; if (element.type === 'Identifier') { normalizedDeclarations.push({ type: 'VariableDeclarator', id: { type: 'Identifier', name: element.name }, init: { type: 'MemberExpression', object: declaration.init, property: { type: 'Literal', value: elementIndex, raw: elementIndex.toString(), start: element.start, end: element.end }, computed: true } }); } else { throw new Error('unexpected state'); } } } else { normalizedDeclarations.push(declaration); } } return normalizedDeclarations; }, splitHTMLImageToRGB: (gpu, image) => { const rKernel = gpu.createKernel(function(a) { const pixel = a[this.thread.y][this.thread.x]; return pixel.r * 255; }, { output: [image.width, image.height], precision: 'unsigned', argumentTypes: { a: 'HTMLImage' }, }); const gKernel = gpu.createKernel(function(a) { const pixel = a[this.thread.y][this.thread.x]; return pixel.g * 255; }, { output: [image.width, image.height], precision: 'unsigned', argumentTypes: { a: 'HTMLImage' }, }); const bKernel = gpu.createKernel(function(a) { const pixel = a[this.thread.y][this.thread.x]; return pixel.b * 255; }, { output: [image.width, image.height], precision: 'unsigned', argumentTypes: { a: 'HTMLImage' }, }); const aKernel = gpu.createKernel(function(a) { const pixel = a[this.thread.y][this.thread.x]; return pixel.a * 255; }, { output: [image.width, image.height], precision: 'unsigned', argumentTypes: { a: 'HTMLImage' }, }); const result = [ rKernel(image), gKernel(image), bKernel(image), aKernel(image), ]; result.rKernel = rKernel; result.gKernel = gKernel; result.bKernel = bKernel; result.aKernel = aKernel; result.gpu = gpu; return result; }, splitRGBAToCanvases: (gpu, rgba, width, height) => { const visualKernelR = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(pixel.r / 255, 0, 0, 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelR(rgba); const visualKernelG = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(0, pixel.g / 255, 0, 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelG(rgba); const visualKernelB = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(0, 0, pixel.b / 255, 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelB(rgba); const visualKernelA = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(255, 255, 255, pixel.a / 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelA(rgba); return [ visualKernelR.canvas, visualKernelG.canvas, visualKernelB.canvas, visualKernelA.canvas, ]; }, getMinifySafeName: (fn) => { try { const ast = acorn.parse(`const value = ${fn.toString()}`); const { init } = ast.body[0].declarations[0]; return init.body.name || init.body.body[0].argument.name; } catch (e) { throw new Error('Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }'); } }, sanitizeName: function(name) { if (dollarSign.test(name)) { name = name.replace(dollarSign, 'S_S'); } if (doubleUnderscore.test(name)) { name = name.replace(doubleUnderscore, 'U_U'); } else if (singleUnderscore.test(name)) { name = name.replace(singleUnderscore, 'u_u'); } return name; } }; const dollarSign = /\$/; const doubleUnderscore = /__/; const singleUnderscore = /_/; const _systemEndianness = utils.getSystemEndianness(); module.exports = { utils }; },{"./input":109,"./texture":112,"acorn":1}]},{},[106])(106) }); ================================================ FILE: dist/gpu-browser.js ================================================ /** * gpu.js * http://gpu.rocks/ * * GPU Accelerated JavaScript * * @version 2.16.0 * @date Thu Feb 13 2025 11:46:48 GMT-0800 (Pacific Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2025 gpu.js Team */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.GPU = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i code) { return false } pos += set[i + 1]; if (pos >= code) { return true } } return false } function isIdentifierStart(code, astral) { if (code < 65) { return code === 36 } if (code < 91) { return true } if (code < 97) { return code === 95 } if (code < 123) { return true } if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet(code, astralIdentifierStartCodes) } function isIdentifierChar(code, astral) { if (code < 48) { return code === 36 } if (code < 58) { return true } if (code < 65) { return false } if (code < 91) { return true } if (code < 97) { return code === 95 } if (code < 123) { return true } if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) } var TokenType = function TokenType(label, conf) { if ( conf === void 0 ) conf = {}; this.label = label; this.keyword = conf.keyword; this.beforeExpr = !!conf.beforeExpr; this.startsExpr = !!conf.startsExpr; this.isLoop = !!conf.isLoop; this.isAssign = !!conf.isAssign; this.prefix = !!conf.prefix; this.postfix = !!conf.postfix; this.binop = conf.binop || null; this.updateContext = null; }; function binop(name, prec) { return new TokenType(name, {beforeExpr: true, binop: prec}) } var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; var keywords = {}; function kw(name, options) { if ( options === void 0 ) options = {}; options.keyword = name; return keywords[name] = new TokenType(name, options) } var types$1 = { num: new TokenType("num", startsExpr), regexp: new TokenType("regexp", startsExpr), string: new TokenType("string", startsExpr), name: new TokenType("name", startsExpr), privateId: new TokenType("privateId", startsExpr), eof: new TokenType("eof"), bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), bracketR: new TokenType("]"), braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), braceR: new TokenType("}"), parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), parenR: new TokenType(")"), comma: new TokenType(",", beforeExpr), semi: new TokenType(";", beforeExpr), colon: new TokenType(":", beforeExpr), dot: new TokenType("."), question: new TokenType("?", beforeExpr), questionDot: new TokenType("?."), arrow: new TokenType("=>", beforeExpr), template: new TokenType("template"), invalidTemplate: new TokenType("invalidTemplate"), ellipsis: new TokenType("...", beforeExpr), backQuote: new TokenType("`", startsExpr), dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), eq: new TokenType("=", {beforeExpr: true, isAssign: true}), assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), logicalOR: binop("||", 1), logicalAND: binop("&&", 2), bitwiseOR: binop("|", 3), bitwiseXOR: binop("^", 4), bitwiseAND: binop("&", 5), equality: binop("==/!=/===/!==", 6), relational: binop("/<=/>=", 7), bitShift: binop("<>/>>>", 8), plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), modulo: binop("%", 10), star: binop("*", 10), slash: binop("/", 10), starstar: new TokenType("**", {beforeExpr: true}), coalesce: binop("??", 1), _break: kw("break"), _case: kw("case", beforeExpr), _catch: kw("catch"), _continue: kw("continue"), _debugger: kw("debugger"), _default: kw("default", beforeExpr), _do: kw("do", {isLoop: true, beforeExpr: true}), _else: kw("else", beforeExpr), _finally: kw("finally"), _for: kw("for", {isLoop: true}), _function: kw("function", startsExpr), _if: kw("if"), _return: kw("return", beforeExpr), _switch: kw("switch"), _throw: kw("throw", beforeExpr), _try: kw("try"), _var: kw("var"), _const: kw("const"), _while: kw("while", {isLoop: true}), _with: kw("with"), _new: kw("new", {beforeExpr: true, startsExpr: true}), _this: kw("this", startsExpr), _super: kw("super", startsExpr), _class: kw("class", startsExpr), _extends: kw("extends", beforeExpr), _export: kw("export"), _import: kw("import", startsExpr), _null: kw("null", startsExpr), _true: kw("true", startsExpr), _false: kw("false", startsExpr), _in: kw("in", {beforeExpr: true, binop: 7}), _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) }; var lineBreak = /\r\n?|\n|\u2028|\u2029/; var lineBreakG = new RegExp(lineBreak.source, "g"); function isNewLine(code) { return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 } function nextLineBreak(code, from, end) { if ( end === void 0 ) end = code.length; for (var i = from; i < end; i++) { var next = code.charCodeAt(i); if (isNewLine(next)) { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 } } return -1 } var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; var ref = Object.prototype; var hasOwnProperty = ref.hasOwnProperty; var toString = ref.toString; var hasOwn = Object.hasOwn || (function (obj, propName) { return ( hasOwnProperty.call(obj, propName) ); }); var isArray = Array.isArray || (function (obj) { return ( toString.call(obj) === "[object Array]" ); }); var regexpCache = Object.create(null); function wordsRegexp(words) { return regexpCache[words] || (regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")) } function codePointToString(code) { if (code <= 0xFFFF) { return String.fromCharCode(code) } code -= 0x10000; return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) } var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; var Position = function Position(line, col) { this.line = line; this.column = col; }; Position.prototype.offset = function offset (n) { return new Position(this.line, this.column + n) }; var SourceLocation = function SourceLocation(p, start, end) { this.start = start; this.end = end; if (p.sourceFile !== null) { this.source = p.sourceFile; } }; function getLineInfo(input, offset) { for (var line = 1, cur = 0;;) { var nextBreak = nextLineBreak(input, cur, offset); if (nextBreak < 0) { return new Position(line, offset - cur) } ++line; cur = nextBreak; } } var defaultOptions = { ecmaVersion: null, sourceType: "script", onInsertedSemicolon: null, onTrailingComma: null, allowReserved: null, allowReturnOutsideFunction: false, allowImportExportEverywhere: false, allowAwaitOutsideFunction: null, allowSuperOutsideMethod: null, allowHashBang: false, checkPrivateFields: true, locations: false, onToken: null, onComment: null, ranges: false, program: null, sourceFile: null, directSourceFile: null, preserveParens: false }; var warnedAboutEcmaVersion = false; function getOptions(opts) { var options = {}; for (var opt in defaultOptions) { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; } if (options.ecmaVersion === "latest") { options.ecmaVersion = 1e8; } else if (options.ecmaVersion == null) { if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { warnedAboutEcmaVersion = true; console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); } options.ecmaVersion = 11; } else if (options.ecmaVersion >= 2015) { options.ecmaVersion -= 2009; } if (options.allowReserved == null) { options.allowReserved = options.ecmaVersion < 5; } if (!opts || opts.allowHashBang == null) { options.allowHashBang = options.ecmaVersion >= 14; } if (isArray(options.onToken)) { var tokens = options.onToken; options.onToken = function (token) { return tokens.push(token); }; } if (isArray(options.onComment)) { options.onComment = pushComment(options, options.onComment); } return options } function pushComment(options, array) { return function(block, text, start, end, startLoc, endLoc) { var comment = { type: block ? "Block" : "Line", value: text, start: start, end: end }; if (options.locations) { comment.loc = new SourceLocation(this, startLoc, endLoc); } if (options.ranges) { comment.range = [start, end]; } array.push(comment); } } var SCOPE_TOP = 1, SCOPE_FUNCTION = 2, SCOPE_ASYNC = 4, SCOPE_GENERATOR = 8, SCOPE_ARROW = 16, SCOPE_SIMPLE_CATCH = 32, SCOPE_SUPER = 64, SCOPE_DIRECT_SUPER = 128, SCOPE_CLASS_STATIC_BLOCK = 256, SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; function functionFlags(async, generator) { return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) } var BIND_NONE = 0, BIND_VAR = 1, BIND_LEXICAL = 2, BIND_FUNCTION = 3, BIND_SIMPLE_CATCH = 4, BIND_OUTSIDE = 5; var Parser = function Parser(options, input, startPos) { this.options = options = getOptions(options); this.sourceFile = options.sourceFile; this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); var reserved = ""; if (options.allowReserved !== true) { reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; if (options.sourceType === "module") { reserved += " await"; } } this.reservedWords = wordsRegexp(reserved); var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; this.reservedWordsStrict = wordsRegexp(reservedStrict); this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); this.input = String(input); this.containsEsc = false; if (startPos) { this.pos = startPos; this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; } else { this.pos = this.lineStart = 0; this.curLine = 1; } this.type = types$1.eof; this.value = null; this.start = this.end = this.pos; this.startLoc = this.endLoc = this.curPosition(); this.lastTokEndLoc = this.lastTokStartLoc = null; this.lastTokStart = this.lastTokEnd = this.pos; this.context = this.initialContext(); this.exprAllowed = true; this.inModule = options.sourceType === "module"; this.strict = this.inModule || this.strictDirective(this.pos); this.potentialArrowAt = -1; this.potentialArrowInForAwait = false; this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; this.labels = []; this.undefinedExports = Object.create(null); if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") { this.skipLineComment(2); } this.scopeStack = []; this.enterScope(SCOPE_TOP); this.regexpState = null; this.privateNameStack = []; }; var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } }; Parser.prototype.parse = function parse () { var node = this.options.program || this.startNode(); this.nextToken(); return this.parseTopLevel(node) }; prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit }; prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit }; prototypeAccessors.canAwait.get = function () { for (var i = this.scopeStack.length - 1; i >= 0; i--) { var scope = this.scopeStack[i]; if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false } if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 } } return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction }; prototypeAccessors.allowSuper.get = function () { var ref = this.currentThisScope(); var flags = ref.flags; var inClassFieldInit = ref.inClassFieldInit; return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod }; prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; prototypeAccessors.allowNewDotTarget.get = function () { var ref = this.currentThisScope(); var flags = ref.flags; var inClassFieldInit = ref.inClassFieldInit; return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit }; prototypeAccessors.inClassStaticBlock.get = function () { return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0 }; Parser.extend = function extend () { var plugins = [], len = arguments.length; while ( len-- ) plugins[ len ] = arguments[ len ]; var cls = this; for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } return cls }; Parser.parse = function parse (input, options) { return new this(options, input).parse() }; Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { var parser = new this(options, input, pos); parser.nextToken(); return parser.parseExpression() }; Parser.tokenizer = function tokenizer (input, options) { return new this(options, input) }; Object.defineProperties( Parser.prototype, prototypeAccessors ); var pp$9 = Parser.prototype; var literal = /^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/; pp$9.strictDirective = function(start) { if (this.options.ecmaVersion < 5) { return false } for (;;) { skipWhiteSpace.lastIndex = start; start += skipWhiteSpace.exec(this.input)[0].length; var match = literal.exec(this.input.slice(start)); if (!match) { return false } if ((match[1] || match[2]) === "use strict") { skipWhiteSpace.lastIndex = start + match[0].length; var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; var next = this.input.charAt(end); return next === ";" || next === "}" || (lineBreak.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) } start += match[0].length; skipWhiteSpace.lastIndex = start; start += skipWhiteSpace.exec(this.input)[0].length; if (this.input[start] === ";") { start++; } } }; pp$9.eat = function(type) { if (this.type === type) { this.next(); return true } else { return false } }; pp$9.isContextual = function(name) { return this.type === types$1.name && this.value === name && !this.containsEsc }; pp$9.eatContextual = function(name) { if (!this.isContextual(name)) { return false } this.next(); return true }; pp$9.expectContextual = function(name) { if (!this.eatContextual(name)) { this.unexpected(); } }; pp$9.canInsertSemicolon = function() { return this.type === types$1.eof || this.type === types$1.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }; pp$9.insertSemicolon = function() { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon) { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } return true } }; pp$9.semicolon = function() { if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); } }; pp$9.afterTrailingComma = function(tokType, notNext) { if (this.type === tokType) { if (this.options.onTrailingComma) { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } if (!notNext) { this.next(); } return true } }; pp$9.expect = function(type) { this.eat(type) || this.unexpected(); }; pp$9.unexpected = function(pos) { this.raise(pos != null ? pos : this.start, "Unexpected token"); }; var DestructuringErrors = function DestructuringErrors() { this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1; }; pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) { if (!refDestructuringErrors) { return } if (refDestructuringErrors.trailingComma > -1) { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); } }; pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) { if (!refDestructuringErrors) { return false } var shorthandAssign = refDestructuringErrors.shorthandAssign; var doubleProto = refDestructuringErrors.doubleProto; if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } if (shorthandAssign >= 0) { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } if (doubleProto >= 0) { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } }; pp$9.checkYieldAwaitInDefaultParams = function() { if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } if (this.awaitPos) { this.raise(this.awaitPos, "Await expression cannot be a default value"); } }; pp$9.isSimpleAssignTarget = function(expr) { if (expr.type === "ParenthesizedExpression") { return this.isSimpleAssignTarget(expr.expression) } return expr.type === "Identifier" || expr.type === "MemberExpression" }; var pp$8 = Parser.prototype; pp$8.parseTopLevel = function(node) { var exports = Object.create(null); if (!node.body) { node.body = []; } while (this.type !== types$1.eof) { var stmt = this.parseStatement(null, true, exports); node.body.push(stmt); } if (this.inModule) { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) { var name = list[i]; this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); } } this.adaptDirectivePrologue(node.body); this.next(); node.sourceType = this.options.sourceType; return this.finishNode(node, "Program") }; var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; pp$8.isLet = function(context) { if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } skipWhiteSpace.lastIndex = this.pos; var skip = skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); if (nextCh === 91 || nextCh === 92) { return true } if (context) { return false } if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } if (isIdentifierStart(nextCh, true)) { var pos = next + 1; while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } var ident = this.input.slice(next, pos); if (!keywordRelationalOperator.test(ident)) { return true } } return false }; pp$8.isAsyncFunction = function() { if (this.options.ecmaVersion < 8 || !this.isContextual("async")) { return false } skipWhiteSpace.lastIndex = this.pos; var skip = skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length, after; return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) }; pp$8.parseStatement = function(context, topLevel, exports) { var starttype = this.type, node = this.startNode(), kind; if (this.isLet(context)) { starttype = types$1._var; kind = "let"; } switch (starttype) { case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword) case types$1._debugger: return this.parseDebuggerStatement(node) case types$1._do: return this.parseDoStatement(node) case types$1._for: return this.parseForStatement(node) case types$1._function: if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } return this.parseFunctionStatement(node, false, !context) case types$1._class: if (context) { this.unexpected(); } return this.parseClass(node, true) case types$1._if: return this.parseIfStatement(node) case types$1._return: return this.parseReturnStatement(node) case types$1._switch: return this.parseSwitchStatement(node) case types$1._throw: return this.parseThrowStatement(node) case types$1._try: return this.parseTryStatement(node) case types$1._const: case types$1._var: kind = kind || this.value; if (context && kind !== "var") { this.unexpected(); } return this.parseVarStatement(node, kind) case types$1._while: return this.parseWhileStatement(node) case types$1._with: return this.parseWithStatement(node) case types$1.braceL: return this.parseBlock(true, node) case types$1.semi: return this.parseEmptyStatement(node) case types$1._export: case types$1._import: if (this.options.ecmaVersion > 10 && starttype === types$1._import) { skipWhiteSpace.lastIndex = this.pos; var skip = skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); if (nextCh === 40 || nextCh === 46) { return this.parseExpressionStatement(node, this.parseExpression()) } } if (!this.options.allowImportExportEverywhere) { if (!topLevel) { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } if (!this.inModule) { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } } return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports) default: if (this.isAsyncFunction()) { if (context) { this.unexpected(); } this.next(); return this.parseFunctionStatement(node, true, !context) } var maybeName = this.value, expr = this.parseExpression(); if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) { return this.parseLabeledStatement(node, maybeName, expr, context) } else { return this.parseExpressionStatement(node, expr) } } }; pp$8.parseBreakContinueStatement = function(node, keyword) { var isBreak = keyword === "break"; this.next(); if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; } else if (this.type !== types$1.name) { this.unexpected(); } else { node.label = this.parseIdent(); this.semicolon(); } var i = 0; for (; i < this.labels.length; ++i) { var lab = this.labels[i]; if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } if (node.label && isBreak) { break } } } if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") }; pp$8.parseDebuggerStatement = function(node) { this.next(); this.semicolon(); return this.finishNode(node, "DebuggerStatement") }; pp$8.parseDoStatement = function(node) { this.next(); this.labels.push(loopLabel); node.body = this.parseStatement("do"); this.labels.pop(); this.expect(types$1._while); node.test = this.parseParenExpression(); if (this.options.ecmaVersion >= 6) { this.eat(types$1.semi); } else { this.semicolon(); } return this.finishNode(node, "DoWhileStatement") }; pp$8.parseForStatement = function(node) { this.next(); var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; this.labels.push(loopLabel); this.enterScope(0); this.expect(types$1.parenL); if (this.type === types$1.semi) { if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, null) } var isLet = this.isLet(); if (this.type === types$1._var || this.type === types$1._const || isLet) { var init$1 = this.startNode(), kind = isLet ? "let" : this.value; this.next(); this.parseVar(init$1, true, kind); this.finishNode(init$1, "VariableDeclaration"); if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { if (this.options.ecmaVersion >= 9) { if (this.type === types$1._in) { if (awaitAt > -1) { this.unexpected(awaitAt); } } else { node.await = awaitAt > -1; } } return this.parseForIn(node, init$1) } if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, init$1) } var startsWithLet = this.isContextual("let"), isForOf = false; var containsEsc = this.containsEsc; var refDestructuringErrors = new DestructuringErrors; var initPos = this.start; var init = awaitAt > -1 ? this.parseExprSubscripts(refDestructuringErrors, "await") : this.parseExpression(true, refDestructuringErrors); if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { if (awaitAt > -1) { if (this.type === types$1._in) { this.unexpected(awaitAt); } node.await = true; } else if (isForOf && this.options.ecmaVersion >= 8) { if (init.start === initPos && !containsEsc && init.type === "Identifier" && init.name === "async") { this.unexpected(); } else if (this.options.ecmaVersion >= 9) { node.await = false; } } if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); } this.toAssignable(init, false, refDestructuringErrors); this.checkLValPattern(init); return this.parseForIn(node, init) } else { this.checkExpressionErrors(refDestructuringErrors, true); } if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, init) }; pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) { this.next(); return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) }; pp$8.parseIfStatement = function(node) { this.next(); node.test = this.parseParenExpression(); node.consequent = this.parseStatement("if"); node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null; return this.finishNode(node, "IfStatement") }; pp$8.parseReturnStatement = function(node) { if (!this.inFunction && !this.options.allowReturnOutsideFunction) { this.raise(this.start, "'return' outside of function"); } this.next(); if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; } else { node.argument = this.parseExpression(); this.semicolon(); } return this.finishNode(node, "ReturnStatement") }; pp$8.parseSwitchStatement = function(node) { this.next(); node.discriminant = this.parseParenExpression(); node.cases = []; this.expect(types$1.braceL); this.labels.push(switchLabel); this.enterScope(0); var cur; for (var sawDefault = false; this.type !== types$1.braceR;) { if (this.type === types$1._case || this.type === types$1._default) { var isCase = this.type === types$1._case; if (cur) { this.finishNode(cur, "SwitchCase"); } node.cases.push(cur = this.startNode()); cur.consequent = []; this.next(); if (isCase) { cur.test = this.parseExpression(); } else { if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } sawDefault = true; cur.test = null; } this.expect(types$1.colon); } else { if (!cur) { this.unexpected(); } cur.consequent.push(this.parseStatement(null)); } } this.exitScope(); if (cur) { this.finishNode(cur, "SwitchCase"); } this.next(); this.labels.pop(); return this.finishNode(node, "SwitchStatement") }; pp$8.parseThrowStatement = function(node) { this.next(); if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) { this.raise(this.lastTokEnd, "Illegal newline after throw"); } node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement") }; var empty$1 = []; pp$8.parseCatchClauseParam = function() { var param = this.parseBindingAtom(); var simple = param.type === "Identifier"; this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); this.expect(types$1.parenR); return param }; pp$8.parseTryStatement = function(node) { this.next(); node.block = this.parseBlock(); node.handler = null; if (this.type === types$1._catch) { var clause = this.startNode(); this.next(); if (this.eat(types$1.parenL)) { clause.param = this.parseCatchClauseParam(); } else { if (this.options.ecmaVersion < 10) { this.unexpected(); } clause.param = null; this.enterScope(0); } clause.body = this.parseBlock(false); this.exitScope(); node.handler = this.finishNode(clause, "CatchClause"); } node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) { this.raise(node.start, "Missing catch or finally clause"); } return this.finishNode(node, "TryStatement") }; pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) { this.next(); this.parseVar(node, false, kind, allowMissingInitializer); this.semicolon(); return this.finishNode(node, "VariableDeclaration") }; pp$8.parseWhileStatement = function(node) { this.next(); node.test = this.parseParenExpression(); this.labels.push(loopLabel); node.body = this.parseStatement("while"); this.labels.pop(); return this.finishNode(node, "WhileStatement") }; pp$8.parseWithStatement = function(node) { if (this.strict) { this.raise(this.start, "'with' in strict mode"); } this.next(); node.object = this.parseParenExpression(); node.body = this.parseStatement("with"); return this.finishNode(node, "WithStatement") }; pp$8.parseEmptyStatement = function(node) { this.next(); return this.finishNode(node, "EmptyStatement") }; pp$8.parseLabeledStatement = function(node, maybeName, expr, context) { for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) { var label = list[i$1]; if (label.name === maybeName) { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); } } var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null; for (var i = this.labels.length - 1; i >= 0; i--) { var label$1 = this.labels[i]; if (label$1.statementStart === node.start) { label$1.statementStart = this.start; label$1.kind = kind; } else { break } } this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); this.labels.pop(); node.label = expr; return this.finishNode(node, "LabeledStatement") }; pp$8.parseExpressionStatement = function(node, expr) { node.expression = expr; this.semicolon(); return this.finishNode(node, "ExpressionStatement") }; pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) { if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; if ( node === void 0 ) node = this.startNode(); node.body = []; this.expect(types$1.braceL); if (createNewLexicalScope) { this.enterScope(0); } while (this.type !== types$1.braceR) { var stmt = this.parseStatement(null); node.body.push(stmt); } if (exitStrict) { this.strict = false; } this.next(); if (createNewLexicalScope) { this.exitScope(); } return this.finishNode(node, "BlockStatement") }; pp$8.parseFor = function(node, init) { node.init = init; this.expect(types$1.semi); node.test = this.type === types$1.semi ? null : this.parseExpression(); this.expect(types$1.semi); node.update = this.type === types$1.parenR ? null : this.parseExpression(); this.expect(types$1.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, "ForStatement") }; pp$8.parseForIn = function(node, init) { var isForIn = this.type === types$1._in; this.next(); if ( init.type === "VariableDeclaration" && init.declarations[0].init != null && ( !isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier" ) ) { this.raise( init.start, ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") ); } node.left = init; node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); this.expect(types$1.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") }; pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) { node.declarations = []; node.kind = kind; for (;;) { var decl = this.startNode(); this.parseVarId(decl, kind); if (this.eat(types$1.eq)) { decl.init = this.parseMaybeAssign(isFor); } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { this.unexpected(); } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) { this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); } else { decl.init = null; } node.declarations.push(this.finishNode(decl, "VariableDeclarator")); if (!this.eat(types$1.comma)) { break } } return node }; pp$8.parseVarId = function(decl, kind) { decl.id = this.parseBindingAtom(); this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); }; var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { this.initFunction(node); if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT)) { this.unexpected(); } node.generator = this.eat(types$1.star); } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } if (statement & FUNC_STATEMENT) { node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent(); if (node.id && !(statement & FUNC_HANGING_STATEMENT)) { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } } var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags(node.async, node.generator)); if (!(statement & FUNC_STATEMENT)) { node.id = this.type === types$1.name ? this.parseIdent() : null; } this.parseFunctionParams(node); this.parseFunctionBody(node, allowExpressionBody, false, forInit); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") }; pp$8.parseFunctionParams = function(node) { this.expect(types$1.parenL); node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); }; pp$8.parseClass = function(node, isStatement) { this.next(); var oldStrict = this.strict; this.strict = true; this.parseClassId(node, isStatement); this.parseClassSuper(node); var privateNameMap = this.enterClassBody(); var classBody = this.startNode(); var hadConstructor = false; classBody.body = []; this.expect(types$1.braceL); while (this.type !== types$1.braceR) { var element = this.parseClassElement(node.superClass !== null); if (element) { classBody.body.push(element); if (element.type === "MethodDefinition" && element.kind === "constructor") { if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); } hadConstructor = true; } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); } } } this.strict = oldStrict; this.next(); node.body = this.finishNode(classBody, "ClassBody"); this.exitClassBody(); return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") }; pp$8.parseClassElement = function(constructorAllowsSuper) { if (this.eat(types$1.semi)) { return null } var ecmaVersion = this.options.ecmaVersion; var node = this.startNode(); var keyName = ""; var isGenerator = false; var isAsync = false; var kind = "method"; var isStatic = false; if (this.eatContextual("static")) { if (ecmaVersion >= 13 && this.eat(types$1.braceL)) { this.parseClassStaticBlock(node); return node } if (this.isClassElementNameStart() || this.type === types$1.star) { isStatic = true; } else { keyName = "static"; } } node.static = isStatic; if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) { isAsync = true; } else { keyName = "async"; } } if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) { isGenerator = true; } if (!keyName && !isAsync && !isGenerator) { var lastValue = this.value; if (this.eatContextual("get") || this.eatContextual("set")) { if (this.isClassElementNameStart()) { kind = lastValue; } else { keyName = lastValue; } } } if (keyName) { node.computed = false; node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); node.key.name = keyName; this.finishNode(node.key, "Identifier"); } else { this.parseClassElementName(node); } if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) { var isConstructor = !node.static && checkKeyName(node, "constructor"); var allowsDirectSuper = isConstructor && constructorAllowsSuper; if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } node.kind = isConstructor ? "constructor" : kind; this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); } else { this.parseClassField(node); } return node }; pp$8.isClassElementNameStart = function() { return ( this.type === types$1.name || this.type === types$1.privateId || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword ) }; pp$8.parseClassElementName = function(element) { if (this.type === types$1.privateId) { if (this.value === "constructor") { this.raise(this.start, "Classes can't have an element named '#constructor'"); } element.computed = false; element.key = this.parsePrivateIdent(); } else { this.parsePropertyName(element); } }; pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { var key = method.key; if (method.kind === "constructor") { if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } } else if (method.static && checkKeyName(method, "prototype")) { this.raise(key.start, "Classes may not have a static property named prototype"); } var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); if (method.kind === "get" && value.params.length !== 0) { this.raiseRecoverable(value.start, "getter should have no params"); } if (method.kind === "set" && value.params.length !== 1) { this.raiseRecoverable(value.start, "setter should have exactly one param"); } if (method.kind === "set" && value.params[0].type === "RestElement") { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } return this.finishNode(method, "MethodDefinition") }; pp$8.parseClassField = function(field) { if (checkKeyName(field, "constructor")) { this.raise(field.key.start, "Classes can't have a field named 'constructor'"); } else if (field.static && checkKeyName(field, "prototype")) { this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); } if (this.eat(types$1.eq)) { var scope = this.currentThisScope(); var inClassFieldInit = scope.inClassFieldInit; scope.inClassFieldInit = true; field.value = this.parseMaybeAssign(); scope.inClassFieldInit = inClassFieldInit; } else { field.value = null; } this.semicolon(); return this.finishNode(field, "PropertyDefinition") }; pp$8.parseClassStaticBlock = function(node) { node.body = []; var oldLabels = this.labels; this.labels = []; this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); while (this.type !== types$1.braceR) { var stmt = this.parseStatement(null); node.body.push(stmt); } this.next(); this.exitScope(); this.labels = oldLabels; return this.finishNode(node, "StaticBlock") }; pp$8.parseClassId = function(node, isStatement) { if (this.type === types$1.name) { node.id = this.parseIdent(); if (isStatement) { this.checkLValSimple(node.id, BIND_LEXICAL, false); } } else { if (isStatement === true) { this.unexpected(); } node.id = null; } }; pp$8.parseClassSuper = function(node) { node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null; }; pp$8.enterClassBody = function() { var element = {declared: Object.create(null), used: []}; this.privateNameStack.push(element); return element.declared }; pp$8.exitClassBody = function() { var ref = this.privateNameStack.pop(); var declared = ref.declared; var used = ref.used; if (!this.options.checkPrivateFields) { return } var len = this.privateNameStack.length; var parent = len === 0 ? null : this.privateNameStack[len - 1]; for (var i = 0; i < used.length; ++i) { var id = used[i]; if (!hasOwn(declared, id.name)) { if (parent) { parent.used.push(id); } else { this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); } } } }; function isPrivateNameConflicted(privateNameMap, element) { var name = element.key.name; var curr = privateNameMap[name]; var next = "true"; if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { next = (element.static ? "s" : "i") + element.kind; } if ( curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget" ) { privateNameMap[name] = "true"; return false } else if (!curr) { privateNameMap[name] = next; return false } else { return true } } function checkKeyName(node, name) { var computed = node.computed; var key = node.key; return !computed && ( key.type === "Identifier" && key.name === name || key.type === "Literal" && key.value === name ) } pp$8.parseExportAllDeclaration = function(node, exports) { if (this.options.ecmaVersion >= 11) { if (this.eatContextual("as")) { node.exported = this.parseModuleExportName(); this.checkExport(exports, node.exported, this.lastTokStart); } else { node.exported = null; } } this.expectContextual("from"); if (this.type !== types$1.string) { this.unexpected(); } node.source = this.parseExprAtom(); if (this.options.ecmaVersion >= 16) { node.attributes = this.parseWithClause(); } this.semicolon(); return this.finishNode(node, "ExportAllDeclaration") }; pp$8.parseExport = function(node, exports) { this.next(); if (this.eat(types$1.star)) { return this.parseExportAllDeclaration(node, exports) } if (this.eat(types$1._default)) { this.checkExport(exports, "default", this.lastTokStart); node.declaration = this.parseExportDefaultDeclaration(); return this.finishNode(node, "ExportDefaultDeclaration") } if (this.shouldParseExportStatement()) { node.declaration = this.parseExportDeclaration(node); if (node.declaration.type === "VariableDeclaration") { this.checkVariableExport(exports, node.declaration.declarations); } else { this.checkExport(exports, node.declaration.id, node.declaration.id.start); } node.specifiers = []; node.source = null; } else { node.declaration = null; node.specifiers = this.parseExportSpecifiers(exports); if (this.eatContextual("from")) { if (this.type !== types$1.string) { this.unexpected(); } node.source = this.parseExprAtom(); if (this.options.ecmaVersion >= 16) { node.attributes = this.parseWithClause(); } } else { for (var i = 0, list = node.specifiers; i < list.length; i += 1) { var spec = list[i]; this.checkUnreserved(spec.local); this.checkLocalExport(spec.local); if (spec.local.type === "Literal") { this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); } } node.source = null; } this.semicolon(); } return this.finishNode(node, "ExportNamedDeclaration") }; pp$8.parseExportDeclaration = function(node) { return this.parseStatement(null) }; pp$8.parseExportDefaultDeclaration = function() { var isAsync; if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) { var fNode = this.startNode(); this.next(); if (isAsync) { this.next(); } return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync) } else if (this.type === types$1._class) { var cNode = this.startNode(); return this.parseClass(cNode, "nullableID") } else { var declaration = this.parseMaybeAssign(); this.semicolon(); return declaration } }; pp$8.checkExport = function(exports, name, pos) { if (!exports) { return } if (typeof name !== "string") { name = name.type === "Identifier" ? name.name : name.value; } if (hasOwn(exports, name)) { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } exports[name] = true; }; pp$8.checkPatternExport = function(exports, pat) { var type = pat.type; if (type === "Identifier") { this.checkExport(exports, pat, pat.start); } else if (type === "ObjectPattern") { for (var i = 0, list = pat.properties; i < list.length; i += 1) { var prop = list[i]; this.checkPatternExport(exports, prop); } } else if (type === "ArrayPattern") { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { var elt = list$1[i$1]; if (elt) { this.checkPatternExport(exports, elt); } } } else if (type === "Property") { this.checkPatternExport(exports, pat.value); } else if (type === "AssignmentPattern") { this.checkPatternExport(exports, pat.left); } else if (type === "RestElement") { this.checkPatternExport(exports, pat.argument); } }; pp$8.checkVariableExport = function(exports, decls) { if (!exports) { return } for (var i = 0, list = decls; i < list.length; i += 1) { var decl = list[i]; this.checkPatternExport(exports, decl.id); } }; pp$8.shouldParseExportStatement = function() { return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction() }; pp$8.parseExportSpecifier = function(exports) { var node = this.startNode(); node.local = this.parseModuleExportName(); node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; this.checkExport( exports, node.exported, node.exported.start ); return this.finishNode(node, "ExportSpecifier") }; pp$8.parseExportSpecifiers = function(exports) { var nodes = [], first = true; this.expect(types$1.braceL); while (!this.eat(types$1.braceR)) { if (!first) { this.expect(types$1.comma); if (this.afterTrailingComma(types$1.braceR)) { break } } else { first = false; } nodes.push(this.parseExportSpecifier(exports)); } return nodes }; pp$8.parseImport = function(node) { this.next(); if (this.type === types$1.string) { node.specifiers = empty$1; node.source = this.parseExprAtom(); } else { node.specifiers = this.parseImportSpecifiers(); this.expectContextual("from"); node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected(); } if (this.options.ecmaVersion >= 16) { node.attributes = this.parseWithClause(); } this.semicolon(); return this.finishNode(node, "ImportDeclaration") }; pp$8.parseImportSpecifier = function() { var node = this.startNode(); node.imported = this.parseModuleExportName(); if (this.eatContextual("as")) { node.local = this.parseIdent(); } else { this.checkUnreserved(node.imported); node.local = node.imported; } this.checkLValSimple(node.local, BIND_LEXICAL); return this.finishNode(node, "ImportSpecifier") }; pp$8.parseImportDefaultSpecifier = function() { var node = this.startNode(); node.local = this.parseIdent(); this.checkLValSimple(node.local, BIND_LEXICAL); return this.finishNode(node, "ImportDefaultSpecifier") }; pp$8.parseImportNamespaceSpecifier = function() { var node = this.startNode(); this.next(); this.expectContextual("as"); node.local = this.parseIdent(); this.checkLValSimple(node.local, BIND_LEXICAL); return this.finishNode(node, "ImportNamespaceSpecifier") }; pp$8.parseImportSpecifiers = function() { var nodes = [], first = true; if (this.type === types$1.name) { nodes.push(this.parseImportDefaultSpecifier()); if (!this.eat(types$1.comma)) { return nodes } } if (this.type === types$1.star) { nodes.push(this.parseImportNamespaceSpecifier()); return nodes } this.expect(types$1.braceL); while (!this.eat(types$1.braceR)) { if (!first) { this.expect(types$1.comma); if (this.afterTrailingComma(types$1.braceR)) { break } } else { first = false; } nodes.push(this.parseImportSpecifier()); } return nodes }; pp$8.parseWithClause = function() { var nodes = []; if (!this.eat(types$1._with)) { return nodes } this.expect(types$1.braceL); var attributeKeys = {}; var first = true; while (!this.eat(types$1.braceR)) { if (!first) { this.expect(types$1.comma); if (this.afterTrailingComma(types$1.braceR)) { break } } else { first = false; } var attr = this.parseImportAttribute(); var keyName = attr.key.type === "Identifier" ? attr.key.name : attr.key.value; if (hasOwn(attributeKeys, keyName)) { this.raiseRecoverable(attr.key.start, "Duplicate attribute key '" + keyName + "'"); } attributeKeys[keyName] = true; nodes.push(attr); } return nodes }; pp$8.parseImportAttribute = function() { var node = this.startNode(); node.key = this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never"); this.expect(types$1.colon); if (this.type !== types$1.string) { this.unexpected(); } node.value = this.parseExprAtom(); return this.finishNode(node, "ImportAttribute") }; pp$8.parseModuleExportName = function() { if (this.options.ecmaVersion >= 13 && this.type === types$1.string) { var stringLiteral = this.parseLiteral(this.value); if (loneSurrogate.test(stringLiteral.value)) { this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); } return stringLiteral } return this.parseIdent(true) }; pp$8.adaptDirectivePrologue = function(statements) { for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { statements[i].directive = statements[i].expression.raw.slice(1, -1); } }; pp$8.isDirectiveCandidate = function(statement) { return ( this.options.ecmaVersion >= 5 && statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && (this.input[statement.start] === "\"" || this.input[statement.start] === "'") ) }; var pp$7 = Parser.prototype; pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) { if (this.options.ecmaVersion >= 6 && node) { switch (node.type) { case "Identifier": if (this.inAsync && node.name === "await") { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } break case "ObjectPattern": case "ArrayPattern": case "AssignmentPattern": case "RestElement": break case "ObjectExpression": node.type = "ObjectPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } for (var i = 0, list = node.properties; i < list.length; i += 1) { var prop = list[i]; this.toAssignable(prop, isBinding); if ( prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") ) { this.raise(prop.argument.start, "Unexpected token"); } } break case "Property": if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } this.toAssignable(node.value, isBinding); break case "ArrayExpression": node.type = "ArrayPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } this.toAssignableList(node.elements, isBinding); break case "SpreadElement": node.type = "RestElement"; this.toAssignable(node.argument, isBinding); if (node.argument.type === "AssignmentPattern") { this.raise(node.argument.start, "Rest elements cannot have a default value"); } break case "AssignmentExpression": if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } node.type = "AssignmentPattern"; delete node.operator; this.toAssignable(node.left, isBinding); break case "ParenthesizedExpression": this.toAssignable(node.expression, isBinding, refDestructuringErrors); break case "ChainExpression": this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); break case "MemberExpression": if (!isBinding) { break } default: this.raise(node.start, "Assigning to rvalue"); } } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } return node }; pp$7.toAssignableList = function(exprList, isBinding) { var end = exprList.length; for (var i = 0; i < end; i++) { var elt = exprList[i]; if (elt) { this.toAssignable(elt, isBinding); } } if (end) { var last = exprList[end - 1]; if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") { this.unexpected(last.argument.start); } } return exprList }; pp$7.parseSpread = function(refDestructuringErrors) { var node = this.startNode(); this.next(); node.argument = this.parseMaybeAssign(false, refDestructuringErrors); return this.finishNode(node, "SpreadElement") }; pp$7.parseRestBinding = function() { var node = this.startNode(); this.next(); if (this.options.ecmaVersion === 6 && this.type !== types$1.name) { this.unexpected(); } node.argument = this.parseBindingAtom(); return this.finishNode(node, "RestElement") }; pp$7.parseBindingAtom = function() { if (this.options.ecmaVersion >= 6) { switch (this.type) { case types$1.bracketL: var node = this.startNode(); this.next(); node.elements = this.parseBindingList(types$1.bracketR, true, true); return this.finishNode(node, "ArrayPattern") case types$1.braceL: return this.parseObj(true) } } return this.parseIdent() }; pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) { var elts = [], first = true; while (!this.eat(close)) { if (first) { first = false; } else { this.expect(types$1.comma); } if (allowEmpty && this.type === types$1.comma) { elts.push(null); } else if (allowTrailingComma && this.afterTrailingComma(close)) { break } else if (this.type === types$1.ellipsis) { var rest = this.parseRestBinding(); this.parseBindingListItem(rest); elts.push(rest); if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); } this.expect(close); break } else { elts.push(this.parseAssignableListItem(allowModifiers)); } } return elts }; pp$7.parseAssignableListItem = function(allowModifiers) { var elem = this.parseMaybeDefault(this.start, this.startLoc); this.parseBindingListItem(elem); return elem }; pp$7.parseBindingListItem = function(param) { return param }; pp$7.parseMaybeDefault = function(startPos, startLoc, left) { left = left || this.parseBindingAtom(); if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left } var node = this.startNodeAt(startPos, startLoc); node.left = left; node.right = this.parseMaybeAssign(); return this.finishNode(node, "AssignmentPattern") }; pp$7.checkLValSimple = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE; var isBind = bindingType !== BIND_NONE; switch (expr.type) { case "Identifier": if (this.strict && this.reservedWordsStrictBind.test(expr.name)) { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } if (isBind) { if (bindingType === BIND_LEXICAL && expr.name === "let") { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } if (checkClashes) { if (hasOwn(checkClashes, expr.name)) { this.raiseRecoverable(expr.start, "Argument name clash"); } checkClashes[expr.name] = true; } if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } } break case "ChainExpression": this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); break case "MemberExpression": if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } break case "ParenthesizedExpression": if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } return this.checkLValSimple(expr.expression, bindingType, checkClashes) default: this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); } }; pp$7.checkLValPattern = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE; switch (expr.type) { case "ObjectPattern": for (var i = 0, list = expr.properties; i < list.length; i += 1) { var prop = list[i]; this.checkLValInnerPattern(prop, bindingType, checkClashes); } break case "ArrayPattern": for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { var elem = list$1[i$1]; if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } } break default: this.checkLValSimple(expr, bindingType, checkClashes); } }; pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE; switch (expr.type) { case "Property": this.checkLValInnerPattern(expr.value, bindingType, checkClashes); break case "AssignmentPattern": this.checkLValPattern(expr.left, bindingType, checkClashes); break case "RestElement": this.checkLValPattern(expr.argument, bindingType, checkClashes); break default: this.checkLValPattern(expr, bindingType, checkClashes); } }; var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override; this.generator = !!generator; }; var types = { b_stat: new TokContext("{", false), b_expr: new TokContext("{", true), b_tmpl: new TokContext("${", false), p_stat: new TokContext("(", false), p_expr: new TokContext("(", true), q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), f_stat: new TokContext("function", false), f_expr: new TokContext("function", true), f_expr_gen: new TokContext("function", true, false, null, true), f_gen: new TokContext("function", false, false, null, true) }; var pp$6 = Parser.prototype; pp$6.initialContext = function() { return [types.b_stat] }; pp$6.curContext = function() { return this.context[this.context.length - 1] }; pp$6.braceIsBlock = function(prevType) { var parent = this.curContext(); if (parent === types.f_expr || parent === types.f_stat) { return true } if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr)) { return !parent.isExpr } if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) { return true } if (prevType === types$1.braceL) { return parent === types.b_stat } if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) { return false } return !this.exprAllowed }; pp$6.inGeneratorContext = function() { for (var i = this.context.length - 1; i >= 1; i--) { var context = this.context[i]; if (context.token === "function") { return context.generator } } return false }; pp$6.updateContext = function(prevType) { var update, type = this.type; if (type.keyword && prevType === types$1.dot) { this.exprAllowed = false; } else if (update = type.updateContext) { update.call(this, prevType); } else { this.exprAllowed = type.beforeExpr; } }; pp$6.overrideContext = function(tokenCtx) { if (this.curContext() !== tokenCtx) { this.context[this.context.length - 1] = tokenCtx; } }; types$1.parenR.updateContext = types$1.braceR.updateContext = function() { if (this.context.length === 1) { this.exprAllowed = true; return } var out = this.context.pop(); if (out === types.b_stat && this.curContext().token === "function") { out = this.context.pop(); } this.exprAllowed = !out.isExpr; }; types$1.braceL.updateContext = function(prevType) { this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr); this.exprAllowed = true; }; types$1.dollarBraceL.updateContext = function() { this.context.push(types.b_tmpl); this.exprAllowed = true; }; types$1.parenL.updateContext = function(prevType) { var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while; this.context.push(statementParens ? types.p_stat : types.p_expr); this.exprAllowed = true; }; types$1.incDec.updateContext = function() { }; types$1._function.updateContext = types$1._class.updateContext = function(prevType) { if (prevType.beforeExpr && prevType !== types$1._else && !(prevType === types$1.semi && this.curContext() !== types.p_stat) && !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat)) { this.context.push(types.f_expr); } else { this.context.push(types.f_stat); } this.exprAllowed = false; }; types$1.colon.updateContext = function() { if (this.curContext().token === "function") { this.context.pop(); } this.exprAllowed = true; }; types$1.backQuote.updateContext = function() { if (this.curContext() === types.q_tmpl) { this.context.pop(); } else { this.context.push(types.q_tmpl); } this.exprAllowed = false; }; types$1.star.updateContext = function(prevType) { if (prevType === types$1._function) { var index = this.context.length - 1; if (this.context[index] === types.f_expr) { this.context[index] = types.f_expr_gen; } else { this.context[index] = types.f_gen; } } this.exprAllowed = true; }; types$1.name.updateContext = function(prevType) { var allowed = false; if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) { if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) { allowed = true; } } this.exprAllowed = allowed; }; var pp$5 = Parser.prototype; pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) { if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") { return } if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) { return } var key = prop.key; var name; switch (key.type) { case "Identifier": name = key.name; break case "Literal": name = String(key.value); break default: return } var kind = prop.kind; if (this.options.ecmaVersion >= 6) { if (name === "__proto__" && kind === "init") { if (propHash.proto) { if (refDestructuringErrors) { if (refDestructuringErrors.doubleProto < 0) { refDestructuringErrors.doubleProto = key.start; } } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } } propHash.proto = true; } return } name = "$" + name; var other = propHash[name]; if (other) { var redefinition; if (kind === "init") { redefinition = this.strict && other.init || other.get || other.set; } else { redefinition = other.init || other[kind]; } if (redefinition) { this.raiseRecoverable(key.start, "Redefinition of property"); } } else { other = propHash[name] = { init: false, get: false, set: false }; } other[kind] = true; }; pp$5.parseExpression = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); if (this.type === types$1.comma) { var node = this.startNodeAt(startPos, startLoc); node.expressions = [expr]; while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } return this.finishNode(node, "SequenceExpression") } return expr }; pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { if (this.isContextual("yield")) { if (this.inGenerator) { return this.parseYield(forInit) } else { this.exprAllowed = false; } } var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; if (refDestructuringErrors) { oldParenAssign = refDestructuringErrors.parenthesizedAssign; oldTrailingComma = refDestructuringErrors.trailingComma; oldDoubleProto = refDestructuringErrors.doubleProto; refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; } else { refDestructuringErrors = new DestructuringErrors; ownDestructuringErrors = true; } var startPos = this.start, startLoc = this.startLoc; if (this.type === types$1.parenL || this.type === types$1.name) { this.potentialArrowAt = this.start; this.potentialArrowInForAwait = forInit === "await"; } var left = this.parseMaybeConditional(forInit, refDestructuringErrors); if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } if (this.type.isAssign) { var node = this.startNodeAt(startPos, startLoc); node.operator = this.value; if (this.type === types$1.eq) { left = this.toAssignable(left, false, refDestructuringErrors); } if (!ownDestructuringErrors) { refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; } if (refDestructuringErrors.shorthandAssign >= left.start) { refDestructuringErrors.shorthandAssign = -1; } if (this.type === types$1.eq) { this.checkLValPattern(left); } else { this.checkLValSimple(left); } node.left = left; this.next(); node.right = this.parseMaybeAssign(forInit); if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; } return this.finishNode(node, "AssignmentExpression") } else { if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } } if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } return left }; pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprOps(forInit, refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } if (this.eat(types$1.question)) { var node = this.startNodeAt(startPos, startLoc); node.test = expr; node.consequent = this.parseMaybeAssign(); this.expect(types$1.colon); node.alternate = this.parseMaybeAssign(forInit); return this.finishNode(node, "ConditionalExpression") } return expr }; pp$5.parseExprOps = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) }; pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { var prec = this.type.binop; if (prec != null && (!forInit || this.type !== types$1._in)) { if (prec > minPrec) { var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND; var coalesce = this.type === types$1.coalesce; if (coalesce) { prec = types$1.logicalAND.binop; } var op = this.value; this.next(); var startPos = this.start, startLoc = this.startLoc; var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) { this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); } return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) } } return left }; pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) { if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); } var node = this.startNodeAt(startPos, startLoc); node.left = left; node.operator = op; node.right = right; return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") }; pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { var startPos = this.start, startLoc = this.startLoc, expr; if (this.isContextual("await") && this.canAwait) { expr = this.parseAwait(forInit); sawUnary = true; } else if (this.type.prefix) { var node = this.startNode(), update = this.type === types$1.incDec; node.operator = this.value; node.prefix = true; this.next(); node.argument = this.parseMaybeUnary(null, true, update, forInit); this.checkExpressionErrors(refDestructuringErrors, true); if (update) { this.checkLValSimple(node.argument); } else if (this.strict && node.operator === "delete" && isLocalVariableAccess(node.argument)) { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } else { sawUnary = true; } expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); } else if (!sawUnary && this.type === types$1.privateId) { if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { this.unexpected(); } expr = this.parsePrivateIdent(); if (this.type !== types$1._in) { this.unexpected(); } } else { expr = this.parseExprSubscripts(refDestructuringErrors, forInit); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } while (this.type.postfix && !this.canInsertSemicolon()) { var node$1 = this.startNodeAt(startPos, startLoc); node$1.operator = this.value; node$1.prefix = false; node$1.argument = expr; this.checkLValSimple(expr); this.next(); expr = this.finishNode(node$1, "UpdateExpression"); } } if (!incDec && this.eat(types$1.starstar)) { if (sawUnary) { this.unexpected(this.lastTokStart); } else { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) } } else { return expr } }; function isLocalVariableAccess(node) { return ( node.type === "Identifier" || node.type === "ParenthesizedExpression" && isLocalVariableAccess(node.expression) ) } function isPrivateFieldAccess(node) { return ( node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) || node.type === "ParenthesizedExpression" && isPrivateFieldAccess(node.expression) ) } pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprAtom(refDestructuringErrors, forInit); if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") { return expr } var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); if (refDestructuringErrors && result.type === "MemberExpression") { if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } } return result }; pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.potentialArrowAt === base.start; var optionalChained = false; while (true) { var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); if (element.optional) { optionalChained = true; } if (element === base || element.type === "ArrowFunctionExpression") { if (optionalChained) { var chainNode = this.startNodeAt(startPos, startLoc); chainNode.expression = element; element = this.finishNode(chainNode, "ChainExpression"); } return element } base = element; } }; pp$5.shouldParseAsyncArrow = function() { return !this.canInsertSemicolon() && this.eat(types$1.arrow) }; pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit) }; pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { var optionalSupported = this.options.ecmaVersion >= 11; var optional = optionalSupported && this.eat(types$1.questionDot); if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } var computed = this.eat(types$1.bracketL); if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) { var node = this.startNodeAt(startPos, startLoc); node.object = base; if (computed) { node.property = this.parseExpression(); this.expect(types$1.bracketR); } else if (this.type === types$1.privateId && base.type !== "Super") { node.property = this.parsePrivateIdent(); } else { node.property = this.parseIdent(this.options.allowReserved !== "never"); } node.computed = !!computed; if (optionalSupported) { node.optional = optional; } base = this.finishNode(node, "MemberExpression"); } else if (!noCalls && this.eat(types$1.parenL)) { var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); if (this.awaitIdentPos > 0) { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit) } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; var node$1 = this.startNodeAt(startPos, startLoc); node$1.callee = base; node$1.arguments = exprList; if (optionalSupported) { node$1.optional = optional; } base = this.finishNode(node$1, "CallExpression"); } else if (this.type === types$1.backQuote) { if (optional || optionalChained) { this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); } var node$2 = this.startNodeAt(startPos, startLoc); node$2.tag = base; node$2.quasi = this.parseTemplate({isTagged: true}); base = this.finishNode(node$2, "TaggedTemplateExpression"); } return base }; pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) { if (this.type === types$1.slash) { this.readRegexp(); } var node, canBeArrow = this.potentialArrowAt === this.start; switch (this.type) { case types$1._super: if (!this.allowSuper) { this.raise(this.start, "'super' keyword outside a method"); } node = this.startNode(); this.next(); if (this.type === types$1.parenL && !this.allowDirectSuper) { this.raise(node.start, "super() call outside constructor of a subclass"); } if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) { this.unexpected(); } return this.finishNode(node, "Super") case types$1._this: node = this.startNode(); this.next(); return this.finishNode(node, "ThisExpression") case types$1.name: var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; var id = this.parseIdent(false); if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) { this.overrideContext(types.f_expr); return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit) } if (canBeArrow && !this.canInsertSemicolon()) { if (this.eat(types$1.arrow)) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) } if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { id = this.parseIdent(false); if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) { this.unexpected(); } return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit) } } return id case types$1.regexp: var value = this.value; node = this.parseLiteral(value.value); node.regex = {pattern: value.pattern, flags: value.flags}; return node case types$1.num: case types$1.string: return this.parseLiteral(this.value) case types$1._null: case types$1._true: case types$1._false: node = this.startNode(); node.value = this.type === types$1._null ? null : this.type === types$1._true; node.raw = this.type.keyword; this.next(); return this.finishNode(node, "Literal") case types$1.parenL: var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); if (refDestructuringErrors) { if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) { refDestructuringErrors.parenthesizedAssign = start; } if (refDestructuringErrors.parenthesizedBind < 0) { refDestructuringErrors.parenthesizedBind = start; } } return expr case types$1.bracketL: node = this.startNode(); this.next(); node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors); return this.finishNode(node, "ArrayExpression") case types$1.braceL: this.overrideContext(types.b_expr); return this.parseObj(false, refDestructuringErrors) case types$1._function: node = this.startNode(); this.next(); return this.parseFunction(node, 0) case types$1._class: return this.parseClass(this.startNode(), false) case types$1._new: return this.parseNew() case types$1.backQuote: return this.parseTemplate() case types$1._import: if (this.options.ecmaVersion >= 11) { return this.parseExprImport(forNew) } else { return this.unexpected() } default: return this.parseExprAtomDefault() } }; pp$5.parseExprAtomDefault = function() { this.unexpected(); }; pp$5.parseExprImport = function(forNew) { var node = this.startNode(); if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } this.next(); if (this.type === types$1.parenL && !forNew) { return this.parseDynamicImport(node) } else if (this.type === types$1.dot) { var meta = this.startNodeAt(node.start, node.loc && node.loc.start); meta.name = "import"; node.meta = this.finishNode(meta, "Identifier"); return this.parseImportMeta(node) } else { this.unexpected(); } }; pp$5.parseDynamicImport = function(node) { this.next(); node.source = this.parseMaybeAssign(); if (this.options.ecmaVersion >= 16) { if (!this.eat(types$1.parenR)) { this.expect(types$1.comma); if (!this.afterTrailingComma(types$1.parenR)) { node.options = this.parseMaybeAssign(); if (!this.eat(types$1.parenR)) { this.expect(types$1.comma); if (!this.afterTrailingComma(types$1.parenR)) { this.unexpected(); } } } else { node.options = null; } } else { node.options = null; } } else { if (!this.eat(types$1.parenR)) { var errorPos = this.start; if (this.eat(types$1.comma) && this.eat(types$1.parenR)) { this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); } else { this.unexpected(errorPos); } } } return this.finishNode(node, "ImportExpression") }; pp$5.parseImportMeta = function(node) { this.next(); var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "meta") { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } if (containsEsc) { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } return this.finishNode(node, "MetaProperty") }; pp$5.parseLiteral = function(value) { var node = this.startNode(); node.value = value; node.raw = this.input.slice(this.start, this.end); if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } this.next(); return this.finishNode(node, "Literal") }; pp$5.parseParenExpression = function() { this.expect(types$1.parenL); var val = this.parseExpression(); this.expect(types$1.parenR); return val }; pp$5.shouldParseArrow = function(exprList) { return !this.canInsertSemicolon() }; pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; if (this.options.ecmaVersion >= 6) { this.next(); var innerStartPos = this.start, innerStartLoc = this.startLoc; var exprList = [], first = true, lastIsComma = false; var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; this.yieldPos = 0; this.awaitPos = 0; while (this.type !== types$1.parenR) { first ? first = false : this.expect(types$1.comma); if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) { lastIsComma = true; break } else if (this.type === types$1.ellipsis) { spreadStart = this.start; exprList.push(this.parseParenItem(this.parseRestBinding())); if (this.type === types$1.comma) { this.raiseRecoverable( this.start, "Comma is not permitted after the rest element" ); } break } else { exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); } } var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; this.expect(types$1.parenR); if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; return this.parseParenArrowList(startPos, startLoc, exprList, forInit) } if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } if (spreadStart) { this.unexpected(spreadStart); } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; if (exprList.length > 1) { val = this.startNodeAt(innerStartPos, innerStartLoc); val.expressions = exprList; this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); } else { val = exprList[0]; } } else { val = this.parseParenExpression(); } if (this.options.preserveParens) { var par = this.startNodeAt(startPos, startLoc); par.expression = val; return this.finishNode(par, "ParenthesizedExpression") } else { return val } }; pp$5.parseParenItem = function(item) { return item }; pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit) }; var empty = []; pp$5.parseNew = function() { if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } var node = this.startNode(); this.next(); if (this.options.ecmaVersion >= 6 && this.type === types$1.dot) { var meta = this.startNodeAt(node.start, node.loc && node.loc.start); meta.name = "new"; node.meta = this.finishNode(meta, "Identifier"); this.next(); var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "target") { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } if (containsEsc) { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } if (!this.allowNewDotTarget) { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); } return this.finishNode(node, "MetaProperty") } var startPos = this.start, startLoc = this.startLoc; node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false); if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); } else { node.arguments = empty; } return this.finishNode(node, "NewExpression") }; pp$5.parseTemplateElement = function(ref) { var isTagged = ref.isTagged; var elem = this.startNode(); if (this.type === types$1.invalidTemplate) { if (!isTagged) { this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); } elem.value = { raw: this.value.replace(/\r\n?/g, "\n"), cooked: null }; } else { elem.value = { raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), cooked: this.value }; } this.next(); elem.tail = this.type === types$1.backQuote; return this.finishNode(elem, "TemplateElement") }; pp$5.parseTemplate = function(ref) { if ( ref === void 0 ) ref = {}; var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; var node = this.startNode(); this.next(); node.expressions = []; var curElt = this.parseTemplateElement({isTagged: isTagged}); node.quasis = [curElt]; while (!curElt.tail) { if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); } this.expect(types$1.dollarBraceL); node.expressions.push(this.parseExpression()); this.expect(types$1.braceR); node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); } this.next(); return this.finishNode(node, "TemplateLiteral") }; pp$5.isAsyncProp = function(prop) { return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }; pp$5.parseObj = function(isPattern, refDestructuringErrors) { var node = this.startNode(), first = true, propHash = {}; node.properties = []; this.next(); while (!this.eat(types$1.braceR)) { if (!first) { this.expect(types$1.comma); if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break } } else { first = false; } var prop = this.parseProperty(isPattern, refDestructuringErrors); if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } node.properties.push(prop); } return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") }; pp$5.parseProperty = function(isPattern, refDestructuringErrors) { var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) { if (isPattern) { prop.argument = this.parseIdent(false); if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); } return this.finishNode(prop, "RestElement") } prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this.start; } return this.finishNode(prop, "SpreadElement") } if (this.options.ecmaVersion >= 6) { prop.method = false; prop.shorthand = false; if (isPattern || refDestructuringErrors) { startPos = this.start; startLoc = this.startLoc; } if (!isPattern) { isGenerator = this.eat(types$1.star); } } var containsEsc = this.containsEsc; this.parsePropertyName(prop); if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { isAsync = true; isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star); this.parsePropertyName(prop); } else { isAsync = false; } this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); return this.finishNode(prop, "Property") }; pp$5.parseGetterSetter = function(prop) { prop.kind = prop.key.name; this.parsePropertyName(prop); prop.value = this.parseMethod(false); var paramCount = prop.kind === "get" ? 0 : 1; if (prop.value.params.length !== paramCount) { var start = prop.value.start; if (prop.kind === "get") { this.raiseRecoverable(start, "getter should have no params"); } else { this.raiseRecoverable(start, "setter should have exactly one param"); } } else { if (prop.kind === "set" && prop.value.params[0].type === "RestElement") { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } } }; pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { if ((isGenerator || isAsync) && this.type === types$1.colon) { this.unexpected(); } if (this.eat(types$1.colon)) { prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); prop.kind = "init"; } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) { if (isPattern) { this.unexpected(); } prop.kind = "init"; prop.method = true; prop.value = this.parseMethod(isGenerator, isAsync); } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) { if (isGenerator || isAsync) { this.unexpected(); } this.parseGetterSetter(prop); } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { if (isGenerator || isAsync) { this.unexpected(); } this.checkUnreserved(prop.key); if (prop.key.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = startPos; } prop.kind = "init"; if (isPattern) { prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); } else if (this.type === types$1.eq && refDestructuringErrors) { if (refDestructuringErrors.shorthandAssign < 0) { refDestructuringErrors.shorthandAssign = this.start; } prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); } else { prop.value = this.copyNode(prop.key); } prop.shorthand = true; } else { this.unexpected(); } }; pp$5.parsePropertyName = function(prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(types$1.bracketL)) { prop.computed = true; prop.key = this.parseMaybeAssign(); this.expect(types$1.bracketR); return prop.key } else { prop.computed = false; } } return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") }; pp$5.initFunction = function(node) { node.id = null; if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } if (this.options.ecmaVersion >= 8) { node.async = false; } }; pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.initFunction(node); if (this.options.ecmaVersion >= 6) { node.generator = isGenerator; } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); this.expect(types$1.parenL); node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); this.parseFunctionBody(node, false, true, false); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "FunctionExpression") }; pp$5.parseArrowExpression = function(node, params, isAsync, forInit) { var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); this.initFunction(node); if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; node.params = this.toAssignableList(params, true); this.parseFunctionBody(node, true, false, forInit); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "ArrowFunctionExpression") }; pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { var isExpression = isArrowFunction && this.type !== types$1.braceL; var oldStrict = this.strict, useStrict = false; if (isExpression) { node.body = this.parseMaybeAssign(forInit); node.expression = true; this.checkParams(node, false); } else { var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); if (!oldStrict || nonSimple) { useStrict = this.strictDirective(this.end); if (useStrict && nonSimple) { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } } var oldLabels = this.labels; this.labels = []; if (useStrict) { this.strict = true; } this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); node.expression = false; this.adaptDirectivePrologue(node.body.body); this.labels = oldLabels; } this.exitScope(); }; pp$5.isSimpleParamList = function(params) { for (var i = 0, list = params; i < list.length; i += 1) { var param = list[i]; if (param.type !== "Identifier") { return false } } return true }; pp$5.checkParams = function(node, allowDuplicates) { var nameHash = Object.create(null); for (var i = 0, list = node.params; i < list.length; i += 1) { var param = list[i]; this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); } }; pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { var elts = [], first = true; while (!this.eat(close)) { if (!first) { this.expect(types$1.comma); if (allowTrailingComma && this.afterTrailingComma(close)) { break } } else { first = false; } var elt = (void 0); if (allowEmpty && this.type === types$1.comma) { elt = null; } else if (this.type === types$1.ellipsis) { elt = this.parseSpread(refDestructuringErrors); if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this.start; } } else { elt = this.parseMaybeAssign(false, refDestructuringErrors); } elts.push(elt); } return elts }; pp$5.checkUnreserved = function(ref) { var start = ref.start; var end = ref.end; var name = ref.name; if (this.inGenerator && name === "yield") { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } if (this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } if (this.currentThisScope().inClassFieldInit && name === "arguments") { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } if (this.inClassStaticBlock && (name === "arguments" || name === "await")) { this.raise(start, ("Cannot use " + name + " in class static initialization block")); } if (this.keywords.test(name)) { this.raise(start, ("Unexpected keyword '" + name + "'")); } if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) { return } var re = this.strict ? this.reservedWordsStrict : this.reservedWords; if (re.test(name)) { if (!this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); } }; pp$5.parseIdent = function(liberal) { var node = this.parseIdentNode(); this.next(!!liberal); this.finishNode(node, "Identifier"); if (!liberal) { this.checkUnreserved(node); if (node.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = node.start; } } return node }; pp$5.parseIdentNode = function() { var node = this.startNode(); if (this.type === types$1.name) { node.name = this.value; } else if (this.type.keyword) { node.name = this.type.keyword; if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { this.context.pop(); } this.type = types$1.name; } else { this.unexpected(); } return node }; pp$5.parsePrivateIdent = function() { var node = this.startNode(); if (this.type === types$1.privateId) { node.name = this.value; } else { this.unexpected(); } this.next(); this.finishNode(node, "PrivateIdentifier"); if (this.options.checkPrivateFields) { if (this.privateNameStack.length === 0) { this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); } else { this.privateNameStack[this.privateNameStack.length - 1].used.push(node); } } return node }; pp$5.parseYield = function(forInit) { if (!this.yieldPos) { this.yieldPos = this.start; } var node = this.startNode(); this.next(); if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) { node.delegate = false; node.argument = null; } else { node.delegate = this.eat(types$1.star); node.argument = this.parseMaybeAssign(forInit); } return this.finishNode(node, "YieldExpression") }; pp$5.parseAwait = function(forInit) { if (!this.awaitPos) { this.awaitPos = this.start; } var node = this.startNode(); this.next(); node.argument = this.parseMaybeUnary(null, true, false, forInit); return this.finishNode(node, "AwaitExpression") }; var pp$4 = Parser.prototype; pp$4.raise = function(pos, message) { var loc = getLineInfo(this.input, pos); message += " (" + loc.line + ":" + loc.column + ")"; var err = new SyntaxError(message); err.pos = pos; err.loc = loc; err.raisedAt = this.pos; throw err }; pp$4.raiseRecoverable = pp$4.raise; pp$4.curPosition = function() { if (this.options.locations) { return new Position(this.curLine, this.pos - this.lineStart) } }; var pp$3 = Parser.prototype; var Scope = function Scope(flags) { this.flags = flags; this.var = []; this.lexical = []; this.functions = []; this.inClassFieldInit = false; }; pp$3.enterScope = function(flags) { this.scopeStack.push(new Scope(flags)); }; pp$3.exitScope = function() { this.scopeStack.pop(); }; pp$3.treatFunctionsAsVarInScope = function(scope) { return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) }; pp$3.declareName = function(name, bindingType, pos) { var redeclared = false; if (bindingType === BIND_LEXICAL) { var scope = this.currentScope(); redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; scope.lexical.push(name); if (this.inModule && (scope.flags & SCOPE_TOP)) { delete this.undefinedExports[name]; } } else if (bindingType === BIND_SIMPLE_CATCH) { var scope$1 = this.currentScope(); scope$1.lexical.push(name); } else if (bindingType === BIND_FUNCTION) { var scope$2 = this.currentScope(); if (this.treatFunctionsAsVar) { redeclared = scope$2.lexical.indexOf(name) > -1; } else { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } scope$2.functions.push(name); } else { for (var i = this.scopeStack.length - 1; i >= 0; --i) { var scope$3 = this.scopeStack[i]; if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { redeclared = true; break } scope$3.var.push(name); if (this.inModule && (scope$3.flags & SCOPE_TOP)) { delete this.undefinedExports[name]; } if (scope$3.flags & SCOPE_VAR) { break } } } if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } }; pp$3.checkLocalExport = function(id) { if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) { this.undefinedExports[id.name] = id; } }; pp$3.currentScope = function() { return this.scopeStack[this.scopeStack.length - 1] }; pp$3.currentVarScope = function() { for (var i = this.scopeStack.length - 1;; i--) { var scope = this.scopeStack[i]; if (scope.flags & SCOPE_VAR) { return scope } } }; pp$3.currentThisScope = function() { for (var i = this.scopeStack.length - 1;; i--) { var scope = this.scopeStack[i]; if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } } }; var Node = function Node(parser, pos, loc) { this.type = ""; this.start = pos; this.end = 0; if (parser.options.locations) { this.loc = new SourceLocation(parser, loc); } if (parser.options.directSourceFile) { this.sourceFile = parser.options.directSourceFile; } if (parser.options.ranges) { this.range = [pos, 0]; } }; var pp$2 = Parser.prototype; pp$2.startNode = function() { return new Node(this, this.start, this.startLoc) }; pp$2.startNodeAt = function(pos, loc) { return new Node(this, pos, loc) }; function finishNodeAt(node, type, pos, loc) { node.type = type; node.end = pos; if (this.options.locations) { node.loc.end = loc; } if (this.options.ranges) { node.range[1] = pos; } return node } pp$2.finishNode = function(node, type) { return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) }; pp$2.finishNodeAt = function(node, type, pos, loc) { return finishNodeAt.call(this, node, type, pos, loc) }; pp$2.copyNode = function(node) { var newNode = new Node(this, node.start, this.startLoc); for (var prop in node) { newNode[prop] = node[prop]; } return newNode }; var scriptValuesAddedInUnicode = "Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"; var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; var ecma11BinaryProperties = ecma10BinaryProperties; var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; var ecma13BinaryProperties = ecma12BinaryProperties; var ecma14BinaryProperties = ecma13BinaryProperties; var unicodeBinaryProperties = { 9: ecma9BinaryProperties, 10: ecma10BinaryProperties, 11: ecma11BinaryProperties, 12: ecma12BinaryProperties, 13: ecma13BinaryProperties, 14: ecma14BinaryProperties }; var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"; var unicodeBinaryPropertiesOfStrings = { 9: "", 10: "", 11: "", 12: "", 13: "", 14: ecma14BinaryPropertiesOfStrings }; var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; var ecma14ScriptValues = ecma13ScriptValues + " " + scriptValuesAddedInUnicode; var unicodeScriptValues = { 9: ecma9ScriptValues, 10: ecma10ScriptValues, 11: ecma11ScriptValues, 12: ecma12ScriptValues, 13: ecma13ScriptValues, 14: ecma14ScriptValues }; var data = {}; function buildUnicodeData(ecmaVersion) { var d = data[ecmaVersion] = { binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]), nonBinary: { General_Category: wordsRegexp(unicodeGeneralCategoryValues), Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) } }; d.nonBinary.Script_Extensions = d.nonBinary.Script; d.nonBinary.gc = d.nonBinary.General_Category; d.nonBinary.sc = d.nonBinary.Script; d.nonBinary.scx = d.nonBinary.Script_Extensions; } for (var i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) { var ecmaVersion = list[i]; buildUnicodeData(ecmaVersion); } var pp$1 = Parser.prototype; var BranchID = function BranchID(parent, base) { this.parent = parent; this.base = base || this; }; BranchID.prototype.separatedFrom = function separatedFrom (alt) { for (var self = this; self; self = self.parent) { for (var other = alt; other; other = other.parent) { if (self.base === other.base && self !== other) { return true } } } return false }; BranchID.prototype.sibling = function sibling () { return new BranchID(this.parent, this.base) }; var RegExpValidationState = function RegExpValidationState(parser) { this.parser = parser; this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : ""); this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion]; this.source = ""; this.flags = ""; this.start = 0; this.switchU = false; this.switchV = false; this.switchN = false; this.pos = 0; this.lastIntValue = 0; this.lastStringValue = ""; this.lastAssertionIsQuantifiable = false; this.numCapturingParens = 0; this.maxBackReference = 0; this.groupNames = Object.create(null); this.backReferenceNames = []; this.branchID = null; }; RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { var unicodeSets = flags.indexOf("v") !== -1; var unicode = flags.indexOf("u") !== -1; this.start = start | 0; this.source = pattern + ""; this.flags = flags; if (unicodeSets && this.parser.options.ecmaVersion >= 15) { this.switchU = true; this.switchV = true; this.switchN = true; } else { this.switchU = unicode && this.parser.options.ecmaVersion >= 6; this.switchV = false; this.switchN = unicode && this.parser.options.ecmaVersion >= 9; } }; RegExpValidationState.prototype.raise = function raise (message) { this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); }; RegExpValidationState.prototype.at = function at (i, forceU) { if ( forceU === void 0 ) forceU = false; var s = this.source; var l = s.length; if (i >= l) { return -1 } var c = s.charCodeAt(i); if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { return c } var next = s.charCodeAt(i + 1); return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c }; RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { if ( forceU === void 0 ) forceU = false; var s = this.source; var l = s.length; if (i >= l) { return l } var c = s.charCodeAt(i), next; if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { return i + 1 } return i + 2 }; RegExpValidationState.prototype.current = function current (forceU) { if ( forceU === void 0 ) forceU = false; return this.at(this.pos, forceU) }; RegExpValidationState.prototype.lookahead = function lookahead (forceU) { if ( forceU === void 0 ) forceU = false; return this.at(this.nextIndex(this.pos, forceU), forceU) }; RegExpValidationState.prototype.advance = function advance (forceU) { if ( forceU === void 0 ) forceU = false; this.pos = this.nextIndex(this.pos, forceU); }; RegExpValidationState.prototype.eat = function eat (ch, forceU) { if ( forceU === void 0 ) forceU = false; if (this.current(forceU) === ch) { this.advance(forceU); return true } return false }; RegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) { if ( forceU === void 0 ) forceU = false; var pos = this.pos; for (var i = 0, list = chs; i < list.length; i += 1) { var ch = list[i]; var current = this.at(pos, forceU); if (current === -1 || current !== ch) { return false } pos = this.nextIndex(pos, forceU); } this.pos = pos; return true }; pp$1.validateRegExpFlags = function(state) { var validFlags = state.validFlags; var flags = state.flags; var u = false; var v = false; for (var i = 0; i < flags.length; i++) { var flag = flags.charAt(i); if (validFlags.indexOf(flag) === -1) { this.raise(state.start, "Invalid regular expression flag"); } if (flags.indexOf(flag, i + 1) > -1) { this.raise(state.start, "Duplicate regular expression flag"); } if (flag === "u") { u = true; } if (flag === "v") { v = true; } } if (this.options.ecmaVersion >= 15 && u && v) { this.raise(state.start, "Invalid regular expression flag"); } }; function hasProp(obj) { for (var _ in obj) { return true } return false } pp$1.validateRegExpPattern = function(state) { this.regexp_pattern(state); if (!state.switchN && this.options.ecmaVersion >= 9 && hasProp(state.groupNames)) { state.switchN = true; this.regexp_pattern(state); } }; pp$1.regexp_pattern = function(state) { state.pos = 0; state.lastIntValue = 0; state.lastStringValue = ""; state.lastAssertionIsQuantifiable = false; state.numCapturingParens = 0; state.maxBackReference = 0; state.groupNames = Object.create(null); state.backReferenceNames.length = 0; state.branchID = null; this.regexp_disjunction(state); if (state.pos !== state.source.length) { if (state.eat(0x29 )) { state.raise("Unmatched ')'"); } if (state.eat(0x5D ) || state.eat(0x7D )) { state.raise("Lone quantifier brackets"); } } if (state.maxBackReference > state.numCapturingParens) { state.raise("Invalid escape"); } for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { var name = list[i]; if (!state.groupNames[name]) { state.raise("Invalid named capture referenced"); } } }; pp$1.regexp_disjunction = function(state) { var trackDisjunction = this.options.ecmaVersion >= 16; if (trackDisjunction) { state.branchID = new BranchID(state.branchID, null); } this.regexp_alternative(state); while (state.eat(0x7C )) { if (trackDisjunction) { state.branchID = state.branchID.sibling(); } this.regexp_alternative(state); } if (trackDisjunction) { state.branchID = state.branchID.parent; } if (this.regexp_eatQuantifier(state, true)) { state.raise("Nothing to repeat"); } if (state.eat(0x7B )) { state.raise("Lone quantifier brackets"); } }; pp$1.regexp_alternative = function(state) { while (state.pos < state.source.length && this.regexp_eatTerm(state)) {} }; pp$1.regexp_eatTerm = function(state) { if (this.regexp_eatAssertion(state)) { if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { if (state.switchU) { state.raise("Invalid quantifier"); } } return true } if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { this.regexp_eatQuantifier(state); return true } return false }; pp$1.regexp_eatAssertion = function(state) { var start = state.pos; state.lastAssertionIsQuantifiable = false; if (state.eat(0x5E ) || state.eat(0x24 )) { return true } if (state.eat(0x5C )) { if (state.eat(0x42 ) || state.eat(0x62 )) { return true } state.pos = start; } if (state.eat(0x28 ) && state.eat(0x3F )) { var lookbehind = false; if (this.options.ecmaVersion >= 9) { lookbehind = state.eat(0x3C ); } if (state.eat(0x3D ) || state.eat(0x21 )) { this.regexp_disjunction(state); if (!state.eat(0x29 )) { state.raise("Unterminated group"); } state.lastAssertionIsQuantifiable = !lookbehind; return true } } state.pos = start; return false }; pp$1.regexp_eatQuantifier = function(state, noError) { if ( noError === void 0 ) noError = false; if (this.regexp_eatQuantifierPrefix(state, noError)) { state.eat(0x3F ); return true } return false }; pp$1.regexp_eatQuantifierPrefix = function(state, noError) { return ( state.eat(0x2A ) || state.eat(0x2B ) || state.eat(0x3F ) || this.regexp_eatBracedQuantifier(state, noError) ) }; pp$1.regexp_eatBracedQuantifier = function(state, noError) { var start = state.pos; if (state.eat(0x7B )) { var min = 0, max = -1; if (this.regexp_eatDecimalDigits(state)) { min = state.lastIntValue; if (state.eat(0x2C ) && this.regexp_eatDecimalDigits(state)) { max = state.lastIntValue; } if (state.eat(0x7D )) { if (max !== -1 && max < min && !noError) { state.raise("numbers out of order in {} quantifier"); } return true } } if (state.switchU && !noError) { state.raise("Incomplete quantifier"); } state.pos = start; } return false }; pp$1.regexp_eatAtom = function(state) { return ( this.regexp_eatPatternCharacters(state) || state.eat(0x2E ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) ) }; pp$1.regexp_eatReverseSolidusAtomEscape = function(state) { var start = state.pos; if (state.eat(0x5C )) { if (this.regexp_eatAtomEscape(state)) { return true } state.pos = start; } return false }; pp$1.regexp_eatUncapturingGroup = function(state) { var start = state.pos; if (state.eat(0x28 )) { if (state.eat(0x3F )) { if (this.options.ecmaVersion >= 16) { var addModifiers = this.regexp_eatModifiers(state); var hasHyphen = state.eat(0x2D ); if (addModifiers || hasHyphen) { for (var i = 0; i < addModifiers.length; i++) { var modifier = addModifiers.charAt(i); if (addModifiers.indexOf(modifier, i + 1) > -1) { state.raise("Duplicate regular expression modifiers"); } } if (hasHyphen) { var removeModifiers = this.regexp_eatModifiers(state); if (!addModifiers && !removeModifiers && state.current() === 0x3A ) { state.raise("Invalid regular expression modifiers"); } for (var i$1 = 0; i$1 < removeModifiers.length; i$1++) { var modifier$1 = removeModifiers.charAt(i$1); if ( removeModifiers.indexOf(modifier$1, i$1 + 1) > -1 || addModifiers.indexOf(modifier$1) > -1 ) { state.raise("Duplicate regular expression modifiers"); } } } } } if (state.eat(0x3A )) { this.regexp_disjunction(state); if (state.eat(0x29 )) { return true } state.raise("Unterminated group"); } } state.pos = start; } return false }; pp$1.regexp_eatCapturingGroup = function(state) { if (state.eat(0x28 )) { if (this.options.ecmaVersion >= 9) { this.regexp_groupSpecifier(state); } else if (state.current() === 0x3F ) { state.raise("Invalid group"); } this.regexp_disjunction(state); if (state.eat(0x29 )) { state.numCapturingParens += 1; return true } state.raise("Unterminated group"); } return false }; pp$1.regexp_eatModifiers = function(state) { var modifiers = ""; var ch = 0; while ((ch = state.current()) !== -1 && isRegularExpressionModifier(ch)) { modifiers += codePointToString(ch); state.advance(); } return modifiers }; function isRegularExpressionModifier(ch) { return ch === 0x69 || ch === 0x6d || ch === 0x73 } pp$1.regexp_eatExtendedAtom = function(state) { return ( state.eat(0x2E ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state) ) }; pp$1.regexp_eatInvalidBracedQuantifier = function(state) { if (this.regexp_eatBracedQuantifier(state, true)) { state.raise("Nothing to repeat"); } return false }; pp$1.regexp_eatSyntaxCharacter = function(state) { var ch = state.current(); if (isSyntaxCharacter(ch)) { state.lastIntValue = ch; state.advance(); return true } return false }; function isSyntaxCharacter(ch) { return ( ch === 0x24 || ch >= 0x28 && ch <= 0x2B || ch === 0x2E || ch === 0x3F || ch >= 0x5B && ch <= 0x5E || ch >= 0x7B && ch <= 0x7D ) } pp$1.regexp_eatPatternCharacters = function(state) { var start = state.pos; var ch = 0; while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { state.advance(); } return state.pos !== start }; pp$1.regexp_eatExtendedPatternCharacter = function(state) { var ch = state.current(); if ( ch !== -1 && ch !== 0x24 && !(ch >= 0x28 && ch <= 0x2B ) && ch !== 0x2E && ch !== 0x3F && ch !== 0x5B && ch !== 0x5E && ch !== 0x7C ) { state.advance(); return true } return false }; pp$1.regexp_groupSpecifier = function(state) { if (state.eat(0x3F )) { if (!this.regexp_eatGroupName(state)) { state.raise("Invalid group"); } var trackDisjunction = this.options.ecmaVersion >= 16; var known = state.groupNames[state.lastStringValue]; if (known) { if (trackDisjunction) { for (var i = 0, list = known; i < list.length; i += 1) { var altID = list[i]; if (!altID.separatedFrom(state.branchID)) { state.raise("Duplicate capture group name"); } } } else { state.raise("Duplicate capture group name"); } } if (trackDisjunction) { (known || (state.groupNames[state.lastStringValue] = [])).push(state.branchID); } else { state.groupNames[state.lastStringValue] = true; } } }; pp$1.regexp_eatGroupName = function(state) { state.lastStringValue = ""; if (state.eat(0x3C )) { if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E )) { return true } state.raise("Invalid capture group name"); } return false }; pp$1.regexp_eatRegExpIdentifierName = function(state) { state.lastStringValue = ""; if (this.regexp_eatRegExpIdentifierStart(state)) { state.lastStringValue += codePointToString(state.lastIntValue); while (this.regexp_eatRegExpIdentifierPart(state)) { state.lastStringValue += codePointToString(state.lastIntValue); } return true } return false }; pp$1.regexp_eatRegExpIdentifierStart = function(state) { var start = state.pos; var forceU = this.options.ecmaVersion >= 11; var ch = state.current(forceU); state.advance(forceU); if (ch === 0x5C && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue; } if (isRegExpIdentifierStart(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierStart(ch) { return isIdentifierStart(ch, true) || ch === 0x24 || ch === 0x5F } pp$1.regexp_eatRegExpIdentifierPart = function(state) { var start = state.pos; var forceU = this.options.ecmaVersion >= 11; var ch = state.current(forceU); state.advance(forceU); if (ch === 0x5C && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue; } if (isRegExpIdentifierPart(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierPart(ch) { return isIdentifierChar(ch, true) || ch === 0x24 || ch === 0x5F || ch === 0x200C || ch === 0x200D } pp$1.regexp_eatAtomEscape = function(state) { if ( this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || (state.switchN && this.regexp_eatKGroupName(state)) ) { return true } if (state.switchU) { if (state.current() === 0x63 ) { state.raise("Invalid unicode escape"); } state.raise("Invalid escape"); } return false }; pp$1.regexp_eatBackReference = function(state) { var start = state.pos; if (this.regexp_eatDecimalEscape(state)) { var n = state.lastIntValue; if (state.switchU) { if (n > state.maxBackReference) { state.maxBackReference = n; } return true } if (n <= state.numCapturingParens) { return true } state.pos = start; } return false }; pp$1.regexp_eatKGroupName = function(state) { if (state.eat(0x6B )) { if (this.regexp_eatGroupName(state)) { state.backReferenceNames.push(state.lastStringValue); return true } state.raise("Invalid named reference"); } return false }; pp$1.regexp_eatCharacterEscape = function(state) { return ( this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || this.regexp_eatIdentityEscape(state) ) }; pp$1.regexp_eatCControlLetter = function(state) { var start = state.pos; if (state.eat(0x63 )) { if (this.regexp_eatControlLetter(state)) { return true } state.pos = start; } return false }; pp$1.regexp_eatZero = function(state) { if (state.current() === 0x30 && !isDecimalDigit(state.lookahead())) { state.lastIntValue = 0; state.advance(); return true } return false }; pp$1.regexp_eatControlEscape = function(state) { var ch = state.current(); if (ch === 0x74 ) { state.lastIntValue = 0x09; state.advance(); return true } if (ch === 0x6E ) { state.lastIntValue = 0x0A; state.advance(); return true } if (ch === 0x76 ) { state.lastIntValue = 0x0B; state.advance(); return true } if (ch === 0x66 ) { state.lastIntValue = 0x0C; state.advance(); return true } if (ch === 0x72 ) { state.lastIntValue = 0x0D; state.advance(); return true } return false }; pp$1.regexp_eatControlLetter = function(state) { var ch = state.current(); if (isControlLetter(ch)) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; function isControlLetter(ch) { return ( (ch >= 0x41 && ch <= 0x5A ) || (ch >= 0x61 && ch <= 0x7A ) ) } pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { if ( forceU === void 0 ) forceU = false; var start = state.pos; var switchU = forceU || state.switchU; if (state.eat(0x75 )) { if (this.regexp_eatFixedHexDigits(state, 4)) { var lead = state.lastIntValue; if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { var leadSurrogateEnd = state.pos; if (state.eat(0x5C ) && state.eat(0x75 ) && this.regexp_eatFixedHexDigits(state, 4)) { var trail = state.lastIntValue; if (trail >= 0xDC00 && trail <= 0xDFFF) { state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; return true } } state.pos = leadSurrogateEnd; state.lastIntValue = lead; } return true } if ( switchU && state.eat(0x7B ) && this.regexp_eatHexDigits(state) && state.eat(0x7D ) && isValidUnicode(state.lastIntValue) ) { return true } if (switchU) { state.raise("Invalid unicode escape"); } state.pos = start; } return false }; function isValidUnicode(ch) { return ch >= 0 && ch <= 0x10FFFF } pp$1.regexp_eatIdentityEscape = function(state) { if (state.switchU) { if (this.regexp_eatSyntaxCharacter(state)) { return true } if (state.eat(0x2F )) { state.lastIntValue = 0x2F; return true } return false } var ch = state.current(); if (ch !== 0x63 && (!state.switchN || ch !== 0x6B )) { state.lastIntValue = ch; state.advance(); return true } return false }; pp$1.regexp_eatDecimalEscape = function(state) { state.lastIntValue = 0; var ch = state.current(); if (ch >= 0x31 && ch <= 0x39 ) { do { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 ); state.advance(); } while ((ch = state.current()) >= 0x30 && ch <= 0x39 ) return true } return false }; var CharSetNone = 0; var CharSetOk = 1; var CharSetString = 2; pp$1.regexp_eatCharacterClassEscape = function(state) { var ch = state.current(); if (isCharacterClassEscape(ch)) { state.lastIntValue = -1; state.advance(); return CharSetOk } var negate = false; if ( state.switchU && this.options.ecmaVersion >= 9 && ((negate = ch === 0x50 ) || ch === 0x70 ) ) { state.lastIntValue = -1; state.advance(); var result; if ( state.eat(0x7B ) && (result = this.regexp_eatUnicodePropertyValueExpression(state)) && state.eat(0x7D ) ) { if (negate && result === CharSetString) { state.raise("Invalid property name"); } return result } state.raise("Invalid property name"); } return CharSetNone }; function isCharacterClassEscape(ch) { return ( ch === 0x64 || ch === 0x44 || ch === 0x73 || ch === 0x53 || ch === 0x77 || ch === 0x57 ) } pp$1.regexp_eatUnicodePropertyValueExpression = function(state) { var start = state.pos; if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D )) { var name = state.lastStringValue; if (this.regexp_eatUnicodePropertyValue(state)) { var value = state.lastStringValue; this.regexp_validateUnicodePropertyNameAndValue(state, name, value); return CharSetOk } } state.pos = start; if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { var nameOrValue = state.lastStringValue; return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue) } return CharSetNone }; pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { if (!hasOwn(state.unicodeProperties.nonBinary, name)) { state.raise("Invalid property name"); } if (!state.unicodeProperties.nonBinary[name].test(value)) { state.raise("Invalid property value"); } }; pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk } if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString } state.raise("Invalid property name"); }; pp$1.regexp_eatUnicodePropertyName = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyNameCharacter(ch = state.current())) { state.lastStringValue += codePointToString(ch); state.advance(); } return state.lastStringValue !== "" }; function isUnicodePropertyNameCharacter(ch) { return isControlLetter(ch) || ch === 0x5F } pp$1.regexp_eatUnicodePropertyValue = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyValueCharacter(ch = state.current())) { state.lastStringValue += codePointToString(ch); state.advance(); } return state.lastStringValue !== "" }; function isUnicodePropertyValueCharacter(ch) { return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) } pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { return this.regexp_eatUnicodePropertyValue(state) }; pp$1.regexp_eatCharacterClass = function(state) { if (state.eat(0x5B )) { var negate = state.eat(0x5E ); var result = this.regexp_classContents(state); if (!state.eat(0x5D )) { state.raise("Unterminated character class"); } if (negate && result === CharSetString) { state.raise("Negated character class may contain strings"); } return true } return false }; pp$1.regexp_classContents = function(state) { if (state.current() === 0x5D ) { return CharSetOk } if (state.switchV) { return this.regexp_classSetExpression(state) } this.regexp_nonEmptyClassRanges(state); return CharSetOk }; pp$1.regexp_nonEmptyClassRanges = function(state) { while (this.regexp_eatClassAtom(state)) { var left = state.lastIntValue; if (state.eat(0x2D ) && this.regexp_eatClassAtom(state)) { var right = state.lastIntValue; if (state.switchU && (left === -1 || right === -1)) { state.raise("Invalid character class"); } if (left !== -1 && right !== -1 && left > right) { state.raise("Range out of order in character class"); } } } }; pp$1.regexp_eatClassAtom = function(state) { var start = state.pos; if (state.eat(0x5C )) { if (this.regexp_eatClassEscape(state)) { return true } if (state.switchU) { var ch$1 = state.current(); if (ch$1 === 0x63 || isOctalDigit(ch$1)) { state.raise("Invalid class escape"); } state.raise("Invalid escape"); } state.pos = start; } var ch = state.current(); if (ch !== 0x5D ) { state.lastIntValue = ch; state.advance(); return true } return false }; pp$1.regexp_eatClassEscape = function(state) { var start = state.pos; if (state.eat(0x62 )) { state.lastIntValue = 0x08; return true } if (state.switchU && state.eat(0x2D )) { state.lastIntValue = 0x2D; return true } if (!state.switchU && state.eat(0x63 )) { if (this.regexp_eatClassControlLetter(state)) { return true } state.pos = start; } return ( this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) ) }; pp$1.regexp_classSetExpression = function(state) { var result = CharSetOk, subResult; if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) { if (subResult === CharSetString) { result = CharSetString; } var start = state.pos; while (state.eatChars([0x26, 0x26] )) { if ( state.current() !== 0x26 && (subResult = this.regexp_eatClassSetOperand(state)) ) { if (subResult !== CharSetString) { result = CharSetOk; } continue } state.raise("Invalid character in character class"); } if (start !== state.pos) { return result } while (state.eatChars([0x2D, 0x2D] )) { if (this.regexp_eatClassSetOperand(state)) { continue } state.raise("Invalid character in character class"); } if (start !== state.pos) { return result } } else { state.raise("Invalid character in character class"); } for (;;) { if (this.regexp_eatClassSetRange(state)) { continue } subResult = this.regexp_eatClassSetOperand(state); if (!subResult) { return result } if (subResult === CharSetString) { result = CharSetString; } } }; pp$1.regexp_eatClassSetRange = function(state) { var start = state.pos; if (this.regexp_eatClassSetCharacter(state)) { var left = state.lastIntValue; if (state.eat(0x2D ) && this.regexp_eatClassSetCharacter(state)) { var right = state.lastIntValue; if (left !== -1 && right !== -1 && left > right) { state.raise("Range out of order in character class"); } return true } state.pos = start; } return false }; pp$1.regexp_eatClassSetOperand = function(state) { if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk } return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state) }; pp$1.regexp_eatNestedClass = function(state) { var start = state.pos; if (state.eat(0x5B )) { var negate = state.eat(0x5E ); var result = this.regexp_classContents(state); if (state.eat(0x5D )) { if (negate && result === CharSetString) { state.raise("Negated character class may contain strings"); } return result } state.pos = start; } if (state.eat(0x5C )) { var result$1 = this.regexp_eatCharacterClassEscape(state); if (result$1) { return result$1 } state.pos = start; } return null }; pp$1.regexp_eatClassStringDisjunction = function(state) { var start = state.pos; if (state.eatChars([0x5C, 0x71] )) { if (state.eat(0x7B )) { var result = this.regexp_classStringDisjunctionContents(state); if (state.eat(0x7D )) { return result } } else { state.raise("Invalid escape"); } state.pos = start; } return null }; pp$1.regexp_classStringDisjunctionContents = function(state) { var result = this.regexp_classString(state); while (state.eat(0x7C )) { if (this.regexp_classString(state) === CharSetString) { result = CharSetString; } } return result }; pp$1.regexp_classString = function(state) { var count = 0; while (this.regexp_eatClassSetCharacter(state)) { count++; } return count === 1 ? CharSetOk : CharSetString }; pp$1.regexp_eatClassSetCharacter = function(state) { var start = state.pos; if (state.eat(0x5C )) { if ( this.regexp_eatCharacterEscape(state) || this.regexp_eatClassSetReservedPunctuator(state) ) { return true } if (state.eat(0x62 )) { state.lastIntValue = 0x08; return true } state.pos = start; return false } var ch = state.current(); if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { return false } if (isClassSetSyntaxCharacter(ch)) { return false } state.advance(); state.lastIntValue = ch; return true }; function isClassSetReservedDoublePunctuatorCharacter(ch) { return ( ch === 0x21 || ch >= 0x23 && ch <= 0x26 || ch >= 0x2A && ch <= 0x2C || ch === 0x2E || ch >= 0x3A && ch <= 0x40 || ch === 0x5E || ch === 0x60 || ch === 0x7E ) } function isClassSetSyntaxCharacter(ch) { return ( ch === 0x28 || ch === 0x29 || ch === 0x2D || ch === 0x2F || ch >= 0x5B && ch <= 0x5D || ch >= 0x7B && ch <= 0x7D ) } pp$1.regexp_eatClassSetReservedPunctuator = function(state) { var ch = state.current(); if (isClassSetReservedPunctuator(ch)) { state.lastIntValue = ch; state.advance(); return true } return false }; function isClassSetReservedPunctuator(ch) { return ( ch === 0x21 || ch === 0x23 || ch === 0x25 || ch === 0x26 || ch === 0x2C || ch === 0x2D || ch >= 0x3A && ch <= 0x3E || ch === 0x40 || ch === 0x60 || ch === 0x7E ) } pp$1.regexp_eatClassControlLetter = function(state) { var ch = state.current(); if (isDecimalDigit(ch) || ch === 0x5F ) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; pp$1.regexp_eatHexEscapeSequence = function(state) { var start = state.pos; if (state.eat(0x78 )) { if (this.regexp_eatFixedHexDigits(state, 2)) { return true } if (state.switchU) { state.raise("Invalid escape"); } state.pos = start; } return false }; pp$1.regexp_eatDecimalDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isDecimalDigit(ch = state.current())) { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 ); state.advance(); } return state.pos !== start }; function isDecimalDigit(ch) { return ch >= 0x30 && ch <= 0x39 } pp$1.regexp_eatHexDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isHexDigit(ch = state.current())) { state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance(); } return state.pos !== start }; function isHexDigit(ch) { return ( (ch >= 0x30 && ch <= 0x39 ) || (ch >= 0x41 && ch <= 0x46 ) || (ch >= 0x61 && ch <= 0x66 ) ) } function hexToInt(ch) { if (ch >= 0x41 && ch <= 0x46 ) { return 10 + (ch - 0x41 ) } if (ch >= 0x61 && ch <= 0x66 ) { return 10 + (ch - 0x61 ) } return ch - 0x30 } pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) { if (this.regexp_eatOctalDigit(state)) { var n1 = state.lastIntValue; if (this.regexp_eatOctalDigit(state)) { var n2 = state.lastIntValue; if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; } else { state.lastIntValue = n1 * 8 + n2; } } else { state.lastIntValue = n1; } return true } return false }; pp$1.regexp_eatOctalDigit = function(state) { var ch = state.current(); if (isOctalDigit(ch)) { state.lastIntValue = ch - 0x30; state.advance(); return true } state.lastIntValue = 0; return false }; function isOctalDigit(ch) { return ch >= 0x30 && ch <= 0x37 } pp$1.regexp_eatFixedHexDigits = function(state, length) { var start = state.pos; state.lastIntValue = 0; for (var i = 0; i < length; ++i) { var ch = state.current(); if (!isHexDigit(ch)) { state.pos = start; return false } state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance(); } return true }; var Token = function Token(p) { this.type = p.type; this.value = p.value; this.start = p.start; this.end = p.end; if (p.options.locations) { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } if (p.options.ranges) { this.range = [p.start, p.end]; } }; var pp = Parser.prototype; pp.next = function(ignoreEscapeSequenceInKeyword) { if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } if (this.options.onToken) { this.options.onToken(new Token(this)); } this.lastTokEnd = this.end; this.lastTokStart = this.start; this.lastTokEndLoc = this.endLoc; this.lastTokStartLoc = this.startLoc; this.nextToken(); }; pp.getToken = function() { this.next(); return new Token(this) }; if (typeof Symbol !== "undefined") { pp[Symbol.iterator] = function() { var this$1$1 = this; return { next: function () { var token = this$1$1.getToken(); return { done: token.type === types$1.eof, value: token } } } }; } pp.nextToken = function() { var curContext = this.curContext(); if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } this.start = this.pos; if (this.options.locations) { this.startLoc = this.curPosition(); } if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) } if (curContext.override) { return curContext.override(this) } else { this.readToken(this.fullCharCodeAtPos()); } }; pp.readToken = function(code) { if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 ) { return this.readWord() } return this.getTokenFromCode(code) }; pp.fullCharCodeAtPos = function() { var code = this.input.charCodeAt(this.pos); if (code <= 0xd7ff || code >= 0xdc00) { return code } var next = this.input.charCodeAt(this.pos + 1); return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 }; pp.skipBlockComment = function() { var startLoc = this.options.onComment && this.curPosition(); var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } this.pos = end + 2; if (this.options.locations) { for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) { ++this.curLine; pos = this.lineStart = nextBreak; } } if (this.options.onComment) { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition()); } }; pp.skipLineComment = function(startSkip) { var start = this.pos; var startLoc = this.options.onComment && this.curPosition(); var ch = this.input.charCodeAt(this.pos += startSkip); while (this.pos < this.input.length && !isNewLine(ch)) { ch = this.input.charCodeAt(++this.pos); } if (this.options.onComment) { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition()); } }; pp.skipSpace = function() { loop: while (this.pos < this.input.length) { var ch = this.input.charCodeAt(this.pos); switch (ch) { case 32: case 160: ++this.pos; break case 13: if (this.input.charCodeAt(this.pos + 1) === 10) { ++this.pos; } case 10: case 8232: case 8233: ++this.pos; if (this.options.locations) { ++this.curLine; this.lineStart = this.pos; } break case 47: switch (this.input.charCodeAt(this.pos + 1)) { case 42: this.skipBlockComment(); break case 47: this.skipLineComment(2); break default: break loop } break default: if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { ++this.pos; } else { break loop } } } }; pp.finishToken = function(type, val) { this.end = this.pos; if (this.options.locations) { this.endLoc = this.curPosition(); } var prevType = this.type; this.type = type; this.value = val; this.updateContext(prevType); }; pp.readToken_dot = function() { var next = this.input.charCodeAt(this.pos + 1); if (next >= 48 && next <= 57) { return this.readNumber(true) } var next2 = this.input.charCodeAt(this.pos + 2); if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { this.pos += 3; return this.finishToken(types$1.ellipsis) } else { ++this.pos; return this.finishToken(types$1.dot) } }; pp.readToken_slash = function() { var next = this.input.charCodeAt(this.pos + 1); if (this.exprAllowed) { ++this.pos; return this.readRegexp() } if (next === 61) { return this.finishOp(types$1.assign, 2) } return this.finishOp(types$1.slash, 1) }; pp.readToken_mult_modulo_exp = function(code) { var next = this.input.charCodeAt(this.pos + 1); var size = 1; var tokentype = code === 42 ? types$1.star : types$1.modulo; if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { ++size; tokentype = types$1.starstar; next = this.input.charCodeAt(this.pos + 2); } if (next === 61) { return this.finishOp(types$1.assign, size + 1) } return this.finishOp(tokentype, size) }; pp.readToken_pipe_amp = function(code) { var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (this.options.ecmaVersion >= 12) { var next2 = this.input.charCodeAt(this.pos + 2); if (next2 === 61) { return this.finishOp(types$1.assign, 3) } } return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2) } if (next === 61) { return this.finishOp(types$1.assign, 2) } return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1) }; pp.readToken_caret = function() { var next = this.input.charCodeAt(this.pos + 1); if (next === 61) { return this.finishOp(types$1.assign, 2) } return this.finishOp(types$1.bitwiseXOR, 1) }; pp.readToken_plus_min = function(code) { var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { this.skipLineComment(3); this.skipSpace(); return this.nextToken() } return this.finishOp(types$1.incDec, 2) } if (next === 61) { return this.finishOp(types$1.assign, 2) } return this.finishOp(types$1.plusMin, 1) }; pp.readToken_lt_gt = function(code) { var next = this.input.charCodeAt(this.pos + 1); var size = 1; if (next === code) { size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) } return this.finishOp(types$1.bitShift, size) } if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) { this.skipLineComment(4); this.skipSpace(); return this.nextToken() } if (next === 61) { size = 2; } return this.finishOp(types$1.relational, size) }; pp.readToken_eq_excl = function(code) { var next = this.input.charCodeAt(this.pos + 1); if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) } if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { this.pos += 2; return this.finishToken(types$1.arrow) } return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1) }; pp.readToken_question = function() { var ecmaVersion = this.options.ecmaVersion; if (ecmaVersion >= 11) { var next = this.input.charCodeAt(this.pos + 1); if (next === 46) { var next2 = this.input.charCodeAt(this.pos + 2); if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) } } if (next === 63) { if (ecmaVersion >= 12) { var next2$1 = this.input.charCodeAt(this.pos + 2); if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) } } return this.finishOp(types$1.coalesce, 2) } } return this.finishOp(types$1.question, 1) }; pp.readToken_numberSign = function() { var ecmaVersion = this.options.ecmaVersion; var code = 35; if (ecmaVersion >= 13) { ++this.pos; code = this.fullCharCodeAtPos(); if (isIdentifierStart(code, true) || code === 92 ) { return this.finishToken(types$1.privateId, this.readWord1()) } } this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'"); }; pp.getTokenFromCode = function(code) { switch (code) { case 46: return this.readToken_dot() case 40: ++this.pos; return this.finishToken(types$1.parenL) case 41: ++this.pos; return this.finishToken(types$1.parenR) case 59: ++this.pos; return this.finishToken(types$1.semi) case 44: ++this.pos; return this.finishToken(types$1.comma) case 91: ++this.pos; return this.finishToken(types$1.bracketL) case 93: ++this.pos; return this.finishToken(types$1.bracketR) case 123: ++this.pos; return this.finishToken(types$1.braceL) case 125: ++this.pos; return this.finishToken(types$1.braceR) case 58: ++this.pos; return this.finishToken(types$1.colon) case 96: if (this.options.ecmaVersion < 6) { break } ++this.pos; return this.finishToken(types$1.backQuote) case 48: var next = this.input.charCodeAt(this.pos + 1); if (next === 120 || next === 88) { return this.readRadixNumber(16) } if (this.options.ecmaVersion >= 6) { if (next === 111 || next === 79) { return this.readRadixNumber(8) } if (next === 98 || next === 66) { return this.readRadixNumber(2) } } case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return this.readNumber(false) case 34: case 39: return this.readString(code) case 47: return this.readToken_slash() case 37: case 42: return this.readToken_mult_modulo_exp(code) case 124: case 38: return this.readToken_pipe_amp(code) case 94: return this.readToken_caret() case 43: case 45: return this.readToken_plus_min(code) case 60: case 62: return this.readToken_lt_gt(code) case 61: case 33: return this.readToken_eq_excl(code) case 63: return this.readToken_question() case 126: return this.finishOp(types$1.prefix, 1) case 35: return this.readToken_numberSign() } this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'"); }; pp.finishOp = function(type, size) { var str = this.input.slice(this.pos, this.pos + size); this.pos += size; return this.finishToken(type, str) }; pp.readRegexp = function() { var escaped, inClass, start = this.pos; for (;;) { if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); } var ch = this.input.charAt(this.pos); if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); } if (!escaped) { if (ch === "[") { inClass = true; } else if (ch === "]" && inClass) { inClass = false; } else if (ch === "/" && !inClass) { break } escaped = ch === "\\"; } else { escaped = false; } ++this.pos; } var pattern = this.input.slice(start, this.pos); ++this.pos; var flagsStart = this.pos; var flags = this.readWord1(); if (this.containsEsc) { this.unexpected(flagsStart); } var state = this.regexpState || (this.regexpState = new RegExpValidationState(this)); state.reset(start, pattern, flags); this.validateRegExpFlags(state); this.validateRegExpPattern(state); var value = null; try { value = new RegExp(pattern, flags); } catch (e) { } return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value}) }; pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) { var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined; var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48; var start = this.pos, total = 0, lastCode = 0; for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) { var code = this.input.charCodeAt(this.pos), val = (void 0); if (allowSeparators && code === 95) { if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); } if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); } if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); } lastCode = code; continue } if (code >= 97) { val = code - 97 + 10; } else if (code >= 65) { val = code - 65 + 10; } else if (code >= 48 && code <= 57) { val = code - 48; } else { val = Infinity; } if (val >= radix) { break } lastCode = code; total = total * radix + val; } if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); } if (this.pos === start || len != null && this.pos - start !== len) { return null } return total }; function stringToNumber(str, isLegacyOctalNumericLiteral) { if (isLegacyOctalNumericLiteral) { return parseInt(str, 8) } return parseFloat(str.replace(/_/g, "")) } function stringToBigInt(str) { if (typeof BigInt !== "function") { return null } return BigInt(str.replace(/_/g, "")) } pp.readRadixNumber = function(radix) { var start = this.pos; this.pos += 2; var val = this.readInt(radix); if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); } if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) { val = stringToBigInt(this.input.slice(start, this.pos)); ++this.pos; } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); } return this.finishToken(types$1.num, val) }; pp.readNumber = function(startsWithDot) { var start = this.pos; if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); } var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48; if (octal && this.strict) { this.raise(start, "Invalid number"); } var next = this.input.charCodeAt(this.pos); if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) { var val$1 = stringToBigInt(this.input.slice(start, this.pos)); ++this.pos; if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); } return this.finishToken(types$1.num, val$1) } if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; } if (next === 46 && !octal) { ++this.pos; this.readInt(10); next = this.input.charCodeAt(this.pos); } if ((next === 69 || next === 101) && !octal) { next = this.input.charCodeAt(++this.pos); if (next === 43 || next === 45) { ++this.pos; } if (this.readInt(10) === null) { this.raise(start, "Invalid number"); } } if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); } var val = stringToNumber(this.input.slice(start, this.pos), octal); return this.finishToken(types$1.num, val) }; pp.readCodePoint = function() { var ch = this.input.charCodeAt(this.pos), code; if (ch === 123) { if (this.options.ecmaVersion < 6) { this.unexpected(); } var codePos = ++this.pos; code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos); ++this.pos; if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); } } else { code = this.readHexChar(4); } return code }; pp.readString = function(quote) { var out = "", chunkStart = ++this.pos; for (;;) { if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); } var ch = this.input.charCodeAt(this.pos); if (ch === quote) { break } if (ch === 92) { out += this.input.slice(chunkStart, this.pos); out += this.readEscapedChar(false); chunkStart = this.pos; } else if (ch === 0x2028 || ch === 0x2029) { if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); } ++this.pos; if (this.options.locations) { this.curLine++; this.lineStart = this.pos; } } else { if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); } ++this.pos; } } out += this.input.slice(chunkStart, this.pos++); return this.finishToken(types$1.string, out) }; var INVALID_TEMPLATE_ESCAPE_ERROR = {}; pp.tryReadTemplateToken = function() { this.inTemplateElement = true; try { this.readTmplToken(); } catch (err) { if (err === INVALID_TEMPLATE_ESCAPE_ERROR) { this.readInvalidTemplateToken(); } else { throw err } } this.inTemplateElement = false; }; pp.invalidStringToken = function(position, message) { if (this.inTemplateElement && this.options.ecmaVersion >= 9) { throw INVALID_TEMPLATE_ESCAPE_ERROR } else { this.raise(position, message); } }; pp.readTmplToken = function() { var out = "", chunkStart = this.pos; for (;;) { if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); } var ch = this.input.charCodeAt(this.pos); if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) { if (ch === 36) { this.pos += 2; return this.finishToken(types$1.dollarBraceL) } else { ++this.pos; return this.finishToken(types$1.backQuote) } } out += this.input.slice(chunkStart, this.pos); return this.finishToken(types$1.template, out) } if (ch === 92) { out += this.input.slice(chunkStart, this.pos); out += this.readEscapedChar(true); chunkStart = this.pos; } else if (isNewLine(ch)) { out += this.input.slice(chunkStart, this.pos); ++this.pos; switch (ch) { case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } case 10: out += "\n"; break default: out += String.fromCharCode(ch); break } if (this.options.locations) { ++this.curLine; this.lineStart = this.pos; } chunkStart = this.pos; } else { ++this.pos; } } }; pp.readInvalidTemplateToken = function() { for (; this.pos < this.input.length; this.pos++) { switch (this.input[this.pos]) { case "\\": ++this.pos; break case "$": if (this.input[this.pos + 1] !== "{") { break } case "`": return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos)) case "\r": if (this.input[this.pos + 1] === "\n") { ++this.pos; } case "\n": case "\u2028": case "\u2029": ++this.curLine; this.lineStart = this.pos + 1; break } } this.raise(this.start, "Unterminated template"); }; pp.readEscapedChar = function(inTemplate) { var ch = this.input.charCodeAt(++this.pos); ++this.pos; switch (ch) { case 110: return "\n" case 114: return "\r" case 120: return String.fromCharCode(this.readHexChar(2)) case 117: return codePointToString(this.readCodePoint()) case 116: return "\t" case 98: return "\b" case 118: return "\u000b" case 102: return "\f" case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } case 10: if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; } return "" case 56: case 57: if (this.strict) { this.invalidStringToken( this.pos - 1, "Invalid escape sequence" ); } if (inTemplate) { var codePos = this.pos - 1; this.invalidStringToken( codePos, "Invalid escape sequence in template string" ); } default: if (ch >= 48 && ch <= 55) { var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0]; var octal = parseInt(octalStr, 8); if (octal > 255) { octalStr = octalStr.slice(0, -1); octal = parseInt(octalStr, 8); } this.pos += octalStr.length - 1; ch = this.input.charCodeAt(this.pos); if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) { this.invalidStringToken( this.pos - 1 - octalStr.length, inTemplate ? "Octal literal in template string" : "Octal literal in strict mode" ); } return String.fromCharCode(octal) } if (isNewLine(ch)) { if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; } return "" } return String.fromCharCode(ch) } }; pp.readHexChar = function(len) { var codePos = this.pos; var n = this.readInt(16, len); if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); } return n }; pp.readWord1 = function() { this.containsEsc = false; var word = "", first = true, chunkStart = this.pos; var astral = this.options.ecmaVersion >= 6; while (this.pos < this.input.length) { var ch = this.fullCharCodeAtPos(); if (isIdentifierChar(ch, astral)) { this.pos += ch <= 0xffff ? 1 : 2; } else if (ch === 92) { this.containsEsc = true; word += this.input.slice(chunkStart, this.pos); var escStart = this.pos; if (this.input.charCodeAt(++this.pos) !== 117) { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); } ++this.pos; var esc = this.readCodePoint(); if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) { this.invalidStringToken(escStart, "Invalid Unicode escape"); } word += codePointToString(esc); chunkStart = this.pos; } else { break } first = false; } return word + this.input.slice(chunkStart, this.pos) }; pp.readWord = function() { var word = this.readWord1(); var type = types$1.name; if (this.keywords.test(word)) { type = keywords[word]; } return this.finishToken(type, word) }; var version = "8.14.0"; Parser.acorn = { Parser: Parser, version: version, defaultOptions: defaultOptions, Position: Position, SourceLocation: SourceLocation, getLineInfo: getLineInfo, Node: Node, TokenType: TokenType, tokTypes: types$1, keywordTypes: keywords, TokContext: TokContext, tokContexts: types, isIdentifierChar: isIdentifierChar, isIdentifierStart: isIdentifierStart, Token: Token, isNewLine: isNewLine, lineBreak: lineBreak, lineBreakG: lineBreakG, nonASCIIwhitespace: nonASCIIwhitespace }; function parse(input, options) { return Parser.parse(input, options) } function parseExpressionAt(input, pos, options) { return Parser.parseExpressionAt(input, pos, options) } function tokenizer(input, options) { return Parser.tokenizer(input, options) } exports.Node = Node; exports.Parser = Parser; exports.Position = Position; exports.SourceLocation = SourceLocation; exports.TokContext = TokContext; exports.Token = Token; exports.TokenType = TokenType; exports.defaultOptions = defaultOptions; exports.getLineInfo = getLineInfo; exports.isIdentifierChar = isIdentifierChar; exports.isIdentifierStart = isIdentifierStart; exports.isNewLine = isNewLine; exports.keywordTypes = keywords; exports.lineBreak = lineBreak; exports.lineBreakG = lineBreakG; exports.nonASCIIwhitespace = nonASCIIwhitespace; exports.parse = parse; exports.parseExpressionAt = parseExpressionAt; exports.tokContexts = types; exports.tokTypes = types$1; exports.tokenizer = tokenizer; exports.version = version; })); },{}],2:[function(require,module,exports){ },{}],3:[function(require,module,exports){ function glWiretap(gl, options = {}) { const { contextName = 'gl', throwGetError, useTrackablePrimitives, readPixelsFile, recording = [], variables = {}, onReadPixels, onUnrecognizedArgumentLookup, } = options; const proxy = new Proxy(gl, { get: listen }); const contextVariables = []; const entityNames = {}; let imageCount = 0; let indent = ''; let readPixelsVariableName; return proxy; function listen(obj, property) { switch (property) { case 'addComment': return addComment; case 'checkThrowError': return checkThrowError; case 'getReadPixelsVariableName': return readPixelsVariableName; case 'insertVariable': return insertVariable; case 'reset': return reset; case 'setIndent': return setIndent; case 'toString': return toString; case 'getContextVariableName': return getContextVariableName; } if (typeof gl[property] === 'function') { return function() { switch (property) { case 'getError': if (throwGetError) { recording.push(`${indent}if (${contextName}.getError() !== ${contextName}.NONE) throw new Error('error');`); } else { recording.push(`${indent}${contextName}.getError();`); } return gl.getError(); case 'getExtension': { const variableName = `${contextName}Variables${contextVariables.length}`; recording.push(`${indent}const ${variableName} = ${contextName}.getExtension('${arguments[0]}');`); const extension = gl.getExtension(arguments[0]); if (extension && typeof extension === 'object') { const tappedExtension = glExtensionWiretap(extension, { getEntity, useTrackablePrimitives, recording, contextName: variableName, contextVariables, variables, indent, onUnrecognizedArgumentLookup, }); contextVariables.push(tappedExtension); return tappedExtension; } else { contextVariables.push(null); } return extension; } case 'readPixels': const i = contextVariables.indexOf(arguments[6]); let targetVariableName; if (i === -1) { const variableName = getVariableName(arguments[6]); if (variableName) { targetVariableName = variableName; recording.push(`${indent}${variableName}`); } else { targetVariableName = `${contextName}Variable${contextVariables.length}`; contextVariables.push(arguments[6]); recording.push(`${indent}const ${targetVariableName} = new ${arguments[6].constructor.name}(${arguments[6].length});`); } } else { targetVariableName = `${contextName}Variable${i}`; } readPixelsVariableName = targetVariableName; const argumentAsStrings = [ arguments[0], arguments[1], arguments[2], arguments[3], getEntity(arguments[4]), getEntity(arguments[5]), targetVariableName ]; recording.push(`${indent}${contextName}.readPixels(${argumentAsStrings.join(', ')});`); if (readPixelsFile) { writePPM(arguments[2], arguments[3]); } if (onReadPixels) { onReadPixels(targetVariableName, argumentAsStrings); } return gl.readPixels.apply(gl, arguments); case 'drawBuffers': recording.push(`${indent}${contextName}.drawBuffers([${argumentsToString(arguments[0], { contextName, contextVariables, getEntity, addVariable, variables, onUnrecognizedArgumentLookup } )}]);`); return gl.drawBuffers(arguments[0]); } let result = gl[property].apply(gl, arguments); switch (typeof result) { case 'undefined': recording.push(`${indent}${methodCallToString(property, arguments)};`); return; case 'number': case 'boolean': if (useTrackablePrimitives && contextVariables.indexOf(trackablePrimitive(result)) === -1) { recording.push(`${indent}const ${contextName}Variable${contextVariables.length} = ${methodCallToString(property, arguments)};`); contextVariables.push(result = trackablePrimitive(result)); break; } default: if (result === null) { recording.push(`${methodCallToString(property, arguments)};`); } else { recording.push(`${indent}const ${contextName}Variable${contextVariables.length} = ${methodCallToString(property, arguments)};`); } contextVariables.push(result); } return result; } } entityNames[gl[property]] = property; return gl[property]; } function toString() { return recording.join('\n'); } function reset() { while (recording.length > 0) { recording.pop(); } } function insertVariable(name, value) { variables[name] = value; } function getEntity(value) { const name = entityNames[value]; if (name) { return contextName + '.' + name; } return value; } function setIndent(spaces) { indent = ' '.repeat(spaces); } function addVariable(value, source) { const variableName = `${contextName}Variable${contextVariables.length}`; recording.push(`${indent}const ${variableName} = ${source};`); contextVariables.push(value); return variableName; } function writePPM(width, height) { const sourceVariable = `${contextName}Variable${contextVariables.length}`; const imageVariable = `imageDatum${imageCount}`; recording.push(`${indent}let ${imageVariable} = ["P3\\n# ${readPixelsFile}.ppm\\n", ${width}, ' ', ${height}, "\\n255\\n"].join("");`); recording.push(`${indent}for (let i = 0; i < ${imageVariable}.length; i += 4) {`); recording.push(`${indent} ${imageVariable} += ${sourceVariable}[i] + ' ' + ${sourceVariable}[i + 1] + ' ' + ${sourceVariable}[i + 2] + ' ';`); recording.push(`${indent}}`); recording.push(`${indent}if (typeof require !== "undefined") {`); recording.push(`${indent} require('fs').writeFileSync('./${readPixelsFile}.ppm', ${imageVariable});`); recording.push(`${indent}}`); imageCount++; } function addComment(value) { recording.push(`${indent}// ${value}`); } function checkThrowError() { recording.push(`${indent}(() => { ${indent}const error = ${contextName}.getError(); ${indent}if (error !== ${contextName}.NONE) { ${indent} const names = Object.getOwnPropertyNames(gl); ${indent} for (let i = 0; i < names.length; i++) { ${indent} const name = names[i]; ${indent} if (${contextName}[name] === error) { ${indent} throw new Error('${contextName} threw ' + name); ${indent} } ${indent} } ${indent}} ${indent}})();`); } function methodCallToString(method, args) { return `${contextName}.${method}(${argumentsToString(args, { contextName, contextVariables, getEntity, addVariable, variables, onUnrecognizedArgumentLookup })})`; } function getVariableName(value) { if (variables) { for (const name in variables) { if (variables[name] === value) { return name; } } } return null; } function getContextVariableName(value) { const i = contextVariables.indexOf(value); if (i !== -1) { return `${contextName}Variable${i}`; } return null; } } function glExtensionWiretap(extension, options) { const proxy = new Proxy(extension, { get: listen }); const extensionEntityNames = {}; const { contextName, contextVariables, getEntity, useTrackablePrimitives, recording, variables, indent, onUnrecognizedArgumentLookup, } = options; return proxy; function listen(obj, property) { if (typeof obj[property] === 'function') { return function() { switch (property) { case 'drawBuffersWEBGL': recording.push(`${indent}${contextName}.drawBuffersWEBGL([${argumentsToString(arguments[0], { contextName, contextVariables, getEntity: getExtensionEntity, addVariable, variables, onUnrecognizedArgumentLookup })}]);`); return extension.drawBuffersWEBGL(arguments[0]); } let result = extension[property].apply(extension, arguments); switch (typeof result) { case 'undefined': recording.push(`${indent}${methodCallToString(property, arguments)};`); return; case 'number': case 'boolean': if (useTrackablePrimitives && contextVariables.indexOf(trackablePrimitive(result)) === -1) { recording.push(`${indent}const ${contextName}Variable${contextVariables.length} = ${methodCallToString(property, arguments)};`); contextVariables.push(result = trackablePrimitive(result)); } else { recording.push(`${indent}const ${contextName}Variable${contextVariables.length} = ${methodCallToString(property, arguments)};`); contextVariables.push(result); } break; default: if (result === null) { recording.push(`${methodCallToString(property, arguments)};`); } else { recording.push(`${indent}const ${contextName}Variable${contextVariables.length} = ${methodCallToString(property, arguments)};`); } contextVariables.push(result); } return result; }; } extensionEntityNames[extension[property]] = property; return extension[property]; } function getExtensionEntity(value) { if (extensionEntityNames.hasOwnProperty(value)) { return `${contextName}.${extensionEntityNames[value]}`; } return getEntity(value); } function methodCallToString(method, args) { return `${contextName}.${method}(${argumentsToString(args, { contextName, contextVariables, getEntity: getExtensionEntity, addVariable, variables, onUnrecognizedArgumentLookup })})`; } function addVariable(value, source) { const variableName = `${contextName}Variable${contextVariables.length}`; contextVariables.push(value); recording.push(`${indent}const ${variableName} = ${source};`); return variableName; } } function argumentsToString(args, options) { const { variables, onUnrecognizedArgumentLookup } = options; return (Array.from(args).map((arg) => { const variableName = getVariableName(arg); if (variableName) { return variableName; } return argumentToString(arg, options); }).join(', ')); function getVariableName(value) { if (variables) { for (const name in variables) { if (!variables.hasOwnProperty(name)) continue; if (variables[name] === value) { return name; } } } if (onUnrecognizedArgumentLookup) { return onUnrecognizedArgumentLookup(value); } return null; } } function argumentToString(arg, options) { const { contextName, contextVariables, getEntity, addVariable, onUnrecognizedArgumentLookup } = options; if (typeof arg === 'undefined') { return 'undefined'; } if (arg === null) { return 'null'; } const i = contextVariables.indexOf(arg); if (i > -1) { return `${contextName}Variable${i}`; } switch (arg.constructor.name) { case 'String': const hasLines = /\n/.test(arg); const hasSingleQuotes = /'/.test(arg); const hasDoubleQuotes = /"/.test(arg); if (hasLines) { return '`' + arg + '`'; } else if (hasSingleQuotes && !hasDoubleQuotes) { return '"' + arg + '"'; } else if (!hasSingleQuotes && hasDoubleQuotes) { return "'" + arg + "'"; } else { return '\'' + arg + '\''; } case 'Number': return getEntity(arg); case 'Boolean': return getEntity(arg); case 'Array': return addVariable(arg, `new ${arg.constructor.name}([${Array.from(arg).join(',')}])`); case 'Float32Array': case 'Uint8Array': case 'Uint16Array': case 'Int32Array': return addVariable(arg, `new ${arg.constructor.name}(${JSON.stringify(Array.from(arg))})`); default: if (onUnrecognizedArgumentLookup) { const instantiationString = onUnrecognizedArgumentLookup(arg); if (instantiationString) { return instantiationString; } } throw new Error(`unrecognized argument type ${arg.constructor.name}`); } } function trackablePrimitive(value) { return new value.constructor(value); } if (typeof module !== 'undefined') { module.exports = { glWiretap, glExtensionWiretap }; } if (typeof window !== 'undefined') { glWiretap.glExtensionWiretap = glExtensionWiretap; window.glWiretap = glWiretap; } },{}],4:[function(require,module,exports){ function setupArguments(args) { const newArguments = new Array(args.length); for (let i = 0; i < args.length; i++) { const arg = args[i]; if (arg.toArray) { newArguments[i] = arg.toArray(); } else { newArguments[i] = arg; } } return newArguments; } function mock1D() { const args = setupArguments(arguments); const row = new Float32Array(this.output.x); for (let x = 0; x < this.output.x; x++) { this.thread.x = x; this.thread.y = 0; this.thread.z = 0; row[x] = this._fn.apply(this, args); } return row; } function mock2D() { const args = setupArguments(arguments); const matrix = new Array(this.output.y); for (let y = 0; y < this.output.y; y++) { const row = new Float32Array(this.output.x); for (let x = 0; x < this.output.x; x++) { this.thread.x = x; this.thread.y = y; this.thread.z = 0; row[x] = this._fn.apply(this, args); } matrix[y] = row; } return matrix; } function mock2DGraphical() { const args = setupArguments(arguments); for (let y = 0; y < this.output.y; y++) { for (let x = 0; x < this.output.x; x++) { this.thread.x = x; this.thread.y = y; this.thread.z = 0; this._fn.apply(this, args); } } } function mock3D() { const args = setupArguments(arguments); const cube = new Array(this.output.z); for (let z = 0; z < this.output.z; z++) { const matrix = new Array(this.output.y); for (let y = 0; y < this.output.y; y++) { const row = new Float32Array(this.output.x); for (let x = 0; x < this.output.x; x++) { this.thread.x = x; this.thread.y = y; this.thread.z = z; row[x] = this._fn.apply(this, args); } matrix[y] = row; } cube[z] = matrix; } return cube; } function apiDecorate(kernel) { kernel.setOutput = (output) => { kernel.output = setupOutput(output); if (kernel.graphical) { setupGraphical(kernel); } }; kernel.toJSON = () => { throw new Error('Not usable with gpuMock'); }; kernel.setConstants = (flag) => { kernel.constants = flag; return kernel; }; kernel.setGraphical = (flag) => { kernel.graphical = flag; return kernel; }; kernel.setCanvas = (flag) => { kernel.canvas = flag; return kernel; }; kernel.setContext = (flag) => { kernel.context = flag; return kernel; }; kernel.destroy = () => {}; kernel.validateSettings = () => {}; if (kernel.graphical && kernel.output) { setupGraphical(kernel); } kernel.exec = function() { return new Promise((resolve, reject) => { try { resolve(kernel.apply(kernel, arguments)); } catch(e) { reject(e); } }); }; kernel.getPixels = (flip) => { const {x, y} = kernel.output; return flip ? flipPixels(kernel._imageData.data, x, y) : kernel._imageData.data.slice(0); }; kernel.color = function(r, g, b, a) { if (typeof a === 'undefined') { a = 1; } r = Math.floor(r * 255); g = Math.floor(g * 255); b = Math.floor(b * 255); a = Math.floor(a * 255); const width = kernel.output.x; const height = kernel.output.y; const x = kernel.thread.x; const y = height - kernel.thread.y - 1; const index = x + y * width; kernel._colorData[index * 4 + 0] = r; kernel._colorData[index * 4 + 1] = g; kernel._colorData[index * 4 + 2] = b; kernel._colorData[index * 4 + 3] = a; }; const mockMethod = () => kernel; const methods = [ 'setWarnVarUsage', 'setArgumentTypes', 'setTactic', 'setOptimizeFloatMemory', 'setDebug', 'setLoopMaxIterations', 'setConstantTypes', 'setFunctions', 'setNativeFunctions', 'setInjectedNative', 'setPipeline', 'setPrecision', 'setOutputToTexture', 'setImmutable', 'setStrictIntegers', 'setDynamicOutput', 'setHardcodeConstants', 'setDynamicArguments', 'setUseLegacyEncoder', 'setWarnVarUsage', 'addSubKernel', ]; for (let i = 0; i < methods.length; i++) { kernel[methods[i]] = mockMethod; } return kernel; } function setupGraphical(kernel) { const {x, y} = kernel.output; if (kernel.context && kernel.context.createImageData) { const data = new Uint8ClampedArray(x * y * 4); kernel._imageData = kernel.context.createImageData(x, y); kernel._colorData = data; } else { const data = new Uint8ClampedArray(x * y * 4); kernel._imageData = { data }; kernel._colorData = data; } } function setupOutput(output) { let result = null; if (output.length) { if (output.length === 3) { const [x,y,z] = output; result = { x, y, z }; } else if (output.length === 2) { const [x,y] = output; result = { x, y }; } else { const [x] = output; result = { x }; } } else { result = output; } return result; } function gpuMock(fn, settings = {}) { const output = settings.output ? setupOutput(settings.output) : null; function kernel() { if (kernel.output.z) { return mock3D.apply(kernel, arguments); } else if (kernel.output.y) { if (kernel.graphical) { return mock2DGraphical.apply(kernel, arguments); } return mock2D.apply(kernel, arguments); } else { return mock1D.apply(kernel, arguments); } } kernel._fn = fn; kernel.constants = settings.constants || null; kernel.context = settings.context || null; kernel.canvas = settings.canvas || null; kernel.graphical = settings.graphical || false; kernel._imageData = null; kernel._colorData = null; kernel.output = output; kernel.thread = { x: 0, y: 0, z: 0 }; return apiDecorate(kernel); } function flipPixels(pixels, width, height) { const halfHeight = height / 2 | 0; const bytesPerRow = width * 4; const temp = new Uint8ClampedArray(width * 4); const result = pixels.slice(0); for (let y = 0; y < halfHeight; ++y) { const topOffset = y * bytesPerRow; const bottomOffset = (height - y - 1) * bytesPerRow; temp.set(result.subarray(topOffset, topOffset + bytesPerRow)); result.copyWithin(topOffset, bottomOffset, bottomOffset + bytesPerRow); result.set(temp, bottomOffset); } return result; } module.exports = { gpuMock }; },{}],5:[function(require,module,exports){ const { utils } = require('./utils'); function alias(name, source) { const fnString = source.toString(); return new Function(`return function ${ name } (${ utils.getArgumentNamesFromString(fnString).join(', ') }) { ${ utils.getFunctionBodyFromString(fnString) } }`)(); } module.exports = { alias }; },{"./utils":114}],6:[function(require,module,exports){ const { FunctionNode } = require('../function-node'); class CPUFunctionNode extends FunctionNode { astFunction(ast, retArr) { if (!this.isRootKernel) { retArr.push('function'); retArr.push(' '); retArr.push(this.name); retArr.push('('); for (let i = 0; i < this.argumentNames.length; ++i) { const argumentName = this.argumentNames[i]; if (i > 0) { retArr.push(', '); } retArr.push('user_'); retArr.push(argumentName); } retArr.push(') {\n'); } for (let i = 0; i < ast.body.body.length; ++i) { this.astGeneric(ast.body.body[i], retArr); retArr.push('\n'); } if (!this.isRootKernel) { retArr.push('}\n'); } return retArr; } astReturnStatement(ast, retArr) { const type = this.returnType || this.getType(ast.argument); if (!this.returnType) { this.returnType = type; } if (this.isRootKernel) { retArr.push(this.leadingReturnStatement); this.astGeneric(ast.argument, retArr); retArr.push(';\n'); retArr.push(this.followingReturnStatement); retArr.push('continue;\n'); } else if (this.isSubKernel) { retArr.push(`subKernelResult_${ this.name } = `); this.astGeneric(ast.argument, retArr); retArr.push(';'); retArr.push(`return subKernelResult_${ this.name };`); } else { retArr.push('return '); this.astGeneric(ast.argument, retArr); retArr.push(';'); } return retArr; } astLiteral(ast, retArr) { if (isNaN(ast.value)) { throw this.astErrorOutput( 'Non-numeric literal not supported : ' + ast.value, ast ); } retArr.push(ast.value); return retArr; } astBinaryExpression(ast, retArr) { retArr.push('('); this.astGeneric(ast.left, retArr); retArr.push(ast.operator); this.astGeneric(ast.right, retArr); retArr.push(')'); return retArr; } astIdentifierExpression(idtNode, retArr) { if (idtNode.type !== 'Identifier') { throw this.astErrorOutput( 'IdentifierExpression - not an Identifier', idtNode ); } switch (idtNode.name) { case 'Infinity': retArr.push('Infinity'); break; default: if (this.constants && this.constants.hasOwnProperty(idtNode.name)) { retArr.push('constants_' + idtNode.name); } else { retArr.push('user_' + idtNode.name); } } return retArr; } astForStatement(forNode, retArr) { if (forNode.type !== 'ForStatement') { throw this.astErrorOutput('Invalid for statement', forNode); } const initArr = []; const testArr = []; const updateArr = []; const bodyArr = []; let isSafe = null; if (forNode.init) { this.pushState('in-for-loop-init'); this.astGeneric(forNode.init, initArr); for (let i = 0; i < initArr.length; i++) { if (initArr[i].includes && initArr[i].includes(',')) { isSafe = false; } } this.popState('in-for-loop-init'); } else { isSafe = false; } if (forNode.test) { this.astGeneric(forNode.test, testArr); } else { isSafe = false; } if (forNode.update) { this.astGeneric(forNode.update, updateArr); } else { isSafe = false; } if (forNode.body) { this.pushState('loop-body'); this.astGeneric(forNode.body, bodyArr); this.popState('loop-body'); } if (isSafe === null) { isSafe = this.isSafe(forNode.init) && this.isSafe(forNode.test); } if (isSafe) { retArr.push(`for (${initArr.join('')};${testArr.join('')};${updateArr.join('')}){\n`); retArr.push(bodyArr.join('')); retArr.push('}\n'); } else { const iVariableName = this.getInternalVariableName('safeI'); if (initArr.length > 0) { retArr.push(initArr.join(''), ';\n'); } retArr.push(`for (let ${iVariableName}=0;${iVariableName} 0) { retArr.push(`if (!${testArr.join('')}) break;\n`); } retArr.push(bodyArr.join('')); retArr.push(`\n${updateArr.join('')};`); retArr.push('}\n'); } return retArr; } astWhileStatement(whileNode, retArr) { if (whileNode.type !== 'WhileStatement') { throw this.astErrorOutput( 'Invalid while statement', whileNode ); } retArr.push('for (let i = 0; i < LOOP_MAX; i++) {'); retArr.push('if ('); this.astGeneric(whileNode.test, retArr); retArr.push(') {\n'); this.astGeneric(whileNode.body, retArr); retArr.push('} else {\n'); retArr.push('break;\n'); retArr.push('}\n'); retArr.push('}\n'); return retArr; } astDoWhileStatement(doWhileNode, retArr) { if (doWhileNode.type !== 'DoWhileStatement') { throw this.astErrorOutput( 'Invalid while statement', doWhileNode ); } retArr.push('for (let i = 0; i < LOOP_MAX; i++) {'); this.astGeneric(doWhileNode.body, retArr); retArr.push('if (!'); this.astGeneric(doWhileNode.test, retArr); retArr.push(') {\n'); retArr.push('break;\n'); retArr.push('}\n'); retArr.push('}\n'); return retArr; } astAssignmentExpression(assNode, retArr) { const declaration = this.getDeclaration(assNode.left); if (declaration && !declaration.assignable) { throw this.astErrorOutput(`Variable ${assNode.left.name} is not assignable here`, assNode); } this.astGeneric(assNode.left, retArr); retArr.push(assNode.operator); this.astGeneric(assNode.right, retArr); return retArr; } astBlockStatement(bNode, retArr) { if (this.isState('loop-body')) { this.pushState('block-body'); for (let i = 0; i < bNode.body.length; i++) { this.astGeneric(bNode.body[i], retArr); } this.popState('block-body'); } else { retArr.push('{\n'); for (let i = 0; i < bNode.body.length; i++) { this.astGeneric(bNode.body[i], retArr); } retArr.push('}\n'); } return retArr; } astVariableDeclaration(varDecNode, retArr) { retArr.push(`${varDecNode.kind} `); const { declarations } = varDecNode; for (let i = 0; i < declarations.length; i++) { if (i > 0) { retArr.push(','); } const declaration = declarations[i]; const info = this.getDeclaration(declaration.id); if (!info.valueType) { info.valueType = this.getType(declaration.init); } this.astGeneric(declaration, retArr); } if (!this.isState('in-for-loop-init')) { retArr.push(';'); } return retArr; } astIfStatement(ifNode, retArr) { retArr.push('if ('); this.astGeneric(ifNode.test, retArr); retArr.push(')'); if (ifNode.consequent.type === 'BlockStatement') { this.astGeneric(ifNode.consequent, retArr); } else { retArr.push(' {\n'); this.astGeneric(ifNode.consequent, retArr); retArr.push('\n}\n'); } if (ifNode.alternate) { retArr.push('else '); if (ifNode.alternate.type === 'BlockStatement' || ifNode.alternate.type === 'IfStatement') { this.astGeneric(ifNode.alternate, retArr); } else { retArr.push(' {\n'); this.astGeneric(ifNode.alternate, retArr); retArr.push('\n}\n'); } } return retArr; } astSwitchStatement(ast, retArr) { const { discriminant, cases } = ast; retArr.push('switch ('); this.astGeneric(discriminant, retArr); retArr.push(') {\n'); for (let i = 0; i < cases.length; i++) { if (cases[i].test === null) { retArr.push('default:\n'); this.astGeneric(cases[i].consequent, retArr); if (cases[i].consequent && cases[i].consequent.length > 0) { retArr.push('break;\n'); } continue; } retArr.push('case '); this.astGeneric(cases[i].test, retArr); retArr.push(':\n'); if (cases[i].consequent && cases[i].consequent.length > 0) { this.astGeneric(cases[i].consequent, retArr); retArr.push('break;\n'); } } retArr.push('\n}'); } astThisExpression(tNode, retArr) { retArr.push('_this'); return retArr; } astMemberExpression(mNode, retArr) { const { signature, type, property, xProperty, yProperty, zProperty, name, origin } = this.getMemberExpressionDetails(mNode); switch (signature) { case 'this.thread.value': retArr.push(`_this.thread.${ name }`); return retArr; case 'this.output.value': switch (name) { case 'x': retArr.push('outputX'); break; case 'y': retArr.push('outputY'); break; case 'z': retArr.push('outputZ'); break; default: throw this.astErrorOutput('Unexpected expression', mNode); } return retArr; case 'value': throw this.astErrorOutput('Unexpected expression', mNode); case 'value[]': case 'value[][]': case 'value[][][]': case 'value.value': if (origin === 'Math') { retArr.push(Math[name]); return retArr; } switch (property) { case 'r': retArr.push(`user_${ name }[0]`); return retArr; case 'g': retArr.push(`user_${ name }[1]`); return retArr; case 'b': retArr.push(`user_${ name }[2]`); return retArr; case 'a': retArr.push(`user_${ name }[3]`); return retArr; } break; case 'this.constants.value': case 'this.constants.value[]': case 'this.constants.value[][]': case 'this.constants.value[][][]': break; case 'fn()[]': this.astGeneric(mNode.object, retArr); retArr.push('['); this.astGeneric(mNode.property, retArr); retArr.push(']'); return retArr; case 'fn()[][]': this.astGeneric(mNode.object.object, retArr); retArr.push('['); this.astGeneric(mNode.object.property, retArr); retArr.push(']'); retArr.push('['); this.astGeneric(mNode.property, retArr); retArr.push(']'); return retArr; default: throw this.astErrorOutput('Unexpected expression', mNode); } if (!mNode.computed) { switch (type) { case 'Number': case 'Integer': case 'Float': case 'Boolean': retArr.push(`${origin}_${name}`); return retArr; } } const markupName = `${origin}_${name}`; switch (type) { case 'Array(2)': case 'Array(3)': case 'Array(4)': case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': case 'HTMLImageArray': case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': case 'HTMLImage': default: let size; let isInput; if (origin === 'constants') { const constant = this.constants[name]; isInput = this.constantTypes[name] === 'Input'; size = isInput ? constant.size : null; } else { isInput = this.isInput(name); size = isInput ? this.argumentSizes[this.argumentNames.indexOf(name)] : null; } retArr.push(`${ markupName }`); if (zProperty && yProperty) { if (isInput) { retArr.push('[('); this.astGeneric(zProperty, retArr); retArr.push(`*${ this.dynamicArguments ? '(outputY * outputX)' : size[1] * size[0] })+(`); this.astGeneric(yProperty, retArr); retArr.push(`*${ this.dynamicArguments ? 'outputX' : size[0] })+`); this.astGeneric(xProperty, retArr); retArr.push(']'); } else { retArr.push('['); this.astGeneric(zProperty, retArr); retArr.push(']'); retArr.push('['); this.astGeneric(yProperty, retArr); retArr.push(']'); retArr.push('['); this.astGeneric(xProperty, retArr); retArr.push(']'); } } else if (yProperty) { if (isInput) { retArr.push('[('); this.astGeneric(yProperty, retArr); retArr.push(`*${ this.dynamicArguments ? 'outputX' : size[0] })+`); this.astGeneric(xProperty, retArr); retArr.push(']'); } else { retArr.push('['); this.astGeneric(yProperty, retArr); retArr.push(']'); retArr.push('['); this.astGeneric(xProperty, retArr); retArr.push(']'); } } else if (typeof xProperty !== 'undefined') { retArr.push('['); this.astGeneric(xProperty, retArr); retArr.push(']'); } } return retArr; } astCallExpression(ast, retArr) { if (ast.type !== 'CallExpression') { throw this.astErrorOutput('Unknown CallExpression', ast); } let functionName = this.astMemberExpressionUnroll(ast.callee); if (this.calledFunctions.indexOf(functionName) < 0) { this.calledFunctions.push(functionName); } const isMathFunction = this.isAstMathFunction(ast); if (this.onFunctionCall) { this.onFunctionCall(this.name, functionName, ast.arguments); } retArr.push(functionName); retArr.push('('); const targetTypes = this.lookupFunctionArgumentTypes(functionName) || []; for (let i = 0; i < ast.arguments.length; ++i) { const argument = ast.arguments[i]; let argumentType = this.getType(argument); if (!targetTypes[i]) { this.triggerImplyArgumentType(functionName, i, argumentType, this); } if (i > 0) { retArr.push(', '); } this.astGeneric(argument, retArr); } retArr.push(')'); return retArr; } astArrayExpression(arrNode, retArr) { const returnType = this.getType(arrNode); const arrLen = arrNode.elements.length; const elements = []; for (let i = 0; i < arrLen; ++i) { const element = []; this.astGeneric(arrNode.elements[i], element); elements.push(element.join('')); } switch (returnType) { case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': retArr.push(`[${elements.join(', ')}]`); break; default: retArr.push(`new Float32Array([${elements.join(', ')}])`); } return retArr; } astDebuggerStatement(arrNode, retArr) { retArr.push('debugger;'); return retArr; } } module.exports = { CPUFunctionNode }; },{"../function-node":10}],7:[function(require,module,exports){ const { utils } = require('../../utils'); function constantsToString(constants, types) { const results = []; for (const name in types) { if (!types.hasOwnProperty(name)) continue; const type = types[name]; const constant = constants[name]; switch (type) { case 'Number': case 'Integer': case 'Float': case 'Boolean': results.push(`${name}:${constant}`); break; case 'Array(2)': case 'Array(3)': case 'Array(4)': case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': results.push(`${name}:new ${constant.constructor.name}(${JSON.stringify(Array.from(constant))})`); break; } } return `{ ${ results.join() } }`; } function cpuKernelString(cpuKernel, name) { const header = []; const thisProperties = []; const beforeReturn = []; const useFunctionKeyword = !/^function/.test(cpuKernel.color.toString()); header.push( ' const { context, canvas, constants: incomingConstants } = settings;', ` const output = new Int32Array(${JSON.stringify(Array.from(cpuKernel.output))});`, ` const _constantTypes = ${JSON.stringify(cpuKernel.constantTypes)};`, ` const _constants = ${constantsToString(cpuKernel.constants, cpuKernel.constantTypes)};` ); thisProperties.push( ' constants: _constants,', ' context,', ' output,', ' thread: {x: 0, y: 0, z: 0},' ); if (cpuKernel.graphical) { header.push(` const _imageData = context.createImageData(${cpuKernel.output[0]}, ${cpuKernel.output[1]});`); header.push(` const _colorData = new Uint8ClampedArray(${cpuKernel.output[0]} * ${cpuKernel.output[1]} * 4);`); const colorFn = utils.flattenFunctionToString((useFunctionKeyword ? 'function ' : '') + cpuKernel.color.toString(), { thisLookup: (propertyName) => { switch (propertyName) { case '_colorData': return '_colorData'; case '_imageData': return '_imageData'; case 'output': return 'output'; case 'thread': return 'this.thread'; } return JSON.stringify(cpuKernel[propertyName]); }, findDependency: (object, name) => { return null; } }); const getPixelsFn = utils.flattenFunctionToString((useFunctionKeyword ? 'function ' : '') + cpuKernel.getPixels.toString(), { thisLookup: (propertyName) => { switch (propertyName) { case '_colorData': return '_colorData'; case '_imageData': return '_imageData'; case 'output': return 'output'; case 'thread': return 'this.thread'; } return JSON.stringify(cpuKernel[propertyName]); }, findDependency: () => { return null; } }); thisProperties.push( ' _imageData,', ' _colorData,', ` color: ${colorFn},` ); beforeReturn.push( ` kernel.getPixels = ${getPixelsFn};` ); } const constantTypes = []; const constantKeys = Object.keys(cpuKernel.constantTypes); for (let i = 0; i < constantKeys.length; i++) { constantTypes.push(cpuKernel.constantTypes[constantKeys]); } if (cpuKernel.argumentTypes.indexOf('HTMLImageArray') !== -1 || constantTypes.indexOf('HTMLImageArray') !== -1) { const flattenedImageTo3DArray = utils.flattenFunctionToString((useFunctionKeyword ? 'function ' : '') + cpuKernel._imageTo3DArray.toString(), { doNotDefine: ['canvas'], findDependency: (object, name) => { if (object === 'this') { return (useFunctionKeyword ? 'function ' : '') + cpuKernel[name].toString(); } return null; }, thisLookup: (propertyName) => { switch (propertyName) { case 'canvas': return; case 'context': return 'context'; } } }); beforeReturn.push(flattenedImageTo3DArray); thisProperties.push(` _mediaTo2DArray,`); thisProperties.push(` _imageTo3DArray,`); } else if (cpuKernel.argumentTypes.indexOf('HTMLImage') !== -1 || constantTypes.indexOf('HTMLImage') !== -1) { const flattenedImageTo2DArray = utils.flattenFunctionToString((useFunctionKeyword ? 'function ' : '') + cpuKernel._mediaTo2DArray.toString(), { findDependency: (object, name) => { return null; }, thisLookup: (propertyName) => { switch (propertyName) { case 'canvas': return 'settings.canvas'; case 'context': return 'settings.context'; } throw new Error('unhandled thisLookup'); } }); beforeReturn.push(flattenedImageTo2DArray); thisProperties.push(` _mediaTo2DArray,`); } return `function(settings) { ${ header.join('\n') } for (const p in _constantTypes) { if (!_constantTypes.hasOwnProperty(p)) continue; const type = _constantTypes[p]; switch (type) { case 'Number': case 'Integer': case 'Float': case 'Boolean': case 'Array(2)': case 'Array(3)': case 'Array(4)': case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': if (incomingConstants.hasOwnProperty(p)) { console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned'); } continue; } if (!incomingConstants.hasOwnProperty(p)) { throw new Error('constant ' + p + ' not found'); } _constants[p] = incomingConstants[p]; } const kernel = (function() { ${cpuKernel._kernelString} }) .apply({ ${thisProperties.join('\n')} }); ${ beforeReturn.join('\n') } return kernel; }`; } module.exports = { cpuKernelString }; },{"../../utils":114}],8:[function(require,module,exports){ const { Kernel } = require('../kernel'); const { FunctionBuilder } = require('../function-builder'); const { CPUFunctionNode } = require('./function-node'); const { utils } = require('../../utils'); const { cpuKernelString } = require('./kernel-string'); class CPUKernel extends Kernel { static getFeatures() { return this.features; } static get features() { return Object.freeze({ kernelMap: true, isIntegerDivisionAccurate: true }); } static get isSupported() { return true; } static isContextMatch(context) { return false; } static get mode() { return 'cpu'; } static nativeFunctionArguments() { return null; } static nativeFunctionReturnType() { throw new Error(`Looking up native function return type not supported on ${this.name}`); } static combineKernels(combinedKernel) { return combinedKernel; } static getSignature(kernel, argumentTypes) { return 'cpu' + (argumentTypes.length > 0 ? ':' + argumentTypes.join(',') : ''); } constructor(source, settings) { super(source, settings); this.mergeSettings(source.settings || settings); this._imageData = null; this._colorData = null; this._kernelString = null; this._prependedString = []; this.thread = { x: 0, y: 0, z: 0 }; this.translatedSources = null; } initCanvas() { if (typeof document !== 'undefined') { return document.createElement('canvas'); } else if (typeof OffscreenCanvas !== 'undefined') { return new OffscreenCanvas(0, 0); } } initContext() { if (!this.canvas) return null; return this.canvas.getContext('2d'); } initPlugins(settings) { return []; } validateSettings(args) { if (!this.output || this.output.length === 0) { if (args.length !== 1) { throw new Error('Auto output only supported for kernels with only one input'); } const argType = utils.getVariableType(args[0], this.strictIntegers); if (argType === 'Array') { this.output = utils.getDimensions(argType); } else if (argType === 'NumberTexture' || argType === 'ArrayTexture(4)') { this.output = args[0].output; } else { throw new Error('Auto output not supported for input type: ' + argType); } } if (this.graphical) { if (this.output.length !== 2) { throw new Error('Output must have 2 dimensions on graphical mode'); } } this.checkOutput(); } translateSource() { this.leadingReturnStatement = this.output.length > 1 ? 'resultX[x] = ' : 'result[x] = '; if (this.subKernels) { const followingReturnStatement = []; for (let i = 0; i < this.subKernels.length; i++) { const { name } = this.subKernels[i]; followingReturnStatement.push(this.output.length > 1 ? `resultX_${ name }[x] = subKernelResult_${ name };\n` : `result_${ name }[x] = subKernelResult_${ name };\n`); } this.followingReturnStatement = followingReturnStatement.join(''); } const functionBuilder = FunctionBuilder.fromKernel(this, CPUFunctionNode); this.translatedSources = functionBuilder.getPrototypes('kernel'); if (!this.graphical && !this.returnType) { this.returnType = functionBuilder.getKernelResultType(); } } build() { if (this.built) return; this.setupConstants(); this.setupArguments(arguments); this.validateSettings(arguments); this.translateSource(); if (this.graphical) { const { canvas, output } = this; if (!canvas) { throw new Error('no canvas available for using graphical output'); } const width = output[0]; const height = output[1] || 1; canvas.width = width; canvas.height = height; this._imageData = this.context.createImageData(width, height); this._colorData = new Uint8ClampedArray(width * height * 4); } const kernelString = this.getKernelString(); this.kernelString = kernelString; if (this.debug) { console.log('Function output:'); console.log(kernelString); } try { this.run = new Function([], kernelString).bind(this)(); } catch (e) { console.error('An error occurred compiling the javascript: ', e); } this.buildSignature(arguments); this.built = true; } color(r, g, b, a) { if (typeof a === 'undefined') { a = 1; } r = Math.floor(r * 255); g = Math.floor(g * 255); b = Math.floor(b * 255); a = Math.floor(a * 255); const width = this.output[0]; const height = this.output[1]; const x = this.thread.x; const y = height - this.thread.y - 1; const index = x + y * width; this._colorData[index * 4 + 0] = r; this._colorData[index * 4 + 1] = g; this._colorData[index * 4 + 2] = b; this._colorData[index * 4 + 3] = a; } getKernelString() { if (this._kernelString !== null) return this._kernelString; let kernelThreadString = null; let { translatedSources } = this; if (translatedSources.length > 1) { translatedSources = translatedSources.filter(fn => { if (/^function/.test(fn)) return fn; kernelThreadString = fn; return false; }); } else { kernelThreadString = translatedSources.shift(); } return this._kernelString = ` const LOOP_MAX = ${ this._getLoopMaxString() }; ${ this.injectedNative || '' } const _this = this; ${ this._resultKernelHeader() } ${ this._processConstants() } return (${ this.argumentNames.map(argumentName => 'user_' + argumentName).join(', ') }) => { ${ this._prependedString.join('') } ${ this._earlyThrows() } ${ this._processArguments() } ${ this.graphical ? this._graphicalKernelBody(kernelThreadString) : this._resultKernelBody(kernelThreadString) } ${ translatedSources.length > 0 ? translatedSources.join('\n') : '' } };`; } toString() { return cpuKernelString(this); } _getLoopMaxString() { return ( this.loopMaxIterations ? ` ${ parseInt(this.loopMaxIterations) };` : ' 1000;' ); } _processConstants() { if (!this.constants) return ''; const result = []; for (let p in this.constants) { const type = this.constantTypes[p]; switch (type) { case 'HTMLCanvas': case 'OffscreenCanvas': case 'HTMLImage': case 'ImageBitmap': case 'ImageData': case 'HTMLVideo': result.push(` const constants_${p} = this._mediaTo2DArray(this.constants.${p});\n`); break; case 'HTMLImageArray': result.push(` const constants_${p} = this._imageTo3DArray(this.constants.${p});\n`); break; case 'Input': result.push(` const constants_${p} = this.constants.${p}.value;\n`); break; default: result.push(` const constants_${p} = this.constants.${p};\n`); } } return result.join(''); } _earlyThrows() { if (this.graphical) return ''; if (this.immutable) return ''; if (!this.pipeline) return ''; const arrayArguments = []; for (let i = 0; i < this.argumentTypes.length; i++) { if (this.argumentTypes[i] === 'Array') { arrayArguments.push(this.argumentNames[i]); } } if (arrayArguments.length === 0) return ''; const checks = []; for (let i = 0; i < arrayArguments.length; i++) { const argumentName = arrayArguments[i]; const checkSubKernels = this._mapSubKernels(subKernel => `user_${argumentName} === result_${subKernel.name}`).join(' || '); checks.push(`user_${argumentName} === result${checkSubKernels ? ` || ${checkSubKernels}` : ''}`); } return `if (${checks.join(' || ')}) throw new Error('Source and destination arrays are the same. Use immutable = true');`; } _processArguments() { const result = []; for (let i = 0; i < this.argumentTypes.length; i++) { const variableName = `user_${this.argumentNames[i]}`; switch (this.argumentTypes[i]) { case 'HTMLCanvas': case 'OffscreenCanvas': case 'HTMLImage': case 'ImageBitmap': case 'ImageData': case 'HTMLVideo': result.push(` ${variableName} = this._mediaTo2DArray(${variableName});\n`); break; case 'HTMLImageArray': result.push(` ${variableName} = this._imageTo3DArray(${variableName});\n`); break; case 'Input': result.push(` ${variableName} = ${variableName}.value;\n`); break; case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': case 'NumberTexture': case 'MemoryOptimizedNumberTexture': result.push(` if (${variableName}.toArray) { if (!_this.textureCache) { _this.textureCache = []; _this.arrayCache = []; } const textureIndex = _this.textureCache.indexOf(${variableName}); if (textureIndex !== -1) { ${variableName} = _this.arrayCache[textureIndex]; } else { _this.textureCache.push(${variableName}); ${variableName} = ${variableName}.toArray(); _this.arrayCache.push(${variableName}); } }`); break; } } return result.join(''); } _mediaTo2DArray(media) { const canvas = this.canvas; const width = media.width > 0 ? media.width : media.videoWidth; const height = media.height > 0 ? media.height : media.videoHeight; if (canvas.width < width) { canvas.width = width; } if (canvas.height < height) { canvas.height = height; } const ctx = this.context; let pixelsData; if (media.constructor === ImageData) { pixelsData = media.data; } else { ctx.drawImage(media, 0, 0, width, height); pixelsData = ctx.getImageData(0, 0, width, height).data; } const imageArray = new Array(height); let index = 0; for (let y = height - 1; y >= 0; y--) { const row = imageArray[y] = new Array(width); for (let x = 0; x < width; x++) { const pixel = new Float32Array(4); pixel[0] = pixelsData[index++] / 255; pixel[1] = pixelsData[index++] / 255; pixel[2] = pixelsData[index++] / 255; pixel[3] = pixelsData[index++] / 255; row[x] = pixel; } } return imageArray; } getPixels(flip) { const [width, height] = this.output; return flip ? utils.flipPixels(this._imageData.data, width, height) : this._imageData.data.slice(0); } _imageTo3DArray(images) { const imagesArray = new Array(images.length); for (let i = 0; i < images.length; i++) { imagesArray[i] = this._mediaTo2DArray(images[i]); } return imagesArray; } _resultKernelHeader() { if (this.graphical) return ''; if (this.immutable) return ''; if (!this.pipeline) return ''; switch (this.output.length) { case 1: return this._mutableKernel1DResults(); case 2: return this._mutableKernel2DResults(); case 3: return this._mutableKernel3DResults(); } } _resultKernelBody(kernelString) { switch (this.output.length) { case 1: return (!this.immutable && this.pipeline ? this._resultMutableKernel1DLoop(kernelString) : this._resultImmutableKernel1DLoop(kernelString)) + this._kernelOutput(); case 2: return (!this.immutable && this.pipeline ? this._resultMutableKernel2DLoop(kernelString) : this._resultImmutableKernel2DLoop(kernelString)) + this._kernelOutput(); case 3: return (!this.immutable && this.pipeline ? this._resultMutableKernel3DLoop(kernelString) : this._resultImmutableKernel3DLoop(kernelString)) + this._kernelOutput(); default: throw new Error('unsupported size kernel'); } } _graphicalKernelBody(kernelThreadString) { switch (this.output.length) { case 2: return this._graphicalKernel2DLoop(kernelThreadString) + this._graphicalOutput(); default: throw new Error('unsupported size kernel'); } } _graphicalOutput() { return ` this._imageData.data.set(this._colorData); this.context.putImageData(this._imageData, 0, 0); return;` } _getKernelResultTypeConstructorString() { switch (this.returnType) { case 'LiteralInteger': case 'Number': case 'Integer': case 'Float': return 'Float32Array'; case 'Array(2)': case 'Array(3)': case 'Array(4)': return 'Array'; default: if (this.graphical) { return 'Float32Array'; } throw new Error(`unhandled returnType ${ this.returnType }`); } } _resultImmutableKernel1DLoop(kernelString) { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const result = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new ${constructorString}(outputX);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') } for (let x = 0; x < outputX; x++) { this.thread.x = x; this.thread.y = 0; this.thread.z = 0; ${ kernelString } }`; } _mutableKernel1DResults() { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const result = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new ${constructorString}(outputX);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') }`; } _resultMutableKernel1DLoop(kernelString) { return ` const outputX = _this.output[0]; for (let x = 0; x < outputX; x++) { this.thread.x = x; this.thread.y = 0; this.thread.z = 0; ${ kernelString } }`; } _resultImmutableKernel2DLoop(kernelString) { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const outputY = _this.output[1]; const result = new Array(outputY); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new Array(outputY);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') } for (let y = 0; y < outputY; y++) { this.thread.z = 0; this.thread.y = y; const resultX = result[y] = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const resultX_${ subKernel.name } = result_${subKernel.name}[y] = new ${constructorString}(outputX);\n`).join('') } for (let x = 0; x < outputX; x++) { this.thread.x = x; ${ kernelString } } }`; } _mutableKernel2DResults() { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const outputY = _this.output[1]; const result = new Array(outputY); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new Array(outputY);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') } for (let y = 0; y < outputY; y++) { const resultX = result[y] = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const resultX_${ subKernel.name } = result_${subKernel.name}[y] = new ${constructorString}(outputX);\n`).join('') } }`; } _resultMutableKernel2DLoop(kernelString) { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const outputY = _this.output[1]; for (let y = 0; y < outputY; y++) { this.thread.z = 0; this.thread.y = y; const resultX = result[y]; ${ this._mapSubKernels(subKernel => `const resultX_${ subKernel.name } = result_${subKernel.name}[y] = new ${constructorString}(outputX);\n`).join('') } for (let x = 0; x < outputX; x++) { this.thread.x = x; ${ kernelString } } }`; } _graphicalKernel2DLoop(kernelString) { return ` const outputX = _this.output[0]; const outputY = _this.output[1]; for (let y = 0; y < outputY; y++) { this.thread.z = 0; this.thread.y = y; for (let x = 0; x < outputX; x++) { this.thread.x = x; ${ kernelString } } }`; } _resultImmutableKernel3DLoop(kernelString) { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const outputY = _this.output[1]; const outputZ = _this.output[2]; const result = new Array(outputZ); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new Array(outputZ);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') } for (let z = 0; z < outputZ; z++) { this.thread.z = z; const resultY = result[z] = new Array(outputY); ${ this._mapSubKernels(subKernel => `const resultY_${ subKernel.name } = result_${subKernel.name}[z] = new Array(outputY);\n`).join(' ') } for (let y = 0; y < outputY; y++) { this.thread.y = y; const resultX = resultY[y] = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const resultX_${ subKernel.name } = resultY_${subKernel.name}[y] = new ${constructorString}(outputX);\n`).join(' ') } for (let x = 0; x < outputX; x++) { this.thread.x = x; ${ kernelString } } } }`; } _mutableKernel3DResults() { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const outputY = _this.output[1]; const outputZ = _this.output[2]; const result = new Array(outputZ); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new Array(outputZ);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') } for (let z = 0; z < outputZ; z++) { const resultY = result[z] = new Array(outputY); ${ this._mapSubKernels(subKernel => `const resultY_${ subKernel.name } = result_${subKernel.name}[z] = new Array(outputY);\n`).join(' ') } for (let y = 0; y < outputY; y++) { const resultX = resultY[y] = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const resultX_${ subKernel.name } = resultY_${subKernel.name}[y] = new ${constructorString}(outputX);\n`).join(' ') } } }`; } _resultMutableKernel3DLoop(kernelString) { return ` const outputX = _this.output[0]; const outputY = _this.output[1]; const outputZ = _this.output[2]; for (let z = 0; z < outputZ; z++) { this.thread.z = z; const resultY = result[z]; for (let y = 0; y < outputY; y++) { this.thread.y = y; const resultX = resultY[y]; for (let x = 0; x < outputX; x++) { this.thread.x = x; ${ kernelString } } } }`; } _kernelOutput() { if (!this.subKernels) { return '\n return result;'; } return `\n return { result: result, ${ this.subKernels.map(subKernel => `${ subKernel.property }: result_${ subKernel.name }`).join(',\n ') } };`; } _mapSubKernels(fn) { return this.subKernels === null ? [''] : this.subKernels.map(fn); } destroy(removeCanvasReference) { if (removeCanvasReference) { delete this.canvas; } } static destroyContext(context) {} toJSON() { const json = super.toJSON(); json.functionNodes = FunctionBuilder.fromKernel(this, CPUFunctionNode).toJSON(); return json; } setOutput(output) { super.setOutput(output); const [width, height] = this.output; if (this.graphical) { this._imageData = this.context.createImageData(width, height); this._colorData = new Uint8ClampedArray(width * height * 4); } } prependString(value) { if (this._kernelString) throw new Error('Kernel already built'); this._prependedString.push(value); } hasPrependString(value) { return this._prependedString.indexOf(value) > -1; } } module.exports = { CPUKernel }; },{"../../utils":114,"../function-builder":9,"../kernel":36,"./function-node":6,"./kernel-string":7}],9:[function(require,module,exports){ class FunctionBuilder { static fromKernel(kernel, FunctionNode, extraNodeOptions) { const { kernelArguments, kernelConstants, argumentNames, argumentSizes, argumentBitRatios, constants, constantBitRatios, debug, loopMaxIterations, nativeFunctions, output, optimizeFloatMemory, precision, plugins, source, subKernels, functions, leadingReturnStatement, followingReturnStatement, dynamicArguments, dynamicOutput, } = kernel; const argumentTypes = new Array(kernelArguments.length); const constantTypes = {}; for (let i = 0; i < kernelArguments.length; i++) { argumentTypes[i] = kernelArguments[i].type; } for (let i = 0; i < kernelConstants.length; i++) { const kernelConstant = kernelConstants[i]; constantTypes[kernelConstant.name] = kernelConstant.type; } const needsArgumentType = (functionName, index) => { return functionBuilder.needsArgumentType(functionName, index); }; const assignArgumentType = (functionName, index, type) => { functionBuilder.assignArgumentType(functionName, index, type); }; const lookupReturnType = (functionName, ast, requestingNode) => { return functionBuilder.lookupReturnType(functionName, ast, requestingNode); }; const lookupFunctionArgumentTypes = (functionName) => { return functionBuilder.lookupFunctionArgumentTypes(functionName); }; const lookupFunctionArgumentName = (functionName, argumentIndex) => { return functionBuilder.lookupFunctionArgumentName(functionName, argumentIndex); }; const lookupFunctionArgumentBitRatio = (functionName, argumentName) => { return functionBuilder.lookupFunctionArgumentBitRatio(functionName, argumentName); }; const triggerImplyArgumentType = (functionName, i, argumentType, requestingNode) => { functionBuilder.assignArgumentType(functionName, i, argumentType, requestingNode); }; const triggerImplyArgumentBitRatio = (functionName, argumentName, calleeFunctionName, argumentIndex) => { functionBuilder.assignArgumentBitRatio(functionName, argumentName, calleeFunctionName, argumentIndex); }; const onFunctionCall = (functionName, calleeFunctionName, args) => { functionBuilder.trackFunctionCall(functionName, calleeFunctionName, args); }; const onNestedFunction = (ast, source) => { const argumentNames = []; for (let i = 0; i < ast.params.length; i++) { argumentNames.push(ast.params[i].name); } const nestedFunction = new FunctionNode(source, Object.assign({}, nodeOptions, { returnType: null, ast, name: ast.id.name, argumentNames, lookupReturnType, lookupFunctionArgumentTypes, lookupFunctionArgumentName, lookupFunctionArgumentBitRatio, needsArgumentType, assignArgumentType, triggerImplyArgumentType, triggerImplyArgumentBitRatio, onFunctionCall, })); nestedFunction.traceFunctionAST(ast); functionBuilder.addFunctionNode(nestedFunction); }; const nodeOptions = Object.assign({ isRootKernel: false, onNestedFunction, lookupReturnType, lookupFunctionArgumentTypes, lookupFunctionArgumentName, lookupFunctionArgumentBitRatio, needsArgumentType, assignArgumentType, triggerImplyArgumentType, triggerImplyArgumentBitRatio, onFunctionCall, optimizeFloatMemory, precision, constants, constantTypes, constantBitRatios, debug, loopMaxIterations, output, plugins, dynamicArguments, dynamicOutput, }, extraNodeOptions || {}); const rootNodeOptions = Object.assign({}, nodeOptions, { isRootKernel: true, name: 'kernel', argumentNames, argumentTypes, argumentSizes, argumentBitRatios, leadingReturnStatement, followingReturnStatement, }); if (typeof source === 'object' && source.functionNodes) { return new FunctionBuilder().fromJSON(source.functionNodes, FunctionNode); } const rootNode = new FunctionNode(source, rootNodeOptions); let functionNodes = null; if (functions) { functionNodes = functions.map((fn) => new FunctionNode(fn.source, { returnType: fn.returnType, argumentTypes: fn.argumentTypes, output, plugins, constants, constantTypes, constantBitRatios, optimizeFloatMemory, precision, lookupReturnType, lookupFunctionArgumentTypes, lookupFunctionArgumentName, lookupFunctionArgumentBitRatio, needsArgumentType, assignArgumentType, triggerImplyArgumentType, triggerImplyArgumentBitRatio, onFunctionCall, onNestedFunction, })); } let subKernelNodes = null; if (subKernels) { subKernelNodes = subKernels.map((subKernel) => { const { name, source } = subKernel; return new FunctionNode(source, Object.assign({}, nodeOptions, { name, isSubKernel: true, isRootKernel: false, })); }); } const functionBuilder = new FunctionBuilder({ kernel, rootNode, functionNodes, nativeFunctions, subKernelNodes }); return functionBuilder; } constructor(settings) { settings = settings || {}; this.kernel = settings.kernel; this.rootNode = settings.rootNode; this.functionNodes = settings.functionNodes || []; this.subKernelNodes = settings.subKernelNodes || []; this.nativeFunctions = settings.nativeFunctions || []; this.functionMap = {}; this.nativeFunctionNames = []; this.lookupChain = []; this.functionNodeDependencies = {}; this.functionCalls = {}; if (this.rootNode) { this.functionMap['kernel'] = this.rootNode; } if (this.functionNodes) { for (let i = 0; i < this.functionNodes.length; i++) { this.functionMap[this.functionNodes[i].name] = this.functionNodes[i]; } } if (this.subKernelNodes) { for (let i = 0; i < this.subKernelNodes.length; i++) { this.functionMap[this.subKernelNodes[i].name] = this.subKernelNodes[i]; } } if (this.nativeFunctions) { for (let i = 0; i < this.nativeFunctions.length; i++) { const nativeFunction = this.nativeFunctions[i]; this.nativeFunctionNames.push(nativeFunction.name); } } } addFunctionNode(functionNode) { if (!functionNode.name) throw new Error('functionNode.name needs set'); this.functionMap[functionNode.name] = functionNode; if (functionNode.isRootKernel) { this.rootNode = functionNode; } } traceFunctionCalls(functionName, retList) { functionName = functionName || 'kernel'; retList = retList || []; if (this.nativeFunctionNames.indexOf(functionName) > -1) { const nativeFunctionIndex = retList.indexOf(functionName); if (nativeFunctionIndex === -1) { retList.push(functionName); } else { const dependantNativeFunctionName = retList.splice(nativeFunctionIndex, 1)[0]; retList.push(dependantNativeFunctionName); } return retList; } const functionNode = this.functionMap[functionName]; if (functionNode) { const functionIndex = retList.indexOf(functionName); if (functionIndex === -1) { retList.push(functionName); functionNode.toString(); for (let i = 0; i < functionNode.calledFunctions.length; ++i) { this.traceFunctionCalls(functionNode.calledFunctions[i], retList); } } else { const dependantFunctionName = retList.splice(functionIndex, 1)[0]; retList.push(dependantFunctionName); } } return retList; } getPrototypeString(functionName) { return this.getPrototypes(functionName).join('\n'); } getPrototypes(functionName) { if (this.rootNode) { this.rootNode.toString(); } if (functionName) { return this.getPrototypesFromFunctionNames(this.traceFunctionCalls(functionName, []).reverse()); } return this.getPrototypesFromFunctionNames(Object.keys(this.functionMap)); } getStringFromFunctionNames(functionList) { const ret = []; for (let i = 0; i < functionList.length; ++i) { const node = this.functionMap[functionList[i]]; if (node) { ret.push(this.functionMap[functionList[i]].toString()); } } return ret.join('\n'); } getPrototypesFromFunctionNames(functionList) { const ret = []; for (let i = 0; i < functionList.length; ++i) { const functionName = functionList[i]; const functionIndex = this.nativeFunctionNames.indexOf(functionName); if (functionIndex > -1) { ret.push(this.nativeFunctions[functionIndex].source); continue; } const node = this.functionMap[functionName]; if (node) { ret.push(node.toString()); } } return ret; } toJSON() { return this.traceFunctionCalls(this.rootNode.name).reverse().map(name => { const nativeIndex = this.nativeFunctions.indexOf(name); if (nativeIndex > -1) { return { name, source: this.nativeFunctions[nativeIndex].source }; } else if (this.functionMap[name]) { return this.functionMap[name].toJSON(); } else { throw new Error(`function ${ name } not found`); } }); } fromJSON(jsonFunctionNodes, FunctionNode) { this.functionMap = {}; for (let i = 0; i < jsonFunctionNodes.length; i++) { const jsonFunctionNode = jsonFunctionNodes[i]; this.functionMap[jsonFunctionNode.settings.name] = new FunctionNode(jsonFunctionNode.ast, jsonFunctionNode.settings); } return this; } getString(functionName) { if (functionName) { return this.getStringFromFunctionNames(this.traceFunctionCalls(functionName).reverse()); } return this.getStringFromFunctionNames(Object.keys(this.functionMap)); } lookupReturnType(functionName, ast, requestingNode) { if (ast.type !== 'CallExpression') { throw new Error(`expected ast type of "CallExpression", but is ${ ast.type }`); } if (this._isNativeFunction(functionName)) { return this._lookupNativeFunctionReturnType(functionName); } else if (this._isFunction(functionName)) { const node = this._getFunction(functionName); if (node.returnType) { return node.returnType; } else { for (let i = 0; i < this.lookupChain.length; i++) { if (this.lookupChain[i].ast === ast) { if (node.argumentTypes.length === 0 && ast.arguments.length > 0) { const args = ast.arguments; for (let j = 0; j < args.length; j++) { this.lookupChain.push({ name: requestingNode.name, ast: args[i], requestingNode }); node.argumentTypes[j] = requestingNode.getType(args[j]); this.lookupChain.pop(); } return node.returnType = node.getType(node.getJsAST()); } throw new Error('circlical logic detected!'); } } this.lookupChain.push({ name: requestingNode.name, ast, requestingNode }); const type = node.getType(node.getJsAST()); this.lookupChain.pop(); return node.returnType = type; } } return null; } _getFunction(functionName) { if (!this._isFunction(functionName)) { new Error(`Function ${functionName} not found`); } return this.functionMap[functionName]; } _isFunction(functionName) { return Boolean(this.functionMap[functionName]); } _getNativeFunction(functionName) { for (let i = 0; i < this.nativeFunctions.length; i++) { if (this.nativeFunctions[i].name === functionName) return this.nativeFunctions[i]; } return null; } _isNativeFunction(functionName) { return Boolean(this._getNativeFunction(functionName)); } _lookupNativeFunctionReturnType(functionName) { let nativeFunction = this._getNativeFunction(functionName); if (nativeFunction) { return nativeFunction.returnType; } throw new Error(`Native function ${ functionName } not found`); } lookupFunctionArgumentTypes(functionName) { if (this._isNativeFunction(functionName)) { return this._getNativeFunction(functionName).argumentTypes; } else if (this._isFunction(functionName)) { return this._getFunction(functionName).argumentTypes; } return null; } lookupFunctionArgumentName(functionName, argumentIndex) { return this._getFunction(functionName).argumentNames[argumentIndex]; } lookupFunctionArgumentBitRatio(functionName, argumentName) { if (!this._isFunction(functionName)) { throw new Error('function not found'); } if (this.rootNode.name === functionName) { const i = this.rootNode.argumentNames.indexOf(argumentName); if (i !== -1) { return this.rootNode.argumentBitRatios[i]; } } const node = this._getFunction(functionName); const i = node.argumentNames.indexOf(argumentName); if (i === -1) { throw new Error('argument not found'); } const bitRatio = node.argumentBitRatios[i]; if (typeof bitRatio !== 'number') { throw new Error('argument bit ratio not found'); } return bitRatio; } needsArgumentType(functionName, i) { if (!this._isFunction(functionName)) return false; const fnNode = this._getFunction(functionName); return !fnNode.argumentTypes[i]; } assignArgumentType(functionName, i, argumentType, requestingNode) { if (!this._isFunction(functionName)) return; const fnNode = this._getFunction(functionName); if (!fnNode.argumentTypes[i]) { fnNode.argumentTypes[i] = argumentType; } } assignArgumentBitRatio(functionName, argumentName, calleeFunctionName, argumentIndex) { const node = this._getFunction(functionName); if (this._isNativeFunction(calleeFunctionName)) return null; const calleeNode = this._getFunction(calleeFunctionName); const i = node.argumentNames.indexOf(argumentName); if (i === -1) { throw new Error(`Argument ${argumentName} not found in arguments from function ${functionName}`); } const bitRatio = node.argumentBitRatios[i]; if (typeof bitRatio !== 'number') { throw new Error(`Bit ratio for argument ${argumentName} not found in function ${functionName}`); } if (!calleeNode.argumentBitRatios) { calleeNode.argumentBitRatios = new Array(calleeNode.argumentNames.length); } const calleeBitRatio = calleeNode.argumentBitRatios[i]; if (typeof calleeBitRatio === 'number') { if (calleeBitRatio !== bitRatio) { throw new Error(`Incompatible bit ratio found at function ${functionName} at argument ${argumentName}`); } return calleeBitRatio; } calleeNode.argumentBitRatios[i] = bitRatio; return bitRatio; } trackFunctionCall(functionName, calleeFunctionName, args) { if (!this.functionNodeDependencies[functionName]) { this.functionNodeDependencies[functionName] = new Set(); this.functionCalls[functionName] = []; } this.functionNodeDependencies[functionName].add(calleeFunctionName); this.functionCalls[functionName].push(args); } getKernelResultType() { return this.rootNode.returnType || this.rootNode.getType(this.rootNode.ast); } getSubKernelResultType(index) { const subKernelNode = this.subKernelNodes[index]; let called = false; for (let functionCallIndex = 0; functionCallIndex < this.rootNode.functionCalls.length; functionCallIndex++) { const functionCall = this.rootNode.functionCalls[functionCallIndex]; if (functionCall.ast.callee.name === subKernelNode.name) { called = true; } } if (!called) { throw new Error(`SubKernel ${ subKernelNode.name } never called by kernel`); } return subKernelNode.returnType || subKernelNode.getType(subKernelNode.getJsAST()); } getReturnTypes() { const result = { [this.rootNode.name]: this.rootNode.getType(this.rootNode.ast), }; const list = this.traceFunctionCalls(this.rootNode.name); for (let i = 0; i < list.length; i++) { const functionName = list[i]; const functionNode = this.functionMap[functionName]; result[functionName] = functionNode.getType(functionNode.ast); } return result; } } module.exports = { FunctionBuilder }; },{}],10:[function(require,module,exports){ const acorn = require('acorn'); const { utils } = require('../utils'); const { FunctionTracer } = require('./function-tracer'); class FunctionNode { constructor(source, settings) { if (!source && !settings.ast) { throw new Error('source parameter is missing'); } settings = settings || {}; this.source = source; this.ast = null; this.name = typeof source === 'string' ? settings.isRootKernel ? 'kernel' : (settings.name || utils.getFunctionNameFromString(source)) : null; this.calledFunctions = []; this.constants = {}; this.constantTypes = {}; this.constantBitRatios = {}; this.isRootKernel = false; this.isSubKernel = false; this.debug = null; this.functions = null; this.identifiers = null; this.contexts = null; this.functionCalls = null; this.states = []; this.needsArgumentType = null; this.assignArgumentType = null; this.lookupReturnType = null; this.lookupFunctionArgumentTypes = null; this.lookupFunctionArgumentBitRatio = null; this.triggerImplyArgumentType = null; this.triggerImplyArgumentBitRatio = null; this.onNestedFunction = null; this.onFunctionCall = null; this.optimizeFloatMemory = null; this.precision = null; this.loopMaxIterations = null; this.argumentNames = (typeof this.source === 'string' ? utils.getArgumentNamesFromString(this.source) : null); this.argumentTypes = []; this.argumentSizes = []; this.argumentBitRatios = null; this.returnType = null; this.output = []; this.plugins = null; this.leadingReturnStatement = null; this.followingReturnStatement = null; this.dynamicOutput = null; this.dynamicArguments = null; this.strictTypingChecking = false; this.fixIntegerDivisionAccuracy = null; if (settings) { for (const p in settings) { if (!settings.hasOwnProperty(p)) continue; if (!this.hasOwnProperty(p)) continue; this[p] = settings[p]; } } this.literalTypes = {}; this.validate(); this._string = null; this._internalVariableNames = {}; } validate() { if (typeof this.source !== 'string' && !this.ast) { throw new Error('this.source not a string'); } if (!this.ast && !utils.isFunctionString(this.source)) { throw new Error('this.source not a function string'); } if (!this.name) { throw new Error('this.name could not be set'); } if (this.argumentTypes.length > 0 && this.argumentTypes.length !== this.argumentNames.length) { throw new Error(`argumentTypes count of ${ this.argumentTypes.length } exceeds ${ this.argumentNames.length }`); } if (this.output.length < 1) { throw new Error('this.output is not big enough'); } } isIdentifierConstant(name) { if (!this.constants) return false; return this.constants.hasOwnProperty(name); } isInput(argumentName) { return this.argumentTypes[this.argumentNames.indexOf(argumentName)] === 'Input'; } pushState(state) { this.states.push(state); } popState(state) { if (this.state !== state) { throw new Error(`Cannot popState ${ state } when in ${ this.state }`); } this.states.pop(); } isState(state) { return this.state === state; } get state() { return this.states[this.states.length - 1]; } astMemberExpressionUnroll(ast) { if (ast.type === 'Identifier') { return ast.name; } else if (ast.type === 'ThisExpression') { return 'this'; } if (ast.type === 'MemberExpression') { if (ast.object && ast.property) { if (ast.object.hasOwnProperty('name') && ast.object.name !== 'Math') { return this.astMemberExpressionUnroll(ast.property); } return ( this.astMemberExpressionUnroll(ast.object) + '.' + this.astMemberExpressionUnroll(ast.property) ); } } if (ast.hasOwnProperty('expressions')) { const firstExpression = ast.expressions[0]; if (firstExpression.type === 'Literal' && firstExpression.value === 0 && ast.expressions.length === 2) { return this.astMemberExpressionUnroll(ast.expressions[1]); } } throw this.astErrorOutput('Unknown astMemberExpressionUnroll', ast); } getJsAST(inParser) { if (this.ast) { return this.ast; } if (typeof this.source === 'object') { this.traceFunctionAST(this.source); return this.ast = this.source; } inParser = inParser || acorn; if (inParser === null) { throw new Error('Missing JS to AST parser'); } const ast = Object.freeze(inParser.parse(`const parser_${ this.name } = ${ this.source };`, { locations: true })); const functionAST = ast.body[0].declarations[0].init; this.traceFunctionAST(functionAST); if (!ast) { throw new Error('Failed to parse JS code'); } return this.ast = functionAST; } traceFunctionAST(ast) { const { contexts, declarations, functions, identifiers, functionCalls } = new FunctionTracer(ast); this.contexts = contexts; this.identifiers = identifiers; this.functionCalls = functionCalls; this.functions = functions; for (let i = 0; i < declarations.length; i++) { const declaration = declarations[i]; const { ast, inForLoopInit, inForLoopTest } = declaration; const { init } = ast; const dependencies = this.getDependencies(init); let valueType = null; if (inForLoopInit && inForLoopTest) { valueType = 'Integer'; } else { if (init) { const realType = this.getType(init); switch (realType) { case 'Integer': case 'Float': case 'Number': if (init.type === 'MemberExpression') { valueType = realType; } else { valueType = 'Number'; } break; case 'LiteralInteger': valueType = 'Number'; break; default: valueType = realType; } } } declaration.valueType = valueType; declaration.dependencies = dependencies; declaration.isSafe = this.isSafeDependencies(dependencies); } for (let i = 0; i < functions.length; i++) { this.onNestedFunction(functions[i], this.source); } } getDeclaration(ast) { for (let i = 0; i < this.identifiers.length; i++) { const identifier = this.identifiers[i]; if (ast === identifier.ast) { return identifier.declaration; } } return null; } getVariableType(ast) { if (ast.type !== 'Identifier') { throw new Error(`ast of ${ast.type} not "Identifier"`); } let type = null; const argumentIndex = this.argumentNames.indexOf(ast.name); if (argumentIndex === -1) { const declaration = this.getDeclaration(ast); if (declaration) { return declaration.valueType; } } else { const argumentType = this.argumentTypes[argumentIndex]; if (argumentType) { type = argumentType; } } if (!type && this.strictTypingChecking) { throw new Error(`Declaration of ${name} not found`); } return type; } getLookupType(type) { if (!typeLookupMap.hasOwnProperty(type)) { throw new Error(`unknown typeLookupMap ${ type }`); } return typeLookupMap[type]; } getConstantType(constantName) { if (this.constantTypes[constantName]) { const type = this.constantTypes[constantName]; if (type === 'Float') { return 'Number'; } else { return type; } } throw new Error(`Type for constant "${ constantName }" not declared`); } toString() { if (this._string) return this._string; return this._string = this.astGeneric(this.getJsAST(), []).join('').trim(); } toJSON() { const settings = { source: this.source, name: this.name, constants: this.constants, constantTypes: this.constantTypes, isRootKernel: this.isRootKernel, isSubKernel: this.isSubKernel, debug: this.debug, output: this.output, loopMaxIterations: this.loopMaxIterations, argumentNames: this.argumentNames, argumentTypes: this.argumentTypes, argumentSizes: this.argumentSizes, returnType: this.returnType, leadingReturnStatement: this.leadingReturnStatement, followingReturnStatement: this.followingReturnStatement, }; return { ast: this.ast, settings }; } getType(ast) { if (Array.isArray(ast)) { return this.getType(ast[ast.length - 1]); } switch (ast.type) { case 'BlockStatement': return this.getType(ast.body); case 'ArrayExpression': const childType = this.getType(ast.elements[0]); switch (childType) { case 'Array(2)': case 'Array(3)': case 'Array(4)': return `Matrix(${ast.elements.length})`; } return `Array(${ ast.elements.length })`; case 'Literal': const literalKey = this.astKey(ast); if (this.literalTypes[literalKey]) { return this.literalTypes[literalKey]; } if (Number.isInteger(ast.value)) { return 'LiteralInteger'; } else if (ast.value === true || ast.value === false) { return 'Boolean'; } else { return 'Number'; } case 'AssignmentExpression': return this.getType(ast.left); case 'CallExpression': if (this.isAstMathFunction(ast)) { return 'Number'; } if (!ast.callee || !ast.callee.name) { if (ast.callee.type === 'SequenceExpression' && ast.callee.expressions[ast.callee.expressions.length - 1].property.name) { const functionName = ast.callee.expressions[ast.callee.expressions.length - 1].property.name; this.inferArgumentTypesIfNeeded(functionName, ast.arguments); return this.lookupReturnType(functionName, ast, this); } if (this.getVariableSignature(ast.callee, true) === 'this.color') { return null; } if (ast.callee.type === 'MemberExpression' && ast.callee.object && ast.callee.property && ast.callee.property.name && ast.arguments) { const functionName = ast.callee.property.name; this.inferArgumentTypesIfNeeded(functionName, ast.arguments); return this.lookupReturnType(functionName, ast, this); } throw this.astErrorOutput('Unknown call expression', ast); } if (ast.callee && ast.callee.name) { const functionName = ast.callee.name; this.inferArgumentTypesIfNeeded(functionName, ast.arguments); return this.lookupReturnType(functionName, ast, this); } throw this.astErrorOutput(`Unhandled getType Type "${ ast.type }"`, ast); case 'LogicalExpression': return 'Boolean'; case 'BinaryExpression': switch (ast.operator) { case '%': case '/': if (this.fixIntegerDivisionAccuracy) { return 'Number'; } else { break; } case '>': case '<': return 'Boolean'; case '&': case '|': case '^': case '<<': case '>>': case '>>>': return 'Integer'; } const type = this.getType(ast.left); if (this.isState('skip-literal-correction')) return type; if (type === 'LiteralInteger') { const rightType = this.getType(ast.right); if (rightType === 'LiteralInteger') { if (ast.left.value % 1 === 0) { return 'Integer'; } else { return 'Float'; } } return rightType; } return typeLookupMap[type] || type; case 'UpdateExpression': return this.getType(ast.argument); case 'UnaryExpression': if (ast.operator === '~') { return 'Integer'; } return this.getType(ast.argument); case 'VariableDeclaration': { const declarations = ast.declarations; let lastType; for (let i = 0; i < declarations.length; i++) { const declaration = declarations[i]; lastType = this.getType(declaration); } if (!lastType) { throw this.astErrorOutput(`Unable to find type for declaration`, ast); } return lastType; } case 'VariableDeclarator': const declaration = this.getDeclaration(ast.id); if (!declaration) { throw this.astErrorOutput(`Unable to find declarator`, ast); } if (!declaration.valueType) { throw this.astErrorOutput(`Unable to find declarator valueType`, ast); } return declaration.valueType; case 'Identifier': if (ast.name === 'Infinity') { return 'Number'; } if (this.isAstVariable(ast)) { const signature = this.getVariableSignature(ast); if (signature === 'value') { return this.getCheckVariableType(ast); } } const origin = this.findIdentifierOrigin(ast); if (origin && origin.init) { return this.getType(origin.init); } return null; case 'ReturnStatement': return this.getType(ast.argument); case 'MemberExpression': if (this.isAstMathFunction(ast)) { switch (ast.property.name) { case 'ceil': return 'Integer'; case 'floor': return 'Integer'; case 'round': return 'Integer'; } return 'Number'; } if (this.isAstVariable(ast)) { const variableSignature = this.getVariableSignature(ast); switch (variableSignature) { case 'value[]': return this.getLookupType(this.getCheckVariableType(ast.object)); case 'value[][]': return this.getLookupType(this.getCheckVariableType(ast.object.object)); case 'value[][][]': return this.getLookupType(this.getCheckVariableType(ast.object.object.object)); case 'value[][][][]': return this.getLookupType(this.getCheckVariableType(ast.object.object.object.object)); case 'value.thread.value': case 'this.thread.value': return 'Integer'; case 'this.output.value': return this.dynamicOutput ? 'Integer' : 'LiteralInteger'; case 'this.constants.value': return this.getConstantType(ast.property.name); case 'this.constants.value[]': return this.getLookupType(this.getConstantType(ast.object.property.name)); case 'this.constants.value[][]': return this.getLookupType(this.getConstantType(ast.object.object.property.name)); case 'this.constants.value[][][]': return this.getLookupType(this.getConstantType(ast.object.object.object.property.name)); case 'this.constants.value[][][][]': return this.getLookupType(this.getConstantType(ast.object.object.object.object.property.name)); case 'fn()[]': case 'fn()[][]': case 'fn()[][][]': return this.getLookupType(this.getType(ast.object)); case 'value.value': if (this.isAstMathVariable(ast)) { return 'Number'; } switch (ast.property.name) { case 'r': case 'g': case 'b': case 'a': return this.getLookupType(this.getCheckVariableType(ast.object)); } case '[][]': return 'Number'; } throw this.astErrorOutput('Unhandled getType MemberExpression', ast); } throw this.astErrorOutput('Unhandled getType MemberExpression', ast); case 'ConditionalExpression': return this.getType(ast.consequent); case 'FunctionDeclaration': case 'FunctionExpression': const lastReturn = this.findLastReturn(ast.body); if (lastReturn) { return this.getType(lastReturn); } return null; case 'IfStatement': return this.getType(ast.consequent); case 'SequenceExpression': return this.getType(ast.expressions[ast.expressions.length - 1]); default: throw this.astErrorOutput(`Unhandled getType Type "${ ast.type }"`, ast); } } getCheckVariableType(ast) { const type = this.getVariableType(ast); if (!type) { throw this.astErrorOutput(`${ast.type} is not defined`, ast); } return type; } inferArgumentTypesIfNeeded(functionName, args) { for (let i = 0; i < args.length; i++) { if (!this.needsArgumentType(functionName, i)) continue; const type = this.getType(args[i]); if (!type) { throw this.astErrorOutput(`Unable to infer argument ${i}`, args[i]); } this.assignArgumentType(functionName, i, type); } } isAstMathVariable(ast) { const mathProperties = [ 'E', 'PI', 'SQRT2', 'SQRT1_2', 'LN2', 'LN10', 'LOG2E', 'LOG10E', ]; return ast.type === 'MemberExpression' && ast.object && ast.object.type === 'Identifier' && ast.object.name === 'Math' && ast.property && ast.property.type === 'Identifier' && mathProperties.indexOf(ast.property.name) > -1; } isAstMathFunction(ast) { const mathFunctions = [ 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'clz32', 'cos', 'cosh', 'expm1', 'exp', 'floor', 'fround', 'imul', 'log', 'log2', 'log10', 'log1p', 'max', 'min', 'pow', 'random', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc', ]; return ast.type === 'CallExpression' && ast.callee && ast.callee.type === 'MemberExpression' && ast.callee.object && ast.callee.object.type === 'Identifier' && ast.callee.object.name === 'Math' && ast.callee.property && ast.callee.property.type === 'Identifier' && mathFunctions.indexOf(ast.callee.property.name) > -1; } isAstVariable(ast) { return ast.type === 'Identifier' || ast.type === 'MemberExpression'; } isSafe(ast) { return this.isSafeDependencies(this.getDependencies(ast)); } isSafeDependencies(dependencies) { return dependencies && dependencies.every ? dependencies.every(dependency => dependency.isSafe) : true; } getDependencies(ast, dependencies, isNotSafe) { if (!dependencies) { dependencies = []; } if (!ast) return null; if (Array.isArray(ast)) { for (let i = 0; i < ast.length; i++) { this.getDependencies(ast[i], dependencies, isNotSafe); } return dependencies; } switch (ast.type) { case 'AssignmentExpression': this.getDependencies(ast.left, dependencies, isNotSafe); this.getDependencies(ast.right, dependencies, isNotSafe); return dependencies; case 'ConditionalExpression': this.getDependencies(ast.test, dependencies, isNotSafe); this.getDependencies(ast.alternate, dependencies, isNotSafe); this.getDependencies(ast.consequent, dependencies, isNotSafe); return dependencies; case 'Literal': dependencies.push({ origin: 'literal', value: ast.value, isSafe: isNotSafe === true ? false : ast.value > -Infinity && ast.value < Infinity && !isNaN(ast.value) }); break; case 'VariableDeclarator': return this.getDependencies(ast.init, dependencies, isNotSafe); case 'Identifier': const declaration = this.getDeclaration(ast); if (declaration) { dependencies.push({ name: ast.name, origin: 'declaration', isSafe: isNotSafe ? false : this.isSafeDependencies(declaration.dependencies), }); } else if (this.argumentNames.indexOf(ast.name) > -1) { dependencies.push({ name: ast.name, origin: 'argument', isSafe: false, }); } else if (this.strictTypingChecking) { throw new Error(`Cannot find identifier origin "${ast.name}"`); } break; case 'FunctionDeclaration': return this.getDependencies(ast.body.body[ast.body.body.length - 1], dependencies, isNotSafe); case 'ReturnStatement': return this.getDependencies(ast.argument, dependencies); case 'BinaryExpression': case 'LogicalExpression': isNotSafe = (ast.operator === '/' || ast.operator === '*'); this.getDependencies(ast.left, dependencies, isNotSafe); this.getDependencies(ast.right, dependencies, isNotSafe); return dependencies; case 'UnaryExpression': case 'UpdateExpression': return this.getDependencies(ast.argument, dependencies, isNotSafe); case 'VariableDeclaration': return this.getDependencies(ast.declarations, dependencies, isNotSafe); case 'ArrayExpression': dependencies.push({ origin: 'declaration', isSafe: true, }); return dependencies; case 'CallExpression': dependencies.push({ origin: 'function', isSafe: true, }); return dependencies; case 'MemberExpression': const details = this.getMemberExpressionDetails(ast); switch (details.signature) { case 'value[]': this.getDependencies(ast.object, dependencies, isNotSafe); break; case 'value[][]': this.getDependencies(ast.object.object, dependencies, isNotSafe); break; case 'value[][][]': this.getDependencies(ast.object.object.object, dependencies, isNotSafe); break; case 'this.output.value': if (this.dynamicOutput) { dependencies.push({ name: details.name, origin: 'output', isSafe: false, }); } break; } if (details) { if (details.property) { this.getDependencies(details.property, dependencies, isNotSafe); } if (details.xProperty) { this.getDependencies(details.xProperty, dependencies, isNotSafe); } if (details.yProperty) { this.getDependencies(details.yProperty, dependencies, isNotSafe); } if (details.zProperty) { this.getDependencies(details.zProperty, dependencies, isNotSafe); } return dependencies; } case 'SequenceExpression': return this.getDependencies(ast.expressions, dependencies, isNotSafe); default: throw this.astErrorOutput(`Unhandled type ${ ast.type } in getDependencies`, ast); } return dependencies; } getVariableSignature(ast, returnRawValue) { if (!this.isAstVariable(ast)) { throw new Error(`ast of type "${ ast.type }" is not a variable signature`); } if (ast.type === 'Identifier') { return 'value'; } const signature = []; while (true) { if (!ast) break; if (ast.computed) { signature.push('[]'); } else if (ast.type === 'ThisExpression') { signature.unshift('this'); } else if (ast.property && ast.property.name) { if ( ast.property.name === 'x' || ast.property.name === 'y' || ast.property.name === 'z' ) { signature.unshift(returnRawValue ? '.' + ast.property.name : '.value'); } else if ( ast.property.name === 'constants' || ast.property.name === 'thread' || ast.property.name === 'output' ) { signature.unshift('.' + ast.property.name); } else { signature.unshift(returnRawValue ? '.' + ast.property.name : '.value'); } } else if (ast.name) { signature.unshift(returnRawValue ? ast.name : 'value'); } else if (ast.callee && ast.callee.name) { signature.unshift(returnRawValue ? ast.callee.name + '()' : 'fn()'); } else if (ast.elements) { signature.unshift('[]'); } else { signature.unshift('unknown'); } ast = ast.object; } const signatureString = signature.join(''); if (returnRawValue) { return signatureString; } const allowedExpressions = [ 'value', 'value[]', 'value[][]', 'value[][][]', 'value[][][][]', 'value.value', 'value.thread.value', 'this.thread.value', 'this.output.value', 'this.constants.value', 'this.constants.value[]', 'this.constants.value[][]', 'this.constants.value[][][]', 'this.constants.value[][][][]', 'fn()[]', 'fn()[][]', 'fn()[][][]', '[][]', ]; if (allowedExpressions.indexOf(signatureString) > -1) { return signatureString; } return null; } build() { return this.toString().length > 0; } astGeneric(ast, retArr) { if (ast === null) { throw this.astErrorOutput('NULL ast', ast); } else { if (Array.isArray(ast)) { for (let i = 0; i < ast.length; i++) { this.astGeneric(ast[i], retArr); } return retArr; } switch (ast.type) { case 'FunctionDeclaration': return this.astFunctionDeclaration(ast, retArr); case 'FunctionExpression': return this.astFunctionExpression(ast, retArr); case 'ReturnStatement': return this.astReturnStatement(ast, retArr); case 'Literal': return this.astLiteral(ast, retArr); case 'BinaryExpression': return this.astBinaryExpression(ast, retArr); case 'Identifier': return this.astIdentifierExpression(ast, retArr); case 'AssignmentExpression': return this.astAssignmentExpression(ast, retArr); case 'ExpressionStatement': return this.astExpressionStatement(ast, retArr); case 'EmptyStatement': return this.astEmptyStatement(ast, retArr); case 'BlockStatement': return this.astBlockStatement(ast, retArr); case 'IfStatement': return this.astIfStatement(ast, retArr); case 'SwitchStatement': return this.astSwitchStatement(ast, retArr); case 'BreakStatement': return this.astBreakStatement(ast, retArr); case 'ContinueStatement': return this.astContinueStatement(ast, retArr); case 'ForStatement': return this.astForStatement(ast, retArr); case 'WhileStatement': return this.astWhileStatement(ast, retArr); case 'DoWhileStatement': return this.astDoWhileStatement(ast, retArr); case 'VariableDeclaration': return this.astVariableDeclaration(ast, retArr); case 'VariableDeclarator': return this.astVariableDeclarator(ast, retArr); case 'ThisExpression': return this.astThisExpression(ast, retArr); case 'SequenceExpression': return this.astSequenceExpression(ast, retArr); case 'UnaryExpression': return this.astUnaryExpression(ast, retArr); case 'UpdateExpression': return this.astUpdateExpression(ast, retArr); case 'LogicalExpression': return this.astLogicalExpression(ast, retArr); case 'MemberExpression': return this.astMemberExpression(ast, retArr); case 'CallExpression': return this.astCallExpression(ast, retArr); case 'ArrayExpression': return this.astArrayExpression(ast, retArr); case 'DebuggerStatement': return this.astDebuggerStatement(ast, retArr); case 'ConditionalExpression': return this.astConditionalExpression(ast, retArr); } throw this.astErrorOutput('Unknown ast type : ' + ast.type, ast); } } astErrorOutput(error, ast) { if (typeof this.source !== 'string') { return new Error(error); } const debugString = utils.getAstString(this.source, ast); const leadingSource = this.source.substr(ast.start); const splitLines = leadingSource.split(/\n/); const lineBefore = splitLines.length > 0 ? splitLines[splitLines.length - 1] : 0; return new Error(`${error} on line ${ splitLines.length }, position ${ lineBefore.length }:\n ${ debugString }`); } astDebuggerStatement(arrNode, retArr) { return retArr; } astConditionalExpression(ast, retArr) { if (ast.type !== 'ConditionalExpression') { throw this.astErrorOutput('Not a conditional expression', ast); } retArr.push('('); this.astGeneric(ast.test, retArr); retArr.push('?'); this.astGeneric(ast.consequent, retArr); retArr.push(':'); this.astGeneric(ast.alternate, retArr); retArr.push(')'); return retArr; } astFunction(ast, retArr) { throw new Error(`"astFunction" not defined on ${ this.constructor.name }`); } astFunctionDeclaration(ast, retArr) { if (this.isChildFunction(ast)) { return retArr; } return this.astFunction(ast, retArr); } astFunctionExpression(ast, retArr) { if (this.isChildFunction(ast)) { return retArr; } return this.astFunction(ast, retArr); } isChildFunction(ast) { for (let i = 0; i < this.functions.length; i++) { if (this.functions[i] === ast) { return true; } } return false; } astReturnStatement(ast, retArr) { return retArr; } astLiteral(ast, retArr) { this.literalTypes[this.astKey(ast)] = 'Number'; return retArr; } astBinaryExpression(ast, retArr) { return retArr; } astIdentifierExpression(ast, retArr) { return retArr; } astAssignmentExpression(ast, retArr) { return retArr; } astExpressionStatement(esNode, retArr) { this.astGeneric(esNode.expression, retArr); retArr.push(';'); return retArr; } astEmptyStatement(eNode, retArr) { return retArr; } astBlockStatement(ast, retArr) { return retArr; } astIfStatement(ast, retArr) { return retArr; } astSwitchStatement(ast, retArr) { return retArr; } astBreakStatement(brNode, retArr) { retArr.push('break;'); return retArr; } astContinueStatement(crNode, retArr) { retArr.push('continue;\n'); return retArr; } astForStatement(ast, retArr) { return retArr; } astWhileStatement(ast, retArr) { return retArr; } astDoWhileStatement(ast, retArr) { return retArr; } astVariableDeclarator(iVarDecNode, retArr) { this.astGeneric(iVarDecNode.id, retArr); if (iVarDecNode.init !== null) { retArr.push('='); this.astGeneric(iVarDecNode.init, retArr); } return retArr; } astThisExpression(ast, retArr) { return retArr; } astSequenceExpression(sNode, retArr) { const { expressions } = sNode; const sequenceResult = []; for (let i = 0; i < expressions.length; i++) { const expression = expressions[i]; const expressionResult = []; this.astGeneric(expression, expressionResult); sequenceResult.push(expressionResult.join('')); } if (sequenceResult.length > 1) { retArr.push('(', sequenceResult.join(','), ')'); } else { retArr.push(sequenceResult[0]); } return retArr; } astUnaryExpression(uNode, retArr) { const unaryResult = this.checkAndUpconvertBitwiseUnary(uNode, retArr); if (unaryResult) { return retArr; } if (uNode.prefix) { retArr.push(uNode.operator); this.astGeneric(uNode.argument, retArr); } else { this.astGeneric(uNode.argument, retArr); retArr.push(uNode.operator); } return retArr; } checkAndUpconvertBitwiseUnary(uNode, retArr) {} astUpdateExpression(uNode, retArr) { if (uNode.prefix) { retArr.push(uNode.operator); this.astGeneric(uNode.argument, retArr); } else { this.astGeneric(uNode.argument, retArr); retArr.push(uNode.operator); } return retArr; } astLogicalExpression(logNode, retArr) { retArr.push('('); this.astGeneric(logNode.left, retArr); retArr.push(logNode.operator); this.astGeneric(logNode.right, retArr); retArr.push(')'); return retArr; } astMemberExpression(ast, retArr) { return retArr; } astCallExpression(ast, retArr) { return retArr; } astArrayExpression(ast, retArr) { return retArr; } getMemberExpressionDetails(ast) { if (ast.type !== 'MemberExpression') { throw this.astErrorOutput(`Expression ${ ast.type } not a MemberExpression`, ast); } let name = null; let type = null; const variableSignature = this.getVariableSignature(ast); switch (variableSignature) { case 'value': return null; case 'value.thread.value': case 'this.thread.value': case 'this.output.value': return { signature: variableSignature, type: 'Integer', name: ast.property.name }; case 'value[]': if (typeof ast.object.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.name; return { name, origin: 'user', signature: variableSignature, type: this.getVariableType(ast.object), xProperty: ast.property }; case 'value[][]': if (typeof ast.object.object.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.object.name; return { name, origin: 'user', signature: variableSignature, type: this.getVariableType(ast.object.object), yProperty: ast.object.property, xProperty: ast.property, }; case 'value[][][]': if (typeof ast.object.object.object.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.object.object.name; return { name, origin: 'user', signature: variableSignature, type: this.getVariableType(ast.object.object.object), zProperty: ast.object.object.property, yProperty: ast.object.property, xProperty: ast.property, }; case 'value[][][][]': if (typeof ast.object.object.object.object.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.object.object.object.name; return { name, origin: 'user', signature: variableSignature, type: this.getVariableType(ast.object.object.object.object), zProperty: ast.object.object.property, yProperty: ast.object.property, xProperty: ast.property, }; case 'value.value': if (typeof ast.property.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } if (this.isAstMathVariable(ast)) { name = ast.property.name; return { name, origin: 'Math', type: 'Number', signature: variableSignature, }; } switch (ast.property.name) { case 'r': case 'g': case 'b': case 'a': name = ast.object.name; return { name, property: ast.property.name, origin: 'user', signature: variableSignature, type: 'Number' }; default: throw this.astErrorOutput('Unexpected expression', ast); } case 'this.constants.value': if (typeof ast.property.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.property.name; type = this.getConstantType(name); if (!type) { throw this.astErrorOutput('Constant has no type', ast); } return { name, type, origin: 'constants', signature: variableSignature, }; case 'this.constants.value[]': if (typeof ast.object.property.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.property.name; type = this.getConstantType(name); if (!type) { throw this.astErrorOutput('Constant has no type', ast); } return { name, type, origin: 'constants', signature: variableSignature, xProperty: ast.property, }; case 'this.constants.value[][]': { if (typeof ast.object.object.property.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.object.property.name; type = this.getConstantType(name); if (!type) { throw this.astErrorOutput('Constant has no type', ast); } return { name, type, origin: 'constants', signature: variableSignature, yProperty: ast.object.property, xProperty: ast.property, }; } case 'this.constants.value[][][]': { if (typeof ast.object.object.object.property.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.object.object.property.name; type = this.getConstantType(name); if (!type) { throw this.astErrorOutput('Constant has no type', ast); } return { name, type, origin: 'constants', signature: variableSignature, zProperty: ast.object.object.property, yProperty: ast.object.property, xProperty: ast.property, }; } case 'fn()[]': case 'fn()[][]': case '[][]': return { signature: variableSignature, property: ast.property, }; default: throw this.astErrorOutput('Unexpected expression', ast); } } findIdentifierOrigin(astToFind) { const stack = [this.ast]; while (stack.length > 0) { const atNode = stack[0]; if (atNode.type === 'VariableDeclarator' && atNode.id && atNode.id.name && atNode.id.name === astToFind.name) { return atNode; } stack.shift(); if (atNode.argument) { stack.push(atNode.argument); } else if (atNode.body) { stack.push(atNode.body); } else if (atNode.declarations) { stack.push(atNode.declarations); } else if (Array.isArray(atNode)) { for (let i = 0; i < atNode.length; i++) { stack.push(atNode[i]); } } } return null; } findLastReturn(ast) { const stack = [ast || this.ast]; while (stack.length > 0) { const atNode = stack.pop(); if (atNode.type === 'ReturnStatement') { return atNode; } if (atNode.type === 'FunctionDeclaration') { continue; } if (atNode.argument) { stack.push(atNode.argument); } else if (atNode.body) { stack.push(atNode.body); } else if (atNode.declarations) { stack.push(atNode.declarations); } else if (Array.isArray(atNode)) { for (let i = 0; i < atNode.length; i++) { stack.push(atNode[i]); } } else if (atNode.consequent) { stack.push(atNode.consequent); } else if (atNode.cases) { stack.push(atNode.cases); } } return null; } getInternalVariableName(name) { if (!this._internalVariableNames.hasOwnProperty(name)) { this._internalVariableNames[name] = 0; } this._internalVariableNames[name]++; if (this._internalVariableNames[name] === 1) { return name; } return name + this._internalVariableNames[name]; } astKey(ast, separator = ',') { if (!ast.start || !ast.end) throw new Error('AST start and end needed'); return `${ast.start}${separator}${ast.end}`; } } const typeLookupMap = { 'Number': 'Number', 'Float': 'Float', 'Integer': 'Integer', 'Array': 'Number', 'Array(2)': 'Number', 'Array(3)': 'Number', 'Array(4)': 'Number', 'Matrix(2)': 'Number', 'Matrix(3)': 'Number', 'Matrix(4)': 'Number', 'Array2D': 'Number', 'Array3D': 'Number', 'Input': 'Number', 'HTMLCanvas': 'Array(4)', 'OffscreenCanvas': 'Array(4)', 'HTMLImage': 'Array(4)', 'ImageBitmap': 'Array(4)', 'ImageData': 'Array(4)', 'HTMLVideo': 'Array(4)', 'HTMLImageArray': 'Array(4)', 'NumberTexture': 'Number', 'MemoryOptimizedNumberTexture': 'Number', 'Array1D(2)': 'Array(2)', 'Array1D(3)': 'Array(3)', 'Array1D(4)': 'Array(4)', 'Array2D(2)': 'Array(2)', 'Array2D(3)': 'Array(3)', 'Array2D(4)': 'Array(4)', 'Array3D(2)': 'Array(2)', 'Array3D(3)': 'Array(3)', 'Array3D(4)': 'Array(4)', 'ArrayTexture(1)': 'Number', 'ArrayTexture(2)': 'Array(2)', 'ArrayTexture(3)': 'Array(3)', 'ArrayTexture(4)': 'Array(4)', }; module.exports = { FunctionNode }; },{"../utils":114,"./function-tracer":11,"acorn":1}],11:[function(require,module,exports){ const { utils } = require('../utils'); function last(array) { return array.length > 0 ? array[array.length - 1] : null; } const states = { trackIdentifiers: 'trackIdentifiers', memberExpression: 'memberExpression', inForLoopInit: 'inForLoopInit' }; class FunctionTracer { constructor(ast) { this.runningContexts = []; this.functionContexts = []; this.contexts = []; this.functionCalls = []; this.declarations = []; this.identifiers = []; this.functions = []; this.returnStatements = []; this.trackedIdentifiers = null; this.states = []; this.newFunctionContext(); this.scan(ast); } isState(state) { return this.states[this.states.length - 1] === state; } hasState(state) { return this.states.indexOf(state) > -1; } pushState(state) { this.states.push(state); } popState(state) { if (this.isState(state)) { this.states.pop(); } else { throw new Error(`Cannot pop the non-active state "${state}"`); } } get currentFunctionContext() { return last(this.functionContexts); } get currentContext() { return last(this.runningContexts); } newFunctionContext() { const newContext = { '@contextType': 'function' }; this.contexts.push(newContext); this.functionContexts.push(newContext); } newContext(run) { const newContext = Object.assign({ '@contextType': 'const/let' }, this.currentContext); this.contexts.push(newContext); this.runningContexts.push(newContext); run(); const { currentFunctionContext } = this; for (const p in currentFunctionContext) { if (!currentFunctionContext.hasOwnProperty(p) || newContext.hasOwnProperty(p)) continue; newContext[p] = currentFunctionContext[p]; } this.runningContexts.pop(); return newContext; } useFunctionContext(run) { const functionContext = last(this.functionContexts); this.runningContexts.push(functionContext); run(); this.runningContexts.pop(); } getIdentifiers(run) { const trackedIdentifiers = this.trackedIdentifiers = []; this.pushState(states.trackIdentifiers); run(); this.trackedIdentifiers = null; this.popState(states.trackIdentifiers); return trackedIdentifiers; } getDeclaration(name) { const { currentContext, currentFunctionContext, runningContexts } = this; const declaration = currentContext[name] || currentFunctionContext[name] || null; if ( !declaration && currentContext === currentFunctionContext && runningContexts.length > 0 ) { const previousRunningContext = runningContexts[runningContexts.length - 2]; if (previousRunningContext[name]) { return previousRunningContext[name]; } } return declaration; } scan(ast) { if (!ast) return; if (Array.isArray(ast)) { for (let i = 0; i < ast.length; i++) { this.scan(ast[i]); } return; } switch (ast.type) { case 'Program': this.useFunctionContext(() => { this.scan(ast.body); }); break; case 'BlockStatement': this.newContext(() => { this.scan(ast.body); }); break; case 'AssignmentExpression': case 'LogicalExpression': this.scan(ast.left); this.scan(ast.right); break; case 'BinaryExpression': this.scan(ast.left); this.scan(ast.right); break; case 'UpdateExpression': if (ast.operator === '++') { const declaration = this.getDeclaration(ast.argument.name); if (declaration) { declaration.suggestedType = 'Integer'; } } this.scan(ast.argument); break; case 'UnaryExpression': this.scan(ast.argument); break; case 'VariableDeclaration': if (ast.kind === 'var') { this.useFunctionContext(() => { ast.declarations = utils.normalizeDeclarations(ast); this.scan(ast.declarations); }); } else { ast.declarations = utils.normalizeDeclarations(ast); this.scan(ast.declarations); } break; case 'VariableDeclarator': { const { currentContext } = this; const inForLoopInit = this.hasState(states.inForLoopInit); const declaration = { ast: ast, context: currentContext, name: ast.id.name, origin: 'declaration', inForLoopInit, inForLoopTest: null, assignable: currentContext === this.currentFunctionContext || (!inForLoopInit && !currentContext.hasOwnProperty(ast.id.name)), suggestedType: null, valueType: null, dependencies: null, isSafe: null, }; if (!currentContext[ast.id.name]) { currentContext[ast.id.name] = declaration; } this.declarations.push(declaration); this.scan(ast.id); this.scan(ast.init); break; } case 'FunctionExpression': case 'FunctionDeclaration': if (this.runningContexts.length === 0) { this.scan(ast.body); } else { this.functions.push(ast); } break; case 'IfStatement': this.scan(ast.test); this.scan(ast.consequent); if (ast.alternate) this.scan(ast.alternate); break; case 'ForStatement': { let testIdentifiers; const context = this.newContext(() => { this.pushState(states.inForLoopInit); this.scan(ast.init); this.popState(states.inForLoopInit); testIdentifiers = this.getIdentifiers(() => { this.scan(ast.test); }); this.scan(ast.update); this.newContext(() => { this.scan(ast.body); }); }); if (testIdentifiers) { for (const p in context) { if (p === '@contextType') continue; if (testIdentifiers.indexOf(p) > -1) { context[p].inForLoopTest = true; } } } break; } case 'DoWhileStatement': case 'WhileStatement': this.newContext(() => { this.scan(ast.body); this.scan(ast.test); }); break; case 'Identifier': { if (this.isState(states.trackIdentifiers)) { this.trackedIdentifiers.push(ast.name); } this.identifiers.push({ context: this.currentContext, declaration: this.getDeclaration(ast.name), ast, }); break; } case 'ReturnStatement': this.returnStatements.push(ast); this.scan(ast.argument); break; case 'MemberExpression': this.pushState(states.memberExpression); this.scan(ast.object); this.scan(ast.property); this.popState(states.memberExpression); break; case 'ExpressionStatement': this.scan(ast.expression); break; case 'SequenceExpression': this.scan(ast.expressions); break; case 'CallExpression': this.functionCalls.push({ context: this.currentContext, ast, }); this.scan(ast.arguments); break; case 'ArrayExpression': this.scan(ast.elements); break; case 'ConditionalExpression': this.scan(ast.test); this.scan(ast.alternate); this.scan(ast.consequent); break; case 'SwitchStatement': this.scan(ast.discriminant); this.scan(ast.cases); break; case 'SwitchCase': this.scan(ast.test); this.scan(ast.consequent); break; case 'ThisExpression': case 'Literal': case 'DebuggerStatement': case 'EmptyStatement': case 'BreakStatement': case 'ContinueStatement': break; default: throw new Error(`unhandled type "${ast.type}"`); } } } module.exports = { FunctionTracer, }; },{"../utils":114}],12:[function(require,module,exports){ const { glWiretap } = require('gl-wiretap'); const { utils } = require('../../utils'); function toStringWithoutUtils(fn) { return fn.toString() .replace('=>', '') .replace(/^function /, '') .replace(/utils[.]/g, '/*utils.*/'); } function glKernelString(Kernel, args, originKernel, setupContextString, destroyContextString) { if (!originKernel.built) { originKernel.build.apply(originKernel, args); } args = args ? Array.from(args).map(arg => { switch (typeof arg) { case 'boolean': return new Boolean(arg); case 'number': return new Number(arg); default: return arg; } }) : null; const uploadedValues = []; const postResult = []; const context = glWiretap(originKernel.context, { useTrackablePrimitives: true, onReadPixels: (targetName) => { if (kernel.subKernels) { if (!subKernelsResultVariableSetup) { postResult.push(` const result = { result: ${getRenderString(targetName, kernel)} };`); subKernelsResultVariableSetup = true; } else { const property = kernel.subKernels[subKernelsResultIndex++].property; postResult.push(` result${isNaN(property) ? '.' + property : `[${property}]`} = ${getRenderString(targetName, kernel)};`); } if (subKernelsResultIndex === kernel.subKernels.length) { postResult.push(' return result;'); } return; } if (targetName) { postResult.push(` return ${getRenderString(targetName, kernel)};`); } else { postResult.push(` return null;`); } }, onUnrecognizedArgumentLookup: (argument) => { const argumentName = findKernelValue(argument, kernel.kernelArguments, [], context, uploadedValues); if (argumentName) { return argumentName; } const constantName = findKernelValue(argument, kernel.kernelConstants, constants ? Object.keys(constants).map(key => constants[key]) : [], context, uploadedValues); if (constantName) { return constantName; } return null; } }); let subKernelsResultVariableSetup = false; let subKernelsResultIndex = 0; const { source, canvas, output, pipeline, graphical, loopMaxIterations, constants, optimizeFloatMemory, precision, fixIntegerDivisionAccuracy, functions, nativeFunctions, subKernels, immutable, argumentTypes, constantTypes, kernelArguments, kernelConstants, tactic, } = originKernel; const kernel = new Kernel(source, { canvas, context, checkContext: false, output, pipeline, graphical, loopMaxIterations, constants, optimizeFloatMemory, precision, fixIntegerDivisionAccuracy, functions, nativeFunctions, subKernels, immutable, argumentTypes, constantTypes, tactic, }); let result = []; context.setIndent(2); kernel.build.apply(kernel, args); result.push(context.toString()); context.reset(); kernel.kernelArguments.forEach((kernelArgument, i) => { switch (kernelArgument.type) { case 'Integer': case 'Boolean': case 'Number': case 'Float': case 'Array': case 'Array(2)': case 'Array(3)': case 'Array(4)': case 'HTMLCanvas': case 'HTMLImage': case 'HTMLVideo': context.insertVariable(`uploadValue_${kernelArgument.name}`, kernelArgument.uploadValue); break; case 'HTMLImageArray': for (let imageIndex = 0; imageIndex < args[i].length; imageIndex++) { const arg = args[i]; context.insertVariable(`uploadValue_${kernelArgument.name}[${imageIndex}]`, arg[imageIndex]); } break; case 'Input': context.insertVariable(`uploadValue_${kernelArgument.name}`, kernelArgument.uploadValue); break; case 'MemoryOptimizedNumberTexture': case 'NumberTexture': case 'Array1D(2)': case 'Array1D(3)': case 'Array1D(4)': case 'Array2D(2)': case 'Array2D(3)': case 'Array2D(4)': case 'Array3D(2)': case 'Array3D(3)': case 'Array3D(4)': case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': context.insertVariable(`uploadValue_${kernelArgument.name}`, args[i].texture); break; default: throw new Error(`unhandled kernelArgumentType insertion for glWiretap of type ${kernelArgument.type}`); } }); result.push('/** start of injected functions **/'); result.push(`function ${toStringWithoutUtils(utils.flattenTo)}`); result.push(`function ${toStringWithoutUtils(utils.flatten2dArrayTo)}`); result.push(`function ${toStringWithoutUtils(utils.flatten3dArrayTo)}`); result.push(`function ${toStringWithoutUtils(utils.flatten4dArrayTo)}`); result.push(`function ${toStringWithoutUtils(utils.isArray)}`); if (kernel.renderOutput !== kernel.renderTexture && kernel.formatValues) { result.push( ` const renderOutput = function ${toStringWithoutUtils(kernel.formatValues)};` ); } result.push('/** end of injected functions **/'); result.push(` const innerKernel = function (${kernel.kernelArguments.map(kernelArgument => kernelArgument.varName).join(', ')}) {`); context.setIndent(4); kernel.run.apply(kernel, args); if (kernel.renderKernels) { kernel.renderKernels(); } else if (kernel.renderOutput) { kernel.renderOutput(); } result.push(' /** start setup uploads for kernel values **/'); kernel.kernelArguments.forEach(kernelArgument => { result.push(' ' + kernelArgument.getStringValueHandler().split('\n').join('\n ')); }); result.push(' /** end setup uploads for kernel values **/'); result.push(context.toString()); if (kernel.renderOutput === kernel.renderTexture) { context.reset(); const framebufferName = context.getContextVariableName(kernel.framebuffer); if (kernel.renderKernels) { const results = kernel.renderKernels(); const textureName = context.getContextVariableName(kernel.texture.texture); result.push(` return { result: { texture: ${ textureName }, type: '${ results.result.type }', toArray: ${ getToArrayString(results.result, textureName, framebufferName) } },`); const { subKernels, mappedTextures } = kernel; for (let i = 0; i < subKernels.length; i++) { const texture = mappedTextures[i]; const subKernel = subKernels[i]; const subKernelResult = results[subKernel.property]; const subKernelTextureName = context.getContextVariableName(texture.texture); result.push(` ${subKernel.property}: { texture: ${ subKernelTextureName }, type: '${ subKernelResult.type }', toArray: ${ getToArrayString(subKernelResult, subKernelTextureName, framebufferName) } },`); } result.push(` };`); } else { const rendered = kernel.renderOutput(); const textureName = context.getContextVariableName(kernel.texture.texture); result.push(` return { texture: ${ textureName }, type: '${ rendered.type }', toArray: ${ getToArrayString(rendered, textureName, framebufferName) } };`); } } result.push(` ${destroyContextString ? '\n' + destroyContextString + ' ': ''}`); result.push(postResult.join('\n')); result.push(' };'); if (kernel.graphical) { result.push(getGetPixelsString(kernel)); result.push(` innerKernel.getPixels = getPixels;`); } result.push(' return innerKernel;'); let constantsUpload = []; kernelConstants.forEach((kernelConstant) => { constantsUpload.push(`${kernelConstant.getStringValueHandler()}`); }); return `function kernel(settings) { const { context, constants } = settings; ${constantsUpload.join('')} ${setupContextString ? setupContextString : ''} ${result.join('\n')} }`; } function getRenderString(targetName, kernel) { const readBackValue = kernel.precision === 'single' ? targetName : `new Float32Array(${targetName}.buffer)`; if (kernel.output[2]) { return `renderOutput(${readBackValue}, ${kernel.output[0]}, ${kernel.output[1]}, ${kernel.output[2]})`; } if (kernel.output[1]) { return `renderOutput(${readBackValue}, ${kernel.output[0]}, ${kernel.output[1]})`; } return `renderOutput(${readBackValue}, ${kernel.output[0]})`; } function getGetPixelsString(kernel) { const getPixels = kernel.getPixels.toString(); const useFunctionKeyword = !/^function/.test(getPixels); return utils.flattenFunctionToString(`${useFunctionKeyword ? 'function ' : ''}${ getPixels }`, { findDependency: (object, name) => { if (object === 'utils') { return `const ${name} = ${utils[name].toString()};`; } return null; }, thisLookup: (property) => { if (property === 'context') { return null; } if (kernel.hasOwnProperty(property)) { return JSON.stringify(kernel[property]); } throw new Error(`unhandled thisLookup ${ property }`); } }); } function getToArrayString(kernelResult, textureName, framebufferName) { const toArray = kernelResult.toArray.toString(); const useFunctionKeyword = !/^function/.test(toArray); const flattenedFunctions = utils.flattenFunctionToString(`${useFunctionKeyword ? 'function ' : ''}${ toArray }`, { findDependency: (object, name) => { if (object === 'utils') { return `const ${name} = ${utils[name].toString()};`; } else if (object === 'this') { if (name === 'framebuffer') { return ''; } return `${useFunctionKeyword ? 'function ' : ''}${kernelResult[name].toString()}`; } else { throw new Error('unhandled fromObject'); } }, thisLookup: (property, isDeclaration) => { if (property === 'texture') { return textureName; } if (property === 'context') { if (isDeclaration) return null; return 'gl'; } if (kernelResult.hasOwnProperty(property)) { return JSON.stringify(kernelResult[property]); } throw new Error(`unhandled thisLookup ${ property }`); } }); return `() => { function framebuffer() { return ${framebufferName}; }; ${flattenedFunctions} return toArray(); }`; } function findKernelValue(argument, kernelValues, values, context, uploadedValues) { if (argument === null) return null; if (kernelValues === null) return null; switch (typeof argument) { case 'boolean': case 'number': return null; } if ( typeof HTMLImageElement !== 'undefined' && argument instanceof HTMLImageElement ) { for (let i = 0; i < kernelValues.length; i++) { const kernelValue = kernelValues[i]; if (kernelValue.type !== 'HTMLImageArray' && kernelValue) continue; if (kernelValue.uploadValue !== argument) continue; const variableIndex = values[i].indexOf(argument); if (variableIndex === -1) continue; const variableName = `uploadValue_${kernelValue.name}[${variableIndex}]`; context.insertVariable(variableName, argument); return variableName; } } for (let i = 0; i < kernelValues.length; i++) { const kernelValue = kernelValues[i]; if (argument !== kernelValue.uploadValue) continue; const variable = `uploadValue_${kernelValue.name}`; context.insertVariable(variable, kernelValue); return variable; } return null; } module.exports = { glKernelString }; },{"../../utils":114,"gl-wiretap":3}],13:[function(require,module,exports){ const { Kernel } = require('../kernel'); const { utils } = require('../../utils'); const { GLTextureArray2Float } = require('./texture/array-2-float'); const { GLTextureArray2Float2D } = require('./texture/array-2-float-2d'); const { GLTextureArray2Float3D } = require('./texture/array-2-float-3d'); const { GLTextureArray3Float } = require('./texture/array-3-float'); const { GLTextureArray3Float2D } = require('./texture/array-3-float-2d'); const { GLTextureArray3Float3D } = require('./texture/array-3-float-3d'); const { GLTextureArray4Float } = require('./texture/array-4-float'); const { GLTextureArray4Float2D } = require('./texture/array-4-float-2d'); const { GLTextureArray4Float3D } = require('./texture/array-4-float-3d'); const { GLTextureFloat } = require('./texture/float'); const { GLTextureFloat2D } = require('./texture/float-2d'); const { GLTextureFloat3D } = require('./texture/float-3d'); const { GLTextureMemoryOptimized } = require('./texture/memory-optimized'); const { GLTextureMemoryOptimized2D } = require('./texture/memory-optimized-2d'); const { GLTextureMemoryOptimized3D } = require('./texture/memory-optimized-3d'); const { GLTextureUnsigned } = require('./texture/unsigned'); const { GLTextureUnsigned2D } = require('./texture/unsigned-2d'); const { GLTextureUnsigned3D } = require('./texture/unsigned-3d'); const { GLTextureGraphical } = require('./texture/graphical'); class GLKernel extends Kernel { static get mode() { return 'gpu'; } static getIsFloatRead() { const kernelString = `function kernelFunction() { return 1; }`; const kernel = new this(kernelString, { context: this.testContext, canvas: this.testCanvas, validate: false, output: [1], precision: 'single', returnType: 'Number', tactic: 'speed', }); kernel.build(); kernel.run(); const result = kernel.renderOutput(); kernel.destroy(true); return result[0] === 1; } static getIsIntegerDivisionAccurate() { function kernelFunction(v1, v2) { return v1[this.thread.x] / v2[this.thread.x]; } const kernel = new this(kernelFunction.toString(), { context: this.testContext, canvas: this.testCanvas, validate: false, output: [2], returnType: 'Number', precision: 'unsigned', tactic: 'speed', }); const args = [ [6, 6030401], [3, 3991] ]; kernel.build.apply(kernel, args); kernel.run.apply(kernel, args); const result = kernel.renderOutput(); kernel.destroy(true); return result[0] === 2 && result[1] === 1511; } static getIsSpeedTacticSupported() { function kernelFunction(value) { return value[this.thread.x]; } const kernel = new this(kernelFunction.toString(), { context: this.testContext, canvas: this.testCanvas, validate: false, output: [4], returnType: 'Number', precision: 'unsigned', tactic: 'speed', }); const args = [ [0, 1, 2, 3] ]; kernel.build.apply(kernel, args); kernel.run.apply(kernel, args); const result = kernel.renderOutput(); kernel.destroy(true); return Math.round(result[0]) === 0 && Math.round(result[1]) === 1 && Math.round(result[2]) === 2 && Math.round(result[3]) === 3; } static get testCanvas() { throw new Error(`"testCanvas" not defined on ${ this.name }`); } static get testContext() { throw new Error(`"testContext" not defined on ${ this.name }`); } static getFeatures() { const gl = this.testContext; const isDrawBuffers = this.getIsDrawBuffers(); return Object.freeze({ isFloatRead: this.getIsFloatRead(), isIntegerDivisionAccurate: this.getIsIntegerDivisionAccurate(), isSpeedTacticSupported: this.getIsSpeedTacticSupported(), isTextureFloat: this.getIsTextureFloat(), isDrawBuffers, kernelMap: isDrawBuffers, channelCount: this.getChannelCount(), maxTextureSize: this.getMaxTextureSize(), lowIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT), lowFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT), mediumIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT), mediumFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT), highIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT), highFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT), }); } static setupFeatureChecks() { throw new Error(`"setupFeatureChecks" not defined on ${ this.name }`); } static getSignature(kernel, argumentTypes) { return kernel.getVariablePrecisionString() + (argumentTypes.length > 0 ? ':' + argumentTypes.join(',') : ''); } setFixIntegerDivisionAccuracy(fix) { this.fixIntegerDivisionAccuracy = fix; return this; } setPrecision(flag) { this.precision = flag; return this; } setFloatTextures(flag) { utils.warnDeprecated('method', 'setFloatTextures', 'setOptimizeFloatMemory'); this.floatTextures = flag; return this; } static nativeFunctionArguments(source) { const argumentTypes = []; const argumentNames = []; const states = []; const isStartingVariableName = /^[a-zA-Z_]/; const isVariableChar = /[a-zA-Z_0-9]/; let i = 0; let argumentName = null; let argumentType = null; while (i < source.length) { const char = source[i]; const nextChar = source[i + 1]; const state = states.length > 0 ? states[states.length - 1] : null; if (state === 'FUNCTION_ARGUMENTS' && char === '/' && nextChar === '*') { states.push('MULTI_LINE_COMMENT'); i += 2; continue; } else if (state === 'MULTI_LINE_COMMENT' && char === '*' && nextChar === '/') { states.pop(); i += 2; continue; } else if (state === 'FUNCTION_ARGUMENTS' && char === '/' && nextChar === '/') { states.push('COMMENT'); i += 2; continue; } else if (state === 'COMMENT' && char === '\n') { states.pop(); i++; continue; } else if (state === null && char === '(') { states.push('FUNCTION_ARGUMENTS'); i++; continue; } else if (state === 'FUNCTION_ARGUMENTS') { if (char === ')') { states.pop(); break; } if (char === 'f' && nextChar === 'l' && source[i + 2] === 'o' && source[i + 3] === 'a' && source[i + 4] === 't' && source[i + 5] === ' ') { states.push('DECLARE_VARIABLE'); argumentType = 'float'; argumentName = ''; i += 6; continue; } else if (char === 'i' && nextChar === 'n' && source[i + 2] === 't' && source[i + 3] === ' ') { states.push('DECLARE_VARIABLE'); argumentType = 'int'; argumentName = ''; i += 4; continue; } else if (char === 'v' && nextChar === 'e' && source[i + 2] === 'c' && source[i + 3] === '2' && source[i + 4] === ' ') { states.push('DECLARE_VARIABLE'); argumentType = 'vec2'; argumentName = ''; i += 5; continue; } else if (char === 'v' && nextChar === 'e' && source[i + 2] === 'c' && source[i + 3] === '3' && source[i + 4] === ' ') { states.push('DECLARE_VARIABLE'); argumentType = 'vec3'; argumentName = ''; i += 5; continue; } else if (char === 'v' && nextChar === 'e' && source[i + 2] === 'c' && source[i + 3] === '4' && source[i + 4] === ' ') { states.push('DECLARE_VARIABLE'); argumentType = 'vec4'; argumentName = ''; i += 5; continue; } } else if (state === 'DECLARE_VARIABLE') { if (argumentName === '') { if (char === ' ') { i++; continue; } if (!isStartingVariableName.test(char)) { throw new Error('variable name is not expected string'); } } argumentName += char; if (!isVariableChar.test(nextChar)) { states.pop(); argumentNames.push(argumentName); argumentTypes.push(typeMap[argumentType]); } } i++; } if (states.length > 0) { throw new Error('GLSL function was not parsable'); } return { argumentNames, argumentTypes, }; } static nativeFunctionReturnType(source) { return typeMap[source.match(/int|float|vec[2-4]/)[0]]; } static combineKernels(combinedKernel, lastKernel) { combinedKernel.apply(null, arguments); const { texSize, context, threadDim } = lastKernel.texSize; let result; if (lastKernel.precision === 'single') { const w = texSize[0]; const h = Math.ceil(texSize[1] / 4); result = new Float32Array(w * h * 4 * 4); context.readPixels(0, 0, w, h * 4, context.RGBA, context.FLOAT, result); } else { const bytes = new Uint8Array(texSize[0] * texSize[1] * 4); context.readPixels(0, 0, texSize[0], texSize[1], context.RGBA, context.UNSIGNED_BYTE, bytes); result = new Float32Array(bytes.buffer); } result = result.subarray(0, threadDim[0] * threadDim[1] * threadDim[2]); if (lastKernel.output.length === 1) { return result; } else if (lastKernel.output.length === 2) { return utils.splitArray(result, lastKernel.output[0]); } else if (lastKernel.output.length === 3) { const cube = utils.splitArray(result, lastKernel.output[0] * lastKernel.output[1]); return cube.map(function(x) { return utils.splitArray(x, lastKernel.output[0]); }); } } constructor(source, settings) { super(source, settings); this.transferValues = null; this.formatValues = null; this.TextureConstructor = null; this.renderOutput = null; this.renderRawOutput = null; this.texSize = null; this.translatedSource = null; this.compiledFragmentShader = null; this.compiledVertexShader = null; this.switchingKernels = null; this._textureSwitched = null; this._mappedTextureSwitched = null; } checkTextureSize() { const { features } = this.constructor; if (this.texSize[0] > features.maxTextureSize || this.texSize[1] > features.maxTextureSize) { throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${features.maxTextureSize},${features.maxTextureSize}]`); } } translateSource() { throw new Error(`"translateSource" not defined on ${this.constructor.name}`); } pickRenderStrategy(args) { if (this.graphical) { this.renderRawOutput = this.readPackedPixelsToUint8Array; this.transferValues = (pixels) => pixels; this.TextureConstructor = GLTextureGraphical; return null; } if (this.precision === 'unsigned') { this.renderRawOutput = this.readPackedPixelsToUint8Array; this.transferValues = this.readPackedPixelsToFloat32Array; if (this.pipeline) { this.renderOutput = this.renderTexture; if (this.subKernels !== null) { this.renderKernels = this.renderKernelsToTextures; } switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': if (this.output[2] > 0) { this.TextureConstructor = GLTextureUnsigned3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureUnsigned2D; return null; } else { this.TextureConstructor = GLTextureUnsigned; return null; } case 'Array(2)': case 'Array(3)': case 'Array(4)': return this.requestFallback(args); } } else { if (this.subKernels !== null) { this.renderKernels = this.renderKernelsToArrays; } switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': this.renderOutput = this.renderValues; if (this.output[2] > 0) { this.TextureConstructor = GLTextureUnsigned3D; this.formatValues = utils.erect3DPackedFloat; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureUnsigned2D; this.formatValues = utils.erect2DPackedFloat; return null; } else { this.TextureConstructor = GLTextureUnsigned; this.formatValues = utils.erectPackedFloat; return null; } case 'Array(2)': case 'Array(3)': case 'Array(4)': return this.requestFallback(args); } } } else if (this.precision === 'single') { this.renderRawOutput = this.readFloatPixelsToFloat32Array; this.transferValues = this.readFloatPixelsToFloat32Array; if (this.pipeline) { this.renderOutput = this.renderTexture; if (this.subKernels !== null) { this.renderKernels = this.renderKernelsToTextures; } switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': { if (this.optimizeFloatMemory) { if (this.output[2] > 0) { this.TextureConstructor = GLTextureMemoryOptimized3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureMemoryOptimized2D; return null; } else { this.TextureConstructor = GLTextureMemoryOptimized; return null; } } else { if (this.output[2] > 0) { this.TextureConstructor = GLTextureFloat3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureFloat2D; return null; } else { this.TextureConstructor = GLTextureFloat; return null; } } } case 'Array(2)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray2Float3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray2Float2D; return null; } else { this.TextureConstructor = GLTextureArray2Float; return null; } } case 'Array(3)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray3Float3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray3Float2D; return null; } else { this.TextureConstructor = GLTextureArray3Float; return null; } } case 'Array(4)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray4Float3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray4Float2D; return null; } else { this.TextureConstructor = GLTextureArray4Float; return null; } } } } this.renderOutput = this.renderValues; if (this.subKernels !== null) { this.renderKernels = this.renderKernelsToArrays; } if (this.optimizeFloatMemory) { switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureMemoryOptimized3D; this.formatValues = utils.erectMemoryOptimized3DFloat; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureMemoryOptimized2D; this.formatValues = utils.erectMemoryOptimized2DFloat; return null; } else { this.TextureConstructor = GLTextureMemoryOptimized; this.formatValues = utils.erectMemoryOptimizedFloat; return null; } } case 'Array(2)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray2Float3D; this.formatValues = utils.erect3DArray2; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray2Float2D; this.formatValues = utils.erect2DArray2; return null; } else { this.TextureConstructor = GLTextureArray2Float; this.formatValues = utils.erectArray2; return null; } } case 'Array(3)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray3Float3D; this.formatValues = utils.erect3DArray3; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray3Float2D; this.formatValues = utils.erect2DArray3; return null; } else { this.TextureConstructor = GLTextureArray3Float; this.formatValues = utils.erectArray3; return null; } } case 'Array(4)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray4Float3D; this.formatValues = utils.erect3DArray4; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray4Float2D; this.formatValues = utils.erect2DArray4; return null; } else { this.TextureConstructor = GLTextureArray4Float; this.formatValues = utils.erectArray4; return null; } } } } else { switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureFloat3D; this.formatValues = utils.erect3DFloat; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureFloat2D; this.formatValues = utils.erect2DFloat; return null; } else { this.TextureConstructor = GLTextureFloat; this.formatValues = utils.erectFloat; return null; } } case 'Array(2)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray2Float3D; this.formatValues = utils.erect3DArray2; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray2Float2D; this.formatValues = utils.erect2DArray2; return null; } else { this.TextureConstructor = GLTextureArray2Float; this.formatValues = utils.erectArray2; return null; } } case 'Array(3)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray3Float3D; this.formatValues = utils.erect3DArray3; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray3Float2D; this.formatValues = utils.erect2DArray3; return null; } else { this.TextureConstructor = GLTextureArray3Float; this.formatValues = utils.erectArray3; return null; } } case 'Array(4)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray4Float3D; this.formatValues = utils.erect3DArray4; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray4Float2D; this.formatValues = utils.erect2DArray4; return null; } else { this.TextureConstructor = GLTextureArray4Float; this.formatValues = utils.erectArray4; return null; } } } } } else { throw new Error(`unhandled precision of "${this.precision}"`); } throw new Error(`unhandled return type "${this.returnType}"`); } getKernelString() { throw new Error(`abstract method call`); } getMainResultTexture() { switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Integer': case 'Number': return this.getMainResultNumberTexture(); case 'Array(2)': return this.getMainResultArray2Texture(); case 'Array(3)': return this.getMainResultArray3Texture(); case 'Array(4)': return this.getMainResultArray4Texture(); default: throw new Error(`unhandled returnType type ${ this.returnType }`); } } getMainResultKernelNumberTexture() { throw new Error(`abstract method call`); } getMainResultSubKernelNumberTexture() { throw new Error(`abstract method call`); } getMainResultKernelArray2Texture() { throw new Error(`abstract method call`); } getMainResultSubKernelArray2Texture() { throw new Error(`abstract method call`); } getMainResultKernelArray3Texture() { throw new Error(`abstract method call`); } getMainResultSubKernelArray3Texture() { throw new Error(`abstract method call`); } getMainResultKernelArray4Texture() { throw new Error(`abstract method call`); } getMainResultSubKernelArray4Texture() { throw new Error(`abstract method call`); } getMainResultGraphical() { throw new Error(`abstract method call`); } getMainResultMemoryOptimizedFloats() { throw new Error(`abstract method call`); } getMainResultPackedPixels() { throw new Error(`abstract method call`); } getMainResultString() { if (this.graphical) { return this.getMainResultGraphical(); } else if (this.precision === 'single') { if (this.optimizeFloatMemory) { return this.getMainResultMemoryOptimizedFloats(); } return this.getMainResultTexture(); } else { return this.getMainResultPackedPixels(); } } getMainResultNumberTexture() { return utils.linesToString(this.getMainResultKernelNumberTexture()) + utils.linesToString(this.getMainResultSubKernelNumberTexture()); } getMainResultArray2Texture() { return utils.linesToString(this.getMainResultKernelArray2Texture()) + utils.linesToString(this.getMainResultSubKernelArray2Texture()); } getMainResultArray3Texture() { return utils.linesToString(this.getMainResultKernelArray3Texture()) + utils.linesToString(this.getMainResultSubKernelArray3Texture()); } getMainResultArray4Texture() { return utils.linesToString(this.getMainResultKernelArray4Texture()) + utils.linesToString(this.getMainResultSubKernelArray4Texture()); } getFloatTacticDeclaration() { const variablePrecision = this.getVariablePrecisionString(this.texSize, this.tactic); return `precision ${variablePrecision} float;\n`; } getIntTacticDeclaration() { return `precision ${this.getVariablePrecisionString(this.texSize, this.tactic, true)} int;\n`; } getSampler2DTacticDeclaration() { return `precision ${this.getVariablePrecisionString(this.texSize, this.tactic)} sampler2D;\n`; } getSampler2DArrayTacticDeclaration() { return `precision ${this.getVariablePrecisionString(this.texSize, this.tactic)} sampler2DArray;\n`; } renderTexture() { return this.immutable ? this.texture.clone() : this.texture; } readPackedPixelsToUint8Array() { if (this.precision !== 'unsigned') throw new Error('Requires this.precision to be "unsigned"'); const { texSize, context: gl } = this; const result = new Uint8Array(texSize[0] * texSize[1] * 4); gl.readPixels(0, 0, texSize[0], texSize[1], gl.RGBA, gl.UNSIGNED_BYTE, result); return result; } readPackedPixelsToFloat32Array() { return new Float32Array(this.readPackedPixelsToUint8Array().buffer); } readFloatPixelsToFloat32Array() { if (this.precision !== 'single') throw new Error('Requires this.precision to be "single"'); const { texSize, context: gl } = this; const w = texSize[0]; const h = texSize[1]; const result = new Float32Array(w * h * 4); gl.readPixels(0, 0, w, h, gl.RGBA, gl.FLOAT, result); return result; } getPixels(flip) { const { context: gl, output } = this; const [width, height] = output; const pixels = new Uint8Array(width * height * 4); gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); return new Uint8ClampedArray((flip ? pixels : utils.flipPixels(pixels, width, height)).buffer); } renderKernelsToArrays() { const result = { result: this.renderOutput(), }; for (let i = 0; i < this.subKernels.length; i++) { result[this.subKernels[i].property] = this.mappedTextures[i].toArray(); } return result; } renderKernelsToTextures() { const result = { result: this.renderOutput(), }; if (this.immutable) { for (let i = 0; i < this.subKernels.length; i++) { result[this.subKernels[i].property] = this.mappedTextures[i].clone(); } } else { for (let i = 0; i < this.subKernels.length; i++) { result[this.subKernels[i].property] = this.mappedTextures[i]; } } return result; } resetSwitchingKernels() { const existingValue = this.switchingKernels; this.switchingKernels = null; return existingValue; } setOutput(output) { const newOutput = this.toKernelOutput(output); if (this.program) { if (!this.dynamicOutput) { throw new Error('Resizing a kernel with dynamicOutput: false is not possible'); } const newThreadDim = [newOutput[0], newOutput[1] || 1, newOutput[2] || 1]; const newTexSize = utils.getKernelTextureSize({ optimizeFloatMemory: this.optimizeFloatMemory, precision: this.precision, }, newThreadDim); const oldTexSize = this.texSize; if (oldTexSize) { const oldPrecision = this.getVariablePrecisionString(oldTexSize, this.tactic); const newPrecision = this.getVariablePrecisionString(newTexSize, this.tactic); if (oldPrecision !== newPrecision) { if (this.debug) { console.warn('Precision requirement changed, asking GPU instance to recompile'); } this.switchKernels({ type: 'outputPrecisionMismatch', precision: newPrecision, needed: output }); return; } } this.output = newOutput; this.threadDim = newThreadDim; this.texSize = newTexSize; const { context: gl } = this; gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); this.updateMaxTexSize(); this.framebuffer.width = this.texSize[0]; this.framebuffer.height = this.texSize[1]; gl.viewport(0, 0, this.maxTexSize[0], this.maxTexSize[1]); this.canvas.width = this.maxTexSize[0]; this.canvas.height = this.maxTexSize[1]; if (this.texture) { this.texture.delete(); } this.texture = null; this._setupOutputTexture(); if (this.mappedTextures && this.mappedTextures.length > 0) { for (let i = 0; i < this.mappedTextures.length; i++) { this.mappedTextures[i].delete(); } this.mappedTextures = null; this._setupSubOutputTextures(); } } else { this.output = newOutput; } return this; } renderValues() { return this.formatValues( this.transferValues(), this.output[0], this.output[1], this.output[2] ); } switchKernels(reason) { if (this.switchingKernels) { this.switchingKernels.push(reason); } else { this.switchingKernels = [reason]; } } getVariablePrecisionString(textureSize = this.texSize, tactic = this.tactic, isInt = false) { if (!tactic) { if (!this.constructor.features.isSpeedTacticSupported) return 'highp'; const low = this.constructor.features[isInt ? 'lowIntPrecision' : 'lowFloatPrecision']; const medium = this.constructor.features[isInt ? 'mediumIntPrecision' : 'mediumFloatPrecision']; const high = this.constructor.features[isInt ? 'highIntPrecision' : 'highFloatPrecision']; const requiredSize = Math.log2(textureSize[0] * textureSize[1]); if (requiredSize <= low.rangeMax) { return 'lowp'; } else if (requiredSize <= medium.rangeMax) { return 'mediump'; } else if (requiredSize <= high.rangeMax) { return 'highp'; } else { throw new Error(`The required size exceeds that of the ability of your system`); } } switch (tactic) { case 'speed': return 'lowp'; case 'balanced': return 'mediump'; case 'precision': return 'highp'; default: throw new Error(`Unknown tactic "${tactic}" use "speed", "balanced", "precision", or empty for auto`); } } updateTextureArgumentRefs(kernelValue, arg) { if (!this.immutable) return; if (this.texture.texture === arg.texture) { const { prevArg } = kernelValue; if (prevArg) { if (prevArg.texture._refs === 1) { this.texture.delete(); this.texture = prevArg.clone(); this._textureSwitched = true; } prevArg.delete(); } kernelValue.prevArg = arg.clone(); } else if (this.mappedTextures && this.mappedTextures.length > 0) { const { mappedTextures } = this; for (let i = 0; i < mappedTextures.length; i++) { const mappedTexture = mappedTextures[i]; if (mappedTexture.texture === arg.texture) { const { prevArg } = kernelValue; if (prevArg) { if (prevArg.texture._refs === 1) { mappedTexture.delete(); mappedTextures[i] = prevArg.clone(); this._mappedTextureSwitched[i] = true; } prevArg.delete(); } kernelValue.prevArg = arg.clone(); return; } } } } onActivate(previousKernel) { this._textureSwitched = true; this.texture = previousKernel.texture; if (this.mappedTextures) { for (let i = 0; i < this.mappedTextures.length; i++) { this._mappedTextureSwitched[i] = true; } this.mappedTextures = previousKernel.mappedTextures; } } initCanvas() {} } const typeMap = { int: 'Integer', float: 'Number', vec2: 'Array(2)', vec3: 'Array(3)', vec4: 'Array(4)', }; module.exports = { GLKernel }; },{"../../utils":114,"../kernel":36,"./texture/array-2-float":16,"./texture/array-2-float-2d":14,"./texture/array-2-float-3d":15,"./texture/array-3-float":19,"./texture/array-3-float-2d":17,"./texture/array-3-float-3d":18,"./texture/array-4-float":22,"./texture/array-4-float-2d":20,"./texture/array-4-float-3d":21,"./texture/float":25,"./texture/float-2d":23,"./texture/float-3d":24,"./texture/graphical":26,"./texture/memory-optimized":30,"./texture/memory-optimized-2d":28,"./texture/memory-optimized-3d":29,"./texture/unsigned":33,"./texture/unsigned-2d":31,"./texture/unsigned-3d":32}],14:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray2Float2D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(2)'; } toArray() { return utils.erect2DArray2(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureArray2Float2D }; },{"../../../utils":114,"./float":25}],15:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray2Float3D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(2)'; } toArray() { return utils.erect3DArray2(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureArray2Float3D }; },{"../../../utils":114,"./float":25}],16:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray2Float extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(2)'; } toArray() { return utils.erectArray2(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureArray2Float }; },{"../../../utils":114,"./float":25}],17:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray3Float2D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(3)'; } toArray() { return utils.erect2DArray3(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureArray3Float2D }; },{"../../../utils":114,"./float":25}],18:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray3Float3D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(3)'; } toArray() { return utils.erect3DArray3(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureArray3Float3D }; },{"../../../utils":114,"./float":25}],19:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray3Float extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(3)'; } toArray() { return utils.erectArray3(this.renderValues(), this.output[0]); } } module.exports = { GLTextureArray3Float }; },{"../../../utils":114,"./float":25}],20:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray4Float2D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(4)'; } toArray() { return utils.erect2DArray4(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureArray4Float2D }; },{"../../../utils":114,"./float":25}],21:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray4Float3D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(4)'; } toArray() { return utils.erect3DArray4(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureArray4Float3D }; },{"../../../utils":114,"./float":25}],22:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray4Float extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(4)'; } toArray() { return utils.erectArray4(this.renderValues(), this.output[0]); } } module.exports = { GLTextureArray4Float }; },{"../../../utils":114,"./float":25}],23:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureFloat2D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(1)'; } toArray() { return utils.erect2DFloat(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureFloat2D }; },{"../../../utils":114,"./float":25}],24:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureFloat3D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(1)'; } toArray() { return utils.erect3DFloat(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureFloat3D }; },{"../../../utils":114,"./float":25}],25:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTexture } = require('./index'); class GLTextureFloat extends GLTexture { get textureType() { return this.context.FLOAT; } constructor(settings) { super(settings); this.type = 'ArrayTexture(1)'; } renderRawOutput() { const gl = this.context; const size = this.size; gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer()); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0 ); const result = new Float32Array(size[0] * size[1] * 4); gl.readPixels(0, 0, size[0], size[1], gl.RGBA, gl.FLOAT, result); return result; } renderValues() { if (this._deleted) return null; return this.renderRawOutput(); } toArray() { return utils.erectFloat(this.renderValues(), this.output[0]); } } module.exports = { GLTextureFloat }; },{"../../../utils":114,"./index":27}],26:[function(require,module,exports){ const { GLTextureUnsigned } = require('./unsigned'); class GLTextureGraphical extends GLTextureUnsigned { constructor(settings) { super(settings); this.type = 'ArrayTexture(4)'; } toArray() { return this.renderValues(); } } module.exports = { GLTextureGraphical }; },{"./unsigned":33}],27:[function(require,module,exports){ const { Texture } = require('../../../texture'); class GLTexture extends Texture { get textureType() { throw new Error(`"textureType" not implemented on ${ this.name }`); } clone() { return new this.constructor(this); } beforeMutate() { if (this.texture._refs > 1) { this.newTexture(); return true; } return false; } cloneTexture() { this.texture._refs--; const { context: gl, size, texture, kernel } = this; if (kernel.debug) { console.warn('cloning internal texture'); } gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer()); selectTexture(gl, texture); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); const target = gl.createTexture(); selectTexture(gl, target); gl.texImage2D(gl.TEXTURE_2D, 0, this.internalFormat, size[0], size[1], 0, this.textureFormat, this.textureType, null); gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 0, 0, size[0], size[1]); target._refs = 1; this.texture = target; } newTexture() { this.texture._refs--; const gl = this.context; const size = this.size; const kernel = this.kernel; if (kernel.debug) { console.warn('new internal texture'); } const target = gl.createTexture(); selectTexture(gl, target); gl.texImage2D(gl.TEXTURE_2D, 0, this.internalFormat, size[0], size[1], 0, this.textureFormat, this.textureType, null); target._refs = 1; this.texture = target; } clear() { if (this.texture._refs) { this.texture._refs--; const gl = this.context; const target = this.texture = gl.createTexture(); selectTexture(gl, target); const size = this.size; target._refs = 1; gl.texImage2D(gl.TEXTURE_2D, 0, this.internalFormat, size[0], size[1], 0, this.textureFormat, this.textureType, null); } const { context: gl, texture } = this; gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer()); gl.bindTexture(gl.TEXTURE_2D, texture); selectTexture(gl, texture); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); } delete() { if (this._deleted) return; this._deleted = true; if (this.texture._refs) { this.texture._refs--; if (this.texture._refs) return; } this.context.deleteTexture(this.texture); } framebuffer() { if (!this._framebuffer) { this._framebuffer = this.kernel.getRawValueFramebuffer(this.size[0], this.size[1]); } return this._framebuffer; } } function selectTexture(gl, texture) { gl.activeTexture(gl.TEXTURE15); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); } module.exports = { GLTexture }; },{"../../../texture":113}],28:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureMemoryOptimized2D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'MemoryOptimizedNumberTexture'; } toArray() { return utils.erectMemoryOptimized2DFloat(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureMemoryOptimized2D }; },{"../../../utils":114,"./float":25}],29:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureMemoryOptimized3D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'MemoryOptimizedNumberTexture'; } toArray() { return utils.erectMemoryOptimized3DFloat(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureMemoryOptimized3D }; },{"../../../utils":114,"./float":25}],30:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureMemoryOptimized extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'MemoryOptimizedNumberTexture'; } toArray() { return utils.erectMemoryOptimizedFloat(this.renderValues(), this.output[0]); } } module.exports = { GLTextureMemoryOptimized }; },{"../../../utils":114,"./float":25}],31:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureUnsigned } = require('./unsigned'); class GLTextureUnsigned2D extends GLTextureUnsigned { constructor(settings) { super(settings); this.type = 'NumberTexture'; } toArray() { return utils.erect2DPackedFloat(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureUnsigned2D }; },{"../../../utils":114,"./unsigned":33}],32:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTextureUnsigned } = require('./unsigned'); class GLTextureUnsigned3D extends GLTextureUnsigned { constructor(settings) { super(settings); this.type = 'NumberTexture'; } toArray() { return utils.erect3DPackedFloat(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureUnsigned3D }; },{"../../../utils":114,"./unsigned":33}],33:[function(require,module,exports){ const { utils } = require('../../../utils'); const { GLTexture } = require('./index'); class GLTextureUnsigned extends GLTexture { get textureType() { return this.context.UNSIGNED_BYTE; } constructor(settings) { super(settings); this.type = 'NumberTexture'; } renderRawOutput() { const { context: gl } = this; gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer()); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0 ); const result = new Uint8Array(this.size[0] * this.size[1] * 4); gl.readPixels(0, 0, this.size[0], this.size[1], gl.RGBA, gl.UNSIGNED_BYTE, result); return result; } renderValues() { if (this._deleted) return null; return new Float32Array(this.renderRawOutput().buffer); } toArray() { return utils.erectPackedFloat(this.renderValues(), this.output[0]); } } module.exports = { GLTextureUnsigned }; },{"../../../utils":114,"./index":27}],34:[function(require,module,exports){ const getContext = require('gl'); const { WebGLKernel } = require('../web-gl/kernel'); const { glKernelString } = require('../gl/kernel-string'); let isSupported = null; let testCanvas = null; let testContext = null; let testExtensions = null; let features = null; class HeadlessGLKernel extends WebGLKernel { static get isSupported() { if (isSupported !== null) return isSupported; this.setupFeatureChecks(); isSupported = testContext !== null; return isSupported; } static setupFeatureChecks() { testCanvas = null; testExtensions = null; if (typeof getContext !== 'function') return; try { testContext = getContext(2, 2, { preserveDrawingBuffer: true }); if (!testContext || !testContext.getExtension) return; testExtensions = { STACKGL_resize_drawingbuffer: testContext.getExtension('STACKGL_resize_drawingbuffer'), STACKGL_destroy_context: testContext.getExtension('STACKGL_destroy_context'), OES_texture_float: testContext.getExtension('OES_texture_float'), OES_texture_float_linear: testContext.getExtension('OES_texture_float_linear'), OES_element_index_uint: testContext.getExtension('OES_element_index_uint'), WEBGL_draw_buffers: testContext.getExtension('WEBGL_draw_buffers'), WEBGL_color_buffer_float: testContext.getExtension('WEBGL_color_buffer_float'), }; features = this.getFeatures(); } catch (e) { console.warn(e); } } static isContextMatch(context) { try { return context.getParameter(context.RENDERER) === 'ANGLE'; } catch (e) { return false; } } static getIsTextureFloat() { return Boolean(testExtensions.OES_texture_float); } static getIsDrawBuffers() { return Boolean(testExtensions.WEBGL_draw_buffers); } static getChannelCount() { return testExtensions.WEBGL_draw_buffers ? testContext.getParameter(testExtensions.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL) : 1; } static getMaxTextureSize() { return testContext.getParameter(testContext.MAX_TEXTURE_SIZE); } static get testCanvas() { return testCanvas; } static get testContext() { return testContext; } static get features() { return features; } initCanvas() { return {}; } initContext() { return getContext(2, 2, { preserveDrawingBuffer: true }); } initExtensions() { this.extensions = { STACKGL_resize_drawingbuffer: this.context.getExtension('STACKGL_resize_drawingbuffer'), STACKGL_destroy_context: this.context.getExtension('STACKGL_destroy_context'), OES_texture_float: this.context.getExtension('OES_texture_float'), OES_texture_float_linear: this.context.getExtension('OES_texture_float_linear'), OES_element_index_uint: this.context.getExtension('OES_element_index_uint'), WEBGL_draw_buffers: this.context.getExtension('WEBGL_draw_buffers'), }; } build() { super.build.apply(this, arguments); if (!this.fallbackRequested) { this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0], this.maxTexSize[1]); } } destroyExtensions() { this.extensions.STACKGL_resize_drawingbuffer = null; this.extensions.STACKGL_destroy_context = null; this.extensions.OES_texture_float = null; this.extensions.OES_texture_float_linear = null; this.extensions.OES_element_index_uint = null; this.extensions.WEBGL_draw_buffers = null; } static destroyContext(context) { const extension = context.getExtension('STACKGL_destroy_context'); if (extension && extension.destroy) { extension.destroy(); } } toString() { const setupContextString = `const gl = context || require('gl')(1, 1);\n`; const destroyContextString = ` if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n`; return glKernelString(this.constructor, arguments, this, setupContextString, destroyContextString); } setOutput(output) { super.setOutput(output); if (this.graphical && this.extensions.STACKGL_resize_drawingbuffer) { this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0], this.maxTexSize[1]); } return this; } } module.exports = { HeadlessGLKernel }; },{"../gl/kernel-string":12,"../web-gl/kernel":70,"gl":2}],35:[function(require,module,exports){ class KernelValue { constructor(value, settings) { const { name, kernel, context, checkContext, onRequestContextHandle, onUpdateValueMismatch, origin, strictIntegers, type, tactic, } = settings; if (!name) { throw new Error('name not set'); } if (!type) { throw new Error('type not set'); } if (!origin) { throw new Error('origin not set'); } if (origin !== 'user' && origin !== 'constants') { throw new Error(`origin must be "user" or "constants" value is "${ origin }"`); } if (!onRequestContextHandle) { throw new Error('onRequestContextHandle is not set'); } this.name = name; this.origin = origin; this.tactic = tactic; this.varName = origin === 'constants' ? `constants.${name}` : name; this.kernel = kernel; this.strictIntegers = strictIntegers; this.type = value.type || type; this.size = value.size || null; this.index = null; this.context = context; this.checkContext = checkContext !== null && checkContext !== undefined ? checkContext : true; this.contextHandle = null; this.onRequestContextHandle = onRequestContextHandle; this.onUpdateValueMismatch = onUpdateValueMismatch; this.forceUploadEachRun = null; } get id() { return `${this.origin}_${name}`; } getSource() { throw new Error(`"getSource" not defined on ${ this.constructor.name }`); } updateValue(value) { throw new Error(`"updateValue" not defined on ${ this.constructor.name }`); } } module.exports = { KernelValue }; },{}],36:[function(require,module,exports){ const { utils } = require('../utils'); const { Input } = require('../input'); class Kernel { static get isSupported() { throw new Error(`"isSupported" not implemented on ${ this.name }`); } static isContextMatch(context) { throw new Error(`"isContextMatch" not implemented on ${ this.name }`); } static getFeatures() { throw new Error(`"getFeatures" not implemented on ${ this.name }`); } static destroyContext(context) { throw new Error(`"destroyContext" called on ${ this.name }`); } static nativeFunctionArguments() { throw new Error(`"nativeFunctionArguments" called on ${ this.name }`); } static nativeFunctionReturnType() { throw new Error(`"nativeFunctionReturnType" called on ${ this.name }`); } static combineKernels() { throw new Error(`"combineKernels" called on ${ this.name }`); } constructor(source, settings) { if (typeof source !== 'object') { if (typeof source !== 'string') { throw new Error('source not a string'); } if (!utils.isFunctionString(source)) { throw new Error('source not a function string'); } } this.useLegacyEncoder = false; this.fallbackRequested = false; this.onRequestFallback = null; this.argumentNames = typeof source === 'string' ? utils.getArgumentNamesFromString(source) : null; this.argumentTypes = null; this.argumentSizes = null; this.argumentBitRatios = null; this.kernelArguments = null; this.kernelConstants = null; this.forceUploadKernelConstants = null; this.source = source; this.output = null; this.debug = false; this.graphical = false; this.loopMaxIterations = 0; this.constants = null; this.constantTypes = null; this.constantBitRatios = null; this.dynamicArguments = false; this.dynamicOutput = false; this.canvas = null; this.context = null; this.checkContext = null; this.gpu = null; this.functions = null; this.nativeFunctions = null; this.injectedNative = null; this.subKernels = null; this.validate = true; this.immutable = false; this.pipeline = false; this.precision = null; this.tactic = null; this.plugins = null; this.returnType = null; this.leadingReturnStatement = null; this.followingReturnStatement = null; this.optimizeFloatMemory = null; this.strictIntegers = false; this.fixIntegerDivisionAccuracy = null; this.built = false; this.signature = null; } mergeSettings(settings) { for (let p in settings) { if (!settings.hasOwnProperty(p) || !this.hasOwnProperty(p)) continue; switch (p) { case 'output': if (!Array.isArray(settings.output)) { this.setOutput(settings.output); continue; } break; case 'functions': this.functions = []; for (let i = 0; i < settings.functions.length; i++) { this.addFunction(settings.functions[i]); } continue; case 'graphical': if (settings[p] && !settings.hasOwnProperty('precision')) { this.precision = 'unsigned'; } this[p] = settings[p]; continue; case 'nativeFunctions': if (!settings.nativeFunctions) continue; this.nativeFunctions = []; for (let i = 0; i < settings.nativeFunctions.length; i++) { const s = settings.nativeFunctions[i]; const { name, source } = s; this.addNativeFunction(name, source, s); } continue; } this[p] = settings[p]; } if (!this.canvas) this.canvas = this.initCanvas(); if (!this.context) this.context = this.initContext(); if (!this.plugins) this.plugins = this.initPlugins(settings); } build() { throw new Error(`"build" not defined on ${ this.constructor.name }`); } run() { throw new Error(`"run" not defined on ${ this.constructor.name }`) } initCanvas() { throw new Error(`"initCanvas" not defined on ${ this.constructor.name }`); } initContext() { throw new Error(`"initContext" not defined on ${ this.constructor.name }`); } initPlugins(settings) { throw new Error(`"initPlugins" not defined on ${ this.constructor.name }`); } addFunction(source, settings = {}) { if (source.name && source.source && source.argumentTypes && 'returnType' in source) { this.functions.push(source); } else if ('settings' in source && 'source' in source) { this.functions.push(this.functionToIGPUFunction(source.source, source.settings)); } else if (typeof source === 'string' || typeof source === 'function') { this.functions.push(this.functionToIGPUFunction(source, settings)); } else { throw new Error(`function not properly defined`); } return this; } addNativeFunction(name, source, settings = {}) { const { argumentTypes, argumentNames } = settings.argumentTypes ? splitArgumentTypes(settings.argumentTypes) : this.constructor.nativeFunctionArguments(source) || {}; this.nativeFunctions.push({ name, source, settings, argumentTypes, argumentNames, returnType: settings.returnType || this.constructor.nativeFunctionReturnType(source) }); return this; } setupArguments(args) { this.kernelArguments = []; if (!this.argumentTypes) { if (!this.argumentTypes) { this.argumentTypes = []; for (let i = 0; i < args.length; i++) { const argType = utils.getVariableType(args[i], this.strictIntegers); const type = argType === 'Integer' ? 'Number' : argType; this.argumentTypes.push(type); this.kernelArguments.push({ type }); } } } else { for (let i = 0; i < this.argumentTypes.length; i++) { this.kernelArguments.push({ type: this.argumentTypes[i] }); } } this.argumentSizes = new Array(args.length); this.argumentBitRatios = new Int32Array(args.length); for (let i = 0; i < args.length; i++) { const arg = args[i]; this.argumentSizes[i] = arg.constructor === Input ? arg.size : null; this.argumentBitRatios[i] = this.getBitRatio(arg); } if (this.argumentNames.length !== args.length) { throw new Error(`arguments are miss-aligned`); } } setupConstants() { this.kernelConstants = []; let needsConstantTypes = this.constantTypes === null; if (needsConstantTypes) { this.constantTypes = {}; } this.constantBitRatios = {}; if (this.constants) { for (let name in this.constants) { if (needsConstantTypes) { const type = utils.getVariableType(this.constants[name], this.strictIntegers); this.constantTypes[name] = type; this.kernelConstants.push({ name, type }); } else { this.kernelConstants.push({ name, type: this.constantTypes[name] }); } this.constantBitRatios[name] = this.getBitRatio(this.constants[name]); } } } setOptimizeFloatMemory(flag) { this.optimizeFloatMemory = flag; return this; } toKernelOutput(output) { if (output.hasOwnProperty('x')) { if (output.hasOwnProperty('y')) { if (output.hasOwnProperty('z')) { return [output.x, output.y, output.z]; } else { return [output.x, output.y]; } } else { return [output.x]; } } else { return output; } } setOutput(output) { this.output = this.toKernelOutput(output); return this; } setDebug(flag) { this.debug = flag; return this; } setGraphical(flag) { this.graphical = flag; this.precision = 'unsigned'; return this; } setLoopMaxIterations(max) { this.loopMaxIterations = max; return this; } setConstants(constants) { this.constants = constants; return this; } setConstantTypes(constantTypes) { this.constantTypes = constantTypes; return this; } setFunctions(functions) { for (let i = 0; i < functions.length; i++) { this.addFunction(functions[i]); } return this; } setNativeFunctions(nativeFunctions) { for (let i = 0; i < nativeFunctions.length; i++) { const settings = nativeFunctions[i]; const { name, source } = settings; this.addNativeFunction(name, source, settings); } return this; } setInjectedNative(injectedNative) { this.injectedNative = injectedNative; return this; } setPipeline(flag) { this.pipeline = flag; return this; } setPrecision(flag) { this.precision = flag; return this; } setDimensions(flag) { utils.warnDeprecated('method', 'setDimensions', 'setOutput'); this.output = flag; return this; } setOutputToTexture(flag) { utils.warnDeprecated('method', 'setOutputToTexture', 'setPipeline'); this.pipeline = flag; return this; } setImmutable(flag) { this.immutable = flag; return this; } setCanvas(canvas) { this.canvas = canvas; return this; } setStrictIntegers(flag) { this.strictIntegers = flag; return this; } setDynamicOutput(flag) { this.dynamicOutput = flag; return this; } setHardcodeConstants(flag) { utils.warnDeprecated('method', 'setHardcodeConstants'); this.setDynamicOutput(flag); this.setDynamicArguments(flag); return this; } setDynamicArguments(flag) { this.dynamicArguments = flag; return this; } setUseLegacyEncoder(flag) { this.useLegacyEncoder = flag; return this; } setWarnVarUsage(flag) { utils.warnDeprecated('method', 'setWarnVarUsage'); return this; } getCanvas() { utils.warnDeprecated('method', 'getCanvas'); return this.canvas; } getWebGl() { utils.warnDeprecated('method', 'getWebGl'); return this.context; } setContext(context) { this.context = context; return this; } setArgumentTypes(argumentTypes) { if (Array.isArray(argumentTypes)) { this.argumentTypes = argumentTypes; } else { this.argumentTypes = []; for (const p in argumentTypes) { if (!argumentTypes.hasOwnProperty(p)) continue; const argumentIndex = this.argumentNames.indexOf(p); if (argumentIndex === -1) throw new Error(`unable to find argument ${ p }`); this.argumentTypes[argumentIndex] = argumentTypes[p]; } } return this; } setTactic(tactic) { this.tactic = tactic; return this; } requestFallback(args) { if (!this.onRequestFallback) { throw new Error(`"onRequestFallback" not defined on ${ this.constructor.name }`); } this.fallbackRequested = true; return this.onRequestFallback(args); } validateSettings() { throw new Error(`"validateSettings" not defined on ${ this.constructor.name }`); } addSubKernel(subKernel) { if (this.subKernels === null) { this.subKernels = []; } if (!subKernel.source) throw new Error('subKernel missing "source" property'); if (!subKernel.property && isNaN(subKernel.property)) throw new Error('subKernel missing "property" property'); if (!subKernel.name) throw new Error('subKernel missing "name" property'); this.subKernels.push(subKernel); return this; } destroy(removeCanvasReferences) { throw new Error(`"destroy" called on ${ this.constructor.name }`); } getBitRatio(value) { if (this.precision === 'single') { return 4; } else if (Array.isArray(value[0])) { return this.getBitRatio(value[0]); } else if (value.constructor === Input) { return this.getBitRatio(value.value); } switch (value.constructor) { case Uint8ClampedArray: case Uint8Array: case Int8Array: return 1; case Uint16Array: case Int16Array: return 2; case Float32Array: case Int32Array: default: return 4; } } getPixels(flip) { throw new Error(`"getPixels" called on ${ this.constructor.name }`); } checkOutput() { if (!this.output || !utils.isArray(this.output)) throw new Error('kernel.output not an array'); if (this.output.length < 1) throw new Error('kernel.output is empty, needs at least 1 value'); for (let i = 0; i < this.output.length; i++) { if (isNaN(this.output[i]) || this.output[i] < 1) { throw new Error(`${ this.constructor.name }.output[${ i }] incorrectly defined as \`${ this.output[i] }\`, needs to be numeric, and greater than 0`); } } } prependString(value) { throw new Error(`"prependString" called on ${ this.constructor.name }`); } hasPrependString(value) { throw new Error(`"hasPrependString" called on ${ this.constructor.name }`); } toJSON() { return { settings: { output: this.output, pipeline: this.pipeline, argumentNames: this.argumentNames, argumentsTypes: this.argumentTypes, constants: this.constants, pluginNames: this.plugins ? this.plugins.map(plugin => plugin.name) : null, returnType: this.returnType, } }; } buildSignature(args) { const Constructor = this.constructor; this.signature = Constructor.getSignature(this, Constructor.getArgumentTypes(this, args)); } static getArgumentTypes(kernel, args) { const argumentTypes = new Array(args.length); for (let i = 0; i < args.length; i++) { const arg = args[i]; const type = kernel.argumentTypes[i]; if (arg.type) { argumentTypes[i] = arg.type; } else { switch (type) { case 'Number': case 'Integer': case 'Float': case 'ArrayTexture(1)': argumentTypes[i] = utils.getVariableType(arg); break; default: argumentTypes[i] = type; } } } return argumentTypes; } static getSignature(kernel, argumentTypes) { throw new Error(`"getSignature" not implemented on ${ this.name }`); } functionToIGPUFunction(source, settings = {}) { if (typeof source !== 'string' && typeof source !== 'function') throw new Error('source not a string or function'); const sourceString = typeof source === 'string' ? source : source.toString(); let argumentTypes = []; if (Array.isArray(settings.argumentTypes)) { argumentTypes = settings.argumentTypes; } else if (typeof settings.argumentTypes === 'object') { argumentTypes = utils.getArgumentNamesFromString(sourceString) .map(name => settings.argumentTypes[name]) || []; } else { argumentTypes = settings.argumentTypes || []; } return { name: utils.getFunctionNameFromString(sourceString) || null, source: sourceString, argumentTypes, returnType: settings.returnType || null, }; } onActivate(previousKernel) {} } function splitArgumentTypes(argumentTypesObject) { const argumentNames = Object.keys(argumentTypesObject); const argumentTypes = []; for (let i = 0; i < argumentNames.length; i++) { const argumentName = argumentNames[i]; argumentTypes.push(argumentTypesObject[argumentName]); } return { argumentTypes, argumentNames }; } module.exports = { Kernel }; },{"../input":110,"../utils":114}],37:[function(require,module,exports){ const fragmentShader = `__HEADER__; __FLOAT_TACTIC_DECLARATION__; __INT_TACTIC_DECLARATION__; __SAMPLER_2D_TACTIC_DECLARATION__; const int LOOP_MAX = __LOOP_MAX__; __PLUGINS__; __CONSTANTS__; varying vec2 vTexCoord; float acosh(float x) { return log(x + sqrt(x * x - 1.0)); } float sinh(float x) { return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0; } float asinh(float x) { return log(x + sqrt(x * x + 1.0)); } float atan2(float v1, float v2) { if (v1 == 0.0 || v2 == 0.0) return 0.0; return atan(v1 / v2); } float atanh(float x) { x = (x + 1.0) / (x - 1.0); if (x < 0.0) { return 0.5 * log(-x); } return 0.5 * log(x); } float cbrt(float x) { if (x >= 0.0) { return pow(x, 1.0 / 3.0); } else { return -pow(x, 1.0 / 3.0); } } float cosh(float x) { return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; } float expm1(float x) { return pow(${Math.E}, x) - 1.0; } float fround(highp float x) { return x; } float imul(float v1, float v2) { return float(int(v1) * int(v2)); } float log10(float x) { return log2(x) * (1.0 / log2(10.0)); } float log1p(float x) { return log(1.0 + x); } float _pow(float v1, float v2) { if (v2 == 0.0) return 1.0; return pow(v1, v2); } float tanh(float x) { float e = exp(2.0 * x); return (e - 1.0) / (e + 1.0); } float trunc(float x) { if (x >= 0.0) { return floor(x); } else { return ceil(x); } } vec4 _round(vec4 x) { return floor(x + 0.5); } float _round(float x) { return floor(x + 0.5); } const int BIT_COUNT = 32; int modi(int x, int y) { return x - y * (x / y); } int bitwiseOr(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 || b > 0)) { break; } } return result; } int bitwiseXOR(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 || b > 0)) { break; } } return result; } int bitwiseAnd(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 && b > 0)) { break; } } return result; } int bitwiseNot(int a) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if (modi(a, 2) == 0) { result += n; } a = a / 2; n = n * 2; } return result; } int bitwiseZeroFillLeftShift(int n, int shift) { int maxBytes = BIT_COUNT; for (int i = 0; i < BIT_COUNT; i++) { if (maxBytes >= n) { break; } maxBytes *= 2; } for (int i = 0; i < BIT_COUNT; i++) { if (i >= shift) { break; } n *= 2; } int result = 0; int byteVal = 1; for (int i = 0; i < BIT_COUNT; i++) { if (i >= maxBytes) break; if (modi(n, 2) > 0) { result += byteVal; } n = int(n / 2); byteVal *= 2; } return result; } int bitwiseSignedRightShift(int num, int shifts) { return int(floor(float(num) / pow(2.0, float(shifts)))); } int bitwiseZeroFillRightShift(int n, int shift) { int maxBytes = BIT_COUNT; for (int i = 0; i < BIT_COUNT; i++) { if (maxBytes >= n) { break; } maxBytes *= 2; } for (int i = 0; i < BIT_COUNT; i++) { if (i >= shift) { break; } n /= 2; } int result = 0; int byteVal = 1; for (int i = 0; i < BIT_COUNT; i++) { if (i >= maxBytes) break; if (modi(n, 2) > 0) { result += byteVal; } n = int(n / 2); byteVal *= 2; } return result; } vec2 integerMod(vec2 x, float y) { vec2 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } vec3 integerMod(vec3 x, float y) { vec3 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } vec4 integerMod(vec4 x, vec4 y) { vec4 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } float integerMod(float x, float y) { float res = floor(mod(x, y)); return res * (res > floor(y) - 1.0 ? 0.0 : 1.0); } int integerMod(int x, int y) { return x - (y * int(x / y)); } __DIVIDE_WITH_INTEGER_CHECK__; // Here be dragons! // DO NOT OPTIMIZE THIS CODE // YOU WILL BREAK SOMETHING ON SOMEBODY\'S MACHINE // LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME const vec2 MAGIC_VEC = vec2(1.0, -256.0); const vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0); const vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536 float decode32(vec4 texel) { __DECODE32_ENDIANNESS__; texel *= 255.0; vec2 gte128; gte128.x = texel.b >= 128.0 ? 1.0 : 0.0; gte128.y = texel.a >= 128.0 ? 1.0 : 0.0; float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC); float res = exp2(_round(exponent)); texel.b = texel.b - 128.0 * gte128.x; res = dot(texel, SCALE_FACTOR) * exp2(_round(exponent-23.0)) + res; res *= gte128.y * -2.0 + 1.0; return res; } float decode16(vec4 texel, int index) { int channel = integerMod(index, 2); if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0; if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0; return 0.0; } float decode8(vec4 texel, int index) { int channel = integerMod(index, 4); if (channel == 0) return texel.r * 255.0; if (channel == 1) return texel.g * 255.0; if (channel == 2) return texel.b * 255.0; if (channel == 3) return texel.a * 255.0; return 0.0; } vec4 legacyEncode32(float f) { float F = abs(f); float sign = f < 0.0 ? 1.0 : 0.0; float exponent = floor(log2(F)); float mantissa = (exp2(-exponent) * F); // exponent += floor(log2(mantissa)); vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV; texel.rg = integerMod(texel.rg, 256.0); texel.b = integerMod(texel.b, 128.0); texel.a = exponent*0.5 + 63.5; texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0; texel = floor(texel); texel *= 0.003921569; // 1/255 __ENCODE32_ENDIANNESS__; return texel; } // https://github.com/gpujs/gpu.js/wiki/Encoder-details vec4 encode32(float value) { if (value == 0.0) return vec4(0, 0, 0, 0); float exponent; float mantissa; vec4 result; float sgn; sgn = step(0.0, -value); value = abs(value); exponent = floor(log2(value)); mantissa = value*pow(2.0, -exponent)-1.0; exponent = exponent+127.0; result = vec4(0,0,0,0); result.a = floor(exponent/2.0); exponent = exponent - result.a*2.0; result.a = result.a + 128.0*sgn; result.b = floor(mantissa * 128.0); mantissa = mantissa - result.b / 128.0; result.b = result.b + exponent*128.0; result.g = floor(mantissa*32768.0); mantissa = mantissa - result.g/32768.0; result.r = floor(mantissa*8388608.0); return result/255.0; } // Dragons end here int index; ivec3 threadId; ivec3 indexTo3D(int idx, ivec3 texDim) { int z = int(idx / (texDim.x * texDim.y)); idx -= z * int(texDim.x * texDim.y); int y = int(idx / texDim.x); int x = int(integerMod(idx, texDim.x)); return ivec3(x, y, z); } float get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize)); return decode32(texel); } float get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x * 2; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y)); return decode16(texel, index); } float get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x * 4; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y)); return decode8(texel, index); } float getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int channel = integerMod(index, 4); index = index / 4; int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize)); if (channel == 0) return texel.r; if (channel == 1) return texel.g; if (channel == 2) return texel.b; if (channel == 3) return texel.a; return 0.0; } vec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; return texture2D(tex, st / vec2(texSize)); } float getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return result[0]; } vec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return vec2(result[0], result[1]); } vec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + (texDim.x * (y + (texDim.y * z))); int channel = integerMod(index, 2); index = index / 2; int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize)); if (channel == 0) return vec2(texel.r, texel.g); if (channel == 1) return vec2(texel.b, texel.a); return vec2(0.0, 0.0); } vec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return vec3(result[0], result[1], result[2]); } vec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z)); int vectorIndex = fieldIndex / 4; int vectorOffset = fieldIndex - vectorIndex * 4; int readY = vectorIndex / texSize.x; int readX = vectorIndex - readY * texSize.x; vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize)); if (vectorOffset == 0) { return tex1.xyz; } else if (vectorOffset == 1) { return tex1.yzw; } else { readX++; if (readX >= texSize.x) { readX = 0; readY++; } vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize)); if (vectorOffset == 2) { return vec3(tex1.z, tex1.w, tex2.x); } else { return vec3(tex1.w, tex2.x, tex2.y); } } } vec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { return getImage2D(tex, texSize, texDim, z, y, x); } vec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int channel = integerMod(index, 2); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize)); return vec4(texel.r, texel.g, texel.b, texel.a); } vec4 actualColor; void color(float r, float g, float b, float a) { actualColor = vec4(r,g,b,a); } void color(float r, float g, float b) { color(r,g,b,1.0); } void color(sampler2D image) { actualColor = texture2D(image, vTexCoord); } float modulo(float number, float divisor) { if (number < 0.0) { number = abs(number); if (divisor < 0.0) { divisor = abs(divisor); } return -mod(number, divisor); } if (divisor < 0.0) { divisor = abs(divisor); } return mod(number, divisor); } __INJECTED_NATIVE__; __MAIN_CONSTANTS__; __MAIN_ARGUMENTS__; __KERNEL__; void main(void) { index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x; __MAIN_RESULT__; }`; module.exports = { fragmentShader }; },{}],38:[function(require,module,exports){ const { utils } = require('../../utils'); const { FunctionNode } = require('../function-node'); class WebGLFunctionNode extends FunctionNode { constructor(source, settings) { super(source, settings); if (settings && settings.hasOwnProperty('fixIntegerDivisionAccuracy')) { this.fixIntegerDivisionAccuracy = settings.fixIntegerDivisionAccuracy; } } astConditionalExpression(ast, retArr) { if (ast.type !== 'ConditionalExpression') { throw this.astErrorOutput('Not a conditional expression', ast); } const consequentType = this.getType(ast.consequent); const alternateType = this.getType(ast.alternate); if (consequentType === null && alternateType === null) { retArr.push('if ('); this.astGeneric(ast.test, retArr); retArr.push(') {'); this.astGeneric(ast.consequent, retArr); retArr.push(';'); retArr.push('} else {'); this.astGeneric(ast.alternate, retArr); retArr.push(';'); retArr.push('}'); return retArr; } retArr.push('('); this.astGeneric(ast.test, retArr); retArr.push('?'); this.astGeneric(ast.consequent, retArr); retArr.push(':'); this.astGeneric(ast.alternate, retArr); retArr.push(')'); return retArr; } astFunction(ast, retArr) { if (this.isRootKernel) { retArr.push('void'); } else { if (!this.returnType) { const lastReturn = this.findLastReturn(); if (lastReturn) { this.returnType = this.getType(ast.body); if (this.returnType === 'LiteralInteger') { this.returnType = 'Number'; } } } const { returnType } = this; if (!returnType) { retArr.push('void'); } else { const type = typeMap[returnType]; if (!type) { throw new Error(`unknown type ${returnType}`); } retArr.push(type); } } retArr.push(' '); retArr.push(this.name); retArr.push('('); if (!this.isRootKernel) { for (let i = 0; i < this.argumentNames.length; ++i) { const argumentName = this.argumentNames[i]; if (i > 0) { retArr.push(', '); } let argumentType = this.argumentTypes[this.argumentNames.indexOf(argumentName)]; if (!argumentType) { throw this.astErrorOutput(`Unknown argument ${argumentName} type`, ast); } if (argumentType === 'LiteralInteger') { this.argumentTypes[i] = argumentType = 'Number'; } const type = typeMap[argumentType]; if (!type) { throw this.astErrorOutput('Unexpected expression', ast); } const name = utils.sanitizeName(argumentName); if (type === 'sampler2D' || type === 'sampler2DArray') { retArr.push(`${type} user_${name},ivec2 user_${name}Size,ivec3 user_${name}Dim`); } else { retArr.push(`${type} user_${name}`); } } } retArr.push(') {\n'); for (let i = 0; i < ast.body.body.length; ++i) { this.astGeneric(ast.body.body[i], retArr); retArr.push('\n'); } retArr.push('}\n'); return retArr; } astReturnStatement(ast, retArr) { if (!ast.argument) throw this.astErrorOutput('Unexpected return statement', ast); this.pushState('skip-literal-correction'); const type = this.getType(ast.argument); this.popState('skip-literal-correction'); const result = []; if (!this.returnType) { if (type === 'LiteralInteger' || type === 'Integer') { this.returnType = 'Number'; } else { this.returnType = type; } } switch (this.returnType) { case 'LiteralInteger': case 'Number': case 'Float': switch (type) { case 'Integer': result.push('float('); this.astGeneric(ast.argument, result); result.push(')'); break; case 'LiteralInteger': this.castLiteralToFloat(ast.argument, result); if (this.getType(ast) === 'Integer') { result.unshift('float('); result.push(')'); } break; default: this.astGeneric(ast.argument, result); } break; case 'Integer': switch (type) { case 'Float': case 'Number': this.castValueToInteger(ast.argument, result); break; case 'LiteralInteger': this.castLiteralToInteger(ast.argument, result); break; default: this.astGeneric(ast.argument, result); } break; case 'Array(4)': case 'Array(3)': case 'Array(2)': case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': case 'Input': this.astGeneric(ast.argument, result); break; default: throw this.astErrorOutput(`unhandled return type ${this.returnType}`, ast); } if (this.isRootKernel) { retArr.push(`kernelResult = ${ result.join('') };`); retArr.push('return;'); } else if (this.isSubKernel) { retArr.push(`subKernelResult_${ this.name } = ${ result.join('') };`); retArr.push(`return subKernelResult_${ this.name };`); } else { retArr.push(`return ${ result.join('') };`); } return retArr; } astLiteral(ast, retArr) { if (isNaN(ast.value)) { throw this.astErrorOutput( 'Non-numeric literal not supported : ' + ast.value, ast ); } const key = this.astKey(ast); if (Number.isInteger(ast.value)) { if (this.isState('casting-to-integer') || this.isState('building-integer')) { this.literalTypes[key] = 'Integer'; retArr.push(`${ast.value}`); } else if (this.isState('casting-to-float') || this.isState('building-float')) { this.literalTypes[key] = 'Number'; retArr.push(`${ast.value}.0`); } else { this.literalTypes[key] = 'Number'; retArr.push(`${ast.value}.0`); } } else if (this.isState('casting-to-integer') || this.isState('building-integer')) { this.literalTypes[key] = 'Integer'; retArr.push(Math.round(ast.value)); } else { this.literalTypes[key] = 'Number'; retArr.push(`${ast.value}`); } return retArr; } astBinaryExpression(ast, retArr) { if (this.checkAndUpconvertOperator(ast, retArr)) { return retArr; } if (this.fixIntegerDivisionAccuracy && ast.operator === '/') { retArr.push('divWithIntCheck('); this.pushState('building-float'); switch (this.getType(ast.left)) { case 'Integer': this.castValueToFloat(ast.left, retArr); break; case 'LiteralInteger': this.castLiteralToFloat(ast.left, retArr); break; default: this.astGeneric(ast.left, retArr); } retArr.push(', '); switch (this.getType(ast.right)) { case 'Integer': this.castValueToFloat(ast.right, retArr); break; case 'LiteralInteger': this.castLiteralToFloat(ast.right, retArr); break; default: this.astGeneric(ast.right, retArr); } this.popState('building-float'); retArr.push(')'); return retArr; } retArr.push('('); const leftType = this.getType(ast.left) || 'Number'; const rightType = this.getType(ast.right) || 'Number'; if (!leftType || !rightType) { throw this.astErrorOutput(`Unhandled binary expression`, ast); } const key = leftType + ' & ' + rightType; switch (key) { case 'Integer & Integer': this.pushState('building-integer'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-integer'); break; case 'Number & Float': case 'Float & Number': case 'Float & Float': case 'Number & Number': this.pushState('building-float'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-float'); break; case 'LiteralInteger & LiteralInteger': if (this.isState('casting-to-integer') || this.isState('building-integer')) { this.pushState('building-integer'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-integer'); } else { this.pushState('building-float'); this.castLiteralToFloat(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castLiteralToFloat(ast.right, retArr); this.popState('building-float'); } break; case 'Integer & Float': case 'Integer & Number': if (ast.operator === '>' || ast.operator === '<' && ast.right.type === 'Literal') { if (!Number.isInteger(ast.right.value)) { this.pushState('building-float'); this.castValueToFloat(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-float'); break; } } this.pushState('building-integer'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.pushState('casting-to-integer'); if (ast.right.type === 'Literal') { const literalResult = []; this.astGeneric(ast.right, literalResult); const literalType = this.getType(ast.right); if (literalType === 'Integer') { retArr.push(literalResult.join('')); } else { throw this.astErrorOutput(`Unhandled binary expression with literal`, ast); } } else { retArr.push('int('); this.astGeneric(ast.right, retArr); retArr.push(')'); } this.popState('casting-to-integer'); this.popState('building-integer'); break; case 'Integer & LiteralInteger': this.pushState('building-integer'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castLiteralToInteger(ast.right, retArr); this.popState('building-integer'); break; case 'Number & Integer': this.pushState('building-float'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castValueToFloat(ast.right, retArr); this.popState('building-float'); break; case 'Float & LiteralInteger': case 'Number & LiteralInteger': this.pushState('building-float'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castLiteralToFloat(ast.right, retArr); this.popState('building-float'); break; case 'LiteralInteger & Float': case 'LiteralInteger & Number': if (this.isState('casting-to-integer')) { this.pushState('building-integer'); this.castLiteralToInteger(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castValueToInteger(ast.right, retArr); this.popState('building-integer'); } else { this.pushState('building-float'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.pushState('casting-to-float'); this.astGeneric(ast.right, retArr); this.popState('casting-to-float'); this.popState('building-float'); } break; case 'LiteralInteger & Integer': this.pushState('building-integer'); this.castLiteralToInteger(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-integer'); break; case 'Boolean & Boolean': this.pushState('building-boolean'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-boolean'); break; case 'Float & Integer': this.pushState('building-float'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castValueToFloat(ast.right, retArr); this.popState('building-float'); break; default: throw this.astErrorOutput(`Unhandled binary expression between ${key}`, ast); } retArr.push(')'); return retArr; } checkAndUpconvertOperator(ast, retArr) { const bitwiseResult = this.checkAndUpconvertBitwiseOperators(ast, retArr); if (bitwiseResult) { return bitwiseResult; } const upconvertableOperators = { '%': this.fixIntegerDivisionAccuracy ? 'integerCorrectionModulo' : 'modulo', '**': 'pow', }; const foundOperator = upconvertableOperators[ast.operator]; if (!foundOperator) return null; retArr.push(foundOperator); retArr.push('('); switch (this.getType(ast.left)) { case 'Integer': this.castValueToFloat(ast.left, retArr); break; case 'LiteralInteger': this.castLiteralToFloat(ast.left, retArr); break; default: this.astGeneric(ast.left, retArr); } retArr.push(','); switch (this.getType(ast.right)) { case 'Integer': this.castValueToFloat(ast.right, retArr); break; case 'LiteralInteger': this.castLiteralToFloat(ast.right, retArr); break; default: this.astGeneric(ast.right, retArr); } retArr.push(')'); return retArr; } checkAndUpconvertBitwiseOperators(ast, retArr) { const upconvertableOperators = { '&': 'bitwiseAnd', '|': 'bitwiseOr', '^': 'bitwiseXOR', '<<': 'bitwiseZeroFillLeftShift', '>>': 'bitwiseSignedRightShift', '>>>': 'bitwiseZeroFillRightShift', }; const foundOperator = upconvertableOperators[ast.operator]; if (!foundOperator) return null; retArr.push(foundOperator); retArr.push('('); const leftType = this.getType(ast.left); switch (leftType) { case 'Number': case 'Float': this.castValueToInteger(ast.left, retArr); break; case 'LiteralInteger': this.castLiteralToInteger(ast.left, retArr); break; default: this.astGeneric(ast.left, retArr); } retArr.push(','); const rightType = this.getType(ast.right); switch (rightType) { case 'Number': case 'Float': this.castValueToInteger(ast.right, retArr); break; case 'LiteralInteger': this.castLiteralToInteger(ast.right, retArr); break; default: this.astGeneric(ast.right, retArr); } retArr.push(')'); return retArr; } checkAndUpconvertBitwiseUnary(ast, retArr) { const upconvertableOperators = { '~': 'bitwiseNot', }; const foundOperator = upconvertableOperators[ast.operator]; if (!foundOperator) return null; retArr.push(foundOperator); retArr.push('('); switch (this.getType(ast.argument)) { case 'Number': case 'Float': this.castValueToInteger(ast.argument, retArr); break; case 'LiteralInteger': this.castLiteralToInteger(ast.argument, retArr); break; default: this.astGeneric(ast.argument, retArr); } retArr.push(')'); return retArr; } castLiteralToInteger(ast, retArr) { this.pushState('casting-to-integer'); this.astGeneric(ast, retArr); this.popState('casting-to-integer'); return retArr; } castLiteralToFloat(ast, retArr) { this.pushState('casting-to-float'); this.astGeneric(ast, retArr); this.popState('casting-to-float'); return retArr; } castValueToInteger(ast, retArr) { this.pushState('casting-to-integer'); retArr.push('int('); this.astGeneric(ast, retArr); retArr.push(')'); this.popState('casting-to-integer'); return retArr; } castValueToFloat(ast, retArr) { this.pushState('casting-to-float'); retArr.push('float('); this.astGeneric(ast, retArr); retArr.push(')'); this.popState('casting-to-float'); return retArr; } astIdentifierExpression(idtNode, retArr) { if (idtNode.type !== 'Identifier') { throw this.astErrorOutput('IdentifierExpression - not an Identifier', idtNode); } const type = this.getType(idtNode); const name = utils.sanitizeName(idtNode.name); if (idtNode.name === 'Infinity') { retArr.push('3.402823466e+38'); } else if (type === 'Boolean') { if (this.argumentNames.indexOf(name) > -1) { retArr.push(`bool(user_${name})`); } else { retArr.push(`user_${name}`); } } else { retArr.push(`user_${name}`); } return retArr; } astForStatement(forNode, retArr) { if (forNode.type !== 'ForStatement') { throw this.astErrorOutput('Invalid for statement', forNode); } const initArr = []; const testArr = []; const updateArr = []; const bodyArr = []; let isSafe = null; if (forNode.init) { const { declarations } = forNode.init; if (declarations.length > 1) { isSafe = false; } this.astGeneric(forNode.init, initArr); for (let i = 0; i < declarations.length; i++) { if (declarations[i].init && declarations[i].init.type !== 'Literal') { isSafe = false; } } } else { isSafe = false; } if (forNode.test) { this.astGeneric(forNode.test, testArr); } else { isSafe = false; } if (forNode.update) { this.astGeneric(forNode.update, updateArr); } else { isSafe = false; } if (forNode.body) { this.pushState('loop-body'); this.astGeneric(forNode.body, bodyArr); this.popState('loop-body'); } if (isSafe === null) { isSafe = this.isSafe(forNode.init) && this.isSafe(forNode.test); } if (isSafe) { const initString = initArr.join(''); const initNeedsSemiColon = initString[initString.length - 1] !== ';'; retArr.push(`for (${initString}${initNeedsSemiColon ? ';' : ''}${testArr.join('')};${updateArr.join('')}){\n`); retArr.push(bodyArr.join('')); retArr.push('}\n'); } else { const iVariableName = this.getInternalVariableName('safeI'); if (initArr.length > 0) { retArr.push(initArr.join(''), '\n'); } retArr.push(`for (int ${iVariableName}=0;${iVariableName} 0) { retArr.push(`if (!${testArr.join('')}) break;\n`); } retArr.push(bodyArr.join('')); retArr.push(`\n${updateArr.join('')};`); retArr.push('}\n'); } return retArr; } astWhileStatement(whileNode, retArr) { if (whileNode.type !== 'WhileStatement') { throw this.astErrorOutput('Invalid while statement', whileNode); } const iVariableName = this.getInternalVariableName('safeI'); retArr.push(`for (int ${iVariableName}=0;${iVariableName} 0) { declarationSets.push(declarationSet.join(',')); } result.push(declarationSets.join(';')); retArr.push(result.join('')); retArr.push(';'); return retArr; } astIfStatement(ifNode, retArr) { retArr.push('if ('); this.astGeneric(ifNode.test, retArr); retArr.push(')'); if (ifNode.consequent.type === 'BlockStatement') { this.astGeneric(ifNode.consequent, retArr); } else { retArr.push(' {\n'); this.astGeneric(ifNode.consequent, retArr); retArr.push('\n}\n'); } if (ifNode.alternate) { retArr.push('else '); if (ifNode.alternate.type === 'BlockStatement' || ifNode.alternate.type === 'IfStatement') { this.astGeneric(ifNode.alternate, retArr); } else { retArr.push(' {\n'); this.astGeneric(ifNode.alternate, retArr); retArr.push('\n}\n'); } } return retArr; } astSwitchStatement(ast, retArr) { if (ast.type !== 'SwitchStatement') { throw this.astErrorOutput('Invalid switch statement', ast); } const { discriminant, cases } = ast; const type = this.getType(discriminant); const varName = `switchDiscriminant${this.astKey(ast, '_')}`; switch (type) { case 'Float': case 'Number': retArr.push(`float ${varName} = `); this.astGeneric(discriminant, retArr); retArr.push(';\n'); break; case 'Integer': retArr.push(`int ${varName} = `); this.astGeneric(discriminant, retArr); retArr.push(';\n'); break; } if (cases.length === 1 && !cases[0].test) { this.astGeneric(cases[0].consequent, retArr); return retArr; } let fallingThrough = false; let defaultResult = []; let movingDefaultToEnd = false; let pastFirstIf = false; for (let i = 0; i < cases.length; i++) { if (!cases[i].test) { if (cases.length > i + 1) { movingDefaultToEnd = true; this.astGeneric(cases[i].consequent, defaultResult); continue; } else { retArr.push(' else {\n'); } } else { if (i === 0 || !pastFirstIf) { pastFirstIf = true; retArr.push(`if (${varName} == `); } else { if (fallingThrough) { retArr.push(`${varName} == `); fallingThrough = false; } else { retArr.push(` else if (${varName} == `); } } if (type === 'Integer') { const testType = this.getType(cases[i].test); switch (testType) { case 'Number': case 'Float': this.castValueToInteger(cases[i].test, retArr); break; case 'LiteralInteger': this.castLiteralToInteger(cases[i].test, retArr); break; } } else if (type === 'Float') { const testType = this.getType(cases[i].test); switch (testType) { case 'LiteralInteger': this.castLiteralToFloat(cases[i].test, retArr); break; case 'Integer': this.castValueToFloat(cases[i].test, retArr); break; } } else { throw new Error('unhanlded'); } if (!cases[i].consequent || cases[i].consequent.length === 0) { fallingThrough = true; retArr.push(' || '); continue; } retArr.push(`) {\n`); } this.astGeneric(cases[i].consequent, retArr); retArr.push('\n}'); } if (movingDefaultToEnd) { retArr.push(' else {'); retArr.push(defaultResult.join('')); retArr.push('}'); } return retArr; } astThisExpression(tNode, retArr) { retArr.push('this'); return retArr; } astMemberExpression(mNode, retArr) { const { property, name, signature, origin, type, xProperty, yProperty, zProperty } = this.getMemberExpressionDetails(mNode); switch (signature) { case 'value.thread.value': case 'this.thread.value': if (name !== 'x' && name !== 'y' && name !== 'z') { throw this.astErrorOutput('Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`', mNode); } retArr.push(`threadId.${name}`); return retArr; case 'this.output.value': if (this.dynamicOutput) { switch (name) { case 'x': if (this.isState('casting-to-float')) { retArr.push('float(uOutputDim.x)'); } else { retArr.push('uOutputDim.x'); } break; case 'y': if (this.isState('casting-to-float')) { retArr.push('float(uOutputDim.y)'); } else { retArr.push('uOutputDim.y'); } break; case 'z': if (this.isState('casting-to-float')) { retArr.push('float(uOutputDim.z)'); } else { retArr.push('uOutputDim.z'); } break; default: throw this.astErrorOutput('Unexpected expression', mNode); } } else { switch (name) { case 'x': if (this.isState('casting-to-integer')) { retArr.push(this.output[0]); } else { retArr.push(this.output[0], '.0'); } break; case 'y': if (this.isState('casting-to-integer')) { retArr.push(this.output[1]); } else { retArr.push(this.output[1], '.0'); } break; case 'z': if (this.isState('casting-to-integer')) { retArr.push(this.output[2]); } else { retArr.push(this.output[2], '.0'); } break; default: throw this.astErrorOutput('Unexpected expression', mNode); } } return retArr; case 'value': throw this.astErrorOutput('Unexpected expression', mNode); case 'value[]': case 'value[][]': case 'value[][][]': case 'value[][][][]': case 'value.value': if (origin === 'Math') { retArr.push(Math[name]); return retArr; } const cleanName = utils.sanitizeName(name); switch (property) { case 'r': retArr.push(`user_${ cleanName }.r`); return retArr; case 'g': retArr.push(`user_${ cleanName }.g`); return retArr; case 'b': retArr.push(`user_${ cleanName }.b`); return retArr; case 'a': retArr.push(`user_${ cleanName }.a`); return retArr; } break; case 'this.constants.value': if (typeof xProperty === 'undefined') { switch (type) { case 'Array(2)': case 'Array(3)': case 'Array(4)': retArr.push(`constants_${ utils.sanitizeName(name) }`); return retArr; } } case 'this.constants.value[]': case 'this.constants.value[][]': case 'this.constants.value[][][]': case 'this.constants.value[][][][]': break; case 'fn()[]': this.astCallExpression(mNode.object, retArr); retArr.push('['); retArr.push(this.memberExpressionPropertyMarkup(property)); retArr.push(']'); return retArr; case 'fn()[][]': this.astCallExpression(mNode.object.object, retArr); retArr.push('['); retArr.push(this.memberExpressionPropertyMarkup(mNode.object.property)); retArr.push(']'); retArr.push('['); retArr.push(this.memberExpressionPropertyMarkup(mNode.property)); retArr.push(']'); return retArr; case '[][]': this.astArrayExpression(mNode.object, retArr); retArr.push('['); retArr.push(this.memberExpressionPropertyMarkup(property)); retArr.push(']'); return retArr; default: throw this.astErrorOutput('Unexpected expression', mNode); } if (mNode.computed === false) { switch (type) { case 'Number': case 'Integer': case 'Float': case 'Boolean': retArr.push(`${origin}_${utils.sanitizeName(name)}`); return retArr; } } const markupName = `${origin}_${utils.sanitizeName(name)}`; switch (type) { case 'Array(2)': case 'Array(3)': case 'Array(4)': this.astGeneric(mNode.object, retArr); retArr.push('['); retArr.push(this.memberExpressionPropertyMarkup(xProperty)); retArr.push(']'); break; case 'HTMLImageArray': retArr.push(`getImage3D(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'ArrayTexture(1)': retArr.push(`getFloatFromSampler2D(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'Array1D(2)': case 'Array2D(2)': case 'Array3D(2)': retArr.push(`getMemoryOptimizedVec2(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'ArrayTexture(2)': retArr.push(`getVec2FromSampler2D(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'Array1D(3)': case 'Array2D(3)': case 'Array3D(3)': retArr.push(`getMemoryOptimizedVec3(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'ArrayTexture(3)': retArr.push(`getVec3FromSampler2D(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'Array1D(4)': case 'Array2D(4)': case 'Array3D(4)': retArr.push(`getMemoryOptimizedVec4(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'ArrayTexture(4)': case 'HTMLCanvas': case 'OffscreenCanvas': case 'HTMLImage': case 'ImageBitmap': case 'ImageData': case 'HTMLVideo': retArr.push(`getVec4FromSampler2D(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'NumberTexture': case 'Array': case 'Array2D': case 'Array3D': case 'Array4D': case 'Input': case 'Number': case 'Float': case 'Integer': if (this.precision === 'single') { retArr.push(`getMemoryOptimized32(${markupName}, ${markupName}Size, ${markupName}Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); } else { const bitRatio = (origin === 'user' ? this.lookupFunctionArgumentBitRatio(this.name, name) : this.constantBitRatios[name] ); switch (bitRatio) { case 1: retArr.push(`get8(${markupName}, ${markupName}Size, ${markupName}Dim, `); break; case 2: retArr.push(`get16(${markupName}, ${markupName}Size, ${markupName}Dim, `); break; case 4: case 0: retArr.push(`get32(${markupName}, ${markupName}Size, ${markupName}Dim, `); break; default: throw new Error(`unhandled bit ratio of ${bitRatio}`); } this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); } break; case 'MemoryOptimizedNumberTexture': retArr.push(`getMemoryOptimized32(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': retArr.push(`${markupName}[${this.memberExpressionPropertyMarkup(yProperty)}]`); if (yProperty) { retArr.push(`[${this.memberExpressionPropertyMarkup(xProperty)}]`); } break; default: throw new Error(`unhandled member expression "${ type }"`); } return retArr; } astCallExpression(ast, retArr) { if (!ast.callee) { throw this.astErrorOutput('Unknown CallExpression', ast); } let functionName = null; const isMathFunction = this.isAstMathFunction(ast); if (isMathFunction || (ast.callee.object && ast.callee.object.type === 'ThisExpression')) { functionName = ast.callee.property.name; } else if (ast.callee.type === 'SequenceExpression' && ast.callee.expressions[0].type === 'Literal' && !isNaN(ast.callee.expressions[0].raw)) { functionName = ast.callee.expressions[1].property.name; } else { functionName = ast.callee.name; } if (!functionName) { throw this.astErrorOutput(`Unhandled function, couldn't find name`, ast); } switch (functionName) { case 'pow': functionName = '_pow'; break; case 'round': functionName = '_round'; break; } if (this.calledFunctions.indexOf(functionName) < 0) { this.calledFunctions.push(functionName); } if (functionName === 'random' && this.plugins && this.plugins.length > 0) { for (let i = 0; i < this.plugins.length; i++) { const plugin = this.plugins[i]; if (plugin.functionMatch === 'Math.random()' && plugin.functionReplace) { retArr.push(plugin.functionReplace); return retArr; } } } if (this.onFunctionCall) { this.onFunctionCall(this.name, functionName, ast.arguments); } retArr.push(functionName); retArr.push('('); if (isMathFunction) { for (let i = 0; i < ast.arguments.length; ++i) { const argument = ast.arguments[i]; const argumentType = this.getType(argument); if (i > 0) { retArr.push(', '); } switch (argumentType) { case 'Integer': this.castValueToFloat(argument, retArr); break; default: this.astGeneric(argument, retArr); break; } } } else { const targetTypes = this.lookupFunctionArgumentTypes(functionName) || []; for (let i = 0; i < ast.arguments.length; ++i) { const argument = ast.arguments[i]; let targetType = targetTypes[i]; if (i > 0) { retArr.push(', '); } const argumentType = this.getType(argument); if (!targetType) { this.triggerImplyArgumentType(functionName, i, argumentType, this); targetType = argumentType; } switch (argumentType) { case 'Boolean': this.astGeneric(argument, retArr); continue; case 'Number': case 'Float': if (targetType === 'Integer') { retArr.push('int('); this.astGeneric(argument, retArr); retArr.push(')'); continue; } else if (targetType === 'Number' || targetType === 'Float') { this.astGeneric(argument, retArr); continue; } else if (targetType === 'LiteralInteger') { this.castLiteralToFloat(argument, retArr); continue; } break; case 'Integer': if (targetType === 'Number' || targetType === 'Float') { retArr.push('float('); this.astGeneric(argument, retArr); retArr.push(')'); continue; } else if (targetType === 'Integer') { this.astGeneric(argument, retArr); continue; } break; case 'LiteralInteger': if (targetType === 'Integer') { this.castLiteralToInteger(argument, retArr); continue; } else if (targetType === 'Number' || targetType === 'Float') { this.castLiteralToFloat(argument, retArr); continue; } else if (targetType === 'LiteralInteger') { this.astGeneric(argument, retArr); continue; } break; case 'Array(2)': case 'Array(3)': case 'Array(4)': if (targetType === argumentType) { if (argument.type === 'Identifier') { retArr.push(`user_${utils.sanitizeName(argument.name)}`); } else if (argument.type === 'ArrayExpression' || argument.type === 'MemberExpression' || argument.type === 'CallExpression') { this.astGeneric(argument, retArr); } else { throw this.astErrorOutput(`Unhandled argument type ${ argument.type }`, ast); } continue; } break; case 'HTMLCanvas': case 'OffscreenCanvas': case 'HTMLImage': case 'ImageBitmap': case 'ImageData': case 'HTMLImageArray': case 'HTMLVideo': case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': case 'Array': case 'Input': if (targetType === argumentType) { if (argument.type !== 'Identifier') throw this.astErrorOutput(`Unhandled argument type ${ argument.type }`, ast); this.triggerImplyArgumentBitRatio(this.name, argument.name, functionName, i); const name = utils.sanitizeName(argument.name); retArr.push(`user_${name},user_${name}Size,user_${name}Dim`); continue; } break; } throw this.astErrorOutput(`Unhandled argument combination of ${ argumentType } and ${ targetType } for argument named "${ argument.name }"`, ast); } } retArr.push(')'); return retArr; } astArrayExpression(arrNode, retArr) { const returnType = this.getType(arrNode); const arrLen = arrNode.elements.length; switch (returnType) { case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': retArr.push(`mat${arrLen}(`); break; default: retArr.push(`vec${arrLen}(`); } for (let i = 0; i < arrLen; ++i) { if (i > 0) { retArr.push(', '); } const subNode = arrNode.elements[i]; this.astGeneric(subNode, retArr) } retArr.push(')'); return retArr; } memberExpressionXYZ(x, y, z, retArr) { if (z) { retArr.push(this.memberExpressionPropertyMarkup(z), ', '); } else { retArr.push('0, '); } if (y) { retArr.push(this.memberExpressionPropertyMarkup(y), ', '); } else { retArr.push('0, '); } retArr.push(this.memberExpressionPropertyMarkup(x)); return retArr; } memberExpressionPropertyMarkup(property) { if (!property) { throw new Error('Property not set'); } const type = this.getType(property); const result = []; switch (type) { case 'Number': case 'Float': this.castValueToInteger(property, result); break; case 'LiteralInteger': this.castLiteralToInteger(property, result); break; default: this.astGeneric(property, result); } return result.join(''); } } const typeMap = { 'Array': 'sampler2D', 'Array(2)': 'vec2', 'Array(3)': 'vec3', 'Array(4)': 'vec4', 'Matrix(2)': 'mat2', 'Matrix(3)': 'mat3', 'Matrix(4)': 'mat4', 'Array2D': 'sampler2D', 'Array3D': 'sampler2D', 'Boolean': 'bool', 'Float': 'float', 'Input': 'sampler2D', 'Integer': 'int', 'Number': 'float', 'LiteralInteger': 'float', 'NumberTexture': 'sampler2D', 'MemoryOptimizedNumberTexture': 'sampler2D', 'ArrayTexture(1)': 'sampler2D', 'ArrayTexture(2)': 'sampler2D', 'ArrayTexture(3)': 'sampler2D', 'ArrayTexture(4)': 'sampler2D', 'HTMLVideo': 'sampler2D', 'HTMLCanvas': 'sampler2D', 'OffscreenCanvas': 'sampler2D', 'HTMLImage': 'sampler2D', 'ImageBitmap': 'sampler2D', 'ImageData': 'sampler2D', 'HTMLImageArray': 'sampler2DArray', }; const operatorMap = { '===': '==', '!==': '!=' }; module.exports = { WebGLFunctionNode }; },{"../../utils":114,"../function-node":10}],39:[function(require,module,exports){ const { WebGLKernelValueBoolean } = require('./kernel-value/boolean'); const { WebGLKernelValueFloat } = require('./kernel-value/float'); const { WebGLKernelValueInteger } = require('./kernel-value/integer'); const { WebGLKernelValueHTMLImage } = require('./kernel-value/html-image'); const { WebGLKernelValueDynamicHTMLImage } = require('./kernel-value/dynamic-html-image'); const { WebGLKernelValueHTMLVideo } = require('./kernel-value/html-video'); const { WebGLKernelValueDynamicHTMLVideo } = require('./kernel-value/dynamic-html-video'); const { WebGLKernelValueSingleInput } = require('./kernel-value/single-input'); const { WebGLKernelValueDynamicSingleInput } = require('./kernel-value/dynamic-single-input'); const { WebGLKernelValueUnsignedInput } = require('./kernel-value/unsigned-input'); const { WebGLKernelValueDynamicUnsignedInput } = require('./kernel-value/dynamic-unsigned-input'); const { WebGLKernelValueMemoryOptimizedNumberTexture } = require('./kernel-value/memory-optimized-number-texture'); const { WebGLKernelValueDynamicMemoryOptimizedNumberTexture } = require('./kernel-value/dynamic-memory-optimized-number-texture'); const { WebGLKernelValueNumberTexture } = require('./kernel-value/number-texture'); const { WebGLKernelValueDynamicNumberTexture } = require('./kernel-value/dynamic-number-texture'); const { WebGLKernelValueSingleArray } = require('./kernel-value/single-array'); const { WebGLKernelValueDynamicSingleArray } = require('./kernel-value/dynamic-single-array'); const { WebGLKernelValueSingleArray1DI } = require('./kernel-value/single-array1d-i'); const { WebGLKernelValueDynamicSingleArray1DI } = require('./kernel-value/dynamic-single-array1d-i'); const { WebGLKernelValueSingleArray2DI } = require('./kernel-value/single-array2d-i'); const { WebGLKernelValueDynamicSingleArray2DI } = require('./kernel-value/dynamic-single-array2d-i'); const { WebGLKernelValueSingleArray3DI } = require('./kernel-value/single-array3d-i'); const { WebGLKernelValueDynamicSingleArray3DI } = require('./kernel-value/dynamic-single-array3d-i'); const { WebGLKernelValueArray2 } = require('./kernel-value/array2'); const { WebGLKernelValueArray3 } = require('./kernel-value/array3'); const { WebGLKernelValueArray4 } = require('./kernel-value/array4'); const { WebGLKernelValueUnsignedArray } = require('./kernel-value/unsigned-array'); const { WebGLKernelValueDynamicUnsignedArray } = require('./kernel-value/dynamic-unsigned-array'); const kernelValueMaps = { unsigned: { dynamic: { 'Boolean': WebGLKernelValueBoolean, 'Integer': WebGLKernelValueInteger, 'Float': WebGLKernelValueFloat, 'Array': WebGLKernelValueDynamicUnsignedArray, 'Array(2)': WebGLKernelValueArray2, 'Array(3)': WebGLKernelValueArray3, 'Array(4)': WebGLKernelValueArray4, 'Array1D(2)': false, 'Array1D(3)': false, 'Array1D(4)': false, 'Array2D(2)': false, 'Array2D(3)': false, 'Array2D(4)': false, 'Array3D(2)': false, 'Array3D(3)': false, 'Array3D(4)': false, 'Input': WebGLKernelValueDynamicUnsignedInput, 'NumberTexture': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(1)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(2)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(3)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(4)': WebGLKernelValueDynamicNumberTexture, 'MemoryOptimizedNumberTexture': WebGLKernelValueDynamicMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGLKernelValueDynamicHTMLImage, 'OffscreenCanvas': WebGLKernelValueDynamicHTMLImage, 'HTMLImage': WebGLKernelValueDynamicHTMLImage, 'ImageBitmap': WebGLKernelValueDynamicHTMLImage, 'ImageData': WebGLKernelValueDynamicHTMLImage, 'HTMLImageArray': false, 'HTMLVideo': WebGLKernelValueDynamicHTMLVideo, }, static: { 'Boolean': WebGLKernelValueBoolean, 'Float': WebGLKernelValueFloat, 'Integer': WebGLKernelValueInteger, 'Array': WebGLKernelValueUnsignedArray, 'Array(2)': WebGLKernelValueArray2, 'Array(3)': WebGLKernelValueArray3, 'Array(4)': WebGLKernelValueArray4, 'Array1D(2)': false, 'Array1D(3)': false, 'Array1D(4)': false, 'Array2D(2)': false, 'Array2D(3)': false, 'Array2D(4)': false, 'Array3D(2)': false, 'Array3D(3)': false, 'Array3D(4)': false, 'Input': WebGLKernelValueUnsignedInput, 'NumberTexture': WebGLKernelValueNumberTexture, 'ArrayTexture(1)': WebGLKernelValueNumberTexture, 'ArrayTexture(2)': WebGLKernelValueNumberTexture, 'ArrayTexture(3)': WebGLKernelValueNumberTexture, 'ArrayTexture(4)': WebGLKernelValueNumberTexture, 'MemoryOptimizedNumberTexture': WebGLKernelValueMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGLKernelValueHTMLImage, 'OffscreenCanvas': WebGLKernelValueHTMLImage, 'HTMLImage': WebGLKernelValueHTMLImage, 'ImageBitmap': WebGLKernelValueHTMLImage, 'ImageData': WebGLKernelValueHTMLImage, 'HTMLImageArray': false, 'HTMLVideo': WebGLKernelValueHTMLVideo, } }, single: { dynamic: { 'Boolean': WebGLKernelValueBoolean, 'Integer': WebGLKernelValueInteger, 'Float': WebGLKernelValueFloat, 'Array': WebGLKernelValueDynamicSingleArray, 'Array(2)': WebGLKernelValueArray2, 'Array(3)': WebGLKernelValueArray3, 'Array(4)': WebGLKernelValueArray4, 'Array1D(2)': WebGLKernelValueDynamicSingleArray1DI, 'Array1D(3)': WebGLKernelValueDynamicSingleArray1DI, 'Array1D(4)': WebGLKernelValueDynamicSingleArray1DI, 'Array2D(2)': WebGLKernelValueDynamicSingleArray2DI, 'Array2D(3)': WebGLKernelValueDynamicSingleArray2DI, 'Array2D(4)': WebGLKernelValueDynamicSingleArray2DI, 'Array3D(2)': WebGLKernelValueDynamicSingleArray3DI, 'Array3D(3)': WebGLKernelValueDynamicSingleArray3DI, 'Array3D(4)': WebGLKernelValueDynamicSingleArray3DI, 'Input': WebGLKernelValueDynamicSingleInput, 'NumberTexture': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(1)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(2)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(3)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(4)': WebGLKernelValueDynamicNumberTexture, 'MemoryOptimizedNumberTexture': WebGLKernelValueDynamicMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGLKernelValueDynamicHTMLImage, 'OffscreenCanvas': WebGLKernelValueDynamicHTMLImage, 'HTMLImage': WebGLKernelValueDynamicHTMLImage, 'ImageBitmap': WebGLKernelValueDynamicHTMLImage, 'ImageData': WebGLKernelValueDynamicHTMLImage, 'HTMLImageArray': false, 'HTMLVideo': WebGLKernelValueDynamicHTMLVideo, }, static: { 'Boolean': WebGLKernelValueBoolean, 'Float': WebGLKernelValueFloat, 'Integer': WebGLKernelValueInteger, 'Array': WebGLKernelValueSingleArray, 'Array(2)': WebGLKernelValueArray2, 'Array(3)': WebGLKernelValueArray3, 'Array(4)': WebGLKernelValueArray4, 'Array1D(2)': WebGLKernelValueSingleArray1DI, 'Array1D(3)': WebGLKernelValueSingleArray1DI, 'Array1D(4)': WebGLKernelValueSingleArray1DI, 'Array2D(2)': WebGLKernelValueSingleArray2DI, 'Array2D(3)': WebGLKernelValueSingleArray2DI, 'Array2D(4)': WebGLKernelValueSingleArray2DI, 'Array3D(2)': WebGLKernelValueSingleArray3DI, 'Array3D(3)': WebGLKernelValueSingleArray3DI, 'Array3D(4)': WebGLKernelValueSingleArray3DI, 'Input': WebGLKernelValueSingleInput, 'NumberTexture': WebGLKernelValueNumberTexture, 'ArrayTexture(1)': WebGLKernelValueNumberTexture, 'ArrayTexture(2)': WebGLKernelValueNumberTexture, 'ArrayTexture(3)': WebGLKernelValueNumberTexture, 'ArrayTexture(4)': WebGLKernelValueNumberTexture, 'MemoryOptimizedNumberTexture': WebGLKernelValueMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGLKernelValueHTMLImage, 'OffscreenCanvas': WebGLKernelValueHTMLImage, 'HTMLImage': WebGLKernelValueHTMLImage, 'ImageBitmap': WebGLKernelValueHTMLImage, 'ImageData': WebGLKernelValueHTMLImage, 'HTMLImageArray': false, 'HTMLVideo': WebGLKernelValueHTMLVideo, } }, }; function lookupKernelValueType(type, dynamic, precision, value) { if (!type) { throw new Error('type missing'); } if (!dynamic) { throw new Error('dynamic missing'); } if (!precision) { throw new Error('precision missing'); } if (value.type) { type = value.type; } const types = kernelValueMaps[precision][dynamic]; if (types[type] === false) { return null; } else if (types[type] === undefined) { throw new Error(`Could not find a KernelValue for ${ type }`); } return types[type]; } module.exports = { lookupKernelValueType, kernelValueMaps, }; },{"./kernel-value/array2":41,"./kernel-value/array3":42,"./kernel-value/array4":43,"./kernel-value/boolean":44,"./kernel-value/dynamic-html-image":45,"./kernel-value/dynamic-html-video":46,"./kernel-value/dynamic-memory-optimized-number-texture":47,"./kernel-value/dynamic-number-texture":48,"./kernel-value/dynamic-single-array":49,"./kernel-value/dynamic-single-array1d-i":50,"./kernel-value/dynamic-single-array2d-i":51,"./kernel-value/dynamic-single-array3d-i":52,"./kernel-value/dynamic-single-input":53,"./kernel-value/dynamic-unsigned-array":54,"./kernel-value/dynamic-unsigned-input":55,"./kernel-value/float":56,"./kernel-value/html-image":57,"./kernel-value/html-video":58,"./kernel-value/integer":60,"./kernel-value/memory-optimized-number-texture":61,"./kernel-value/number-texture":62,"./kernel-value/single-array":63,"./kernel-value/single-array1d-i":64,"./kernel-value/single-array2d-i":65,"./kernel-value/single-array3d-i":66,"./kernel-value/single-input":67,"./kernel-value/unsigned-array":68,"./kernel-value/unsigned-input":69}],40:[function(require,module,exports){ const { WebGLKernelValue } = require('./index'); const { Input } = require('../../../input'); class WebGLKernelArray extends WebGLKernelValue { checkSize(width, height) { if (!this.kernel.validate) return; const { maxTextureSize } = this.kernel.constructor.features; if (width > maxTextureSize || height > maxTextureSize) { if (width > height) { throw new Error(`Argument texture width of ${width} larger than maximum size of ${maxTextureSize} for your GPU`); } else if (width < height) { throw new Error(`Argument texture height of ${height} larger than maximum size of ${maxTextureSize} for your GPU`); } else { throw new Error(`Argument texture height and width of ${height} larger than maximum size of ${maxTextureSize} for your GPU`); } } } setup() { this.requestTexture(); this.setupTexture(); this.defineTexture(); } requestTexture() { this.texture = this.onRequestTexture(); } defineTexture() { const { context: gl } = this; gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); } setupTexture() { this.contextHandle = this.onRequestContextHandle(); this.index = this.onRequestIndex(); this.dimensionsId = this.id + 'Dim'; this.sizeId = this.id + 'Size'; } getBitRatio(value) { if (Array.isArray(value[0])) { return this.getBitRatio(value[0]); } else if (value.constructor === Input) { return this.getBitRatio(value.value); } switch (value.constructor) { case Uint8ClampedArray: case Uint8Array: case Int8Array: return 1; case Uint16Array: case Int16Array: return 2; case Float32Array: case Int32Array: default: return 4; } } destroy() { if (this.prevArg) { this.prevArg.delete(); } this.context.deleteTexture(this.texture); } } module.exports = { WebGLKernelArray }; },{"../../../input":110,"./index":59}],41:[function(require,module,exports){ const { WebGLKernelValue } = require('./index'); class WebGLKernelValueArray2 extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getSource(value) { if (this.origin === 'constants') { return `const vec2 ${this.id} = vec2(${value[0]},${value[1]});\n`; } return `uniform vec2 ${this.id};\n`; } getStringValueHandler() { if (this.origin === 'constants') return ''; return `const uploadValue_${this.name} = ${this.varName};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform2fv(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueArray2 }; },{"./index":59}],42:[function(require,module,exports){ const { WebGLKernelValue } = require('./index'); class WebGLKernelValueArray3 extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getSource(value) { if (this.origin === 'constants') { return `const vec3 ${this.id} = vec3(${value[0]},${value[1]},${value[2]});\n`; } return `uniform vec3 ${this.id};\n`; } getStringValueHandler() { if (this.origin === 'constants') return ''; return `const uploadValue_${this.name} = ${this.varName};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform3fv(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueArray3 }; },{"./index":59}],43:[function(require,module,exports){ const { WebGLKernelValue } = require('./index'); class WebGLKernelValueArray4 extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getSource(value) { if (this.origin === 'constants') { return `const vec4 ${this.id} = vec4(${value[0]},${value[1]},${value[2]},${value[3]});\n`; } return `uniform vec4 ${this.id};\n`; } getStringValueHandler() { if (this.origin === 'constants') return ''; return `const uploadValue_${this.name} = ${this.varName};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform4fv(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueArray4 }; },{"./index":59}],44:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValue } = require('./index'); class WebGLKernelValueBoolean extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getSource(value) { if (this.origin === 'constants') { return `const bool ${this.id} = ${value};\n`; } return `uniform bool ${this.id};\n`; } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform1i(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueBoolean }; },{"../../../utils":114,"./index":59}],45:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueHTMLImage } = require('./html-image'); class WebGLKernelValueDynamicHTMLImage extends WebGLKernelValueHTMLImage { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { const { width, height } = value; this.checkSize(width, height); this.dimensions = [width, height, 1]; this.textureSize = [width, height]; this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicHTMLImage }; },{"../../../utils":114,"./html-image":57}],46:[function(require,module,exports){ const { WebGLKernelValueDynamicHTMLImage } = require('./dynamic-html-image'); class WebGLKernelValueDynamicHTMLVideo extends WebGLKernelValueDynamicHTMLImage {} module.exports = { WebGLKernelValueDynamicHTMLVideo }; },{"./dynamic-html-image":45}],47:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueMemoryOptimizedNumberTexture } = require('./memory-optimized-number-texture'); class WebGLKernelValueDynamicMemoryOptimizedNumberTexture extends WebGLKernelValueMemoryOptimizedNumberTexture { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(inputTexture) { this.dimensions = inputTexture.dimensions; this.checkSize(inputTexture.size[0], inputTexture.size[1]); this.textureSize = inputTexture.size; this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(inputTexture); } } module.exports = { WebGLKernelValueDynamicMemoryOptimizedNumberTexture }; },{"../../../utils":114,"./memory-optimized-number-texture":61}],48:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueNumberTexture } = require('./number-texture'); class WebGLKernelValueDynamicNumberTexture extends WebGLKernelValueNumberTexture { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.dimensions = value.dimensions; this.checkSize(value.size[0], value.size[1]); this.textureSize = value.size; this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicNumberTexture }; },{"../../../utils":114,"./number-texture":62}],49:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray } = require('./single-array'); class WebGLKernelValueDynamicSingleArray extends WebGLKernelValueSingleArray { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.dimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicSingleArray }; },{"../../../utils":114,"./single-array":63}],50:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray1DI } = require('./single-array1d-i'); class WebGLKernelValueDynamicSingleArray1DI extends WebGLKernelValueSingleArray1DI { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicSingleArray1DI }; },{"../../../utils":114,"./single-array1d-i":64}],51:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray2DI } = require('./single-array2d-i'); class WebGLKernelValueDynamicSingleArray2DI extends WebGLKernelValueSingleArray2DI { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicSingleArray2DI }; },{"../../../utils":114,"./single-array2d-i":65}],52:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray3DI } = require('./single-array3d-i'); class WebGLKernelValueDynamicSingleArray3DI extends WebGLKernelValueSingleArray3DI { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicSingleArray3DI }; },{"../../../utils":114,"./single-array3d-i":66}],53:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleInput } = require('./single-input'); class WebGLKernelValueDynamicSingleInput extends WebGLKernelValueSingleInput { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { let [w, h, d] = value.size; this.dimensions = new Int32Array([w || 1, h || 1, d || 1]); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicSingleInput }; },{"../../../utils":114,"./single-input":67}],54:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueUnsignedArray } = require('./unsigned-array'); class WebGLKernelValueDynamicUnsignedArray extends WebGLKernelValueUnsignedArray { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.dimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedPackedTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * (4 / this.bitRatio); this.checkSize(this.textureSize[0], this.textureSize[1]); const Type = this.getTransferArrayType(value); this.preUploadValue = new Type(this.uploadArrayLength); this.uploadValue = new Uint8Array(this.preUploadValue.buffer); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicUnsignedArray }; },{"../../../utils":114,"./unsigned-array":68}],55:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueUnsignedInput } = require('./unsigned-input'); class WebGLKernelValueDynamicUnsignedInput extends WebGLKernelValueUnsignedInput { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { let [w, h, d] = value.size; this.dimensions = new Int32Array([w || 1, h || 1, d || 1]); this.textureSize = utils.getMemoryOptimizedPackedTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * (4 / this.bitRatio); this.checkSize(this.textureSize[0], this.textureSize[1]); const Type = this.getTransferArrayType(value.value); this.preUploadValue = new Type(this.uploadArrayLength); this.uploadValue = new Uint8Array(this.preUploadValue.buffer); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicUnsignedInput }; },{"../../../utils":114,"./unsigned-input":69}],56:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValue } = require('./index'); class WebGLKernelValueFloat extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName};\n`; } getSource(value) { if (this.origin === 'constants') { if (Number.isInteger(value)) { return `const float ${this.id} = ${value}.0;\n`; } return `const float ${this.id} = ${value};\n`; } return `uniform float ${this.id};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform1f(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueFloat }; },{"../../../utils":114,"./index":59}],57:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueHTMLImage extends WebGLKernelArray { constructor(value, settings) { super(value, settings); const { width, height } = value; this.checkSize(width, height); this.dimensions = [width, height, 1]; this.textureSize = [width, height]; this.uploadValue = value; } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName};\n`; } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(inputImage) { if (inputImage.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(inputImage.constructor); return; } const { context: gl } = this; gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.uploadValue = inputImage); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueHTMLImage }; },{"../../../utils":114,"./array":40}],58:[function(require,module,exports){ const { WebGLKernelValueHTMLImage } = require('./html-image'); class WebGLKernelValueHTMLVideo extends WebGLKernelValueHTMLImage {} module.exports = { WebGLKernelValueHTMLVideo }; },{"./html-image":57}],59:[function(require,module,exports){ const { utils } = require('../../../utils'); const { KernelValue } = require('../../kernel-value'); class WebGLKernelValue extends KernelValue { constructor(value, settings) { super(value, settings); this.dimensionsId = null; this.sizeId = null; this.initialValueConstructor = value.constructor; this.onRequestTexture = settings.onRequestTexture; this.onRequestIndex = settings.onRequestIndex; this.uploadValue = null; this.textureSize = null; this.bitRatio = null; this.prevArg = null; } get id() { return `${this.origin}_${utils.sanitizeName(this.name)}`; } setup() {} getTransferArrayType(value) { if (Array.isArray(value[0])) { return this.getTransferArrayType(value[0]); } switch (value.constructor) { case Array: case Int32Array: case Int16Array: case Int8Array: return Float32Array; case Uint8ClampedArray: case Uint8Array: case Uint16Array: case Uint32Array: case Float32Array: case Float64Array: return value.constructor; } console.warn('Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros'); return value.constructor; } getStringValueHandler() { throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`); } getVariablePrecisionString() { return this.kernel.getVariablePrecisionString(this.textureSize || undefined, this.tactic || undefined); } destroy() {} } module.exports = { WebGLKernelValue }; },{"../../../utils":114,"../../kernel-value":35}],60:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValue } = require('./index'); class WebGLKernelValueInteger extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName};\n`; } getSource(value) { if (this.origin === 'constants') { return `const int ${this.id} = ${ parseInt(value) };\n`; } return `uniform int ${this.id};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform1i(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueInteger }; },{"../../../utils":114,"./index":59}],61:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); const sameError = `Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()`; class WebGLKernelValueMemoryOptimizedNumberTexture extends WebGLKernelArray { constructor(value, settings) { super(value, settings); const [width, height] = value.size; this.checkSize(width, height); this.dimensions = value.dimensions; this.textureSize = value.size; this.uploadValue = value.texture; this.forceUploadEachRun = true; } setup() { this.setupTexture(); } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName}.texture;\n`; } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(inputTexture) { if (inputTexture.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(inputTexture.constructor); return; } if (this.checkContext && inputTexture.context !== this.context) { throw new Error(`Value ${this.name} (${this.type}) must be from same context`); } const { kernel, context: gl } = this; if (kernel.pipeline) { if (kernel.immutable) { kernel.updateTextureArgumentRefs(this, inputTexture); } else { if (kernel.texture && kernel.texture.texture === inputTexture.texture) { throw new Error(sameError); } else if (kernel.mappedTextures) { const { mappedTextures } = kernel; for (let i = 0; i < mappedTextures.length; i++) { if (mappedTextures[i].texture === inputTexture.texture) { throw new Error(sameError); } } } } } gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.uploadValue = inputTexture.texture); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueMemoryOptimizedNumberTexture, sameError }; },{"../../../utils":114,"./array":40}],62:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); const { sameError } = require('./memory-optimized-number-texture'); class WebGLKernelValueNumberTexture extends WebGLKernelArray { constructor(value, settings) { super(value, settings); const [width, height] = value.size; this.checkSize(width, height); const { size: textureSize, dimensions } = value; this.bitRatio = this.getBitRatio(value); this.dimensions = dimensions; this.textureSize = textureSize; this.uploadValue = value.texture; this.forceUploadEachRun = true; } setup() { this.setupTexture(); } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName}.texture;\n`; } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(inputTexture) { if (inputTexture.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(inputTexture.constructor); return; } if (this.checkContext && inputTexture.context !== this.context) { throw new Error(`Value ${this.name} (${this.type}) must be from same context`); } const { kernel, context: gl } = this; if (kernel.pipeline) { if (kernel.immutable) { kernel.updateTextureArgumentRefs(this, inputTexture); } else { if (kernel.texture && kernel.texture.texture === inputTexture.texture) { throw new Error(sameError); } else if (kernel.mappedTextures) { const { mappedTextures } = kernel; for (let i = 0; i < mappedTextures.length; i++) { if (mappedTextures[i].texture === inputTexture.texture) { throw new Error(sameError); } } } } } gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.uploadValue = inputTexture.texture); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueNumberTexture }; },{"../../../utils":114,"./array":40,"./memory-optimized-number-texture":61}],63:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueSingleArray extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = 4; this.dimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); } getStringValueHandler() { return utils.linesToString([ `const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`, `flattenTo(${this.varName}, uploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueSingleArray }; },{"../../../utils":114,"./array":40}],64:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueSingleArray1DI extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = 4; this.setShape(value); } setShape(value) { const valueDimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(valueDimensions, this.bitRatio); this.dimensions = new Int32Array([valueDimensions[1], 1, 1]); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); } getStringValueHandler() { return utils.linesToString([ `const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`, `flattenTo(${this.varName}, uploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flatten2dArrayTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueSingleArray1DI }; },{"../../../utils":114,"./array":40}],65:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueSingleArray2DI extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = 4; this.setShape(value); } setShape(value) { const valueDimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(valueDimensions, this.bitRatio); this.dimensions = new Int32Array([valueDimensions[1], valueDimensions[2], 1]); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); } getStringValueHandler() { return utils.linesToString([ `const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`, `flattenTo(${this.varName}, uploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flatten3dArrayTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueSingleArray2DI }; },{"../../../utils":114,"./array":40}],66:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueSingleArray3DI extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = 4; this.setShape(value); } setShape(value) { const valueDimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(valueDimensions, this.bitRatio); this.dimensions = new Int32Array([valueDimensions[1], valueDimensions[2], valueDimensions[3]]); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); } getStringValueHandler() { return utils.linesToString([ `const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`, `flattenTo(${this.varName}, uploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flatten4dArrayTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueSingleArray3DI }; },{"../../../utils":114,"./array":40}],67:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueSingleInput extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = 4; let [w, h, d] = value.size; this.dimensions = new Int32Array([w || 1, h || 1, d || 1]); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); } getStringValueHandler() { return utils.linesToString([ `const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`, `flattenTo(${this.varName}.value, uploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(input) { if (input.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(input.constructor); return; } const { context: gl } = this; utils.flattenTo(input.value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueSingleInput }; },{"../../../utils":114,"./array":40}],68:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueUnsignedArray extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = this.getBitRatio(value); this.dimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedPackedTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * (4 / this.bitRatio); this.checkSize(this.textureSize[0], this.textureSize[1]); this.TranserArrayType = this.getTransferArrayType(value); this.preUploadValue = new this.TranserArrayType(this.uploadArrayLength); this.uploadValue = new Uint8Array(this.preUploadValue.buffer); } getStringValueHandler() { return utils.linesToString([ `const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`, `const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`, `flattenTo(${this.varName}, preUploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.preUploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueUnsignedArray }; },{"../../../utils":114,"./array":40}],69:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueUnsignedInput extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = this.getBitRatio(value); const [w, h, d] = value.size; this.dimensions = new Int32Array([w || 1, h || 1, d || 1]); this.textureSize = utils.getMemoryOptimizedPackedTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * (4 / this.bitRatio); this.checkSize(this.textureSize[0], this.textureSize[1]); this.TranserArrayType = this.getTransferArrayType(value.value); this.preUploadValue = new this.TranserArrayType(this.uploadArrayLength); this.uploadValue = new Uint8Array(this.preUploadValue.buffer); } getStringValueHandler() { return utils.linesToString([ `const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`, `const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`, `flattenTo(${this.varName}.value, preUploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(input) { if (input.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(input.value, this.preUploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueUnsignedInput }; },{"../../../utils":114,"./array":40}],70:[function(require,module,exports){ const { GLKernel } = require('../gl/kernel'); const { FunctionBuilder } = require('../function-builder'); const { WebGLFunctionNode } = require('./function-node'); const { utils } = require('../../utils'); const mrud = require('../../plugins/math-random-uniformly-distributed'); const { fragmentShader } = require('./fragment-shader'); const { vertexShader } = require('./vertex-shader'); const { glKernelString } = require('../gl/kernel-string'); const { lookupKernelValueType } = require('./kernel-value-maps'); let isSupported = null; let testCanvas = null; let testContext = null; let testExtensions = null; let features = null; const plugins = [mrud]; const canvases = []; const maxTexSizes = {}; class WebGLKernel extends GLKernel { static get isSupported() { if (isSupported !== null) { return isSupported; } this.setupFeatureChecks(); isSupported = this.isContextMatch(testContext); return isSupported; } static setupFeatureChecks() { if (typeof document !== 'undefined') { testCanvas = document.createElement('canvas'); } else if (typeof OffscreenCanvas !== 'undefined') { testCanvas = new OffscreenCanvas(0, 0); } if (!testCanvas) return; testContext = testCanvas.getContext('webgl') || testCanvas.getContext('experimental-webgl'); if (!testContext || !testContext.getExtension) return; testExtensions = { OES_texture_float: testContext.getExtension('OES_texture_float'), OES_texture_float_linear: testContext.getExtension('OES_texture_float_linear'), OES_element_index_uint: testContext.getExtension('OES_element_index_uint'), WEBGL_draw_buffers: testContext.getExtension('WEBGL_draw_buffers'), }; features = this.getFeatures(); } static isContextMatch(context) { if (typeof WebGLRenderingContext !== 'undefined') { return context instanceof WebGLRenderingContext; } return false; } static getIsTextureFloat() { return Boolean(testExtensions.OES_texture_float); } static getIsDrawBuffers() { return Boolean(testExtensions.WEBGL_draw_buffers); } static getChannelCount() { return testExtensions.WEBGL_draw_buffers ? testContext.getParameter(testExtensions.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL) : 1; } static getMaxTextureSize() { return testContext.getParameter(testContext.MAX_TEXTURE_SIZE); } static lookupKernelValueType(type, dynamic, precision, value) { return lookupKernelValueType(type, dynamic, precision, value); } static get testCanvas() { return testCanvas; } static get testContext() { return testContext; } static get features() { return features; } static get fragmentShader() { return fragmentShader; } static get vertexShader() { return vertexShader; } constructor(source, settings) { super(source, settings); this.program = null; this.pipeline = settings.pipeline; this.endianness = utils.systemEndianness(); this.extensions = {}; this.argumentTextureCount = 0; this.constantTextureCount = 0; this.fragShader = null; this.vertShader = null; this.drawBuffersMap = null; this.maxTexSize = null; this.onRequestSwitchKernel = null; this.texture = null; this.mappedTextures = null; this.mergeSettings(source.settings || settings); this.threadDim = null; this.framebuffer = null; this.buffer = null; this.textureCache = []; this.programUniformLocationCache = {}; this.uniform1fCache = {}; this.uniform1iCache = {}; this.uniform2fCache = {}; this.uniform2fvCache = {}; this.uniform2ivCache = {}; this.uniform3fvCache = {}; this.uniform3ivCache = {}; this.uniform4fvCache = {}; this.uniform4ivCache = {}; } initCanvas() { if (typeof document !== 'undefined') { const canvas = document.createElement('canvas'); canvas.width = 2; canvas.height = 2; return canvas; } else if (typeof OffscreenCanvas !== 'undefined') { return new OffscreenCanvas(0, 0); } } initContext() { const settings = { alpha: false, depth: false, antialias: false }; return this.canvas.getContext('webgl', settings) || this.canvas.getContext('experimental-webgl', settings); } initPlugins(settings) { const pluginsToUse = []; const { source } = this; if (typeof source === 'string') { for (let i = 0; i < plugins.length; i++) { const plugin = plugins[i]; if (source.match(plugin.functionMatch)) { pluginsToUse.push(plugin); } } } else if (typeof source === 'object') { if (settings.pluginNames) { for (let i = 0; i < plugins.length; i++) { const plugin = plugins[i]; const usePlugin = settings.pluginNames.some(pluginName => pluginName === plugin.name); if (usePlugin) { pluginsToUse.push(plugin); } } } } return pluginsToUse; } initExtensions() { this.extensions = { OES_texture_float: this.context.getExtension('OES_texture_float'), OES_texture_float_linear: this.context.getExtension('OES_texture_float_linear'), OES_element_index_uint: this.context.getExtension('OES_element_index_uint'), WEBGL_draw_buffers: this.context.getExtension('WEBGL_draw_buffers'), WEBGL_color_buffer_float: this.context.getExtension('WEBGL_color_buffer_float'), }; } validateSettings(args) { if (!this.validate) { this.texSize = utils.getKernelTextureSize({ optimizeFloatMemory: this.optimizeFloatMemory, precision: this.precision, }, this.output); return; } const { features } = this.constructor; if (this.optimizeFloatMemory === true && !features.isTextureFloat) { throw new Error('Float textures are not supported'); } else if (this.precision === 'single' && !features.isFloatRead) { throw new Error('Single precision not supported'); } else if (!this.graphical && this.precision === null && features.isTextureFloat) { this.precision = features.isFloatRead ? 'single' : 'unsigned'; } if (this.subKernels && this.subKernels.length > 0 && !this.extensions.WEBGL_draw_buffers) { throw new Error('could not instantiate draw buffers extension'); } if (this.fixIntegerDivisionAccuracy === null) { this.fixIntegerDivisionAccuracy = !features.isIntegerDivisionAccurate; } else if (this.fixIntegerDivisionAccuracy && features.isIntegerDivisionAccurate) { this.fixIntegerDivisionAccuracy = false; } this.checkOutput(); if (!this.output || this.output.length === 0) { if (args.length !== 1) { throw new Error('Auto output only supported for kernels with only one input'); } const argType = utils.getVariableType(args[0], this.strictIntegers); switch (argType) { case 'Array': this.output = utils.getDimensions(argType); break; case 'NumberTexture': case 'MemoryOptimizedNumberTexture': case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': this.output = args[0].output; break; default: throw new Error('Auto output not supported for input type: ' + argType); } } if (this.graphical) { if (this.output.length !== 2) { throw new Error('Output must have 2 dimensions on graphical mode'); } if (this.precision === 'precision') { this.precision = 'unsigned'; console.warn('Cannot use graphical mode and single precision at the same time'); } this.texSize = utils.clone(this.output); return; } else if (this.precision === null && features.isTextureFloat) { this.precision = 'single'; } this.texSize = utils.getKernelTextureSize({ optimizeFloatMemory: this.optimizeFloatMemory, precision: this.precision, }, this.output); this.checkTextureSize(); } updateMaxTexSize() { const { texSize, canvas } = this; if (this.maxTexSize === null) { let canvasIndex = canvases.indexOf(canvas); if (canvasIndex === -1) { canvasIndex = canvases.length; canvases.push(canvas); maxTexSizes[canvasIndex] = [texSize[0], texSize[1]]; } this.maxTexSize = maxTexSizes[canvasIndex]; } if (this.maxTexSize[0] < texSize[0]) { this.maxTexSize[0] = texSize[0]; } if (this.maxTexSize[1] < texSize[1]) { this.maxTexSize[1] = texSize[1]; } } setupArguments(args) { this.kernelArguments = []; this.argumentTextureCount = 0; const needsArgumentTypes = this.argumentTypes === null; if (needsArgumentTypes) { this.argumentTypes = []; } this.argumentSizes = []; this.argumentBitRatios = []; if (args.length < this.argumentNames.length) { throw new Error('not enough arguments for kernel'); } else if (args.length > this.argumentNames.length) { throw new Error('too many arguments for kernel'); } const { context: gl } = this; let textureIndexes = 0; const onRequestTexture = () => { return this.createTexture(); }; const onRequestIndex = () => { return this.constantTextureCount + textureIndexes++; }; const onUpdateValueMismatch = (constructor) => { this.switchKernels({ type: 'argumentMismatch', needed: constructor }); }; const onRequestContextHandle = () => { return gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount++; }; for (let index = 0; index < args.length; index++) { const value = args[index]; const name = this.argumentNames[index]; let type; if (needsArgumentTypes) { type = utils.getVariableType(value, this.strictIntegers); this.argumentTypes.push(type); } else { type = this.argumentTypes[index]; } const KernelValue = this.constructor.lookupKernelValueType(type, this.dynamicArguments ? 'dynamic' : 'static', this.precision, args[index]); if (KernelValue === null) { return this.requestFallback(args); } const kernelArgument = new KernelValue(value, { name, type, tactic: this.tactic, origin: 'user', context: gl, checkContext: this.checkContext, kernel: this, strictIntegers: this.strictIntegers, onRequestTexture, onRequestIndex, onUpdateValueMismatch, onRequestContextHandle, }); this.kernelArguments.push(kernelArgument); kernelArgument.setup(); this.argumentSizes.push(kernelArgument.textureSize); this.argumentBitRatios[index] = kernelArgument.bitRatio; } } createTexture() { const texture = this.context.createTexture(); this.textureCache.push(texture); return texture; } setupConstants(args) { const { context: gl } = this; this.kernelConstants = []; this.forceUploadKernelConstants = []; let needsConstantTypes = this.constantTypes === null; if (needsConstantTypes) { this.constantTypes = {}; } this.constantBitRatios = {}; let textureIndexes = 0; for (const name in this.constants) { const value = this.constants[name]; let type; if (needsConstantTypes) { type = utils.getVariableType(value, this.strictIntegers); this.constantTypes[name] = type; } else { type = this.constantTypes[name]; } const KernelValue = this.constructor.lookupKernelValueType(type, 'static', this.precision, value); if (KernelValue === null) { return this.requestFallback(args); } const kernelValue = new KernelValue(value, { name, type, tactic: this.tactic, origin: 'constants', context: this.context, checkContext: this.checkContext, kernel: this, strictIntegers: this.strictIntegers, onRequestTexture: () => { return this.createTexture(); }, onRequestIndex: () => { return textureIndexes++; }, onRequestContextHandle: () => { return gl.TEXTURE0 + this.constantTextureCount++; } }); this.constantBitRatios[name] = kernelValue.bitRatio; this.kernelConstants.push(kernelValue); kernelValue.setup(); if (kernelValue.forceUploadEachRun) { this.forceUploadKernelConstants.push(kernelValue); } } } build() { if (this.built) return; this.initExtensions(); this.validateSettings(arguments); this.setupConstants(arguments); if (this.fallbackRequested) return; this.setupArguments(arguments); if (this.fallbackRequested) return; this.updateMaxTexSize(); this.translateSource(); const failureResult = this.pickRenderStrategy(arguments); if (failureResult) { return failureResult; } const { texSize, context: gl, canvas } = this; gl.enable(gl.SCISSOR_TEST); if (this.pipeline && this.precision === 'single') { gl.viewport(0, 0, this.maxTexSize[0], this.maxTexSize[1]); canvas.width = this.maxTexSize[0]; canvas.height = this.maxTexSize[1]; } else { gl.viewport(0, 0, this.maxTexSize[0], this.maxTexSize[1]); canvas.width = this.maxTexSize[0]; canvas.height = this.maxTexSize[1]; } const threadDim = this.threadDim = Array.from(this.output); while (threadDim.length < 3) { threadDim.push(1); } const compiledVertexShader = this.getVertexShader(arguments); const vertShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertShader, compiledVertexShader); gl.compileShader(vertShader); this.vertShader = vertShader; const compiledFragmentShader = this.getFragmentShader(arguments); const fragShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragShader, compiledFragmentShader); gl.compileShader(fragShader); this.fragShader = fragShader; if (this.debug) { console.log('GLSL Shader Output:'); console.log(compiledFragmentShader); } if (!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) { throw new Error('Error compiling vertex shader: ' + gl.getShaderInfoLog(vertShader)); } if (!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) { throw new Error('Error compiling fragment shader: ' + gl.getShaderInfoLog(fragShader)); } const program = this.program = gl.createProgram(); gl.attachShader(program, vertShader); gl.attachShader(program, fragShader); gl.linkProgram(program); this.framebuffer = gl.createFramebuffer(); this.framebuffer.width = texSize[0]; this.framebuffer.height = texSize[1]; this.rawValueFramebuffers = {}; const vertices = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1 ]); const texCoords = new Float32Array([ 0, 0, 1, 0, 0, 1, 1, 1 ]); const texCoordOffset = vertices.byteLength; let buffer = this.buffer; if (!buffer) { buffer = this.buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, vertices.byteLength + texCoords.byteLength, gl.STATIC_DRAW); } else { gl.bindBuffer(gl.ARRAY_BUFFER, buffer); } gl.bufferSubData(gl.ARRAY_BUFFER, 0, vertices); gl.bufferSubData(gl.ARRAY_BUFFER, texCoordOffset, texCoords); const aPosLoc = gl.getAttribLocation(this.program, 'aPos'); gl.enableVertexAttribArray(aPosLoc); gl.vertexAttribPointer(aPosLoc, 2, gl.FLOAT, false, 0, 0); const aTexCoordLoc = gl.getAttribLocation(this.program, 'aTexCoord'); gl.enableVertexAttribArray(aTexCoordLoc); gl.vertexAttribPointer(aTexCoordLoc, 2, gl.FLOAT, false, 0, texCoordOffset); gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); let i = 0; gl.useProgram(this.program); for (let p in this.constants) { this.kernelConstants[i++].updateValue(this.constants[p]); } this._setupOutputTexture(); if ( this.subKernels !== null && this.subKernels.length > 0 ) { this._mappedTextureSwitched = {}; this._setupSubOutputTextures(); } this.buildSignature(arguments); this.built = true; } translateSource() { const functionBuilder = FunctionBuilder.fromKernel(this, WebGLFunctionNode, { fixIntegerDivisionAccuracy: this.fixIntegerDivisionAccuracy }); this.translatedSource = functionBuilder.getPrototypeString('kernel'); this.setupReturnTypes(functionBuilder); } setupReturnTypes(functionBuilder) { if (!this.graphical && !this.returnType) { this.returnType = functionBuilder.getKernelResultType(); } if (this.subKernels && this.subKernels.length > 0) { for (let i = 0; i < this.subKernels.length; i++) { const subKernel = this.subKernels[i]; if (!subKernel.returnType) { subKernel.returnType = functionBuilder.getSubKernelResultType(i); } } } } run() { const { kernelArguments, texSize, forceUploadKernelConstants, context: gl } = this; gl.useProgram(this.program); gl.scissor(0, 0, texSize[0], texSize[1]); if (this.dynamicOutput) { this.setUniform3iv('uOutputDim', new Int32Array(this.threadDim)); this.setUniform2iv('uTexSize', texSize); } this.setUniform2f('ratio', texSize[0] / this.maxTexSize[0], texSize[1] / this.maxTexSize[1]); for (let i = 0; i < forceUploadKernelConstants.length; i++) { const constant = forceUploadKernelConstants[i]; constant.updateValue(this.constants[constant.name]); if (this.switchingKernels) return; } for (let i = 0; i < kernelArguments.length; i++) { kernelArguments[i].updateValue(arguments[i]); if (this.switchingKernels) return; } if (this.plugins) { for (let i = 0; i < this.plugins.length; i++) { const plugin = this.plugins[i]; if (plugin.onBeforeRun) { plugin.onBeforeRun(this); } } } if (this.graphical) { if (this.pipeline) { gl.bindRenderbuffer(gl.RENDERBUFFER, null); gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); if (this.immutable) { this._replaceOutputTexture(); } gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); return this.immutable ? this.texture.clone() : this.texture; } gl.bindRenderbuffer(gl.RENDERBUFFER, null); gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); return; } gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); if (this.immutable) { this._replaceOutputTexture(); } if (this.subKernels !== null) { if (this.immutable) { this._replaceSubOutputTextures(); } this.drawBuffers(); } gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); } drawBuffers() { this.extensions.WEBGL_draw_buffers.drawBuffersWEBGL(this.drawBuffersMap); } getInternalFormat() { return this.context.RGBA; } getTextureFormat() { const { context: gl } = this; switch (this.getInternalFormat()) { case gl.RGBA: return gl.RGBA; default: throw new Error('Unknown internal format'); } } _replaceOutputTexture() { if (this.texture.beforeMutate() || this._textureSwitched) { const gl = this.context; gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); this._textureSwitched = false; } } _setupOutputTexture() { const gl = this.context; const texSize = this.texSize; if (this.texture) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); return; } const texture = this.createTexture(); gl.activeTexture(gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); const format = this.getInternalFormat(); if (this.precision === 'single') { gl.texImage2D(gl.TEXTURE_2D, 0, format, texSize[0], texSize[1], 0, gl.RGBA, gl.FLOAT, null); } else { gl.texImage2D(gl.TEXTURE_2D, 0, format, texSize[0], texSize[1], 0, format, gl.UNSIGNED_BYTE, null); } gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); this.texture = new this.TextureConstructor({ texture, size: texSize, dimensions: this.threadDim, output: this.output, context: this.context, internalFormat: this.getInternalFormat(), textureFormat: this.getTextureFormat(), kernel: this, }); } _replaceSubOutputTextures() { const gl = this.context; for (let i = 0; i < this.mappedTextures.length; i++) { const mappedTexture = this.mappedTextures[i]; if (mappedTexture.beforeMutate() || this._mappedTextureSwitched[i]) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, mappedTexture.texture, 0); this._mappedTextureSwitched[i] = false; } } } _setupSubOutputTextures() { const gl = this.context; if (this.mappedTextures) { for (let i = 0; i < this.subKernels.length; i++) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, this.mappedTextures[i].texture, 0); } return; } const texSize = this.texSize; this.drawBuffersMap = [gl.COLOR_ATTACHMENT0]; this.mappedTextures = []; for (let i = 0; i < this.subKernels.length; i++) { const texture = this.createTexture(); this.drawBuffersMap.push(gl.COLOR_ATTACHMENT0 + i + 1); gl.activeTexture(gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount + i); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); if (this.precision === 'single') { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize[0], texSize[1], 0, gl.RGBA, gl.FLOAT, null); } else { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize[0], texSize[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, texture, 0); this.mappedTextures.push(new this.TextureConstructor({ texture, size: texSize, dimensions: this.threadDim, output: this.output, context: this.context, internalFormat: this.getInternalFormat(), textureFormat: this.getTextureFormat(), kernel: this, })); } } setUniform1f(name, value) { if (this.uniform1fCache.hasOwnProperty(name)) { const cache = this.uniform1fCache[name]; if (value === cache) { return; } } this.uniform1fCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform1f(loc, value); } setUniform1i(name, value) { if (this.uniform1iCache.hasOwnProperty(name)) { const cache = this.uniform1iCache[name]; if (value === cache) { return; } } this.uniform1iCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform1i(loc, value); } setUniform2f(name, value1, value2) { if (this.uniform2fCache.hasOwnProperty(name)) { const cache = this.uniform2fCache[name]; if ( value1 === cache[0] && value2 === cache[1] ) { return; } } this.uniform2fCache[name] = [value1, value2]; const loc = this.getUniformLocation(name); this.context.uniform2f(loc, value1, value2); } setUniform2fv(name, value) { if (this.uniform2fvCache.hasOwnProperty(name)) { const cache = this.uniform2fvCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] ) { return; } } this.uniform2fvCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform2fv(loc, value); } setUniform2iv(name, value) { if (this.uniform2ivCache.hasOwnProperty(name)) { const cache = this.uniform2ivCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] ) { return; } } this.uniform2ivCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform2iv(loc, value); } setUniform3fv(name, value) { if (this.uniform3fvCache.hasOwnProperty(name)) { const cache = this.uniform3fvCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] && value[2] === cache[2] ) { return; } } this.uniform3fvCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform3fv(loc, value); } setUniform3iv(name, value) { if (this.uniform3ivCache.hasOwnProperty(name)) { const cache = this.uniform3ivCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] && value[2] === cache[2] ) { return; } } this.uniform3ivCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform3iv(loc, value); } setUniform4fv(name, value) { if (this.uniform4fvCache.hasOwnProperty(name)) { const cache = this.uniform4fvCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] && value[2] === cache[2] && value[3] === cache[3] ) { return; } } this.uniform4fvCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform4fv(loc, value); } setUniform4iv(name, value) { if (this.uniform4ivCache.hasOwnProperty(name)) { const cache = this.uniform4ivCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] && value[2] === cache[2] && value[3] === cache[3] ) { return; } } this.uniform4ivCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform4iv(loc, value); } getUniformLocation(name) { if (this.programUniformLocationCache.hasOwnProperty(name)) { return this.programUniformLocationCache[name]; } return this.programUniformLocationCache[name] = this.context.getUniformLocation(this.program, name); } _getFragShaderArtifactMap(args) { return { HEADER: this._getHeaderString(), LOOP_MAX: this._getLoopMaxString(), PLUGINS: this._getPluginsString(), CONSTANTS: this._getConstantsString(), DECODE32_ENDIANNESS: this._getDecode32EndiannessString(), ENCODE32_ENDIANNESS: this._getEncode32EndiannessString(), DIVIDE_WITH_INTEGER_CHECK: this._getDivideWithIntegerCheckString(), INJECTED_NATIVE: this._getInjectedNative(), MAIN_CONSTANTS: this._getMainConstantsString(), MAIN_ARGUMENTS: this._getMainArgumentsString(args), KERNEL: this.getKernelString(), MAIN_RESULT: this.getMainResultString(), FLOAT_TACTIC_DECLARATION: this.getFloatTacticDeclaration(), INT_TACTIC_DECLARATION: this.getIntTacticDeclaration(), SAMPLER_2D_TACTIC_DECLARATION: this.getSampler2DTacticDeclaration(), SAMPLER_2D_ARRAY_TACTIC_DECLARATION: this.getSampler2DArrayTacticDeclaration(), }; } _getVertShaderArtifactMap(args) { return { FLOAT_TACTIC_DECLARATION: this.getFloatTacticDeclaration(), INT_TACTIC_DECLARATION: this.getIntTacticDeclaration(), SAMPLER_2D_TACTIC_DECLARATION: this.getSampler2DTacticDeclaration(), SAMPLER_2D_ARRAY_TACTIC_DECLARATION: this.getSampler2DArrayTacticDeclaration(), }; } _getHeaderString() { return ( this.subKernels !== null ? '#extension GL_EXT_draw_buffers : require\n' : '' ); } _getLoopMaxString() { return ( this.loopMaxIterations ? ` ${parseInt(this.loopMaxIterations)};\n` : ' 1000;\n' ); } _getPluginsString() { if (!this.plugins) return '\n'; return this.plugins.map(plugin => plugin.source && this.source.match(plugin.functionMatch) ? plugin.source : '').join('\n'); } _getConstantsString() { const result = []; const { threadDim, texSize } = this; if (this.dynamicOutput) { result.push( 'uniform ivec3 uOutputDim', 'uniform ivec2 uTexSize' ); } else { result.push( `ivec3 uOutputDim = ivec3(${threadDim[0]}, ${threadDim[1]}, ${threadDim[2]})`, `ivec2 uTexSize = ivec2(${texSize[0]}, ${texSize[1]})` ); } return utils.linesToString(result); } _getTextureCoordinate() { const subKernels = this.subKernels; if (subKernels === null || subKernels.length < 1) { return 'varying vec2 vTexCoord;\n'; } else { return 'out vec2 vTexCoord;\n'; } } _getDecode32EndiannessString() { return ( this.endianness === 'LE' ? '' : ' texel.rgba = texel.abgr;\n' ); } _getEncode32EndiannessString() { return ( this.endianness === 'LE' ? '' : ' texel.rgba = texel.abgr;\n' ); } _getDivideWithIntegerCheckString() { return this.fixIntegerDivisionAccuracy ? `float divWithIntCheck(float x, float y) { if (floor(x) == x && floor(y) == y && integerMod(x, y) == 0.0) { return float(int(x) / int(y)); } return x / y; } float integerCorrectionModulo(float number, float divisor) { if (number < 0.0) { number = abs(number); if (divisor < 0.0) { divisor = abs(divisor); } return -(number - (divisor * floor(divWithIntCheck(number, divisor)))); } if (divisor < 0.0) { divisor = abs(divisor); } return number - (divisor * floor(divWithIntCheck(number, divisor))); }` : ''; } _getMainArgumentsString(args) { const results = []; const { argumentNames } = this; for (let i = 0; i < argumentNames.length; i++) { results.push(this.kernelArguments[i].getSource(args[i])); } return results.join(''); } _getInjectedNative() { return this.injectedNative || ''; } _getMainConstantsString() { const result = []; const { constants } = this; if (constants) { let i = 0; for (const name in constants) { if (!this.constants.hasOwnProperty(name)) continue; result.push(this.kernelConstants[i++].getSource(this.constants[name])); } } return result.join(''); } getRawValueFramebuffer(width, height) { if (!this.rawValueFramebuffers[width]) { this.rawValueFramebuffers[width] = {}; } if (!this.rawValueFramebuffers[width][height]) { const framebuffer = this.context.createFramebuffer(); framebuffer.width = width; framebuffer.height = height; this.rawValueFramebuffers[width][height] = framebuffer; } return this.rawValueFramebuffers[width][height]; } getKernelResultDeclaration() { switch (this.returnType) { case 'Array(2)': return 'vec2 kernelResult'; case 'Array(3)': return 'vec3 kernelResult'; case 'Array(4)': return 'vec4 kernelResult'; case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': return 'float kernelResult'; default: if (this.graphical) { return 'float kernelResult'; } else { throw new Error(`unrecognized output type "${ this.returnType }"`); } } } getKernelString() { const result = [this.getKernelResultDeclaration()]; const { subKernels } = this; if (subKernels !== null) { switch (this.returnType) { case 'Number': case 'Float': case 'Integer': for (let i = 0; i < subKernels.length; i++) { const subKernel = subKernels[i]; result.push( subKernel.returnType === 'Integer' ? `int subKernelResult_${ subKernel.name } = 0` : `float subKernelResult_${ subKernel.name } = 0.0` ); } break; case 'Array(2)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec2 subKernelResult_${ subKernels[i].name }` ); } break; case 'Array(3)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec3 subKernelResult_${ subKernels[i].name }` ); } break; case 'Array(4)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec4 subKernelResult_${ subKernels[i].name }` ); } break; } } return utils.linesToString(result) + this.translatedSource; } getMainResultGraphical() { return utils.linesToString([ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' gl_FragColor = actualColor', ]); } getMainResultPackedPixels() { switch (this.returnType) { case 'LiteralInteger': case 'Number': case 'Integer': case 'Float': return this.getMainResultKernelPackedPixels() + this.getMainResultSubKernelPackedPixels(); default: throw new Error(`packed output only usable with Numbers, "${this.returnType}" specified`); } } getMainResultKernelPackedPixels() { return utils.linesToString([ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ` gl_FragData[0] = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(kernelResult)` ]); } getMainResultSubKernelPackedPixels() { const result = []; if (!this.subKernels) return ''; for (let i = 0; i < this.subKernels.length; i++) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` gl_FragData[${i + 1}] = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(float(subKernelResult_${this.subKernels[i].name}))` ); } else { result.push( ` gl_FragData[${i + 1}] = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(subKernelResult_${this.subKernels[i].name})` ); } } return utils.linesToString(result); } getMainResultMemoryOptimizedFloats() { const result = [ ' index *= 4', ]; switch (this.returnType) { case 'Number': case 'Integer': case 'Float': const channels = ['r', 'g', 'b', 'a']; for (let i = 0; i < channels.length; i++) { const channel = channels[i]; this.getMainResultKernelMemoryOptimizedFloats(result, channel); this.getMainResultSubKernelMemoryOptimizedFloats(result, channel); if (i + 1 < channels.length) { result.push(' index += 1'); } } break; default: throw new Error(`optimized output only usable with Numbers, ${this.returnType} specified`); } return utils.linesToString(result); } getMainResultKernelMemoryOptimizedFloats(result, channel) { result.push( ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ` gl_FragData[0].${channel} = kernelResult` ); } getMainResultSubKernelMemoryOptimizedFloats(result, channel) { if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; i++) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` gl_FragData[${i + 1}].${channel} = float(subKernelResult_${this.subKernels[i].name})` ); } else { result.push( ` gl_FragData[${i + 1}].${channel} = subKernelResult_${this.subKernels[i].name}` ); } } } getMainResultKernelNumberTexture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' gl_FragData[0][0] = kernelResult', ]; } getMainResultSubKernelNumberTexture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` gl_FragData[${i + 1}][0] = float(subKernelResult_${subKernel.name})` ); } else { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${subKernel.name}` ); } } return result; } getMainResultKernelArray2Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' gl_FragData[0][0] = kernelResult[0]', ' gl_FragData[0][1] = kernelResult[1]', ]; } getMainResultSubKernelArray2Texture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${this.subKernels[i].name}[0]`, ` gl_FragData[${i + 1}][1] = subKernelResult_${this.subKernels[i].name}[1]` ); } return result; } getMainResultKernelArray3Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' gl_FragData[0][0] = kernelResult[0]', ' gl_FragData[0][1] = kernelResult[1]', ' gl_FragData[0][2] = kernelResult[2]', ]; } getMainResultSubKernelArray3Texture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${this.subKernels[i].name}[0]`, ` gl_FragData[${i + 1}][1] = subKernelResult_${this.subKernels[i].name}[1]`, ` gl_FragData[${i + 1}][2] = subKernelResult_${this.subKernels[i].name}[2]` ); } return result; } getMainResultKernelArray4Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' gl_FragData[0] = kernelResult', ]; } getMainResultSubKernelArray4Texture() { const result = []; if (!this.subKernels) return result; switch (this.returnType) { case 'Number': case 'Float': case 'Integer': for (let i = 0; i < this.subKernels.length; ++i) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` gl_FragData[${i + 1}] = float(subKernelResult_${this.subKernels[i].name})` ); } else { result.push( ` gl_FragData[${i + 1}] = subKernelResult_${this.subKernels[i].name}` ); } } break; case 'Array(2)': for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${this.subKernels[i].name}[0]`, ` gl_FragData[${i + 1}][1] = subKernelResult_${this.subKernels[i].name}[1]` ); } break; case 'Array(3)': for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${this.subKernels[i].name}[0]`, ` gl_FragData[${i + 1}][1] = subKernelResult_${this.subKernels[i].name}[1]`, ` gl_FragData[${i + 1}][2] = subKernelResult_${this.subKernels[i].name}[2]` ); } break; case 'Array(4)': for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${this.subKernels[i].name}[0]`, ` gl_FragData[${i + 1}][1] = subKernelResult_${this.subKernels[i].name}[1]`, ` gl_FragData[${i + 1}][2] = subKernelResult_${this.subKernels[i].name}[2]`, ` gl_FragData[${i + 1}][3] = subKernelResult_${this.subKernels[i].name}[3]` ); } break; } return result; } replaceArtifacts(src, map) { return src.replace(/[ ]*__([A-Z]+[0-9]*([_]?[A-Z]*[0-9]?)*)__;\n/g, (match, artifact) => { if (map.hasOwnProperty(artifact)) { return map[artifact]; } throw `unhandled artifact ${artifact}`; }); } getFragmentShader(args) { if (this.compiledFragmentShader !== null) { return this.compiledFragmentShader; } return this.compiledFragmentShader = this.replaceArtifacts(this.constructor.fragmentShader, this._getFragShaderArtifactMap(args)); } getVertexShader(args) { if (this.compiledVertexShader !== null) { return this.compiledVertexShader; } return this.compiledVertexShader = this.replaceArtifacts(this.constructor.vertexShader, this._getVertShaderArtifactMap(args)); } toString() { const setupContextString = utils.linesToString([ `const gl = context`, ]); return glKernelString(this.constructor, arguments, this, setupContextString); } destroy(removeCanvasReferences) { if (!this.context) return; if (this.buffer) { this.context.deleteBuffer(this.buffer); } if (this.framebuffer) { this.context.deleteFramebuffer(this.framebuffer); } for (const width in this.rawValueFramebuffers) { for (const height in this.rawValueFramebuffers[width]) { this.context.deleteFramebuffer(this.rawValueFramebuffers[width][height]); delete this.rawValueFramebuffers[width][height]; } delete this.rawValueFramebuffers[width]; } if (this.vertShader) { this.context.deleteShader(this.vertShader); } if (this.fragShader) { this.context.deleteShader(this.fragShader); } if (this.program) { this.context.deleteProgram(this.program); } if (this.texture) { this.texture.delete(); const textureCacheIndex = this.textureCache.indexOf(this.texture.texture); if (textureCacheIndex > -1) { this.textureCache.splice(textureCacheIndex, 1); } this.texture = null; } if (this.mappedTextures && this.mappedTextures.length) { for (let i = 0; i < this.mappedTextures.length; i++) { const mappedTexture = this.mappedTextures[i]; mappedTexture.delete(); const textureCacheIndex = this.textureCache.indexOf(mappedTexture.texture); if (textureCacheIndex > -1) { this.textureCache.splice(textureCacheIndex, 1); } } this.mappedTextures = null; } if (this.kernelArguments) { for (let i = 0; i < this.kernelArguments.length; i++) { this.kernelArguments[i].destroy(); } } if (this.kernelConstants) { for (let i = 0; i < this.kernelConstants.length; i++) { this.kernelConstants[i].destroy(); } } while (this.textureCache.length > 0) { const texture = this.textureCache.pop(); this.context.deleteTexture(texture); } if (removeCanvasReferences) { const idx = canvases.indexOf(this.canvas); if (idx >= 0) { canvases[idx] = null; maxTexSizes[idx] = null; } } this.destroyExtensions(); delete this.context; delete this.canvas; if (!this.gpu) return; const i = this.gpu.kernels.indexOf(this); if (i === -1) return; this.gpu.kernels.splice(i, 1); } destroyExtensions() { this.extensions.OES_texture_float = null; this.extensions.OES_texture_float_linear = null; this.extensions.OES_element_index_uint = null; this.extensions.WEBGL_draw_buffers = null; } static destroyContext(context) { const extension = context.getExtension('WEBGL_lose_context'); if (extension) { extension.loseContext(); } } toJSON() { const json = super.toJSON(); json.functionNodes = FunctionBuilder.fromKernel(this, WebGLFunctionNode).toJSON(); json.settings.threadDim = this.threadDim; return json; } } module.exports = { WebGLKernel }; },{"../../plugins/math-random-uniformly-distributed":112,"../../utils":114,"../function-builder":9,"../gl/kernel":13,"../gl/kernel-string":12,"./fragment-shader":37,"./function-node":38,"./kernel-value-maps":39,"./vertex-shader":71}],71:[function(require,module,exports){ const vertexShader = `__FLOAT_TACTIC_DECLARATION__; __INT_TACTIC_DECLARATION__; __SAMPLER_2D_TACTIC_DECLARATION__; attribute vec2 aPos; attribute vec2 aTexCoord; varying vec2 vTexCoord; uniform vec2 ratio; void main(void) { gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1); vTexCoord = aTexCoord; }`; module.exports = { vertexShader }; },{}],72:[function(require,module,exports){ const fragmentShader = `#version 300 es __HEADER__; __FLOAT_TACTIC_DECLARATION__; __INT_TACTIC_DECLARATION__; __SAMPLER_2D_TACTIC_DECLARATION__; __SAMPLER_2D_ARRAY_TACTIC_DECLARATION__; const int LOOP_MAX = __LOOP_MAX__; __PLUGINS__; __CONSTANTS__; in vec2 vTexCoord; float atan2(float v1, float v2) { if (v1 == 0.0 || v2 == 0.0) return 0.0; return atan(v1 / v2); } float cbrt(float x) { if (x >= 0.0) { return pow(x, 1.0 / 3.0); } else { return -pow(x, 1.0 / 3.0); } } float expm1(float x) { return pow(${Math.E}, x) - 1.0; } float fround(highp float x) { return x; } float imul(float v1, float v2) { return float(int(v1) * int(v2)); } float log10(float x) { return log2(x) * (1.0 / log2(10.0)); } float log1p(float x) { return log(1.0 + x); } float _pow(float v1, float v2) { if (v2 == 0.0) return 1.0; return pow(v1, v2); } float _round(float x) { return floor(x + 0.5); } const int BIT_COUNT = 32; int modi(int x, int y) { return x - y * (x / y); } int bitwiseOr(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 || b > 0)) { break; } } return result; } int bitwiseXOR(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 || b > 0)) { break; } } return result; } int bitwiseAnd(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 && b > 0)) { break; } } return result; } int bitwiseNot(int a) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if (modi(a, 2) == 0) { result += n; } a = a / 2; n = n * 2; } return result; } int bitwiseZeroFillLeftShift(int n, int shift) { int maxBytes = BIT_COUNT; for (int i = 0; i < BIT_COUNT; i++) { if (maxBytes >= n) { break; } maxBytes *= 2; } for (int i = 0; i < BIT_COUNT; i++) { if (i >= shift) { break; } n *= 2; } int result = 0; int byteVal = 1; for (int i = 0; i < BIT_COUNT; i++) { if (i >= maxBytes) break; if (modi(n, 2) > 0) { result += byteVal; } n = int(n / 2); byteVal *= 2; } return result; } int bitwiseSignedRightShift(int num, int shifts) { return int(floor(float(num) / pow(2.0, float(shifts)))); } int bitwiseZeroFillRightShift(int n, int shift) { int maxBytes = BIT_COUNT; for (int i = 0; i < BIT_COUNT; i++) { if (maxBytes >= n) { break; } maxBytes *= 2; } for (int i = 0; i < BIT_COUNT; i++) { if (i >= shift) { break; } n /= 2; } int result = 0; int byteVal = 1; for (int i = 0; i < BIT_COUNT; i++) { if (i >= maxBytes) break; if (modi(n, 2) > 0) { result += byteVal; } n = int(n / 2); byteVal *= 2; } return result; } vec2 integerMod(vec2 x, float y) { vec2 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } vec3 integerMod(vec3 x, float y) { vec3 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } vec4 integerMod(vec4 x, vec4 y) { vec4 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } float integerMod(float x, float y) { float res = floor(mod(x, y)); return res * (res > floor(y) - 1.0 ? 0.0 : 1.0); } int integerMod(int x, int y) { return x - (y * int(x/y)); } __DIVIDE_WITH_INTEGER_CHECK__; // Here be dragons! // DO NOT OPTIMIZE THIS CODE // YOU WILL BREAK SOMETHING ON SOMEBODY\'S MACHINE // LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME const vec2 MAGIC_VEC = vec2(1.0, -256.0); const vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0); const vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536 float decode32(vec4 texel) { __DECODE32_ENDIANNESS__; texel *= 255.0; vec2 gte128; gte128.x = texel.b >= 128.0 ? 1.0 : 0.0; gte128.y = texel.a >= 128.0 ? 1.0 : 0.0; float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC); float res = exp2(round(exponent)); texel.b = texel.b - 128.0 * gte128.x; res = dot(texel, SCALE_FACTOR) * exp2(round(exponent-23.0)) + res; res *= gte128.y * -2.0 + 1.0; return res; } float decode16(vec4 texel, int index) { int channel = integerMod(index, 2); return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0; } float decode8(vec4 texel, int index) { int channel = integerMod(index, 4); return texel[channel] * 255.0; } vec4 legacyEncode32(float f) { float F = abs(f); float sign = f < 0.0 ? 1.0 : 0.0; float exponent = floor(log2(F)); float mantissa = (exp2(-exponent) * F); // exponent += floor(log2(mantissa)); vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV; texel.rg = integerMod(texel.rg, 256.0); texel.b = integerMod(texel.b, 128.0); texel.a = exponent*0.5 + 63.5; texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0; texel = floor(texel); texel *= 0.003921569; // 1/255 __ENCODE32_ENDIANNESS__; return texel; } // https://github.com/gpujs/gpu.js/wiki/Encoder-details vec4 encode32(float value) { if (value == 0.0) return vec4(0, 0, 0, 0); float exponent; float mantissa; vec4 result; float sgn; sgn = step(0.0, -value); value = abs(value); exponent = floor(log2(value)); mantissa = value*pow(2.0, -exponent)-1.0; exponent = exponent+127.0; result = vec4(0,0,0,0); result.a = floor(exponent/2.0); exponent = exponent - result.a*2.0; result.a = result.a + 128.0*sgn; result.b = floor(mantissa * 128.0); mantissa = mantissa - result.b / 128.0; result.b = result.b + exponent*128.0; result.g = floor(mantissa*32768.0); mantissa = mantissa - result.g/32768.0; result.r = floor(mantissa*8388608.0); return result/255.0; } // Dragons end here int index; ivec3 threadId; ivec3 indexTo3D(int idx, ivec3 texDim) { int z = int(idx / (texDim.x * texDim.y)); idx -= z * int(texDim.x * texDim.y); int y = int(idx / texDim.x); int x = int(integerMod(idx, texDim.x)); return ivec3(x, y, z); } float get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture(tex, st / vec2(texSize)); return decode32(texel); } float get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + (texDim.x * (y + (texDim.y * z))); int w = texSize.x * 2; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y)); return decode16(texel, index); } float get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + (texDim.x * (y + (texDim.y * z))); int w = texSize.x * 4; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y)); return decode8(texel, index); } float getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + (texDim.x * (y + (texDim.y * z))); int channel = integerMod(index, 4); index = index / 4; int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; index = index / 4; vec4 texel = texture(tex, st / vec2(texSize)); return texel[channel]; } vec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; return texture(tex, st / vec2(texSize)); } vec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; return texture(tex, vec3(st / vec2(texSize), z)); } float getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return result[0]; } vec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return vec2(result[0], result[1]); } vec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int channel = integerMod(index, 2); index = index / 2; int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture(tex, st / vec2(texSize)); if (channel == 0) return vec2(texel.r, texel.g); if (channel == 1) return vec2(texel.b, texel.a); return vec2(0.0, 0.0); } vec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return vec3(result[0], result[1], result[2]); } vec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z)); int vectorIndex = fieldIndex / 4; int vectorOffset = fieldIndex - vectorIndex * 4; int readY = vectorIndex / texSize.x; int readX = vectorIndex - readY * texSize.x; vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize)); if (vectorOffset == 0) { return tex1.xyz; } else if (vectorOffset == 1) { return tex1.yzw; } else { readX++; if (readX >= texSize.x) { readX = 0; readY++; } vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize)); if (vectorOffset == 2) { return vec3(tex1.z, tex1.w, tex2.x); } else { return vec3(tex1.w, tex2.x, tex2.y); } } } vec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { return getImage2D(tex, texSize, texDim, z, y, x); } vec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int channel = integerMod(index, 2); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture(tex, st / vec2(texSize)); return vec4(texel.r, texel.g, texel.b, texel.a); } vec4 actualColor; void color(float r, float g, float b, float a) { actualColor = vec4(r,g,b,a); } void color(float r, float g, float b) { color(r,g,b,1.0); } float modulo(float number, float divisor) { if (number < 0.0) { number = abs(number); if (divisor < 0.0) { divisor = abs(divisor); } return -mod(number, divisor); } if (divisor < 0.0) { divisor = abs(divisor); } return mod(number, divisor); } __INJECTED_NATIVE__; __MAIN_CONSTANTS__; __MAIN_ARGUMENTS__; __KERNEL__; void main(void) { index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x; __MAIN_RESULT__; }`; module.exports = { fragmentShader }; },{}],73:[function(require,module,exports){ const { utils } = require('../../utils'); const { WebGLFunctionNode } = require('../web-gl/function-node'); class WebGL2FunctionNode extends WebGLFunctionNode { astIdentifierExpression(idtNode, retArr) { if (idtNode.type !== 'Identifier') { throw this.astErrorOutput( 'IdentifierExpression - not an Identifier', idtNode ); } const type = this.getType(idtNode); const name = utils.sanitizeName(idtNode.name); if (idtNode.name === 'Infinity') { retArr.push('intBitsToFloat(2139095039)'); } else if (type === 'Boolean') { if (this.argumentNames.indexOf(name) > -1) { retArr.push(`bool(user_${name})`); } else { retArr.push(`user_${name}`); } } else { retArr.push(`user_${name}`); } return retArr; } } module.exports = { WebGL2FunctionNode }; },{"../../utils":114,"../web-gl/function-node":38}],74:[function(require,module,exports){ const { WebGL2KernelValueBoolean } = require('./kernel-value/boolean'); const { WebGL2KernelValueFloat } = require('./kernel-value/float'); const { WebGL2KernelValueInteger } = require('./kernel-value/integer'); const { WebGL2KernelValueHTMLImage } = require('./kernel-value/html-image'); const { WebGL2KernelValueDynamicHTMLImage } = require('./kernel-value/dynamic-html-image'); const { WebGL2KernelValueHTMLImageArray } = require('./kernel-value/html-image-array'); const { WebGL2KernelValueDynamicHTMLImageArray } = require('./kernel-value/dynamic-html-image-array'); const { WebGL2KernelValueHTMLVideo } = require('./kernel-value/html-video'); const { WebGL2KernelValueDynamicHTMLVideo } = require('./kernel-value/dynamic-html-video'); const { WebGL2KernelValueSingleInput } = require('./kernel-value/single-input'); const { WebGL2KernelValueDynamicSingleInput } = require('./kernel-value/dynamic-single-input'); const { WebGL2KernelValueUnsignedInput } = require('./kernel-value/unsigned-input'); const { WebGL2KernelValueDynamicUnsignedInput } = require('./kernel-value/dynamic-unsigned-input'); const { WebGL2KernelValueMemoryOptimizedNumberTexture } = require('./kernel-value/memory-optimized-number-texture'); const { WebGL2KernelValueDynamicMemoryOptimizedNumberTexture } = require('./kernel-value/dynamic-memory-optimized-number-texture'); const { WebGL2KernelValueNumberTexture } = require('./kernel-value/number-texture'); const { WebGL2KernelValueDynamicNumberTexture } = require('./kernel-value/dynamic-number-texture'); const { WebGL2KernelValueSingleArray } = require('./kernel-value/single-array'); const { WebGL2KernelValueDynamicSingleArray } = require('./kernel-value/dynamic-single-array'); const { WebGL2KernelValueSingleArray1DI } = require('./kernel-value/single-array1d-i'); const { WebGL2KernelValueDynamicSingleArray1DI } = require('./kernel-value/dynamic-single-array1d-i'); const { WebGL2KernelValueSingleArray2DI } = require('./kernel-value/single-array2d-i'); const { WebGL2KernelValueDynamicSingleArray2DI } = require('./kernel-value/dynamic-single-array2d-i'); const { WebGL2KernelValueSingleArray3DI } = require('./kernel-value/single-array3d-i'); const { WebGL2KernelValueDynamicSingleArray3DI } = require('./kernel-value/dynamic-single-array3d-i'); const { WebGL2KernelValueArray2 } = require('./kernel-value/array2'); const { WebGL2KernelValueArray3 } = require('./kernel-value/array3'); const { WebGL2KernelValueArray4 } = require('./kernel-value/array4'); const { WebGL2KernelValueUnsignedArray } = require('./kernel-value/unsigned-array'); const { WebGL2KernelValueDynamicUnsignedArray } = require('./kernel-value/dynamic-unsigned-array'); const kernelValueMaps = { unsigned: { dynamic: { 'Boolean': WebGL2KernelValueBoolean, 'Integer': WebGL2KernelValueInteger, 'Float': WebGL2KernelValueFloat, 'Array': WebGL2KernelValueDynamicUnsignedArray, 'Array(2)': WebGL2KernelValueArray2, 'Array(3)': WebGL2KernelValueArray3, 'Array(4)': WebGL2KernelValueArray4, 'Array1D(2)': false, 'Array1D(3)': false, 'Array1D(4)': false, 'Array2D(2)': false, 'Array2D(3)': false, 'Array2D(4)': false, 'Array3D(2)': false, 'Array3D(3)': false, 'Array3D(4)': false, 'Input': WebGL2KernelValueDynamicUnsignedInput, 'NumberTexture': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(1)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(2)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(3)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(4)': WebGL2KernelValueDynamicNumberTexture, 'MemoryOptimizedNumberTexture': WebGL2KernelValueDynamicMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGL2KernelValueDynamicHTMLImage, 'OffscreenCanvas': WebGL2KernelValueDynamicHTMLImage, 'HTMLImage': WebGL2KernelValueDynamicHTMLImage, 'ImageBitmap': WebGL2KernelValueDynamicHTMLImage, 'ImageData': WebGL2KernelValueDynamicHTMLImage, 'HTMLImageArray': WebGL2KernelValueDynamicHTMLImageArray, 'HTMLVideo': WebGL2KernelValueDynamicHTMLVideo, }, static: { 'Boolean': WebGL2KernelValueBoolean, 'Float': WebGL2KernelValueFloat, 'Integer': WebGL2KernelValueInteger, 'Array': WebGL2KernelValueUnsignedArray, 'Array(2)': WebGL2KernelValueArray2, 'Array(3)': WebGL2KernelValueArray3, 'Array(4)': WebGL2KernelValueArray4, 'Array1D(2)': false, 'Array1D(3)': false, 'Array1D(4)': false, 'Array2D(2)': false, 'Array2D(3)': false, 'Array2D(4)': false, 'Array3D(2)': false, 'Array3D(3)': false, 'Array3D(4)': false, 'Input': WebGL2KernelValueUnsignedInput, 'NumberTexture': WebGL2KernelValueNumberTexture, 'ArrayTexture(1)': WebGL2KernelValueNumberTexture, 'ArrayTexture(2)': WebGL2KernelValueNumberTexture, 'ArrayTexture(3)': WebGL2KernelValueNumberTexture, 'ArrayTexture(4)': WebGL2KernelValueNumberTexture, 'MemoryOptimizedNumberTexture': WebGL2KernelValueDynamicMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGL2KernelValueHTMLImage, 'OffscreenCanvas': WebGL2KernelValueHTMLImage, 'HTMLImage': WebGL2KernelValueHTMLImage, 'ImageBitmap': WebGL2KernelValueHTMLImage, 'ImageData': WebGL2KernelValueHTMLImage, 'HTMLImageArray': WebGL2KernelValueHTMLImageArray, 'HTMLVideo': WebGL2KernelValueHTMLVideo, } }, single: { dynamic: { 'Boolean': WebGL2KernelValueBoolean, 'Integer': WebGL2KernelValueInteger, 'Float': WebGL2KernelValueFloat, 'Array': WebGL2KernelValueDynamicSingleArray, 'Array(2)': WebGL2KernelValueArray2, 'Array(3)': WebGL2KernelValueArray3, 'Array(4)': WebGL2KernelValueArray4, 'Array1D(2)': WebGL2KernelValueDynamicSingleArray1DI, 'Array1D(3)': WebGL2KernelValueDynamicSingleArray1DI, 'Array1D(4)': WebGL2KernelValueDynamicSingleArray1DI, 'Array2D(2)': WebGL2KernelValueDynamicSingleArray2DI, 'Array2D(3)': WebGL2KernelValueDynamicSingleArray2DI, 'Array2D(4)': WebGL2KernelValueDynamicSingleArray2DI, 'Array3D(2)': WebGL2KernelValueDynamicSingleArray3DI, 'Array3D(3)': WebGL2KernelValueDynamicSingleArray3DI, 'Array3D(4)': WebGL2KernelValueDynamicSingleArray3DI, 'Input': WebGL2KernelValueDynamicSingleInput, 'NumberTexture': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(1)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(2)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(3)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(4)': WebGL2KernelValueDynamicNumberTexture, 'MemoryOptimizedNumberTexture': WebGL2KernelValueDynamicMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGL2KernelValueDynamicHTMLImage, 'OffscreenCanvas': WebGL2KernelValueDynamicHTMLImage, 'HTMLImage': WebGL2KernelValueDynamicHTMLImage, 'ImageBitmap': WebGL2KernelValueDynamicHTMLImage, 'ImageData': WebGL2KernelValueDynamicHTMLImage, 'HTMLImageArray': WebGL2KernelValueDynamicHTMLImageArray, 'HTMLVideo': WebGL2KernelValueDynamicHTMLVideo, }, static: { 'Boolean': WebGL2KernelValueBoolean, 'Float': WebGL2KernelValueFloat, 'Integer': WebGL2KernelValueInteger, 'Array': WebGL2KernelValueSingleArray, 'Array(2)': WebGL2KernelValueArray2, 'Array(3)': WebGL2KernelValueArray3, 'Array(4)': WebGL2KernelValueArray4, 'Array1D(2)': WebGL2KernelValueSingleArray1DI, 'Array1D(3)': WebGL2KernelValueSingleArray1DI, 'Array1D(4)': WebGL2KernelValueSingleArray1DI, 'Array2D(2)': WebGL2KernelValueSingleArray2DI, 'Array2D(3)': WebGL2KernelValueSingleArray2DI, 'Array2D(4)': WebGL2KernelValueSingleArray2DI, 'Array3D(2)': WebGL2KernelValueSingleArray3DI, 'Array3D(3)': WebGL2KernelValueSingleArray3DI, 'Array3D(4)': WebGL2KernelValueSingleArray3DI, 'Input': WebGL2KernelValueSingleInput, 'NumberTexture': WebGL2KernelValueNumberTexture, 'ArrayTexture(1)': WebGL2KernelValueNumberTexture, 'ArrayTexture(2)': WebGL2KernelValueNumberTexture, 'ArrayTexture(3)': WebGL2KernelValueNumberTexture, 'ArrayTexture(4)': WebGL2KernelValueNumberTexture, 'MemoryOptimizedNumberTexture': WebGL2KernelValueMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGL2KernelValueHTMLImage, 'OffscreenCanvas': WebGL2KernelValueHTMLImage, 'HTMLImage': WebGL2KernelValueHTMLImage, 'ImageBitmap': WebGL2KernelValueHTMLImage, 'ImageData': WebGL2KernelValueHTMLImage, 'HTMLImageArray': WebGL2KernelValueHTMLImageArray, 'HTMLVideo': WebGL2KernelValueHTMLVideo, } }, }; function lookupKernelValueType(type, dynamic, precision, value) { if (!type) { throw new Error('type missing'); } if (!dynamic) { throw new Error('dynamic missing'); } if (!precision) { throw new Error('precision missing'); } if (value.type) { type = value.type; } const types = kernelValueMaps[precision][dynamic]; if (types[type] === false) { return null; } else if (types[type] === undefined) { throw new Error(`Could not find a KernelValue for ${ type }`); } return types[type]; } module.exports = { kernelValueMaps, lookupKernelValueType }; },{"./kernel-value/array2":75,"./kernel-value/array3":76,"./kernel-value/array4":77,"./kernel-value/boolean":78,"./kernel-value/dynamic-html-image":80,"./kernel-value/dynamic-html-image-array":79,"./kernel-value/dynamic-html-video":81,"./kernel-value/dynamic-memory-optimized-number-texture":82,"./kernel-value/dynamic-number-texture":83,"./kernel-value/dynamic-single-array":84,"./kernel-value/dynamic-single-array1d-i":85,"./kernel-value/dynamic-single-array2d-i":86,"./kernel-value/dynamic-single-array3d-i":87,"./kernel-value/dynamic-single-input":88,"./kernel-value/dynamic-unsigned-array":89,"./kernel-value/dynamic-unsigned-input":90,"./kernel-value/float":91,"./kernel-value/html-image":93,"./kernel-value/html-image-array":92,"./kernel-value/html-video":94,"./kernel-value/integer":95,"./kernel-value/memory-optimized-number-texture":96,"./kernel-value/number-texture":97,"./kernel-value/single-array":98,"./kernel-value/single-array1d-i":99,"./kernel-value/single-array2d-i":100,"./kernel-value/single-array3d-i":101,"./kernel-value/single-input":102,"./kernel-value/unsigned-array":103,"./kernel-value/unsigned-input":104}],75:[function(require,module,exports){ const { WebGLKernelValueArray2 } = require('../../web-gl/kernel-value/array2'); class WebGL2KernelValueArray2 extends WebGLKernelValueArray2 {} module.exports = { WebGL2KernelValueArray2 }; },{"../../web-gl/kernel-value/array2":41}],76:[function(require,module,exports){ const { WebGLKernelValueArray3 } = require('../../web-gl/kernel-value/array3'); class WebGL2KernelValueArray3 extends WebGLKernelValueArray3 {} module.exports = { WebGL2KernelValueArray3 }; },{"../../web-gl/kernel-value/array3":42}],77:[function(require,module,exports){ const { WebGLKernelValueArray4 } = require('../../web-gl/kernel-value/array4'); class WebGL2KernelValueArray4 extends WebGLKernelValueArray4 {} module.exports = { WebGL2KernelValueArray4 }; },{"../../web-gl/kernel-value/array4":43}],78:[function(require,module,exports){ const { WebGLKernelValueBoolean } = require('../../web-gl/kernel-value/boolean'); class WebGL2KernelValueBoolean extends WebGLKernelValueBoolean {} module.exports = { WebGL2KernelValueBoolean }; },{"../../web-gl/kernel-value/boolean":44}],79:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueHTMLImageArray } = require('./html-image-array'); class WebGL2KernelValueDynamicHTMLImageArray extends WebGL2KernelValueHTMLImageArray { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2DArray ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(images) { const { width, height } = images[0]; this.checkSize(width, height); this.dimensions = [width, height, images.length]; this.textureSize = [width, height]; this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(images); } } module.exports = { WebGL2KernelValueDynamicHTMLImageArray }; },{"../../../utils":114,"./html-image-array":92}],80:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueDynamicHTMLImage } = require('../../web-gl/kernel-value/dynamic-html-image'); class WebGL2KernelValueDynamicHTMLImage extends WebGLKernelValueDynamicHTMLImage { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } } module.exports = { WebGL2KernelValueDynamicHTMLImage }; },{"../../../utils":114,"../../web-gl/kernel-value/dynamic-html-image":45}],81:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueDynamicHTMLImage } = require('./dynamic-html-image'); class WebGL2KernelValueDynamicHTMLVideo extends WebGL2KernelValueDynamicHTMLImage {} module.exports = { WebGL2KernelValueDynamicHTMLVideo }; },{"../../../utils":114,"./dynamic-html-image":80}],82:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueDynamicMemoryOptimizedNumberTexture } = require('../../web-gl/kernel-value/dynamic-memory-optimized-number-texture'); class WebGL2KernelValueDynamicMemoryOptimizedNumberTexture extends WebGLKernelValueDynamicMemoryOptimizedNumberTexture { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } } module.exports = { WebGL2KernelValueDynamicMemoryOptimizedNumberTexture }; },{"../../../utils":114,"../../web-gl/kernel-value/dynamic-memory-optimized-number-texture":47}],83:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueDynamicNumberTexture } = require('../../web-gl/kernel-value/dynamic-number-texture'); class WebGL2KernelValueDynamicNumberTexture extends WebGLKernelValueDynamicNumberTexture { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } } module.exports = { WebGL2KernelValueDynamicNumberTexture }; },{"../../../utils":114,"../../web-gl/kernel-value/dynamic-number-texture":48}],84:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueSingleArray } = require('../../web-gl2/kernel-value/single-array'); class WebGL2KernelValueDynamicSingleArray extends WebGL2KernelValueSingleArray { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.dimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGL2KernelValueDynamicSingleArray }; },{"../../../utils":114,"../../web-gl2/kernel-value/single-array":98}],85:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueSingleArray1DI } = require('../../web-gl2/kernel-value/single-array1d-i'); class WebGL2KernelValueDynamicSingleArray1DI extends WebGL2KernelValueSingleArray1DI { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGL2KernelValueDynamicSingleArray1DI }; },{"../../../utils":114,"../../web-gl2/kernel-value/single-array1d-i":99}],86:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueSingleArray2DI } = require('../../web-gl2/kernel-value/single-array2d-i'); class WebGL2KernelValueDynamicSingleArray2DI extends WebGL2KernelValueSingleArray2DI { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGL2KernelValueDynamicSingleArray2DI }; },{"../../../utils":114,"../../web-gl2/kernel-value/single-array2d-i":100}],87:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueSingleArray3DI } = require('../../web-gl2/kernel-value/single-array3d-i'); class WebGL2KernelValueDynamicSingleArray3DI extends WebGL2KernelValueSingleArray3DI { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGL2KernelValueDynamicSingleArray3DI }; },{"../../../utils":114,"../../web-gl2/kernel-value/single-array3d-i":101}],88:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueSingleInput } = require('../../web-gl2/kernel-value/single-input'); class WebGL2KernelValueDynamicSingleInput extends WebGL2KernelValueSingleInput { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { let [w, h, d] = value.size; this.dimensions = new Int32Array([w || 1, h || 1, d || 1]); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGL2KernelValueDynamicSingleInput }; },{"../../../utils":114,"../../web-gl2/kernel-value/single-input":102}],89:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueDynamicUnsignedArray } = require('../../web-gl/kernel-value/dynamic-unsigned-array'); class WebGL2KernelValueDynamicUnsignedArray extends WebGLKernelValueDynamicUnsignedArray { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } } module.exports = { WebGL2KernelValueDynamicUnsignedArray }; },{"../../../utils":114,"../../web-gl/kernel-value/dynamic-unsigned-array":54}],90:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueDynamicUnsignedInput } = require('../../web-gl/kernel-value/dynamic-unsigned-input'); class WebGL2KernelValueDynamicUnsignedInput extends WebGLKernelValueDynamicUnsignedInput { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } } module.exports = { WebGL2KernelValueDynamicUnsignedInput }; },{"../../../utils":114,"../../web-gl/kernel-value/dynamic-unsigned-input":55}],91:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueFloat } = require('../../web-gl/kernel-value/float'); class WebGL2KernelValueFloat extends WebGLKernelValueFloat {} module.exports = { WebGL2KernelValueFloat }; },{"../../../utils":114,"../../web-gl/kernel-value/float":56}],92:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('../../web-gl/kernel-value/array'); class WebGL2KernelValueHTMLImageArray extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.checkSize(value[0].width, value[0].height); this.dimensions = [value[0].width, value[0].height, value.length]; this.textureSize = [value[0].width, value[0].height]; } defineTexture() { const { context: gl } = this; gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.texture); gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MIN_FILTER, gl.NEAREST); } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName};\n`; } getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2DArray ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(images) { const { context: gl } = this; gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.texImage3D( gl.TEXTURE_2D_ARRAY, 0, gl.RGBA, images[0].width, images[0].height, images.length, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); for (let i = 0; i < images.length; i++) { const xOffset = 0; const yOffset = 0; const imageDepth = 1; gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, xOffset, yOffset, i, images[i].width, images[i].height, imageDepth, gl.RGBA, gl.UNSIGNED_BYTE, this.uploadValue = images[i] ); } this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueHTMLImageArray }; },{"../../../utils":114,"../../web-gl/kernel-value/array":40}],93:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueHTMLImage } = require('../../web-gl/kernel-value/html-image'); class WebGL2KernelValueHTMLImage extends WebGLKernelValueHTMLImage { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } } module.exports = { WebGL2KernelValueHTMLImage }; },{"../../../utils":114,"../../web-gl/kernel-value/html-image":57}],94:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGL2KernelValueHTMLImage } = require('./html-image'); class WebGL2KernelValueHTMLVideo extends WebGL2KernelValueHTMLImage {} module.exports = { WebGL2KernelValueHTMLVideo }; },{"../../../utils":114,"./html-image":93}],95:[function(require,module,exports){ const { WebGLKernelValueInteger } = require('../../web-gl/kernel-value/integer'); class WebGL2KernelValueInteger extends WebGLKernelValueInteger { getSource(value) { const variablePrecision = this.getVariablePrecisionString(); if (this.origin === 'constants') { return `const ${ variablePrecision } int ${this.id} = ${ parseInt(value) };\n`; } return `uniform ${ variablePrecision } int ${this.id};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform1i(this.id, this.uploadValue = value); } } module.exports = { WebGL2KernelValueInteger }; },{"../../web-gl/kernel-value/integer":60}],96:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueMemoryOptimizedNumberTexture } = require('../../web-gl/kernel-value/memory-optimized-number-texture'); class WebGL2KernelValueMemoryOptimizedNumberTexture extends WebGLKernelValueMemoryOptimizedNumberTexture { getSource() { const { id, sizeId, textureSize, dimensionsId, dimensions } = this; const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform sampler2D ${id}`, `${ variablePrecision } ivec2 ${sizeId} = ivec2(${textureSize[0]}, ${textureSize[1]})`, `${ variablePrecision } ivec3 ${dimensionsId} = ivec3(${dimensions[0]}, ${dimensions[1]}, ${dimensions[2]})`, ]); } } module.exports = { WebGL2KernelValueMemoryOptimizedNumberTexture }; },{"../../../utils":114,"../../web-gl/kernel-value/memory-optimized-number-texture":61}],97:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueNumberTexture } = require('../../web-gl/kernel-value/number-texture'); class WebGL2KernelValueNumberTexture extends WebGLKernelValueNumberTexture { getSource() { const { id, sizeId, textureSize, dimensionsId, dimensions } = this; const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${id}`, `${ variablePrecision } ivec2 ${sizeId} = ivec2(${textureSize[0]}, ${textureSize[1]})`, `${ variablePrecision } ivec3 ${dimensionsId} = ivec3(${dimensions[0]}, ${dimensions[1]}, ${dimensions[2]})`, ]); } } module.exports = { WebGL2KernelValueNumberTexture }; },{"../../../utils":114,"../../web-gl/kernel-value/number-texture":62}],98:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray } = require('../../web-gl/kernel-value/single-array'); class WebGL2KernelValueSingleArray extends WebGLKernelValueSingleArray { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueSingleArray }; },{"../../../utils":114,"../../web-gl/kernel-value/single-array":63}],99:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray1DI } = require('../../web-gl/kernel-value/single-array1d-i'); class WebGL2KernelValueSingleArray1DI extends WebGLKernelValueSingleArray1DI { updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueSingleArray1DI }; },{"../../../utils":114,"../../web-gl/kernel-value/single-array1d-i":64}],100:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray2DI } = require('../../web-gl/kernel-value/single-array2d-i'); class WebGL2KernelValueSingleArray2DI extends WebGLKernelValueSingleArray2DI { updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueSingleArray2DI }; },{"../../../utils":114,"../../web-gl/kernel-value/single-array2d-i":65}],101:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray3DI } = require('../../web-gl/kernel-value/single-array3d-i'); class WebGL2KernelValueSingleArray3DI extends WebGLKernelValueSingleArray3DI { updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueSingleArray3DI }; },{"../../../utils":114,"../../web-gl/kernel-value/single-array3d-i":66}],102:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleInput } = require('../../web-gl/kernel-value/single-input'); class WebGL2KernelValueSingleInput extends WebGLKernelValueSingleInput { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(input) { const { context: gl } = this; utils.flattenTo(input.value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueSingleInput }; },{"../../../utils":114,"../../web-gl/kernel-value/single-input":67}],103:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueUnsignedArray } = require('../../web-gl/kernel-value/unsigned-array'); class WebGL2KernelValueUnsignedArray extends WebGLKernelValueUnsignedArray { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } } module.exports = { WebGL2KernelValueUnsignedArray }; },{"../../../utils":114,"../../web-gl/kernel-value/unsigned-array":68}],104:[function(require,module,exports){ const { utils } = require('../../../utils'); const { WebGLKernelValueUnsignedInput } = require('../../web-gl/kernel-value/unsigned-input'); class WebGL2KernelValueUnsignedInput extends WebGLKernelValueUnsignedInput { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } } module.exports = { WebGL2KernelValueUnsignedInput }; },{"../../../utils":114,"../../web-gl/kernel-value/unsigned-input":69}],105:[function(require,module,exports){ const { WebGLKernel } = require('../web-gl/kernel'); const { WebGL2FunctionNode } = require('./function-node'); const { FunctionBuilder } = require('../function-builder'); const { utils } = require('../../utils'); const { fragmentShader } = require('./fragment-shader'); const { vertexShader } = require('./vertex-shader'); const { lookupKernelValueType } = require('./kernel-value-maps'); let isSupported = null; let testCanvas = null; let testContext = null; let testExtensions = null; let features = null; class WebGL2Kernel extends WebGLKernel { static get isSupported() { if (isSupported !== null) { return isSupported; } this.setupFeatureChecks(); isSupported = this.isContextMatch(testContext); return isSupported; } static setupFeatureChecks() { if (typeof document !== 'undefined') { testCanvas = document.createElement('canvas'); } else if (typeof OffscreenCanvas !== 'undefined') { testCanvas = new OffscreenCanvas(0, 0); } if (!testCanvas) return; testContext = testCanvas.getContext('webgl2'); if (!testContext || !testContext.getExtension) return; testExtensions = { EXT_color_buffer_float: testContext.getExtension('EXT_color_buffer_float'), OES_texture_float_linear: testContext.getExtension('OES_texture_float_linear'), }; features = this.getFeatures(); } static isContextMatch(context) { if (typeof WebGL2RenderingContext !== 'undefined') { return context instanceof WebGL2RenderingContext; } return false; } static getFeatures() { const gl = this.testContext; return Object.freeze({ isFloatRead: this.getIsFloatRead(), isIntegerDivisionAccurate: this.getIsIntegerDivisionAccurate(), isSpeedTacticSupported: this.getIsSpeedTacticSupported(), kernelMap: true, isTextureFloat: true, isDrawBuffers: true, channelCount: this.getChannelCount(), maxTextureSize: this.getMaxTextureSize(), lowIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT), lowFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT), mediumIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT), mediumFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT), highIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT), highFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT), }); } static getIsTextureFloat() { return true; } static getChannelCount() { return testContext.getParameter(testContext.MAX_DRAW_BUFFERS); } static getMaxTextureSize() { return testContext.getParameter(testContext.MAX_TEXTURE_SIZE); } static lookupKernelValueType(type, dynamic, precision, value) { return lookupKernelValueType(type, dynamic, precision, value); } static get testCanvas() { return testCanvas; } static get testContext() { return testContext; } static get features() { return features; } static get fragmentShader() { return fragmentShader; } static get vertexShader() { return vertexShader; } initContext() { const settings = { alpha: false, depth: false, antialias: false }; return this.canvas.getContext('webgl2', settings); } initExtensions() { this.extensions = { EXT_color_buffer_float: this.context.getExtension('EXT_color_buffer_float'), OES_texture_float_linear: this.context.getExtension('OES_texture_float_linear'), }; } validateSettings(args) { if (!this.validate) { this.texSize = utils.getKernelTextureSize({ optimizeFloatMemory: this.optimizeFloatMemory, precision: this.precision, }, this.output); return; } const { features } = this.constructor; if (this.precision === 'single' && !features.isFloatRead) { throw new Error('Float texture outputs are not supported'); } else if (!this.graphical && this.precision === null) { this.precision = features.isFloatRead ? 'single' : 'unsigned'; } if (this.fixIntegerDivisionAccuracy === null) { this.fixIntegerDivisionAccuracy = !features.isIntegerDivisionAccurate; } else if (this.fixIntegerDivisionAccuracy && features.isIntegerDivisionAccurate) { this.fixIntegerDivisionAccuracy = false; } this.checkOutput(); if (!this.output || this.output.length === 0) { if (args.length !== 1) { throw new Error('Auto output only supported for kernels with only one input'); } const argType = utils.getVariableType(args[0], this.strictIntegers); switch (argType) { case 'Array': this.output = utils.getDimensions(argType); break; case 'NumberTexture': case 'MemoryOptimizedNumberTexture': case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': this.output = args[0].output; break; default: throw new Error('Auto output not supported for input type: ' + argType); } } if (this.graphical) { if (this.output.length !== 2) { throw new Error('Output must have 2 dimensions on graphical mode'); } if (this.precision === 'single') { console.warn('Cannot use graphical mode and single precision at the same time'); this.precision = 'unsigned'; } this.texSize = utils.clone(this.output); return; } else if (!this.graphical && this.precision === null && features.isTextureFloat) { this.precision = 'single'; } this.texSize = utils.getKernelTextureSize({ optimizeFloatMemory: this.optimizeFloatMemory, precision: this.precision, }, this.output); this.checkTextureSize(); } translateSource() { const functionBuilder = FunctionBuilder.fromKernel(this, WebGL2FunctionNode, { fixIntegerDivisionAccuracy: this.fixIntegerDivisionAccuracy }); this.translatedSource = functionBuilder.getPrototypeString('kernel'); this.setupReturnTypes(functionBuilder); } drawBuffers() { this.context.drawBuffers(this.drawBuffersMap); } getTextureFormat() { const { context: gl } = this; switch (this.getInternalFormat()) { case gl.R32F: return gl.RED; case gl.RG32F: return gl.RG; case gl.RGBA32F: return gl.RGBA; case gl.RGBA: return gl.RGBA; default: throw new Error('Unknown internal format'); } } getInternalFormat() { const { context: gl } = this; if (this.precision === 'single') { if (this.pipeline) { switch (this.returnType) { case 'Number': case 'Float': case 'Integer': if (this.optimizeFloatMemory) { return gl.RGBA32F; } else { return gl.R32F; } case 'Array(2)': return gl.RG32F; case 'Array(3)': case 'Array(4)': return gl.RGBA32F; default: throw new Error('Unhandled return type'); } } return gl.RGBA32F; } return gl.RGBA; } _setupOutputTexture() { const gl = this.context; if (this.texture) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); return; } gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); const texture = gl.createTexture(); const texSize = this.texSize; gl.activeTexture(gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); const format = this.getInternalFormat(); if (this.precision === 'single') { gl.texStorage2D(gl.TEXTURE_2D, 1, format, texSize[0], texSize[1]); } else { gl.texImage2D(gl.TEXTURE_2D, 0, format, texSize[0], texSize[1], 0, format, gl.UNSIGNED_BYTE, null); } gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); this.texture = new this.TextureConstructor({ texture, size: texSize, dimensions: this.threadDim, output: this.output, context: this.context, internalFormat: this.getInternalFormat(), textureFormat: this.getTextureFormat(), kernel: this, }); } _setupSubOutputTextures() { const gl = this.context; if (this.mappedTextures) { for (let i = 0; i < this.subKernels.length; i++) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, this.mappedTextures[i].texture, 0); } return; } const texSize = this.texSize; this.drawBuffersMap = [gl.COLOR_ATTACHMENT0]; this.mappedTextures = []; for (let i = 0; i < this.subKernels.length; i++) { const texture = this.createTexture(); this.drawBuffersMap.push(gl.COLOR_ATTACHMENT0 + i + 1); gl.activeTexture(gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount + i); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); const format = this.getInternalFormat(); if (this.precision === 'single') { gl.texStorage2D(gl.TEXTURE_2D, 1, format, texSize[0], texSize[1]); } else { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize[0], texSize[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, texture, 0); this.mappedTextures.push(new this.TextureConstructor({ texture, size: texSize, dimensions: this.threadDim, output: this.output, context: this.context, internalFormat: this.getInternalFormat(), textureFormat: this.getTextureFormat(), kernel: this, })); } } _getHeaderString() { return ''; } _getTextureCoordinate() { const subKernels = this.subKernels; const variablePrecision = this.getVariablePrecisionString(this.texSize, this.tactic); if (subKernels === null || subKernels.length < 1) { return `in ${ variablePrecision } vec2 vTexCoord;\n`; } else { return `out ${ variablePrecision } vec2 vTexCoord;\n`; } } _getMainArgumentsString(args) { const result = []; const argumentNames = this.argumentNames; for (let i = 0; i < argumentNames.length; i++) { result.push(this.kernelArguments[i].getSource(args[i])); } return result.join(''); } getKernelString() { const result = [this.getKernelResultDeclaration()]; const subKernels = this.subKernels; if (subKernels !== null) { result.push( 'layout(location = 0) out vec4 data0' ); switch (this.returnType) { case 'Number': case 'Float': case 'Integer': for (let i = 0; i < subKernels.length; i++) { const subKernel = subKernels[i]; result.push( subKernel.returnType === 'Integer' ? `int subKernelResult_${ subKernel.name } = 0` : `float subKernelResult_${ subKernel.name } = 0.0`, `layout(location = ${ i + 1 }) out vec4 data${ i + 1 }` ); } break; case 'Array(2)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec2 subKernelResult_${ subKernels[i].name }`, `layout(location = ${ i + 1 }) out vec4 data${ i + 1 }` ); } break; case 'Array(3)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec3 subKernelResult_${ subKernels[i].name }`, `layout(location = ${ i + 1 }) out vec4 data${ i + 1 }` ); } break; case 'Array(4)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec4 subKernelResult_${ subKernels[i].name }`, `layout(location = ${ i + 1 }) out vec4 data${ i + 1 }` ); } break; } } else { result.push( 'out vec4 data0' ); } return utils.linesToString(result) + this.translatedSource; } getMainResultGraphical() { return utils.linesToString([ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' data0 = actualColor', ]); } getMainResultPackedPixels() { switch (this.returnType) { case 'LiteralInteger': case 'Number': case 'Integer': case 'Float': return this.getMainResultKernelPackedPixels() + this.getMainResultSubKernelPackedPixels(); default: throw new Error(`packed output only usable with Numbers, "${this.returnType}" specified`); } } getMainResultKernelPackedPixels() { return utils.linesToString([ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ` data0 = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(kernelResult)` ]); } getMainResultSubKernelPackedPixels() { const result = []; if (!this.subKernels) return ''; for (let i = 0; i < this.subKernels.length; i++) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` data${i + 1} = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(float(subKernelResult_${this.subKernels[i].name}))` ); } else { result.push( ` data${i + 1} = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(subKernelResult_${this.subKernels[i].name})` ); } } return utils.linesToString(result); } getMainResultKernelMemoryOptimizedFloats(result, channel) { result.push( ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ` data0.${channel} = kernelResult` ); } getMainResultSubKernelMemoryOptimizedFloats(result, channel) { if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; i++) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` data${i + 1}.${channel} = float(subKernelResult_${subKernel.name})` ); } else { result.push( ` data${i + 1}.${channel} = subKernelResult_${subKernel.name}` ); } } } getMainResultKernelNumberTexture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' data0[0] = kernelResult', ]; } getMainResultSubKernelNumberTexture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` data${i + 1}[0] = float(subKernelResult_${subKernel.name})` ); } else { result.push( ` data${i + 1}[0] = subKernelResult_${subKernel.name}` ); } } return result; } getMainResultKernelArray2Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' data0[0] = kernelResult[0]', ' data0[1] = kernelResult[1]', ]; } getMainResultSubKernelArray2Texture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { const subKernel = this.subKernels[i]; result.push( ` data${i + 1}[0] = subKernelResult_${subKernel.name}[0]`, ` data${i + 1}[1] = subKernelResult_${subKernel.name}[1]` ); } return result; } getMainResultKernelArray3Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' data0[0] = kernelResult[0]', ' data0[1] = kernelResult[1]', ' data0[2] = kernelResult[2]', ]; } getMainResultSubKernelArray3Texture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { const subKernel = this.subKernels[i]; result.push( ` data${i + 1}[0] = subKernelResult_${subKernel.name}[0]`, ` data${i + 1}[1] = subKernelResult_${subKernel.name}[1]`, ` data${i + 1}[2] = subKernelResult_${subKernel.name}[2]` ); } return result; } getMainResultKernelArray4Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' data0 = kernelResult', ]; } getMainResultSubKernelArray4Texture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` data${i + 1} = subKernelResult_${this.subKernels[i].name}` ); } return result; } destroyExtensions() { this.extensions.EXT_color_buffer_float = null; this.extensions.OES_texture_float_linear = null; } toJSON() { const json = super.toJSON(); json.functionNodes = FunctionBuilder.fromKernel(this, WebGL2FunctionNode).toJSON(); json.settings.threadDim = this.threadDim; return json; } } module.exports = { WebGL2Kernel }; },{"../../utils":114,"../function-builder":9,"../web-gl/kernel":70,"./fragment-shader":72,"./function-node":73,"./kernel-value-maps":74,"./vertex-shader":106}],106:[function(require,module,exports){ const vertexShader = `#version 300 es __FLOAT_TACTIC_DECLARATION__; __INT_TACTIC_DECLARATION__; __SAMPLER_2D_TACTIC_DECLARATION__; in vec2 aPos; in vec2 aTexCoord; out vec2 vTexCoord; uniform vec2 ratio; void main(void) { gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1); vTexCoord = aTexCoord; }`; module.exports = { vertexShader }; },{}],107:[function(require,module,exports){ const lib = require('./index'); const GPU = lib.GPU; for (const p in lib) { if (!lib.hasOwnProperty(p)) continue; if (p === 'GPU') continue; GPU[p] = lib[p]; } if (typeof window !== 'undefined') { bindTo(window); } if (typeof self !== 'undefined') { bindTo(self); } function bindTo(target) { if (target.GPU) return; Object.defineProperty(target, 'GPU', { get() { return GPU; } }); } module.exports = lib; },{"./index":109}],108:[function(require,module,exports){ const { gpuMock } = require('gpu-mock.js'); const { utils } = require('./utils'); const { Kernel } = require('./backend/kernel'); const { CPUKernel } = require('./backend/cpu/kernel'); const { HeadlessGLKernel } = require('./backend/headless-gl/kernel'); const { WebGL2Kernel } = require('./backend/web-gl2/kernel'); const { WebGLKernel } = require('./backend/web-gl/kernel'); const { kernelRunShortcut } = require('./kernel-run-shortcut'); const kernelOrder = [HeadlessGLKernel, WebGL2Kernel, WebGLKernel]; const kernelTypes = ['gpu', 'cpu']; const internalKernels = { 'headlessgl': HeadlessGLKernel, 'webgl2': WebGL2Kernel, 'webgl': WebGLKernel, }; let validate = true; class GPU { static disableValidation() { validate = false; } static enableValidation() { validate = true; } static get isGPUSupported() { return kernelOrder.some(Kernel => Kernel.isSupported); } static get isKernelMapSupported() { return kernelOrder.some(Kernel => Kernel.isSupported && Kernel.features.kernelMap); } static get isOffscreenCanvasSupported() { return (typeof Worker !== 'undefined' && typeof OffscreenCanvas !== 'undefined') || typeof importScripts !== 'undefined'; } static get isWebGLSupported() { return WebGLKernel.isSupported; } static get isWebGL2Supported() { return WebGL2Kernel.isSupported; } static get isHeadlessGLSupported() { return HeadlessGLKernel.isSupported; } static get isCanvasSupported() { return typeof HTMLCanvasElement !== 'undefined'; } static get isGPUHTMLImageArraySupported() { return WebGL2Kernel.isSupported; } static get isSinglePrecisionSupported() { return kernelOrder.some(Kernel => Kernel.isSupported && Kernel.features.isFloatRead && Kernel.features.isTextureFloat); } constructor(settings) { settings = settings || {}; this.canvas = settings.canvas || null; this.context = settings.context || null; this.mode = settings.mode; this.Kernel = null; this.kernels = []; this.functions = []; this.nativeFunctions = []; this.injectedNative = null; if (this.mode === 'dev') return; this.chooseKernel(); if (settings.functions) { for (let i = 0; i < settings.functions.length; i++) { this.addFunction(settings.functions[i]); } } if (settings.nativeFunctions) { for (const p in settings.nativeFunctions) { if (!settings.nativeFunctions.hasOwnProperty(p)) continue; const s = settings.nativeFunctions[p]; const { name, source } = s; this.addNativeFunction(name, source, s); } } } chooseKernel() { if (this.Kernel) return; let Kernel = null; if (this.context) { for (let i = 0; i < kernelOrder.length; i++) { const ExternalKernel = kernelOrder[i]; if (ExternalKernel.isContextMatch(this.context)) { if (!ExternalKernel.isSupported) { throw new Error(`Kernel type ${ExternalKernel.name} not supported`); } Kernel = ExternalKernel; break; } } if (Kernel === null) { throw new Error('unknown Context'); } } else if (this.mode) { if (this.mode in internalKernels) { if (!validate || internalKernels[this.mode].isSupported) { Kernel = internalKernels[this.mode]; } } else if (this.mode === 'gpu') { for (let i = 0; i < kernelOrder.length; i++) { if (kernelOrder[i].isSupported) { Kernel = kernelOrder[i]; break; } } } else if (this.mode === 'cpu') { Kernel = CPUKernel; } if (!Kernel) { throw new Error(`A requested mode of "${this.mode}" and is not supported`); } } else { for (let i = 0; i < kernelOrder.length; i++) { if (kernelOrder[i].isSupported) { Kernel = kernelOrder[i]; break; } } if (!Kernel) { Kernel = CPUKernel; } } if (!this.mode) { this.mode = Kernel.mode; } this.Kernel = Kernel; } createKernel(source, settings) { if (typeof source === 'undefined') { throw new Error('Missing source parameter'); } if (typeof source !== 'object' && !utils.isFunction(source) && typeof source !== 'string') { throw new Error('source parameter not a function'); } const kernels = this.kernels; if (this.mode === 'dev') { const devKernel = gpuMock(source, upgradeDeprecatedCreateKernelSettings(settings)); kernels.push(devKernel); return devKernel; } source = typeof source === 'function' ? source.toString() : source; const switchableKernels = {}; const settingsCopy = upgradeDeprecatedCreateKernelSettings(settings) || {}; if (settings && typeof settings.argumentTypes === 'object') { settingsCopy.argumentTypes = Object.keys(settings.argumentTypes).map(argumentName => settings.argumentTypes[argumentName]); } function onRequestFallback(args) { console.warn('Falling back to CPU'); const fallbackKernel = new CPUKernel(source, { argumentTypes: kernelRun.argumentTypes, constantTypes: kernelRun.constantTypes, graphical: kernelRun.graphical, loopMaxIterations: kernelRun.loopMaxIterations, constants: kernelRun.constants, dynamicOutput: kernelRun.dynamicOutput, dynamicArgument: kernelRun.dynamicArguments, output: kernelRun.output, precision: kernelRun.precision, pipeline: kernelRun.pipeline, immutable: kernelRun.immutable, optimizeFloatMemory: kernelRun.optimizeFloatMemory, fixIntegerDivisionAccuracy: kernelRun.fixIntegerDivisionAccuracy, functions: kernelRun.functions, nativeFunctions: kernelRun.nativeFunctions, injectedNative: kernelRun.injectedNative, subKernels: kernelRun.subKernels, strictIntegers: kernelRun.strictIntegers, debug: kernelRun.debug, }); fallbackKernel.build.apply(fallbackKernel, args); const result = fallbackKernel.run.apply(fallbackKernel, args); kernelRun.replaceKernel(fallbackKernel); return result; } function onRequestSwitchKernel(reasons, args, _kernel) { if (_kernel.debug) { console.warn('Switching kernels'); } let newOutput = null; if (_kernel.signature && !switchableKernels[_kernel.signature]) { switchableKernels[_kernel.signature] = _kernel; } if (_kernel.dynamicOutput) { for (let i = reasons.length - 1; i >= 0; i--) { const reason = reasons[i]; if (reason.type === 'outputPrecisionMismatch') { newOutput = reason.needed; } } } const Constructor = _kernel.constructor; const argumentTypes = Constructor.getArgumentTypes(_kernel, args); const signature = Constructor.getSignature(_kernel, argumentTypes); const existingKernel = switchableKernels[signature]; if (existingKernel) { existingKernel.onActivate(_kernel); return existingKernel; } const newKernel = switchableKernels[signature] = new Constructor(source, { argumentTypes, constantTypes: _kernel.constantTypes, graphical: _kernel.graphical, loopMaxIterations: _kernel.loopMaxIterations, constants: _kernel.constants, dynamicOutput: _kernel.dynamicOutput, dynamicArgument: _kernel.dynamicArguments, context: _kernel.context, canvas: _kernel.canvas, output: newOutput || _kernel.output, precision: _kernel.precision, pipeline: _kernel.pipeline, immutable: _kernel.immutable, optimizeFloatMemory: _kernel.optimizeFloatMemory, fixIntegerDivisionAccuracy: _kernel.fixIntegerDivisionAccuracy, functions: _kernel.functions, nativeFunctions: _kernel.nativeFunctions, injectedNative: _kernel.injectedNative, subKernels: _kernel.subKernels, strictIntegers: _kernel.strictIntegers, debug: _kernel.debug, gpu: _kernel.gpu, validate, returnType: _kernel.returnType, tactic: _kernel.tactic, onRequestFallback, onRequestSwitchKernel, texture: _kernel.texture, mappedTextures: _kernel.mappedTextures, drawBuffersMap: _kernel.drawBuffersMap, }); newKernel.build.apply(newKernel, args); kernelRun.replaceKernel(newKernel); kernels.push(newKernel); return newKernel; } const mergedSettings = Object.assign({ context: this.context, canvas: this.canvas, functions: this.functions, nativeFunctions: this.nativeFunctions, injectedNative: this.injectedNative, gpu: this, validate, onRequestFallback, onRequestSwitchKernel }, settingsCopy); const kernel = new this.Kernel(source, mergedSettings); const kernelRun = kernelRunShortcut(kernel); if (!this.canvas) { this.canvas = kernel.canvas; } if (!this.context) { this.context = kernel.context; } kernels.push(kernel); return kernelRun; } createKernelMap() { let fn; let settings; const argument2Type = typeof arguments[arguments.length - 2]; if (argument2Type === 'function' || argument2Type === 'string') { fn = arguments[arguments.length - 2]; settings = arguments[arguments.length - 1]; } else { fn = arguments[arguments.length - 1]; } if (this.mode !== 'dev') { if (!this.Kernel.isSupported || !this.Kernel.features.kernelMap) { if (this.mode && kernelTypes.indexOf(this.mode) < 0) { throw new Error(`kernelMap not supported on ${this.Kernel.name}`); } } } const settingsCopy = upgradeDeprecatedCreateKernelSettings(settings); if (settings && typeof settings.argumentTypes === 'object') { settingsCopy.argumentTypes = Object.keys(settings.argumentTypes).map(argumentName => settings.argumentTypes[argumentName]); } if (Array.isArray(arguments[0])) { settingsCopy.subKernels = []; const functions = arguments[0]; for (let i = 0; i < functions.length; i++) { const source = functions[i].toString(); const name = utils.getFunctionNameFromString(source); settingsCopy.subKernels.push({ name, source, property: i, }); } } else { settingsCopy.subKernels = []; const functions = arguments[0]; for (let p in functions) { if (!functions.hasOwnProperty(p)) continue; const source = functions[p].toString(); const name = utils.getFunctionNameFromString(source); settingsCopy.subKernels.push({ name: name || p, source, property: p, }); } } return this.createKernel(fn, settingsCopy); } combineKernels() { const firstKernel = arguments[0]; const combinedKernel = arguments[arguments.length - 1]; if (firstKernel.kernel.constructor.mode === 'cpu') return combinedKernel; const canvas = arguments[0].canvas; const context = arguments[0].context; const max = arguments.length - 1; for (let i = 0; i < max; i++) { arguments[i] .setCanvas(canvas) .setContext(context) .setPipeline(true); } return function() { const texture = combinedKernel.apply(this, arguments); if (texture.toArray) { return texture.toArray(); } return texture; }; } setFunctions(functions) { this.functions = functions; return this; } setNativeFunctions(nativeFunctions) { this.nativeFunctions = nativeFunctions; return this; } addFunction(source, settings) { this.functions.push({ source, settings }); return this; } addNativeFunction(name, source, settings) { if (this.kernels.length > 0) { throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.'); } this.nativeFunctions.push(Object.assign({ name, source }, settings)); return this; } injectNative(source) { this.injectedNative = source; return this; } destroy() { return new Promise((resolve, reject) => { if (!this.kernels) { resolve(); } setTimeout(() => { try { for (let i = 0; i < this.kernels.length; i++) { this.kernels[i].destroy(true); } let firstKernel = this.kernels[0]; if (firstKernel) { if (firstKernel.kernel) { firstKernel = firstKernel.kernel; } if (firstKernel.constructor.destroyContext) { firstKernel.constructor.destroyContext(this.context); } } } catch (e) { reject(e); } resolve(); }, 0); }); } } function upgradeDeprecatedCreateKernelSettings(settings) { if (!settings) { return {}; } const upgradedSettings = Object.assign({}, settings); if (settings.hasOwnProperty('floatOutput')) { utils.warnDeprecated('setting', 'floatOutput', 'precision'); upgradedSettings.precision = settings.floatOutput ? 'single' : 'unsigned'; } if (settings.hasOwnProperty('outputToTexture')) { utils.warnDeprecated('setting', 'outputToTexture', 'pipeline'); upgradedSettings.pipeline = Boolean(settings.outputToTexture); } if (settings.hasOwnProperty('outputImmutable')) { utils.warnDeprecated('setting', 'outputImmutable', 'immutable'); upgradedSettings.immutable = Boolean(settings.outputImmutable); } if (settings.hasOwnProperty('floatTextures')) { utils.warnDeprecated('setting', 'floatTextures', 'optimizeFloatMemory'); upgradedSettings.optimizeFloatMemory = Boolean(settings.floatTextures); } return upgradedSettings; } module.exports = { GPU, kernelOrder, kernelTypes }; },{"./backend/cpu/kernel":8,"./backend/headless-gl/kernel":34,"./backend/kernel":36,"./backend/web-gl/kernel":70,"./backend/web-gl2/kernel":105,"./kernel-run-shortcut":111,"./utils":114,"gpu-mock.js":4}],109:[function(require,module,exports){ const { GPU } = require('./gpu'); const { alias } = require('./alias'); const { utils } = require('./utils'); const { Input, input } = require('./input'); const { Texture } = require('./texture'); const { FunctionBuilder } = require('./backend/function-builder'); const { FunctionNode } = require('./backend/function-node'); const { CPUFunctionNode } = require('./backend/cpu/function-node'); const { CPUKernel } = require('./backend/cpu/kernel'); const { HeadlessGLKernel } = require('./backend/headless-gl/kernel'); const { WebGLFunctionNode } = require('./backend/web-gl/function-node'); const { WebGLKernel } = require('./backend/web-gl/kernel'); const { kernelValueMaps: webGLKernelValueMaps } = require('./backend/web-gl/kernel-value-maps'); const { WebGL2FunctionNode } = require('./backend/web-gl2/function-node'); const { WebGL2Kernel } = require('./backend/web-gl2/kernel'); const { kernelValueMaps: webGL2KernelValueMaps } = require('./backend/web-gl2/kernel-value-maps'); const { GLKernel } = require('./backend/gl/kernel'); const { Kernel } = require('./backend/kernel'); const { FunctionTracer } = require('./backend/function-tracer'); const mathRandom = require('./plugins/math-random-uniformly-distributed'); module.exports = { alias, CPUFunctionNode, CPUKernel, GPU, FunctionBuilder, FunctionNode, HeadlessGLKernel, Input, input, Texture, utils, WebGL2FunctionNode, WebGL2Kernel, webGL2KernelValueMaps, WebGLFunctionNode, WebGLKernel, webGLKernelValueMaps, GLKernel, Kernel, FunctionTracer, plugins: { mathRandom } }; },{"./alias":5,"./backend/cpu/function-node":6,"./backend/cpu/kernel":8,"./backend/function-builder":9,"./backend/function-node":10,"./backend/function-tracer":11,"./backend/gl/kernel":13,"./backend/headless-gl/kernel":34,"./backend/kernel":36,"./backend/web-gl/function-node":38,"./backend/web-gl/kernel":70,"./backend/web-gl/kernel-value-maps":39,"./backend/web-gl2/function-node":73,"./backend/web-gl2/kernel":105,"./backend/web-gl2/kernel-value-maps":74,"./gpu":108,"./input":110,"./plugins/math-random-uniformly-distributed":112,"./texture":113,"./utils":114}],110:[function(require,module,exports){ class Input { constructor(value, size) { this.value = value; if (Array.isArray(size)) { this.size = size; } else { this.size = new Int32Array(3); if (size.z) { this.size = new Int32Array([size.x, size.y, size.z]); } else if (size.y) { this.size = new Int32Array([size.x, size.y]); } else { this.size = new Int32Array([size.x]); } } const [w, h, d] = this.size; if (d) { if (this.value.length !== (w * h * d)) { throw new Error(`Input size ${this.value.length} does not match ${w} * ${h} * ${d} = ${(h * w * d)}`); } } else if (h) { if (this.value.length !== (w * h)) { throw new Error(`Input size ${this.value.length} does not match ${w} * ${h} = ${(h * w)}`); } } else { if (this.value.length !== w) { throw new Error(`Input size ${this.value.length} does not match ${w}`); } } } toArray() { const { utils } = require('./utils'); const [w, h, d] = this.size; if (d) { return utils.erectMemoryOptimized3DFloat(this.value.subarray ? this.value : new Float32Array(this.value), w, h, d); } else if (h) { return utils.erectMemoryOptimized2DFloat(this.value.subarray ? this.value : new Float32Array(this.value), w, h); } else { return this.value; } } } function input(value, size) { return new Input(value, size); } module.exports = { Input, input }; },{"./utils":114}],111:[function(require,module,exports){ const { utils } = require('./utils'); function kernelRunShortcut(kernel) { let run = function() { kernel.build.apply(kernel, arguments); run = function() { let result = kernel.run.apply(kernel, arguments); if (kernel.switchingKernels) { const reasons = kernel.resetSwitchingKernels(); const newKernel = kernel.onRequestSwitchKernel(reasons, arguments, kernel); shortcut.kernel = kernel = newKernel; result = newKernel.run.apply(newKernel, arguments); } if (kernel.renderKernels) { return kernel.renderKernels(); } else if (kernel.renderOutput) { return kernel.renderOutput(); } else { return result; } }; return run.apply(kernel, arguments); }; const shortcut = function() { return run.apply(kernel, arguments); }; shortcut.exec = function() { return new Promise((accept, reject) => { try { accept(run.apply(this, arguments)); } catch (e) { reject(e); } }); }; shortcut.replaceKernel = function(replacementKernel) { kernel = replacementKernel; bindKernelToShortcut(kernel, shortcut); }; bindKernelToShortcut(kernel, shortcut); return shortcut; } function bindKernelToShortcut(kernel, shortcut) { if (shortcut.kernel) { shortcut.kernel = kernel; return; } const properties = utils.allPropertiesOf(kernel); for (let i = 0; i < properties.length; i++) { const property = properties[i]; if (property[0] === '_' && property[1] === '_') continue; if (typeof kernel[property] === 'function') { if (property.substring(0, 3) === 'add' || property.substring(0, 3) === 'set') { shortcut[property] = function() { shortcut.kernel[property].apply(shortcut.kernel, arguments); return shortcut; }; } else { shortcut[property] = function() { return shortcut.kernel[property].apply(shortcut.kernel, arguments); }; } } else { shortcut.__defineGetter__(property, () => shortcut.kernel[property]); shortcut.__defineSetter__(property, (value) => { shortcut.kernel[property] = value; }); } } shortcut.kernel = kernel; } module.exports = { kernelRunShortcut }; },{"./utils":114}],112:[function(require,module,exports){ const source = `// https://www.shadertoy.com/view/4t2SDh //note: uniformly distributed, normalized rand, [0,1] highp float randomSeedShift = 1.0; highp float slide = 1.0; uniform highp float randomSeed1; uniform highp float randomSeed2; highp float nrand(highp vec2 n) { highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453); randomSeedShift = result; if (randomSeedShift > 0.5) { slide += 0.00009; } else { slide += 0.0009; } return result; }`; const name = 'math-random-uniformly-distributed'; const functionMatch = `Math.random()`; const functionReplace = `nrand(vTexCoord)`; const functionReturnType = 'Number'; const onBeforeRun = (kernel) => { kernel.setUniform1f('randomSeed1', Math.random()); kernel.setUniform1f('randomSeed2', Math.random()); }; const plugin = { name, onBeforeRun, functionMatch, functionReplace, functionReturnType, source }; module.exports = plugin; },{}],113:[function(require,module,exports){ class Texture { constructor(settings) { const { texture, size, dimensions, output, context, type = 'NumberTexture', kernel, internalFormat, textureFormat } = settings; if (!output) throw new Error('settings property "output" required.'); if (!context) throw new Error('settings property "context" required.'); if (!texture) throw new Error('settings property "texture" required.'); if (!kernel) throw new Error('settings property "kernel" required.'); this.texture = texture; if (texture._refs) { texture._refs++; } else { texture._refs = 1; } this.size = size; this.dimensions = dimensions; this.output = output; this.context = context; this.kernel = kernel; this.type = type; this._deleted = false; this.internalFormat = internalFormat; this.textureFormat = textureFormat; } toArray() { throw new Error(`Not implemented on ${this.constructor.name}`); } clone() { throw new Error(`Not implemented on ${this.constructor.name}`); } delete() { throw new Error(`Not implemented on ${this.constructor.name}`); } clear() { throw new Error(`Not implemented on ${this.constructor.name}`); } } module.exports = { Texture }; },{}],114:[function(require,module,exports){ const acorn = require('acorn'); const { Input } = require('./input'); const { Texture } = require('./texture'); const FUNCTION_NAME = /function ([^(]*)/; const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; const ARGUMENT_NAMES = /([^\s,]+)/g; const utils = { systemEndianness() { return _systemEndianness; }, getSystemEndianness() { const b = new ArrayBuffer(4); const a = new Uint32Array(b); const c = new Uint8Array(b); a[0] = 0xdeadbeef; if (c[0] === 0xef) return 'LE'; if (c[0] === 0xde) return 'BE'; throw new Error('unknown endianness'); }, isFunction(funcObj) { return typeof(funcObj) === 'function'; }, isFunctionString(fn) { if (typeof fn === 'string') { return (fn .slice(0, 'function'.length) .toLowerCase() === 'function'); } return false; }, getFunctionNameFromString(funcStr) { const result = FUNCTION_NAME.exec(funcStr); if (!result || result.length === 0) return null; return result[1].trim(); }, getFunctionBodyFromString(funcStr) { return funcStr.substring(funcStr.indexOf('{') + 1, funcStr.lastIndexOf('}')); }, getArgumentNamesFromString(fn) { const fnStr = fn.replace(STRIP_COMMENTS, ''); let result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES); if (result === null) { result = []; } return result; }, clone(obj) { if (obj === null || typeof obj !== 'object' || obj.hasOwnProperty('isActiveClone')) return obj; const temp = obj.constructor(); for (let key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { obj.isActiveClone = null; temp[key] = utils.clone(obj[key]); delete obj.isActiveClone; } } return temp; }, isArray(array) { return !isNaN(array.length); }, getVariableType(value, strictIntegers) { if (utils.isArray(value)) { if (value.length > 0 && value[0].nodeName === 'IMG') { return 'HTMLImageArray'; } return 'Array'; } switch (value.constructor) { case Boolean: return 'Boolean'; case Number: if (strictIntegers && Number.isInteger(value)) { return 'Integer'; } return 'Float'; case Texture: return value.type; case Input: return 'Input'; } if ('nodeName' in value) { switch (value.nodeName) { case 'IMG': return 'HTMLImage'; case 'CANVAS': return 'HTMLImage'; case 'VIDEO': return 'HTMLVideo'; } } else if (value.hasOwnProperty('type')) { return value.type; } else if (typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas) { return 'OffscreenCanvas'; } else if (typeof ImageBitmap !== 'undefined' && value instanceof ImageBitmap) { return 'ImageBitmap'; } else if (typeof ImageData !== 'undefined' && value instanceof ImageData) { return 'ImageData'; } return 'Unknown'; }, getKernelTextureSize(settings, dimensions) { let [w, h, d] = dimensions; let texelCount = (w || 1) * (h || 1) * (d || 1); if (settings.optimizeFloatMemory && settings.precision === 'single') { w = texelCount = Math.ceil(texelCount / 4); } if (h > 1 && w * h === texelCount) { return new Int32Array([w, h]); } return utils.closestSquareDimensions(texelCount); }, closestSquareDimensions(length) { const sqrt = Math.sqrt(length); let high = Math.ceil(sqrt); let low = Math.floor(sqrt); while (high * low < length) { high--; low = Math.ceil(length / high); } return new Int32Array([low, Math.ceil(length / low)]); }, getMemoryOptimizedFloatTextureSize(dimensions, bitRatio) { const totalArea = utils.roundTo((dimensions[0] || 1) * (dimensions[1] || 1) * (dimensions[2] || 1) * (dimensions[3] || 1), 4); const texelCount = totalArea / bitRatio; return utils.closestSquareDimensions(texelCount); }, getMemoryOptimizedPackedTextureSize(dimensions, bitRatio) { const [w, h, d] = dimensions; const totalArea = utils.roundTo((w || 1) * (h || 1) * (d || 1), 4); const texelCount = totalArea / (4 / bitRatio); return utils.closestSquareDimensions(texelCount); }, roundTo(n, d) { return Math.floor((n + d - 1) / d) * d; }, getDimensions(x, pad) { let ret; if (utils.isArray(x)) { const dim = []; let temp = x; while (utils.isArray(temp)) { dim.push(temp.length); temp = temp[0]; } ret = dim.reverse(); } else if (x instanceof Texture) { ret = x.output; } else if (x instanceof Input) { ret = x.size; } else { throw new Error(`Unknown dimensions of ${x}`); } if (pad) { ret = Array.from(ret); while (ret.length < 3) { ret.push(1); } } return new Int32Array(ret); }, flatten2dArrayTo(array, target) { let offset = 0; for (let y = 0; y < array.length; y++) { target.set(array[y], offset); offset += array[y].length; } }, flatten3dArrayTo(array, target) { let offset = 0; for (let z = 0; z < array.length; z++) { for (let y = 0; y < array[z].length; y++) { target.set(array[z][y], offset); offset += array[z][y].length; } } }, flatten4dArrayTo(array, target) { let offset = 0; for (let l = 0; l < array.length; l++) { for (let z = 0; z < array[l].length; z++) { for (let y = 0; y < array[l][z].length; y++) { target.set(array[l][z][y], offset); offset += array[l][z][y].length; } } } }, flattenTo(array, target) { if (utils.isArray(array[0])) { if (utils.isArray(array[0][0])) { if (utils.isArray(array[0][0][0])) { utils.flatten4dArrayTo(array, target); } else { utils.flatten3dArrayTo(array, target); } } else { utils.flatten2dArrayTo(array, target); } } else { target.set(array); } }, splitArray(array, part) { const result = []; for (let i = 0; i < array.length; i += part) { result.push(new array.constructor(array.buffer, i * 4 + array.byteOffset, part)); } return result; }, getAstString(source, ast) { const lines = Array.isArray(source) ? source : source.split(/\r?\n/g); const start = ast.loc.start; const end = ast.loc.end; const result = []; if (start.line === end.line) { result.push(lines[start.line - 1].substring(start.column, end.column)); } else { result.push(lines[start.line - 1].slice(start.column)); for (let i = start.line; i < end.line; i++) { result.push(lines[i]); } result.push(lines[end.line - 1].slice(0, end.column)); } return result.join('\n'); }, allPropertiesOf(obj) { const props = []; do { props.push.apply(props, Object.getOwnPropertyNames(obj)); } while (obj = Object.getPrototypeOf(obj)); return props; }, linesToString(lines) { if (lines.length > 0) { return lines.join(';\n') + ';\n'; } else { return '\n'; } }, warnDeprecated(type, oldName, newName) { if (newName) { console.warn(`You are using a deprecated ${ type } "${ oldName }". It has been replaced with "${ newName }". Fixing, but please upgrade as it will soon be removed.`); } else { console.warn(`You are using a deprecated ${ type } "${ oldName }". It has been removed. Fixing, but please upgrade as it will soon be removed.`); } }, flipPixels: (pixels, width, height) => { const halfHeight = height / 2 | 0; const bytesPerRow = width * 4; const temp = new Uint8ClampedArray(width * 4); const result = pixels.slice(0); for (let y = 0; y < halfHeight; ++y) { const topOffset = y * bytesPerRow; const bottomOffset = (height - y - 1) * bytesPerRow; temp.set(result.subarray(topOffset, topOffset + bytesPerRow)); result.copyWithin(topOffset, bottomOffset, bottomOffset + bytesPerRow); result.set(temp, bottomOffset); } return result; }, erectPackedFloat: (array, width) => { return array.subarray(0, width); }, erect2DPackedFloat: (array, width, height) => { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xStart = y * width; const xEnd = xStart + width; yResults[y] = array.subarray(xStart, xEnd); } return yResults; }, erect3DPackedFloat: (array, width, height, depth) => { const zResults = new Array(depth); for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xStart = (z * height * width) + y * width; const xEnd = xStart + width; yResults[y] = array.subarray(xStart, xEnd); } zResults[z] = yResults; } return zResults; }, erectMemoryOptimizedFloat: (array, width) => { return array.subarray(0, width); }, erectMemoryOptimized2DFloat: (array, width, height) => { const yResults = new Array(height); for (let y = 0; y < height; y++) { const offset = y * width; yResults[y] = array.subarray(offset, offset + width); } return yResults; }, erectMemoryOptimized3DFloat: (array, width, height, depth) => { const zResults = new Array(depth); for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const offset = (z * height * width) + (y * width); yResults[y] = array.subarray(offset, offset + width); } zResults[z] = yResults; } return zResults; }, erectFloat: (array, width) => { const xResults = new Float32Array(width); let i = 0; for (let x = 0; x < width; x++) { xResults[x] = array[i]; i += 4; } return xResults; }, erect2DFloat: (array, width, height) => { const yResults = new Array(height); let i = 0; for (let y = 0; y < height; y++) { const xResults = new Float32Array(width); for (let x = 0; x < width; x++) { xResults[x] = array[i]; i += 4; } yResults[y] = xResults; } return yResults; }, erect3DFloat: (array, width, height, depth) => { const zResults = new Array(depth); let i = 0; for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Float32Array(width); for (let x = 0; x < width; x++) { xResults[x] = array[i]; i += 4; } yResults[y] = xResults; } zResults[z] = yResults; } return zResults; }, erectArray2: (array, width) => { const xResults = new Array(width); const xResultsMax = width * 4; let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x, x + 2); } return xResults; }, erect2DArray2: (array, width, height) => { const yResults = new Array(height); const XResultsMax = width * 4; for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = y * XResultsMax; let i = 0; for (let x = 0; x < XResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 2); } yResults[y] = xResults; } return yResults; }, erect3DArray2: (array, width, height, depth) => { const xResultsMax = width * 4; const zResults = new Array(depth); for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = (z * xResultsMax * height) + (y * xResultsMax); let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 2); } yResults[y] = xResults; } zResults[z] = yResults; } return zResults; }, erectArray3: (array, width) => { const xResults = new Array(width); const xResultsMax = width * 4; let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x, x + 3); } return xResults; }, erect2DArray3: (array, width, height) => { const xResultsMax = width * 4; const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = y * xResultsMax; let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 3); } yResults[y] = xResults; } return yResults; }, erect3DArray3: (array, width, height, depth) => { const xResultsMax = width * 4; const zResults = new Array(depth); for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = (z * xResultsMax * height) + (y * xResultsMax); let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 3); } yResults[y] = xResults; } zResults[z] = yResults; } return zResults; }, erectArray4: (array, width) => { const xResults = new Array(array); const xResultsMax = width * 4; let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x, x + 4); } return xResults; }, erect2DArray4: (array, width, height) => { const xResultsMax = width * 4; const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = y * xResultsMax; let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 4); } yResults[y] = xResults; } return yResults; }, erect3DArray4: (array, width, height, depth) => { const xResultsMax = width * 4; const zResults = new Array(depth); for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = (z * xResultsMax * height) + (y * xResultsMax); let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 4); } yResults[y] = xResults; } zResults[z] = yResults; } return zResults; }, flattenFunctionToString: (source, settings) => { const { findDependency, thisLookup, doNotDefine } = settings; let flattened = settings.flattened; if (!flattened) { flattened = settings.flattened = {}; } const ast = acorn.parse(source); const functionDependencies = []; let indent = 0; function flatten(ast) { if (Array.isArray(ast)) { const results = []; for (let i = 0; i < ast.length; i++) { results.push(flatten(ast[i])); } return results.join(''); } switch (ast.type) { case 'Program': return flatten(ast.body) + (ast.body[0].type === 'VariableDeclaration' ? ';' : ''); case 'FunctionDeclaration': return `function ${ast.id.name}(${ast.params.map(flatten).join(', ')}) ${ flatten(ast.body) }`; case 'BlockStatement': { const result = []; indent += 2; for (let i = 0; i < ast.body.length; i++) { const flat = flatten(ast.body[i]); if (flat) { result.push(' '.repeat(indent) + flat, ';\n'); } } indent -= 2; return `{\n${result.join('')}}`; } case 'VariableDeclaration': const declarations = utils.normalizeDeclarations(ast) .map(flatten) .filter(r => r !== null); if (declarations.length < 1) { return ''; } else { return `${ast.kind} ${declarations.join(',')}`; } case 'VariableDeclarator': if (ast.init.object && ast.init.object.type === 'ThisExpression') { const lookup = thisLookup(ast.init.property.name, true); if (lookup) { return `${ast.id.name} = ${flatten(ast.init)}`; } else { return null; } } else { return `${ast.id.name} = ${flatten(ast.init)}`; } case 'CallExpression': { if (ast.callee.property.name === 'subarray') { return `${flatten(ast.callee.object)}.${flatten(ast.callee.property)}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } if (ast.callee.object.name === 'gl' || ast.callee.object.name === 'context') { return `${flatten(ast.callee.object)}.${flatten(ast.callee.property)}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } if (ast.callee.object.type === 'ThisExpression') { functionDependencies.push(findDependency('this', ast.callee.property.name)); return `${ast.callee.property.name}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } else if (ast.callee.object.name) { const foundSource = findDependency(ast.callee.object.name, ast.callee.property.name); if (foundSource === null) { return `${ast.callee.object.name}.${ast.callee.property.name}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } else { functionDependencies.push(foundSource); return `${ast.callee.property.name}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } } else if (ast.callee.object.type === 'MemberExpression') { return `${flatten(ast.callee.object)}.${ast.callee.property.name}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } else { throw new Error('unknown ast.callee'); } } case 'ReturnStatement': return `return ${flatten(ast.argument)}`; case 'BinaryExpression': return `(${flatten(ast.left)}${ast.operator}${flatten(ast.right)})`; case 'UnaryExpression': if (ast.prefix) { return `${ast.operator} ${flatten(ast.argument)}`; } else { return `${flatten(ast.argument)} ${ast.operator}`; } case 'ExpressionStatement': return `${flatten(ast.expression)}`; case 'SequenceExpression': return `(${flatten(ast.expressions)})`; case 'ArrowFunctionExpression': return `(${ast.params.map(flatten).join(', ')}) => ${flatten(ast.body)}`; case 'Literal': return ast.raw; case 'Identifier': return ast.name; case 'MemberExpression': if (ast.object.type === 'ThisExpression') { return thisLookup(ast.property.name); } if (ast.computed) { return `${flatten(ast.object)}[${flatten(ast.property)}]`; } return flatten(ast.object) + '.' + flatten(ast.property); case 'ThisExpression': return 'this'; case 'NewExpression': return `new ${flatten(ast.callee)}(${ast.arguments.map(value => flatten(value)).join(', ')})`; case 'ForStatement': return `for (${flatten(ast.init)};${flatten(ast.test)};${flatten(ast.update)}) ${flatten(ast.body)}`; case 'AssignmentExpression': return `${flatten(ast.left)}${ast.operator}${flatten(ast.right)}`; case 'UpdateExpression': return `${flatten(ast.argument)}${ast.operator}`; case 'IfStatement': return `if (${flatten(ast.test)}) ${flatten(ast.consequent)}`; case 'ThrowStatement': return `throw ${flatten(ast.argument)}`; case 'ObjectPattern': return ast.properties.map(flatten).join(', '); case 'ArrayPattern': return ast.elements.map(flatten).join(', '); case 'DebuggerStatement': return 'debugger;'; case 'ConditionalExpression': return `${flatten(ast.test)}?${flatten(ast.consequent)}:${flatten(ast.alternate)}`; case 'Property': if (ast.kind === 'init') { return flatten(ast.key); } } throw new Error(`unhandled ast.type of ${ ast.type }`); } const result = flatten(ast); if (functionDependencies.length > 0) { const flattenedFunctionDependencies = []; for (let i = 0; i < functionDependencies.length; i++) { const functionDependency = functionDependencies[i]; if (!flattened[functionDependency]) { flattened[functionDependency] = true; } functionDependency ? flattenedFunctionDependencies.push(utils.flattenFunctionToString(functionDependency, settings) + '\n') : ''; } return flattenedFunctionDependencies.join('') + result; } return result; }, normalizeDeclarations: (ast) => { if (ast.type !== 'VariableDeclaration') throw new Error('Ast is not of type "VariableDeclaration"'); const normalizedDeclarations = []; for (let declarationIndex = 0; declarationIndex < ast.declarations.length; declarationIndex++) { const declaration = ast.declarations[declarationIndex]; if (declaration.id && declaration.id.type === 'ObjectPattern' && declaration.id.properties) { const { properties } = declaration.id; for (let propertyIndex = 0; propertyIndex < properties.length; propertyIndex++) { const property = properties[propertyIndex]; if (property.value.type === 'ObjectPattern' && property.value.properties) { for (let subPropertyIndex = 0; subPropertyIndex < property.value.properties.length; subPropertyIndex++) { const subProperty = property.value.properties[subPropertyIndex]; if (subProperty.type === 'Property') { normalizedDeclarations.push({ type: 'VariableDeclarator', id: { type: 'Identifier', name: subProperty.key.name }, init: { type: 'MemberExpression', object: { type: 'MemberExpression', object: declaration.init, property: { type: 'Identifier', name: property.key.name }, computed: false }, property: { type: 'Identifier', name: subProperty.key.name }, computed: false } }); } else { throw new Error('unexpected state'); } } } else if (property.value.type === 'Identifier') { normalizedDeclarations.push({ type: 'VariableDeclarator', id: { type: 'Identifier', name: property.value && property.value.name ? property.value.name : property.key.name }, init: { type: 'MemberExpression', object: declaration.init, property: { type: 'Identifier', name: property.key.name }, computed: false } }); } else { throw new Error('unexpected state'); } } } else if (declaration.id && declaration.id.type === 'ArrayPattern' && declaration.id.elements) { const { elements } = declaration.id; for (let elementIndex = 0; elementIndex < elements.length; elementIndex++) { const element = elements[elementIndex]; if (element.type === 'Identifier') { normalizedDeclarations.push({ type: 'VariableDeclarator', id: { type: 'Identifier', name: element.name }, init: { type: 'MemberExpression', object: declaration.init, property: { type: 'Literal', value: elementIndex, raw: elementIndex.toString(), start: element.start, end: element.end }, computed: true } }); } else { throw new Error('unexpected state'); } } } else { normalizedDeclarations.push(declaration); } } return normalizedDeclarations; }, splitHTMLImageToRGB: (gpu, image) => { const rKernel = gpu.createKernel(function(a) { const pixel = a[this.thread.y][this.thread.x]; return pixel.r * 255; }, { output: [image.width, image.height], precision: 'unsigned', argumentTypes: { a: 'HTMLImage' }, }); const gKernel = gpu.createKernel(function(a) { const pixel = a[this.thread.y][this.thread.x]; return pixel.g * 255; }, { output: [image.width, image.height], precision: 'unsigned', argumentTypes: { a: 'HTMLImage' }, }); const bKernel = gpu.createKernel(function(a) { const pixel = a[this.thread.y][this.thread.x]; return pixel.b * 255; }, { output: [image.width, image.height], precision: 'unsigned', argumentTypes: { a: 'HTMLImage' }, }); const aKernel = gpu.createKernel(function(a) { const pixel = a[this.thread.y][this.thread.x]; return pixel.a * 255; }, { output: [image.width, image.height], precision: 'unsigned', argumentTypes: { a: 'HTMLImage' }, }); const result = [ rKernel(image), gKernel(image), bKernel(image), aKernel(image), ]; result.rKernel = rKernel; result.gKernel = gKernel; result.bKernel = bKernel; result.aKernel = aKernel; result.gpu = gpu; return result; }, splitRGBAToCanvases: (gpu, rgba, width, height) => { const visualKernelR = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(pixel.r / 255, 0, 0, 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelR(rgba); const visualKernelG = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(0, pixel.g / 255, 0, 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelG(rgba); const visualKernelB = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(0, 0, pixel.b / 255, 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelB(rgba); const visualKernelA = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(255, 255, 255, pixel.a / 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelA(rgba); return [ visualKernelR.canvas, visualKernelG.canvas, visualKernelB.canvas, visualKernelA.canvas, ]; }, getMinifySafeName: (fn) => { try { const ast = acorn.parse(`const value = ${fn.toString()}`); const { init } = ast.body[0].declarations[0]; return init.body.name || init.body.body[0].argument.name; } catch (e) { throw new Error('Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }'); } }, sanitizeName: function(name) { if (dollarSign.test(name)) { name = name.replace(dollarSign, 'S_S'); } if (doubleUnderscore.test(name)) { name = name.replace(doubleUnderscore, 'U_U'); } else if (singleUnderscore.test(name)) { name = name.replace(singleUnderscore, 'u_u'); } return name; } }; const dollarSign = /\$/; const doubleUnderscore = /__/; const singleUnderscore = /_/; const _systemEndianness = utils.getSystemEndianness(); module.exports = { utils }; },{"./input":110,"./texture":113,"acorn":1}]},{},[107])(107) }); ================================================ FILE: examples/advanced-typescript.ts ================================================ /** * This is an arbitrary example (overly complex with types for overly simplified kernel) to show type inheritance * throughout the kernel's usage. * * The whole idea here is that you can define custom: * - `constants` * - `this` context * - mapped kernels * - arguments * - kernel output */ import { GPU, Texture, IKernelFunctionThis, IConstantsThis, KernelOutput, ISubKernelsResults } from '../src'; const gpu = new GPU(); interface IConstants extends IConstantsThis { rotation: number, } interface IThis extends IKernelFunctionThis { constants: IConstants, } function kernelFunction(this: IThis, degrees: number, divisors: [number, number]): [number, number] { const bounds = subKernel(this.constants.rotation * degrees); return [bounds[0] / divisors[0], bounds[1] / divisors[1]]; } function subKernel(value: number): [number, number] { return [-value, value]; } interface IKernelMapResult extends ISubKernelsResults { test: KernelOutput; } const kernelMap = gpu.createKernelMap>({ test: subKernel, }, kernelFunction) .setConstants({ rotation: 45, }) .setOutput([1]) .setPrecision('single') .setPipeline(true) .setImmutable(true); const { test, result } = kernelMap(360, [256, 512]); const testTexture = test as Texture; const resultTexture = result as Texture; console.log(testTexture.toArray() as [number, number][]); console.log(resultTexture.toArray() as [number, number][]); testTexture.delete(); resultTexture.delete(); kernelMap.destroy(); ================================================ FILE: examples/cat-image/index.html ================================================ Cat image with GPU.js

Image to GPU.js from https://observablehq.com/@fil/image-to-gpu

================================================ FILE: examples/fluid.html ================================================ SSPS - Chadams Studios (slightly upgraded) ================================================ FILE: examples/internal-variable-precision.html ================================================ GPU.js Internal Variable Precision

GPU.js Internal variable precision:

================================================ FILE: examples/json-saving.js ================================================ const { GPU } = require('../src'); const gpu1 = new GPU(); const kernel1 = gpu1.createKernel(function(value) { return value * 100; }, { output: [1] }); const resultFromRegularKernel = kernel1(42); const json = kernel1.toJSON(); console.log(resultFromRegularKernel); // Use bin/gpu-browser-core.js to get "CORE" mode, which works only with JSON const gpu2 = new GPU(); const kernel2 = gpu2.createKernel(json); const resultFromJsonKernel = kernel2(42); console.log(resultFromJsonKernel); ================================================ FILE: examples/mandelbrot-set.html ================================================
Left click to zoom in, right click to zoom out.
================================================ FILE: examples/mandelbulb.html ================================================ Frakal

Mandelbulb - Real-time 3d fractal
in Javascript

Kamil Kiełczewski Airavana
Instruction
Click on picture and move mouse around
A S D W E C keys for change view poin position
Push ESC to stop move and unlock mouse
Calculate Light
Level of Details (and camera speed)
Mouse whell or +/- keys
================================================ FILE: examples/parallel-raytracer.html ================================================ GPU.js Raytracer

A parallel raytracer built with TypeScript and GPU.js (WebGL/GLSL).

GitHub: http://github.com/jin/raytracer

Press W, A, S, D to move the camera around.

Current mode

GPU

FPS

Loading..

Number of spheres

4

Grid dimension

2

The canvas is 640px by 640px. Each canvas object is controlled by a single GPU.js kernel and a single thread is spawned for each pixel to compute the color of the pixel.

Increase the dimensions of the grid to break the canvas up into tiles, so that there are multiple kernels controlling multiple tiles. With this approach, the kernels will run sequentially, computing one canvas after another.

Benchmark

Benchmark the performance of the parallelized GPU and sequential CPU kernels. This will render 30 frames each and compute min, max, median frame rendering durations, and speedups.

================================================ FILE: examples/random.html ================================================ GPU.js Random Examples

CPU Random

WebGL1 Random

WebGL2 Random

================================================ FILE: examples/raster-globe/index.html ================================================ Raster projection with GPU.js

Raster projection with GPU.js from https://observablehq.com/d/b70d084526a1a764

================================================ FILE: examples/raytracer.html ================================================ GPU.js Raytracer

From https://staceytay.com/raytracer/. A simple ray tracer with Lambertian and specular reflection, built with GPU.js. Read more about ray tracing and GPU.js in my blog post. Code available on GitHub.


fps
================================================ FILE: examples/simple-javascript.js ================================================ const { GPU } = require('../src'); const gpu = new GPU({ mode: 'gpu' }); // Look ma! I can javascript on my GPU! function kernelFunction(anInt, anArray, aNestedArray) { const x = .25 + anInt + anArray[this.thread.x] + aNestedArray[this.thread.x][this.thread.y]; return x; } const kernel = gpu.createKernel(kernelFunction, { output: [1] }); const result = kernel(1, [.25], [[1.5]]); console.log(result[0]); // 3 ================================================ FILE: examples/simple-typescript.ts ================================================ import { GPU, KernelFunction, IKernelRunShortcut } from '../src'; const gpu = new GPU({ mode: 'gpu' }); // Look ma! I can typescript on my GPU! const kernelFunction: KernelFunction = function(anInt: number, anArray: number[], aNestedArray: number[][]) { const x = .25 + anInt + anArray[this.thread.x] + aNestedArray[this.thread.x][this.thread.y]; return x; }; const kernel: IKernelRunShortcut = gpu.createKernel(kernelFunction) .setOutput([1]); const result = kernel(1, [.25], [[1.5]]); console.log(result[0]); // 3 ================================================ FILE: examples/slow-fade.html ================================================ Slow Fade

Slow Fade

================================================ FILE: examples/video/index.html ================================================ Video input with GPU.js

Video input (and output) with GPU.js





Video

GPU.js Graphical Output 0 fps

================================================ FILE: gulpfile.js ================================================ const fs = require('fs'); const gulp = require('gulp'); const rename = require('gulp-rename'); const header = require('gulp-header'); const browserSync = require('browser-sync'); const browserify = require('browserify'); const replace = require('gulp-replace'); const source = require('vinyl-source-stream'); const buffer = require('vinyl-buffer'); const path = require('path'); const uglify = require('gulp-uglify-es').default; const pkg = require('./package.json'); const jsprettify = require('gulp-jsbeautifier'); const stripComments = require('gulp-strip-comments'); const merge = require('ordered-read-streams'); const { readDirDeepSync } = require('read-dir-deep'); gulp.task('build', () => { const gpu = browserify('./src/browser.js', { standalone: 'GPU', browserField: false }) .ignore('gl') .bundle() .pipe(source('gpu-browser.js')) .pipe(buffer()) .pipe(stripComments()) .pipe(header(fs.readFileSync('./src/browser-header.txt', 'utf8'), { pkg : pkg })) .pipe(gulp.dest('./dist')) .on('error', console.error); const gpuCore = browserify('./src/browser.js', { standalone: 'GPU', browserField: false }) .ignore('gl') .ignore('acorn') .bundle() .pipe(source('gpu-browser-core.js')) .pipe(buffer()) .pipe(stripComments()) .pipe(header(fs.readFileSync('./src/browser-header.txt', 'utf8'), { pkg : pkg })) .pipe(gulp.dest('./dist')) .on('error', console.error); return merge(gpu, gpuCore); }); /// Minify the build script, after building it gulp.task('minify', () => { const gpu = gulp.src('dist/gpu-browser.js') .pipe(uglify()) .pipe(rename('gpu-browser.min.js')) .pipe(header(fs.readFileSync('./src/browser-header.txt', 'utf8'), { pkg : pkg })) .pipe(gulp.dest('./dist')) .on('error', console.error); const gpuCore = gulp.src('dist/gpu-browser-core.js') .pipe(uglify()) .pipe(rename('gpu-browser-core.min.js')) .pipe(header(fs.readFileSync('./src/browser-header.txt', 'utf8'), { pkg : pkg })) .pipe(gulp.dest('./dist')) .on('error', console.error); return merge(gpu, gpuCore); }); /// The browser sync prototyping gulp.task('bsync', () => { // Syncs browser browserSync.init({ server: { baseDir: './' }, open: true, startPath: "./test/html/test-all.html", // Makes it easier to test on external mobile devices host: "0.0.0.0", tunnel: true }); // Detect change -> rebuild TS gulp.watch(['src/**.js'], gulp.series('minify')); }); /// Auto rebuild and host gulp.task('default', gulp.series('minify','bsync')); /// Beautify source code /// Use before merge request gulp.task('beautify', () => { return gulp.src(['src/**/*.js']) .pipe(jsprettify({ indent_size: 2, indent_char: ' ', indent_with_tabs: false, eol: '\n', brace_style: 'preserve-inline' })) .pipe(gulp.dest('src')); }); gulp.task('build-tests', () => { const folder = 'test'; const testFile = 'all.html'; try { fs.unlinkSync(`${folder}/${testFile}`); } catch (e) {} const rootPath = path.resolve(process.cwd(), folder); const warning = '\n'; const files = readDirDeepSync(rootPath, { patterns: [ '**/*.js' ], ignore: [ '*.js' ] }) .map(file => file.replace(/^test\//, '')); return gulp.src(`${folder}/all-template.html`) .pipe(replace('{{test-files}}', warning + files.map(file => ``).join('\n'))) .pipe(rename(testFile)) .pipe(gulp.dest(folder)); }); gulp.task('make', gulp.series('build', 'beautify', 'minify', 'build-tests')); ================================================ FILE: package.json ================================================ { "name": "gpu.js", "version": "2.16.0", "description": "GPU Accelerated JavaScript", "engines": { "node": ">=8.0.0" }, "main": "./src/index.js", "files": [ "src", "dist" ], "unpkg": "./dist/gpu-browser.js", "jsdelivr": "./dist/gpu-browser.js", "browser": "./dist/gpu-browser.js", "directories": { "doc": "doc", "test": "test" }, "dependencies": { "acorn": "8.14.0", "gl": "8.1.6", "gl-wiretap": "0.6.2", "gpu-mock.js": "github:weagle08/gpu-mock.js", "ordered-read-streams": "^2.0.0", "webgpu": "0.2.9" }, "devDependencies": { "benchmark": "2.1.4", "browser-sync": "3.0.2", "browserify": "17.0.0", "c8": "10.1.2", "gulp": "5.0.0", "gulp-concat": "2.6.1", "gulp-header": "2.0.9", "gulp-jsbeautifier": "3.0.1", "gulp-rename": "2.0.0", "gulp-replace": "1.1.4", "gulp-strip-comments": "2.6.0", "gulp-uglify-es": "3.0.0", "merge-stream": "2.0.0", "qunit": "2.22.0", "read-dir-deep": "8.0.0", "sinon": "18.0.0", "vinyl-buffer": "1.0.1", "vinyl-source-stream": "2.0.0" }, "scripts": { "test": "qunit test/issues test/internal test/features", "coverage": "c8 qunit test/issues test/internal test/features", "setup": "npm i -g gulp-cli", "make": "gulp make", "build": "gulp build", "docs": "doxdox ./src --layout bootstrap --output docs.html" }, "repository": { "type": "git", "url": "git+https://github.com/gpujs/gpu.js.git" }, "keywords": [ "gpgpu", "webgl" ], "author": "The gpu.js Team", "license": "MIT", "bugs": { "url": "https://github.com/gpujs/gpu.js/issues" }, "homepage": "http://gpu.rocks/", "typings": "./src/index.d.ts" } ================================================ FILE: src/alias.js ================================================ const { utils } = require('./utils'); /** * * @param name * @param source * @returns {Function} */ function alias(name, source) { const fnString = source.toString(); return new Function(`return function ${ name } (${ utils.getArgumentNamesFromString(fnString).join(', ') }) { ${ utils.getFunctionBodyFromString(fnString) } }`)(); } module.exports = { alias }; ================================================ FILE: src/backend/cpu/function-node.js ================================================ const { FunctionNode } = require('../function-node'); /** * @desc [INTERNAL] Represents a single function, inside JS * *

This handles all the raw state, converted state, etc. Of a single function.

*/ class CPUFunctionNode extends FunctionNode { /** * @desc Parses the abstract syntax tree for to its *named function* * @param {Object} ast - the AST object to parse * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astFunction(ast, retArr) { // Setup function return type and name if (!this.isRootKernel) { retArr.push('function'); retArr.push(' '); retArr.push(this.name); retArr.push('('); // Arguments handling for (let i = 0; i < this.argumentNames.length; ++i) { const argumentName = this.argumentNames[i]; if (i > 0) { retArr.push(', '); } retArr.push('user_'); retArr.push(argumentName); } // Function opening retArr.push(') {\n'); } // Body statement iteration for (let i = 0; i < ast.body.body.length; ++i) { this.astGeneric(ast.body.body[i], retArr); retArr.push('\n'); } if (!this.isRootKernel) { // Function closing retArr.push('}\n'); } return retArr; } /** * @desc Parses the abstract syntax tree for to *return* statement * @param {Object} ast - the AST object to parse * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astReturnStatement(ast, retArr) { const type = this.returnType || this.getType(ast.argument); if (!this.returnType) { this.returnType = type; } if (this.isRootKernel) { retArr.push(this.leadingReturnStatement); this.astGeneric(ast.argument, retArr); retArr.push(';\n'); retArr.push(this.followingReturnStatement); retArr.push('continue;\n'); } else if (this.isSubKernel) { retArr.push(`subKernelResult_${ this.name } = `); this.astGeneric(ast.argument, retArr); retArr.push(';'); retArr.push(`return subKernelResult_${ this.name };`); } else { retArr.push('return '); this.astGeneric(ast.argument, retArr); retArr.push(';'); } return retArr; } /** * @desc Parses the abstract syntax tree for *literal value* * @param {Object} ast - the AST object to parse * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astLiteral(ast, retArr) { // Reject non numeric literals if (isNaN(ast.value)) { throw this.astErrorOutput( 'Non-numeric literal not supported : ' + ast.value, ast ); } retArr.push(ast.value); return retArr; } /** * @desc Parses the abstract syntax tree for *binary* expression * @param {Object} ast - the AST object to parse * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astBinaryExpression(ast, retArr) { retArr.push('('); this.astGeneric(ast.left, retArr); retArr.push(ast.operator); this.astGeneric(ast.right, retArr); retArr.push(')'); return retArr; } /** * @desc Parses the abstract syntax tree for *identifier* expression * @param {Object} idtNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astIdentifierExpression(idtNode, retArr) { if (idtNode.type !== 'Identifier') { throw this.astErrorOutput( 'IdentifierExpression - not an Identifier', idtNode ); } switch (idtNode.name) { case 'Infinity': retArr.push('Infinity'); break; default: if (this.constants && this.constants.hasOwnProperty(idtNode.name)) { retArr.push('constants_' + idtNode.name); } else { retArr.push('user_' + idtNode.name); } } return retArr; } /** * @desc Parses the abstract syntax tree for *for-loop* expression * @param {Object} forNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the parsed webgl string */ astForStatement(forNode, retArr) { if (forNode.type !== 'ForStatement') { throw this.astErrorOutput('Invalid for statement', forNode); } const initArr = []; const testArr = []; const updateArr = []; const bodyArr = []; let isSafe = null; if (forNode.init) { this.pushState('in-for-loop-init'); this.astGeneric(forNode.init, initArr); for (let i = 0; i < initArr.length; i++) { if (initArr[i].includes && initArr[i].includes(',')) { isSafe = false; } } this.popState('in-for-loop-init'); } else { isSafe = false; } if (forNode.test) { this.astGeneric(forNode.test, testArr); } else { isSafe = false; } if (forNode.update) { this.astGeneric(forNode.update, updateArr); } else { isSafe = false; } if (forNode.body) { this.pushState('loop-body'); this.astGeneric(forNode.body, bodyArr); this.popState('loop-body'); } // have all parts, now make them safe if (isSafe === null) { isSafe = this.isSafe(forNode.init) && this.isSafe(forNode.test); } if (isSafe) { retArr.push(`for (${initArr.join('')};${testArr.join('')};${updateArr.join('')}){\n`); retArr.push(bodyArr.join('')); retArr.push('}\n'); } else { const iVariableName = this.getInternalVariableName('safeI'); if (initArr.length > 0) { retArr.push(initArr.join(''), ';\n'); } retArr.push(`for (let ${iVariableName}=0;${iVariableName} 0) { retArr.push(`if (!${testArr.join('')}) break;\n`); } retArr.push(bodyArr.join('')); retArr.push(`\n${updateArr.join('')};`); retArr.push('}\n'); } return retArr; } /** * @desc Parses the abstract syntax tree for *while* loop * @param {Object} whileNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the parsed javascript string */ astWhileStatement(whileNode, retArr) { if (whileNode.type !== 'WhileStatement') { throw this.astErrorOutput( 'Invalid while statement', whileNode ); } retArr.push('for (let i = 0; i < LOOP_MAX; i++) {'); retArr.push('if ('); this.astGeneric(whileNode.test, retArr); retArr.push(') {\n'); this.astGeneric(whileNode.body, retArr); retArr.push('} else {\n'); retArr.push('break;\n'); retArr.push('}\n'); retArr.push('}\n'); return retArr; } /** * @desc Parses the abstract syntax tree for *do while* loop * @param {Object} doWhileNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the parsed webgl string */ astDoWhileStatement(doWhileNode, retArr) { if (doWhileNode.type !== 'DoWhileStatement') { throw this.astErrorOutput( 'Invalid while statement', doWhileNode ); } retArr.push('for (let i = 0; i < LOOP_MAX; i++) {'); this.astGeneric(doWhileNode.body, retArr); retArr.push('if (!'); this.astGeneric(doWhileNode.test, retArr); retArr.push(') {\n'); retArr.push('break;\n'); retArr.push('}\n'); retArr.push('}\n'); return retArr; } /** * @desc Parses the abstract syntax tree for *Assignment* Expression * @param {Object} assNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astAssignmentExpression(assNode, retArr) { const declaration = this.getDeclaration(assNode.left); if (declaration && !declaration.assignable) { throw this.astErrorOutput(`Variable ${assNode.left.name} is not assignable here`, assNode); } this.astGeneric(assNode.left, retArr); retArr.push(assNode.operator); this.astGeneric(assNode.right, retArr); return retArr; } /** * @desc Parses the abstract syntax tree for *Block* statement * @param {Object} bNode - the AST object to parse * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astBlockStatement(bNode, retArr) { if (this.isState('loop-body')) { this.pushState('block-body'); // this prevents recursive removal of braces for (let i = 0; i < bNode.body.length; i++) { this.astGeneric(bNode.body[i], retArr); } this.popState('block-body'); } else { retArr.push('{\n'); for (let i = 0; i < bNode.body.length; i++) { this.astGeneric(bNode.body[i], retArr); } retArr.push('}\n'); } return retArr; } /** * @desc Parses the abstract syntax tree for *Variable Declaration* * @param {Object} varDecNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astVariableDeclaration(varDecNode, retArr) { retArr.push(`${varDecNode.kind} `); const { declarations } = varDecNode; for (let i = 0; i < declarations.length; i++) { if (i > 0) { retArr.push(','); } const declaration = declarations[i]; const info = this.getDeclaration(declaration.id); if (!info.valueType) { info.valueType = this.getType(declaration.init); } this.astGeneric(declaration, retArr); } if (!this.isState('in-for-loop-init')) { retArr.push(';'); } return retArr; } /** * @desc Parses the abstract syntax tree for *If* Statement * @param {Object} ifNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astIfStatement(ifNode, retArr) { retArr.push('if ('); this.astGeneric(ifNode.test, retArr); retArr.push(')'); if (ifNode.consequent.type === 'BlockStatement') { this.astGeneric(ifNode.consequent, retArr); } else { retArr.push(' {\n'); this.astGeneric(ifNode.consequent, retArr); retArr.push('\n}\n'); } if (ifNode.alternate) { retArr.push('else '); if (ifNode.alternate.type === 'BlockStatement' || ifNode.alternate.type === 'IfStatement') { this.astGeneric(ifNode.alternate, retArr); } else { retArr.push(' {\n'); this.astGeneric(ifNode.alternate, retArr); retArr.push('\n}\n'); } } return retArr; } astSwitchStatement(ast, retArr) { const { discriminant, cases } = ast; retArr.push('switch ('); this.astGeneric(discriminant, retArr); retArr.push(') {\n'); for (let i = 0; i < cases.length; i++) { if (cases[i].test === null) { retArr.push('default:\n'); this.astGeneric(cases[i].consequent, retArr); if (cases[i].consequent && cases[i].consequent.length > 0) { retArr.push('break;\n'); } continue; } retArr.push('case '); this.astGeneric(cases[i].test, retArr); retArr.push(':\n'); if (cases[i].consequent && cases[i].consequent.length > 0) { this.astGeneric(cases[i].consequent, retArr); retArr.push('break;\n'); } } retArr.push('\n}'); } /** * @desc Parses the abstract syntax tree for *This* expression * @param {Object} tNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astThisExpression(tNode, retArr) { retArr.push('_this'); return retArr; } /** * @desc Parses the abstract syntax tree for *Member* Expression * @param {Object} mNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astMemberExpression(mNode, retArr) { const { signature, type, property, xProperty, yProperty, zProperty, name, origin } = this.getMemberExpressionDetails(mNode); switch (signature) { case 'this.thread.value': retArr.push(`_this.thread.${ name }`); return retArr; case 'this.output.value': switch (name) { case 'x': retArr.push('outputX'); break; case 'y': retArr.push('outputY'); break; case 'z': retArr.push('outputZ'); break; default: throw this.astErrorOutput('Unexpected expression', mNode); } return retArr; case 'value': throw this.astErrorOutput('Unexpected expression', mNode); case 'value[]': case 'value[][]': case 'value[][][]': case 'value.value': if (origin === 'Math') { retArr.push(Math[name]); return retArr; } switch (property) { case 'r': retArr.push(`user_${ name }[0]`); return retArr; case 'g': retArr.push(`user_${ name }[1]`); return retArr; case 'b': retArr.push(`user_${ name }[2]`); return retArr; case 'a': retArr.push(`user_${ name }[3]`); return retArr; } break; case 'this.constants.value': case 'this.constants.value[]': case 'this.constants.value[][]': case 'this.constants.value[][][]': break; case 'fn()[]': this.astGeneric(mNode.object, retArr); retArr.push('['); this.astGeneric(mNode.property, retArr); retArr.push(']'); return retArr; case 'fn()[][]': this.astGeneric(mNode.object.object, retArr); retArr.push('['); this.astGeneric(mNode.object.property, retArr); retArr.push(']'); retArr.push('['); this.astGeneric(mNode.property, retArr); retArr.push(']'); return retArr; default: throw this.astErrorOutput('Unexpected expression', mNode); } if (!mNode.computed) { // handle simple types switch (type) { case 'Number': case 'Integer': case 'Float': case 'Boolean': retArr.push(`${origin}_${name}`); return retArr; } } // handle more complex types // argument may have come from a parent const markupName = `${origin}_${name}`; switch (type) { case 'Array(2)': case 'Array(3)': case 'Array(4)': case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': case 'HTMLImageArray': case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': case 'HTMLImage': default: let size; let isInput; if (origin === 'constants') { const constant = this.constants[name]; isInput = this.constantTypes[name] === 'Input'; size = isInput ? constant.size : null; } else { isInput = this.isInput(name); size = isInput ? this.argumentSizes[this.argumentNames.indexOf(name)] : null; } retArr.push(`${ markupName }`); if (zProperty && yProperty) { if (isInput) { retArr.push('[('); this.astGeneric(zProperty, retArr); retArr.push(`*${ this.dynamicArguments ? '(outputY * outputX)' : size[1] * size[0] })+(`); this.astGeneric(yProperty, retArr); retArr.push(`*${ this.dynamicArguments ? 'outputX' : size[0] })+`); this.astGeneric(xProperty, retArr); retArr.push(']'); } else { retArr.push('['); this.astGeneric(zProperty, retArr); retArr.push(']'); retArr.push('['); this.astGeneric(yProperty, retArr); retArr.push(']'); retArr.push('['); this.astGeneric(xProperty, retArr); retArr.push(']'); } } else if (yProperty) { if (isInput) { retArr.push('[('); this.astGeneric(yProperty, retArr); retArr.push(`*${ this.dynamicArguments ? 'outputX' : size[0] })+`); this.astGeneric(xProperty, retArr); retArr.push(']'); } else { retArr.push('['); this.astGeneric(yProperty, retArr); retArr.push(']'); retArr.push('['); this.astGeneric(xProperty, retArr); retArr.push(']'); } } else if (typeof xProperty !== 'undefined') { retArr.push('['); this.astGeneric(xProperty, retArr); retArr.push(']'); } } return retArr; } /** * @desc Parses the abstract syntax tree for *call* expression * @param {Object} ast - the AST object to parse * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astCallExpression(ast, retArr) { if (ast.type !== 'CallExpression') { // Failure, unknown expression throw this.astErrorOutput('Unknown CallExpression', ast); } // Get the full function call, unrolled let functionName = this.astMemberExpressionUnroll(ast.callee); // Register the function into the called registry if (this.calledFunctions.indexOf(functionName) < 0) { this.calledFunctions.push(functionName); } const isMathFunction = this.isAstMathFunction(ast); // track the function was called if (this.onFunctionCall) { this.onFunctionCall(this.name, functionName, ast.arguments); } // Call the function retArr.push(functionName); // Open arguments space retArr.push('('); const targetTypes = this.lookupFunctionArgumentTypes(functionName) || []; // Add the arguments for (let i = 0; i < ast.arguments.length; ++i) { const argument = ast.arguments[i]; // in order to track return type, even though this is CPU let argumentType = this.getType(argument); if (!targetTypes[i]) { this.triggerImplyArgumentType(functionName, i, argumentType, this); } if (i > 0) { retArr.push(', '); } this.astGeneric(argument, retArr); } // Close arguments space retArr.push(')'); return retArr; } /** * @desc Parses the abstract syntax tree for *Array* Expression * @param {Object} arrNode - the AST object to parse * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astArrayExpression(arrNode, retArr) { const returnType = this.getType(arrNode); const arrLen = arrNode.elements.length; const elements = []; for (let i = 0; i < arrLen; ++i) { const element = []; this.astGeneric(arrNode.elements[i], element); elements.push(element.join('')); } switch (returnType) { case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': retArr.push(`[${elements.join(', ')}]`); break; default: retArr.push(`new Float32Array([${elements.join(', ')}])`); } return retArr; } astDebuggerStatement(arrNode, retArr) { retArr.push('debugger;'); return retArr; } } module.exports = { CPUFunctionNode }; ================================================ FILE: src/backend/cpu/kernel-string.js ================================================ const { utils } = require('../../utils'); function constantsToString(constants, types) { const results = []; for (const name in types) { if (!types.hasOwnProperty(name)) continue; const type = types[name]; const constant = constants[name]; switch (type) { case 'Number': case 'Integer': case 'Float': case 'Boolean': results.push(`${name}:${constant}`); break; case 'Array(2)': case 'Array(3)': case 'Array(4)': case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': results.push(`${name}:new ${constant.constructor.name}(${JSON.stringify(Array.from(constant))})`); break; } } return `{ ${ results.join() } }`; } function cpuKernelString(cpuKernel, name) { const header = []; const thisProperties = []; const beforeReturn = []; const useFunctionKeyword = !/^function/.test(cpuKernel.color.toString()); header.push( ' const { context, canvas, constants: incomingConstants } = settings;', ` const output = new Int32Array(${JSON.stringify(Array.from(cpuKernel.output))});`, ` const _constantTypes = ${JSON.stringify(cpuKernel.constantTypes)};`, ` const _constants = ${constantsToString(cpuKernel.constants, cpuKernel.constantTypes)};` ); thisProperties.push( ' constants: _constants,', ' context,', ' output,', ' thread: {x: 0, y: 0, z: 0},' ); if (cpuKernel.graphical) { header.push(` const _imageData = context.createImageData(${cpuKernel.output[0]}, ${cpuKernel.output[1]});`); header.push(` const _colorData = new Uint8ClampedArray(${cpuKernel.output[0]} * ${cpuKernel.output[1]} * 4);`); const colorFn = utils.flattenFunctionToString((useFunctionKeyword ? 'function ' : '') + cpuKernel.color.toString(), { thisLookup: (propertyName) => { switch (propertyName) { case '_colorData': return '_colorData'; case '_imageData': return '_imageData'; case 'output': return 'output'; case 'thread': return 'this.thread'; } return JSON.stringify(cpuKernel[propertyName]); }, findDependency: (object, name) => { return null; } }); const getPixelsFn = utils.flattenFunctionToString((useFunctionKeyword ? 'function ' : '') + cpuKernel.getPixels.toString(), { thisLookup: (propertyName) => { switch (propertyName) { case '_colorData': return '_colorData'; case '_imageData': return '_imageData'; case 'output': return 'output'; case 'thread': return 'this.thread'; } return JSON.stringify(cpuKernel[propertyName]); }, findDependency: () => { return null; } }); thisProperties.push( ' _imageData,', ' _colorData,', ` color: ${colorFn},` ); beforeReturn.push( ` kernel.getPixels = ${getPixelsFn};` ); } const constantTypes = []; const constantKeys = Object.keys(cpuKernel.constantTypes); for (let i = 0; i < constantKeys.length; i++) { constantTypes.push(cpuKernel.constantTypes[constantKeys]); } if (cpuKernel.argumentTypes.indexOf('HTMLImageArray') !== -1 || constantTypes.indexOf('HTMLImageArray') !== -1) { const flattenedImageTo3DArray = utils.flattenFunctionToString((useFunctionKeyword ? 'function ' : '') + cpuKernel._imageTo3DArray.toString(), { doNotDefine: ['canvas'], findDependency: (object, name) => { if (object === 'this') { return (useFunctionKeyword ? 'function ' : '') + cpuKernel[name].toString(); } return null; }, thisLookup: (propertyName) => { switch (propertyName) { case 'canvas': return; case 'context': return 'context'; } } }); beforeReturn.push(flattenedImageTo3DArray); thisProperties.push(` _mediaTo2DArray,`); thisProperties.push(` _imageTo3DArray,`); } else if (cpuKernel.argumentTypes.indexOf('HTMLImage') !== -1 || constantTypes.indexOf('HTMLImage') !== -1) { const flattenedImageTo2DArray = utils.flattenFunctionToString((useFunctionKeyword ? 'function ' : '') + cpuKernel._mediaTo2DArray.toString(), { findDependency: (object, name) => { return null; }, thisLookup: (propertyName) => { switch (propertyName) { case 'canvas': return 'settings.canvas'; case 'context': return 'settings.context'; } throw new Error('unhandled thisLookup'); } }); beforeReturn.push(flattenedImageTo2DArray); thisProperties.push(` _mediaTo2DArray,`); } return `function(settings) { ${ header.join('\n') } for (const p in _constantTypes) { if (!_constantTypes.hasOwnProperty(p)) continue; const type = _constantTypes[p]; switch (type) { case 'Number': case 'Integer': case 'Float': case 'Boolean': case 'Array(2)': case 'Array(3)': case 'Array(4)': case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': if (incomingConstants.hasOwnProperty(p)) { console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned'); } continue; } if (!incomingConstants.hasOwnProperty(p)) { throw new Error('constant ' + p + ' not found'); } _constants[p] = incomingConstants[p]; } const kernel = (function() { ${cpuKernel._kernelString} }) .apply({ ${thisProperties.join('\n')} }); ${ beforeReturn.join('\n') } return kernel; }`; } module.exports = { cpuKernelString }; ================================================ FILE: src/backend/cpu/kernel.js ================================================ const { Kernel } = require('../kernel'); const { FunctionBuilder } = require('../function-builder'); const { CPUFunctionNode } = require('./function-node'); const { utils } = require('../../utils'); const { cpuKernelString } = require('./kernel-string'); /** * @desc Kernel Implementation for CPU. *

Instantiates properties to the CPU Kernel.

*/ class CPUKernel extends Kernel { static getFeatures() { return this.features; } static get features() { return Object.freeze({ kernelMap: true, isIntegerDivisionAccurate: true }); } static get isSupported() { return true; } static isContextMatch(context) { return false; } /** * @desc The current mode in which gpu.js is executing. */ static get mode() { return 'cpu'; } static nativeFunctionArguments() { return null; } static nativeFunctionReturnType() { throw new Error(`Looking up native function return type not supported on ${this.name}`); } static combineKernels(combinedKernel) { return combinedKernel; } static getSignature(kernel, argumentTypes) { return 'cpu' + (argumentTypes.length > 0 ? ':' + argumentTypes.join(',') : ''); } constructor(source, settings) { super(source, settings); this.mergeSettings(source.settings || settings); this._imageData = null; this._colorData = null; this._kernelString = null; this._prependedString = []; this.thread = { x: 0, y: 0, z: 0 }; this.translatedSources = null; } initCanvas() { if (typeof document !== 'undefined') { return document.createElement('canvas'); } else if (typeof OffscreenCanvas !== 'undefined') { return new OffscreenCanvas(0, 0); } } initContext() { if (!this.canvas) return null; return this.canvas.getContext('2d'); } initPlugins(settings) { return []; } /** * @desc Validate settings related to Kernel, such as dimensions size, and auto output support. * @param {IArguments} args */ validateSettings(args) { if (!this.output || this.output.length === 0) { if (args.length !== 1) { throw new Error('Auto output only supported for kernels with only one input'); } const argType = utils.getVariableType(args[0], this.strictIntegers); if (argType === 'Array') { this.output = utils.getDimensions(argType); } else if (argType === 'NumberTexture' || argType === 'ArrayTexture(4)') { this.output = args[0].output; } else { throw new Error('Auto output not supported for input type: ' + argType); } } if (this.graphical) { if (this.output.length !== 2) { throw new Error('Output must have 2 dimensions on graphical mode'); } } this.checkOutput(); } translateSource() { this.leadingReturnStatement = this.output.length > 1 ? 'resultX[x] = ' : 'result[x] = '; if (this.subKernels) { const followingReturnStatement = []; for (let i = 0; i < this.subKernels.length; i++) { const { name } = this.subKernels[i]; followingReturnStatement.push(this.output.length > 1 ? `resultX_${ name }[x] = subKernelResult_${ name };\n` : `result_${ name }[x] = subKernelResult_${ name };\n`); } this.followingReturnStatement = followingReturnStatement.join(''); } const functionBuilder = FunctionBuilder.fromKernel(this, CPUFunctionNode); this.translatedSources = functionBuilder.getPrototypes('kernel'); if (!this.graphical && !this.returnType) { this.returnType = functionBuilder.getKernelResultType(); } } /** * @desc Builds the Kernel, by generating the kernel * string using thread dimensions, and arguments * supplied to the kernel. * *

If the graphical flag is enabled, canvas is used.

*/ build() { if (this.built) return; this.setupConstants(); this.setupArguments(arguments); this.validateSettings(arguments); this.translateSource(); if (this.graphical) { const { canvas, output } = this; if (!canvas) { throw new Error('no canvas available for using graphical output'); } const width = output[0]; const height = output[1] || 1; canvas.width = width; canvas.height = height; this._imageData = this.context.createImageData(width, height); this._colorData = new Uint8ClampedArray(width * height * 4); } const kernelString = this.getKernelString(); this.kernelString = kernelString; if (this.debug) { console.log('Function output:'); console.log(kernelString); } try { this.run = new Function([], kernelString).bind(this)(); } catch (e) { console.error('An error occurred compiling the javascript: ', e); } this.buildSignature(arguments); this.built = true; } color(r, g, b, a) { if (typeof a === 'undefined') { a = 1; } r = Math.floor(r * 255); g = Math.floor(g * 255); b = Math.floor(b * 255); a = Math.floor(a * 255); const width = this.output[0]; const height = this.output[1]; const x = this.thread.x; const y = height - this.thread.y - 1; const index = x + y * width; this._colorData[index * 4 + 0] = r; this._colorData[index * 4 + 1] = g; this._colorData[index * 4 + 2] = b; this._colorData[index * 4 + 3] = a; } /** * @desc Generates kernel string for this kernel program. * *

If sub-kernels are supplied, they are also factored in. * This string can be saved by calling the `toString` method * and then can be reused later.

* * @returns {String} result * */ getKernelString() { if (this._kernelString !== null) return this._kernelString; let kernelThreadString = null; let { translatedSources } = this; if (translatedSources.length > 1) { translatedSources = translatedSources.filter(fn => { if (/^function/.test(fn)) return fn; kernelThreadString = fn; return false; }); } else { kernelThreadString = translatedSources.shift(); } return this._kernelString = ` const LOOP_MAX = ${ this._getLoopMaxString() }; ${ this.injectedNative || '' } const _this = this; ${ this._resultKernelHeader() } ${ this._processConstants() } return (${ this.argumentNames.map(argumentName => 'user_' + argumentName).join(', ') }) => { ${ this._prependedString.join('') } ${ this._earlyThrows() } ${ this._processArguments() } ${ this.graphical ? this._graphicalKernelBody(kernelThreadString) : this._resultKernelBody(kernelThreadString) } ${ translatedSources.length > 0 ? translatedSources.join('\n') : '' } };`; } /** * @desc Returns the *pre-compiled* Kernel as a JS Object String, that can be reused. */ toString() { return cpuKernelString(this); } /** * @desc Get the maximum loop size String. * @returns {String} result */ _getLoopMaxString() { return ( this.loopMaxIterations ? ` ${ parseInt(this.loopMaxIterations) };` : ' 1000;' ); } _processConstants() { if (!this.constants) return ''; const result = []; for (let p in this.constants) { const type = this.constantTypes[p]; switch (type) { case 'HTMLCanvas': case 'OffscreenCanvas': case 'HTMLImage': case 'ImageBitmap': case 'ImageData': case 'HTMLVideo': result.push(` const constants_${p} = this._mediaTo2DArray(this.constants.${p});\n`); break; case 'HTMLImageArray': result.push(` const constants_${p} = this._imageTo3DArray(this.constants.${p});\n`); break; case 'Input': result.push(` const constants_${p} = this.constants.${p}.value;\n`); break; default: result.push(` const constants_${p} = this.constants.${p};\n`); } } return result.join(''); } _earlyThrows() { if (this.graphical) return ''; if (this.immutable) return ''; if (!this.pipeline) return ''; const arrayArguments = []; for (let i = 0; i < this.argumentTypes.length; i++) { if (this.argumentTypes[i] === 'Array') { arrayArguments.push(this.argumentNames[i]); } } if (arrayArguments.length === 0) return ''; const checks = []; for (let i = 0; i < arrayArguments.length; i++) { const argumentName = arrayArguments[i]; const checkSubKernels = this._mapSubKernels(subKernel => `user_${argumentName} === result_${subKernel.name}`).join(' || '); checks.push(`user_${argumentName} === result${checkSubKernels ? ` || ${checkSubKernels}` : ''}`); } return `if (${checks.join(' || ')}) throw new Error('Source and destination arrays are the same. Use immutable = true');`; } _processArguments() { const result = []; for (let i = 0; i < this.argumentTypes.length; i++) { const variableName = `user_${this.argumentNames[i]}`; switch (this.argumentTypes[i]) { case 'HTMLCanvas': case 'OffscreenCanvas': case 'HTMLImage': case 'ImageBitmap': case 'ImageData': case 'HTMLVideo': result.push(` ${variableName} = this._mediaTo2DArray(${variableName});\n`); break; case 'HTMLImageArray': result.push(` ${variableName} = this._imageTo3DArray(${variableName});\n`); break; case 'Input': result.push(` ${variableName} = ${variableName}.value;\n`); break; case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': case 'NumberTexture': case 'MemoryOptimizedNumberTexture': result.push(` if (${variableName}.toArray) { if (!_this.textureCache) { _this.textureCache = []; _this.arrayCache = []; } const textureIndex = _this.textureCache.indexOf(${variableName}); if (textureIndex !== -1) { ${variableName} = _this.arrayCache[textureIndex]; } else { _this.textureCache.push(${variableName}); ${variableName} = ${variableName}.toArray(); _this.arrayCache.push(${variableName}); } }`); break; } } return result.join(''); } _mediaTo2DArray(media) { const canvas = this.canvas; const width = media.width > 0 ? media.width : media.videoWidth; const height = media.height > 0 ? media.height : media.videoHeight; if (canvas.width < width) { canvas.width = width; } if (canvas.height < height) { canvas.height = height; } const ctx = this.context; let pixelsData; if (media.constructor === ImageData) { pixelsData = media.data; } else { ctx.drawImage(media, 0, 0, width, height); pixelsData = ctx.getImageData(0, 0, width, height).data; } const imageArray = new Array(height); let index = 0; for (let y = height - 1; y >= 0; y--) { const row = imageArray[y] = new Array(width); for (let x = 0; x < width; x++) { const pixel = new Float32Array(4); pixel[0] = pixelsData[index++] / 255; // r pixel[1] = pixelsData[index++] / 255; // g pixel[2] = pixelsData[index++] / 255; // b pixel[3] = pixelsData[index++] / 255; // a row[x] = pixel; } } return imageArray; } /** * * @param flip * @return {Uint8ClampedArray} */ getPixels(flip) { const [width, height] = this.output; // cpu is not flipped by default return flip ? utils.flipPixels(this._imageData.data, width, height) : this._imageData.data.slice(0); } _imageTo3DArray(images) { const imagesArray = new Array(images.length); for (let i = 0; i < images.length; i++) { imagesArray[i] = this._mediaTo2DArray(images[i]); } return imagesArray; } _resultKernelHeader() { if (this.graphical) return ''; if (this.immutable) return ''; if (!this.pipeline) return ''; switch (this.output.length) { case 1: return this._mutableKernel1DResults(); case 2: return this._mutableKernel2DResults(); case 3: return this._mutableKernel3DResults(); } } _resultKernelBody(kernelString) { switch (this.output.length) { case 1: return (!this.immutable && this.pipeline ? this._resultMutableKernel1DLoop(kernelString) : this._resultImmutableKernel1DLoop(kernelString)) + this._kernelOutput(); case 2: return (!this.immutable && this.pipeline ? this._resultMutableKernel2DLoop(kernelString) : this._resultImmutableKernel2DLoop(kernelString)) + this._kernelOutput(); case 3: return (!this.immutable && this.pipeline ? this._resultMutableKernel3DLoop(kernelString) : this._resultImmutableKernel3DLoop(kernelString)) + this._kernelOutput(); default: throw new Error('unsupported size kernel'); } } _graphicalKernelBody(kernelThreadString) { switch (this.output.length) { case 2: return this._graphicalKernel2DLoop(kernelThreadString) + this._graphicalOutput(); default: throw new Error('unsupported size kernel'); } } _graphicalOutput() { return ` this._imageData.data.set(this._colorData); this.context.putImageData(this._imageData, 0, 0); return;` } _getKernelResultTypeConstructorString() { switch (this.returnType) { case 'LiteralInteger': case 'Number': case 'Integer': case 'Float': return 'Float32Array'; case 'Array(2)': case 'Array(3)': case 'Array(4)': return 'Array'; default: if (this.graphical) { return 'Float32Array'; } throw new Error(`unhandled returnType ${ this.returnType }`); } } _resultImmutableKernel1DLoop(kernelString) { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const result = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new ${constructorString}(outputX);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') } for (let x = 0; x < outputX; x++) { this.thread.x = x; this.thread.y = 0; this.thread.z = 0; ${ kernelString } }`; } _mutableKernel1DResults() { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const result = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new ${constructorString}(outputX);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') }`; } _resultMutableKernel1DLoop(kernelString) { return ` const outputX = _this.output[0]; for (let x = 0; x < outputX; x++) { this.thread.x = x; this.thread.y = 0; this.thread.z = 0; ${ kernelString } }`; } _resultImmutableKernel2DLoop(kernelString) { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const outputY = _this.output[1]; const result = new Array(outputY); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new Array(outputY);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') } for (let y = 0; y < outputY; y++) { this.thread.z = 0; this.thread.y = y; const resultX = result[y] = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const resultX_${ subKernel.name } = result_${subKernel.name}[y] = new ${constructorString}(outputX);\n`).join('') } for (let x = 0; x < outputX; x++) { this.thread.x = x; ${ kernelString } } }`; } _mutableKernel2DResults() { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const outputY = _this.output[1]; const result = new Array(outputY); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new Array(outputY);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') } for (let y = 0; y < outputY; y++) { const resultX = result[y] = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const resultX_${ subKernel.name } = result_${subKernel.name}[y] = new ${constructorString}(outputX);\n`).join('') } }`; } _resultMutableKernel2DLoop(kernelString) { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const outputY = _this.output[1]; for (let y = 0; y < outputY; y++) { this.thread.z = 0; this.thread.y = y; const resultX = result[y]; ${ this._mapSubKernels(subKernel => `const resultX_${ subKernel.name } = result_${subKernel.name}[y] = new ${constructorString}(outputX);\n`).join('') } for (let x = 0; x < outputX; x++) { this.thread.x = x; ${ kernelString } } }`; } _graphicalKernel2DLoop(kernelString) { return ` const outputX = _this.output[0]; const outputY = _this.output[1]; for (let y = 0; y < outputY; y++) { this.thread.z = 0; this.thread.y = y; for (let x = 0; x < outputX; x++) { this.thread.x = x; ${ kernelString } } }`; } _resultImmutableKernel3DLoop(kernelString) { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const outputY = _this.output[1]; const outputZ = _this.output[2]; const result = new Array(outputZ); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new Array(outputZ);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') } for (let z = 0; z < outputZ; z++) { this.thread.z = z; const resultY = result[z] = new Array(outputY); ${ this._mapSubKernels(subKernel => `const resultY_${ subKernel.name } = result_${subKernel.name}[z] = new Array(outputY);\n`).join(' ') } for (let y = 0; y < outputY; y++) { this.thread.y = y; const resultX = resultY[y] = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const resultX_${ subKernel.name } = resultY_${subKernel.name}[y] = new ${constructorString}(outputX);\n`).join(' ') } for (let x = 0; x < outputX; x++) { this.thread.x = x; ${ kernelString } } } }`; } _mutableKernel3DResults() { const constructorString = this._getKernelResultTypeConstructorString(); return ` const outputX = _this.output[0]; const outputY = _this.output[1]; const outputZ = _this.output[2]; const result = new Array(outputZ); ${ this._mapSubKernels(subKernel => `const result_${ subKernel.name } = new Array(outputZ);\n`).join(' ') } ${ this._mapSubKernels(subKernel => `let subKernelResult_${ subKernel.name };\n`).join(' ') } for (let z = 0; z < outputZ; z++) { const resultY = result[z] = new Array(outputY); ${ this._mapSubKernels(subKernel => `const resultY_${ subKernel.name } = result_${subKernel.name}[z] = new Array(outputY);\n`).join(' ') } for (let y = 0; y < outputY; y++) { const resultX = resultY[y] = new ${constructorString}(outputX); ${ this._mapSubKernels(subKernel => `const resultX_${ subKernel.name } = resultY_${subKernel.name}[y] = new ${constructorString}(outputX);\n`).join(' ') } } }`; } _resultMutableKernel3DLoop(kernelString) { return ` const outputX = _this.output[0]; const outputY = _this.output[1]; const outputZ = _this.output[2]; for (let z = 0; z < outputZ; z++) { this.thread.z = z; const resultY = result[z]; for (let y = 0; y < outputY; y++) { this.thread.y = y; const resultX = resultY[y]; for (let x = 0; x < outputX; x++) { this.thread.x = x; ${ kernelString } } } }`; } _kernelOutput() { if (!this.subKernels) { return '\n return result;'; } return `\n return { result: result, ${ this.subKernels.map(subKernel => `${ subKernel.property }: result_${ subKernel.name }`).join(',\n ') } };`; } _mapSubKernels(fn) { return this.subKernels === null ? [''] : this.subKernels.map(fn); } destroy(removeCanvasReference) { if (removeCanvasReference) { delete this.canvas; } } static destroyContext(context) {} toJSON() { const json = super.toJSON(); json.functionNodes = FunctionBuilder.fromKernel(this, CPUFunctionNode).toJSON(); return json; } setOutput(output) { super.setOutput(output); const [width, height] = this.output; if (this.graphical) { this._imageData = this.context.createImageData(width, height); this._colorData = new Uint8ClampedArray(width * height * 4); } } prependString(value) { if (this._kernelString) throw new Error('Kernel already built'); this._prependedString.push(value); } hasPrependString(value) { return this._prependedString.indexOf(value) > -1; } } module.exports = { CPUKernel }; ================================================ FILE: src/backend/function-builder.js ================================================ /** * @desc This handles all the raw state, converted state, etc. of a single function. * [INTERNAL] A collection of functionNodes. * @class */ class FunctionBuilder { /** * * @param {Kernel} kernel * @param {FunctionNode} FunctionNode * @param {object} [extraNodeOptions] * @returns {FunctionBuilder} * @static */ static fromKernel(kernel, FunctionNode, extraNodeOptions) { const { kernelArguments, kernelConstants, argumentNames, argumentSizes, argumentBitRatios, constants, constantBitRatios, debug, loopMaxIterations, nativeFunctions, output, optimizeFloatMemory, precision, plugins, source, subKernels, functions, leadingReturnStatement, followingReturnStatement, dynamicArguments, dynamicOutput, } = kernel; const argumentTypes = new Array(kernelArguments.length); const constantTypes = {}; for (let i = 0; i < kernelArguments.length; i++) { argumentTypes[i] = kernelArguments[i].type; } for (let i = 0; i < kernelConstants.length; i++) { const kernelConstant = kernelConstants[i]; constantTypes[kernelConstant.name] = kernelConstant.type; } const needsArgumentType = (functionName, index) => { return functionBuilder.needsArgumentType(functionName, index); }; const assignArgumentType = (functionName, index, type) => { functionBuilder.assignArgumentType(functionName, index, type); }; const lookupReturnType = (functionName, ast, requestingNode) => { return functionBuilder.lookupReturnType(functionName, ast, requestingNode); }; const lookupFunctionArgumentTypes = (functionName) => { return functionBuilder.lookupFunctionArgumentTypes(functionName); }; const lookupFunctionArgumentName = (functionName, argumentIndex) => { return functionBuilder.lookupFunctionArgumentName(functionName, argumentIndex); }; const lookupFunctionArgumentBitRatio = (functionName, argumentName) => { return functionBuilder.lookupFunctionArgumentBitRatio(functionName, argumentName); }; const triggerImplyArgumentType = (functionName, i, argumentType, requestingNode) => { functionBuilder.assignArgumentType(functionName, i, argumentType, requestingNode); }; const triggerImplyArgumentBitRatio = (functionName, argumentName, calleeFunctionName, argumentIndex) => { functionBuilder.assignArgumentBitRatio(functionName, argumentName, calleeFunctionName, argumentIndex); }; const onFunctionCall = (functionName, calleeFunctionName, args) => { functionBuilder.trackFunctionCall(functionName, calleeFunctionName, args); }; const onNestedFunction = (ast, source) => { const argumentNames = []; for (let i = 0; i < ast.params.length; i++) { argumentNames.push(ast.params[i].name); } const nestedFunction = new FunctionNode(source, Object.assign({}, nodeOptions, { returnType: null, ast, name: ast.id.name, argumentNames, lookupReturnType, lookupFunctionArgumentTypes, lookupFunctionArgumentName, lookupFunctionArgumentBitRatio, needsArgumentType, assignArgumentType, triggerImplyArgumentType, triggerImplyArgumentBitRatio, onFunctionCall, })); nestedFunction.traceFunctionAST(ast); functionBuilder.addFunctionNode(nestedFunction); }; const nodeOptions = Object.assign({ isRootKernel: false, onNestedFunction, lookupReturnType, lookupFunctionArgumentTypes, lookupFunctionArgumentName, lookupFunctionArgumentBitRatio, needsArgumentType, assignArgumentType, triggerImplyArgumentType, triggerImplyArgumentBitRatio, onFunctionCall, optimizeFloatMemory, precision, constants, constantTypes, constantBitRatios, debug, loopMaxIterations, output, plugins, dynamicArguments, dynamicOutput, }, extraNodeOptions || {}); const rootNodeOptions = Object.assign({}, nodeOptions, { isRootKernel: true, name: 'kernel', argumentNames, argumentTypes, argumentSizes, argumentBitRatios, leadingReturnStatement, followingReturnStatement, }); if (typeof source === 'object' && source.functionNodes) { return new FunctionBuilder().fromJSON(source.functionNodes, FunctionNode); } const rootNode = new FunctionNode(source, rootNodeOptions); let functionNodes = null; if (functions) { functionNodes = functions.map((fn) => new FunctionNode(fn.source, { returnType: fn.returnType, argumentTypes: fn.argumentTypes, output, plugins, constants, constantTypes, constantBitRatios, optimizeFloatMemory, precision, lookupReturnType, lookupFunctionArgumentTypes, lookupFunctionArgumentName, lookupFunctionArgumentBitRatio, needsArgumentType, assignArgumentType, triggerImplyArgumentType, triggerImplyArgumentBitRatio, onFunctionCall, onNestedFunction, })); } let subKernelNodes = null; if (subKernels) { subKernelNodes = subKernels.map((subKernel) => { const { name, source } = subKernel; return new FunctionNode(source, Object.assign({}, nodeOptions, { name, isSubKernel: true, isRootKernel: false, })); }); } const functionBuilder = new FunctionBuilder({ kernel, rootNode, functionNodes, nativeFunctions, subKernelNodes }); return functionBuilder; } /** * * @param {IFunctionBuilderSettings} [settings] */ constructor(settings) { settings = settings || {}; this.kernel = settings.kernel; this.rootNode = settings.rootNode; this.functionNodes = settings.functionNodes || []; this.subKernelNodes = settings.subKernelNodes || []; this.nativeFunctions = settings.nativeFunctions || []; this.functionMap = {}; this.nativeFunctionNames = []; this.lookupChain = []; this.functionNodeDependencies = {}; this.functionCalls = {}; if (this.rootNode) { this.functionMap['kernel'] = this.rootNode; } if (this.functionNodes) { for (let i = 0; i < this.functionNodes.length; i++) { this.functionMap[this.functionNodes[i].name] = this.functionNodes[i]; } } if (this.subKernelNodes) { for (let i = 0; i < this.subKernelNodes.length; i++) { this.functionMap[this.subKernelNodes[i].name] = this.subKernelNodes[i]; } } if (this.nativeFunctions) { for (let i = 0; i < this.nativeFunctions.length; i++) { const nativeFunction = this.nativeFunctions[i]; this.nativeFunctionNames.push(nativeFunction.name); } } } /** * @desc Add the function node directly * * @param {FunctionNode} functionNode - functionNode to add * */ addFunctionNode(functionNode) { if (!functionNode.name) throw new Error('functionNode.name needs set'); this.functionMap[functionNode.name] = functionNode; if (functionNode.isRootKernel) { this.rootNode = functionNode; } } /** * @desc Trace all the depending functions being called, from a single function * * This allow for 'unneeded' functions to be automatically optimized out. * Note that the 0-index, is the starting function trace. * * @param {String} functionName - Function name to trace from, default to 'kernel' * @param {String[]} [retList] - Returning list of function names that is traced. Including itself. * * @returns {String[]} Returning list of function names that is traced. Including itself. */ traceFunctionCalls(functionName, retList) { functionName = functionName || 'kernel'; retList = retList || []; if (this.nativeFunctionNames.indexOf(functionName) > -1) { const nativeFunctionIndex = retList.indexOf(functionName); if (nativeFunctionIndex === -1) { retList.push(functionName); } else { /** * https://github.com/gpujs/gpu.js/issues/207 * if dependent function is already in the list, because a function depends on it, and because it has * already been traced, we know that we must move the dependent function to the end of the the retList. * */ const dependantNativeFunctionName = retList.splice(nativeFunctionIndex, 1)[0]; retList.push(dependantNativeFunctionName); } return retList; } const functionNode = this.functionMap[functionName]; if (functionNode) { // Check if function already exists const functionIndex = retList.indexOf(functionName); if (functionIndex === -1) { retList.push(functionName); functionNode.toString(); //ensure JS trace is done for (let i = 0; i < functionNode.calledFunctions.length; ++i) { this.traceFunctionCalls(functionNode.calledFunctions[i], retList); } } else { /** * https://github.com/gpujs/gpu.js/issues/207 * if dependent function is already in the list, because a function depends on it, and because it has * already been traced, we know that we must move the dependent function to the end of the the retList. * */ const dependantFunctionName = retList.splice(functionIndex, 1)[0]; retList.push(dependantFunctionName); } } return retList; } /** * @desc Return the string for a function * @param {String} functionName - Function name to trace from. If null, it returns the WHOLE builder stack * @returns {String} The full string, of all the various functions. Trace optimized if functionName given */ getPrototypeString(functionName) { return this.getPrototypes(functionName).join('\n'); } /** * @desc Return the string for a function * @param {String} [functionName] - Function name to trace from. If null, it returns the WHOLE builder stack * @returns {Array} The full string, of all the various functions. Trace optimized if functionName given */ getPrototypes(functionName) { if (this.rootNode) { this.rootNode.toString(); } if (functionName) { return this.getPrototypesFromFunctionNames(this.traceFunctionCalls(functionName, []).reverse()); } return this.getPrototypesFromFunctionNames(Object.keys(this.functionMap)); } /** * @desc Get string from function names * @param {String[]} functionList - List of function to build string * @returns {String} The string, of all the various functions. Trace optimized if functionName given */ getStringFromFunctionNames(functionList) { const ret = []; for (let i = 0; i < functionList.length; ++i) { const node = this.functionMap[functionList[i]]; if (node) { ret.push(this.functionMap[functionList[i]].toString()); } } return ret.join('\n'); } /** * @desc Return string of all functions converted * @param {String[]} functionList - List of function names to build the string. * @returns {Array} Prototypes of all functions converted */ getPrototypesFromFunctionNames(functionList) { const ret = []; for (let i = 0; i < functionList.length; ++i) { const functionName = functionList[i]; const functionIndex = this.nativeFunctionNames.indexOf(functionName); if (functionIndex > -1) { ret.push(this.nativeFunctions[functionIndex].source); continue; } const node = this.functionMap[functionName]; if (node) { ret.push(node.toString()); } } return ret; } toJSON() { return this.traceFunctionCalls(this.rootNode.name).reverse().map(name => { const nativeIndex = this.nativeFunctions.indexOf(name); if (nativeIndex > -1) { return { name, source: this.nativeFunctions[nativeIndex].source }; } else if (this.functionMap[name]) { return this.functionMap[name].toJSON(); } else { throw new Error(`function ${ name } not found`); } }); } fromJSON(jsonFunctionNodes, FunctionNode) { this.functionMap = {}; for (let i = 0; i < jsonFunctionNodes.length; i++) { const jsonFunctionNode = jsonFunctionNodes[i]; this.functionMap[jsonFunctionNode.settings.name] = new FunctionNode(jsonFunctionNode.ast, jsonFunctionNode.settings); } return this; } /** * @desc Get string for a particular function name * @param {String} functionName - Function name to trace from. If null, it returns the WHOLE builder stack * @returns {String} settings - The string, of all the various functions. Trace optimized if functionName given */ getString(functionName) { if (functionName) { return this.getStringFromFunctionNames(this.traceFunctionCalls(functionName).reverse()); } return this.getStringFromFunctionNames(Object.keys(this.functionMap)); } lookupReturnType(functionName, ast, requestingNode) { if (ast.type !== 'CallExpression') { throw new Error(`expected ast type of "CallExpression", but is ${ ast.type }`); } if (this._isNativeFunction(functionName)) { return this._lookupNativeFunctionReturnType(functionName); } else if (this._isFunction(functionName)) { const node = this._getFunction(functionName); if (node.returnType) { return node.returnType; } else { for (let i = 0; i < this.lookupChain.length; i++) { // detect circlical logic if (this.lookupChain[i].ast === ast) { // detect if arguments have not resolved, preventing a return type // if so, go ahead and resolve them, so we can resolve the return type if (node.argumentTypes.length === 0 && ast.arguments.length > 0) { const args = ast.arguments; for (let j = 0; j < args.length; j++) { this.lookupChain.push({ name: requestingNode.name, ast: args[i], requestingNode }); node.argumentTypes[j] = requestingNode.getType(args[j]); this.lookupChain.pop(); } return node.returnType = node.getType(node.getJsAST()); } throw new Error('circlical logic detected!'); } } // get ready for a ride! this.lookupChain.push({ name: requestingNode.name, ast, requestingNode }); const type = node.getType(node.getJsAST()); this.lookupChain.pop(); return node.returnType = type; } } return null; } /** * * @param {String} functionName * @return {FunctionNode} * @private */ _getFunction(functionName) { if (!this._isFunction(functionName)) { new Error(`Function ${functionName} not found`); } return this.functionMap[functionName]; } _isFunction(functionName) { return Boolean(this.functionMap[functionName]); } _getNativeFunction(functionName) { for (let i = 0; i < this.nativeFunctions.length; i++) { if (this.nativeFunctions[i].name === functionName) return this.nativeFunctions[i]; } return null; } _isNativeFunction(functionName) { return Boolean(this._getNativeFunction(functionName)); } _lookupNativeFunctionReturnType(functionName) { let nativeFunction = this._getNativeFunction(functionName); if (nativeFunction) { return nativeFunction.returnType; } throw new Error(`Native function ${ functionName } not found`); } lookupFunctionArgumentTypes(functionName) { if (this._isNativeFunction(functionName)) { return this._getNativeFunction(functionName).argumentTypes; } else if (this._isFunction(functionName)) { return this._getFunction(functionName).argumentTypes; } return null; } lookupFunctionArgumentName(functionName, argumentIndex) { return this._getFunction(functionName).argumentNames[argumentIndex]; } /** * * @param {string} functionName * @param {string} argumentName * @return {number} */ lookupFunctionArgumentBitRatio(functionName, argumentName) { if (!this._isFunction(functionName)) { throw new Error('function not found'); } if (this.rootNode.name === functionName) { const i = this.rootNode.argumentNames.indexOf(argumentName); if (i !== -1) { return this.rootNode.argumentBitRatios[i]; } } const node = this._getFunction(functionName); const i = node.argumentNames.indexOf(argumentName); if (i === -1) { throw new Error('argument not found'); } const bitRatio = node.argumentBitRatios[i]; if (typeof bitRatio !== 'number') { throw new Error('argument bit ratio not found'); } return bitRatio; } needsArgumentType(functionName, i) { if (!this._isFunction(functionName)) return false; const fnNode = this._getFunction(functionName); return !fnNode.argumentTypes[i]; } assignArgumentType(functionName, i, argumentType, requestingNode) { if (!this._isFunction(functionName)) return; const fnNode = this._getFunction(functionName); if (!fnNode.argumentTypes[i]) { fnNode.argumentTypes[i] = argumentType; } } /** * @param {string} functionName * @param {string} argumentName * @param {string} calleeFunctionName * @param {number} argumentIndex * @return {number|null} */ assignArgumentBitRatio(functionName, argumentName, calleeFunctionName, argumentIndex) { const node = this._getFunction(functionName); if (this._isNativeFunction(calleeFunctionName)) return null; const calleeNode = this._getFunction(calleeFunctionName); const i = node.argumentNames.indexOf(argumentName); if (i === -1) { throw new Error(`Argument ${argumentName} not found in arguments from function ${functionName}`); } const bitRatio = node.argumentBitRatios[i]; if (typeof bitRatio !== 'number') { throw new Error(`Bit ratio for argument ${argumentName} not found in function ${functionName}`); } if (!calleeNode.argumentBitRatios) { calleeNode.argumentBitRatios = new Array(calleeNode.argumentNames.length); } const calleeBitRatio = calleeNode.argumentBitRatios[i]; if (typeof calleeBitRatio === 'number') { if (calleeBitRatio !== bitRatio) { throw new Error(`Incompatible bit ratio found at function ${functionName} at argument ${argumentName}`); } return calleeBitRatio; } calleeNode.argumentBitRatios[i] = bitRatio; return bitRatio; } trackFunctionCall(functionName, calleeFunctionName, args) { if (!this.functionNodeDependencies[functionName]) { this.functionNodeDependencies[functionName] = new Set(); this.functionCalls[functionName] = []; } this.functionNodeDependencies[functionName].add(calleeFunctionName); this.functionCalls[functionName].push(args); } getKernelResultType() { return this.rootNode.returnType || this.rootNode.getType(this.rootNode.ast); } getSubKernelResultType(index) { const subKernelNode = this.subKernelNodes[index]; let called = false; for (let functionCallIndex = 0; functionCallIndex < this.rootNode.functionCalls.length; functionCallIndex++) { const functionCall = this.rootNode.functionCalls[functionCallIndex]; if (functionCall.ast.callee.name === subKernelNode.name) { called = true; } } if (!called) { throw new Error(`SubKernel ${ subKernelNode.name } never called by kernel`); } return subKernelNode.returnType || subKernelNode.getType(subKernelNode.getJsAST()); } getReturnTypes() { const result = { [this.rootNode.name]: this.rootNode.getType(this.rootNode.ast), }; const list = this.traceFunctionCalls(this.rootNode.name); for (let i = 0; i < list.length; i++) { const functionName = list[i]; const functionNode = this.functionMap[functionName]; result[functionName] = functionNode.getType(functionNode.ast); } return result; } } module.exports = { FunctionBuilder }; ================================================ FILE: src/backend/function-node.js ================================================ const acorn = require('acorn'); const { utils } = require('../utils'); const { FunctionTracer } = require('./function-tracer'); /** * * @desc Represents a single function, inside JS, webGL, or openGL. *

This handles all the raw state, converted state, etc. Of a single function.

*/ class FunctionNode { /** * * @param {string|object} source * @param {IFunctionSettings} [settings] */ constructor(source, settings) { if (!source && !settings.ast) { throw new Error('source parameter is missing'); } settings = settings || {}; this.source = source; this.ast = null; this.name = typeof source === 'string' ? settings.isRootKernel ? 'kernel' : (settings.name || utils.getFunctionNameFromString(source)) : null; this.calledFunctions = []; this.constants = {}; this.constantTypes = {}; this.constantBitRatios = {}; this.isRootKernel = false; this.isSubKernel = false; this.debug = null; this.functions = null; this.identifiers = null; this.contexts = null; this.functionCalls = null; this.states = []; this.needsArgumentType = null; this.assignArgumentType = null; this.lookupReturnType = null; this.lookupFunctionArgumentTypes = null; this.lookupFunctionArgumentBitRatio = null; this.triggerImplyArgumentType = null; this.triggerImplyArgumentBitRatio = null; this.onNestedFunction = null; this.onFunctionCall = null; this.optimizeFloatMemory = null; this.precision = null; this.loopMaxIterations = null; this.argumentNames = (typeof this.source === 'string' ? utils.getArgumentNamesFromString(this.source) : null); this.argumentTypes = []; this.argumentSizes = []; this.argumentBitRatios = null; this.returnType = null; this.output = []; this.plugins = null; this.leadingReturnStatement = null; this.followingReturnStatement = null; this.dynamicOutput = null; this.dynamicArguments = null; this.strictTypingChecking = false; this.fixIntegerDivisionAccuracy = null; if (settings) { for (const p in settings) { if (!settings.hasOwnProperty(p)) continue; if (!this.hasOwnProperty(p)) continue; this[p] = settings[p]; } } this.literalTypes = {}; this.validate(); this._string = null; this._internalVariableNames = {}; } validate() { if (typeof this.source !== 'string' && !this.ast) { throw new Error('this.source not a string'); } if (!this.ast && !utils.isFunctionString(this.source)) { throw new Error('this.source not a function string'); } if (!this.name) { throw new Error('this.name could not be set'); } if (this.argumentTypes.length > 0 && this.argumentTypes.length !== this.argumentNames.length) { throw new Error(`argumentTypes count of ${ this.argumentTypes.length } exceeds ${ this.argumentNames.length }`); } if (this.output.length < 1) { throw new Error('this.output is not big enough'); } } /** * @param {String} name * @returns {boolean} */ isIdentifierConstant(name) { if (!this.constants) return false; return this.constants.hasOwnProperty(name); } isInput(argumentName) { return this.argumentTypes[this.argumentNames.indexOf(argumentName)] === 'Input'; } pushState(state) { this.states.push(state); } popState(state) { if (this.state !== state) { throw new Error(`Cannot popState ${ state } when in ${ this.state }`); } this.states.pop(); } isState(state) { return this.state === state; } get state() { return this.states[this.states.length - 1]; } /** * @function * @name astMemberExpressionUnroll * @desc Parses the abstract syntax tree for binary expression. * *

Utility function for astCallExpression.

* * @param {Object} ast - the AST object to parse * * @returns {String} the function namespace call, unrolled */ astMemberExpressionUnroll(ast) { if (ast.type === 'Identifier') { return ast.name; } else if (ast.type === 'ThisExpression') { return 'this'; } if (ast.type === 'MemberExpression') { if (ast.object && ast.property) { //babel sniffing if (ast.object.hasOwnProperty('name') && ast.object.name !== 'Math') { return this.astMemberExpressionUnroll(ast.property); } return ( this.astMemberExpressionUnroll(ast.object) + '.' + this.astMemberExpressionUnroll(ast.property) ); } } //babel sniffing if (ast.hasOwnProperty('expressions')) { const firstExpression = ast.expressions[0]; if (firstExpression.type === 'Literal' && firstExpression.value === 0 && ast.expressions.length === 2) { return this.astMemberExpressionUnroll(ast.expressions[1]); } } // Failure, unknown expression throw this.astErrorOutput('Unknown astMemberExpressionUnroll', ast); } /** * @desc Parses the class function JS, and returns its Abstract Syntax Tree object. * This is used internally to convert to shader code * * @param {Object} [inParser] - Parser to use, assumes in scope 'parser' if null or undefined * * @returns {Object} The function AST Object, note that result is cached under this.ast; */ getJsAST(inParser) { if (this.ast) { return this.ast; } if (typeof this.source === 'object') { this.traceFunctionAST(this.source); return this.ast = this.source; } inParser = inParser || acorn; if (inParser === null) { throw new Error('Missing JS to AST parser'); } const ast = Object.freeze(inParser.parse(`const parser_${ this.name } = ${ this.source };`, { locations: true })); // take out the function object, outside the var declarations const functionAST = ast.body[0].declarations[0].init; this.traceFunctionAST(functionAST); if (!ast) { throw new Error('Failed to parse JS code'); } return this.ast = functionAST; } traceFunctionAST(ast) { const { contexts, declarations, functions, identifiers, functionCalls } = new FunctionTracer(ast); this.contexts = contexts; this.identifiers = identifiers; this.functionCalls = functionCalls; this.functions = functions; for (let i = 0; i < declarations.length; i++) { const declaration = declarations[i]; const { ast, inForLoopInit, inForLoopTest } = declaration; const { init } = ast; const dependencies = this.getDependencies(init); let valueType = null; if (inForLoopInit && inForLoopTest) { valueType = 'Integer'; } else { if (init) { const realType = this.getType(init); switch (realType) { case 'Integer': case 'Float': case 'Number': if (init.type === 'MemberExpression') { valueType = realType; } else { valueType = 'Number'; } break; case 'LiteralInteger': valueType = 'Number'; break; default: valueType = realType; } } } declaration.valueType = valueType; declaration.dependencies = dependencies; declaration.isSafe = this.isSafeDependencies(dependencies); } for (let i = 0; i < functions.length; i++) { this.onNestedFunction(functions[i], this.source); } } getDeclaration(ast) { for (let i = 0; i < this.identifiers.length; i++) { const identifier = this.identifiers[i]; if (ast === identifier.ast) { return identifier.declaration; } } return null; } /** * @desc Return the type of parameter sent to subKernel/Kernel. * @param {Object} ast - Identifier * @returns {String} Type of the parameter */ getVariableType(ast) { if (ast.type !== 'Identifier') { throw new Error(`ast of ${ast.type} not "Identifier"`); } let type = null; const argumentIndex = this.argumentNames.indexOf(ast.name); if (argumentIndex === -1) { const declaration = this.getDeclaration(ast); if (declaration) { return declaration.valueType; } } else { const argumentType = this.argumentTypes[argumentIndex]; if (argumentType) { type = argumentType; } } if (!type && this.strictTypingChecking) { throw new Error(`Declaration of ${name} not found`); } return type; } /** * Generally used to lookup the value type returned from a member expressions * @param {String} type * @return {String} */ getLookupType(type) { if (!typeLookupMap.hasOwnProperty(type)) { throw new Error(`unknown typeLookupMap ${ type }`); } return typeLookupMap[type]; } getConstantType(constantName) { if (this.constantTypes[constantName]) { const type = this.constantTypes[constantName]; if (type === 'Float') { return 'Number'; } else { return type; } } throw new Error(`Type for constant "${ constantName }" not declared`); } toString() { if (this._string) return this._string; return this._string = this.astGeneric(this.getJsAST(), []).join('').trim(); } toJSON() { const settings = { source: this.source, name: this.name, constants: this.constants, constantTypes: this.constantTypes, isRootKernel: this.isRootKernel, isSubKernel: this.isSubKernel, debug: this.debug, output: this.output, loopMaxIterations: this.loopMaxIterations, argumentNames: this.argumentNames, argumentTypes: this.argumentTypes, argumentSizes: this.argumentSizes, returnType: this.returnType, leadingReturnStatement: this.leadingReturnStatement, followingReturnStatement: this.followingReturnStatement, }; return { ast: this.ast, settings }; } /** * Recursively looks up type for ast expression until it's found * @param ast * @returns {String|null} */ getType(ast) { if (Array.isArray(ast)) { return this.getType(ast[ast.length - 1]); } switch (ast.type) { case 'BlockStatement': return this.getType(ast.body); case 'ArrayExpression': const childType = this.getType(ast.elements[0]); switch (childType) { case 'Array(2)': case 'Array(3)': case 'Array(4)': return `Matrix(${ast.elements.length})`; } return `Array(${ ast.elements.length })`; case 'Literal': const literalKey = this.astKey(ast); if (this.literalTypes[literalKey]) { return this.literalTypes[literalKey]; } if (Number.isInteger(ast.value)) { return 'LiteralInteger'; } else if (ast.value === true || ast.value === false) { return 'Boolean'; } else { return 'Number'; } case 'AssignmentExpression': return this.getType(ast.left); case 'CallExpression': if (this.isAstMathFunction(ast)) { return 'Number'; } if (!ast.callee || !ast.callee.name) { if (ast.callee.type === 'SequenceExpression' && ast.callee.expressions[ast.callee.expressions.length - 1].property.name) { const functionName = ast.callee.expressions[ast.callee.expressions.length - 1].property.name; this.inferArgumentTypesIfNeeded(functionName, ast.arguments); return this.lookupReturnType(functionName, ast, this); } if (this.getVariableSignature(ast.callee, true) === 'this.color') { return null; } if (ast.callee.type === 'MemberExpression' && ast.callee.object && ast.callee.property && ast.callee.property.name && ast.arguments) { const functionName = ast.callee.property.name; this.inferArgumentTypesIfNeeded(functionName, ast.arguments); return this.lookupReturnType(functionName, ast, this); } throw this.astErrorOutput('Unknown call expression', ast); } if (ast.callee && ast.callee.name) { const functionName = ast.callee.name; this.inferArgumentTypesIfNeeded(functionName, ast.arguments); return this.lookupReturnType(functionName, ast, this); } throw this.astErrorOutput(`Unhandled getType Type "${ ast.type }"`, ast); case 'LogicalExpression': return 'Boolean'; case 'BinaryExpression': // modulos is Number switch (ast.operator) { case '%': case '/': if (this.fixIntegerDivisionAccuracy) { return 'Number'; } else { break; } case '>': case '<': return 'Boolean'; case '&': case '|': case '^': case '<<': case '>>': case '>>>': return 'Integer'; } const type = this.getType(ast.left); if (this.isState('skip-literal-correction')) return type; if (type === 'LiteralInteger') { const rightType = this.getType(ast.right); if (rightType === 'LiteralInteger') { if (ast.left.value % 1 === 0) { return 'Integer'; } else { return 'Float'; } } return rightType; } return typeLookupMap[type] || type; case 'UpdateExpression': return this.getType(ast.argument); case 'UnaryExpression': if (ast.operator === '~') { return 'Integer'; } return this.getType(ast.argument); case 'VariableDeclaration': { const declarations = ast.declarations; let lastType; for (let i = 0; i < declarations.length; i++) { const declaration = declarations[i]; lastType = this.getType(declaration); } if (!lastType) { throw this.astErrorOutput(`Unable to find type for declaration`, ast); } return lastType; } case 'VariableDeclarator': const declaration = this.getDeclaration(ast.id); if (!declaration) { throw this.astErrorOutput(`Unable to find declarator`, ast); } if (!declaration.valueType) { throw this.astErrorOutput(`Unable to find declarator valueType`, ast); } return declaration.valueType; case 'Identifier': if (ast.name === 'Infinity') { return 'Number'; } if (this.isAstVariable(ast)) { const signature = this.getVariableSignature(ast); if (signature === 'value') { return this.getCheckVariableType(ast); } } const origin = this.findIdentifierOrigin(ast); if (origin && origin.init) { return this.getType(origin.init); } return null; case 'ReturnStatement': return this.getType(ast.argument); case 'MemberExpression': if (this.isAstMathFunction(ast)) { switch (ast.property.name) { case 'ceil': return 'Integer'; case 'floor': return 'Integer'; case 'round': return 'Integer'; } return 'Number'; } if (this.isAstVariable(ast)) { const variableSignature = this.getVariableSignature(ast); switch (variableSignature) { case 'value[]': return this.getLookupType(this.getCheckVariableType(ast.object)); case 'value[][]': return this.getLookupType(this.getCheckVariableType(ast.object.object)); case 'value[][][]': return this.getLookupType(this.getCheckVariableType(ast.object.object.object)); case 'value[][][][]': return this.getLookupType(this.getCheckVariableType(ast.object.object.object.object)); case 'value.thread.value': case 'this.thread.value': return 'Integer'; case 'this.output.value': return this.dynamicOutput ? 'Integer' : 'LiteralInteger'; case 'this.constants.value': return this.getConstantType(ast.property.name); case 'this.constants.value[]': return this.getLookupType(this.getConstantType(ast.object.property.name)); case 'this.constants.value[][]': return this.getLookupType(this.getConstantType(ast.object.object.property.name)); case 'this.constants.value[][][]': return this.getLookupType(this.getConstantType(ast.object.object.object.property.name)); case 'this.constants.value[][][][]': return this.getLookupType(this.getConstantType(ast.object.object.object.object.property.name)); case 'fn()[]': case 'fn()[][]': case 'fn()[][][]': return this.getLookupType(this.getType(ast.object)); case 'value.value': if (this.isAstMathVariable(ast)) { return 'Number'; } switch (ast.property.name) { case 'r': case 'g': case 'b': case 'a': return this.getLookupType(this.getCheckVariableType(ast.object)); } case '[][]': return 'Number'; } throw this.astErrorOutput('Unhandled getType MemberExpression', ast); } throw this.astErrorOutput('Unhandled getType MemberExpression', ast); case 'ConditionalExpression': return this.getType(ast.consequent); case 'FunctionDeclaration': case 'FunctionExpression': const lastReturn = this.findLastReturn(ast.body); if (lastReturn) { return this.getType(lastReturn); } return null; case 'IfStatement': return this.getType(ast.consequent); case 'SequenceExpression': return this.getType(ast.expressions[ast.expressions.length - 1]); default: throw this.astErrorOutput(`Unhandled getType Type "${ ast.type }"`, ast); } } getCheckVariableType(ast) { const type = this.getVariableType(ast); if (!type) { throw this.astErrorOutput(`${ast.type} is not defined`, ast); } return type; } inferArgumentTypesIfNeeded(functionName, args) { // ensure arguments are filled in, so when we lookup return type, we already can infer it for (let i = 0; i < args.length; i++) { if (!this.needsArgumentType(functionName, i)) continue; const type = this.getType(args[i]); if (!type) { throw this.astErrorOutput(`Unable to infer argument ${i}`, args[i]); } this.assignArgumentType(functionName, i, type); } } isAstMathVariable(ast) { const mathProperties = [ 'E', 'PI', 'SQRT2', 'SQRT1_2', 'LN2', 'LN10', 'LOG2E', 'LOG10E', ]; return ast.type === 'MemberExpression' && ast.object && ast.object.type === 'Identifier' && ast.object.name === 'Math' && ast.property && ast.property.type === 'Identifier' && mathProperties.indexOf(ast.property.name) > -1; } isAstMathFunction(ast) { const mathFunctions = [ 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'clz32', 'cos', 'cosh', 'expm1', 'exp', 'floor', 'fround', 'imul', 'log', 'log2', 'log10', 'log1p', 'max', 'min', 'pow', 'random', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc', ]; return ast.type === 'CallExpression' && ast.callee && ast.callee.type === 'MemberExpression' && ast.callee.object && ast.callee.object.type === 'Identifier' && ast.callee.object.name === 'Math' && ast.callee.property && ast.callee.property.type === 'Identifier' && mathFunctions.indexOf(ast.callee.property.name) > -1; } isAstVariable(ast) { return ast.type === 'Identifier' || ast.type === 'MemberExpression'; } isSafe(ast) { return this.isSafeDependencies(this.getDependencies(ast)); } isSafeDependencies(dependencies) { return dependencies && dependencies.every ? dependencies.every(dependency => dependency.isSafe) : true; } /** * * @param ast * @param dependencies * @param isNotSafe * @return {Array} */ getDependencies(ast, dependencies, isNotSafe) { if (!dependencies) { dependencies = []; } if (!ast) return null; if (Array.isArray(ast)) { for (let i = 0; i < ast.length; i++) { this.getDependencies(ast[i], dependencies, isNotSafe); } return dependencies; } switch (ast.type) { case 'AssignmentExpression': this.getDependencies(ast.left, dependencies, isNotSafe); this.getDependencies(ast.right, dependencies, isNotSafe); return dependencies; case 'ConditionalExpression': this.getDependencies(ast.test, dependencies, isNotSafe); this.getDependencies(ast.alternate, dependencies, isNotSafe); this.getDependencies(ast.consequent, dependencies, isNotSafe); return dependencies; case 'Literal': dependencies.push({ origin: 'literal', value: ast.value, isSafe: isNotSafe === true ? false : ast.value > -Infinity && ast.value < Infinity && !isNaN(ast.value) }); break; case 'VariableDeclarator': return this.getDependencies(ast.init, dependencies, isNotSafe); case 'Identifier': const declaration = this.getDeclaration(ast); if (declaration) { dependencies.push({ name: ast.name, origin: 'declaration', isSafe: isNotSafe ? false : this.isSafeDependencies(declaration.dependencies), }); } else if (this.argumentNames.indexOf(ast.name) > -1) { dependencies.push({ name: ast.name, origin: 'argument', isSafe: false, }); } else if (this.strictTypingChecking) { throw new Error(`Cannot find identifier origin "${ast.name}"`); } break; case 'FunctionDeclaration': return this.getDependencies(ast.body.body[ast.body.body.length - 1], dependencies, isNotSafe); case 'ReturnStatement': return this.getDependencies(ast.argument, dependencies); case 'BinaryExpression': case 'LogicalExpression': isNotSafe = (ast.operator === '/' || ast.operator === '*'); this.getDependencies(ast.left, dependencies, isNotSafe); this.getDependencies(ast.right, dependencies, isNotSafe); return dependencies; case 'UnaryExpression': case 'UpdateExpression': return this.getDependencies(ast.argument, dependencies, isNotSafe); case 'VariableDeclaration': return this.getDependencies(ast.declarations, dependencies, isNotSafe); case 'ArrayExpression': dependencies.push({ origin: 'declaration', isSafe: true, }); return dependencies; case 'CallExpression': dependencies.push({ origin: 'function', isSafe: true, }); return dependencies; case 'MemberExpression': const details = this.getMemberExpressionDetails(ast); switch (details.signature) { case 'value[]': this.getDependencies(ast.object, dependencies, isNotSafe); break; case 'value[][]': this.getDependencies(ast.object.object, dependencies, isNotSafe); break; case 'value[][][]': this.getDependencies(ast.object.object.object, dependencies, isNotSafe); break; case 'this.output.value': if (this.dynamicOutput) { dependencies.push({ name: details.name, origin: 'output', isSafe: false, }); } break; } if (details) { if (details.property) { this.getDependencies(details.property, dependencies, isNotSafe); } if (details.xProperty) { this.getDependencies(details.xProperty, dependencies, isNotSafe); } if (details.yProperty) { this.getDependencies(details.yProperty, dependencies, isNotSafe); } if (details.zProperty) { this.getDependencies(details.zProperty, dependencies, isNotSafe); } return dependencies; } case 'SequenceExpression': return this.getDependencies(ast.expressions, dependencies, isNotSafe); default: throw this.astErrorOutput(`Unhandled type ${ ast.type } in getDependencies`, ast); } return dependencies; } getVariableSignature(ast, returnRawValue) { if (!this.isAstVariable(ast)) { throw new Error(`ast of type "${ ast.type }" is not a variable signature`); } if (ast.type === 'Identifier') { return 'value'; } const signature = []; while (true) { if (!ast) break; if (ast.computed) { signature.push('[]'); } else if (ast.type === 'ThisExpression') { signature.unshift('this'); } else if (ast.property && ast.property.name) { if ( ast.property.name === 'x' || ast.property.name === 'y' || ast.property.name === 'z' ) { signature.unshift(returnRawValue ? '.' + ast.property.name : '.value'); } else if ( ast.property.name === 'constants' || ast.property.name === 'thread' || ast.property.name === 'output' ) { signature.unshift('.' + ast.property.name); } else { signature.unshift(returnRawValue ? '.' + ast.property.name : '.value'); } } else if (ast.name) { signature.unshift(returnRawValue ? ast.name : 'value'); } else if (ast.callee && ast.callee.name) { signature.unshift(returnRawValue ? ast.callee.name + '()' : 'fn()'); } else if (ast.elements) { signature.unshift('[]'); } else { signature.unshift('unknown'); } ast = ast.object; } const signatureString = signature.join(''); if (returnRawValue) { return signatureString; } const allowedExpressions = [ 'value', 'value[]', 'value[][]', 'value[][][]', 'value[][][][]', 'value.value', 'value.thread.value', 'this.thread.value', 'this.output.value', 'this.constants.value', 'this.constants.value[]', 'this.constants.value[][]', 'this.constants.value[][][]', 'this.constants.value[][][][]', 'fn()[]', 'fn()[][]', 'fn()[][][]', '[][]', ]; if (allowedExpressions.indexOf(signatureString) > -1) { return signatureString; } return null; } build() { return this.toString().length > 0; } /** * @desc Parses the abstract syntax tree for generically to its respective function * @param {Object} ast - the AST object to parse * @param {Array} retArr - return array string * @returns {Array} the parsed string array */ astGeneric(ast, retArr) { if (ast === null) { throw this.astErrorOutput('NULL ast', ast); } else { if (Array.isArray(ast)) { for (let i = 0; i < ast.length; i++) { this.astGeneric(ast[i], retArr); } return retArr; } switch (ast.type) { case 'FunctionDeclaration': return this.astFunctionDeclaration(ast, retArr); case 'FunctionExpression': return this.astFunctionExpression(ast, retArr); case 'ReturnStatement': return this.astReturnStatement(ast, retArr); case 'Literal': return this.astLiteral(ast, retArr); case 'BinaryExpression': return this.astBinaryExpression(ast, retArr); case 'Identifier': return this.astIdentifierExpression(ast, retArr); case 'AssignmentExpression': return this.astAssignmentExpression(ast, retArr); case 'ExpressionStatement': return this.astExpressionStatement(ast, retArr); case 'EmptyStatement': return this.astEmptyStatement(ast, retArr); case 'BlockStatement': return this.astBlockStatement(ast, retArr); case 'IfStatement': return this.astIfStatement(ast, retArr); case 'SwitchStatement': return this.astSwitchStatement(ast, retArr); case 'BreakStatement': return this.astBreakStatement(ast, retArr); case 'ContinueStatement': return this.astContinueStatement(ast, retArr); case 'ForStatement': return this.astForStatement(ast, retArr); case 'WhileStatement': return this.astWhileStatement(ast, retArr); case 'DoWhileStatement': return this.astDoWhileStatement(ast, retArr); case 'VariableDeclaration': return this.astVariableDeclaration(ast, retArr); case 'VariableDeclarator': return this.astVariableDeclarator(ast, retArr); case 'ThisExpression': return this.astThisExpression(ast, retArr); case 'SequenceExpression': return this.astSequenceExpression(ast, retArr); case 'UnaryExpression': return this.astUnaryExpression(ast, retArr); case 'UpdateExpression': return this.astUpdateExpression(ast, retArr); case 'LogicalExpression': return this.astLogicalExpression(ast, retArr); case 'MemberExpression': return this.astMemberExpression(ast, retArr); case 'CallExpression': return this.astCallExpression(ast, retArr); case 'ArrayExpression': return this.astArrayExpression(ast, retArr); case 'DebuggerStatement': return this.astDebuggerStatement(ast, retArr); case 'ConditionalExpression': return this.astConditionalExpression(ast, retArr); } throw this.astErrorOutput('Unknown ast type : ' + ast.type, ast); } } /** * @desc To throw the AST error, with its location. * @param {string} error - the error message output * @param {Object} ast - the AST object where the error is */ astErrorOutput(error, ast) { if (typeof this.source !== 'string') { return new Error(error); } const debugString = utils.getAstString(this.source, ast); const leadingSource = this.source.substr(ast.start); const splitLines = leadingSource.split(/\n/); const lineBefore = splitLines.length > 0 ? splitLines[splitLines.length - 1] : 0; return new Error(`${error} on line ${ splitLines.length }, position ${ lineBefore.length }:\n ${ debugString }`); } astDebuggerStatement(arrNode, retArr) { return retArr; } astConditionalExpression(ast, retArr) { if (ast.type !== 'ConditionalExpression') { throw this.astErrorOutput('Not a conditional expression', ast); } retArr.push('('); this.astGeneric(ast.test, retArr); retArr.push('?'); this.astGeneric(ast.consequent, retArr); retArr.push(':'); this.astGeneric(ast.alternate, retArr); retArr.push(')'); return retArr; } /** * @abstract * @param {Object} ast * @param {String[]} retArr * @returns {String[]} */ astFunction(ast, retArr) { throw new Error(`"astFunction" not defined on ${ this.constructor.name }`); } /** * @desc Parses the abstract syntax tree for to its *named function declaration* * @param {Object} ast - the AST object to parse * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astFunctionDeclaration(ast, retArr) { if (this.isChildFunction(ast)) { return retArr; } return this.astFunction(ast, retArr); } astFunctionExpression(ast, retArr) { if (this.isChildFunction(ast)) { return retArr; } return this.astFunction(ast, retArr); } isChildFunction(ast) { for (let i = 0; i < this.functions.length; i++) { if (this.functions[i] === ast) { return true; } } return false; } astReturnStatement(ast, retArr) { return retArr; } astLiteral(ast, retArr) { this.literalTypes[this.astKey(ast)] = 'Number'; return retArr; } astBinaryExpression(ast, retArr) { return retArr; } astIdentifierExpression(ast, retArr) { return retArr; } astAssignmentExpression(ast, retArr) { return retArr; } /** * @desc Parses the abstract syntax tree for *generic expression* statement * @param {Object} esNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astExpressionStatement(esNode, retArr) { this.astGeneric(esNode.expression, retArr); retArr.push(';'); return retArr; } /** * @desc Parses the abstract syntax tree for an *Empty* Statement * @param {Object} eNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astEmptyStatement(eNode, retArr) { return retArr; } astBlockStatement(ast, retArr) { return retArr; } astIfStatement(ast, retArr) { return retArr; } astSwitchStatement(ast, retArr) { return retArr; } /** * @desc Parses the abstract syntax tree for *Break* Statement * @param {Object} brNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astBreakStatement(brNode, retArr) { retArr.push('break;'); return retArr; } /** * @desc Parses the abstract syntax tree for *Continue* Statement * @param {Object} crNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astContinueStatement(crNode, retArr) { retArr.push('continue;\n'); return retArr; } astForStatement(ast, retArr) { return retArr; } astWhileStatement(ast, retArr) { return retArr; } astDoWhileStatement(ast, retArr) { return retArr; } /** * @desc Parses the abstract syntax tree for *Variable Declarator* * @param {Object} iVarDecNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astVariableDeclarator(iVarDecNode, retArr) { this.astGeneric(iVarDecNode.id, retArr); if (iVarDecNode.init !== null) { retArr.push('='); this.astGeneric(iVarDecNode.init, retArr); } return retArr; } astThisExpression(ast, retArr) { return retArr; } astSequenceExpression(sNode, retArr) { const { expressions } = sNode; const sequenceResult = []; for (let i = 0; i < expressions.length; i++) { const expression = expressions[i]; const expressionResult = []; this.astGeneric(expression, expressionResult); sequenceResult.push(expressionResult.join('')); } if (sequenceResult.length > 1) { retArr.push('(', sequenceResult.join(','), ')'); } else { retArr.push(sequenceResult[0]); } return retArr; } /** * @desc Parses the abstract syntax tree for *Unary* Expression * @param {Object} uNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astUnaryExpression(uNode, retArr) { const unaryResult = this.checkAndUpconvertBitwiseUnary(uNode, retArr); if (unaryResult) { return retArr; } if (uNode.prefix) { retArr.push(uNode.operator); this.astGeneric(uNode.argument, retArr); } else { this.astGeneric(uNode.argument, retArr); retArr.push(uNode.operator); } return retArr; } checkAndUpconvertBitwiseUnary(uNode, retArr) {} /** * @desc Parses the abstract syntax tree for *Update* Expression * @param {Object} uNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astUpdateExpression(uNode, retArr) { if (uNode.prefix) { retArr.push(uNode.operator); this.astGeneric(uNode.argument, retArr); } else { this.astGeneric(uNode.argument, retArr); retArr.push(uNode.operator); } return retArr; } /** * @desc Parses the abstract syntax tree for *Logical* Expression * @param {Object} logNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astLogicalExpression(logNode, retArr) { retArr.push('('); this.astGeneric(logNode.left, retArr); retArr.push(logNode.operator); this.astGeneric(logNode.right, retArr); retArr.push(')'); return retArr; } astMemberExpression(ast, retArr) { return retArr; } astCallExpression(ast, retArr) { return retArr; } astArrayExpression(ast, retArr) { return retArr; } /** * * @param ast * @return {IFunctionNodeMemberExpressionDetails} */ getMemberExpressionDetails(ast) { if (ast.type !== 'MemberExpression') { throw this.astErrorOutput(`Expression ${ ast.type } not a MemberExpression`, ast); } let name = null; let type = null; const variableSignature = this.getVariableSignature(ast); switch (variableSignature) { case 'value': return null; case 'value.thread.value': case 'this.thread.value': case 'this.output.value': return { signature: variableSignature, type: 'Integer', name: ast.property.name }; case 'value[]': if (typeof ast.object.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.name; return { name, origin: 'user', signature: variableSignature, type: this.getVariableType(ast.object), xProperty: ast.property }; case 'value[][]': if (typeof ast.object.object.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.object.name; return { name, origin: 'user', signature: variableSignature, type: this.getVariableType(ast.object.object), yProperty: ast.object.property, xProperty: ast.property, }; case 'value[][][]': if (typeof ast.object.object.object.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.object.object.name; return { name, origin: 'user', signature: variableSignature, type: this.getVariableType(ast.object.object.object), zProperty: ast.object.object.property, yProperty: ast.object.property, xProperty: ast.property, }; case 'value[][][][]': if (typeof ast.object.object.object.object.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.object.object.object.name; return { name, origin: 'user', signature: variableSignature, type: this.getVariableType(ast.object.object.object.object), zProperty: ast.object.object.property, yProperty: ast.object.property, xProperty: ast.property, }; case 'value.value': if (typeof ast.property.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } if (this.isAstMathVariable(ast)) { name = ast.property.name; return { name, origin: 'Math', type: 'Number', signature: variableSignature, }; } switch (ast.property.name) { case 'r': case 'g': case 'b': case 'a': name = ast.object.name; return { name, property: ast.property.name, origin: 'user', signature: variableSignature, type: 'Number' }; default: throw this.astErrorOutput('Unexpected expression', ast); } case 'this.constants.value': if (typeof ast.property.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.property.name; type = this.getConstantType(name); if (!type) { throw this.astErrorOutput('Constant has no type', ast); } return { name, type, origin: 'constants', signature: variableSignature, }; case 'this.constants.value[]': if (typeof ast.object.property.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.property.name; type = this.getConstantType(name); if (!type) { throw this.astErrorOutput('Constant has no type', ast); } return { name, type, origin: 'constants', signature: variableSignature, xProperty: ast.property, }; case 'this.constants.value[][]': { if (typeof ast.object.object.property.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.object.property.name; type = this.getConstantType(name); if (!type) { throw this.astErrorOutput('Constant has no type', ast); } return { name, type, origin: 'constants', signature: variableSignature, yProperty: ast.object.property, xProperty: ast.property, }; } case 'this.constants.value[][][]': { if (typeof ast.object.object.object.property.name !== 'string') { throw this.astErrorOutput('Unexpected expression', ast); } name = ast.object.object.object.property.name; type = this.getConstantType(name); if (!type) { throw this.astErrorOutput('Constant has no type', ast); } return { name, type, origin: 'constants', signature: variableSignature, zProperty: ast.object.object.property, yProperty: ast.object.property, xProperty: ast.property, }; } case 'fn()[]': case 'fn()[][]': case '[][]': return { signature: variableSignature, property: ast.property, }; default: throw this.astErrorOutput('Unexpected expression', ast); } } findIdentifierOrigin(astToFind) { const stack = [this.ast]; while (stack.length > 0) { const atNode = stack[0]; if (atNode.type === 'VariableDeclarator' && atNode.id && atNode.id.name && atNode.id.name === astToFind.name) { return atNode; } stack.shift(); if (atNode.argument) { stack.push(atNode.argument); } else if (atNode.body) { stack.push(atNode.body); } else if (atNode.declarations) { stack.push(atNode.declarations); } else if (Array.isArray(atNode)) { for (let i = 0; i < atNode.length; i++) { stack.push(atNode[i]); } } } return null; } findLastReturn(ast) { const stack = [ast || this.ast]; while (stack.length > 0) { const atNode = stack.pop(); if (atNode.type === 'ReturnStatement') { return atNode; } if (atNode.type === 'FunctionDeclaration') { continue; } if (atNode.argument) { stack.push(atNode.argument); } else if (atNode.body) { stack.push(atNode.body); } else if (atNode.declarations) { stack.push(atNode.declarations); } else if (Array.isArray(atNode)) { for (let i = 0; i < atNode.length; i++) { stack.push(atNode[i]); } } else if (atNode.consequent) { stack.push(atNode.consequent); } else if (atNode.cases) { stack.push(atNode.cases); } } return null; } getInternalVariableName(name) { if (!this._internalVariableNames.hasOwnProperty(name)) { this._internalVariableNames[name] = 0; } this._internalVariableNames[name]++; if (this._internalVariableNames[name] === 1) { return name; } return name + this._internalVariableNames[name]; } astKey(ast, separator = ',') { if (!ast.start || !ast.end) throw new Error('AST start and end needed'); return `${ast.start}${separator}${ast.end}`; } } const typeLookupMap = { 'Number': 'Number', 'Float': 'Float', 'Integer': 'Integer', 'Array': 'Number', 'Array(2)': 'Number', 'Array(3)': 'Number', 'Array(4)': 'Number', 'Matrix(2)': 'Number', 'Matrix(3)': 'Number', 'Matrix(4)': 'Number', 'Array2D': 'Number', 'Array3D': 'Number', 'Input': 'Number', 'HTMLCanvas': 'Array(4)', 'OffscreenCanvas': 'Array(4)', 'HTMLImage': 'Array(4)', 'ImageBitmap': 'Array(4)', 'ImageData': 'Array(4)', 'HTMLVideo': 'Array(4)', 'HTMLImageArray': 'Array(4)', 'NumberTexture': 'Number', 'MemoryOptimizedNumberTexture': 'Number', 'Array1D(2)': 'Array(2)', 'Array1D(3)': 'Array(3)', 'Array1D(4)': 'Array(4)', 'Array2D(2)': 'Array(2)', 'Array2D(3)': 'Array(3)', 'Array2D(4)': 'Array(4)', 'Array3D(2)': 'Array(2)', 'Array3D(3)': 'Array(3)', 'Array3D(4)': 'Array(4)', 'ArrayTexture(1)': 'Number', 'ArrayTexture(2)': 'Array(2)', 'ArrayTexture(3)': 'Array(3)', 'ArrayTexture(4)': 'Array(4)', }; module.exports = { FunctionNode }; ================================================ FILE: src/backend/function-tracer.js ================================================ const { utils } = require('../utils'); function last(array) { return array.length > 0 ? array[array.length - 1] : null; } const states = { trackIdentifiers: 'trackIdentifiers', memberExpression: 'memberExpression', inForLoopInit: 'inForLoopInit' }; class FunctionTracer { constructor(ast) { this.runningContexts = []; this.functionContexts = []; this.contexts = []; this.functionCalls = []; /** * * @type {IDeclaration[]} */ this.declarations = []; this.identifiers = []; this.functions = []; this.returnStatements = []; this.trackedIdentifiers = null; this.states = []; this.newFunctionContext(); this.scan(ast); } isState(state) { return this.states[this.states.length - 1] === state; } hasState(state) { return this.states.indexOf(state) > -1; } pushState(state) { this.states.push(state); } popState(state) { if (this.isState(state)) { this.states.pop(); } else { throw new Error(`Cannot pop the non-active state "${state}"`); } } get currentFunctionContext() { return last(this.functionContexts); } get currentContext() { return last(this.runningContexts); } newFunctionContext() { const newContext = { '@contextType': 'function' }; this.contexts.push(newContext); this.functionContexts.push(newContext); } newContext(run) { const newContext = Object.assign({ '@contextType': 'const/let' }, this.currentContext); this.contexts.push(newContext); this.runningContexts.push(newContext); run(); const { currentFunctionContext } = this; for (const p in currentFunctionContext) { if (!currentFunctionContext.hasOwnProperty(p) || newContext.hasOwnProperty(p)) continue; newContext[p] = currentFunctionContext[p]; } this.runningContexts.pop(); return newContext; } useFunctionContext(run) { const functionContext = last(this.functionContexts); this.runningContexts.push(functionContext); run(); this.runningContexts.pop(); } getIdentifiers(run) { const trackedIdentifiers = this.trackedIdentifiers = []; this.pushState(states.trackIdentifiers); run(); this.trackedIdentifiers = null; this.popState(states.trackIdentifiers); return trackedIdentifiers; } /** * @param {string} name * @returns {IDeclaration} */ getDeclaration(name) { const { currentContext, currentFunctionContext, runningContexts } = this; const declaration = currentContext[name] || currentFunctionContext[name] || null; if ( !declaration && currentContext === currentFunctionContext && runningContexts.length > 0 ) { const previousRunningContext = runningContexts[runningContexts.length - 2]; if (previousRunningContext[name]) { return previousRunningContext[name]; } } return declaration; } /** * Recursively scans AST for declarations and functions, and add them to their respective context * @param ast */ scan(ast) { if (!ast) return; if (Array.isArray(ast)) { for (let i = 0; i < ast.length; i++) { this.scan(ast[i]); } return; } switch (ast.type) { case 'Program': this.useFunctionContext(() => { this.scan(ast.body); }); break; case 'BlockStatement': this.newContext(() => { this.scan(ast.body); }); break; case 'AssignmentExpression': case 'LogicalExpression': this.scan(ast.left); this.scan(ast.right); break; case 'BinaryExpression': this.scan(ast.left); this.scan(ast.right); break; case 'UpdateExpression': if (ast.operator === '++') { const declaration = this.getDeclaration(ast.argument.name); if (declaration) { declaration.suggestedType = 'Integer'; } } this.scan(ast.argument); break; case 'UnaryExpression': this.scan(ast.argument); break; case 'VariableDeclaration': if (ast.kind === 'var') { this.useFunctionContext(() => { ast.declarations = utils.normalizeDeclarations(ast); this.scan(ast.declarations); }); } else { ast.declarations = utils.normalizeDeclarations(ast); this.scan(ast.declarations); } break; case 'VariableDeclarator': { const { currentContext } = this; const inForLoopInit = this.hasState(states.inForLoopInit); const declaration = { ast: ast, context: currentContext, name: ast.id.name, origin: 'declaration', inForLoopInit, inForLoopTest: null, assignable: currentContext === this.currentFunctionContext || (!inForLoopInit && !currentContext.hasOwnProperty(ast.id.name)), suggestedType: null, valueType: null, dependencies: null, isSafe: null, }; if (!currentContext[ast.id.name]) { currentContext[ast.id.name] = declaration; } this.declarations.push(declaration); this.scan(ast.id); this.scan(ast.init); break; } case 'FunctionExpression': case 'FunctionDeclaration': if (this.runningContexts.length === 0) { this.scan(ast.body); } else { this.functions.push(ast); } break; case 'IfStatement': this.scan(ast.test); this.scan(ast.consequent); if (ast.alternate) this.scan(ast.alternate); break; case 'ForStatement': { let testIdentifiers; const context = this.newContext(() => { this.pushState(states.inForLoopInit); this.scan(ast.init); this.popState(states.inForLoopInit); testIdentifiers = this.getIdentifiers(() => { this.scan(ast.test); }); this.scan(ast.update); this.newContext(() => { this.scan(ast.body); }); }); if (testIdentifiers) { for (const p in context) { if (p === '@contextType') continue; if (testIdentifiers.indexOf(p) > -1) { context[p].inForLoopTest = true; } } } break; } case 'DoWhileStatement': case 'WhileStatement': this.newContext(() => { this.scan(ast.body); this.scan(ast.test); }); break; case 'Identifier': { if (this.isState(states.trackIdentifiers)) { this.trackedIdentifiers.push(ast.name); } this.identifiers.push({ context: this.currentContext, declaration: this.getDeclaration(ast.name), ast, }); break; } case 'ReturnStatement': this.returnStatements.push(ast); this.scan(ast.argument); break; case 'MemberExpression': this.pushState(states.memberExpression); this.scan(ast.object); this.scan(ast.property); this.popState(states.memberExpression); break; case 'ExpressionStatement': this.scan(ast.expression); break; case 'SequenceExpression': this.scan(ast.expressions); break; case 'CallExpression': this.functionCalls.push({ context: this.currentContext, ast, }); this.scan(ast.arguments); break; case 'ArrayExpression': this.scan(ast.elements); break; case 'ConditionalExpression': this.scan(ast.test); this.scan(ast.alternate); this.scan(ast.consequent); break; case 'SwitchStatement': this.scan(ast.discriminant); this.scan(ast.cases); break; case 'SwitchCase': this.scan(ast.test); this.scan(ast.consequent); break; case 'ThisExpression': case 'Literal': case 'DebuggerStatement': case 'EmptyStatement': case 'BreakStatement': case 'ContinueStatement': break; default: throw new Error(`unhandled type "${ast.type}"`); } } } module.exports = { FunctionTracer, }; ================================================ FILE: src/backend/gl/kernel-string.js ================================================ const { glWiretap } = require('gl-wiretap'); const { utils } = require('../../utils'); function toStringWithoutUtils(fn) { return fn.toString() .replace('=>', '') .replace(/^function /, '') .replace(/utils[.]/g, '/*utils.*/'); } /** * * @param {GLKernel} Kernel * @param {KernelVariable[]} args * @param {Kernel} originKernel * @param {string} [setupContextString] * @param {string} [destroyContextString] * @returns {string} */ function glKernelString(Kernel, args, originKernel, setupContextString, destroyContextString) { if (!originKernel.built) { originKernel.build.apply(originKernel, args); } args = args ? Array.from(args).map(arg => { switch (typeof arg) { case 'boolean': return new Boolean(arg); case 'number': return new Number(arg); default: return arg; } }) : null; const uploadedValues = []; const postResult = []; const context = glWiretap(originKernel.context, { useTrackablePrimitives: true, onReadPixels: (targetName) => { if (kernel.subKernels) { if (!subKernelsResultVariableSetup) { postResult.push(` const result = { result: ${getRenderString(targetName, kernel)} };`); subKernelsResultVariableSetup = true; } else { const property = kernel.subKernels[subKernelsResultIndex++].property; postResult.push(` result${isNaN(property) ? '.' + property : `[${property}]`} = ${getRenderString(targetName, kernel)};`); } if (subKernelsResultIndex === kernel.subKernels.length) { postResult.push(' return result;'); } return; } if (targetName) { postResult.push(` return ${getRenderString(targetName, kernel)};`); } else { postResult.push(` return null;`); } }, onUnrecognizedArgumentLookup: (argument) => { const argumentName = findKernelValue(argument, kernel.kernelArguments, [], context, uploadedValues); if (argumentName) { return argumentName; } const constantName = findKernelValue(argument, kernel.kernelConstants, constants ? Object.keys(constants).map(key => constants[key]) : [], context, uploadedValues); if (constantName) { return constantName; } return null; } }); let subKernelsResultVariableSetup = false; let subKernelsResultIndex = 0; const { source, canvas, output, pipeline, graphical, loopMaxIterations, constants, optimizeFloatMemory, precision, fixIntegerDivisionAccuracy, functions, nativeFunctions, subKernels, immutable, argumentTypes, constantTypes, kernelArguments, kernelConstants, tactic, } = originKernel; const kernel = new Kernel(source, { canvas, context, checkContext: false, output, pipeline, graphical, loopMaxIterations, constants, optimizeFloatMemory, precision, fixIntegerDivisionAccuracy, functions, nativeFunctions, subKernels, immutable, argumentTypes, constantTypes, tactic, }); let result = []; context.setIndent(2); kernel.build.apply(kernel, args); result.push(context.toString()); context.reset(); kernel.kernelArguments.forEach((kernelArgument, i) => { switch (kernelArgument.type) { // primitives case 'Integer': case 'Boolean': case 'Number': case 'Float': // non-primitives case 'Array': case 'Array(2)': case 'Array(3)': case 'Array(4)': case 'HTMLCanvas': case 'HTMLImage': case 'HTMLVideo': context.insertVariable(`uploadValue_${kernelArgument.name}`, kernelArgument.uploadValue); break; case 'HTMLImageArray': for (let imageIndex = 0; imageIndex < args[i].length; imageIndex++) { const arg = args[i]; context.insertVariable(`uploadValue_${kernelArgument.name}[${imageIndex}]`, arg[imageIndex]); } break; case 'Input': context.insertVariable(`uploadValue_${kernelArgument.name}`, kernelArgument.uploadValue); break; case 'MemoryOptimizedNumberTexture': case 'NumberTexture': case 'Array1D(2)': case 'Array1D(3)': case 'Array1D(4)': case 'Array2D(2)': case 'Array2D(3)': case 'Array2D(4)': case 'Array3D(2)': case 'Array3D(3)': case 'Array3D(4)': case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': context.insertVariable(`uploadValue_${kernelArgument.name}`, args[i].texture); break; default: throw new Error(`unhandled kernelArgumentType insertion for glWiretap of type ${kernelArgument.type}`); } }); result.push('/** start of injected functions **/'); result.push(`function ${toStringWithoutUtils(utils.flattenTo)}`); result.push(`function ${toStringWithoutUtils(utils.flatten2dArrayTo)}`); result.push(`function ${toStringWithoutUtils(utils.flatten3dArrayTo)}`); result.push(`function ${toStringWithoutUtils(utils.flatten4dArrayTo)}`); result.push(`function ${toStringWithoutUtils(utils.isArray)}`); if (kernel.renderOutput !== kernel.renderTexture && kernel.formatValues) { result.push( ` const renderOutput = function ${toStringWithoutUtils(kernel.formatValues)};` ); } result.push('/** end of injected functions **/'); result.push(` const innerKernel = function (${kernel.kernelArguments.map(kernelArgument => kernelArgument.varName).join(', ')}) {`); context.setIndent(4); kernel.run.apply(kernel, args); if (kernel.renderKernels) { kernel.renderKernels(); } else if (kernel.renderOutput) { kernel.renderOutput(); } result.push(' /** start setup uploads for kernel values **/'); kernel.kernelArguments.forEach(kernelArgument => { result.push(' ' + kernelArgument.getStringValueHandler().split('\n').join('\n ')); }); result.push(' /** end setup uploads for kernel values **/'); result.push(context.toString()); if (kernel.renderOutput === kernel.renderTexture) { context.reset(); const framebufferName = context.getContextVariableName(kernel.framebuffer); if (kernel.renderKernels) { const results = kernel.renderKernels(); const textureName = context.getContextVariableName(kernel.texture.texture); result.push(` return { result: { texture: ${ textureName }, type: '${ results.result.type }', toArray: ${ getToArrayString(results.result, textureName, framebufferName) } },`); const { subKernels, mappedTextures } = kernel; for (let i = 0; i < subKernels.length; i++) { const texture = mappedTextures[i]; const subKernel = subKernels[i]; const subKernelResult = results[subKernel.property]; const subKernelTextureName = context.getContextVariableName(texture.texture); result.push(` ${subKernel.property}: { texture: ${ subKernelTextureName }, type: '${ subKernelResult.type }', toArray: ${ getToArrayString(subKernelResult, subKernelTextureName, framebufferName) } },`); } result.push(` };`); } else { const rendered = kernel.renderOutput(); const textureName = context.getContextVariableName(kernel.texture.texture); result.push(` return { texture: ${ textureName }, type: '${ rendered.type }', toArray: ${ getToArrayString(rendered, textureName, framebufferName) } };`); } } result.push(` ${destroyContextString ? '\n' + destroyContextString + ' ': ''}`); result.push(postResult.join('\n')); result.push(' };'); if (kernel.graphical) { result.push(getGetPixelsString(kernel)); result.push(` innerKernel.getPixels = getPixels;`); } result.push(' return innerKernel;'); let constantsUpload = []; kernelConstants.forEach((kernelConstant) => { constantsUpload.push(`${kernelConstant.getStringValueHandler()}`); }); return `function kernel(settings) { const { context, constants } = settings; ${constantsUpload.join('')} ${setupContextString ? setupContextString : ''} ${result.join('\n')} }`; } function getRenderString(targetName, kernel) { const readBackValue = kernel.precision === 'single' ? targetName : `new Float32Array(${targetName}.buffer)`; if (kernel.output[2]) { return `renderOutput(${readBackValue}, ${kernel.output[0]}, ${kernel.output[1]}, ${kernel.output[2]})`; } if (kernel.output[1]) { return `renderOutput(${readBackValue}, ${kernel.output[0]}, ${kernel.output[1]})`; } return `renderOutput(${readBackValue}, ${kernel.output[0]})`; } function getGetPixelsString(kernel) { const getPixels = kernel.getPixels.toString(); const useFunctionKeyword = !/^function/.test(getPixels); return utils.flattenFunctionToString(`${useFunctionKeyword ? 'function ' : ''}${ getPixels }`, { findDependency: (object, name) => { if (object === 'utils') { return `const ${name} = ${utils[name].toString()};`; } return null; }, thisLookup: (property) => { if (property === 'context') { return null; } if (kernel.hasOwnProperty(property)) { return JSON.stringify(kernel[property]); } throw new Error(`unhandled thisLookup ${ property }`); } }); } function getToArrayString(kernelResult, textureName, framebufferName) { const toArray = kernelResult.toArray.toString(); const useFunctionKeyword = !/^function/.test(toArray); const flattenedFunctions = utils.flattenFunctionToString(`${useFunctionKeyword ? 'function ' : ''}${ toArray }`, { findDependency: (object, name) => { if (object === 'utils') { return `const ${name} = ${utils[name].toString()};`; } else if (object === 'this') { if (name === 'framebuffer') { return ''; } return `${useFunctionKeyword ? 'function ' : ''}${kernelResult[name].toString()}`; } else { throw new Error('unhandled fromObject'); } }, thisLookup: (property, isDeclaration) => { if (property === 'texture') { return textureName; } if (property === 'context') { if (isDeclaration) return null; return 'gl'; } if (kernelResult.hasOwnProperty(property)) { return JSON.stringify(kernelResult[property]); } throw new Error(`unhandled thisLookup ${ property }`); } }); return `() => { function framebuffer() { return ${framebufferName}; }; ${flattenedFunctions} return toArray(); }`; } /** * * @param {KernelVariable} argument * @param {KernelValue[]} kernelValues * @param {KernelVariable[]} values * @param context * @param {KernelVariable[]} uploadedValues * @return {string|null} */ function findKernelValue(argument, kernelValues, values, context, uploadedValues) { if (argument === null) return null; if (kernelValues === null) return null; switch (typeof argument) { case 'boolean': case 'number': return null; } if ( typeof HTMLImageElement !== 'undefined' && argument instanceof HTMLImageElement ) { for (let i = 0; i < kernelValues.length; i++) { const kernelValue = kernelValues[i]; if (kernelValue.type !== 'HTMLImageArray' && kernelValue) continue; if (kernelValue.uploadValue !== argument) continue; // TODO: if we send two of the same image, the parser could get confused, and short circuit to the first, handle that here const variableIndex = values[i].indexOf(argument); if (variableIndex === -1) continue; const variableName = `uploadValue_${kernelValue.name}[${variableIndex}]`; context.insertVariable(variableName, argument); return variableName; } } for (let i = 0; i < kernelValues.length; i++) { const kernelValue = kernelValues[i]; if (argument !== kernelValue.uploadValue) continue; const variable = `uploadValue_${kernelValue.name}`; context.insertVariable(variable, kernelValue); return variable; } return null; } module.exports = { glKernelString }; ================================================ FILE: src/backend/gl/kernel.js ================================================ const { Kernel } = require('../kernel'); const { utils } = require('../../utils'); const { GLTextureArray2Float } = require('./texture/array-2-float'); const { GLTextureArray2Float2D } = require('./texture/array-2-float-2d'); const { GLTextureArray2Float3D } = require('./texture/array-2-float-3d'); const { GLTextureArray3Float } = require('./texture/array-3-float'); const { GLTextureArray3Float2D } = require('./texture/array-3-float-2d'); const { GLTextureArray3Float3D } = require('./texture/array-3-float-3d'); const { GLTextureArray4Float } = require('./texture/array-4-float'); const { GLTextureArray4Float2D } = require('./texture/array-4-float-2d'); const { GLTextureArray4Float3D } = require('./texture/array-4-float-3d'); const { GLTextureFloat } = require('./texture/float'); const { GLTextureFloat2D } = require('./texture/float-2d'); const { GLTextureFloat3D } = require('./texture/float-3d'); const { GLTextureMemoryOptimized } = require('./texture/memory-optimized'); const { GLTextureMemoryOptimized2D } = require('./texture/memory-optimized-2d'); const { GLTextureMemoryOptimized3D } = require('./texture/memory-optimized-3d'); const { GLTextureUnsigned } = require('./texture/unsigned'); const { GLTextureUnsigned2D } = require('./texture/unsigned-2d'); const { GLTextureUnsigned3D } = require('./texture/unsigned-3d'); const { GLTextureGraphical } = require('./texture/graphical'); /** * @abstract * @extends Kernel */ class GLKernel extends Kernel { static get mode() { return 'gpu'; } static getIsFloatRead() { const kernelString = `function kernelFunction() { return 1; }`; const kernel = new this(kernelString, { context: this.testContext, canvas: this.testCanvas, validate: false, output: [1], precision: 'single', returnType: 'Number', tactic: 'speed', }); kernel.build(); kernel.run(); const result = kernel.renderOutput(); kernel.destroy(true); return result[0] === 1; } static getIsIntegerDivisionAccurate() { function kernelFunction(v1, v2) { return v1[this.thread.x] / v2[this.thread.x]; } const kernel = new this(kernelFunction.toString(), { context: this.testContext, canvas: this.testCanvas, validate: false, output: [2], returnType: 'Number', precision: 'unsigned', tactic: 'speed', }); const args = [ [6, 6030401], [3, 3991] ]; kernel.build.apply(kernel, args); kernel.run.apply(kernel, args); const result = kernel.renderOutput(); kernel.destroy(true); // have we not got whole numbers for 6/3 or 6030401/3991 // add more here if others see this problem return result[0] === 2 && result[1] === 1511; } static getIsSpeedTacticSupported() { function kernelFunction(value) { return value[this.thread.x]; } const kernel = new this(kernelFunction.toString(), { context: this.testContext, canvas: this.testCanvas, validate: false, output: [4], returnType: 'Number', precision: 'unsigned', tactic: 'speed', }); const args = [ [0, 1, 2, 3] ]; kernel.build.apply(kernel, args); kernel.run.apply(kernel, args); const result = kernel.renderOutput(); kernel.destroy(true); return Math.round(result[0]) === 0 && Math.round(result[1]) === 1 && Math.round(result[2]) === 2 && Math.round(result[3]) === 3; } /** * @abstract */ static get testCanvas() { throw new Error(`"testCanvas" not defined on ${ this.name }`); } /** * @abstract */ static get testContext() { throw new Error(`"testContext" not defined on ${ this.name }`); } static getFeatures() { const gl = this.testContext; const isDrawBuffers = this.getIsDrawBuffers(); return Object.freeze({ isFloatRead: this.getIsFloatRead(), isIntegerDivisionAccurate: this.getIsIntegerDivisionAccurate(), isSpeedTacticSupported: this.getIsSpeedTacticSupported(), isTextureFloat: this.getIsTextureFloat(), isDrawBuffers, kernelMap: isDrawBuffers, channelCount: this.getChannelCount(), maxTextureSize: this.getMaxTextureSize(), lowIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT), lowFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT), mediumIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT), mediumFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT), highIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT), highFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT), }); } /** * @abstract */ static setupFeatureChecks() { throw new Error(`"setupFeatureChecks" not defined on ${ this.name }`); } static getSignature(kernel, argumentTypes) { return kernel.getVariablePrecisionString() + (argumentTypes.length > 0 ? ':' + argumentTypes.join(',') : ''); } /** * @desc Fix division by factor of 3 FP accuracy bug * @param {Boolean} fix - should fix */ setFixIntegerDivisionAccuracy(fix) { this.fixIntegerDivisionAccuracy = fix; return this; } /** * @desc Toggle output mode * @param {String} flag - 'single' or 'unsigned' */ setPrecision(flag) { this.precision = flag; return this; } /** * @desc Toggle texture output mode * @param {Boolean} flag - true to enable floatTextures * @deprecated */ setFloatTextures(flag) { utils.warnDeprecated('method', 'setFloatTextures', 'setOptimizeFloatMemory'); this.floatTextures = flag; return this; } /** * A highly readable very forgiving micro-parser for a glsl function that gets argument types * @param {String} source * @returns {{argumentTypes: String[], argumentNames: String[]}} */ static nativeFunctionArguments(source) { const argumentTypes = []; const argumentNames = []; const states = []; const isStartingVariableName = /^[a-zA-Z_]/; const isVariableChar = /[a-zA-Z_0-9]/; let i = 0; let argumentName = null; let argumentType = null; while (i < source.length) { const char = source[i]; const nextChar = source[i + 1]; const state = states.length > 0 ? states[states.length - 1] : null; // begin MULTI_LINE_COMMENT handling if (state === 'FUNCTION_ARGUMENTS' && char === '/' && nextChar === '*') { states.push('MULTI_LINE_COMMENT'); i += 2; continue; } else if (state === 'MULTI_LINE_COMMENT' && char === '*' && nextChar === '/') { states.pop(); i += 2; continue; } // end MULTI_LINE_COMMENT handling // begin COMMENT handling else if (state === 'FUNCTION_ARGUMENTS' && char === '/' && nextChar === '/') { states.push('COMMENT'); i += 2; continue; } else if (state === 'COMMENT' && char === '\n') { states.pop(); i++; continue; } // end COMMENT handling // being FUNCTION_ARGUMENTS handling else if (state === null && char === '(') { states.push('FUNCTION_ARGUMENTS'); i++; continue; } else if (state === 'FUNCTION_ARGUMENTS') { if (char === ')') { states.pop(); break; } if (char === 'f' && nextChar === 'l' && source[i + 2] === 'o' && source[i + 3] === 'a' && source[i + 4] === 't' && source[i + 5] === ' ') { states.push('DECLARE_VARIABLE'); argumentType = 'float'; argumentName = ''; i += 6; continue; } else if (char === 'i' && nextChar === 'n' && source[i + 2] === 't' && source[i + 3] === ' ') { states.push('DECLARE_VARIABLE'); argumentType = 'int'; argumentName = ''; i += 4; continue; } else if (char === 'v' && nextChar === 'e' && source[i + 2] === 'c' && source[i + 3] === '2' && source[i + 4] === ' ') { states.push('DECLARE_VARIABLE'); argumentType = 'vec2'; argumentName = ''; i += 5; continue; } else if (char === 'v' && nextChar === 'e' && source[i + 2] === 'c' && source[i + 3] === '3' && source[i + 4] === ' ') { states.push('DECLARE_VARIABLE'); argumentType = 'vec3'; argumentName = ''; i += 5; continue; } else if (char === 'v' && nextChar === 'e' && source[i + 2] === 'c' && source[i + 3] === '4' && source[i + 4] === ' ') { states.push('DECLARE_VARIABLE'); argumentType = 'vec4'; argumentName = ''; i += 5; continue; } } // end FUNCTION_ARGUMENTS handling // begin DECLARE_VARIABLE handling else if (state === 'DECLARE_VARIABLE') { if (argumentName === '') { if (char === ' ') { i++; continue; } if (!isStartingVariableName.test(char)) { throw new Error('variable name is not expected string'); } } argumentName += char; if (!isVariableChar.test(nextChar)) { states.pop(); argumentNames.push(argumentName); argumentTypes.push(typeMap[argumentType]); } } // end DECLARE_VARIABLE handling // Progress to next character i++; } if (states.length > 0) { throw new Error('GLSL function was not parsable'); } return { argumentNames, argumentTypes, }; } static nativeFunctionReturnType(source) { return typeMap[source.match(/int|float|vec[2-4]/)[0]]; } static combineKernels(combinedKernel, lastKernel) { combinedKernel.apply(null, arguments); const { texSize, context, threadDim } = lastKernel.texSize; let result; if (lastKernel.precision === 'single') { const w = texSize[0]; const h = Math.ceil(texSize[1] / 4); result = new Float32Array(w * h * 4 * 4); context.readPixels(0, 0, w, h * 4, context.RGBA, context.FLOAT, result); } else { const bytes = new Uint8Array(texSize[0] * texSize[1] * 4); context.readPixels(0, 0, texSize[0], texSize[1], context.RGBA, context.UNSIGNED_BYTE, bytes); result = new Float32Array(bytes.buffer); } result = result.subarray(0, threadDim[0] * threadDim[1] * threadDim[2]); if (lastKernel.output.length === 1) { return result; } else if (lastKernel.output.length === 2) { return utils.splitArray(result, lastKernel.output[0]); } else if (lastKernel.output.length === 3) { const cube = utils.splitArray(result, lastKernel.output[0] * lastKernel.output[1]); return cube.map(function(x) { return utils.splitArray(x, lastKernel.output[0]); }); } } constructor(source, settings) { super(source, settings); this.transferValues = null; this.formatValues = null; /** * * @type {Texture} */ this.TextureConstructor = null; this.renderOutput = null; this.renderRawOutput = null; this.texSize = null; this.translatedSource = null; this.compiledFragmentShader = null; this.compiledVertexShader = null; this.switchingKernels = null; this._textureSwitched = null; this._mappedTextureSwitched = null; } checkTextureSize() { const { features } = this.constructor; if (this.texSize[0] > features.maxTextureSize || this.texSize[1] > features.maxTextureSize) { throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${features.maxTextureSize},${features.maxTextureSize}]`); } } translateSource() { throw new Error(`"translateSource" not defined on ${this.constructor.name}`); } /** * Picks a render strategy for the now finally parsed kernel * @param args * @return {null|KernelOutput} */ pickRenderStrategy(args) { if (this.graphical) { this.renderRawOutput = this.readPackedPixelsToUint8Array; this.transferValues = (pixels) => pixels; this.TextureConstructor = GLTextureGraphical; return null; } if (this.precision === 'unsigned') { this.renderRawOutput = this.readPackedPixelsToUint8Array; this.transferValues = this.readPackedPixelsToFloat32Array; if (this.pipeline) { this.renderOutput = this.renderTexture; if (this.subKernels !== null) { this.renderKernels = this.renderKernelsToTextures; } switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': if (this.output[2] > 0) { this.TextureConstructor = GLTextureUnsigned3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureUnsigned2D; return null; } else { this.TextureConstructor = GLTextureUnsigned; return null; } case 'Array(2)': case 'Array(3)': case 'Array(4)': return this.requestFallback(args); } } else { if (this.subKernels !== null) { this.renderKernels = this.renderKernelsToArrays; } switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': this.renderOutput = this.renderValues; if (this.output[2] > 0) { this.TextureConstructor = GLTextureUnsigned3D; this.formatValues = utils.erect3DPackedFloat; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureUnsigned2D; this.formatValues = utils.erect2DPackedFloat; return null; } else { this.TextureConstructor = GLTextureUnsigned; this.formatValues = utils.erectPackedFloat; return null; } case 'Array(2)': case 'Array(3)': case 'Array(4)': return this.requestFallback(args); } } } else if (this.precision === 'single') { this.renderRawOutput = this.readFloatPixelsToFloat32Array; this.transferValues = this.readFloatPixelsToFloat32Array; if (this.pipeline) { this.renderOutput = this.renderTexture; if (this.subKernels !== null) { this.renderKernels = this.renderKernelsToTextures; } switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': { if (this.optimizeFloatMemory) { if (this.output[2] > 0) { this.TextureConstructor = GLTextureMemoryOptimized3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureMemoryOptimized2D; return null; } else { this.TextureConstructor = GLTextureMemoryOptimized; return null; } } else { if (this.output[2] > 0) { this.TextureConstructor = GLTextureFloat3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureFloat2D; return null; } else { this.TextureConstructor = GLTextureFloat; return null; } } } case 'Array(2)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray2Float3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray2Float2D; return null; } else { this.TextureConstructor = GLTextureArray2Float; return null; } } case 'Array(3)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray3Float3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray3Float2D; return null; } else { this.TextureConstructor = GLTextureArray3Float; return null; } } case 'Array(4)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray4Float3D; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray4Float2D; return null; } else { this.TextureConstructor = GLTextureArray4Float; return null; } } } } this.renderOutput = this.renderValues; if (this.subKernels !== null) { this.renderKernels = this.renderKernelsToArrays; } if (this.optimizeFloatMemory) { switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureMemoryOptimized3D; this.formatValues = utils.erectMemoryOptimized3DFloat; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureMemoryOptimized2D; this.formatValues = utils.erectMemoryOptimized2DFloat; return null; } else { this.TextureConstructor = GLTextureMemoryOptimized; this.formatValues = utils.erectMemoryOptimizedFloat; return null; } } case 'Array(2)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray2Float3D; this.formatValues = utils.erect3DArray2; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray2Float2D; this.formatValues = utils.erect2DArray2; return null; } else { this.TextureConstructor = GLTextureArray2Float; this.formatValues = utils.erectArray2; return null; } } case 'Array(3)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray3Float3D; this.formatValues = utils.erect3DArray3; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray3Float2D; this.formatValues = utils.erect2DArray3; return null; } else { this.TextureConstructor = GLTextureArray3Float; this.formatValues = utils.erectArray3; return null; } } case 'Array(4)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray4Float3D; this.formatValues = utils.erect3DArray4; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray4Float2D; this.formatValues = utils.erect2DArray4; return null; } else { this.TextureConstructor = GLTextureArray4Float; this.formatValues = utils.erectArray4; return null; } } } } else { switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureFloat3D; this.formatValues = utils.erect3DFloat; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureFloat2D; this.formatValues = utils.erect2DFloat; return null; } else { this.TextureConstructor = GLTextureFloat; this.formatValues = utils.erectFloat; return null; } } case 'Array(2)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray2Float3D; this.formatValues = utils.erect3DArray2; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray2Float2D; this.formatValues = utils.erect2DArray2; return null; } else { this.TextureConstructor = GLTextureArray2Float; this.formatValues = utils.erectArray2; return null; } } case 'Array(3)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray3Float3D; this.formatValues = utils.erect3DArray3; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray3Float2D; this.formatValues = utils.erect2DArray3; return null; } else { this.TextureConstructor = GLTextureArray3Float; this.formatValues = utils.erectArray3; return null; } } case 'Array(4)': { if (this.output[2] > 0) { this.TextureConstructor = GLTextureArray4Float3D; this.formatValues = utils.erect3DArray4; return null; } else if (this.output[1] > 0) { this.TextureConstructor = GLTextureArray4Float2D; this.formatValues = utils.erect2DArray4; return null; } else { this.TextureConstructor = GLTextureArray4Float; this.formatValues = utils.erectArray4; return null; } } } } } else { throw new Error(`unhandled precision of "${this.precision}"`); } throw new Error(`unhandled return type "${this.returnType}"`); } /** * @abstract * @returns String */ getKernelString() { throw new Error(`abstract method call`); } getMainResultTexture() { switch (this.returnType) { case 'LiteralInteger': case 'Float': case 'Integer': case 'Number': return this.getMainResultNumberTexture(); case 'Array(2)': return this.getMainResultArray2Texture(); case 'Array(3)': return this.getMainResultArray3Texture(); case 'Array(4)': return this.getMainResultArray4Texture(); default: throw new Error(`unhandled returnType type ${ this.returnType }`); } } /** * @abstract * @returns String[] */ getMainResultKernelNumberTexture() { throw new Error(`abstract method call`); } /** * @abstract * @returns String[] */ getMainResultSubKernelNumberTexture() { throw new Error(`abstract method call`); } /** * @abstract * @returns String[] */ getMainResultKernelArray2Texture() { throw new Error(`abstract method call`); } /** * @abstract * @returns String[] */ getMainResultSubKernelArray2Texture() { throw new Error(`abstract method call`); } /** * @abstract * @returns String[] */ getMainResultKernelArray3Texture() { throw new Error(`abstract method call`); } /** * @abstract * @returns String[] */ getMainResultSubKernelArray3Texture() { throw new Error(`abstract method call`); } /** * @abstract * @returns String[] */ getMainResultKernelArray4Texture() { throw new Error(`abstract method call`); } /** * @abstract * @returns String[] */ getMainResultSubKernelArray4Texture() { throw new Error(`abstract method call`); } /** * @abstract * @returns String[] */ getMainResultGraphical() { throw new Error(`abstract method call`); } /** * @abstract * @returns String[] */ getMainResultMemoryOptimizedFloats() { throw new Error(`abstract method call`); } /** * @abstract * @returns String[] */ getMainResultPackedPixels() { throw new Error(`abstract method call`); } getMainResultString() { if (this.graphical) { return this.getMainResultGraphical(); } else if (this.precision === 'single') { if (this.optimizeFloatMemory) { return this.getMainResultMemoryOptimizedFloats(); } return this.getMainResultTexture(); } else { return this.getMainResultPackedPixels(); } } getMainResultNumberTexture() { return utils.linesToString(this.getMainResultKernelNumberTexture()) + utils.linesToString(this.getMainResultSubKernelNumberTexture()); } getMainResultArray2Texture() { return utils.linesToString(this.getMainResultKernelArray2Texture()) + utils.linesToString(this.getMainResultSubKernelArray2Texture()); } getMainResultArray3Texture() { return utils.linesToString(this.getMainResultKernelArray3Texture()) + utils.linesToString(this.getMainResultSubKernelArray3Texture()); } getMainResultArray4Texture() { return utils.linesToString(this.getMainResultKernelArray4Texture()) + utils.linesToString(this.getMainResultSubKernelArray4Texture()); } /** * * @return {string} */ getFloatTacticDeclaration() { const variablePrecision = this.getVariablePrecisionString(this.texSize, this.tactic); return `precision ${variablePrecision} float;\n`; } /** * * @return {string} */ getIntTacticDeclaration() { return `precision ${this.getVariablePrecisionString(this.texSize, this.tactic, true)} int;\n`; } /** * * @return {string} */ getSampler2DTacticDeclaration() { return `precision ${this.getVariablePrecisionString(this.texSize, this.tactic)} sampler2D;\n`; } getSampler2DArrayTacticDeclaration() { return `precision ${this.getVariablePrecisionString(this.texSize, this.tactic)} sampler2DArray;\n`; } renderTexture() { return this.immutable ? this.texture.clone() : this.texture; } readPackedPixelsToUint8Array() { if (this.precision !== 'unsigned') throw new Error('Requires this.precision to be "unsigned"'); const { texSize, context: gl } = this; const result = new Uint8Array(texSize[0] * texSize[1] * 4); gl.readPixels(0, 0, texSize[0], texSize[1], gl.RGBA, gl.UNSIGNED_BYTE, result); return result; } readPackedPixelsToFloat32Array() { return new Float32Array(this.readPackedPixelsToUint8Array().buffer); } readFloatPixelsToFloat32Array() { if (this.precision !== 'single') throw new Error('Requires this.precision to be "single"'); const { texSize, context: gl } = this; const w = texSize[0]; const h = texSize[1]; const result = new Float32Array(w * h * 4); gl.readPixels(0, 0, w, h, gl.RGBA, gl.FLOAT, result); return result; } /** * * @param {Boolean} [flip] * @return {Uint8ClampedArray} */ getPixels(flip) { const { context: gl, output } = this; const [width, height] = output; const pixels = new Uint8Array(width * height * 4); gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); // flipped by default, so invert return new Uint8ClampedArray((flip ? pixels : utils.flipPixels(pixels, width, height)).buffer); } renderKernelsToArrays() { const result = { result: this.renderOutput(), }; for (let i = 0; i < this.subKernels.length; i++) { result[this.subKernels[i].property] = this.mappedTextures[i].toArray(); } return result; } renderKernelsToTextures() { const result = { result: this.renderOutput(), }; if (this.immutable) { for (let i = 0; i < this.subKernels.length; i++) { result[this.subKernels[i].property] = this.mappedTextures[i].clone(); } } else { for (let i = 0; i < this.subKernels.length; i++) { result[this.subKernels[i].property] = this.mappedTextures[i]; } } return result; } resetSwitchingKernels() { const existingValue = this.switchingKernels; this.switchingKernels = null; return existingValue; } setOutput(output) { const newOutput = this.toKernelOutput(output); if (this.program) { if (!this.dynamicOutput) { throw new Error('Resizing a kernel with dynamicOutput: false is not possible'); } const newThreadDim = [newOutput[0], newOutput[1] || 1, newOutput[2] || 1]; const newTexSize = utils.getKernelTextureSize({ optimizeFloatMemory: this.optimizeFloatMemory, precision: this.precision, }, newThreadDim); const oldTexSize = this.texSize; if (oldTexSize) { const oldPrecision = this.getVariablePrecisionString(oldTexSize, this.tactic); const newPrecision = this.getVariablePrecisionString(newTexSize, this.tactic); if (oldPrecision !== newPrecision) { if (this.debug) { console.warn('Precision requirement changed, asking GPU instance to recompile'); } this.switchKernels({ type: 'outputPrecisionMismatch', precision: newPrecision, needed: output }); return; } } this.output = newOutput; this.threadDim = newThreadDim; this.texSize = newTexSize; const { context: gl } = this; gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); this.updateMaxTexSize(); this.framebuffer.width = this.texSize[0]; this.framebuffer.height = this.texSize[1]; gl.viewport(0, 0, this.maxTexSize[0], this.maxTexSize[1]); this.canvas.width = this.maxTexSize[0]; this.canvas.height = this.maxTexSize[1]; if (this.texture) { this.texture.delete(); } this.texture = null; this._setupOutputTexture(); if (this.mappedTextures && this.mappedTextures.length > 0) { for (let i = 0; i < this.mappedTextures.length; i++) { this.mappedTextures[i].delete(); } this.mappedTextures = null; this._setupSubOutputTextures(); } } else { this.output = newOutput; } return this; } renderValues() { return this.formatValues( this.transferValues(), this.output[0], this.output[1], this.output[2] ); } switchKernels(reason) { if (this.switchingKernels) { this.switchingKernels.push(reason); } else { this.switchingKernels = [reason]; } } getVariablePrecisionString(textureSize = this.texSize, tactic = this.tactic, isInt = false) { if (!tactic) { if (!this.constructor.features.isSpeedTacticSupported) return 'highp'; const low = this.constructor.features[isInt ? 'lowIntPrecision' : 'lowFloatPrecision']; const medium = this.constructor.features[isInt ? 'mediumIntPrecision' : 'mediumFloatPrecision']; const high = this.constructor.features[isInt ? 'highIntPrecision' : 'highFloatPrecision']; const requiredSize = Math.log2(textureSize[0] * textureSize[1]); if (requiredSize <= low.rangeMax) { return 'lowp'; } else if (requiredSize <= medium.rangeMax) { return 'mediump'; } else if (requiredSize <= high.rangeMax) { return 'highp'; } else { throw new Error(`The required size exceeds that of the ability of your system`); } } switch (tactic) { case 'speed': return 'lowp'; case 'balanced': return 'mediump'; case 'precision': return 'highp'; default: throw new Error(`Unknown tactic "${tactic}" use "speed", "balanced", "precision", or empty for auto`); } } /** * * @param {WebGLKernelValue} kernelValue * @param {GLTexture} arg */ updateTextureArgumentRefs(kernelValue, arg) { if (!this.immutable) return; if (this.texture.texture === arg.texture) { const { prevArg } = kernelValue; if (prevArg) { if (prevArg.texture._refs === 1) { this.texture.delete(); this.texture = prevArg.clone(); this._textureSwitched = true; } prevArg.delete(); } kernelValue.prevArg = arg.clone(); } else if (this.mappedTextures && this.mappedTextures.length > 0) { const { mappedTextures } = this; for (let i = 0; i < mappedTextures.length; i++) { const mappedTexture = mappedTextures[i]; if (mappedTexture.texture === arg.texture) { const { prevArg } = kernelValue; if (prevArg) { if (prevArg.texture._refs === 1) { mappedTexture.delete(); mappedTextures[i] = prevArg.clone(); this._mappedTextureSwitched[i] = true; } prevArg.delete(); } kernelValue.prevArg = arg.clone(); return; } } } } onActivate(previousKernel) { this._textureSwitched = true; this.texture = previousKernel.texture; if (this.mappedTextures) { for (let i = 0; i < this.mappedTextures.length; i++) { this._mappedTextureSwitched[i] = true; } this.mappedTextures = previousKernel.mappedTextures; } } initCanvas() {} } const typeMap = { int: 'Integer', float: 'Number', vec2: 'Array(2)', vec3: 'Array(3)', vec4: 'Array(4)', }; module.exports = { GLKernel }; ================================================ FILE: src/backend/gl/texture/array-2-float-2d.js ================================================ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray2Float2D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(2)'; } toArray() { return utils.erect2DArray2(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureArray2Float2D }; ================================================ FILE: src/backend/gl/texture/array-2-float-3d.js ================================================ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray2Float3D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(2)'; } toArray() { return utils.erect3DArray2(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureArray2Float3D }; ================================================ FILE: src/backend/gl/texture/array-2-float.js ================================================ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray2Float extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(2)'; } toArray() { return utils.erectArray2(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureArray2Float }; ================================================ FILE: src/backend/gl/texture/array-3-float-2d.js ================================================ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray3Float2D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(3)'; } toArray() { return utils.erect2DArray3(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureArray3Float2D }; ================================================ FILE: src/backend/gl/texture/array-3-float-3d.js ================================================ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray3Float3D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(3)'; } toArray() { return utils.erect3DArray3(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureArray3Float3D }; ================================================ FILE: src/backend/gl/texture/array-3-float.js ================================================ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray3Float extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(3)'; } toArray() { return utils.erectArray3(this.renderValues(), this.output[0]); } } module.exports = { GLTextureArray3Float }; ================================================ FILE: src/backend/gl/texture/array-4-float-2d.js ================================================ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray4Float2D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(4)'; } toArray() { return utils.erect2DArray4(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureArray4Float2D }; ================================================ FILE: src/backend/gl/texture/array-4-float-3d.js ================================================ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray4Float3D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(4)'; } toArray() { return utils.erect3DArray4(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureArray4Float3D }; ================================================ FILE: src/backend/gl/texture/array-4-float.js ================================================ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureArray4Float extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(4)'; } toArray() { return utils.erectArray4(this.renderValues(), this.output[0]); } } module.exports = { GLTextureArray4Float }; ================================================ FILE: src/backend/gl/texture/float-2d.js ================================================ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureFloat2D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(1)'; } toArray() { return utils.erect2DFloat(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureFloat2D }; ================================================ FILE: src/backend/gl/texture/float-3d.js ================================================ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureFloat3D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'ArrayTexture(1)'; } toArray() { return utils.erect3DFloat(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureFloat3D }; ================================================ FILE: src/backend/gl/texture/float.js ================================================ const { utils } = require('../../../utils'); const { GLTexture } = require('./index'); class GLTextureFloat extends GLTexture { get textureType() { return this.context.FLOAT; } constructor(settings) { super(settings); this.type = 'ArrayTexture(1)'; } renderRawOutput() { const gl = this.context; const size = this.size; gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer()); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0 ); const result = new Float32Array(size[0] * size[1] * 4); gl.readPixels(0, 0, size[0], size[1], gl.RGBA, gl.FLOAT, result); return result; } renderValues() { if (this._deleted) return null; return this.renderRawOutput(); } toArray() { return utils.erectFloat(this.renderValues(), this.output[0]); } } module.exports = { GLTextureFloat }; ================================================ FILE: src/backend/gl/texture/graphical.js ================================================ const { GLTextureUnsigned } = require('./unsigned'); class GLTextureGraphical extends GLTextureUnsigned { constructor(settings) { super(settings); this.type = 'ArrayTexture(4)'; } toArray() { return this.renderValues(); } } module.exports = { GLTextureGraphical }; ================================================ FILE: src/backend/gl/texture/index.js ================================================ const { Texture } = require('../../../texture'); /** * @class * @property framebuffer * @extends Texture */ class GLTexture extends Texture { /** * @returns {Number} * @abstract */ get textureType() { throw new Error(`"textureType" not implemented on ${ this.name }`); } clone() { return new this.constructor(this); } /** * @returns {Boolean} */ beforeMutate() { if (this.texture._refs > 1) { this.newTexture(); return true; } return false; } /** * @private */ cloneTexture() { this.texture._refs--; const { context: gl, size, texture, kernel } = this; if (kernel.debug) { console.warn('cloning internal texture'); } gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer()); selectTexture(gl, texture); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); const target = gl.createTexture(); selectTexture(gl, target); gl.texImage2D(gl.TEXTURE_2D, 0, this.internalFormat, size[0], size[1], 0, this.textureFormat, this.textureType, null); gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 0, 0, size[0], size[1]); target._refs = 1; this.texture = target; } /** * @private */ newTexture() { this.texture._refs--; const gl = this.context; const size = this.size; const kernel = this.kernel; if (kernel.debug) { console.warn('new internal texture'); } const target = gl.createTexture(); selectTexture(gl, target); gl.texImage2D(gl.TEXTURE_2D, 0, this.internalFormat, size[0], size[1], 0, this.textureFormat, this.textureType, null); target._refs = 1; this.texture = target; } clear() { if (this.texture._refs) { this.texture._refs--; const gl = this.context; const target = this.texture = gl.createTexture(); selectTexture(gl, target); const size = this.size; target._refs = 1; gl.texImage2D(gl.TEXTURE_2D, 0, this.internalFormat, size[0], size[1], 0, this.textureFormat, this.textureType, null); } const { context: gl, texture } = this; gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer()); gl.bindTexture(gl.TEXTURE_2D, texture); selectTexture(gl, texture); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); } delete() { if (this._deleted) return; this._deleted = true; if (this.texture._refs) { this.texture._refs--; if (this.texture._refs) return; } this.context.deleteTexture(this.texture); // TODO: Remove me // if (this.texture._refs === 0 && this._framebuffer) { // this.context.deleteFramebuffer(this._framebuffer); // this._framebuffer = null; // } } framebuffer() { if (!this._framebuffer) { this._framebuffer = this.kernel.getRawValueFramebuffer(this.size[0], this.size[1]); } return this._framebuffer; } } function selectTexture(gl, texture) { /* Maximum a texture can be, so that collision is highly unlikely * basically gl.TEXTURE15 + gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); * Was gl.TEXTURE31, but safari didn't like it * */ gl.activeTexture(gl.TEXTURE15); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); } module.exports = { GLTexture }; ================================================ FILE: src/backend/gl/texture/memory-optimized-2d.js ================================================ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureMemoryOptimized2D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'MemoryOptimizedNumberTexture'; } toArray() { return utils.erectMemoryOptimized2DFloat(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureMemoryOptimized2D }; ================================================ FILE: src/backend/gl/texture/memory-optimized-3d.js ================================================ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureMemoryOptimized3D extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'MemoryOptimizedNumberTexture'; } toArray() { return utils.erectMemoryOptimized3DFloat(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureMemoryOptimized3D }; ================================================ FILE: src/backend/gl/texture/memory-optimized.js ================================================ const { utils } = require('../../../utils'); const { GLTextureFloat } = require('./float'); class GLTextureMemoryOptimized extends GLTextureFloat { constructor(settings) { super(settings); this.type = 'MemoryOptimizedNumberTexture'; } toArray() { return utils.erectMemoryOptimizedFloat(this.renderValues(), this.output[0]); } } module.exports = { GLTextureMemoryOptimized }; ================================================ FILE: src/backend/gl/texture/unsigned-2d.js ================================================ const { utils } = require('../../../utils'); const { GLTextureUnsigned } = require('./unsigned'); class GLTextureUnsigned2D extends GLTextureUnsigned { constructor(settings) { super(settings); this.type = 'NumberTexture'; } toArray() { return utils.erect2DPackedFloat(this.renderValues(), this.output[0], this.output[1]); } } module.exports = { GLTextureUnsigned2D }; ================================================ FILE: src/backend/gl/texture/unsigned-3d.js ================================================ const { utils } = require('../../../utils'); const { GLTextureUnsigned } = require('./unsigned'); class GLTextureUnsigned3D extends GLTextureUnsigned { constructor(settings) { super(settings); this.type = 'NumberTexture'; } toArray() { return utils.erect3DPackedFloat(this.renderValues(), this.output[0], this.output[1], this.output[2]); } } module.exports = { GLTextureUnsigned3D }; ================================================ FILE: src/backend/gl/texture/unsigned.js ================================================ const { utils } = require('../../../utils'); const { GLTexture } = require('./index'); class GLTextureUnsigned extends GLTexture { get textureType() { return this.context.UNSIGNED_BYTE; } constructor(settings) { super(settings); this.type = 'NumberTexture'; } renderRawOutput() { const { context: gl } = this; gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer()); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0 ); const result = new Uint8Array(this.size[0] * this.size[1] * 4); gl.readPixels(0, 0, this.size[0], this.size[1], gl.RGBA, gl.UNSIGNED_BYTE, result); return result; } renderValues() { if (this._deleted) return null; return new Float32Array(this.renderRawOutput().buffer); } toArray() { return utils.erectPackedFloat(this.renderValues(), this.output[0]); } } module.exports = { GLTextureUnsigned }; ================================================ FILE: src/backend/headless-gl/kernel.js ================================================ const getContext = require('gl'); const { WebGLKernel } = require('../web-gl/kernel'); const { glKernelString } = require('../gl/kernel-string'); let isSupported = null; let testCanvas = null; let testContext = null; let testExtensions = null; let features = null; class HeadlessGLKernel extends WebGLKernel { static get isSupported() { if (isSupported !== null) return isSupported; this.setupFeatureChecks(); isSupported = testContext !== null; return isSupported; } static setupFeatureChecks() { testCanvas = null; testExtensions = null; if (typeof getContext !== 'function') return; try { // just in case, edge cases testContext = getContext(2, 2, { preserveDrawingBuffer: true }); if (!testContext || !testContext.getExtension) return; testExtensions = { STACKGL_resize_drawingbuffer: testContext.getExtension('STACKGL_resize_drawingbuffer'), STACKGL_destroy_context: testContext.getExtension('STACKGL_destroy_context'), OES_texture_float: testContext.getExtension('OES_texture_float'), OES_texture_float_linear: testContext.getExtension('OES_texture_float_linear'), OES_element_index_uint: testContext.getExtension('OES_element_index_uint'), WEBGL_draw_buffers: testContext.getExtension('WEBGL_draw_buffers'), WEBGL_color_buffer_float: testContext.getExtension('WEBGL_color_buffer_float'), }; features = this.getFeatures(); } catch (e) { console.warn(e); } } static isContextMatch(context) { try { return context.getParameter(context.RENDERER) === 'ANGLE'; } catch (e) { return false; } } static getIsTextureFloat() { return Boolean(testExtensions.OES_texture_float); } static getIsDrawBuffers() { return Boolean(testExtensions.WEBGL_draw_buffers); } static getChannelCount() { return testExtensions.WEBGL_draw_buffers ? testContext.getParameter(testExtensions.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL) : 1; } static getMaxTextureSize() { return testContext.getParameter(testContext.MAX_TEXTURE_SIZE); } static get testCanvas() { return testCanvas; } static get testContext() { return testContext; } static get features() { return features; } initCanvas() { return {}; } initContext() { return getContext(2, 2, { preserveDrawingBuffer: true }); } initExtensions() { this.extensions = { STACKGL_resize_drawingbuffer: this.context.getExtension('STACKGL_resize_drawingbuffer'), STACKGL_destroy_context: this.context.getExtension('STACKGL_destroy_context'), OES_texture_float: this.context.getExtension('OES_texture_float'), OES_texture_float_linear: this.context.getExtension('OES_texture_float_linear'), OES_element_index_uint: this.context.getExtension('OES_element_index_uint'), WEBGL_draw_buffers: this.context.getExtension('WEBGL_draw_buffers'), }; } build() { super.build.apply(this, arguments); if (!this.fallbackRequested) { this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0], this.maxTexSize[1]); } } destroyExtensions() { this.extensions.STACKGL_resize_drawingbuffer = null; this.extensions.STACKGL_destroy_context = null; this.extensions.OES_texture_float = null; this.extensions.OES_texture_float_linear = null; this.extensions.OES_element_index_uint = null; this.extensions.WEBGL_draw_buffers = null; } static destroyContext(context) { const extension = context.getExtension('STACKGL_destroy_context'); if (extension && extension.destroy) { extension.destroy(); } } /** * @desc Returns the *pre-compiled* Kernel as a JS Object String, that can be reused. */ toString() { const setupContextString = `const gl = context || require('gl')(1, 1);\n`; const destroyContextString = ` if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n`; return glKernelString(this.constructor, arguments, this, setupContextString, destroyContextString); } setOutput(output) { super.setOutput(output); if (this.graphical && this.extensions.STACKGL_resize_drawingbuffer) { this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0], this.maxTexSize[1]); } return this; } } module.exports = { HeadlessGLKernel }; ================================================ FILE: src/backend/kernel-value.js ================================================ /** * @class KernelValue */ class KernelValue { /** * @param {KernelVariable} value * @param {IKernelValueSettings} settings */ constructor(value, settings) { const { name, kernel, context, checkContext, onRequestContextHandle, onUpdateValueMismatch, origin, strictIntegers, type, tactic, } = settings; if (!name) { throw new Error('name not set'); } if (!type) { throw new Error('type not set'); } if (!origin) { throw new Error('origin not set'); } if (origin !== 'user' && origin !== 'constants') { throw new Error(`origin must be "user" or "constants" value is "${ origin }"`); } if (!onRequestContextHandle) { throw new Error('onRequestContextHandle is not set'); } this.name = name; this.origin = origin; this.tactic = tactic; this.varName = origin === 'constants' ? `constants.${name}` : name; this.kernel = kernel; this.strictIntegers = strictIntegers; // handle textures this.type = value.type || type; this.size = value.size || null; this.index = null; this.context = context; this.checkContext = checkContext !== null && checkContext !== undefined ? checkContext : true; this.contextHandle = null; this.onRequestContextHandle = onRequestContextHandle; this.onUpdateValueMismatch = onUpdateValueMismatch; this.forceUploadEachRun = null; } get id() { return `${this.origin}_${name}`; } getSource() { throw new Error(`"getSource" not defined on ${ this.constructor.name }`); } updateValue(value) { throw new Error(`"updateValue" not defined on ${ this.constructor.name }`); } } module.exports = { KernelValue }; ================================================ FILE: src/backend/kernel.js ================================================ const { utils } = require('../utils'); const { Input } = require('../input'); class Kernel { /** * @type {Boolean} */ static get isSupported() { throw new Error(`"isSupported" not implemented on ${ this.name }`); } /** * @abstract * @returns {Boolean} */ static isContextMatch(context) { throw new Error(`"isContextMatch" not implemented on ${ this.name }`); } /** * @type {IKernelFeatures} * Used internally to populate the kernel.feature, which is a getter for the output of this value */ static getFeatures() { throw new Error(`"getFeatures" not implemented on ${ this.name }`); } static destroyContext(context) { throw new Error(`"destroyContext" called on ${ this.name }`); } static nativeFunctionArguments() { throw new Error(`"nativeFunctionArguments" called on ${ this.name }`); } static nativeFunctionReturnType() { throw new Error(`"nativeFunctionReturnType" called on ${ this.name }`); } static combineKernels() { throw new Error(`"combineKernels" called on ${ this.name }`); } /** * * @param {string|IKernelJSON} source * @param [settings] */ constructor(source, settings) { if (typeof source !== 'object') { if (typeof source !== 'string') { throw new Error('source not a string'); } if (!utils.isFunctionString(source)) { throw new Error('source not a function string'); } } this.useLegacyEncoder = false; this.fallbackRequested = false; this.onRequestFallback = null; /** * Name of the arguments found from parsing source argument * @type {String[]} */ this.argumentNames = typeof source === 'string' ? utils.getArgumentNamesFromString(source) : null; this.argumentTypes = null; this.argumentSizes = null; this.argumentBitRatios = null; this.kernelArguments = null; this.kernelConstants = null; this.forceUploadKernelConstants = null; /** * The function source * @type {String|IKernelJSON} */ this.source = source; /** * The size of the kernel's output * @type {Number[]} */ this.output = null; /** * Debug mode * @type {Boolean} */ this.debug = false; /** * Graphical mode * @type {Boolean} */ this.graphical = false; /** * Maximum loops when using argument values to prevent infinity * @type {Number} */ this.loopMaxIterations = 0; /** * Constants used in kernel via `this.constants` * @type {Object} */ this.constants = null; /** * * @type {Object.} */ this.constantTypes = null; /** * * @type {Object.} */ this.constantBitRatios = null; /** * * @type {boolean} */ this.dynamicArguments = false; /** * * @type {boolean} */ this.dynamicOutput = false; /** * * @type {Object} */ this.canvas = null; /** * * @type {Object} */ this.context = null; /** * * @type {Boolean} */ this.checkContext = null; /** * * @type {GPU} */ this.gpu = null; /** * * @type {IGPUFunction[]} */ this.functions = null; /** * * @type {IGPUNativeFunction[]} */ this.nativeFunctions = null; /** * * @type {String} */ this.injectedNative = null; /** * * @type {ISubKernel[]} */ this.subKernels = null; /** * * @type {Boolean} */ this.validate = true; /** * Enforces kernel to write to a new array or texture on run * @type {Boolean} */ this.immutable = false; /** * Enforces kernel to write to a texture on run * @type {Boolean} */ this.pipeline = false; /** * Make GPU use single precision or unsigned. Acceptable values: 'single' or 'unsigned' * @type {String|null} * @enum 'single' | 'unsigned' */ this.precision = null; /** * * @type {String|null} * @enum 'speed' | 'balanced' | 'precision' */ this.tactic = null; this.plugins = null; this.returnType = null; this.leadingReturnStatement = null; this.followingReturnStatement = null; this.optimizeFloatMemory = null; this.strictIntegers = false; this.fixIntegerDivisionAccuracy = null; this.built = false; this.signature = null; } /** * * @param {IDirectKernelSettings|IJSONSettings} settings */ mergeSettings(settings) { for (let p in settings) { if (!settings.hasOwnProperty(p) || !this.hasOwnProperty(p)) continue; switch (p) { case 'output': if (!Array.isArray(settings.output)) { this.setOutput(settings.output); // Flatten output object continue; } break; case 'functions': this.functions = []; for (let i = 0; i < settings.functions.length; i++) { this.addFunction(settings.functions[i]); } continue; case 'graphical': if (settings[p] && !settings.hasOwnProperty('precision')) { this.precision = 'unsigned'; } this[p] = settings[p]; continue; case 'nativeFunctions': if (!settings.nativeFunctions) continue; this.nativeFunctions = []; for (let i = 0; i < settings.nativeFunctions.length; i++) { const s = settings.nativeFunctions[i]; const { name, source } = s; this.addNativeFunction(name, source, s); } continue; } this[p] = settings[p]; } if (!this.canvas) this.canvas = this.initCanvas(); if (!this.context) this.context = this.initContext(); if (!this.plugins) this.plugins = this.initPlugins(settings); } /** * @desc Builds the Kernel, by compiling Fragment and Vertical Shaders, * and instantiates the program. * @abstract */ build() { throw new Error(`"build" not defined on ${ this.constructor.name }`); } /** * @desc Run the kernel program, and send the output to renderOutput *

This method calls a helper method *renderOutput* to return the result.

* @returns {Float32Array|Float32Array[]|Float32Array[][]|void} Result The final output of the program, as float, and as Textures for reuse. * @abstract */ run() { throw new Error(`"run" not defined on ${ this.constructor.name }`) } /** * @abstract * @return {Object} */ initCanvas() { throw new Error(`"initCanvas" not defined on ${ this.constructor.name }`); } /** * @abstract * @return {Object} */ initContext() { throw new Error(`"initContext" not defined on ${ this.constructor.name }`); } /** * @param {IDirectKernelSettings} settings * @return {string[]}; * @abstract */ initPlugins(settings) { throw new Error(`"initPlugins" not defined on ${ this.constructor.name }`); } /** * * @param {KernelFunction|string|IGPUFunction} source * @param {IFunctionSettings} [settings] * @return {Kernel} */ addFunction(source, settings = {}) { if (source.name && source.source && source.argumentTypes && 'returnType' in source) { this.functions.push(source); } else if ('settings' in source && 'source' in source) { this.functions.push(this.functionToIGPUFunction(source.source, source.settings)); } else if (typeof source === 'string' || typeof source === 'function') { this.functions.push(this.functionToIGPUFunction(source, settings)); } else { throw new Error(`function not properly defined`); } return this; } /** * * @param {string} name * @param {string} source * @param {IGPUFunctionSettings} [settings] */ addNativeFunction(name, source, settings = {}) { const { argumentTypes, argumentNames } = settings.argumentTypes ? splitArgumentTypes(settings.argumentTypes) : this.constructor.nativeFunctionArguments(source) || {}; this.nativeFunctions.push({ name, source, settings, argumentTypes, argumentNames, returnType: settings.returnType || this.constructor.nativeFunctionReturnType(source) }); return this; } /** * @desc Setup the parameter types for the parameters * supplied to the Kernel function * * @param {IArguments} args - The actual parameters sent to the Kernel */ setupArguments(args) { this.kernelArguments = []; if (!this.argumentTypes) { if (!this.argumentTypes) { this.argumentTypes = []; for (let i = 0; i < args.length; i++) { const argType = utils.getVariableType(args[i], this.strictIntegers); const type = argType === 'Integer' ? 'Number' : argType; this.argumentTypes.push(type); this.kernelArguments.push({ type }); } } } else { for (let i = 0; i < this.argumentTypes.length; i++) { this.kernelArguments.push({ type: this.argumentTypes[i] }); } } // setup sizes this.argumentSizes = new Array(args.length); this.argumentBitRatios = new Int32Array(args.length); for (let i = 0; i < args.length; i++) { const arg = args[i]; this.argumentSizes[i] = arg.constructor === Input ? arg.size : null; this.argumentBitRatios[i] = this.getBitRatio(arg); } if (this.argumentNames.length !== args.length) { throw new Error(`arguments are miss-aligned`); } } /** * Setup constants */ setupConstants() { this.kernelConstants = []; let needsConstantTypes = this.constantTypes === null; if (needsConstantTypes) { this.constantTypes = {}; } this.constantBitRatios = {}; if (this.constants) { for (let name in this.constants) { if (needsConstantTypes) { const type = utils.getVariableType(this.constants[name], this.strictIntegers); this.constantTypes[name] = type; this.kernelConstants.push({ name, type }); } else { this.kernelConstants.push({ name, type: this.constantTypes[name] }); } this.constantBitRatios[name] = this.getBitRatio(this.constants[name]); } } } /** * * @param flag * @return {this} */ setOptimizeFloatMemory(flag) { this.optimizeFloatMemory = flag; return this; } /** * * @param {Array|Object} output * @return {number[]} */ toKernelOutput(output) { if (output.hasOwnProperty('x')) { if (output.hasOwnProperty('y')) { if (output.hasOwnProperty('z')) { return [output.x, output.y, output.z]; } else { return [output.x, output.y]; } } else { return [output.x]; } } else { return output; } } /** * @desc Set output dimensions of the kernel function * @param {Array|Object} output - The output array to set the kernel output size to * @return {this} */ setOutput(output) { this.output = this.toKernelOutput(output); return this; } /** * @desc Toggle debug mode * @param {Boolean} flag - true to enable debug * @return {this} */ setDebug(flag) { this.debug = flag; return this; } /** * @desc Toggle graphical output mode * @param {Boolean} flag - true to enable graphical output * @return {this} */ setGraphical(flag) { this.graphical = flag; this.precision = 'unsigned'; return this; } /** * @desc Set the maximum number of loop iterations * @param {number} max - iterations count * @return {this} */ setLoopMaxIterations(max) { this.loopMaxIterations = max; return this; } /** * @desc Set Constants * @return {this} */ setConstants(constants) { this.constants = constants; return this; } /** * * @param {IKernelValueTypes} constantTypes * @return {this} */ setConstantTypes(constantTypes) { this.constantTypes = constantTypes; return this; } /** * * @param {IFunction[]|KernelFunction[]} functions * @return {this} */ setFunctions(functions) { for (let i = 0; i < functions.length; i++) { this.addFunction(functions[i]); } return this; } /** * * @param {IGPUNativeFunction[]} nativeFunctions * @return {this} */ setNativeFunctions(nativeFunctions) { for (let i = 0; i < nativeFunctions.length; i++) { const settings = nativeFunctions[i]; const { name, source } = settings; this.addNativeFunction(name, source, settings); } return this; } /** * * @param {String} injectedNative * @return {this} */ setInjectedNative(injectedNative) { this.injectedNative = injectedNative; return this; } /** * Set writing to texture on/off * @param flag * @return {this} */ setPipeline(flag) { this.pipeline = flag; return this; } /** * Set precision to 'unsigned' or 'single' * @param {String} flag 'unsigned' or 'single' * @return {this} */ setPrecision(flag) { this.precision = flag; return this; } /** * @param flag * @return {Kernel} * @deprecated */ setDimensions(flag) { utils.warnDeprecated('method', 'setDimensions', 'setOutput'); this.output = flag; return this; } /** * @param flag * @return {this} * @deprecated */ setOutputToTexture(flag) { utils.warnDeprecated('method', 'setOutputToTexture', 'setPipeline'); this.pipeline = flag; return this; } /** * Set to immutable * @param flag * @return {this} */ setImmutable(flag) { this.immutable = flag; return this; } /** * @desc Bind the canvas to kernel * @param {Object} canvas * @return {this} */ setCanvas(canvas) { this.canvas = canvas; return this; } /** * @param {Boolean} flag * @return {this} */ setStrictIntegers(flag) { this.strictIntegers = flag; return this; } /** * * @param flag * @return {this} */ setDynamicOutput(flag) { this.dynamicOutput = flag; return this; } /** * @deprecated * @param flag * @return {this} */ setHardcodeConstants(flag) { utils.warnDeprecated('method', 'setHardcodeConstants'); this.setDynamicOutput(flag); this.setDynamicArguments(flag); return this; } /** * * @param flag * @return {this} */ setDynamicArguments(flag) { this.dynamicArguments = flag; return this; } /** * @param {Boolean} flag * @return {this} */ setUseLegacyEncoder(flag) { this.useLegacyEncoder = flag; return this; } /** * * @param {Boolean} flag * @return {this} */ setWarnVarUsage(flag) { utils.warnDeprecated('method', 'setWarnVarUsage'); return this; } /** * @deprecated * @returns {Object} */ getCanvas() { utils.warnDeprecated('method', 'getCanvas'); return this.canvas; } /** * @deprecated * @returns {Object} */ getWebGl() { utils.warnDeprecated('method', 'getWebGl'); return this.context; } /** * @desc Bind the webGL instance to kernel * @param {WebGLRenderingContext} context - webGl instance to bind */ setContext(context) { this.context = context; return this; } /** * * @param {IKernelValueTypes|GPUVariableType[]} argumentTypes * @return {this} */ setArgumentTypes(argumentTypes) { if (Array.isArray(argumentTypes)) { this.argumentTypes = argumentTypes; } else { this.argumentTypes = []; for (const p in argumentTypes) { if (!argumentTypes.hasOwnProperty(p)) continue; const argumentIndex = this.argumentNames.indexOf(p); if (argumentIndex === -1) throw new Error(`unable to find argument ${ p }`); this.argumentTypes[argumentIndex] = argumentTypes[p]; } } return this; } /** * * @param {Tactic} tactic * @return {this} */ setTactic(tactic) { this.tactic = tactic; return this; } requestFallback(args) { if (!this.onRequestFallback) { throw new Error(`"onRequestFallback" not defined on ${ this.constructor.name }`); } this.fallbackRequested = true; return this.onRequestFallback(args); } /** * @desc Validate settings * @abstract */ validateSettings() { throw new Error(`"validateSettings" not defined on ${ this.constructor.name }`); } /** * @desc Add a sub kernel to the root kernel instance. * This is what `createKernelMap` uses. * * @param {ISubKernel} subKernel - function (as a String) of the subKernel to add */ addSubKernel(subKernel) { if (this.subKernels === null) { this.subKernels = []; } if (!subKernel.source) throw new Error('subKernel missing "source" property'); if (!subKernel.property && isNaN(subKernel.property)) throw new Error('subKernel missing "property" property'); if (!subKernel.name) throw new Error('subKernel missing "name" property'); this.subKernels.push(subKernel); return this; } /** * @desc Destroys all memory associated with this kernel * @param {Boolean} [removeCanvasReferences] remove any associated canvas references */ destroy(removeCanvasReferences) { throw new Error(`"destroy" called on ${ this.constructor.name }`); } /** * bit storage ratio of source to target 'buffer', i.e. if 8bit array -> 32bit tex = 4 * @param value * @returns {number} */ getBitRatio(value) { if (this.precision === 'single') { // 8 and 16 are up-converted to float32 return 4; } else if (Array.isArray(value[0])) { return this.getBitRatio(value[0]); } else if (value.constructor === Input) { return this.getBitRatio(value.value); } switch (value.constructor) { case Uint8ClampedArray: case Uint8Array: case Int8Array: return 1; case Uint16Array: case Int16Array: return 2; case Float32Array: case Int32Array: default: return 4; } } /** * @param {Boolean} [flip] * @returns {Uint8ClampedArray} */ getPixels(flip) { throw new Error(`"getPixels" called on ${ this.constructor.name }`); } checkOutput() { if (!this.output || !utils.isArray(this.output)) throw new Error('kernel.output not an array'); if (this.output.length < 1) throw new Error('kernel.output is empty, needs at least 1 value'); for (let i = 0; i < this.output.length; i++) { if (isNaN(this.output[i]) || this.output[i] < 1) { throw new Error(`${ this.constructor.name }.output[${ i }] incorrectly defined as \`${ this.output[i] }\`, needs to be numeric, and greater than 0`); } } } /** * * @param {String} value */ prependString(value) { throw new Error(`"prependString" called on ${ this.constructor.name }`); } /** * * @param {String} value * @return Boolean */ hasPrependString(value) { throw new Error(`"hasPrependString" called on ${ this.constructor.name }`); } /** * @return {IKernelJSON} */ toJSON() { return { settings: { output: this.output, pipeline: this.pipeline, argumentNames: this.argumentNames, argumentsTypes: this.argumentTypes, constants: this.constants, pluginNames: this.plugins ? this.plugins.map(plugin => plugin.name) : null, returnType: this.returnType, } }; } /** * @param {IArguments} args */ buildSignature(args) { const Constructor = this.constructor; this.signature = Constructor.getSignature(this, Constructor.getArgumentTypes(this, args)); } /** * @param {Kernel} kernel * @param {IArguments} args * @returns GPUVariableType[] */ static getArgumentTypes(kernel, args) { const argumentTypes = new Array(args.length); for (let i = 0; i < args.length; i++) { const arg = args[i]; const type = kernel.argumentTypes[i]; if (arg.type) { argumentTypes[i] = arg.type; } else { switch (type) { case 'Number': case 'Integer': case 'Float': case 'ArrayTexture(1)': argumentTypes[i] = utils.getVariableType(arg); break; default: argumentTypes[i] = type; } } } return argumentTypes; } /** * * @param {Kernel} kernel * @param {GPUVariableType[]} argumentTypes * @abstract */ static getSignature(kernel, argumentTypes) { throw new Error(`"getSignature" not implemented on ${ this.name }`); } /** * * @param {String|Function} source * @param {IFunctionSettings} [settings] * @returns {IGPUFunction} */ functionToIGPUFunction(source, settings = {}) { if (typeof source !== 'string' && typeof source !== 'function') throw new Error('source not a string or function'); const sourceString = typeof source === 'string' ? source : source.toString(); let argumentTypes = []; if (Array.isArray(settings.argumentTypes)) { argumentTypes = settings.argumentTypes; } else if (typeof settings.argumentTypes === 'object') { argumentTypes = utils.getArgumentNamesFromString(sourceString) .map(name => settings.argumentTypes[name]) || []; } else { argumentTypes = settings.argumentTypes || []; } return { name: utils.getFunctionNameFromString(sourceString) || null, source: sourceString, argumentTypes, returnType: settings.returnType || null, }; } /** * * @param {Kernel} previousKernel * @abstract */ onActivate(previousKernel) {} } function splitArgumentTypes(argumentTypesObject) { const argumentNames = Object.keys(argumentTypesObject); const argumentTypes = []; for (let i = 0; i < argumentNames.length; i++) { const argumentName = argumentNames[i]; argumentTypes.push(argumentTypesObject[argumentName]); } return { argumentTypes, argumentNames }; } module.exports = { Kernel }; ================================================ FILE: src/backend/web-gl/fragment-shader.js ================================================ // language=GLSL const fragmentShader = `__HEADER__; __FLOAT_TACTIC_DECLARATION__; __INT_TACTIC_DECLARATION__; __SAMPLER_2D_TACTIC_DECLARATION__; const int LOOP_MAX = __LOOP_MAX__; __PLUGINS__; __CONSTANTS__; varying vec2 vTexCoord; float acosh(float x) { return log(x + sqrt(x * x - 1.0)); } float sinh(float x) { return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0; } float asinh(float x) { return log(x + sqrt(x * x + 1.0)); } float atan2(float v1, float v2) { if (v1 == 0.0 || v2 == 0.0) return 0.0; return atan(v1 / v2); } float atanh(float x) { x = (x + 1.0) / (x - 1.0); if (x < 0.0) { return 0.5 * log(-x); } return 0.5 * log(x); } float cbrt(float x) { if (x >= 0.0) { return pow(x, 1.0 / 3.0); } else { return -pow(x, 1.0 / 3.0); } } float cosh(float x) { return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; } float expm1(float x) { return pow(${Math.E}, x) - 1.0; } float fround(highp float x) { return x; } float imul(float v1, float v2) { return float(int(v1) * int(v2)); } float log10(float x) { return log2(x) * (1.0 / log2(10.0)); } float log1p(float x) { return log(1.0 + x); } float _pow(float v1, float v2) { if (v2 == 0.0) return 1.0; return pow(v1, v2); } float tanh(float x) { float e = exp(2.0 * x); return (e - 1.0) / (e + 1.0); } float trunc(float x) { if (x >= 0.0) { return floor(x); } else { return ceil(x); } } vec4 _round(vec4 x) { return floor(x + 0.5); } float _round(float x) { return floor(x + 0.5); } const int BIT_COUNT = 32; int modi(int x, int y) { return x - y * (x / y); } int bitwiseOr(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 || b > 0)) { break; } } return result; } int bitwiseXOR(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 || b > 0)) { break; } } return result; } int bitwiseAnd(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 && b > 0)) { break; } } return result; } int bitwiseNot(int a) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if (modi(a, 2) == 0) { result += n; } a = a / 2; n = n * 2; } return result; } int bitwiseZeroFillLeftShift(int n, int shift) { int maxBytes = BIT_COUNT; for (int i = 0; i < BIT_COUNT; i++) { if (maxBytes >= n) { break; } maxBytes *= 2; } for (int i = 0; i < BIT_COUNT; i++) { if (i >= shift) { break; } n *= 2; } int result = 0; int byteVal = 1; for (int i = 0; i < BIT_COUNT; i++) { if (i >= maxBytes) break; if (modi(n, 2) > 0) { result += byteVal; } n = int(n / 2); byteVal *= 2; } return result; } int bitwiseSignedRightShift(int num, int shifts) { return int(floor(float(num) / pow(2.0, float(shifts)))); } int bitwiseZeroFillRightShift(int n, int shift) { int maxBytes = BIT_COUNT; for (int i = 0; i < BIT_COUNT; i++) { if (maxBytes >= n) { break; } maxBytes *= 2; } for (int i = 0; i < BIT_COUNT; i++) { if (i >= shift) { break; } n /= 2; } int result = 0; int byteVal = 1; for (int i = 0; i < BIT_COUNT; i++) { if (i >= maxBytes) break; if (modi(n, 2) > 0) { result += byteVal; } n = int(n / 2); byteVal *= 2; } return result; } vec2 integerMod(vec2 x, float y) { vec2 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } vec3 integerMod(vec3 x, float y) { vec3 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } vec4 integerMod(vec4 x, vec4 y) { vec4 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } float integerMod(float x, float y) { float res = floor(mod(x, y)); return res * (res > floor(y) - 1.0 ? 0.0 : 1.0); } int integerMod(int x, int y) { return x - (y * int(x / y)); } __DIVIDE_WITH_INTEGER_CHECK__; // Here be dragons! // DO NOT OPTIMIZE THIS CODE // YOU WILL BREAK SOMETHING ON SOMEBODY\'S MACHINE // LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME const vec2 MAGIC_VEC = vec2(1.0, -256.0); const vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0); const vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536 float decode32(vec4 texel) { __DECODE32_ENDIANNESS__; texel *= 255.0; vec2 gte128; gte128.x = texel.b >= 128.0 ? 1.0 : 0.0; gte128.y = texel.a >= 128.0 ? 1.0 : 0.0; float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC); float res = exp2(_round(exponent)); texel.b = texel.b - 128.0 * gte128.x; res = dot(texel, SCALE_FACTOR) * exp2(_round(exponent-23.0)) + res; res *= gte128.y * -2.0 + 1.0; return res; } float decode16(vec4 texel, int index) { int channel = integerMod(index, 2); if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0; if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0; return 0.0; } float decode8(vec4 texel, int index) { int channel = integerMod(index, 4); if (channel == 0) return texel.r * 255.0; if (channel == 1) return texel.g * 255.0; if (channel == 2) return texel.b * 255.0; if (channel == 3) return texel.a * 255.0; return 0.0; } vec4 legacyEncode32(float f) { float F = abs(f); float sign = f < 0.0 ? 1.0 : 0.0; float exponent = floor(log2(F)); float mantissa = (exp2(-exponent) * F); // exponent += floor(log2(mantissa)); vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV; texel.rg = integerMod(texel.rg, 256.0); texel.b = integerMod(texel.b, 128.0); texel.a = exponent*0.5 + 63.5; texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0; texel = floor(texel); texel *= 0.003921569; // 1/255 __ENCODE32_ENDIANNESS__; return texel; } // https://github.com/gpujs/gpu.js/wiki/Encoder-details vec4 encode32(float value) { if (value == 0.0) return vec4(0, 0, 0, 0); float exponent; float mantissa; vec4 result; float sgn; sgn = step(0.0, -value); value = abs(value); exponent = floor(log2(value)); mantissa = value*pow(2.0, -exponent)-1.0; exponent = exponent+127.0; result = vec4(0,0,0,0); result.a = floor(exponent/2.0); exponent = exponent - result.a*2.0; result.a = result.a + 128.0*sgn; result.b = floor(mantissa * 128.0); mantissa = mantissa - result.b / 128.0; result.b = result.b + exponent*128.0; result.g = floor(mantissa*32768.0); mantissa = mantissa - result.g/32768.0; result.r = floor(mantissa*8388608.0); return result/255.0; } // Dragons end here int index; ivec3 threadId; ivec3 indexTo3D(int idx, ivec3 texDim) { int z = int(idx / (texDim.x * texDim.y)); idx -= z * int(texDim.x * texDim.y); int y = int(idx / texDim.x); int x = int(integerMod(idx, texDim.x)); return ivec3(x, y, z); } float get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize)); return decode32(texel); } float get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x * 2; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y)); return decode16(texel, index); } float get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x * 4; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y)); return decode8(texel, index); } float getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int channel = integerMod(index, 4); index = index / 4; int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize)); if (channel == 0) return texel.r; if (channel == 1) return texel.g; if (channel == 2) return texel.b; if (channel == 3) return texel.a; return 0.0; } vec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; return texture2D(tex, st / vec2(texSize)); } float getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return result[0]; } vec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return vec2(result[0], result[1]); } vec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + (texDim.x * (y + (texDim.y * z))); int channel = integerMod(index, 2); index = index / 2; int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize)); if (channel == 0) return vec2(texel.r, texel.g); if (channel == 1) return vec2(texel.b, texel.a); return vec2(0.0, 0.0); } vec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return vec3(result[0], result[1], result[2]); } vec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z)); int vectorIndex = fieldIndex / 4; int vectorOffset = fieldIndex - vectorIndex * 4; int readY = vectorIndex / texSize.x; int readX = vectorIndex - readY * texSize.x; vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize)); if (vectorOffset == 0) { return tex1.xyz; } else if (vectorOffset == 1) { return tex1.yzw; } else { readX++; if (readX >= texSize.x) { readX = 0; readY++; } vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize)); if (vectorOffset == 2) { return vec3(tex1.z, tex1.w, tex2.x); } else { return vec3(tex1.w, tex2.x, tex2.y); } } } vec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { return getImage2D(tex, texSize, texDim, z, y, x); } vec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int channel = integerMod(index, 2); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture2D(tex, st / vec2(texSize)); return vec4(texel.r, texel.g, texel.b, texel.a); } vec4 actualColor; void color(float r, float g, float b, float a) { actualColor = vec4(r,g,b,a); } void color(float r, float g, float b) { color(r,g,b,1.0); } void color(sampler2D image) { actualColor = texture2D(image, vTexCoord); } float modulo(float number, float divisor) { if (number < 0.0) { number = abs(number); if (divisor < 0.0) { divisor = abs(divisor); } return -mod(number, divisor); } if (divisor < 0.0) { divisor = abs(divisor); } return mod(number, divisor); } __INJECTED_NATIVE__; __MAIN_CONSTANTS__; __MAIN_ARGUMENTS__; __KERNEL__; void main(void) { index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x; __MAIN_RESULT__; }`; module.exports = { fragmentShader }; ================================================ FILE: src/backend/web-gl/function-node.js ================================================ const { utils } = require('../../utils'); const { FunctionNode } = require('../function-node'); /** * @desc [INTERNAL] Takes in a function node, and does all the AST voodoo required to toString its respective WebGL code */ class WebGLFunctionNode extends FunctionNode { constructor(source, settings) { super(source, settings); if (settings && settings.hasOwnProperty('fixIntegerDivisionAccuracy')) { this.fixIntegerDivisionAccuracy = settings.fixIntegerDivisionAccuracy; } } astConditionalExpression(ast, retArr) { if (ast.type !== 'ConditionalExpression') { throw this.astErrorOutput('Not a conditional expression', ast); } const consequentType = this.getType(ast.consequent); const alternateType = this.getType(ast.alternate); // minification handling if void if (consequentType === null && alternateType === null) { retArr.push('if ('); this.astGeneric(ast.test, retArr); retArr.push(') {'); this.astGeneric(ast.consequent, retArr); retArr.push(';'); retArr.push('} else {'); this.astGeneric(ast.alternate, retArr); retArr.push(';'); retArr.push('}'); return retArr; } retArr.push('('); this.astGeneric(ast.test, retArr); retArr.push('?'); this.astGeneric(ast.consequent, retArr); retArr.push(':'); this.astGeneric(ast.alternate, retArr); retArr.push(')'); return retArr; } /** * @desc Parses the abstract syntax tree for to its *named function* * @param {Object} ast - the AST object to parse * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astFunction(ast, retArr) { // Setup function return type and name if (this.isRootKernel) { retArr.push('void'); } else { // looking up return type, this is a little expensive, and can be avoided if returnType is set if (!this.returnType) { const lastReturn = this.findLastReturn(); if (lastReturn) { this.returnType = this.getType(ast.body); if (this.returnType === 'LiteralInteger') { this.returnType = 'Number'; } } } const { returnType } = this; if (!returnType) { retArr.push('void'); } else { const type = typeMap[returnType]; if (!type) { throw new Error(`unknown type ${returnType}`); } retArr.push(type); } } retArr.push(' '); retArr.push(this.name); retArr.push('('); if (!this.isRootKernel) { // Arguments handling for (let i = 0; i < this.argumentNames.length; ++i) { const argumentName = this.argumentNames[i]; if (i > 0) { retArr.push(', '); } let argumentType = this.argumentTypes[this.argumentNames.indexOf(argumentName)]; // The type is too loose ended, here we decide to solidify a type, lets go with float if (!argumentType) { throw this.astErrorOutput(`Unknown argument ${argumentName} type`, ast); } if (argumentType === 'LiteralInteger') { this.argumentTypes[i] = argumentType = 'Number'; } const type = typeMap[argumentType]; if (!type) { throw this.astErrorOutput('Unexpected expression', ast); } const name = utils.sanitizeName(argumentName); if (type === 'sampler2D' || type === 'sampler2DArray') { // mash needed arguments together, since now we have end to end inference retArr.push(`${type} user_${name},ivec2 user_${name}Size,ivec3 user_${name}Dim`); } else { retArr.push(`${type} user_${name}`); } } } // Function opening retArr.push(') {\n'); // Body statement iteration for (let i = 0; i < ast.body.body.length; ++i) { this.astGeneric(ast.body.body[i], retArr); retArr.push('\n'); } // Function closing retArr.push('}\n'); return retArr; } /** * @desc Parses the abstract syntax tree for to *return* statement * @param {Object} ast - the AST object to parse * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astReturnStatement(ast, retArr) { if (!ast.argument) throw this.astErrorOutput('Unexpected return statement', ast); this.pushState('skip-literal-correction'); const type = this.getType(ast.argument); this.popState('skip-literal-correction'); const result = []; if (!this.returnType) { if (type === 'LiteralInteger' || type === 'Integer') { this.returnType = 'Number'; } else { this.returnType = type; } } switch (this.returnType) { case 'LiteralInteger': case 'Number': case 'Float': switch (type) { case 'Integer': result.push('float('); this.astGeneric(ast.argument, result); result.push(')'); break; case 'LiteralInteger': this.castLiteralToFloat(ast.argument, result); // Running astGeneric forces the LiteralInteger to pick a type, and here, if we are returning a float, yet // the LiteralInteger has picked to be an integer because of constraints on it we cast it to float. if (this.getType(ast) === 'Integer') { result.unshift('float('); result.push(')'); } break; default: this.astGeneric(ast.argument, result); } break; case 'Integer': switch (type) { case 'Float': case 'Number': this.castValueToInteger(ast.argument, result); break; case 'LiteralInteger': this.castLiteralToInteger(ast.argument, result); break; default: this.astGeneric(ast.argument, result); } break; case 'Array(4)': case 'Array(3)': case 'Array(2)': case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': case 'Input': this.astGeneric(ast.argument, result); break; default: throw this.astErrorOutput(`unhandled return type ${this.returnType}`, ast); } if (this.isRootKernel) { retArr.push(`kernelResult = ${ result.join('') };`); retArr.push('return;'); } else if (this.isSubKernel) { retArr.push(`subKernelResult_${ this.name } = ${ result.join('') };`); retArr.push(`return subKernelResult_${ this.name };`); } else { retArr.push(`return ${ result.join('') };`); } return retArr; } /** * @desc Parses the abstract syntax tree for *literal value* * * @param {Object} ast - the AST object to parse * @param {Array} retArr - return array string * * @returns {Array} the append retArr */ astLiteral(ast, retArr) { // Reject non numeric literals if (isNaN(ast.value)) { throw this.astErrorOutput( 'Non-numeric literal not supported : ' + ast.value, ast ); } const key = this.astKey(ast); if (Number.isInteger(ast.value)) { if (this.isState('casting-to-integer') || this.isState('building-integer')) { this.literalTypes[key] = 'Integer'; retArr.push(`${ast.value}`); } else if (this.isState('casting-to-float') || this.isState('building-float')) { this.literalTypes[key] = 'Number'; retArr.push(`${ast.value}.0`); } else { this.literalTypes[key] = 'Number'; retArr.push(`${ast.value}.0`); } } else if (this.isState('casting-to-integer') || this.isState('building-integer')) { this.literalTypes[key] = 'Integer'; retArr.push(Math.round(ast.value)); } else { this.literalTypes[key] = 'Number'; retArr.push(`${ast.value}`); } return retArr; } /** * @desc Parses the abstract syntax tree for *binary* expression * @param {Object} ast - the AST object to parse * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astBinaryExpression(ast, retArr) { if (this.checkAndUpconvertOperator(ast, retArr)) { return retArr; } if (this.fixIntegerDivisionAccuracy && ast.operator === '/') { retArr.push('divWithIntCheck('); this.pushState('building-float'); switch (this.getType(ast.left)) { case 'Integer': this.castValueToFloat(ast.left, retArr); break; case 'LiteralInteger': this.castLiteralToFloat(ast.left, retArr); break; default: this.astGeneric(ast.left, retArr); } retArr.push(', '); switch (this.getType(ast.right)) { case 'Integer': this.castValueToFloat(ast.right, retArr); break; case 'LiteralInteger': this.castLiteralToFloat(ast.right, retArr); break; default: this.astGeneric(ast.right, retArr); } this.popState('building-float'); retArr.push(')'); return retArr; } retArr.push('('); const leftType = this.getType(ast.left) || 'Number'; const rightType = this.getType(ast.right) || 'Number'; if (!leftType || !rightType) { throw this.astErrorOutput(`Unhandled binary expression`, ast); } const key = leftType + ' & ' + rightType; switch (key) { case 'Integer & Integer': this.pushState('building-integer'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-integer'); break; case 'Number & Float': case 'Float & Number': case 'Float & Float': case 'Number & Number': this.pushState('building-float'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-float'); break; case 'LiteralInteger & LiteralInteger': if (this.isState('casting-to-integer') || this.isState('building-integer')) { this.pushState('building-integer'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-integer'); } else { this.pushState('building-float'); this.castLiteralToFloat(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castLiteralToFloat(ast.right, retArr); this.popState('building-float'); } break; case 'Integer & Float': case 'Integer & Number': if (ast.operator === '>' || ast.operator === '<' && ast.right.type === 'Literal') { // if right value is actually a float, don't loose that information, cast left to right rather than the usual right to left if (!Number.isInteger(ast.right.value)) { this.pushState('building-float'); this.castValueToFloat(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-float'); break; } } this.pushState('building-integer'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.pushState('casting-to-integer'); if (ast.right.type === 'Literal') { const literalResult = []; this.astGeneric(ast.right, literalResult); const literalType = this.getType(ast.right); if (literalType === 'Integer') { retArr.push(literalResult.join('')); } else { throw this.astErrorOutput(`Unhandled binary expression with literal`, ast); } } else { retArr.push('int('); this.astGeneric(ast.right, retArr); retArr.push(')'); } this.popState('casting-to-integer'); this.popState('building-integer'); break; case 'Integer & LiteralInteger': this.pushState('building-integer'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castLiteralToInteger(ast.right, retArr); this.popState('building-integer'); break; case 'Number & Integer': this.pushState('building-float'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castValueToFloat(ast.right, retArr); this.popState('building-float'); break; case 'Float & LiteralInteger': case 'Number & LiteralInteger': this.pushState('building-float'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castLiteralToFloat(ast.right, retArr); this.popState('building-float'); break; case 'LiteralInteger & Float': case 'LiteralInteger & Number': if (this.isState('casting-to-integer')) { this.pushState('building-integer'); this.castLiteralToInteger(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castValueToInteger(ast.right, retArr); this.popState('building-integer'); } else { this.pushState('building-float'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.pushState('casting-to-float'); this.astGeneric(ast.right, retArr); this.popState('casting-to-float'); this.popState('building-float'); } break; case 'LiteralInteger & Integer': this.pushState('building-integer'); this.castLiteralToInteger(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-integer'); break; case 'Boolean & Boolean': this.pushState('building-boolean'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.astGeneric(ast.right, retArr); this.popState('building-boolean'); break; case 'Float & Integer': this.pushState('building-float'); this.astGeneric(ast.left, retArr); retArr.push(operatorMap[ast.operator] || ast.operator); this.castValueToFloat(ast.right, retArr); this.popState('building-float'); break; default: throw this.astErrorOutput(`Unhandled binary expression between ${key}`, ast); } retArr.push(')'); return retArr; } checkAndUpconvertOperator(ast, retArr) { const bitwiseResult = this.checkAndUpconvertBitwiseOperators(ast, retArr); if (bitwiseResult) { return bitwiseResult; } const upconvertableOperators = { '%': this.fixIntegerDivisionAccuracy ? 'integerCorrectionModulo' : 'modulo', '**': 'pow', }; const foundOperator = upconvertableOperators[ast.operator]; if (!foundOperator) return null; retArr.push(foundOperator); retArr.push('('); switch (this.getType(ast.left)) { case 'Integer': this.castValueToFloat(ast.left, retArr); break; case 'LiteralInteger': this.castLiteralToFloat(ast.left, retArr); break; default: this.astGeneric(ast.left, retArr); } retArr.push(','); switch (this.getType(ast.right)) { case 'Integer': this.castValueToFloat(ast.right, retArr); break; case 'LiteralInteger': this.castLiteralToFloat(ast.right, retArr); break; default: this.astGeneric(ast.right, retArr); } retArr.push(')'); return retArr; } checkAndUpconvertBitwiseOperators(ast, retArr) { const upconvertableOperators = { '&': 'bitwiseAnd', '|': 'bitwiseOr', '^': 'bitwiseXOR', '<<': 'bitwiseZeroFillLeftShift', '>>': 'bitwiseSignedRightShift', '>>>': 'bitwiseZeroFillRightShift', }; const foundOperator = upconvertableOperators[ast.operator]; if (!foundOperator) return null; retArr.push(foundOperator); retArr.push('('); const leftType = this.getType(ast.left); switch (leftType) { case 'Number': case 'Float': this.castValueToInteger(ast.left, retArr); break; case 'LiteralInteger': this.castLiteralToInteger(ast.left, retArr); break; default: this.astGeneric(ast.left, retArr); } retArr.push(','); const rightType = this.getType(ast.right); switch (rightType) { case 'Number': case 'Float': this.castValueToInteger(ast.right, retArr); break; case 'LiteralInteger': this.castLiteralToInteger(ast.right, retArr); break; default: this.astGeneric(ast.right, retArr); } retArr.push(')'); return retArr; } checkAndUpconvertBitwiseUnary(ast, retArr) { const upconvertableOperators = { '~': 'bitwiseNot', }; const foundOperator = upconvertableOperators[ast.operator]; if (!foundOperator) return null; retArr.push(foundOperator); retArr.push('('); switch (this.getType(ast.argument)) { case 'Number': case 'Float': this.castValueToInteger(ast.argument, retArr); break; case 'LiteralInteger': this.castLiteralToInteger(ast.argument, retArr); break; default: this.astGeneric(ast.argument, retArr); } retArr.push(')'); return retArr; } /** * * @param {Object} ast * @param {Array} retArr * @return {String[]} */ castLiteralToInteger(ast, retArr) { this.pushState('casting-to-integer'); this.astGeneric(ast, retArr); this.popState('casting-to-integer'); return retArr; } /** * * @param {Object} ast * @param {Array} retArr * @return {String[]} */ castLiteralToFloat(ast, retArr) { this.pushState('casting-to-float'); this.astGeneric(ast, retArr); this.popState('casting-to-float'); return retArr; } /** * * @param {Object} ast * @param {Array} retArr * @return {String[]} */ castValueToInteger(ast, retArr) { this.pushState('casting-to-integer'); retArr.push('int('); this.astGeneric(ast, retArr); retArr.push(')'); this.popState('casting-to-integer'); return retArr; } /** * * @param {Object} ast * @param {Array} retArr * @return {String[]} */ castValueToFloat(ast, retArr) { this.pushState('casting-to-float'); retArr.push('float('); this.astGeneric(ast, retArr); retArr.push(')'); this.popState('casting-to-float'); return retArr; } /** * @desc Parses the abstract syntax tree for *identifier* expression * @param {Object} idtNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astIdentifierExpression(idtNode, retArr) { if (idtNode.type !== 'Identifier') { throw this.astErrorOutput('IdentifierExpression - not an Identifier', idtNode); } const type = this.getType(idtNode); const name = utils.sanitizeName(idtNode.name); if (idtNode.name === 'Infinity') { // https://stackoverflow.com/a/47543127/1324039 retArr.push('3.402823466e+38'); } else if (type === 'Boolean') { if (this.argumentNames.indexOf(name) > -1) { retArr.push(`bool(user_${name})`); } else { retArr.push(`user_${name}`); } } else { retArr.push(`user_${name}`); } return retArr; } /** * @desc Parses the abstract syntax tree for *for-loop* expression * @param {Object} forNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the parsed webgl string */ astForStatement(forNode, retArr) { if (forNode.type !== 'ForStatement') { throw this.astErrorOutput('Invalid for statement', forNode); } const initArr = []; const testArr = []; const updateArr = []; const bodyArr = []; let isSafe = null; if (forNode.init) { const { declarations } = forNode.init; if (declarations.length > 1) { isSafe = false; } this.astGeneric(forNode.init, initArr); for (let i = 0; i < declarations.length; i++) { if (declarations[i].init && declarations[i].init.type !== 'Literal') { isSafe = false; } } } else { isSafe = false; } if (forNode.test) { this.astGeneric(forNode.test, testArr); } else { isSafe = false; } if (forNode.update) { this.astGeneric(forNode.update, updateArr); } else { isSafe = false; } if (forNode.body) { this.pushState('loop-body'); this.astGeneric(forNode.body, bodyArr); this.popState('loop-body'); } // have all parts, now make them safe if (isSafe === null) { isSafe = this.isSafe(forNode.init) && this.isSafe(forNode.test); } if (isSafe) { const initString = initArr.join(''); const initNeedsSemiColon = initString[initString.length - 1] !== ';'; retArr.push(`for (${initString}${initNeedsSemiColon ? ';' : ''}${testArr.join('')};${updateArr.join('')}){\n`); retArr.push(bodyArr.join('')); retArr.push('}\n'); } else { const iVariableName = this.getInternalVariableName('safeI'); if (initArr.length > 0) { retArr.push(initArr.join(''), '\n'); } retArr.push(`for (int ${iVariableName}=0;${iVariableName} 0) { retArr.push(`if (!${testArr.join('')}) break;\n`); } retArr.push(bodyArr.join('')); retArr.push(`\n${updateArr.join('')};`); retArr.push('}\n'); } return retArr; } /** * @desc Parses the abstract syntax tree for *while* loop * @param {Object} whileNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the parsed webgl string */ astWhileStatement(whileNode, retArr) { if (whileNode.type !== 'WhileStatement') { throw this.astErrorOutput('Invalid while statement', whileNode); } const iVariableName = this.getInternalVariableName('safeI'); retArr.push(`for (int ${iVariableName}=0;${iVariableName} 0) { declarationSets.push(declarationSet.join(',')); } result.push(declarationSets.join(';')); retArr.push(result.join('')); retArr.push(';'); return retArr; } /** * @desc Parses the abstract syntax tree for *If* Statement * @param {Object} ifNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astIfStatement(ifNode, retArr) { retArr.push('if ('); this.astGeneric(ifNode.test, retArr); retArr.push(')'); if (ifNode.consequent.type === 'BlockStatement') { this.astGeneric(ifNode.consequent, retArr); } else { retArr.push(' {\n'); this.astGeneric(ifNode.consequent, retArr); retArr.push('\n}\n'); } if (ifNode.alternate) { retArr.push('else '); if (ifNode.alternate.type === 'BlockStatement' || ifNode.alternate.type === 'IfStatement') { this.astGeneric(ifNode.alternate, retArr); } else { retArr.push(' {\n'); this.astGeneric(ifNode.alternate, retArr); retArr.push('\n}\n'); } } return retArr; } astSwitchStatement(ast, retArr) { if (ast.type !== 'SwitchStatement') { throw this.astErrorOutput('Invalid switch statement', ast); } const { discriminant, cases } = ast; const type = this.getType(discriminant); const varName = `switchDiscriminant${this.astKey(ast, '_')}`; switch (type) { case 'Float': case 'Number': retArr.push(`float ${varName} = `); this.astGeneric(discriminant, retArr); retArr.push(';\n'); break; case 'Integer': retArr.push(`int ${varName} = `); this.astGeneric(discriminant, retArr); retArr.push(';\n'); break; } // switch with just a default: if (cases.length === 1 && !cases[0].test) { this.astGeneric(cases[0].consequent, retArr); return retArr; } // regular switches: let fallingThrough = false; let defaultResult = []; let movingDefaultToEnd = false; let pastFirstIf = false; for (let i = 0; i < cases.length; i++) { // default if (!cases[i].test) { if (cases.length > i + 1) { movingDefaultToEnd = true; this.astGeneric(cases[i].consequent, defaultResult); continue; } else { retArr.push(' else {\n'); } } else { // all others if (i === 0 || !pastFirstIf) { pastFirstIf = true; retArr.push(`if (${varName} == `); } else { if (fallingThrough) { retArr.push(`${varName} == `); fallingThrough = false; } else { retArr.push(` else if (${varName} == `); } } if (type === 'Integer') { const testType = this.getType(cases[i].test); switch (testType) { case 'Number': case 'Float': this.castValueToInteger(cases[i].test, retArr); break; case 'LiteralInteger': this.castLiteralToInteger(cases[i].test, retArr); break; } } else if (type === 'Float') { const testType = this.getType(cases[i].test); switch (testType) { case 'LiteralInteger': this.castLiteralToFloat(cases[i].test, retArr); break; case 'Integer': this.castValueToFloat(cases[i].test, retArr); break; } } else { throw new Error('unhanlded'); } if (!cases[i].consequent || cases[i].consequent.length === 0) { fallingThrough = true; retArr.push(' || '); continue; } retArr.push(`) {\n`); } this.astGeneric(cases[i].consequent, retArr); retArr.push('\n}'); } if (movingDefaultToEnd) { retArr.push(' else {'); retArr.push(defaultResult.join('')); retArr.push('}'); } return retArr; } /** * @desc Parses the abstract syntax tree for *This* expression * @param {Object} tNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astThisExpression(tNode, retArr) { retArr.push('this'); return retArr; } /** * @desc Parses the abstract syntax tree for *Member* Expression * @param {Object} mNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astMemberExpression(mNode, retArr) { const { property, name, signature, origin, type, xProperty, yProperty, zProperty } = this.getMemberExpressionDetails(mNode); switch (signature) { case 'value.thread.value': case 'this.thread.value': if (name !== 'x' && name !== 'y' && name !== 'z') { throw this.astErrorOutput('Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`', mNode); } retArr.push(`threadId.${name}`); return retArr; case 'this.output.value': if (this.dynamicOutput) { switch (name) { case 'x': if (this.isState('casting-to-float')) { retArr.push('float(uOutputDim.x)'); } else { retArr.push('uOutputDim.x'); } break; case 'y': if (this.isState('casting-to-float')) { retArr.push('float(uOutputDim.y)'); } else { retArr.push('uOutputDim.y'); } break; case 'z': if (this.isState('casting-to-float')) { retArr.push('float(uOutputDim.z)'); } else { retArr.push('uOutputDim.z'); } break; default: throw this.astErrorOutput('Unexpected expression', mNode); } } else { switch (name) { case 'x': if (this.isState('casting-to-integer')) { retArr.push(this.output[0]); } else { retArr.push(this.output[0], '.0'); } break; case 'y': if (this.isState('casting-to-integer')) { retArr.push(this.output[1]); } else { retArr.push(this.output[1], '.0'); } break; case 'z': if (this.isState('casting-to-integer')) { retArr.push(this.output[2]); } else { retArr.push(this.output[2], '.0'); } break; default: throw this.astErrorOutput('Unexpected expression', mNode); } } return retArr; case 'value': throw this.astErrorOutput('Unexpected expression', mNode); case 'value[]': case 'value[][]': case 'value[][][]': case 'value[][][][]': case 'value.value': if (origin === 'Math') { retArr.push(Math[name]); return retArr; } const cleanName = utils.sanitizeName(name); switch (property) { case 'r': retArr.push(`user_${ cleanName }.r`); return retArr; case 'g': retArr.push(`user_${ cleanName }.g`); return retArr; case 'b': retArr.push(`user_${ cleanName }.b`); return retArr; case 'a': retArr.push(`user_${ cleanName }.a`); return retArr; } break; case 'this.constants.value': if (typeof xProperty === 'undefined') { switch (type) { case 'Array(2)': case 'Array(3)': case 'Array(4)': retArr.push(`constants_${ utils.sanitizeName(name) }`); return retArr; } } case 'this.constants.value[]': case 'this.constants.value[][]': case 'this.constants.value[][][]': case 'this.constants.value[][][][]': break; case 'fn()[]': this.astCallExpression(mNode.object, retArr); retArr.push('['); retArr.push(this.memberExpressionPropertyMarkup(property)); retArr.push(']'); return retArr; case 'fn()[][]': this.astCallExpression(mNode.object.object, retArr); retArr.push('['); retArr.push(this.memberExpressionPropertyMarkup(mNode.object.property)); retArr.push(']'); retArr.push('['); retArr.push(this.memberExpressionPropertyMarkup(mNode.property)); retArr.push(']'); return retArr; case '[][]': this.astArrayExpression(mNode.object, retArr); retArr.push('['); retArr.push(this.memberExpressionPropertyMarkup(property)); retArr.push(']'); return retArr; default: throw this.astErrorOutput('Unexpected expression', mNode); } if (mNode.computed === false) { // handle simple types switch (type) { case 'Number': case 'Integer': case 'Float': case 'Boolean': retArr.push(`${origin}_${utils.sanitizeName(name)}`); return retArr; } } // handle more complex types // argument may have come from a parent const markupName = `${origin}_${utils.sanitizeName(name)}`; switch (type) { case 'Array(2)': case 'Array(3)': case 'Array(4)': // Get from local vec4 this.astGeneric(mNode.object, retArr); retArr.push('['); retArr.push(this.memberExpressionPropertyMarkup(xProperty)); retArr.push(']'); break; case 'HTMLImageArray': retArr.push(`getImage3D(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'ArrayTexture(1)': retArr.push(`getFloatFromSampler2D(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'Array1D(2)': case 'Array2D(2)': case 'Array3D(2)': retArr.push(`getMemoryOptimizedVec2(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'ArrayTexture(2)': retArr.push(`getVec2FromSampler2D(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'Array1D(3)': case 'Array2D(3)': case 'Array3D(3)': retArr.push(`getMemoryOptimizedVec3(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'ArrayTexture(3)': retArr.push(`getVec3FromSampler2D(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'Array1D(4)': case 'Array2D(4)': case 'Array3D(4)': retArr.push(`getMemoryOptimizedVec4(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'ArrayTexture(4)': case 'HTMLCanvas': case 'OffscreenCanvas': case 'HTMLImage': case 'ImageBitmap': case 'ImageData': case 'HTMLVideo': retArr.push(`getVec4FromSampler2D(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'NumberTexture': case 'Array': case 'Array2D': case 'Array3D': case 'Array4D': case 'Input': case 'Number': case 'Float': case 'Integer': if (this.precision === 'single') { // bitRatio is always 4 here, javascript doesn't yet have 8 or 16 bit support // TODO: make 8 or 16 bit work anyway! retArr.push(`getMemoryOptimized32(${markupName}, ${markupName}Size, ${markupName}Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); } else { const bitRatio = (origin === 'user' ? this.lookupFunctionArgumentBitRatio(this.name, name) : this.constantBitRatios[name] ); switch (bitRatio) { case 1: retArr.push(`get8(${markupName}, ${markupName}Size, ${markupName}Dim, `); break; case 2: retArr.push(`get16(${markupName}, ${markupName}Size, ${markupName}Dim, `); break; case 4: case 0: retArr.push(`get32(${markupName}, ${markupName}Size, ${markupName}Dim, `); break; default: throw new Error(`unhandled bit ratio of ${bitRatio}`); } this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); } break; case 'MemoryOptimizedNumberTexture': retArr.push(`getMemoryOptimized32(${ markupName }, ${ markupName }Size, ${ markupName }Dim, `); this.memberExpressionXYZ(xProperty, yProperty, zProperty, retArr); retArr.push(')'); break; case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': retArr.push(`${markupName}[${this.memberExpressionPropertyMarkup(yProperty)}]`); if (yProperty) { retArr.push(`[${this.memberExpressionPropertyMarkup(xProperty)}]`); } break; default: throw new Error(`unhandled member expression "${ type }"`); } return retArr; } /** * @desc Parses the abstract syntax tree for *call* expression * @param {Object} ast - the AST object to parse * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astCallExpression(ast, retArr) { if (!ast.callee) { throw this.astErrorOutput('Unknown CallExpression', ast); } let functionName = null; const isMathFunction = this.isAstMathFunction(ast); // Its a math operator or this.something(), remove the prefix if (isMathFunction || (ast.callee.object && ast.callee.object.type === 'ThisExpression')) { functionName = ast.callee.property.name; } // Issue #212, BABEL! else if (ast.callee.type === 'SequenceExpression' && ast.callee.expressions[0].type === 'Literal' && !isNaN(ast.callee.expressions[0].raw)) { functionName = ast.callee.expressions[1].property.name; } else { functionName = ast.callee.name; } if (!functionName) { throw this.astErrorOutput(`Unhandled function, couldn't find name`, ast); } // if this if grows to more than one, lets use a switch switch (functionName) { case 'pow': functionName = '_pow'; break; case 'round': functionName = '_round'; break; } // Register the function into the called registry if (this.calledFunctions.indexOf(functionName) < 0) { this.calledFunctions.push(functionName); } if (functionName === 'random' && this.plugins && this.plugins.length > 0) { for (let i = 0; i < this.plugins.length; i++) { const plugin = this.plugins[i]; if (plugin.functionMatch === 'Math.random()' && plugin.functionReplace) { retArr.push(plugin.functionReplace); return retArr; } } } // track the function was called if (this.onFunctionCall) { this.onFunctionCall(this.name, functionName, ast.arguments); } // Call the function retArr.push(functionName); // Open arguments space retArr.push('('); // Add the arguments if (isMathFunction) { for (let i = 0; i < ast.arguments.length; ++i) { const argument = ast.arguments[i]; const argumentType = this.getType(argument); if (i > 0) { retArr.push(', '); } switch (argumentType) { case 'Integer': this.castValueToFloat(argument, retArr); break; default: this.astGeneric(argument, retArr); break; } } } else { const targetTypes = this.lookupFunctionArgumentTypes(functionName) || []; for (let i = 0; i < ast.arguments.length; ++i) { const argument = ast.arguments[i]; let targetType = targetTypes[i]; if (i > 0) { retArr.push(', '); } const argumentType = this.getType(argument); if (!targetType) { this.triggerImplyArgumentType(functionName, i, argumentType, this); targetType = argumentType; } switch (argumentType) { case 'Boolean': this.astGeneric(argument, retArr); continue; case 'Number': case 'Float': if (targetType === 'Integer') { retArr.push('int('); this.astGeneric(argument, retArr); retArr.push(')'); continue; } else if (targetType === 'Number' || targetType === 'Float') { this.astGeneric(argument, retArr); continue; } else if (targetType === 'LiteralInteger') { this.castLiteralToFloat(argument, retArr); continue; } break; case 'Integer': if (targetType === 'Number' || targetType === 'Float') { retArr.push('float('); this.astGeneric(argument, retArr); retArr.push(')'); continue; } else if (targetType === 'Integer') { this.astGeneric(argument, retArr); continue; } break; case 'LiteralInteger': if (targetType === 'Integer') { this.castLiteralToInteger(argument, retArr); continue; } else if (targetType === 'Number' || targetType === 'Float') { this.castLiteralToFloat(argument, retArr); continue; } else if (targetType === 'LiteralInteger') { this.astGeneric(argument, retArr); continue; } break; case 'Array(2)': case 'Array(3)': case 'Array(4)': if (targetType === argumentType) { if (argument.type === 'Identifier') { retArr.push(`user_${utils.sanitizeName(argument.name)}`); } else if (argument.type === 'ArrayExpression' || argument.type === 'MemberExpression' || argument.type === 'CallExpression') { this.astGeneric(argument, retArr); } else { throw this.astErrorOutput(`Unhandled argument type ${ argument.type }`, ast); } continue; } break; case 'HTMLCanvas': case 'OffscreenCanvas': case 'HTMLImage': case 'ImageBitmap': case 'ImageData': case 'HTMLImageArray': case 'HTMLVideo': case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': case 'Array': case 'Input': if (targetType === argumentType) { if (argument.type !== 'Identifier') throw this.astErrorOutput(`Unhandled argument type ${ argument.type }`, ast); this.triggerImplyArgumentBitRatio(this.name, argument.name, functionName, i); const name = utils.sanitizeName(argument.name); retArr.push(`user_${name},user_${name}Size,user_${name}Dim`); continue; } break; } throw this.astErrorOutput(`Unhandled argument combination of ${ argumentType } and ${ targetType } for argument named "${ argument.name }"`, ast); } } // Close arguments space retArr.push(')'); return retArr; } /** * @desc Parses the abstract syntax tree for *Array* Expression * @param {Object} arrNode - the AST object to parse * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astArrayExpression(arrNode, retArr) { const returnType = this.getType(arrNode); const arrLen = arrNode.elements.length; switch (returnType) { case 'Matrix(2)': case 'Matrix(3)': case 'Matrix(4)': retArr.push(`mat${arrLen}(`); break; default: retArr.push(`vec${arrLen}(`); } for (let i = 0; i < arrLen; ++i) { if (i > 0) { retArr.push(', '); } const subNode = arrNode.elements[i]; this.astGeneric(subNode, retArr) } retArr.push(')'); return retArr; } memberExpressionXYZ(x, y, z, retArr) { if (z) { retArr.push(this.memberExpressionPropertyMarkup(z), ', '); } else { retArr.push('0, '); } if (y) { retArr.push(this.memberExpressionPropertyMarkup(y), ', '); } else { retArr.push('0, '); } retArr.push(this.memberExpressionPropertyMarkup(x)); return retArr; } memberExpressionPropertyMarkup(property) { if (!property) { throw new Error('Property not set'); } const type = this.getType(property); const result = []; switch (type) { case 'Number': case 'Float': this.castValueToInteger(property, result); break; case 'LiteralInteger': this.castLiteralToInteger(property, result); break; default: this.astGeneric(property, result); } return result.join(''); } } const typeMap = { 'Array': 'sampler2D', 'Array(2)': 'vec2', 'Array(3)': 'vec3', 'Array(4)': 'vec4', 'Matrix(2)': 'mat2', 'Matrix(3)': 'mat3', 'Matrix(4)': 'mat4', 'Array2D': 'sampler2D', 'Array3D': 'sampler2D', 'Boolean': 'bool', 'Float': 'float', 'Input': 'sampler2D', 'Integer': 'int', 'Number': 'float', 'LiteralInteger': 'float', 'NumberTexture': 'sampler2D', 'MemoryOptimizedNumberTexture': 'sampler2D', 'ArrayTexture(1)': 'sampler2D', 'ArrayTexture(2)': 'sampler2D', 'ArrayTexture(3)': 'sampler2D', 'ArrayTexture(4)': 'sampler2D', 'HTMLVideo': 'sampler2D', 'HTMLCanvas': 'sampler2D', 'OffscreenCanvas': 'sampler2D', 'HTMLImage': 'sampler2D', 'ImageBitmap': 'sampler2D', 'ImageData': 'sampler2D', 'HTMLImageArray': 'sampler2DArray', }; const operatorMap = { '===': '==', '!==': '!=' }; module.exports = { WebGLFunctionNode }; ================================================ FILE: src/backend/web-gl/kernel-value/array.js ================================================ const { WebGLKernelValue } = require('./index'); const { Input } = require('../../../input'); /** * @abstract */ class WebGLKernelArray extends WebGLKernelValue { /** * * @param {number} width * @param {number} height */ checkSize(width, height) { if (!this.kernel.validate) return; const { maxTextureSize } = this.kernel.constructor.features; if (width > maxTextureSize || height > maxTextureSize) { if (width > height) { throw new Error(`Argument texture width of ${width} larger than maximum size of ${maxTextureSize} for your GPU`); } else if (width < height) { throw new Error(`Argument texture height of ${height} larger than maximum size of ${maxTextureSize} for your GPU`); } else { throw new Error(`Argument texture height and width of ${height} larger than maximum size of ${maxTextureSize} for your GPU`); } } } setup() { this.requestTexture(); this.setupTexture(); this.defineTexture(); } requestTexture() { this.texture = this.onRequestTexture(); } defineTexture() { const { context: gl } = this; gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); } setupTexture() { this.contextHandle = this.onRequestContextHandle(); this.index = this.onRequestIndex(); this.dimensionsId = this.id + 'Dim'; this.sizeId = this.id + 'Size'; } /** * bit storage ratio of source to target 'buffer', i.e. if 8bit array -> 32bit tex = 4 * @param value * @returns {number} */ getBitRatio(value) { if (Array.isArray(value[0])) { return this.getBitRatio(value[0]); } else if (value.constructor === Input) { return this.getBitRatio(value.value); } switch (value.constructor) { case Uint8ClampedArray: case Uint8Array: case Int8Array: return 1; case Uint16Array: case Int16Array: return 2; case Float32Array: case Int32Array: default: return 4; } } destroy() { if (this.prevArg) { this.prevArg.delete(); } this.context.deleteTexture(this.texture); } } module.exports = { WebGLKernelArray }; ================================================ FILE: src/backend/web-gl/kernel-value/array2.js ================================================ const { WebGLKernelValue } = require('./index'); class WebGLKernelValueArray2 extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getSource(value) { if (this.origin === 'constants') { return `const vec2 ${this.id} = vec2(${value[0]},${value[1]});\n`; } return `uniform vec2 ${this.id};\n`; } getStringValueHandler() { // resetting isn't supported for Array(2) if (this.origin === 'constants') return ''; return `const uploadValue_${this.name} = ${this.varName};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform2fv(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueArray2 }; ================================================ FILE: src/backend/web-gl/kernel-value/array3.js ================================================ const { WebGLKernelValue } = require('./index'); class WebGLKernelValueArray3 extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getSource(value) { if (this.origin === 'constants') { return `const vec3 ${this.id} = vec3(${value[0]},${value[1]},${value[2]});\n`; } return `uniform vec3 ${this.id};\n`; } getStringValueHandler() { // resetting isn't supported for Array(3) if (this.origin === 'constants') return ''; return `const uploadValue_${this.name} = ${this.varName};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform3fv(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueArray3 }; ================================================ FILE: src/backend/web-gl/kernel-value/array4.js ================================================ const { WebGLKernelValue } = require('./index'); class WebGLKernelValueArray4 extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getSource(value) { if (this.origin === 'constants') { return `const vec4 ${this.id} = vec4(${value[0]},${value[1]},${value[2]},${value[3]});\n`; } return `uniform vec4 ${this.id};\n`; } getStringValueHandler() { // resetting isn't supported for Array(4) if (this.origin === 'constants') return ''; return `const uploadValue_${this.name} = ${this.varName};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform4fv(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueArray4 }; ================================================ FILE: src/backend/web-gl/kernel-value/boolean.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValue } = require('./index'); class WebGLKernelValueBoolean extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getSource(value) { if (this.origin === 'constants') { return `const bool ${this.id} = ${value};\n`; } return `uniform bool ${this.id};\n`; } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform1i(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueBoolean }; ================================================ FILE: src/backend/web-gl/kernel-value/dynamic-html-image.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueHTMLImage } = require('./html-image'); class WebGLKernelValueDynamicHTMLImage extends WebGLKernelValueHTMLImage { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { const { width, height } = value; this.checkSize(width, height); this.dimensions = [width, height, 1]; this.textureSize = [width, height]; this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicHTMLImage }; ================================================ FILE: src/backend/web-gl/kernel-value/dynamic-html-video.js ================================================ const { WebGLKernelValueDynamicHTMLImage } = require('./dynamic-html-image'); class WebGLKernelValueDynamicHTMLVideo extends WebGLKernelValueDynamicHTMLImage {} module.exports = { WebGLKernelValueDynamicHTMLVideo }; ================================================ FILE: src/backend/web-gl/kernel-value/dynamic-memory-optimized-number-texture.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueMemoryOptimizedNumberTexture } = require('./memory-optimized-number-texture'); class WebGLKernelValueDynamicMemoryOptimizedNumberTexture extends WebGLKernelValueMemoryOptimizedNumberTexture { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(inputTexture) { this.dimensions = inputTexture.dimensions; this.checkSize(inputTexture.size[0], inputTexture.size[1]); this.textureSize = inputTexture.size; this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(inputTexture); } } module.exports = { WebGLKernelValueDynamicMemoryOptimizedNumberTexture }; ================================================ FILE: src/backend/web-gl/kernel-value/dynamic-number-texture.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueNumberTexture } = require('./number-texture'); class WebGLKernelValueDynamicNumberTexture extends WebGLKernelValueNumberTexture { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.dimensions = value.dimensions; this.checkSize(value.size[0], value.size[1]); this.textureSize = value.size; this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicNumberTexture }; ================================================ FILE: src/backend/web-gl/kernel-value/dynamic-single-array.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray } = require('./single-array'); class WebGLKernelValueDynamicSingleArray extends WebGLKernelValueSingleArray { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.dimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicSingleArray }; ================================================ FILE: src/backend/web-gl/kernel-value/dynamic-single-array1d-i.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray1DI } = require('./single-array1d-i'); class WebGLKernelValueDynamicSingleArray1DI extends WebGLKernelValueSingleArray1DI { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicSingleArray1DI }; ================================================ FILE: src/backend/web-gl/kernel-value/dynamic-single-array2d-i.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray2DI } = require('./single-array2d-i'); class WebGLKernelValueDynamicSingleArray2DI extends WebGLKernelValueSingleArray2DI { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicSingleArray2DI }; ================================================ FILE: src/backend/web-gl/kernel-value/dynamic-single-array3d-i.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray3DI } = require('./single-array3d-i'); class WebGLKernelValueDynamicSingleArray3DI extends WebGLKernelValueSingleArray3DI { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicSingleArray3DI }; ================================================ FILE: src/backend/web-gl/kernel-value/dynamic-single-input.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleInput } = require('./single-input'); class WebGLKernelValueDynamicSingleInput extends WebGLKernelValueSingleInput { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { let [w, h, d] = value.size; this.dimensions = new Int32Array([w || 1, h || 1, d || 1]); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicSingleInput }; ================================================ FILE: src/backend/web-gl/kernel-value/dynamic-unsigned-array.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueUnsignedArray } = require('./unsigned-array'); class WebGLKernelValueDynamicUnsignedArray extends WebGLKernelValueUnsignedArray { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.dimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedPackedTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * (4 / this.bitRatio); this.checkSize(this.textureSize[0], this.textureSize[1]); const Type = this.getTransferArrayType(value); this.preUploadValue = new Type(this.uploadArrayLength); this.uploadValue = new Uint8Array(this.preUploadValue.buffer); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicUnsignedArray }; ================================================ FILE: src/backend/web-gl/kernel-value/dynamic-unsigned-input.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueUnsignedInput } = require('./unsigned-input'); class WebGLKernelValueDynamicUnsignedInput extends WebGLKernelValueUnsignedInput { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { let [w, h, d] = value.size; this.dimensions = new Int32Array([w || 1, h || 1, d || 1]); this.textureSize = utils.getMemoryOptimizedPackedTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * (4 / this.bitRatio); this.checkSize(this.textureSize[0], this.textureSize[1]); const Type = this.getTransferArrayType(value.value); this.preUploadValue = new Type(this.uploadArrayLength); this.uploadValue = new Uint8Array(this.preUploadValue.buffer); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGLKernelValueDynamicUnsignedInput }; ================================================ FILE: src/backend/web-gl/kernel-value/float.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValue } = require('./index'); class WebGLKernelValueFloat extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName};\n`; } getSource(value) { if (this.origin === 'constants') { if (Number.isInteger(value)) { return `const float ${this.id} = ${value}.0;\n`; } return `const float ${this.id} = ${value};\n`; } return `uniform float ${this.id};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform1f(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueFloat }; ================================================ FILE: src/backend/web-gl/kernel-value/html-image.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueHTMLImage extends WebGLKernelArray { constructor(value, settings) { super(value, settings); const { width, height } = value; this.checkSize(width, height); this.dimensions = [width, height, 1]; this.textureSize = [width, height]; this.uploadValue = value; } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName};\n`; } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(inputImage) { if (inputImage.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(inputImage.constructor); return; } const { context: gl } = this; gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.uploadValue = inputImage); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueHTMLImage }; ================================================ FILE: src/backend/web-gl/kernel-value/html-video.js ================================================ const { WebGLKernelValueHTMLImage } = require('./html-image'); class WebGLKernelValueHTMLVideo extends WebGLKernelValueHTMLImage {} module.exports = { WebGLKernelValueHTMLVideo }; ================================================ FILE: src/backend/web-gl/kernel-value/index.js ================================================ const { utils } = require('../../../utils'); const { KernelValue } = require('../../kernel-value'); class WebGLKernelValue extends KernelValue { /** * @param {KernelVariable} value * @param {IWebGLKernelValueSettings} settings */ constructor(value, settings) { super(value, settings); this.dimensionsId = null; this.sizeId = null; this.initialValueConstructor = value.constructor; this.onRequestTexture = settings.onRequestTexture; this.onRequestIndex = settings.onRequestIndex; this.uploadValue = null; this.textureSize = null; this.bitRatio = null; this.prevArg = null; } get id() { return `${this.origin}_${utils.sanitizeName(this.name)}`; } setup() {} getTransferArrayType(value) { if (Array.isArray(value[0])) { return this.getTransferArrayType(value[0]); } switch (value.constructor) { case Array: case Int32Array: case Int16Array: case Int8Array: return Float32Array; case Uint8ClampedArray: case Uint8Array: case Uint16Array: case Uint32Array: case Float32Array: case Float64Array: return value.constructor; } console.warn('Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros'); return value.constructor; } /** * Used for when we want a string output of our kernel, so we can still input values to the kernel */ getStringValueHandler() { throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`); } getVariablePrecisionString() { return this.kernel.getVariablePrecisionString(this.textureSize || undefined, this.tactic || undefined); } destroy() {} } module.exports = { WebGLKernelValue }; ================================================ FILE: src/backend/web-gl/kernel-value/integer.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValue } = require('./index'); class WebGLKernelValueInteger extends WebGLKernelValue { constructor(value, settings) { super(value, settings); this.uploadValue = value; } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName};\n`; } getSource(value) { if (this.origin === 'constants') { return `const int ${this.id} = ${ parseInt(value) };\n`; } return `uniform int ${this.id};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform1i(this.id, this.uploadValue = value); } } module.exports = { WebGLKernelValueInteger }; ================================================ FILE: src/backend/web-gl/kernel-value/memory-optimized-number-texture.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); const sameError = `Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()`; class WebGLKernelValueMemoryOptimizedNumberTexture extends WebGLKernelArray { constructor(value, settings) { super(value, settings); const [width, height] = value.size; this.checkSize(width, height); this.dimensions = value.dimensions; this.textureSize = value.size; this.uploadValue = value.texture; this.forceUploadEachRun = true; } setup() { this.setupTexture(); } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName}.texture;\n`; } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } /** * @param {GLTextureMemoryOptimized} inputTexture */ updateValue(inputTexture) { if (inputTexture.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(inputTexture.constructor); return; } if (this.checkContext && inputTexture.context !== this.context) { throw new Error(`Value ${this.name} (${this.type}) must be from same context`); } const { kernel, context: gl } = this; if (kernel.pipeline) { if (kernel.immutable) { kernel.updateTextureArgumentRefs(this, inputTexture); } else { if (kernel.texture && kernel.texture.texture === inputTexture.texture) { throw new Error(sameError); } else if (kernel.mappedTextures) { const { mappedTextures } = kernel; for (let i = 0; i < mappedTextures.length; i++) { if (mappedTextures[i].texture === inputTexture.texture) { throw new Error(sameError); } } } } } gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.uploadValue = inputTexture.texture); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueMemoryOptimizedNumberTexture, sameError }; ================================================ FILE: src/backend/web-gl/kernel-value/number-texture.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); const { sameError } = require('./memory-optimized-number-texture'); class WebGLKernelValueNumberTexture extends WebGLKernelArray { constructor(value, settings) { super(value, settings); const [width, height] = value.size; this.checkSize(width, height); const { size: textureSize, dimensions } = value; this.bitRatio = this.getBitRatio(value); this.dimensions = dimensions; this.textureSize = textureSize; this.uploadValue = value.texture; this.forceUploadEachRun = true; } setup() { this.setupTexture(); } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName}.texture;\n`; } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } /** * * @param {GLTexture} inputTexture */ updateValue(inputTexture) { if (inputTexture.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(inputTexture.constructor); return; } if (this.checkContext && inputTexture.context !== this.context) { throw new Error(`Value ${this.name} (${this.type}) must be from same context`); } const { kernel, context: gl } = this; if (kernel.pipeline) { if (kernel.immutable) { kernel.updateTextureArgumentRefs(this, inputTexture); } else { if (kernel.texture && kernel.texture.texture === inputTexture.texture) { throw new Error(sameError); } else if (kernel.mappedTextures) { const { mappedTextures } = kernel; for (let i = 0; i < mappedTextures.length; i++) { if (mappedTextures[i].texture === inputTexture.texture) { throw new Error(sameError); } } } } } gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.uploadValue = inputTexture.texture); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueNumberTexture }; ================================================ FILE: src/backend/web-gl/kernel-value/single-array.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueSingleArray extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = 4; this.dimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); } getStringValueHandler() { return utils.linesToString([ `const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`, `flattenTo(${this.varName}, uploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueSingleArray }; ================================================ FILE: src/backend/web-gl/kernel-value/single-array1d-i.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueSingleArray1DI extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = 4; this.setShape(value); } setShape(value) { const valueDimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(valueDimensions, this.bitRatio); this.dimensions = new Int32Array([valueDimensions[1], 1, 1]); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); } getStringValueHandler() { return utils.linesToString([ `const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`, `flattenTo(${this.varName}, uploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flatten2dArrayTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueSingleArray1DI }; ================================================ FILE: src/backend/web-gl/kernel-value/single-array2d-i.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueSingleArray2DI extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = 4; this.setShape(value); } setShape(value) { const valueDimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(valueDimensions, this.bitRatio); this.dimensions = new Int32Array([valueDimensions[1], valueDimensions[2], 1]); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); } getStringValueHandler() { return utils.linesToString([ `const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`, `flattenTo(${this.varName}, uploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flatten3dArrayTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueSingleArray2DI }; ================================================ FILE: src/backend/web-gl/kernel-value/single-array3d-i.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueSingleArray3DI extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = 4; this.setShape(value); } setShape(value) { const valueDimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(valueDimensions, this.bitRatio); this.dimensions = new Int32Array([valueDimensions[1], valueDimensions[2], valueDimensions[3]]); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); } getStringValueHandler() { return utils.linesToString([ `const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`, `flattenTo(${this.varName}, uploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flatten4dArrayTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueSingleArray3DI }; ================================================ FILE: src/backend/web-gl/kernel-value/single-input.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueSingleInput extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = 4; let [w, h, d] = value.size; this.dimensions = new Int32Array([w || 1, h || 1, d || 1]); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); } getStringValueHandler() { return utils.linesToString([ `const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`, `flattenTo(${this.varName}.value, uploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(input) { if (input.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(input.constructor); return; } const { context: gl } = this; utils.flattenTo(input.value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueSingleInput }; ================================================ FILE: src/backend/web-gl/kernel-value/unsigned-array.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueUnsignedArray extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = this.getBitRatio(value); this.dimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedPackedTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * (4 / this.bitRatio); this.checkSize(this.textureSize[0], this.textureSize[1]); this.TranserArrayType = this.getTransferArrayType(value); this.preUploadValue = new this.TranserArrayType(this.uploadArrayLength); this.uploadValue = new Uint8Array(this.preUploadValue.buffer); } getStringValueHandler() { return utils.linesToString([ `const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`, `const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`, `flattenTo(${this.varName}, preUploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.preUploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueUnsignedArray }; ================================================ FILE: src/backend/web-gl/kernel-value/unsigned-input.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('./array'); class WebGLKernelValueUnsignedInput extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.bitRatio = this.getBitRatio(value); const [w, h, d] = value.size; this.dimensions = new Int32Array([w || 1, h || 1, d || 1]); this.textureSize = utils.getMemoryOptimizedPackedTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * (4 / this.bitRatio); this.checkSize(this.textureSize[0], this.textureSize[1]); this.TranserArrayType = this.getTransferArrayType(value.value); this.preUploadValue = new this.TranserArrayType(this.uploadArrayLength); this.uploadValue = new Uint8Array(this.preUploadValue.buffer); } getStringValueHandler() { return utils.linesToString([ `const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`, `const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`, `flattenTo(${this.varName}.value, preUploadValue_${this.name})`, ]); } getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(input) { if (input.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(input.value, this.preUploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGLKernelValueUnsignedInput }; ================================================ FILE: src/backend/web-gl/kernel-value-maps.js ================================================ const { WebGLKernelValueBoolean } = require('./kernel-value/boolean'); const { WebGLKernelValueFloat } = require('./kernel-value/float'); const { WebGLKernelValueInteger } = require('./kernel-value/integer'); const { WebGLKernelValueHTMLImage } = require('./kernel-value/html-image'); const { WebGLKernelValueDynamicHTMLImage } = require('./kernel-value/dynamic-html-image'); const { WebGLKernelValueHTMLVideo } = require('./kernel-value/html-video'); const { WebGLKernelValueDynamicHTMLVideo } = require('./kernel-value/dynamic-html-video'); const { WebGLKernelValueSingleInput } = require('./kernel-value/single-input'); const { WebGLKernelValueDynamicSingleInput } = require('./kernel-value/dynamic-single-input'); const { WebGLKernelValueUnsignedInput } = require('./kernel-value/unsigned-input'); const { WebGLKernelValueDynamicUnsignedInput } = require('./kernel-value/dynamic-unsigned-input'); const { WebGLKernelValueMemoryOptimizedNumberTexture } = require('./kernel-value/memory-optimized-number-texture'); const { WebGLKernelValueDynamicMemoryOptimizedNumberTexture } = require('./kernel-value/dynamic-memory-optimized-number-texture'); const { WebGLKernelValueNumberTexture } = require('./kernel-value/number-texture'); const { WebGLKernelValueDynamicNumberTexture } = require('./kernel-value/dynamic-number-texture'); const { WebGLKernelValueSingleArray } = require('./kernel-value/single-array'); const { WebGLKernelValueDynamicSingleArray } = require('./kernel-value/dynamic-single-array'); const { WebGLKernelValueSingleArray1DI } = require('./kernel-value/single-array1d-i'); const { WebGLKernelValueDynamicSingleArray1DI } = require('./kernel-value/dynamic-single-array1d-i'); const { WebGLKernelValueSingleArray2DI } = require('./kernel-value/single-array2d-i'); const { WebGLKernelValueDynamicSingleArray2DI } = require('./kernel-value/dynamic-single-array2d-i'); const { WebGLKernelValueSingleArray3DI } = require('./kernel-value/single-array3d-i'); const { WebGLKernelValueDynamicSingleArray3DI } = require('./kernel-value/dynamic-single-array3d-i'); const { WebGLKernelValueArray2 } = require('./kernel-value/array2'); const { WebGLKernelValueArray3 } = require('./kernel-value/array3'); const { WebGLKernelValueArray4 } = require('./kernel-value/array4'); const { WebGLKernelValueUnsignedArray } = require('./kernel-value/unsigned-array'); const { WebGLKernelValueDynamicUnsignedArray } = require('./kernel-value/dynamic-unsigned-array'); const kernelValueMaps = { unsigned: { dynamic: { 'Boolean': WebGLKernelValueBoolean, 'Integer': WebGLKernelValueInteger, 'Float': WebGLKernelValueFloat, 'Array': WebGLKernelValueDynamicUnsignedArray, 'Array(2)': WebGLKernelValueArray2, 'Array(3)': WebGLKernelValueArray3, 'Array(4)': WebGLKernelValueArray4, 'Array1D(2)': false, 'Array1D(3)': false, 'Array1D(4)': false, 'Array2D(2)': false, 'Array2D(3)': false, 'Array2D(4)': false, 'Array3D(2)': false, 'Array3D(3)': false, 'Array3D(4)': false, 'Input': WebGLKernelValueDynamicUnsignedInput, 'NumberTexture': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(1)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(2)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(3)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(4)': WebGLKernelValueDynamicNumberTexture, 'MemoryOptimizedNumberTexture': WebGLKernelValueDynamicMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGLKernelValueDynamicHTMLImage, 'OffscreenCanvas': WebGLKernelValueDynamicHTMLImage, 'HTMLImage': WebGLKernelValueDynamicHTMLImage, 'ImageBitmap': WebGLKernelValueDynamicHTMLImage, 'ImageData': WebGLKernelValueDynamicHTMLImage, 'HTMLImageArray': false, 'HTMLVideo': WebGLKernelValueDynamicHTMLVideo, }, static: { 'Boolean': WebGLKernelValueBoolean, 'Float': WebGLKernelValueFloat, 'Integer': WebGLKernelValueInteger, 'Array': WebGLKernelValueUnsignedArray, 'Array(2)': WebGLKernelValueArray2, 'Array(3)': WebGLKernelValueArray3, 'Array(4)': WebGLKernelValueArray4, 'Array1D(2)': false, 'Array1D(3)': false, 'Array1D(4)': false, 'Array2D(2)': false, 'Array2D(3)': false, 'Array2D(4)': false, 'Array3D(2)': false, 'Array3D(3)': false, 'Array3D(4)': false, 'Input': WebGLKernelValueUnsignedInput, 'NumberTexture': WebGLKernelValueNumberTexture, 'ArrayTexture(1)': WebGLKernelValueNumberTexture, 'ArrayTexture(2)': WebGLKernelValueNumberTexture, 'ArrayTexture(3)': WebGLKernelValueNumberTexture, 'ArrayTexture(4)': WebGLKernelValueNumberTexture, 'MemoryOptimizedNumberTexture': WebGLKernelValueMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGLKernelValueHTMLImage, 'OffscreenCanvas': WebGLKernelValueHTMLImage, 'HTMLImage': WebGLKernelValueHTMLImage, 'ImageBitmap': WebGLKernelValueHTMLImage, 'ImageData': WebGLKernelValueHTMLImage, 'HTMLImageArray': false, 'HTMLVideo': WebGLKernelValueHTMLVideo, } }, single: { dynamic: { 'Boolean': WebGLKernelValueBoolean, 'Integer': WebGLKernelValueInteger, 'Float': WebGLKernelValueFloat, 'Array': WebGLKernelValueDynamicSingleArray, 'Array(2)': WebGLKernelValueArray2, 'Array(3)': WebGLKernelValueArray3, 'Array(4)': WebGLKernelValueArray4, 'Array1D(2)': WebGLKernelValueDynamicSingleArray1DI, 'Array1D(3)': WebGLKernelValueDynamicSingleArray1DI, 'Array1D(4)': WebGLKernelValueDynamicSingleArray1DI, 'Array2D(2)': WebGLKernelValueDynamicSingleArray2DI, 'Array2D(3)': WebGLKernelValueDynamicSingleArray2DI, 'Array2D(4)': WebGLKernelValueDynamicSingleArray2DI, 'Array3D(2)': WebGLKernelValueDynamicSingleArray3DI, 'Array3D(3)': WebGLKernelValueDynamicSingleArray3DI, 'Array3D(4)': WebGLKernelValueDynamicSingleArray3DI, 'Input': WebGLKernelValueDynamicSingleInput, 'NumberTexture': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(1)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(2)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(3)': WebGLKernelValueDynamicNumberTexture, 'ArrayTexture(4)': WebGLKernelValueDynamicNumberTexture, 'MemoryOptimizedNumberTexture': WebGLKernelValueDynamicMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGLKernelValueDynamicHTMLImage, 'OffscreenCanvas': WebGLKernelValueDynamicHTMLImage, 'HTMLImage': WebGLKernelValueDynamicHTMLImage, 'ImageBitmap': WebGLKernelValueDynamicHTMLImage, 'ImageData': WebGLKernelValueDynamicHTMLImage, 'HTMLImageArray': false, 'HTMLVideo': WebGLKernelValueDynamicHTMLVideo, }, static: { 'Boolean': WebGLKernelValueBoolean, 'Float': WebGLKernelValueFloat, 'Integer': WebGLKernelValueInteger, 'Array': WebGLKernelValueSingleArray, 'Array(2)': WebGLKernelValueArray2, 'Array(3)': WebGLKernelValueArray3, 'Array(4)': WebGLKernelValueArray4, 'Array1D(2)': WebGLKernelValueSingleArray1DI, 'Array1D(3)': WebGLKernelValueSingleArray1DI, 'Array1D(4)': WebGLKernelValueSingleArray1DI, 'Array2D(2)': WebGLKernelValueSingleArray2DI, 'Array2D(3)': WebGLKernelValueSingleArray2DI, 'Array2D(4)': WebGLKernelValueSingleArray2DI, 'Array3D(2)': WebGLKernelValueSingleArray3DI, 'Array3D(3)': WebGLKernelValueSingleArray3DI, 'Array3D(4)': WebGLKernelValueSingleArray3DI, 'Input': WebGLKernelValueSingleInput, 'NumberTexture': WebGLKernelValueNumberTexture, 'ArrayTexture(1)': WebGLKernelValueNumberTexture, 'ArrayTexture(2)': WebGLKernelValueNumberTexture, 'ArrayTexture(3)': WebGLKernelValueNumberTexture, 'ArrayTexture(4)': WebGLKernelValueNumberTexture, 'MemoryOptimizedNumberTexture': WebGLKernelValueMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGLKernelValueHTMLImage, 'OffscreenCanvas': WebGLKernelValueHTMLImage, 'HTMLImage': WebGLKernelValueHTMLImage, 'ImageBitmap': WebGLKernelValueHTMLImage, 'ImageData': WebGLKernelValueHTMLImage, 'HTMLImageArray': false, 'HTMLVideo': WebGLKernelValueHTMLVideo, } }, }; function lookupKernelValueType(type, dynamic, precision, value) { if (!type) { throw new Error('type missing'); } if (!dynamic) { throw new Error('dynamic missing'); } if (!precision) { throw new Error('precision missing'); } if (value.type) { type = value.type; } const types = kernelValueMaps[precision][dynamic]; if (types[type] === false) { return null; } else if (types[type] === undefined) { throw new Error(`Could not find a KernelValue for ${ type }`); } return types[type]; } module.exports = { lookupKernelValueType, kernelValueMaps, }; ================================================ FILE: src/backend/web-gl/kernel.js ================================================ const { GLKernel } = require('../gl/kernel'); const { FunctionBuilder } = require('../function-builder'); const { WebGLFunctionNode } = require('./function-node'); const { utils } = require('../../utils'); const mrud = require('../../plugins/math-random-uniformly-distributed'); const { fragmentShader } = require('./fragment-shader'); const { vertexShader } = require('./vertex-shader'); const { glKernelString } = require('../gl/kernel-string'); const { lookupKernelValueType } = require('./kernel-value-maps'); let isSupported = null; /** * * @type {HTMLCanvasElement|OffscreenCanvas|null} */ let testCanvas = null; /** * * @type {WebGLRenderingContext|null} */ let testContext = null; let testExtensions = null; let features = null; const plugins = [mrud]; const canvases = []; const maxTexSizes = {}; /** * @desc Kernel Implementation for WebGL. *

This builds the shaders and runs them on the GPU, * the outputs the result back as float(enabled by default) and Texture.

* * @property {WebGLTexture[]} textureCache - webGl Texture cache * @property {Object.} programUniformLocationCache - Location of program variables in memory * @property {WebGLFramebuffer} framebuffer - Webgl frameBuffer * @property {WebGLBuffer} buffer - WebGL buffer * @property {WebGLProgram} program - The webGl Program * @property {FunctionBuilder} functionBuilder - Function Builder instance bound to this Kernel * @property {Boolean} pipeline - Set output type to FAST mode (GPU to GPU via Textures), instead of float * @property {string} endianness - Endian information like Little-endian, Big-endian. * @property {string[]} argumentTypes - Types of parameters sent to the Kernel * @property {string|null} compiledFragmentShader - Compiled fragment shader string * @property {string|null} compiledVertexShader - Compiled Vertical shader string * @extends GLKernel */ class WebGLKernel extends GLKernel { static get isSupported() { if (isSupported !== null) { return isSupported; } this.setupFeatureChecks(); isSupported = this.isContextMatch(testContext); return isSupported; } static setupFeatureChecks() { if (typeof document !== 'undefined') { testCanvas = document.createElement('canvas'); } else if (typeof OffscreenCanvas !== 'undefined') { testCanvas = new OffscreenCanvas(0, 0); } if (!testCanvas) return; testContext = testCanvas.getContext('webgl') || testCanvas.getContext('experimental-webgl'); if (!testContext || !testContext.getExtension) return; testExtensions = { OES_texture_float: testContext.getExtension('OES_texture_float'), OES_texture_float_linear: testContext.getExtension('OES_texture_float_linear'), OES_element_index_uint: testContext.getExtension('OES_element_index_uint'), WEBGL_draw_buffers: testContext.getExtension('WEBGL_draw_buffers'), }; features = this.getFeatures(); } static isContextMatch(context) { if (typeof WebGLRenderingContext !== 'undefined') { return context instanceof WebGLRenderingContext; } return false; } static getIsTextureFloat() { return Boolean(testExtensions.OES_texture_float); } static getIsDrawBuffers() { return Boolean(testExtensions.WEBGL_draw_buffers); } static getChannelCount() { return testExtensions.WEBGL_draw_buffers ? testContext.getParameter(testExtensions.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL) : 1; } static getMaxTextureSize() { return testContext.getParameter(testContext.MAX_TEXTURE_SIZE); } /** * * @param type * @param dynamic * @param precision * @param value * @returns {KernelValue} */ static lookupKernelValueType(type, dynamic, precision, value) { return lookupKernelValueType(type, dynamic, precision, value); } static get testCanvas() { return testCanvas; } static get testContext() { return testContext; } static get features() { return features; } static get fragmentShader() { return fragmentShader; } static get vertexShader() { return vertexShader; } /** * * @param {String|IKernelJSON} source * @param {IDirectKernelSettings} settings */ constructor(source, settings) { super(source, settings); this.program = null; this.pipeline = settings.pipeline; this.endianness = utils.systemEndianness(); this.extensions = {}; this.argumentTextureCount = 0; this.constantTextureCount = 0; this.fragShader = null; this.vertShader = null; this.drawBuffersMap = null; /** * * @type {Int32Array|null} */ this.maxTexSize = null; this.onRequestSwitchKernel = null; this.texture = null; this.mappedTextures = null; this.mergeSettings(source.settings || settings); /** * The thread dimensions, x, y and z * @type {Array|null} */ this.threadDim = null; this.framebuffer = null; this.buffer = null; this.textureCache = []; this.programUniformLocationCache = {}; this.uniform1fCache = {}; this.uniform1iCache = {}; this.uniform2fCache = {}; this.uniform2fvCache = {}; this.uniform2ivCache = {}; this.uniform3fvCache = {}; this.uniform3ivCache = {}; this.uniform4fvCache = {}; this.uniform4ivCache = {}; } initCanvas() { if (typeof document !== 'undefined') { const canvas = document.createElement('canvas'); // Default width and height, to fix webgl issue in safari canvas.width = 2; canvas.height = 2; return canvas; } else if (typeof OffscreenCanvas !== 'undefined') { return new OffscreenCanvas(0, 0); } } /** * * @return {WebGLRenderingContext} */ initContext() { const settings = { alpha: false, depth: false, antialias: false }; return this.canvas.getContext('webgl', settings) || this.canvas.getContext('experimental-webgl', settings); } /** * * @param {IDirectKernelSettings} settings * @return {string[]} */ initPlugins(settings) { // default plugins const pluginsToUse = []; const { source } = this; if (typeof source === 'string') { for (let i = 0; i < plugins.length; i++) { const plugin = plugins[i]; if (source.match(plugin.functionMatch)) { pluginsToUse.push(plugin); } } } else if (typeof source === 'object') { // `source` is from object, json if (settings.pluginNames) { //TODO: in context of JSON support, pluginNames may not exist here for (let i = 0; i < plugins.length; i++) { const plugin = plugins[i]; const usePlugin = settings.pluginNames.some(pluginName => pluginName === plugin.name); if (usePlugin) { pluginsToUse.push(plugin); } } } } return pluginsToUse; } initExtensions() { this.extensions = { OES_texture_float: this.context.getExtension('OES_texture_float'), OES_texture_float_linear: this.context.getExtension('OES_texture_float_linear'), OES_element_index_uint: this.context.getExtension('OES_element_index_uint'), WEBGL_draw_buffers: this.context.getExtension('WEBGL_draw_buffers'), WEBGL_color_buffer_float: this.context.getExtension('WEBGL_color_buffer_float'), }; } /** * @desc Validate settings related to Kernel, such as dimensions size, and auto output support. * @param {IArguments} args */ validateSettings(args) { if (!this.validate) { this.texSize = utils.getKernelTextureSize({ optimizeFloatMemory: this.optimizeFloatMemory, precision: this.precision, }, this.output); return; } const { features } = this.constructor; if (this.optimizeFloatMemory === true && !features.isTextureFloat) { throw new Error('Float textures are not supported'); } else if (this.precision === 'single' && !features.isFloatRead) { throw new Error('Single precision not supported'); } else if (!this.graphical && this.precision === null && features.isTextureFloat) { this.precision = features.isFloatRead ? 'single' : 'unsigned'; } if (this.subKernels && this.subKernels.length > 0 && !this.extensions.WEBGL_draw_buffers) { throw new Error('could not instantiate draw buffers extension'); } if (this.fixIntegerDivisionAccuracy === null) { this.fixIntegerDivisionAccuracy = !features.isIntegerDivisionAccurate; } else if (this.fixIntegerDivisionAccuracy && features.isIntegerDivisionAccurate) { this.fixIntegerDivisionAccuracy = false; } this.checkOutput(); if (!this.output || this.output.length === 0) { if (args.length !== 1) { throw new Error('Auto output only supported for kernels with only one input'); } const argType = utils.getVariableType(args[0], this.strictIntegers); switch (argType) { case 'Array': this.output = utils.getDimensions(argType); break; case 'NumberTexture': case 'MemoryOptimizedNumberTexture': case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': this.output = args[0].output; break; default: throw new Error('Auto output not supported for input type: ' + argType); } } if (this.graphical) { if (this.output.length !== 2) { throw new Error('Output must have 2 dimensions on graphical mode'); } if (this.precision === 'precision') { this.precision = 'unsigned'; console.warn('Cannot use graphical mode and single precision at the same time'); } this.texSize = utils.clone(this.output); return; } else if (this.precision === null && features.isTextureFloat) { this.precision = 'single'; } this.texSize = utils.getKernelTextureSize({ optimizeFloatMemory: this.optimizeFloatMemory, precision: this.precision, }, this.output); this.checkTextureSize(); } updateMaxTexSize() { const { texSize, canvas } = this; if (this.maxTexSize === null) { let canvasIndex = canvases.indexOf(canvas); if (canvasIndex === -1) { canvasIndex = canvases.length; canvases.push(canvas); maxTexSizes[canvasIndex] = [texSize[0], texSize[1]]; } this.maxTexSize = maxTexSizes[canvasIndex]; } if (this.maxTexSize[0] < texSize[0]) { this.maxTexSize[0] = texSize[0]; } if (this.maxTexSize[1] < texSize[1]) { this.maxTexSize[1] = texSize[1]; } } setupArguments(args) { this.kernelArguments = []; this.argumentTextureCount = 0; const needsArgumentTypes = this.argumentTypes === null; // TODO: remove if (needsArgumentTypes) { this.argumentTypes = []; } this.argumentSizes = []; this.argumentBitRatios = []; // TODO: end remove if (args.length < this.argumentNames.length) { throw new Error('not enough arguments for kernel'); } else if (args.length > this.argumentNames.length) { throw new Error('too many arguments for kernel'); } const { context: gl } = this; let textureIndexes = 0; const onRequestTexture = () => { return this.createTexture(); }; const onRequestIndex = () => { return this.constantTextureCount + textureIndexes++; }; const onUpdateValueMismatch = (constructor) => { this.switchKernels({ type: 'argumentMismatch', needed: constructor }); }; const onRequestContextHandle = () => { return gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount++; }; for (let index = 0; index < args.length; index++) { const value = args[index]; const name = this.argumentNames[index]; let type; if (needsArgumentTypes) { type = utils.getVariableType(value, this.strictIntegers); this.argumentTypes.push(type); } else { type = this.argumentTypes[index]; } const KernelValue = this.constructor.lookupKernelValueType(type, this.dynamicArguments ? 'dynamic' : 'static', this.precision, args[index]); if (KernelValue === null) { return this.requestFallback(args); } const kernelArgument = new KernelValue(value, { name, type, tactic: this.tactic, origin: 'user', context: gl, checkContext: this.checkContext, kernel: this, strictIntegers: this.strictIntegers, onRequestTexture, onRequestIndex, onUpdateValueMismatch, onRequestContextHandle, }); this.kernelArguments.push(kernelArgument); kernelArgument.setup(); this.argumentSizes.push(kernelArgument.textureSize); this.argumentBitRatios[index] = kernelArgument.bitRatio; } } createTexture() { const texture = this.context.createTexture(); this.textureCache.push(texture); return texture; } setupConstants(args) { const { context: gl } = this; this.kernelConstants = []; this.forceUploadKernelConstants = []; let needsConstantTypes = this.constantTypes === null; if (needsConstantTypes) { this.constantTypes = {}; } this.constantBitRatios = {}; let textureIndexes = 0; for (const name in this.constants) { const value = this.constants[name]; let type; if (needsConstantTypes) { type = utils.getVariableType(value, this.strictIntegers); this.constantTypes[name] = type; } else { type = this.constantTypes[name]; } const KernelValue = this.constructor.lookupKernelValueType(type, 'static', this.precision, value); if (KernelValue === null) { return this.requestFallback(args); } const kernelValue = new KernelValue(value, { name, type, tactic: this.tactic, origin: 'constants', context: this.context, checkContext: this.checkContext, kernel: this, strictIntegers: this.strictIntegers, onRequestTexture: () => { return this.createTexture(); }, onRequestIndex: () => { return textureIndexes++; }, onRequestContextHandle: () => { return gl.TEXTURE0 + this.constantTextureCount++; } }); this.constantBitRatios[name] = kernelValue.bitRatio; this.kernelConstants.push(kernelValue); kernelValue.setup(); if (kernelValue.forceUploadEachRun) { this.forceUploadKernelConstants.push(kernelValue); } } } build() { if (this.built) return; this.initExtensions(); this.validateSettings(arguments); this.setupConstants(arguments); if (this.fallbackRequested) return; this.setupArguments(arguments); if (this.fallbackRequested) return; this.updateMaxTexSize(); this.translateSource(); const failureResult = this.pickRenderStrategy(arguments); if (failureResult) { return failureResult; } const { texSize, context: gl, canvas } = this; gl.enable(gl.SCISSOR_TEST); if (this.pipeline && this.precision === 'single') { gl.viewport(0, 0, this.maxTexSize[0], this.maxTexSize[1]); canvas.width = this.maxTexSize[0]; canvas.height = this.maxTexSize[1]; } else { gl.viewport(0, 0, this.maxTexSize[0], this.maxTexSize[1]); canvas.width = this.maxTexSize[0]; canvas.height = this.maxTexSize[1]; } const threadDim = this.threadDim = Array.from(this.output); while (threadDim.length < 3) { threadDim.push(1); } const compiledVertexShader = this.getVertexShader(arguments); const vertShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertShader, compiledVertexShader); gl.compileShader(vertShader); this.vertShader = vertShader; const compiledFragmentShader = this.getFragmentShader(arguments); const fragShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragShader, compiledFragmentShader); gl.compileShader(fragShader); this.fragShader = fragShader; if (this.debug) { console.log('GLSL Shader Output:'); console.log(compiledFragmentShader); } if (!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) { throw new Error('Error compiling vertex shader: ' + gl.getShaderInfoLog(vertShader)); } if (!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) { throw new Error('Error compiling fragment shader: ' + gl.getShaderInfoLog(fragShader)); } const program = this.program = gl.createProgram(); gl.attachShader(program, vertShader); gl.attachShader(program, fragShader); gl.linkProgram(program); this.framebuffer = gl.createFramebuffer(); this.framebuffer.width = texSize[0]; this.framebuffer.height = texSize[1]; this.rawValueFramebuffers = {}; const vertices = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1 ]); const texCoords = new Float32Array([ 0, 0, 1, 0, 0, 1, 1, 1 ]); const texCoordOffset = vertices.byteLength; let buffer = this.buffer; if (!buffer) { buffer = this.buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, vertices.byteLength + texCoords.byteLength, gl.STATIC_DRAW); } else { gl.bindBuffer(gl.ARRAY_BUFFER, buffer); } gl.bufferSubData(gl.ARRAY_BUFFER, 0, vertices); gl.bufferSubData(gl.ARRAY_BUFFER, texCoordOffset, texCoords); const aPosLoc = gl.getAttribLocation(this.program, 'aPos'); gl.enableVertexAttribArray(aPosLoc); gl.vertexAttribPointer(aPosLoc, 2, gl.FLOAT, false, 0, 0); const aTexCoordLoc = gl.getAttribLocation(this.program, 'aTexCoord'); gl.enableVertexAttribArray(aTexCoordLoc); gl.vertexAttribPointer(aTexCoordLoc, 2, gl.FLOAT, false, 0, texCoordOffset); gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); let i = 0; gl.useProgram(this.program); for (let p in this.constants) { this.kernelConstants[i++].updateValue(this.constants[p]); } this._setupOutputTexture(); if ( this.subKernels !== null && this.subKernels.length > 0 ) { this._mappedTextureSwitched = {}; this._setupSubOutputTextures(); } this.buildSignature(arguments); this.built = true; } translateSource() { const functionBuilder = FunctionBuilder.fromKernel(this, WebGLFunctionNode, { fixIntegerDivisionAccuracy: this.fixIntegerDivisionAccuracy }); this.translatedSource = functionBuilder.getPrototypeString('kernel'); this.setupReturnTypes(functionBuilder); } setupReturnTypes(functionBuilder) { if (!this.graphical && !this.returnType) { this.returnType = functionBuilder.getKernelResultType(); } if (this.subKernels && this.subKernels.length > 0) { for (let i = 0; i < this.subKernels.length; i++) { const subKernel = this.subKernels[i]; if (!subKernel.returnType) { subKernel.returnType = functionBuilder.getSubKernelResultType(i); } } } } run() { const { kernelArguments, texSize, forceUploadKernelConstants, context: gl } = this; gl.useProgram(this.program); gl.scissor(0, 0, texSize[0], texSize[1]); if (this.dynamicOutput) { this.setUniform3iv('uOutputDim', new Int32Array(this.threadDim)); this.setUniform2iv('uTexSize', texSize); } this.setUniform2f('ratio', texSize[0] / this.maxTexSize[0], texSize[1] / this.maxTexSize[1]); for (let i = 0; i < forceUploadKernelConstants.length; i++) { const constant = forceUploadKernelConstants[i]; constant.updateValue(this.constants[constant.name]); if (this.switchingKernels) return; } for (let i = 0; i < kernelArguments.length; i++) { kernelArguments[i].updateValue(arguments[i]); if (this.switchingKernels) return; } if (this.plugins) { for (let i = 0; i < this.plugins.length; i++) { const plugin = this.plugins[i]; if (plugin.onBeforeRun) { plugin.onBeforeRun(this); } } } if (this.graphical) { if (this.pipeline) { gl.bindRenderbuffer(gl.RENDERBUFFER, null); gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); if (this.immutable) { this._replaceOutputTexture(); } gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); return this.immutable ? this.texture.clone() : this.texture; } gl.bindRenderbuffer(gl.RENDERBUFFER, null); gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); return; } gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); if (this.immutable) { this._replaceOutputTexture(); } if (this.subKernels !== null) { if (this.immutable) { this._replaceSubOutputTextures(); } this.drawBuffers(); } gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); } drawBuffers() { this.extensions.WEBGL_draw_buffers.drawBuffersWEBGL(this.drawBuffersMap); } getInternalFormat() { return this.context.RGBA; } getTextureFormat() { const { context: gl } = this; switch (this.getInternalFormat()) { case gl.RGBA: return gl.RGBA; default: throw new Error('Unknown internal format'); } } /** * * @desc replace output textures where arguments my be the same values */ _replaceOutputTexture() { if (this.texture.beforeMutate() || this._textureSwitched) { const gl = this.context; gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); this._textureSwitched = false; } } /** * @desc Setup output texture */ _setupOutputTexture() { const gl = this.context; const texSize = this.texSize; if (this.texture) { // here we inherit from an already existing kernel, so go ahead and just bind textures to the framebuffer gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); return; } const texture = this.createTexture(); gl.activeTexture(gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); const format = this.getInternalFormat(); if (this.precision === 'single') { gl.texImage2D(gl.TEXTURE_2D, 0, format, texSize[0], texSize[1], 0, gl.RGBA, gl.FLOAT, null); } else { gl.texImage2D(gl.TEXTURE_2D, 0, format, texSize[0], texSize[1], 0, format, gl.UNSIGNED_BYTE, null); } gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); this.texture = new this.TextureConstructor({ texture, size: texSize, dimensions: this.threadDim, output: this.output, context: this.context, internalFormat: this.getInternalFormat(), textureFormat: this.getTextureFormat(), kernel: this, }); } /** * * @desc replace sub-output textures where arguments my be the same values */ _replaceSubOutputTextures() { const gl = this.context; for (let i = 0; i < this.mappedTextures.length; i++) { const mappedTexture = this.mappedTextures[i]; if (mappedTexture.beforeMutate() || this._mappedTextureSwitched[i]) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, mappedTexture.texture, 0); this._mappedTextureSwitched[i] = false; } } } /** * @desc Setup on inherit sub-output textures */ _setupSubOutputTextures() { const gl = this.context; if (this.mappedTextures) { // here we inherit from an already existing kernel, so go ahead and just bind textures to the framebuffer for (let i = 0; i < this.subKernels.length; i++) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, this.mappedTextures[i].texture, 0); } return; } const texSize = this.texSize; this.drawBuffersMap = [gl.COLOR_ATTACHMENT0]; this.mappedTextures = []; for (let i = 0; i < this.subKernels.length; i++) { const texture = this.createTexture(); this.drawBuffersMap.push(gl.COLOR_ATTACHMENT0 + i + 1); gl.activeTexture(gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount + i); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); if (this.precision === 'single') { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize[0], texSize[1], 0, gl.RGBA, gl.FLOAT, null); } else { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize[0], texSize[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, texture, 0); this.mappedTextures.push(new this.TextureConstructor({ texture, size: texSize, dimensions: this.threadDim, output: this.output, context: this.context, internalFormat: this.getInternalFormat(), textureFormat: this.getTextureFormat(), kernel: this, })); } } setUniform1f(name, value) { if (this.uniform1fCache.hasOwnProperty(name)) { const cache = this.uniform1fCache[name]; if (value === cache) { return; } } this.uniform1fCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform1f(loc, value); } setUniform1i(name, value) { if (this.uniform1iCache.hasOwnProperty(name)) { const cache = this.uniform1iCache[name]; if (value === cache) { return; } } this.uniform1iCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform1i(loc, value); } setUniform2f(name, value1, value2) { if (this.uniform2fCache.hasOwnProperty(name)) { const cache = this.uniform2fCache[name]; if ( value1 === cache[0] && value2 === cache[1] ) { return; } } this.uniform2fCache[name] = [value1, value2]; const loc = this.getUniformLocation(name); this.context.uniform2f(loc, value1, value2); } setUniform2fv(name, value) { if (this.uniform2fvCache.hasOwnProperty(name)) { const cache = this.uniform2fvCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] ) { return; } } this.uniform2fvCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform2fv(loc, value); } setUniform2iv(name, value) { if (this.uniform2ivCache.hasOwnProperty(name)) { const cache = this.uniform2ivCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] ) { return; } } this.uniform2ivCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform2iv(loc, value); } setUniform3fv(name, value) { if (this.uniform3fvCache.hasOwnProperty(name)) { const cache = this.uniform3fvCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] && value[2] === cache[2] ) { return; } } this.uniform3fvCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform3fv(loc, value); } setUniform3iv(name, value) { if (this.uniform3ivCache.hasOwnProperty(name)) { const cache = this.uniform3ivCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] && value[2] === cache[2] ) { return; } } this.uniform3ivCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform3iv(loc, value); } setUniform4fv(name, value) { if (this.uniform4fvCache.hasOwnProperty(name)) { const cache = this.uniform4fvCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] && value[2] === cache[2] && value[3] === cache[3] ) { return; } } this.uniform4fvCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform4fv(loc, value); } setUniform4iv(name, value) { if (this.uniform4ivCache.hasOwnProperty(name)) { const cache = this.uniform4ivCache[name]; if ( value[0] === cache[0] && value[1] === cache[1] && value[2] === cache[2] && value[3] === cache[3] ) { return; } } this.uniform4ivCache[name] = value; const loc = this.getUniformLocation(name); this.context.uniform4iv(loc, value); } /** * @desc Return WebGlUniformLocation for various variables * related to webGl program, such as user-defined variables, * as well as, dimension sizes, etc. */ getUniformLocation(name) { if (this.programUniformLocationCache.hasOwnProperty(name)) { return this.programUniformLocationCache[name]; } return this.programUniformLocationCache[name] = this.context.getUniformLocation(this.program, name); } /** * @desc Generate Shader artifacts for the kernel program. * The final object contains HEADER, KERNEL, MAIN_RESULT, and others. * * @param {Array} args - The actual parameters sent to the Kernel * @returns {Object} An object containing the Shader Artifacts(CONSTANTS, HEADER, KERNEL, etc.) */ _getFragShaderArtifactMap(args) { return { HEADER: this._getHeaderString(), LOOP_MAX: this._getLoopMaxString(), PLUGINS: this._getPluginsString(), CONSTANTS: this._getConstantsString(), DECODE32_ENDIANNESS: this._getDecode32EndiannessString(), ENCODE32_ENDIANNESS: this._getEncode32EndiannessString(), DIVIDE_WITH_INTEGER_CHECK: this._getDivideWithIntegerCheckString(), INJECTED_NATIVE: this._getInjectedNative(), MAIN_CONSTANTS: this._getMainConstantsString(), MAIN_ARGUMENTS: this._getMainArgumentsString(args), KERNEL: this.getKernelString(), MAIN_RESULT: this.getMainResultString(), FLOAT_TACTIC_DECLARATION: this.getFloatTacticDeclaration(), INT_TACTIC_DECLARATION: this.getIntTacticDeclaration(), SAMPLER_2D_TACTIC_DECLARATION: this.getSampler2DTacticDeclaration(), SAMPLER_2D_ARRAY_TACTIC_DECLARATION: this.getSampler2DArrayTacticDeclaration(), }; } /** * @desc Generate Shader artifacts for the kernel program. * The final object contains HEADER, KERNEL, MAIN_RESULT, and others. * * @param {Array} args - The actual parameters sent to the Kernel * @returns {Object} An object containing the Shader Artifacts(CONSTANTS, HEADER, KERNEL, etc.) */ _getVertShaderArtifactMap(args) { return { FLOAT_TACTIC_DECLARATION: this.getFloatTacticDeclaration(), INT_TACTIC_DECLARATION: this.getIntTacticDeclaration(), SAMPLER_2D_TACTIC_DECLARATION: this.getSampler2DTacticDeclaration(), SAMPLER_2D_ARRAY_TACTIC_DECLARATION: this.getSampler2DArrayTacticDeclaration(), }; } /** * @desc Get the header string for the program. * This returns an empty string if no sub-kernels are defined. * * @returns {String} result */ _getHeaderString() { return ( this.subKernels !== null ? '#extension GL_EXT_draw_buffers : require\n' : '' ); } /** * @desc Get the maximum loop size String. * @returns {String} result */ _getLoopMaxString() { return ( this.loopMaxIterations ? ` ${parseInt(this.loopMaxIterations)};\n` : ' 1000;\n' ); } _getPluginsString() { if (!this.plugins) return '\n'; return this.plugins.map(plugin => plugin.source && this.source.match(plugin.functionMatch) ? plugin.source : '').join('\n'); } /** * @desc Generate transpiled glsl Strings for constant parameters sent to a kernel * @returns {String} result */ _getConstantsString() { const result = []; const { threadDim, texSize } = this; if (this.dynamicOutput) { result.push( 'uniform ivec3 uOutputDim', 'uniform ivec2 uTexSize' ); } else { result.push( `ivec3 uOutputDim = ivec3(${threadDim[0]}, ${threadDim[1]}, ${threadDim[2]})`, `ivec2 uTexSize = ivec2(${texSize[0]}, ${texSize[1]})` ); } return utils.linesToString(result); } /** * @desc Get texture coordinate string for the program * @returns {String} result */ _getTextureCoordinate() { const subKernels = this.subKernels; if (subKernels === null || subKernels.length < 1) { return 'varying vec2 vTexCoord;\n'; } else { return 'out vec2 vTexCoord;\n'; } } /** * @desc Get Decode32 endianness string for little-endian and big-endian * @returns {String} result */ _getDecode32EndiannessString() { return ( this.endianness === 'LE' ? '' : ' texel.rgba = texel.abgr;\n' ); } /** * @desc Get Encode32 endianness string for little-endian and big-endian * @returns {String} result */ _getEncode32EndiannessString() { return ( this.endianness === 'LE' ? '' : ' texel.rgba = texel.abgr;\n' ); } /** * @desc if fixIntegerDivisionAccuracy provide method to replace / * @returns {String} result */ _getDivideWithIntegerCheckString() { return this.fixIntegerDivisionAccuracy ? `float divWithIntCheck(float x, float y) { if (floor(x) == x && floor(y) == y && integerMod(x, y) == 0.0) { return float(int(x) / int(y)); } return x / y; } float integerCorrectionModulo(float number, float divisor) { if (number < 0.0) { number = abs(number); if (divisor < 0.0) { divisor = abs(divisor); } return -(number - (divisor * floor(divWithIntCheck(number, divisor)))); } if (divisor < 0.0) { divisor = abs(divisor); } return number - (divisor * floor(divWithIntCheck(number, divisor))); }` : ''; } /** * @desc Generate transpiled glsl Strings for user-defined parameters sent to a kernel * @param {Array} args - The actual parameters sent to the Kernel * @returns {String} result */ _getMainArgumentsString(args) { const results = []; const { argumentNames } = this; for (let i = 0; i < argumentNames.length; i++) { results.push(this.kernelArguments[i].getSource(args[i])); } return results.join(''); } _getInjectedNative() { return this.injectedNative || ''; } _getMainConstantsString() { const result = []; const { constants } = this; if (constants) { let i = 0; for (const name in constants) { if (!this.constants.hasOwnProperty(name)) continue; result.push(this.kernelConstants[i++].getSource(this.constants[name])); } } return result.join(''); } getRawValueFramebuffer(width, height) { if (!this.rawValueFramebuffers[width]) { this.rawValueFramebuffers[width] = {}; } if (!this.rawValueFramebuffers[width][height]) { const framebuffer = this.context.createFramebuffer(); framebuffer.width = width; framebuffer.height = height; this.rawValueFramebuffers[width][height] = framebuffer; } return this.rawValueFramebuffers[width][height]; } getKernelResultDeclaration() { switch (this.returnType) { case 'Array(2)': return 'vec2 kernelResult'; case 'Array(3)': return 'vec3 kernelResult'; case 'Array(4)': return 'vec4 kernelResult'; case 'LiteralInteger': case 'Float': case 'Number': case 'Integer': return 'float kernelResult'; default: if (this.graphical) { return 'float kernelResult'; } else { throw new Error(`unrecognized output type "${ this.returnType }"`); } } } /** * @desc Get Kernel program string (in *glsl*) for a kernel. * @returns {String} result */ getKernelString() { const result = [this.getKernelResultDeclaration()]; const { subKernels } = this; if (subKernels !== null) { switch (this.returnType) { case 'Number': case 'Float': case 'Integer': for (let i = 0; i < subKernels.length; i++) { const subKernel = subKernels[i]; result.push( subKernel.returnType === 'Integer' ? `int subKernelResult_${ subKernel.name } = 0` : `float subKernelResult_${ subKernel.name } = 0.0` ); } break; case 'Array(2)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec2 subKernelResult_${ subKernels[i].name }` ); } break; case 'Array(3)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec3 subKernelResult_${ subKernels[i].name }` ); } break; case 'Array(4)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec4 subKernelResult_${ subKernels[i].name }` ); } break; } } return utils.linesToString(result) + this.translatedSource; } getMainResultGraphical() { return utils.linesToString([ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' gl_FragColor = actualColor', ]); } getMainResultPackedPixels() { switch (this.returnType) { case 'LiteralInteger': case 'Number': case 'Integer': case 'Float': return this.getMainResultKernelPackedPixels() + this.getMainResultSubKernelPackedPixels(); default: throw new Error(`packed output only usable with Numbers, "${this.returnType}" specified`); } } /** * @return {String} */ getMainResultKernelPackedPixels() { return utils.linesToString([ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ` gl_FragData[0] = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(kernelResult)` ]); } /** * @return {String} */ getMainResultSubKernelPackedPixels() { const result = []; if (!this.subKernels) return ''; for (let i = 0; i < this.subKernels.length; i++) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` gl_FragData[${i + 1}] = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(float(subKernelResult_${this.subKernels[i].name}))` ); } else { result.push( ` gl_FragData[${i + 1}] = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(subKernelResult_${this.subKernels[i].name})` ); } } return utils.linesToString(result); } getMainResultMemoryOptimizedFloats() { const result = [ ' index *= 4', ]; switch (this.returnType) { case 'Number': case 'Integer': case 'Float': const channels = ['r', 'g', 'b', 'a']; for (let i = 0; i < channels.length; i++) { const channel = channels[i]; this.getMainResultKernelMemoryOptimizedFloats(result, channel); this.getMainResultSubKernelMemoryOptimizedFloats(result, channel); if (i + 1 < channels.length) { result.push(' index += 1'); } } break; default: throw new Error(`optimized output only usable with Numbers, ${this.returnType} specified`); } return utils.linesToString(result); } getMainResultKernelMemoryOptimizedFloats(result, channel) { result.push( ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ` gl_FragData[0].${channel} = kernelResult` ); } getMainResultSubKernelMemoryOptimizedFloats(result, channel) { if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; i++) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` gl_FragData[${i + 1}].${channel} = float(subKernelResult_${this.subKernels[i].name})` ); } else { result.push( ` gl_FragData[${i + 1}].${channel} = subKernelResult_${this.subKernels[i].name}` ); } } } getMainResultKernelNumberTexture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' gl_FragData[0][0] = kernelResult', ]; } getMainResultSubKernelNumberTexture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` gl_FragData[${i + 1}][0] = float(subKernelResult_${subKernel.name})` ); } else { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${subKernel.name}` ); } } return result; } getMainResultKernelArray2Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' gl_FragData[0][0] = kernelResult[0]', ' gl_FragData[0][1] = kernelResult[1]', ]; } getMainResultSubKernelArray2Texture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${this.subKernels[i].name}[0]`, ` gl_FragData[${i + 1}][1] = subKernelResult_${this.subKernels[i].name}[1]` ); } return result; } getMainResultKernelArray3Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' gl_FragData[0][0] = kernelResult[0]', ' gl_FragData[0][1] = kernelResult[1]', ' gl_FragData[0][2] = kernelResult[2]', ]; } getMainResultSubKernelArray3Texture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${this.subKernels[i].name}[0]`, ` gl_FragData[${i + 1}][1] = subKernelResult_${this.subKernels[i].name}[1]`, ` gl_FragData[${i + 1}][2] = subKernelResult_${this.subKernels[i].name}[2]` ); } return result; } getMainResultKernelArray4Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' gl_FragData[0] = kernelResult', ]; } getMainResultSubKernelArray4Texture() { const result = []; if (!this.subKernels) return result; switch (this.returnType) { case 'Number': case 'Float': case 'Integer': for (let i = 0; i < this.subKernels.length; ++i) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` gl_FragData[${i + 1}] = float(subKernelResult_${this.subKernels[i].name})` ); } else { result.push( ` gl_FragData[${i + 1}] = subKernelResult_${this.subKernels[i].name}` ); } } break; case 'Array(2)': for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${this.subKernels[i].name}[0]`, ` gl_FragData[${i + 1}][1] = subKernelResult_${this.subKernels[i].name}[1]` ); } break; case 'Array(3)': for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${this.subKernels[i].name}[0]`, ` gl_FragData[${i + 1}][1] = subKernelResult_${this.subKernels[i].name}[1]`, ` gl_FragData[${i + 1}][2] = subKernelResult_${this.subKernels[i].name}[2]` ); } break; case 'Array(4)': for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` gl_FragData[${i + 1}][0] = subKernelResult_${this.subKernels[i].name}[0]`, ` gl_FragData[${i + 1}][1] = subKernelResult_${this.subKernels[i].name}[1]`, ` gl_FragData[${i + 1}][2] = subKernelResult_${this.subKernels[i].name}[2]`, ` gl_FragData[${i + 1}][3] = subKernelResult_${this.subKernels[i].name}[3]` ); } break; } return result; } /** * @param {String} src - Shader string * @param {Object} map - Variables/Constants associated with shader */ replaceArtifacts(src, map) { return src.replace(/[ ]*__([A-Z]+[0-9]*([_]?[A-Z]*[0-9]?)*)__;\n/g, (match, artifact) => { if (map.hasOwnProperty(artifact)) { return map[artifact]; } throw `unhandled artifact ${artifact}`; }); } /** * @desc Get the fragment shader String. * If the String hasn't been compiled yet, * then this method compiles it as well * * @param {Array} args - The actual parameters sent to the Kernel * @returns {string} Fragment Shader string */ getFragmentShader(args) { if (this.compiledFragmentShader !== null) { return this.compiledFragmentShader; } return this.compiledFragmentShader = this.replaceArtifacts(this.constructor.fragmentShader, this._getFragShaderArtifactMap(args)); } /** * @desc Get the vertical shader String * @param {Array|IArguments} args - The actual parameters sent to the Kernel * @returns {string} Vertical Shader string */ getVertexShader(args) { if (this.compiledVertexShader !== null) { return this.compiledVertexShader; } return this.compiledVertexShader = this.replaceArtifacts(this.constructor.vertexShader, this._getVertShaderArtifactMap(args)); } /** * @desc Returns the *pre-compiled* Kernel as a JS Object String, that can be reused. */ toString() { const setupContextString = utils.linesToString([ `const gl = context`, ]); return glKernelString(this.constructor, arguments, this, setupContextString); } destroy(removeCanvasReferences) { if (!this.context) return; if (this.buffer) { this.context.deleteBuffer(this.buffer); } if (this.framebuffer) { this.context.deleteFramebuffer(this.framebuffer); } for (const width in this.rawValueFramebuffers) { for (const height in this.rawValueFramebuffers[width]) { this.context.deleteFramebuffer(this.rawValueFramebuffers[width][height]); delete this.rawValueFramebuffers[width][height]; } delete this.rawValueFramebuffers[width]; } if (this.vertShader) { this.context.deleteShader(this.vertShader); } if (this.fragShader) { this.context.deleteShader(this.fragShader); } if (this.program) { this.context.deleteProgram(this.program); } if (this.texture) { this.texture.delete(); const textureCacheIndex = this.textureCache.indexOf(this.texture.texture); if (textureCacheIndex > -1) { this.textureCache.splice(textureCacheIndex, 1); } this.texture = null; } if (this.mappedTextures && this.mappedTextures.length) { for (let i = 0; i < this.mappedTextures.length; i++) { const mappedTexture = this.mappedTextures[i]; mappedTexture.delete(); const textureCacheIndex = this.textureCache.indexOf(mappedTexture.texture); if (textureCacheIndex > -1) { this.textureCache.splice(textureCacheIndex, 1); } } this.mappedTextures = null; } if (this.kernelArguments) { for (let i = 0; i < this.kernelArguments.length; i++) { this.kernelArguments[i].destroy(); } } if (this.kernelConstants) { for (let i = 0; i < this.kernelConstants.length; i++) { this.kernelConstants[i].destroy(); } } while (this.textureCache.length > 0) { const texture = this.textureCache.pop(); this.context.deleteTexture(texture); } if (removeCanvasReferences) { const idx = canvases.indexOf(this.canvas); if (idx >= 0) { canvases[idx] = null; maxTexSizes[idx] = null; } } this.destroyExtensions(); delete this.context; delete this.canvas; if (!this.gpu) return; const i = this.gpu.kernels.indexOf(this); if (i === -1) return; this.gpu.kernels.splice(i, 1); } destroyExtensions() { this.extensions.OES_texture_float = null; this.extensions.OES_texture_float_linear = null; this.extensions.OES_element_index_uint = null; this.extensions.WEBGL_draw_buffers = null; } static destroyContext(context) { const extension = context.getExtension('WEBGL_lose_context'); if (extension) { extension.loseContext(); } } /** * @return {IKernelJSON} */ toJSON() { const json = super.toJSON(); json.functionNodes = FunctionBuilder.fromKernel(this, WebGLFunctionNode).toJSON(); json.settings.threadDim = this.threadDim; return json; } } module.exports = { WebGLKernel }; ================================================ FILE: src/backend/web-gl/vertex-shader.js ================================================ // language=GLSL const vertexShader = `__FLOAT_TACTIC_DECLARATION__; __INT_TACTIC_DECLARATION__; __SAMPLER_2D_TACTIC_DECLARATION__; attribute vec2 aPos; attribute vec2 aTexCoord; varying vec2 vTexCoord; uniform vec2 ratio; void main(void) { gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1); vTexCoord = aTexCoord; }`; module.exports = { vertexShader }; ================================================ FILE: src/backend/web-gl2/fragment-shader.js ================================================ // language=GLSL const fragmentShader = `#version 300 es __HEADER__; __FLOAT_TACTIC_DECLARATION__; __INT_TACTIC_DECLARATION__; __SAMPLER_2D_TACTIC_DECLARATION__; __SAMPLER_2D_ARRAY_TACTIC_DECLARATION__; const int LOOP_MAX = __LOOP_MAX__; __PLUGINS__; __CONSTANTS__; in vec2 vTexCoord; float atan2(float v1, float v2) { if (v1 == 0.0 || v2 == 0.0) return 0.0; return atan(v1 / v2); } float cbrt(float x) { if (x >= 0.0) { return pow(x, 1.0 / 3.0); } else { return -pow(x, 1.0 / 3.0); } } float expm1(float x) { return pow(${Math.E}, x) - 1.0; } float fround(highp float x) { return x; } float imul(float v1, float v2) { return float(int(v1) * int(v2)); } float log10(float x) { return log2(x) * (1.0 / log2(10.0)); } float log1p(float x) { return log(1.0 + x); } float _pow(float v1, float v2) { if (v2 == 0.0) return 1.0; return pow(v1, v2); } float _round(float x) { return floor(x + 0.5); } const int BIT_COUNT = 32; int modi(int x, int y) { return x - y * (x / y); } int bitwiseOr(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 || b > 0)) { break; } } return result; } int bitwiseXOR(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 || b > 0)) { break; } } return result; } int bitwiseAnd(int a, int b) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) { result += n; } a = a / 2; b = b / 2; n = n * 2; if(!(a > 0 && b > 0)) { break; } } return result; } int bitwiseNot(int a) { int result = 0; int n = 1; for (int i = 0; i < BIT_COUNT; i++) { if (modi(a, 2) == 0) { result += n; } a = a / 2; n = n * 2; } return result; } int bitwiseZeroFillLeftShift(int n, int shift) { int maxBytes = BIT_COUNT; for (int i = 0; i < BIT_COUNT; i++) { if (maxBytes >= n) { break; } maxBytes *= 2; } for (int i = 0; i < BIT_COUNT; i++) { if (i >= shift) { break; } n *= 2; } int result = 0; int byteVal = 1; for (int i = 0; i < BIT_COUNT; i++) { if (i >= maxBytes) break; if (modi(n, 2) > 0) { result += byteVal; } n = int(n / 2); byteVal *= 2; } return result; } int bitwiseSignedRightShift(int num, int shifts) { return int(floor(float(num) / pow(2.0, float(shifts)))); } int bitwiseZeroFillRightShift(int n, int shift) { int maxBytes = BIT_COUNT; for (int i = 0; i < BIT_COUNT; i++) { if (maxBytes >= n) { break; } maxBytes *= 2; } for (int i = 0; i < BIT_COUNT; i++) { if (i >= shift) { break; } n /= 2; } int result = 0; int byteVal = 1; for (int i = 0; i < BIT_COUNT; i++) { if (i >= maxBytes) break; if (modi(n, 2) > 0) { result += byteVal; } n = int(n / 2); byteVal *= 2; } return result; } vec2 integerMod(vec2 x, float y) { vec2 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } vec3 integerMod(vec3 x, float y) { vec3 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } vec4 integerMod(vec4 x, vec4 y) { vec4 res = floor(mod(x, y)); return res * step(1.0 - floor(y), -res); } float integerMod(float x, float y) { float res = floor(mod(x, y)); return res * (res > floor(y) - 1.0 ? 0.0 : 1.0); } int integerMod(int x, int y) { return x - (y * int(x/y)); } __DIVIDE_WITH_INTEGER_CHECK__; // Here be dragons! // DO NOT OPTIMIZE THIS CODE // YOU WILL BREAK SOMETHING ON SOMEBODY\'S MACHINE // LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME const vec2 MAGIC_VEC = vec2(1.0, -256.0); const vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0); const vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536 float decode32(vec4 texel) { __DECODE32_ENDIANNESS__; texel *= 255.0; vec2 gte128; gte128.x = texel.b >= 128.0 ? 1.0 : 0.0; gte128.y = texel.a >= 128.0 ? 1.0 : 0.0; float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC); float res = exp2(round(exponent)); texel.b = texel.b - 128.0 * gte128.x; res = dot(texel, SCALE_FACTOR) * exp2(round(exponent-23.0)) + res; res *= gte128.y * -2.0 + 1.0; return res; } float decode16(vec4 texel, int index) { int channel = integerMod(index, 2); return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0; } float decode8(vec4 texel, int index) { int channel = integerMod(index, 4); return texel[channel] * 255.0; } vec4 legacyEncode32(float f) { float F = abs(f); float sign = f < 0.0 ? 1.0 : 0.0; float exponent = floor(log2(F)); float mantissa = (exp2(-exponent) * F); // exponent += floor(log2(mantissa)); vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV; texel.rg = integerMod(texel.rg, 256.0); texel.b = integerMod(texel.b, 128.0); texel.a = exponent*0.5 + 63.5; texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0; texel = floor(texel); texel *= 0.003921569; // 1/255 __ENCODE32_ENDIANNESS__; return texel; } // https://github.com/gpujs/gpu.js/wiki/Encoder-details vec4 encode32(float value) { if (value == 0.0) return vec4(0, 0, 0, 0); float exponent; float mantissa; vec4 result; float sgn; sgn = step(0.0, -value); value = abs(value); exponent = floor(log2(value)); mantissa = value*pow(2.0, -exponent)-1.0; exponent = exponent+127.0; result = vec4(0,0,0,0); result.a = floor(exponent/2.0); exponent = exponent - result.a*2.0; result.a = result.a + 128.0*sgn; result.b = floor(mantissa * 128.0); mantissa = mantissa - result.b / 128.0; result.b = result.b + exponent*128.0; result.g = floor(mantissa*32768.0); mantissa = mantissa - result.g/32768.0; result.r = floor(mantissa*8388608.0); return result/255.0; } // Dragons end here int index; ivec3 threadId; ivec3 indexTo3D(int idx, ivec3 texDim) { int z = int(idx / (texDim.x * texDim.y)); idx -= z * int(texDim.x * texDim.y); int y = int(idx / texDim.x); int x = int(integerMod(idx, texDim.x)); return ivec3(x, y, z); } float get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture(tex, st / vec2(texSize)); return decode32(texel); } float get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + (texDim.x * (y + (texDim.y * z))); int w = texSize.x * 2; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y)); return decode16(texel, index); } float get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + (texDim.x * (y + (texDim.y * z))); int w = texSize.x * 4; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y)); return decode8(texel, index); } float getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + (texDim.x * (y + (texDim.y * z))); int channel = integerMod(index, 4); index = index / 4; int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; index = index / 4; vec4 texel = texture(tex, st / vec2(texSize)); return texel[channel]; } vec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; return texture(tex, st / vec2(texSize)); } vec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; return texture(tex, vec3(st / vec2(texSize), z)); } float getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return result[0]; } vec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return vec2(result[0], result[1]); } vec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int channel = integerMod(index, 2); index = index / 2; int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture(tex, st / vec2(texSize)); if (channel == 0) return vec2(texel.r, texel.g); if (channel == 1) return vec2(texel.b, texel.a); return vec2(0.0, 0.0); } vec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { vec4 result = getImage2D(tex, texSize, texDim, z, y, x); return vec3(result[0], result[1], result[2]); } vec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z)); int vectorIndex = fieldIndex / 4; int vectorOffset = fieldIndex - vectorIndex * 4; int readY = vectorIndex / texSize.x; int readX = vectorIndex - readY * texSize.x; vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize)); if (vectorOffset == 0) { return tex1.xyz; } else if (vectorOffset == 1) { return tex1.yzw; } else { readX++; if (readX >= texSize.x) { readX = 0; readY++; } vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize)); if (vectorOffset == 2) { return vec3(tex1.z, tex1.w, tex2.x); } else { return vec3(tex1.w, tex2.x, tex2.y); } } } vec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { return getImage2D(tex, texSize, texDim, z, y, x); } vec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) { int index = x + texDim.x * (y + texDim.y * z); int channel = integerMod(index, 2); int w = texSize.x; vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5; vec4 texel = texture(tex, st / vec2(texSize)); return vec4(texel.r, texel.g, texel.b, texel.a); } vec4 actualColor; void color(float r, float g, float b, float a) { actualColor = vec4(r,g,b,a); } void color(float r, float g, float b) { color(r,g,b,1.0); } float modulo(float number, float divisor) { if (number < 0.0) { number = abs(number); if (divisor < 0.0) { divisor = abs(divisor); } return -mod(number, divisor); } if (divisor < 0.0) { divisor = abs(divisor); } return mod(number, divisor); } __INJECTED_NATIVE__; __MAIN_CONSTANTS__; __MAIN_ARGUMENTS__; __KERNEL__; void main(void) { index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x; __MAIN_RESULT__; }`; module.exports = { fragmentShader }; ================================================ FILE: src/backend/web-gl2/function-node.js ================================================ const { utils } = require('../../utils'); const { WebGLFunctionNode } = require('../web-gl/function-node'); /** * @class WebGL2FunctionNode * @desc [INTERNAL] Takes in a function node, and does all the AST voodoo required to toString its respective webGL code. * @extends WebGLFunctionNode * @returns the converted webGL function string */ class WebGL2FunctionNode extends WebGLFunctionNode { /** * @desc Parses the abstract syntax tree for *identifier* expression * @param {Object} idtNode - An ast Node * @param {Array} retArr - return array string * @returns {Array} the append retArr */ astIdentifierExpression(idtNode, retArr) { if (idtNode.type !== 'Identifier') { throw this.astErrorOutput( 'IdentifierExpression - not an Identifier', idtNode ); } const type = this.getType(idtNode); const name = utils.sanitizeName(idtNode.name); if (idtNode.name === 'Infinity') { retArr.push('intBitsToFloat(2139095039)'); } else if (type === 'Boolean') { if (this.argumentNames.indexOf(name) > -1) { retArr.push(`bool(user_${name})`); } else { retArr.push(`user_${name}`); } } else { retArr.push(`user_${name}`); } return retArr; } } module.exports = { WebGL2FunctionNode }; ================================================ FILE: src/backend/web-gl2/kernel-value/array2.js ================================================ const { WebGLKernelValueArray2 } = require('../../web-gl/kernel-value/array2'); class WebGL2KernelValueArray2 extends WebGLKernelValueArray2 {} module.exports = { WebGL2KernelValueArray2 }; ================================================ FILE: src/backend/web-gl2/kernel-value/array3.js ================================================ const { WebGLKernelValueArray3 } = require('../../web-gl/kernel-value/array3'); class WebGL2KernelValueArray3 extends WebGLKernelValueArray3 {} module.exports = { WebGL2KernelValueArray3 }; ================================================ FILE: src/backend/web-gl2/kernel-value/array4.js ================================================ const { WebGLKernelValueArray4 } = require('../../web-gl/kernel-value/array4'); class WebGL2KernelValueArray4 extends WebGLKernelValueArray4 {} module.exports = { WebGL2KernelValueArray4 }; ================================================ FILE: src/backend/web-gl2/kernel-value/boolean.js ================================================ const { WebGLKernelValueBoolean } = require('../../web-gl/kernel-value/boolean'); class WebGL2KernelValueBoolean extends WebGLKernelValueBoolean {} module.exports = { WebGL2KernelValueBoolean }; ================================================ FILE: src/backend/web-gl2/kernel-value/dynamic-html-image-array.js ================================================ const { utils } = require('../../../utils'); const { WebGL2KernelValueHTMLImageArray } = require('./html-image-array'); class WebGL2KernelValueDynamicHTMLImageArray extends WebGL2KernelValueHTMLImageArray { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2DArray ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(images) { const { width, height } = images[0]; this.checkSize(width, height); this.dimensions = [width, height, images.length]; this.textureSize = [width, height]; this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(images); } } module.exports = { WebGL2KernelValueDynamicHTMLImageArray }; ================================================ FILE: src/backend/web-gl2/kernel-value/dynamic-html-image.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueDynamicHTMLImage } = require('../../web-gl/kernel-value/dynamic-html-image'); class WebGL2KernelValueDynamicHTMLImage extends WebGLKernelValueDynamicHTMLImage { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } } module.exports = { WebGL2KernelValueDynamicHTMLImage }; ================================================ FILE: src/backend/web-gl2/kernel-value/dynamic-html-video.js ================================================ const { utils } = require('../../../utils'); const { WebGL2KernelValueDynamicHTMLImage } = require('./dynamic-html-image'); class WebGL2KernelValueDynamicHTMLVideo extends WebGL2KernelValueDynamicHTMLImage {} module.exports = { WebGL2KernelValueDynamicHTMLVideo }; ================================================ FILE: src/backend/web-gl2/kernel-value/dynamic-memory-optimized-number-texture.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueDynamicMemoryOptimizedNumberTexture } = require('../../web-gl/kernel-value/dynamic-memory-optimized-number-texture'); class WebGL2KernelValueDynamicMemoryOptimizedNumberTexture extends WebGLKernelValueDynamicMemoryOptimizedNumberTexture { getSource() { return utils.linesToString([ `uniform sampler2D ${this.id}`, `uniform ivec2 ${this.sizeId}`, `uniform ivec3 ${this.dimensionsId}`, ]); } } module.exports = { WebGL2KernelValueDynamicMemoryOptimizedNumberTexture }; ================================================ FILE: src/backend/web-gl2/kernel-value/dynamic-number-texture.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueDynamicNumberTexture } = require('../../web-gl/kernel-value/dynamic-number-texture'); class WebGL2KernelValueDynamicNumberTexture extends WebGLKernelValueDynamicNumberTexture { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } } module.exports = { WebGL2KernelValueDynamicNumberTexture }; ================================================ FILE: src/backend/web-gl2/kernel-value/dynamic-single-array.js ================================================ const { utils } = require('../../../utils'); const { WebGL2KernelValueSingleArray } = require('../../web-gl2/kernel-value/single-array'); class WebGL2KernelValueDynamicSingleArray extends WebGL2KernelValueSingleArray { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.dimensions = utils.getDimensions(value, true); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGL2KernelValueDynamicSingleArray }; ================================================ FILE: src/backend/web-gl2/kernel-value/dynamic-single-array1d-i.js ================================================ const { utils } = require('../../../utils'); const { WebGL2KernelValueSingleArray1DI } = require('../../web-gl2/kernel-value/single-array1d-i'); class WebGL2KernelValueDynamicSingleArray1DI extends WebGL2KernelValueSingleArray1DI { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGL2KernelValueDynamicSingleArray1DI }; ================================================ FILE: src/backend/web-gl2/kernel-value/dynamic-single-array2d-i.js ================================================ const { utils } = require('../../../utils'); const { WebGL2KernelValueSingleArray2DI } = require('../../web-gl2/kernel-value/single-array2d-i'); class WebGL2KernelValueDynamicSingleArray2DI extends WebGL2KernelValueSingleArray2DI { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGL2KernelValueDynamicSingleArray2DI }; ================================================ FILE: src/backend/web-gl2/kernel-value/dynamic-single-array3d-i.js ================================================ const { utils } = require('../../../utils'); const { WebGL2KernelValueSingleArray3DI } = require('../../web-gl2/kernel-value/single-array3d-i'); class WebGL2KernelValueDynamicSingleArray3DI extends WebGL2KernelValueSingleArray3DI { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { this.setShape(value); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGL2KernelValueDynamicSingleArray3DI }; ================================================ FILE: src/backend/web-gl2/kernel-value/dynamic-single-input.js ================================================ const { utils } = require('../../../utils'); const { WebGL2KernelValueSingleInput } = require('../../web-gl2/kernel-value/single-input'); class WebGL2KernelValueDynamicSingleInput extends WebGL2KernelValueSingleInput { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } updateValue(value) { let [w, h, d] = value.size; this.dimensions = new Int32Array([w || 1, h || 1, d || 1]); this.textureSize = utils.getMemoryOptimizedFloatTextureSize(this.dimensions, this.bitRatio); this.uploadArrayLength = this.textureSize[0] * this.textureSize[1] * this.bitRatio; this.checkSize(this.textureSize[0], this.textureSize[1]); this.uploadValue = new Float32Array(this.uploadArrayLength); this.kernel.setUniform3iv(this.dimensionsId, this.dimensions); this.kernel.setUniform2iv(this.sizeId, this.textureSize); super.updateValue(value); } } module.exports = { WebGL2KernelValueDynamicSingleInput }; ================================================ FILE: src/backend/web-gl2/kernel-value/dynamic-unsigned-array.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueDynamicUnsignedArray } = require('../../web-gl/kernel-value/dynamic-unsigned-array'); class WebGL2KernelValueDynamicUnsignedArray extends WebGLKernelValueDynamicUnsignedArray { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } } module.exports = { WebGL2KernelValueDynamicUnsignedArray }; ================================================ FILE: src/backend/web-gl2/kernel-value/dynamic-unsigned-input.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueDynamicUnsignedInput } = require('../../web-gl/kernel-value/dynamic-unsigned-input'); class WebGL2KernelValueDynamicUnsignedInput extends WebGLKernelValueDynamicUnsignedInput { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `uniform ${ variablePrecision } ivec2 ${this.sizeId}`, `uniform ${ variablePrecision } ivec3 ${this.dimensionsId}`, ]); } } module.exports = { WebGL2KernelValueDynamicUnsignedInput }; ================================================ FILE: src/backend/web-gl2/kernel-value/float.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueFloat } = require('../../web-gl/kernel-value/float'); class WebGL2KernelValueFloat extends WebGLKernelValueFloat {} module.exports = { WebGL2KernelValueFloat }; ================================================ FILE: src/backend/web-gl2/kernel-value/html-image-array.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelArray } = require('../../web-gl/kernel-value/array'); class WebGL2KernelValueHTMLImageArray extends WebGLKernelArray { constructor(value, settings) { super(value, settings); this.checkSize(value[0].width, value[0].height); this.dimensions = [value[0].width, value[0].height, value.length]; this.textureSize = [value[0].width, value[0].height]; } defineTexture() { const { context: gl } = this; gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.texture); gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MIN_FILTER, gl.NEAREST); } getStringValueHandler() { return `const uploadValue_${this.name} = ${this.varName};\n`; } getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2DArray ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(images) { const { context: gl } = this; gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); // Upload the images into the texture. gl.texImage3D( gl.TEXTURE_2D_ARRAY, 0, gl.RGBA, images[0].width, images[0].height, images.length, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); for (let i = 0; i < images.length; i++) { const xOffset = 0; const yOffset = 0; const imageDepth = 1; gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, xOffset, yOffset, i, images[i].width, images[i].height, imageDepth, gl.RGBA, gl.UNSIGNED_BYTE, this.uploadValue = images[i] ); } this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueHTMLImageArray }; ================================================ FILE: src/backend/web-gl2/kernel-value/html-image.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueHTMLImage } = require('../../web-gl/kernel-value/html-image'); class WebGL2KernelValueHTMLImage extends WebGLKernelValueHTMLImage { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } } module.exports = { WebGL2KernelValueHTMLImage }; ================================================ FILE: src/backend/web-gl2/kernel-value/html-video.js ================================================ const { utils } = require('../../../utils'); const { WebGL2KernelValueHTMLImage } = require('./html-image'); class WebGL2KernelValueHTMLVideo extends WebGL2KernelValueHTMLImage {} module.exports = { WebGL2KernelValueHTMLVideo }; ================================================ FILE: src/backend/web-gl2/kernel-value/integer.js ================================================ const { WebGLKernelValueInteger } = require('../../web-gl/kernel-value/integer'); class WebGL2KernelValueInteger extends WebGLKernelValueInteger { getSource(value) { const variablePrecision = this.getVariablePrecisionString(); if (this.origin === 'constants') { return `const ${ variablePrecision } int ${this.id} = ${ parseInt(value) };\n`; } return `uniform ${ variablePrecision } int ${this.id};\n`; } updateValue(value) { if (this.origin === 'constants') return; this.kernel.setUniform1i(this.id, this.uploadValue = value); } } module.exports = { WebGL2KernelValueInteger }; ================================================ FILE: src/backend/web-gl2/kernel-value/memory-optimized-number-texture.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueMemoryOptimizedNumberTexture } = require('../../web-gl/kernel-value/memory-optimized-number-texture'); class WebGL2KernelValueMemoryOptimizedNumberTexture extends WebGLKernelValueMemoryOptimizedNumberTexture { getSource() { const { id, sizeId, textureSize, dimensionsId, dimensions } = this; const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform sampler2D ${id}`, `${ variablePrecision } ivec2 ${sizeId} = ivec2(${textureSize[0]}, ${textureSize[1]})`, `${ variablePrecision } ivec3 ${dimensionsId} = ivec3(${dimensions[0]}, ${dimensions[1]}, ${dimensions[2]})`, ]); } } module.exports = { WebGL2KernelValueMemoryOptimizedNumberTexture }; ================================================ FILE: src/backend/web-gl2/kernel-value/number-texture.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueNumberTexture } = require('../../web-gl/kernel-value/number-texture'); class WebGL2KernelValueNumberTexture extends WebGLKernelValueNumberTexture { getSource() { const { id, sizeId, textureSize, dimensionsId, dimensions } = this; const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${id}`, `${ variablePrecision } ivec2 ${sizeId} = ivec2(${textureSize[0]}, ${textureSize[1]})`, `${ variablePrecision } ivec3 ${dimensionsId} = ivec3(${dimensions[0]}, ${dimensions[1]}, ${dimensions[2]})`, ]); } } module.exports = { WebGL2KernelValueNumberTexture }; ================================================ FILE: src/backend/web-gl2/kernel-value/single-array.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray } = require('../../web-gl/kernel-value/single-array'); class WebGL2KernelValueSingleArray extends WebGLKernelValueSingleArray { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueSingleArray }; ================================================ FILE: src/backend/web-gl2/kernel-value/single-array1d-i.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray1DI } = require('../../web-gl/kernel-value/single-array1d-i'); class WebGL2KernelValueSingleArray1DI extends WebGLKernelValueSingleArray1DI { updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueSingleArray1DI }; ================================================ FILE: src/backend/web-gl2/kernel-value/single-array2d-i.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray2DI } = require('../../web-gl/kernel-value/single-array2d-i'); class WebGL2KernelValueSingleArray2DI extends WebGLKernelValueSingleArray2DI { updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueSingleArray2DI }; ================================================ FILE: src/backend/web-gl2/kernel-value/single-array3d-i.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleArray3DI } = require('../../web-gl/kernel-value/single-array3d-i'); class WebGL2KernelValueSingleArray3DI extends WebGLKernelValueSingleArray3DI { updateValue(value) { if (value.constructor !== this.initialValueConstructor) { this.onUpdateValueMismatch(value.constructor); return; } const { context: gl } = this; utils.flattenTo(value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueSingleArray3DI }; ================================================ FILE: src/backend/web-gl2/kernel-value/single-input.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueSingleInput } = require('../../web-gl/kernel-value/single-input'); class WebGL2KernelValueSingleInput extends WebGLKernelValueSingleInput { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } updateValue(input) { const { context: gl } = this; utils.flattenTo(input.value, this.uploadValue); gl.activeTexture(this.contextHandle); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, this.textureSize[0], this.textureSize[1], 0, gl.RGBA, gl.FLOAT, this.uploadValue); this.kernel.setUniform1i(this.id, this.index); } } module.exports = { WebGL2KernelValueSingleInput }; ================================================ FILE: src/backend/web-gl2/kernel-value/unsigned-array.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueUnsignedArray } = require('../../web-gl/kernel-value/unsigned-array'); class WebGL2KernelValueUnsignedArray extends WebGLKernelValueUnsignedArray { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } } module.exports = { WebGL2KernelValueUnsignedArray }; ================================================ FILE: src/backend/web-gl2/kernel-value/unsigned-input.js ================================================ const { utils } = require('../../../utils'); const { WebGLKernelValueUnsignedInput } = require('../../web-gl/kernel-value/unsigned-input'); class WebGL2KernelValueUnsignedInput extends WebGLKernelValueUnsignedInput { getSource() { const variablePrecision = this.getVariablePrecisionString(); return utils.linesToString([ `uniform ${ variablePrecision } sampler2D ${this.id}`, `${ variablePrecision } ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`, `${ variablePrecision } ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`, ]); } } module.exports = { WebGL2KernelValueUnsignedInput }; ================================================ FILE: src/backend/web-gl2/kernel-value-maps.js ================================================ const { WebGL2KernelValueBoolean } = require('./kernel-value/boolean'); const { WebGL2KernelValueFloat } = require('./kernel-value/float'); const { WebGL2KernelValueInteger } = require('./kernel-value/integer'); const { WebGL2KernelValueHTMLImage } = require('./kernel-value/html-image'); const { WebGL2KernelValueDynamicHTMLImage } = require('./kernel-value/dynamic-html-image'); const { WebGL2KernelValueHTMLImageArray } = require('./kernel-value/html-image-array'); const { WebGL2KernelValueDynamicHTMLImageArray } = require('./kernel-value/dynamic-html-image-array'); const { WebGL2KernelValueHTMLVideo } = require('./kernel-value/html-video'); const { WebGL2KernelValueDynamicHTMLVideo } = require('./kernel-value/dynamic-html-video'); const { WebGL2KernelValueSingleInput } = require('./kernel-value/single-input'); const { WebGL2KernelValueDynamicSingleInput } = require('./kernel-value/dynamic-single-input'); const { WebGL2KernelValueUnsignedInput } = require('./kernel-value/unsigned-input'); const { WebGL2KernelValueDynamicUnsignedInput } = require('./kernel-value/dynamic-unsigned-input'); const { WebGL2KernelValueMemoryOptimizedNumberTexture } = require('./kernel-value/memory-optimized-number-texture'); const { WebGL2KernelValueDynamicMemoryOptimizedNumberTexture } = require('./kernel-value/dynamic-memory-optimized-number-texture'); const { WebGL2KernelValueNumberTexture } = require('./kernel-value/number-texture'); const { WebGL2KernelValueDynamicNumberTexture } = require('./kernel-value/dynamic-number-texture'); const { WebGL2KernelValueSingleArray } = require('./kernel-value/single-array'); const { WebGL2KernelValueDynamicSingleArray } = require('./kernel-value/dynamic-single-array'); const { WebGL2KernelValueSingleArray1DI } = require('./kernel-value/single-array1d-i'); const { WebGL2KernelValueDynamicSingleArray1DI } = require('./kernel-value/dynamic-single-array1d-i'); const { WebGL2KernelValueSingleArray2DI } = require('./kernel-value/single-array2d-i'); const { WebGL2KernelValueDynamicSingleArray2DI } = require('./kernel-value/dynamic-single-array2d-i'); const { WebGL2KernelValueSingleArray3DI } = require('./kernel-value/single-array3d-i'); const { WebGL2KernelValueDynamicSingleArray3DI } = require('./kernel-value/dynamic-single-array3d-i'); const { WebGL2KernelValueArray2 } = require('./kernel-value/array2'); const { WebGL2KernelValueArray3 } = require('./kernel-value/array3'); const { WebGL2KernelValueArray4 } = require('./kernel-value/array4'); const { WebGL2KernelValueUnsignedArray } = require('./kernel-value/unsigned-array'); const { WebGL2KernelValueDynamicUnsignedArray } = require('./kernel-value/dynamic-unsigned-array'); const kernelValueMaps = { unsigned: { dynamic: { 'Boolean': WebGL2KernelValueBoolean, 'Integer': WebGL2KernelValueInteger, 'Float': WebGL2KernelValueFloat, 'Array': WebGL2KernelValueDynamicUnsignedArray, 'Array(2)': WebGL2KernelValueArray2, 'Array(3)': WebGL2KernelValueArray3, 'Array(4)': WebGL2KernelValueArray4, 'Array1D(2)': false, 'Array1D(3)': false, 'Array1D(4)': false, 'Array2D(2)': false, 'Array2D(3)': false, 'Array2D(4)': false, 'Array3D(2)': false, 'Array3D(3)': false, 'Array3D(4)': false, 'Input': WebGL2KernelValueDynamicUnsignedInput, 'NumberTexture': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(1)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(2)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(3)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(4)': WebGL2KernelValueDynamicNumberTexture, 'MemoryOptimizedNumberTexture': WebGL2KernelValueDynamicMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGL2KernelValueDynamicHTMLImage, 'OffscreenCanvas': WebGL2KernelValueDynamicHTMLImage, 'HTMLImage': WebGL2KernelValueDynamicHTMLImage, 'ImageBitmap': WebGL2KernelValueDynamicHTMLImage, 'ImageData': WebGL2KernelValueDynamicHTMLImage, 'HTMLImageArray': WebGL2KernelValueDynamicHTMLImageArray, 'HTMLVideo': WebGL2KernelValueDynamicHTMLVideo, }, static: { 'Boolean': WebGL2KernelValueBoolean, 'Float': WebGL2KernelValueFloat, 'Integer': WebGL2KernelValueInteger, 'Array': WebGL2KernelValueUnsignedArray, 'Array(2)': WebGL2KernelValueArray2, 'Array(3)': WebGL2KernelValueArray3, 'Array(4)': WebGL2KernelValueArray4, 'Array1D(2)': false, 'Array1D(3)': false, 'Array1D(4)': false, 'Array2D(2)': false, 'Array2D(3)': false, 'Array2D(4)': false, 'Array3D(2)': false, 'Array3D(3)': false, 'Array3D(4)': false, 'Input': WebGL2KernelValueUnsignedInput, 'NumberTexture': WebGL2KernelValueNumberTexture, 'ArrayTexture(1)': WebGL2KernelValueNumberTexture, 'ArrayTexture(2)': WebGL2KernelValueNumberTexture, 'ArrayTexture(3)': WebGL2KernelValueNumberTexture, 'ArrayTexture(4)': WebGL2KernelValueNumberTexture, 'MemoryOptimizedNumberTexture': WebGL2KernelValueDynamicMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGL2KernelValueHTMLImage, 'OffscreenCanvas': WebGL2KernelValueHTMLImage, 'HTMLImage': WebGL2KernelValueHTMLImage, 'ImageBitmap': WebGL2KernelValueHTMLImage, 'ImageData': WebGL2KernelValueHTMLImage, 'HTMLImageArray': WebGL2KernelValueHTMLImageArray, 'HTMLVideo': WebGL2KernelValueHTMLVideo, } }, single: { dynamic: { 'Boolean': WebGL2KernelValueBoolean, 'Integer': WebGL2KernelValueInteger, 'Float': WebGL2KernelValueFloat, 'Array': WebGL2KernelValueDynamicSingleArray, 'Array(2)': WebGL2KernelValueArray2, 'Array(3)': WebGL2KernelValueArray3, 'Array(4)': WebGL2KernelValueArray4, 'Array1D(2)': WebGL2KernelValueDynamicSingleArray1DI, 'Array1D(3)': WebGL2KernelValueDynamicSingleArray1DI, 'Array1D(4)': WebGL2KernelValueDynamicSingleArray1DI, 'Array2D(2)': WebGL2KernelValueDynamicSingleArray2DI, 'Array2D(3)': WebGL2KernelValueDynamicSingleArray2DI, 'Array2D(4)': WebGL2KernelValueDynamicSingleArray2DI, 'Array3D(2)': WebGL2KernelValueDynamicSingleArray3DI, 'Array3D(3)': WebGL2KernelValueDynamicSingleArray3DI, 'Array3D(4)': WebGL2KernelValueDynamicSingleArray3DI, 'Input': WebGL2KernelValueDynamicSingleInput, 'NumberTexture': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(1)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(2)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(3)': WebGL2KernelValueDynamicNumberTexture, 'ArrayTexture(4)': WebGL2KernelValueDynamicNumberTexture, 'MemoryOptimizedNumberTexture': WebGL2KernelValueDynamicMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGL2KernelValueDynamicHTMLImage, 'OffscreenCanvas': WebGL2KernelValueDynamicHTMLImage, 'HTMLImage': WebGL2KernelValueDynamicHTMLImage, 'ImageBitmap': WebGL2KernelValueDynamicHTMLImage, 'ImageData': WebGL2KernelValueDynamicHTMLImage, 'HTMLImageArray': WebGL2KernelValueDynamicHTMLImageArray, 'HTMLVideo': WebGL2KernelValueDynamicHTMLVideo, }, static: { 'Boolean': WebGL2KernelValueBoolean, 'Float': WebGL2KernelValueFloat, 'Integer': WebGL2KernelValueInteger, 'Array': WebGL2KernelValueSingleArray, 'Array(2)': WebGL2KernelValueArray2, 'Array(3)': WebGL2KernelValueArray3, 'Array(4)': WebGL2KernelValueArray4, 'Array1D(2)': WebGL2KernelValueSingleArray1DI, 'Array1D(3)': WebGL2KernelValueSingleArray1DI, 'Array1D(4)': WebGL2KernelValueSingleArray1DI, 'Array2D(2)': WebGL2KernelValueSingleArray2DI, 'Array2D(3)': WebGL2KernelValueSingleArray2DI, 'Array2D(4)': WebGL2KernelValueSingleArray2DI, 'Array3D(2)': WebGL2KernelValueSingleArray3DI, 'Array3D(3)': WebGL2KernelValueSingleArray3DI, 'Array3D(4)': WebGL2KernelValueSingleArray3DI, 'Input': WebGL2KernelValueSingleInput, 'NumberTexture': WebGL2KernelValueNumberTexture, 'ArrayTexture(1)': WebGL2KernelValueNumberTexture, 'ArrayTexture(2)': WebGL2KernelValueNumberTexture, 'ArrayTexture(3)': WebGL2KernelValueNumberTexture, 'ArrayTexture(4)': WebGL2KernelValueNumberTexture, 'MemoryOptimizedNumberTexture': WebGL2KernelValueMemoryOptimizedNumberTexture, 'HTMLCanvas': WebGL2KernelValueHTMLImage, 'OffscreenCanvas': WebGL2KernelValueHTMLImage, 'HTMLImage': WebGL2KernelValueHTMLImage, 'ImageBitmap': WebGL2KernelValueHTMLImage, 'ImageData': WebGL2KernelValueHTMLImage, 'HTMLImageArray': WebGL2KernelValueHTMLImageArray, 'HTMLVideo': WebGL2KernelValueHTMLVideo, } }, }; function lookupKernelValueType(type, dynamic, precision, value) { if (!type) { throw new Error('type missing'); } if (!dynamic) { throw new Error('dynamic missing'); } if (!precision) { throw new Error('precision missing'); } if (value.type) { type = value.type; } const types = kernelValueMaps[precision][dynamic]; if (types[type] === false) { return null; } else if (types[type] === undefined) { throw new Error(`Could not find a KernelValue for ${ type }`); } return types[type]; } module.exports = { kernelValueMaps, lookupKernelValueType }; ================================================ FILE: src/backend/web-gl2/kernel.js ================================================ const { WebGLKernel } = require('../web-gl/kernel'); const { WebGL2FunctionNode } = require('./function-node'); const { FunctionBuilder } = require('../function-builder'); const { utils } = require('../../utils'); const { fragmentShader } = require('./fragment-shader'); const { vertexShader } = require('./vertex-shader'); const { lookupKernelValueType } = require('./kernel-value-maps'); let isSupported = null; /** * * @type {HTMLCanvasElement|OffscreenCanvas} */ let testCanvas = null; /** * * @type {WebGLRenderingContext} */ let testContext = null; let testExtensions = null; /** * * @type {IKernelFeatures} */ let features = null; /** * @extends WebGLKernel */ class WebGL2Kernel extends WebGLKernel { static get isSupported() { if (isSupported !== null) { return isSupported; } this.setupFeatureChecks(); isSupported = this.isContextMatch(testContext); return isSupported; } static setupFeatureChecks() { if (typeof document !== 'undefined') { testCanvas = document.createElement('canvas'); } else if (typeof OffscreenCanvas !== 'undefined') { testCanvas = new OffscreenCanvas(0, 0); } if (!testCanvas) return; testContext = testCanvas.getContext('webgl2'); if (!testContext || !testContext.getExtension) return; testExtensions = { EXT_color_buffer_float: testContext.getExtension('EXT_color_buffer_float'), OES_texture_float_linear: testContext.getExtension('OES_texture_float_linear'), }; features = this.getFeatures(); } static isContextMatch(context) { // from global if (typeof WebGL2RenderingContext !== 'undefined') { return context instanceof WebGL2RenderingContext; } return false; } /** * * @return {IKernelFeatures} */ static getFeatures() { const gl = this.testContext; return Object.freeze({ isFloatRead: this.getIsFloatRead(), isIntegerDivisionAccurate: this.getIsIntegerDivisionAccurate(), isSpeedTacticSupported: this.getIsSpeedTacticSupported(), kernelMap: true, isTextureFloat: true, isDrawBuffers: true, channelCount: this.getChannelCount(), maxTextureSize: this.getMaxTextureSize(), lowIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT), lowFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT), mediumIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT), mediumFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT), highIntPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT), highFloatPrecision: gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT), }); } static getIsTextureFloat() { return true; } static getChannelCount() { return testContext.getParameter(testContext.MAX_DRAW_BUFFERS); } static getMaxTextureSize() { return testContext.getParameter(testContext.MAX_TEXTURE_SIZE); } static lookupKernelValueType(type, dynamic, precision, value) { return lookupKernelValueType(type, dynamic, precision, value); } static get testCanvas() { return testCanvas; } static get testContext() { return testContext; } /** * * @returns {{isFloatRead: Boolean, isIntegerDivisionAccurate: Boolean, kernelMap: Boolean, isTextureFloat: Boolean}} */ static get features() { return features; } static get fragmentShader() { return fragmentShader; } static get vertexShader() { return vertexShader; } /** * * @return {WebGLRenderingContext|WebGL2RenderingContext} */ initContext() { const settings = { alpha: false, depth: false, antialias: false }; return this.canvas.getContext('webgl2', settings); } initExtensions() { this.extensions = { EXT_color_buffer_float: this.context.getExtension('EXT_color_buffer_float'), OES_texture_float_linear: this.context.getExtension('OES_texture_float_linear'), }; } /** * @desc Validate settings related to Kernel, such as dimensions size, and auto output support. * @param {IArguments} args */ validateSettings(args) { if (!this.validate) { this.texSize = utils.getKernelTextureSize({ optimizeFloatMemory: this.optimizeFloatMemory, precision: this.precision, }, this.output); return; } const { features } = this.constructor; if (this.precision === 'single' && !features.isFloatRead) { throw new Error('Float texture outputs are not supported'); } else if (!this.graphical && this.precision === null) { this.precision = features.isFloatRead ? 'single' : 'unsigned'; } if (this.fixIntegerDivisionAccuracy === null) { this.fixIntegerDivisionAccuracy = !features.isIntegerDivisionAccurate; } else if (this.fixIntegerDivisionAccuracy && features.isIntegerDivisionAccurate) { this.fixIntegerDivisionAccuracy = false; } this.checkOutput(); if (!this.output || this.output.length === 0) { if (args.length !== 1) { throw new Error('Auto output only supported for kernels with only one input'); } const argType = utils.getVariableType(args[0], this.strictIntegers); switch (argType) { case 'Array': this.output = utils.getDimensions(argType); break; case 'NumberTexture': case 'MemoryOptimizedNumberTexture': case 'ArrayTexture(1)': case 'ArrayTexture(2)': case 'ArrayTexture(3)': case 'ArrayTexture(4)': this.output = args[0].output; break; default: throw new Error('Auto output not supported for input type: ' + argType); } } if (this.graphical) { if (this.output.length !== 2) { throw new Error('Output must have 2 dimensions on graphical mode'); } if (this.precision === 'single') { console.warn('Cannot use graphical mode and single precision at the same time'); this.precision = 'unsigned'; } this.texSize = utils.clone(this.output); return; } else if (!this.graphical && this.precision === null && features.isTextureFloat) { this.precision = 'single'; } this.texSize = utils.getKernelTextureSize({ optimizeFloatMemory: this.optimizeFloatMemory, precision: this.precision, }, this.output); this.checkTextureSize(); } translateSource() { const functionBuilder = FunctionBuilder.fromKernel(this, WebGL2FunctionNode, { fixIntegerDivisionAccuracy: this.fixIntegerDivisionAccuracy }); this.translatedSource = functionBuilder.getPrototypeString('kernel'); this.setupReturnTypes(functionBuilder); } drawBuffers() { this.context.drawBuffers(this.drawBuffersMap); } getTextureFormat() { const { context: gl } = this; switch (this.getInternalFormat()) { case gl.R32F: return gl.RED; case gl.RG32F: return gl.RG; case gl.RGBA32F: return gl.RGBA; case gl.RGBA: return gl.RGBA; default: throw new Error('Unknown internal format'); } } getInternalFormat() { const { context: gl } = this; if (this.precision === 'single') { if (this.pipeline) { switch (this.returnType) { case 'Number': case 'Float': case 'Integer': if (this.optimizeFloatMemory) { return gl.RGBA32F; } else { return gl.R32F; } case 'Array(2)': return gl.RG32F; case 'Array(3)': // there is _no_ 3 channel format which is guaranteed to be color-renderable case 'Array(4)': return gl.RGBA32F; default: throw new Error('Unhandled return type'); } } return gl.RGBA32F; } return gl.RGBA; } _setupOutputTexture() { const gl = this.context; if (this.texture) { // here we inherit from an already existing kernel, so go ahead and just bind textures to the framebuffer gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); return; } gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); const texture = gl.createTexture(); const texSize = this.texSize; gl.activeTexture(gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); const format = this.getInternalFormat(); if (this.precision === 'single') { gl.texStorage2D(gl.TEXTURE_2D, 1, format, texSize[0], texSize[1]); } else { gl.texImage2D(gl.TEXTURE_2D, 0, format, texSize[0], texSize[1], 0, format, gl.UNSIGNED_BYTE, null); } gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); this.texture = new this.TextureConstructor({ texture, size: texSize, dimensions: this.threadDim, output: this.output, context: this.context, internalFormat: this.getInternalFormat(), textureFormat: this.getTextureFormat(), kernel: this, }); } _setupSubOutputTextures() { const gl = this.context; if (this.mappedTextures) { // here we inherit from an already existing kernel, so go ahead and just bind textures to the framebuffer for (let i = 0; i < this.subKernels.length; i++) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, this.mappedTextures[i].texture, 0); } return; } const texSize = this.texSize; this.drawBuffersMap = [gl.COLOR_ATTACHMENT0]; this.mappedTextures = []; for (let i = 0; i < this.subKernels.length; i++) { const texture = this.createTexture(); this.drawBuffersMap.push(gl.COLOR_ATTACHMENT0 + i + 1); gl.activeTexture(gl.TEXTURE0 + this.constantTextureCount + this.argumentTextureCount + i); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); // TODO: upgrade this const format = this.getInternalFormat(); if (this.precision === 'single') { gl.texStorage2D(gl.TEXTURE_2D, 1, format, texSize[0], texSize[1]); // gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, texSize[0], texSize[1], 0, gl.RGBA, gl.FLOAT, null); } else { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize[0], texSize[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, texture, 0); this.mappedTextures.push(new this.TextureConstructor({ texture, size: texSize, dimensions: this.threadDim, output: this.output, context: this.context, internalFormat: this.getInternalFormat(), textureFormat: this.getTextureFormat(), kernel: this, })); } } /** * * @desc Get the header string for the program. * This returns an empty string if no sub-kernels are defined. * * @returns {String} result */ _getHeaderString() { return ''; } /** * @desc Get texture coordinate string for the program * @returns {String} result */ _getTextureCoordinate() { const subKernels = this.subKernels; const variablePrecision = this.getVariablePrecisionString(this.texSize, this.tactic); if (subKernels === null || subKernels.length < 1) { return `in ${ variablePrecision } vec2 vTexCoord;\n`; } else { return `out ${ variablePrecision } vec2 vTexCoord;\n`; } } /** * @desc Generate transpiled glsl Strings for user-defined parameters sent to a kernel * @param {Array} args - The actual parameters sent to the Kernel * @returns {String} result */ _getMainArgumentsString(args) { const result = []; const argumentNames = this.argumentNames; for (let i = 0; i < argumentNames.length; i++) { result.push(this.kernelArguments[i].getSource(args[i])); } return result.join(''); } /** * @desc Get Kernel program string (in *glsl*) for a kernel. * @returns {String} result */ getKernelString() { const result = [this.getKernelResultDeclaration()]; const subKernels = this.subKernels; if (subKernels !== null) { result.push( 'layout(location = 0) out vec4 data0' ); switch (this.returnType) { case 'Number': case 'Float': case 'Integer': for (let i = 0; i < subKernels.length; i++) { const subKernel = subKernels[i]; result.push( subKernel.returnType === 'Integer' ? `int subKernelResult_${ subKernel.name } = 0` : `float subKernelResult_${ subKernel.name } = 0.0`, `layout(location = ${ i + 1 }) out vec4 data${ i + 1 }` ); } break; case 'Array(2)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec2 subKernelResult_${ subKernels[i].name }`, `layout(location = ${ i + 1 }) out vec4 data${ i + 1 }` ); } break; case 'Array(3)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec3 subKernelResult_${ subKernels[i].name }`, `layout(location = ${ i + 1 }) out vec4 data${ i + 1 }` ); } break; case 'Array(4)': for (let i = 0; i < subKernels.length; i++) { result.push( `vec4 subKernelResult_${ subKernels[i].name }`, `layout(location = ${ i + 1 }) out vec4 data${ i + 1 }` ); } break; } } else { result.push( 'out vec4 data0' ); } return utils.linesToString(result) + this.translatedSource; } getMainResultGraphical() { return utils.linesToString([ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' data0 = actualColor', ]); } getMainResultPackedPixels() { switch (this.returnType) { case 'LiteralInteger': case 'Number': case 'Integer': case 'Float': return this.getMainResultKernelPackedPixels() + this.getMainResultSubKernelPackedPixels(); default: throw new Error(`packed output only usable with Numbers, "${this.returnType}" specified`); } } /** * @return {String} */ getMainResultKernelPackedPixels() { return utils.linesToString([ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ` data0 = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(kernelResult)` ]); } /** * @return {String} */ getMainResultSubKernelPackedPixels() { const result = []; if (!this.subKernels) return ''; for (let i = 0; i < this.subKernels.length; i++) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` data${i + 1} = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(float(subKernelResult_${this.subKernels[i].name}))` ); } else { result.push( ` data${i + 1} = ${this.useLegacyEncoder ? 'legacyEncode32' : 'encode32'}(subKernelResult_${this.subKernels[i].name})` ); } } return utils.linesToString(result); } getMainResultKernelMemoryOptimizedFloats(result, channel) { result.push( ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ` data0.${channel} = kernelResult` ); } getMainResultSubKernelMemoryOptimizedFloats(result, channel) { if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; i++) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` data${i + 1}.${channel} = float(subKernelResult_${subKernel.name})` ); } else { result.push( ` data${i + 1}.${channel} = subKernelResult_${subKernel.name}` ); } } } getMainResultKernelNumberTexture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' data0[0] = kernelResult', ]; } getMainResultSubKernelNumberTexture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { const subKernel = this.subKernels[i]; if (subKernel.returnType === 'Integer') { result.push( ` data${i + 1}[0] = float(subKernelResult_${subKernel.name})` ); } else { result.push( ` data${i + 1}[0] = subKernelResult_${subKernel.name}` ); } } return result; } getMainResultKernelArray2Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' data0[0] = kernelResult[0]', ' data0[1] = kernelResult[1]', ]; } getMainResultSubKernelArray2Texture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { const subKernel = this.subKernels[i]; result.push( ` data${i + 1}[0] = subKernelResult_${subKernel.name}[0]`, ` data${i + 1}[1] = subKernelResult_${subKernel.name}[1]` ); } return result; } getMainResultKernelArray3Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' data0[0] = kernelResult[0]', ' data0[1] = kernelResult[1]', ' data0[2] = kernelResult[2]', ]; } getMainResultSubKernelArray3Texture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { const subKernel = this.subKernels[i]; result.push( ` data${i + 1}[0] = subKernelResult_${subKernel.name}[0]`, ` data${i + 1}[1] = subKernelResult_${subKernel.name}[1]`, ` data${i + 1}[2] = subKernelResult_${subKernel.name}[2]` ); } return result; } getMainResultKernelArray4Texture() { return [ ' threadId = indexTo3D(index, uOutputDim)', ' kernel()', ' data0 = kernelResult', ]; } getMainResultSubKernelArray4Texture() { const result = []; if (!this.subKernels) return result; for (let i = 0; i < this.subKernels.length; ++i) { result.push( ` data${i + 1} = subKernelResult_${this.subKernels[i].name}` ); } return result; } destroyExtensions() { this.extensions.EXT_color_buffer_float = null; this.extensions.OES_texture_float_linear = null; } /** * @return {IKernelJSON} */ toJSON() { const json = super.toJSON(); json.functionNodes = FunctionBuilder.fromKernel(this, WebGL2FunctionNode).toJSON(); json.settings.threadDim = this.threadDim; return json; } } module.exports = { WebGL2Kernel }; ================================================ FILE: src/backend/web-gl2/vertex-shader.js ================================================ // language=GLSL const vertexShader = `#version 300 es __FLOAT_TACTIC_DECLARATION__; __INT_TACTIC_DECLARATION__; __SAMPLER_2D_TACTIC_DECLARATION__; in vec2 aPos; in vec2 aTexCoord; out vec2 vTexCoord; uniform vec2 ratio; void main(void) { gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1); vTexCoord = aTexCoord; }`; module.exports = { vertexShader }; ================================================ FILE: src/browser-header.txt ================================================ /** * <%= pkg.name %> * <%= pkg.homepage %> * * <%= pkg.description %> * * @version <%= pkg.version %> * @date <%= new Date() %> * * @license <%= pkg.license %> * The MIT License * * Copyright (c) <%= new Date().getFullYear() %> gpu.js Team */ ================================================ FILE: src/browser.js ================================================ const lib = require('./index'); const GPU = lib.GPU; for (const p in lib) { if (!lib.hasOwnProperty(p)) continue; if (p === 'GPU') continue; //prevent recursive reference GPU[p] = lib[p]; } if (typeof window !== 'undefined') { bindTo(window); } if (typeof self !== 'undefined') { bindTo(self); } function bindTo(target) { if (target.GPU) return; Object.defineProperty(target, 'GPU', { get() { return GPU; } }); } module.exports = lib; ================================================ FILE: src/gpu.js ================================================ const { gpuMock } = require('gpu-mock.js'); const { utils } = require('./utils'); const { Kernel } = require('./backend/kernel'); const { CPUKernel } = require('./backend/cpu/kernel'); const { HeadlessGLKernel } = require('./backend/headless-gl/kernel'); const { WebGL2Kernel } = require('./backend/web-gl2/kernel'); const { WebGLKernel } = require('./backend/web-gl/kernel'); const { kernelRunShortcut } = require('./kernel-run-shortcut'); /** * * @type {Array.} */ const kernelOrder = [HeadlessGLKernel, WebGL2Kernel, WebGLKernel]; /** * * @type {string[]} */ const kernelTypes = ['gpu', 'cpu']; const internalKernels = { 'headlessgl': HeadlessGLKernel, 'webgl2': WebGL2Kernel, 'webgl': WebGLKernel, }; let validate = true; /** * The GPU.js library class which manages the GPU context for the creating kernels * @class * @return {GPU} */ class GPU { static disableValidation() { validate = false; } static enableValidation() { validate = true; } static get isGPUSupported() { return kernelOrder.some(Kernel => Kernel.isSupported); } /** * * @returns {boolean} */ static get isKernelMapSupported() { return kernelOrder.some(Kernel => Kernel.isSupported && Kernel.features.kernelMap); } /** * @desc TRUE is platform supports OffscreenCanvas */ static get isOffscreenCanvasSupported() { return (typeof Worker !== 'undefined' && typeof OffscreenCanvas !== 'undefined') || typeof importScripts !== 'undefined'; } /** * @desc TRUE if platform supports WebGL */ static get isWebGLSupported() { return WebGLKernel.isSupported; } /** * @desc TRUE if platform supports WebGL2 */ static get isWebGL2Supported() { return WebGL2Kernel.isSupported; } /** * @desc TRUE if platform supports HeadlessGL */ static get isHeadlessGLSupported() { return HeadlessGLKernel.isSupported; } /** * * @desc TRUE if platform supports Canvas */ static get isCanvasSupported() { return typeof HTMLCanvasElement !== 'undefined'; } /** * @desc TRUE if platform supports HTMLImageArray} */ static get isGPUHTMLImageArraySupported() { return WebGL2Kernel.isSupported; } /** * @desc TRUE if platform supports single precision} * @returns {boolean} */ static get isSinglePrecisionSupported() { return kernelOrder.some(Kernel => Kernel.isSupported && Kernel.features.isFloatRead && Kernel.features.isTextureFloat); } /** * Creates an instance of GPU. * @param {IGPUSettings} [settings] - Settings to set mode, and other properties * @constructor */ constructor(settings) { settings = settings || {}; this.canvas = settings.canvas || null; this.context = settings.context || null; this.mode = settings.mode; this.Kernel = null; this.kernels = []; this.functions = []; this.nativeFunctions = []; this.injectedNative = null; if (this.mode === 'dev') return; this.chooseKernel(); // add functions from settings if (settings.functions) { for (let i = 0; i < settings.functions.length; i++) { this.addFunction(settings.functions[i]); } } // add native functions from settings if (settings.nativeFunctions) { for (const p in settings.nativeFunctions) { if (!settings.nativeFunctions.hasOwnProperty(p)) continue; const s = settings.nativeFunctions[p]; const { name, source } = s; this.addNativeFunction(name, source, s); } } } /** * Choose kernel type and save on .Kernel property of GPU */ chooseKernel() { if (this.Kernel) return; /** * * @type {WebGLKernel|WebGL2Kernel|HeadlessGLKernel|CPUKernel} */ let Kernel = null; if (this.context) { for (let i = 0; i < kernelOrder.length; i++) { const ExternalKernel = kernelOrder[i]; if (ExternalKernel.isContextMatch(this.context)) { if (!ExternalKernel.isSupported) { throw new Error(`Kernel type ${ExternalKernel.name} not supported`); } Kernel = ExternalKernel; break; } } if (Kernel === null) { throw new Error('unknown Context'); } } else if (this.mode) { if (this.mode in internalKernels) { if (!validate || internalKernels[this.mode].isSupported) { Kernel = internalKernels[this.mode]; } } else if (this.mode === 'gpu') { for (let i = 0; i < kernelOrder.length; i++) { if (kernelOrder[i].isSupported) { Kernel = kernelOrder[i]; break; } } } else if (this.mode === 'cpu') { Kernel = CPUKernel; } if (!Kernel) { throw new Error(`A requested mode of "${this.mode}" and is not supported`); } } else { for (let i = 0; i < kernelOrder.length; i++) { if (kernelOrder[i].isSupported) { Kernel = kernelOrder[i]; break; } } if (!Kernel) { Kernel = CPUKernel; } } if (!this.mode) { this.mode = Kernel.mode; } this.Kernel = Kernel; } /** * @desc This creates a callable function object to call the kernel function with the argument parameter set * @param {Function|String|object} source - The calling to perform the conversion * @param {IGPUKernelSettings} [settings] - The parameter configuration object * @return {IKernelRunShortcut} callable function to run */ createKernel(source, settings) { if (typeof source === 'undefined') { throw new Error('Missing source parameter'); } if (typeof source !== 'object' && !utils.isFunction(source) && typeof source !== 'string') { throw new Error('source parameter not a function'); } const kernels = this.kernels; if (this.mode === 'dev') { const devKernel = gpuMock(source, upgradeDeprecatedCreateKernelSettings(settings)); kernels.push(devKernel); return devKernel; } source = typeof source === 'function' ? source.toString() : source; const switchableKernels = {}; const settingsCopy = upgradeDeprecatedCreateKernelSettings(settings) || {}; // handle conversion of argumentTypes if (settings && typeof settings.argumentTypes === 'object') { settingsCopy.argumentTypes = Object.keys(settings.argumentTypes).map(argumentName => settings.argumentTypes[argumentName]); } function onRequestFallback(args) { console.warn('Falling back to CPU'); const fallbackKernel = new CPUKernel(source, { argumentTypes: kernelRun.argumentTypes, constantTypes: kernelRun.constantTypes, graphical: kernelRun.graphical, loopMaxIterations: kernelRun.loopMaxIterations, constants: kernelRun.constants, dynamicOutput: kernelRun.dynamicOutput, dynamicArgument: kernelRun.dynamicArguments, output: kernelRun.output, precision: kernelRun.precision, pipeline: kernelRun.pipeline, immutable: kernelRun.immutable, optimizeFloatMemory: kernelRun.optimizeFloatMemory, fixIntegerDivisionAccuracy: kernelRun.fixIntegerDivisionAccuracy, functions: kernelRun.functions, nativeFunctions: kernelRun.nativeFunctions, injectedNative: kernelRun.injectedNative, subKernels: kernelRun.subKernels, strictIntegers: kernelRun.strictIntegers, debug: kernelRun.debug, }); fallbackKernel.build.apply(fallbackKernel, args); const result = fallbackKernel.run.apply(fallbackKernel, args); kernelRun.replaceKernel(fallbackKernel); return result; } /** * * @param {IReason[]} reasons * @param {IArguments} args * @param {Kernel} _kernel * @returns {*} */ function onRequestSwitchKernel(reasons, args, _kernel) { if (_kernel.debug) { console.warn('Switching kernels'); } let newOutput = null; if (_kernel.signature && !switchableKernels[_kernel.signature]) { switchableKernels[_kernel.signature] = _kernel; } if (_kernel.dynamicOutput) { for (let i = reasons.length - 1; i >= 0; i--) { const reason = reasons[i]; if (reason.type === 'outputPrecisionMismatch') { newOutput = reason.needed; } } } const Constructor = _kernel.constructor; const argumentTypes = Constructor.getArgumentTypes(_kernel, args); const signature = Constructor.getSignature(_kernel, argumentTypes); const existingKernel = switchableKernels[signature]; if (existingKernel) { existingKernel.onActivate(_kernel); return existingKernel; } const newKernel = switchableKernels[signature] = new Constructor(source, { argumentTypes, constantTypes: _kernel.constantTypes, graphical: _kernel.graphical, loopMaxIterations: _kernel.loopMaxIterations, constants: _kernel.constants, dynamicOutput: _kernel.dynamicOutput, dynamicArgument: _kernel.dynamicArguments, context: _kernel.context, canvas: _kernel.canvas, output: newOutput || _kernel.output, precision: _kernel.precision, pipeline: _kernel.pipeline, immutable: _kernel.immutable, optimizeFloatMemory: _kernel.optimizeFloatMemory, fixIntegerDivisionAccuracy: _kernel.fixIntegerDivisionAccuracy, functions: _kernel.functions, nativeFunctions: _kernel.nativeFunctions, injectedNative: _kernel.injectedNative, subKernels: _kernel.subKernels, strictIntegers: _kernel.strictIntegers, debug: _kernel.debug, gpu: _kernel.gpu, validate, returnType: _kernel.returnType, tactic: _kernel.tactic, onRequestFallback, onRequestSwitchKernel, texture: _kernel.texture, mappedTextures: _kernel.mappedTextures, drawBuffersMap: _kernel.drawBuffersMap, }); newKernel.build.apply(newKernel, args); kernelRun.replaceKernel(newKernel); kernels.push(newKernel); return newKernel; } const mergedSettings = Object.assign({ context: this.context, canvas: this.canvas, functions: this.functions, nativeFunctions: this.nativeFunctions, injectedNative: this.injectedNative, gpu: this, validate, onRequestFallback, onRequestSwitchKernel }, settingsCopy); const kernel = new this.Kernel(source, mergedSettings); const kernelRun = kernelRunShortcut(kernel); //if canvas didn't come from this, propagate from kernel if (!this.canvas) { this.canvas = kernel.canvas; } //if context didn't come from this, propagate from kernel if (!this.context) { this.context = kernel.context; } kernels.push(kernel); return kernelRun; } /** * * Create a super kernel which executes sub kernels * and saves their output to be used with the next sub kernel. * This can be useful if we want to save the output on one kernel, * and then use it as an input to another kernel. *Machine Learning* * * @param {Object|Array} subKernels - Sub kernels for this kernel * @param {Function} rootKernel - Root kernel * * @returns {Function} callable kernel function * * @example * const megaKernel = gpu.createKernelMap({ * addResult: function add(a, b) { * return a[this.thread.x] + b[this.thread.x]; * }, * multiplyResult: function multiply(a, b) { * return a[this.thread.x] * b[this.thread.x]; * }, * }, function(a, b, c) { * return multiply(add(a, b), c); * }); * * megaKernel(a, b, c); * * Note: You can also define subKernels as an array of functions. * > [add, multiply] * */ createKernelMap() { let fn; let settings; const argument2Type = typeof arguments[arguments.length - 2]; if (argument2Type === 'function' || argument2Type === 'string') { fn = arguments[arguments.length - 2]; settings = arguments[arguments.length - 1]; } else { fn = arguments[arguments.length - 1]; } if (this.mode !== 'dev') { if (!this.Kernel.isSupported || !this.Kernel.features.kernelMap) { if (this.mode && kernelTypes.indexOf(this.mode) < 0) { throw new Error(`kernelMap not supported on ${this.Kernel.name}`); } } } const settingsCopy = upgradeDeprecatedCreateKernelSettings(settings); // handle conversion of argumentTypes if (settings && typeof settings.argumentTypes === 'object') { settingsCopy.argumentTypes = Object.keys(settings.argumentTypes).map(argumentName => settings.argumentTypes[argumentName]); } if (Array.isArray(arguments[0])) { settingsCopy.subKernels = []; const functions = arguments[0]; for (let i = 0; i < functions.length; i++) { const source = functions[i].toString(); const name = utils.getFunctionNameFromString(source); settingsCopy.subKernels.push({ name, source, property: i, }); } } else { settingsCopy.subKernels = []; const functions = arguments[0]; for (let p in functions) { if (!functions.hasOwnProperty(p)) continue; const source = functions[p].toString(); const name = utils.getFunctionNameFromString(source); settingsCopy.subKernels.push({ name: name || p, source, property: p, }); } } return this.createKernel(fn, settingsCopy); } /** * * Combine different kernels into one super Kernel, * useful to perform multiple operations inside one * kernel without the penalty of data transfer between * cpu and gpu. * * The number of kernel functions sent to this method can be variable. * You can send in one, two, etc. * * @param {Function} subKernels - Kernel function(s) to combine. * @param {Function} rootKernel - Root kernel to combine kernels into * * @example * combineKernels(add, multiply, function(a,b,c){ * return add(multiply(a,b), c) * }) * * @returns {Function} Callable kernel function * */ combineKernels() { const firstKernel = arguments[0]; const combinedKernel = arguments[arguments.length - 1]; if (firstKernel.kernel.constructor.mode === 'cpu') return combinedKernel; const canvas = arguments[0].canvas; const context = arguments[0].context; const max = arguments.length - 1; for (let i = 0; i < max; i++) { arguments[i] .setCanvas(canvas) .setContext(context) .setPipeline(true); } return function() { const texture = combinedKernel.apply(this, arguments); if (texture.toArray) { return texture.toArray(); } return texture; }; } setFunctions(functions) { this.functions = functions; return this; } setNativeFunctions(nativeFunctions) { this.nativeFunctions = nativeFunctions; return this; } /** * @desc Adds additional functions, that the kernel may call. * @param {Function|String} source - Javascript function to convert * @param {IFunctionSettings} [settings] * @returns {GPU} returns itself */ addFunction(source, settings) { this.functions.push({ source, settings }); return this; } /** * @desc Adds additional native functions, that the kernel may call. * @param {String} name - native function name, used for reverse lookup * @param {String} source - the native function implementation, as it would be defined in it's entirety * @param {object} [settings] * @returns {GPU} returns itself */ addNativeFunction(name, source, settings) { if (this.kernels.length > 0) { throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.'); } this.nativeFunctions.push(Object.assign({ name, source }, settings)); return this; } /** * Inject a string just before translated kernel functions * @param {String} source * @return {GPU} */ injectNative(source) { this.injectedNative = source; return this; } /** * @desc Destroys all memory associated with gpu.js & the webGl if we created it * @return {Promise} * @resolve {void} * @reject {Error} */ destroy() { return new Promise((resolve, reject) => { if (!this.kernels) { resolve(); } // perform on next run loop - for some reason we dont get lose context events // if webGl is created and destroyed in the same run loop. setTimeout(() => { try { for (let i = 0; i < this.kernels.length; i++) { this.kernels[i].destroy(true); // remove canvas if exists } // all kernels are associated with one context, go ahead and take care of it here let firstKernel = this.kernels[0]; if (firstKernel) { // if it is shortcut if (firstKernel.kernel) { firstKernel = firstKernel.kernel; } if (firstKernel.constructor.destroyContext) { firstKernel.constructor.destroyContext(this.context); } } } catch (e) { reject(e); } resolve(); }, 0); }); } } function upgradeDeprecatedCreateKernelSettings(settings) { if (!settings) { return {}; } const upgradedSettings = Object.assign({}, settings); if (settings.hasOwnProperty('floatOutput')) { utils.warnDeprecated('setting', 'floatOutput', 'precision'); upgradedSettings.precision = settings.floatOutput ? 'single' : 'unsigned'; } if (settings.hasOwnProperty('outputToTexture')) { utils.warnDeprecated('setting', 'outputToTexture', 'pipeline'); upgradedSettings.pipeline = Boolean(settings.outputToTexture); } if (settings.hasOwnProperty('outputImmutable')) { utils.warnDeprecated('setting', 'outputImmutable', 'immutable'); upgradedSettings.immutable = Boolean(settings.outputImmutable); } if (settings.hasOwnProperty('floatTextures')) { utils.warnDeprecated('setting', 'floatTextures', 'optimizeFloatMemory'); upgradedSettings.optimizeFloatMemory = Boolean(settings.floatTextures); } return upgradedSettings; } module.exports = { GPU, kernelOrder, kernelTypes }; ================================================ FILE: src/index.d.ts ================================================ export class GPU { static isGPUSupported: boolean; static isCanvasSupported: boolean; static isHeadlessGLSupported: boolean; static isWebGLSupported: boolean; static isWebGL2Supported: boolean; static isKernelMapSupported: boolean; static isOffscreenCanvasSupported: boolean; static isGPUHTMLImageArraySupported: boolean; static isSinglePrecisionSupported: boolean; constructor(settings?: IGPUSettings); functions: GPUFunction[]; nativeFunctions: IGPUNativeFunction[]; setFunctions(flag: any): this; setNativeFunctions(flag: IGPUNativeFunction[]): this; addFunction(kernel: GPUFunction, settings?: IGPUFunctionSettings): this; addNativeFunction(name: string, source: string, settings?: IGPUFunctionSettings): this; combineKernels(...kernels: KernelFunction[]): IKernelRunShortcut; combineKernels(...kernels: KF[]): ((...args: Parameters) => ReturnType[] | ReturnType[][] | ReturnType[][][] | Texture | void ) & IKernelRunShortcutBase; createKernel(kernel: KernelFunction, settings?: IGPUKernelSettings): IKernelRunShortcut; createKernel(kernel: KernelType, settings?: IGPUKernelSettings): ((...args: Parameters) => ReturnType[] | ReturnType[][] | ReturnType[][][] | Texture | void ) & IKernelRunShortcutBase; createKernelMap< ArgTypes extends ThreadKernelVariable[], ConstantsType = null, >( subKernels: ISubKernelObject, rootKernel: ThreadFunction, settings?: IGPUKernelSettings): (((this: IKernelFunctionThis, ...args: ArgTypes) => IMappedKernelResult) & IKernelMapRunShortcut); destroy(): Promise; Kernel: typeof Kernel; mode: string; canvas: any; context: any; } export interface ISubKernelObject { [targetLocation: string]: ((...args: ThreadKernelVariable[]) => ThreadFunctionResult) | ((...args: any[]) => ThreadFunctionResult); } export interface ISubKernelArray { [index: number]: ((...args: ThreadKernelVariable[]) => ThreadFunctionResult) | ((...args: any[]) => ThreadFunctionResult); } export interface ISubKernelsResults { [resultsLocation: string]: KernelOutput; } export interface IGPUFunction extends IFunctionSettings { source: string; } export interface IGPUNativeFunction extends IGPUFunctionSettings { name: string; source: string; } export interface IMappedKernelResult { result?: KernelVariable; [targetLocation: string]: KernelVariable } export interface INativeFunction extends IGPUFunctionSettings { name: string; source: string; } export interface IInternalNativeFunction extends IArgumentTypes { name: string; source: string; } export interface INativeFunctionList { [name: string]: INativeFunction } export type GPUMode = 'gpu' | 'cpu' | 'dev'; export type GPUInternalMode = 'webgl' | 'webgl2' | 'headlessgl'; export interface IGPUSettings { mode?: GPUMode | GPUInternalMode; canvas?: object; context?: object; functions?: KernelFunction[]; nativeFunctions?: IInternalNativeFunction[]; // format: 'Float32Array' | 'Float16Array' | 'Float' // WE WANT THIS! } export type GPUVariableType = 'Array' | 'Array(2)' | 'Array(3)' | 'Array(4)' | 'Array1D(2)' | 'Array2D(2)' | 'Array3D(2)' | 'Array1D(3)' | 'Array2D(3)' | 'Array3D(3)' | 'Array1D(4)' | 'Array2D(4)' | 'Array3D(4)' | 'Boolean' | 'HTMLCanvas' | 'HTMLImage' | 'HTMLImageArray' | 'Number' | 'Float' | 'Integer' | GPUTextureType; export type GPUTextureType = 'NumberTexture' | 'ArrayTexture(4)'; export interface IGPUArgumentTypes { [argumentName: string]: GPUVariableType; } export interface IGPUFunctionSettings { argumentTypes?: IGPUArgumentTypes | string[], returnType?: GPUVariableType; } export class Kernel { static isSupported: boolean; static isContextMatch(context: any): boolean; static disableValidation(): void; static enableValidation(): void; static nativeFunctionArguments(source: string): IArgumentTypes; static nativeFunctionReturnType(source: string): string; static destroyContext(context: any): void; static features: IKernelFeatures; static getFeatures(): IKernelFeatures; static mode: GPUMode | GPUInternalMode; source: string | IKernelJSON; Kernel: Kernel; output: number[]; debug: boolean; graphical: boolean; loopMaxIterations: number; constants: IConstants; canvas: any; context: WebGLRenderingContext | any; functions: IFunction[]; nativeFunctions: IInternalNativeFunction[]; subKernels: ISubKernel[]; validate: boolean; immutable: boolean; pipeline: boolean; plugins: IPlugin[]; useLegacyEncoder: boolean; tactic: Tactic; built: boolean; texSize: [number, number]; texture: Texture; mappedTextures?: Texture[]; TextureConstructor: typeof Texture; getPixels(flip?: boolean): Uint8ClampedArray[]; getVariablePrecisionString(textureSize?: number[], tactic?: Tactic, isInt?: boolean): string; prependString(value: string): void; hasPrependString(value: string): boolean; constructor(kernel: KernelFunction|IKernelJSON|string, settings?: IDirectKernelSettings); onRequestSwitchKernel?: Kernel; onActivate(previousKernel: Kernel): void; build(...args: KernelVariable[]): void; run(...args: KernelVariable[]): KernelVariable; toString(...args: KernelVariable[]): string; toJSON(): IKernelJSON; setOutput(flag: number[]): this; setWarnVarUsage(flag: boolean): this; setOptimizeFloatMemory(flag: boolean): this; setArgumentTypes(flag: IKernelValueTypes): this; setDebug(flag: boolean): this; setGraphical(flag: boolean): this; setLoopMaxIterations(flag: number): this; setConstants(flag: IConstants): this; setConstants(flag: T & IConstants): this; setConstantTypes(flag: IKernelValueTypes): this; setDynamicOutput(flag: boolean): this; setDynamicArguments(flag: boolean): this; setPipeline(flag: boolean): this; setPrecision(flag: Precision): this; setImmutable(flag: boolean): this; setCanvas(flag: any): this; setContext(flag: any): this; addFunction(flag: GPUFunction, settings?: IFunctionSettings): this; setFunctions(flag: any): this; setNativeFunctions(flag: IGPUNativeFunction[]): this; setStrictIntegers(flag: boolean): this; setTactic(flag: Tactic): this; setUseLegacyEncoder(flag: boolean): this; addSubKernel(subKernel: ISubKernel): this; destroy(removeCanvasReferences?: boolean): void; validateSettings(args: IArguments): void; setUniform1f(name: string, value: number): void; setUniform2f(name: string, value1: number, value2: number): void; setUniform3f(name: string, value1: number, value2: number, value3: number): void; setUniform4f(name: string, value1: number, value2: number, value3: number, value4: number): void; setUniform2fv(name: string, value: [number, number]): void; setUniform3fv(name: string, value: [number, number, number]): void; setUniform4fv(name: string, value: [number, number, number, number]): void; setUniform1i(name: string, value: number): void; setUniform2i(name: string, value1: number, value2: number): void; setUniform3i(name: string, value1: number, value2: number, value3: number): void; setUniform4i(name: string, value1: number, value2: number, value3: number, value4: number): void; setUniform2iv(name: string, value: [number, number]): void; setUniform3iv(name: string, value: [number, number, number]): void; setUniform4iv(name: string, value: [number, number, number, number]): void; } export type GPUFunction = ThreadFunction | IFunction | IGPUFunction | string[]; export type ThreadFunction = ((this: IKernelFunctionThis, ...args: ArgTypes) => ThreadFunctionResult); export type Precision = 'single' | 'unsigned'; export class CPUKernel extends Kernel { } export class GLKernel extends Kernel { } export class WebGLKernel extends GLKernel { } export class WebGL2Kernel extends WebGLKernel { } export class HeadlessGLKernel extends WebGLKernel { } export interface IArgumentTypes { argumentTypes: GPUVariableType[], argumentNames: string[], } export interface IConstants { [constantName: string]: KernelVariable; } export interface IKernelValueTypes { [constantType: string]: GPUVariableType; } export interface IWebGLKernelValueSettings extends IKernelValueSettings { onRequestTexture: () => object; onRequestIndex: () => number; onRequestContextHandle: () => number; texture: any; } export interface IKernelValueSettings { name: string; kernel: Kernel; context: WebGLRenderingContext; contextHandle?: number; checkContext?: boolean; onRequestContextHandle: () => number; onUpdateValueMismatch: (constructor: object) => void; origin: 'user' | 'constants'; strictIntegers?: boolean; type: GPUVariableType; tactic?: Tactic; size: number[]; index?: number; } export type Tactic = 'speed' | 'balanced' | 'precision'; export interface IConstantsThis { [constantName: string]: ThreadKernelVariable; } export interface IKernelXYZ { x: number; y: number; z: number; } export interface FunctionList { [functionName: string]: Function } export interface IGPUKernelSettings extends IKernelSettings { argumentTypes?: ITypesList; functions?: Function[]|FunctionList; tactic?: Tactic; onRequestSwitchKernel?: Kernel; } export interface IKernelSettings { pluginNames?: string[]; output?: number[] | IKernelXYZ; precision?: Precision; constants?: object; context?: any; canvas?: any; pipeline?: boolean; immutable?: boolean; graphical?: boolean; onRequestFallback?: () => Kernel; optimizeFloatMemory?: boolean; dynamicOutput?: boolean; dynamicArguments?: boolean; constantTypes?: ITypesList; useLegacyEncoder?: boolean; nativeFunctions?: IGPUNativeFunction[], strictIntegers?: boolean; } export interface IDirectKernelSettings extends IKernelSettings { argumentTypes?: string[]; functions?: string[]|IFunction; } export interface ITypesList { [typeName: string]: GPUVariableType } export interface IKernelRunShortcutBase extends Kernel { kernel: Kernel; (...args: KernelVariable[]): T; exec(): Promise; } export interface IKernelRunShortcut extends IKernelRunShortcutBase { } export interface IKernelMapRunShortcut extends IKernelRunShortcutBase< { result: KernelOutput } & { [key in keyof SubKernelType]: KernelOutput }> {} export interface IKernelFeatures { isFloatRead: boolean; kernelMap: boolean; isIntegerDivisionAccurate: boolean; isSpeedTacticSupported: boolean; isTextureFloat: boolean; isDrawBuffers: boolean; channelCount: number; maxTextureSize: number; lowIntPrecision: { rangeMax: number }; mediumIntPrecision: { rangeMax: number }; highIntPrecision: { rangeMax: number }; lowFloatPrecision: { rangeMax: number }; mediumFloatPrecision: { rangeMax: number }; highFloatPrecision: { rangeMax: number }; } export interface IKernelFunctionThis { output: IKernelXYZ; thread: IKernelXYZ; constants: ConstantsT; color(r: number): void, color(r: number, g: number): void, color(r: number, g: number, b: number): void, color(r: number, g: number, b: number, a: number): void, } export type KernelVariable = boolean | number | Texture | Input | HTMLCanvasElement | OffscreenCanvas | HTMLVideoElement | HTMLImageElement | HTMLImageElement[] | ImageBitmap | ImageData | Float32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | KernelOutput; export type ThreadFunctionResult = number | number[] | number[][] | [number, number] | [number, number, number] | [number, number, number, number] | Pixel | Boolean; export type ThreadKernelVariable = boolean | number | number[] | number[][] | number[][][] | Float32Array | Float32Array[] | Float32Array[][] | Pixel | Pixel[][] | [number, number] | [number, number][] | [number, number][][] | [number, number][][][] | [number, number, number] | [number, number, number][] | [number, number, number][][] | [number, number, number][][][] | [number, number, number, number] | [number, number, number, number][] | [number, number, number, number][][] | [number, number, number, number][][][] ; export type Pixel = { r: number; g: number; b: number; a: number; }; // export type KernelFunction = (( // this: IKernelFunctionThis, // ...args: ArgT // ) => KernelOutput); export interface KernelFunction { ( this: IKernelFunctionThis, ...args: ArgT ): KernelOutput; } export type KernelOutput = void | number | number[] | number[][] | number[][][] | Float32Array | Float32Array[] | Float32Array[][] | [number, number][] | [number, number, number][] | [number, number, number, number][] | [number, number][][] | [number, number, number][][] | [number, number, number, number][][] | [number, number][][][] | [number, number, number][][][] | [number, number, number, number][][][] | Texture; export interface IFunction { source: string; settings: IFunctionSettings; } export interface IFunctionSettings { name?: string; debug?: boolean; argumentNames?: string[]; argumentTypes?: string[] | { [argumentName: string]: string }; argumentSizes?: number[]; constants?: IConstants; constantTypes?: IKernelValueTypes; output?: number[]; loopMaxIterations?: number; returnType?: string; isRootKernel?: boolean; isSubKernel?: boolean; onNestedFunction?(ast: any, source: string): void; lookupReturnType?(functionName: string, ast: any, node: FunctionNode): void; plugins?: any[]; useLegacyEncoder?: boolean; ast?: any; } export interface ISubKernel { name: string; source: string; property: string | number; returnType: string; } export class FunctionBuilder { static fromKernel(kernel: Kernel, FunctionNode: FunctionNode, extraNodeOptions?: any): FunctionBuilder; constructor(settings: IFunctionBuilderSettings); addFunctionNode(functionNode: FunctionNode): void; traceFunctionCalls(functionName: string, retList?: string[]): string[]; getStringFromFunctionNames(functionName: string[]): string; getPrototypesFromFunctionNames(functionName: string[]): string[]; getString(functionName: string): string; getPrototypeString(functionName: string): string; } export interface IFunctionBuilderSettings { kernel: Kernel; rootNode: FunctionNode; functionNodes?: FunctionNode[]; nativeFunctions?: INativeFunctionList; subKernelNodes?: FunctionNode[]; } // These are mostly internal export class FunctionNode implements IFunctionSettings { constructor(source: string, settings?: IFunctionNodeSettings); } export interface IFunctionNodeSettings extends IFunctionSettings { argumentTypes: string[] } export class WebGLFunctionNode extends FunctionNode {} export class WebGL2FunctionNode extends WebGLFunctionNode {} export class CPUFunctionNode extends FunctionNode {} export interface IGPUTextureSettings { texture: WebGLTexture; size: number[]; dimensions: number[]; output: number[]; context: WebGLRenderingContext; kernel: Kernel; gpu?: GPU; type?: GPUTextureType; } export class Texture { constructor(settings: IGPUTextureSettings) toArray(): TextureArrayOutput; clone(): Texture; delete(): void; clear(): void; kernel: Kernel; } export type TextureArrayOutput = number[] | number[][] | number[][][] | Float32Array | Float32Array[] | Float32Array[][] | [number, number][] | [number, number][][] | [number, number][][][] | [number, number, number][] | [number, number, number][][] | [number, number, number][][][] | [number, number, number, number][] | [number, number, number, number][][] | [number, number, number, number][][][] ; export interface IPlugin { source: string; name: string; functionMatch: string; functionReplace: string; functionReturnType: GPUVariableType; onBeforeRun: (kernel: Kernel) => void; } export type OutputDimensions = [number] | [number, number] | [number, number, number] | Int32Array; export type TextureDimensions = [number, number]; export class Input { value: number[]; size: number[]; constructor(value: number[], size: OutputDimensions); } export type input = (value: number[], size: OutputDimensions) => Input; export function alias(name: string, source: T): T; export class KernelValue { constructor(value: KernelVariable, settings: IKernelValueSettings); getSource(): string; setup(): void; updateValue(value: KernelVariable): void; } export class WebGLKernelValue { constructor(value: any, settings: IWebGLKernelValueSettings); } export interface IFunctionNodeMemberExpressionDetails { xProperty: object; yProperty: object; zProperty: object; property: string; type: string; origin: 'user' | 'constants'; signature: string; } export interface IKernelJSON { settings: IJSONSettings; functionNodes?: object; } export interface IJSONSettings { output: number[]; argumentsTypes: GPUVariableType; returnType: string; argumentNames?: string[]; constants?: IConstants; pipeline?: boolean; pluginNames?: string[]; tactic?: Tactic; threadDim?: number[]; } export declare const utils: { getMinifySafeName: (arrowReference: () => T) => string } export interface IReason { type: 'argumentMismatch' | 'outputPrecisionMismatch'; needed: any; } export interface IDeclaration { ast: object; context: object; name: string; origin: 'declaration'; inForLoopInit: boolean; inForLoopTest: boolean; assignable: boolean; suggestedType: string; valueType: string; dependencies: any; isSafe: boolean; } ================================================ FILE: src/index.js ================================================ const { GPU } = require('./gpu'); const { alias } = require('./alias'); const { utils } = require('./utils'); const { Input, input } = require('./input'); const { Texture } = require('./texture'); const { FunctionBuilder } = require('./backend/function-builder'); const { FunctionNode } = require('./backend/function-node'); const { CPUFunctionNode } = require('./backend/cpu/function-node'); const { CPUKernel } = require('./backend/cpu/kernel'); const { HeadlessGLKernel } = require('./backend/headless-gl/kernel'); const { WebGLFunctionNode } = require('./backend/web-gl/function-node'); const { WebGLKernel } = require('./backend/web-gl/kernel'); const { kernelValueMaps: webGLKernelValueMaps } = require('./backend/web-gl/kernel-value-maps'); const { WebGL2FunctionNode } = require('./backend/web-gl2/function-node'); const { WebGL2Kernel } = require('./backend/web-gl2/kernel'); const { kernelValueMaps: webGL2KernelValueMaps } = require('./backend/web-gl2/kernel-value-maps'); const { GLKernel } = require('./backend/gl/kernel'); const { Kernel } = require('./backend/kernel'); const { FunctionTracer } = require('./backend/function-tracer'); const mathRandom = require('./plugins/math-random-uniformly-distributed'); module.exports = { alias, CPUFunctionNode, CPUKernel, GPU, FunctionBuilder, FunctionNode, HeadlessGLKernel, Input, input, Texture, utils, WebGL2FunctionNode, WebGL2Kernel, webGL2KernelValueMaps, WebGLFunctionNode, WebGLKernel, webGLKernelValueMaps, GLKernel, Kernel, FunctionTracer, plugins: { mathRandom } }; ================================================ FILE: src/input.js ================================================ class Input { constructor(value, size) { this.value = value; if (Array.isArray(size)) { this.size = size; } else { this.size = new Int32Array(3); if (size.z) { this.size = new Int32Array([size.x, size.y, size.z]); } else if (size.y) { this.size = new Int32Array([size.x, size.y]); } else { this.size = new Int32Array([size.x]); } } const [w, h, d] = this.size; if (d) { if (this.value.length !== (w * h * d)) { throw new Error(`Input size ${this.value.length} does not match ${w} * ${h} * ${d} = ${(h * w * d)}`); } } else if (h) { if (this.value.length !== (w * h)) { throw new Error(`Input size ${this.value.length} does not match ${w} * ${h} = ${(h * w)}`); } } else { if (this.value.length !== w) { throw new Error(`Input size ${this.value.length} does not match ${w}`); } } } toArray() { const { utils } = require('./utils'); const [w, h, d] = this.size; if (d) { return utils.erectMemoryOptimized3DFloat(this.value.subarray ? this.value : new Float32Array(this.value), w, h, d); } else if (h) { return utils.erectMemoryOptimized2DFloat(this.value.subarray ? this.value : new Float32Array(this.value), w, h); } else { return this.value; } } } function input(value, size) { return new Input(value, size); } module.exports = { Input, input }; ================================================ FILE: src/kernel-run-shortcut.js ================================================ const { utils } = require('./utils'); /** * Makes kernels easier for mortals (including me) * @param kernel * @returns {function()} */ function kernelRunShortcut(kernel) { let run = function() { kernel.build.apply(kernel, arguments); run = function() { let result = kernel.run.apply(kernel, arguments); if (kernel.switchingKernels) { const reasons = kernel.resetSwitchingKernels(); const newKernel = kernel.onRequestSwitchKernel(reasons, arguments, kernel); shortcut.kernel = kernel = newKernel; result = newKernel.run.apply(newKernel, arguments); } if (kernel.renderKernels) { return kernel.renderKernels(); } else if (kernel.renderOutput) { return kernel.renderOutput(); } else { return result; } }; return run.apply(kernel, arguments); }; const shortcut = function() { return run.apply(kernel, arguments); }; /** * Run kernel in async mode * @returns {Promise} */ shortcut.exec = function() { return new Promise((accept, reject) => { try { accept(run.apply(this, arguments)); } catch (e) { reject(e); } }); }; shortcut.replaceKernel = function(replacementKernel) { kernel = replacementKernel; bindKernelToShortcut(kernel, shortcut); }; bindKernelToShortcut(kernel, shortcut); return shortcut; } function bindKernelToShortcut(kernel, shortcut) { if (shortcut.kernel) { shortcut.kernel = kernel; return; } const properties = utils.allPropertiesOf(kernel); for (let i = 0; i < properties.length; i++) { const property = properties[i]; if (property[0] === '_' && property[1] === '_') continue; if (typeof kernel[property] === 'function') { if (property.substring(0, 3) === 'add' || property.substring(0, 3) === 'set') { shortcut[property] = function() { shortcut.kernel[property].apply(shortcut.kernel, arguments); return shortcut; }; } else { shortcut[property] = function() { return shortcut.kernel[property].apply(shortcut.kernel, arguments); }; } } else { shortcut.__defineGetter__(property, () => shortcut.kernel[property]); shortcut.__defineSetter__(property, (value) => { shortcut.kernel[property] = value; }); } } shortcut.kernel = kernel; } module.exports = { kernelRunShortcut }; ================================================ FILE: src/plugins/math-random-triangle-noise.js ================================================ const source = ` uniform highp float triangle_noise_seed; highp float triangle_noise_shift = 0.000001; //https://www.shadertoy.com/view/4t2SDh //note: uniformly distributed, normalized rand, [0;1[ float nrand( vec2 n ) { return fract(sin(dot(n.xy, vec2(12.9898, 78.233)))* 43758.5453); } //note: remaps v to [0;1] in interval [a;b] float remap( float a, float b, float v ) { return clamp( (v-a) / (b-a), 0.0, 1.0 ); } float n4rand( vec2 n ) { float t = fract( triangle_noise_seed + triangle_noise_shift ); float nrnd0 = nrand( n + 0.07*t ); float nrnd1 = nrand( n + 0.11*t ); float nrnd2 = nrand( n + 0.13*t ); float nrnd3 = nrand( n + 0.17*t ); float result = (nrnd0+nrnd1+nrnd2+nrnd3) / 4.0; triangle_noise_shift = result + 0.000001; return result; }`; const name = 'math-random-triangle-noise-noise'; const functionMatch = 'Math.random()'; const functionReplace = 'nrand(vTexCoord)'; const functionReturnType = 'Number'; const onBeforeRun = (kernel) => { kernel.setUniform1f('triangle_noise_seed', Math.random()); }; /** * * @type IPlugin */ module.exports = { name, onBeforeRun, functionMatch, functionReplace, functionReturnType, source }; ================================================ FILE: src/plugins/math-random-uniformly-distributed.js ================================================ // language=GLSL const source = `// https://www.shadertoy.com/view/4t2SDh //note: uniformly distributed, normalized rand, [0,1] highp float randomSeedShift = 1.0; highp float slide = 1.0; uniform highp float randomSeed1; uniform highp float randomSeed2; highp float nrand(highp vec2 n) { highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453); randomSeedShift = result; if (randomSeedShift > 0.5) { slide += 0.00009; } else { slide += 0.0009; } return result; }`; const name = 'math-random-uniformly-distributed'; // language=JavaScript const functionMatch = `Math.random()`; const functionReplace = `nrand(vTexCoord)`; const functionReturnType = 'Number'; /** * * @param {Kernel} kernel */ const onBeforeRun = (kernel) => { kernel.setUniform1f('randomSeed1', Math.random()); kernel.setUniform1f('randomSeed2', Math.random()); }; /** * * @type IPlugin */ const plugin = { name, onBeforeRun, functionMatch, functionReplace, functionReturnType, source }; module.exports = plugin; ================================================ FILE: src/texture.js ================================================ /** * @desc WebGl Texture implementation in JS * @param {IGPUTextureSettings} settings */ class Texture { constructor(settings) { const { texture, size, dimensions, output, context, type = 'NumberTexture', kernel, internalFormat, textureFormat } = settings; if (!output) throw new Error('settings property "output" required.'); if (!context) throw new Error('settings property "context" required.'); if (!texture) throw new Error('settings property "texture" required.'); if (!kernel) throw new Error('settings property "kernel" required.'); this.texture = texture; if (texture._refs) { texture._refs++; } else { texture._refs = 1; } this.size = size; this.dimensions = dimensions; this.output = output; this.context = context; /** * @type {Kernel} */ this.kernel = kernel; this.type = type; this._deleted = false; this.internalFormat = internalFormat; this.textureFormat = textureFormat; } /** * @desc Converts the Texture into a JavaScript Array * @returns {TextureArrayOutput} */ toArray() { throw new Error(`Not implemented on ${this.constructor.name}`); } /** * @desc Clones the Texture * @returns {Texture} */ clone() { throw new Error(`Not implemented on ${this.constructor.name}`); } /** * @desc Deletes the Texture */ delete() { throw new Error(`Not implemented on ${this.constructor.name}`); } clear() { throw new Error(`Not implemented on ${this.constructor.name}`); } } module.exports = { Texture }; ================================================ FILE: src/utils.js ================================================ const acorn = require('acorn'); const { Input } = require('./input'); const { Texture } = require('./texture'); const FUNCTION_NAME = /function ([^(]*)/; const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; const ARGUMENT_NAMES = /([^\s,]+)/g; /** * * @desc Various utility functions / snippets of code that GPU.JS uses internally. * @type {utils} * This covers various snippets of code that is not entirely gpu.js specific (ie. may find uses elsewhere) */ const utils = { /** * * @desc Gets the system endianness, and cache it * @returns {String} 'LE' or 'BE' depending on system architecture * Credit: https://gist.github.com/TooTallNate/4750953 */ systemEndianness() { return _systemEndianness; }, getSystemEndianness() { const b = new ArrayBuffer(4); const a = new Uint32Array(b); const c = new Uint8Array(b); a[0] = 0xdeadbeef; if (c[0] === 0xef) return 'LE'; if (c[0] === 0xde) return 'BE'; throw new Error('unknown endianness'); }, /** * @descReturn TRUE, on a JS function * @param {Function} funcObj - Object to validate if its a function * @returns {Boolean} TRUE if the object is a JS function */ isFunction(funcObj) { return typeof(funcObj) === 'function'; }, /** * @desc Return TRUE, on a valid JS function string * Note: This does just a VERY simply sanity check. And may give false positives. * * @param {String} fn - String of JS function to validate * @returns {Boolean} TRUE if the string passes basic validation */ isFunctionString(fn) { if (typeof fn === 'string') { return (fn .slice(0, 'function'.length) .toLowerCase() === 'function'); } return false; }, /** * @desc Return the function name from a JS function string * @param {String} funcStr - String of JS function to validate * @returns {String} Function name string (if found) */ getFunctionNameFromString(funcStr) { const result = FUNCTION_NAME.exec(funcStr); if (!result || result.length === 0) return null; return result[1].trim(); }, getFunctionBodyFromString(funcStr) { return funcStr.substring(funcStr.indexOf('{') + 1, funcStr.lastIndexOf('}')); }, /** * @desc Return list of argument names extracted from a javascript function * @param {String} fn - String of JS function to validate * @returns {String[]} Array representing all the parameter names */ getArgumentNamesFromString(fn) { const fnStr = fn.replace(STRIP_COMMENTS, ''); let result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES); if (result === null) { result = []; } return result; }, /** * @desc Returns a clone * @param {Object} obj - Object to clone * @returns {Object|Array} Cloned object */ clone(obj) { if (obj === null || typeof obj !== 'object' || obj.hasOwnProperty('isActiveClone')) return obj; const temp = obj.constructor(); // changed for (let key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { obj.isActiveClone = null; temp[key] = utils.clone(obj[key]); delete obj.isActiveClone; } } return temp; }, /** * @desc Checks if is an array or Array-like object * @param {Object} array - The argument object to check if is array * @returns {Boolean} true if is array or Array-like object */ isArray(array) { return !isNaN(array.length); }, /** * @desc Evaluate the argument type, to apply respective logic for it * @param {*} value - The argument object to evaluate type * @param {boolean} [strictIntegers] * @returns {String} Argument type Array/Number/Float/Texture/Unknown */ getVariableType(value, strictIntegers) { if (utils.isArray(value)) { if (value.length > 0 && value[0].nodeName === 'IMG') { return 'HTMLImageArray'; } return 'Array'; } switch (value.constructor) { case Boolean: return 'Boolean'; case Number: if (strictIntegers && Number.isInteger(value)) { return 'Integer'; } return 'Float'; case Texture: return value.type; case Input: return 'Input'; } if ('nodeName' in value) { switch (value.nodeName) { case 'IMG': return 'HTMLImage'; case 'CANVAS': return 'HTMLImage'; case 'VIDEO': return 'HTMLVideo'; } } else if (value.hasOwnProperty('type')) { return value.type; } else if (typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas) { return 'OffscreenCanvas'; } else if (typeof ImageBitmap !== 'undefined' && value instanceof ImageBitmap) { return 'ImageBitmap'; } else if (typeof ImageData !== 'undefined' && value instanceof ImageData) { return 'ImageData'; } return 'Unknown'; }, getKernelTextureSize(settings, dimensions) { let [w, h, d] = dimensions; let texelCount = (w || 1) * (h || 1) * (d || 1); if (settings.optimizeFloatMemory && settings.precision === 'single') { w = texelCount = Math.ceil(texelCount / 4); } // if given dimensions == a 2d image if (h > 1 && w * h === texelCount) { return new Int32Array([w, h]); } return utils.closestSquareDimensions(texelCount); }, /** * * @param {Number} length * @returns {TextureDimensions} */ closestSquareDimensions(length) { const sqrt = Math.sqrt(length); let high = Math.ceil(sqrt); let low = Math.floor(sqrt); while (high * low < length) { high--; low = Math.ceil(length / high); } return new Int32Array([low, Math.ceil(length / low)]); }, /** * A texture takes up four * @param {OutputDimensions} dimensions * @param {Number} bitRatio * @returns {TextureDimensions} */ getMemoryOptimizedFloatTextureSize(dimensions, bitRatio) { const totalArea = utils.roundTo((dimensions[0] || 1) * (dimensions[1] || 1) * (dimensions[2] || 1) * (dimensions[3] || 1), 4); const texelCount = totalArea / bitRatio; return utils.closestSquareDimensions(texelCount); }, /** * * @param dimensions * @param bitRatio * @returns {*|TextureDimensions} */ getMemoryOptimizedPackedTextureSize(dimensions, bitRatio) { const [w, h, d] = dimensions; const totalArea = utils.roundTo((w || 1) * (h || 1) * (d || 1), 4); const texelCount = totalArea / (4 / bitRatio); return utils.closestSquareDimensions(texelCount); }, roundTo(n, d) { return Math.floor((n + d - 1) / d) * d; }, /** * @desc Return the dimension of an array. * @param {Array|String|Texture|Input} x - The array * @param {Boolean} [pad] - To include padding in the dimension calculation * @returns {OutputDimensions} */ getDimensions(x, pad) { let ret; if (utils.isArray(x)) { const dim = []; let temp = x; while (utils.isArray(temp)) { dim.push(temp.length); temp = temp[0]; } ret = dim.reverse(); } else if (x instanceof Texture) { ret = x.output; } else if (x instanceof Input) { ret = x.size; } else { throw new Error(`Unknown dimensions of ${x}`); } if (pad) { ret = Array.from(ret); while (ret.length < 3) { ret.push(1); } } return new Int32Array(ret); }, /** * Puts a nested 2d array into a one-dimensional target array * @param {Array|*} array * @param {Float32Array|Float64Array} target */ flatten2dArrayTo(array, target) { let offset = 0; for (let y = 0; y < array.length; y++) { target.set(array[y], offset); offset += array[y].length; } }, /** * Puts a nested 3d array into a one-dimensional target array * @param {Array|*} array * @param {Float32Array|Float64Array} target */ flatten3dArrayTo(array, target) { let offset = 0; for (let z = 0; z < array.length; z++) { for (let y = 0; y < array[z].length; y++) { target.set(array[z][y], offset); offset += array[z][y].length; } } }, /** * Puts a nested 4d array into a one-dimensional target array * @param {Array|*} array * @param {Float32Array|Float64Array} target */ flatten4dArrayTo(array, target) { let offset = 0; for (let l = 0; l < array.length; l++) { for (let z = 0; z < array[l].length; z++) { for (let y = 0; y < array[l][z].length; y++) { target.set(array[l][z][y], offset); offset += array[l][z][y].length; } } } }, /** * Puts a nested 1d, 2d, or 3d array into a one-dimensional target array * @param {Float32Array|Uint16Array|Uint8Array} array * @param {Float32Array} target */ flattenTo(array, target) { if (utils.isArray(array[0])) { if (utils.isArray(array[0][0])) { if (utils.isArray(array[0][0][0])) { utils.flatten4dArrayTo(array, target); } else { utils.flatten3dArrayTo(array, target); } } else { utils.flatten2dArrayTo(array, target); } } else { target.set(array); } }, /** * * @desc Splits an array into smaller arrays. * Number of elements in one small chunk is given by `part` * * @param {Number[]} array - The array to split into chunks * @param {Number} part - elements in one chunk * * @returns {Number[]} An array of smaller chunks */ splitArray(array, part) { const result = []; for (let i = 0; i < array.length; i += part) { result.push(new array.constructor(array.buffer, i * 4 + array.byteOffset, part)); } return result; }, getAstString(source, ast) { const lines = Array.isArray(source) ? source : source.split(/\r?\n/g); const start = ast.loc.start; const end = ast.loc.end; const result = []; if (start.line === end.line) { result.push(lines[start.line - 1].substring(start.column, end.column)); } else { result.push(lines[start.line - 1].slice(start.column)); for (let i = start.line; i < end.line; i++) { result.push(lines[i]); } result.push(lines[end.line - 1].slice(0, end.column)); } return result.join('\n'); }, allPropertiesOf(obj) { const props = []; do { props.push.apply(props, Object.getOwnPropertyNames(obj)); } while (obj = Object.getPrototypeOf(obj)); return props; }, /** * @param {Array} lines - An Array of strings * @returns {String} Single combined String, separated by *\n* */ linesToString(lines) { if (lines.length > 0) { return lines.join(';\n') + ';\n'; } else { return '\n'; } }, warnDeprecated(type, oldName, newName) { if (newName) { console.warn(`You are using a deprecated ${ type } "${ oldName }". It has been replaced with "${ newName }". Fixing, but please upgrade as it will soon be removed.`); } else { console.warn(`You are using a deprecated ${ type } "${ oldName }". It has been removed. Fixing, but please upgrade as it will soon be removed.`); } }, flipPixels: (pixels, width, height) => { // https://stackoverflow.com/a/41973289/1324039 const halfHeight = height / 2 | 0; // the | 0 keeps the result an int const bytesPerRow = width * 4; // make a temp buffer to hold one row const temp = new Uint8ClampedArray(width * 4); const result = pixels.slice(0); for (let y = 0; y < halfHeight; ++y) { const topOffset = y * bytesPerRow; const bottomOffset = (height - y - 1) * bytesPerRow; // make copy of a row on the top half temp.set(result.subarray(topOffset, topOffset + bytesPerRow)); // copy a row from the bottom half to the top result.copyWithin(topOffset, bottomOffset, bottomOffset + bytesPerRow); // copy the copy of the top half row to the bottom half result.set(temp, bottomOffset); } return result; }, erectPackedFloat: (array, width) => { return array.subarray(0, width); }, erect2DPackedFloat: (array, width, height) => { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xStart = y * width; const xEnd = xStart + width; yResults[y] = array.subarray(xStart, xEnd); } return yResults; }, erect3DPackedFloat: (array, width, height, depth) => { const zResults = new Array(depth); for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xStart = (z * height * width) + y * width; const xEnd = xStart + width; yResults[y] = array.subarray(xStart, xEnd); } zResults[z] = yResults; } return zResults; }, erectMemoryOptimizedFloat: (array, width) => { return array.subarray(0, width); }, erectMemoryOptimized2DFloat: (array, width, height) => { const yResults = new Array(height); for (let y = 0; y < height; y++) { const offset = y * width; yResults[y] = array.subarray(offset, offset + width); } return yResults; }, erectMemoryOptimized3DFloat: (array, width, height, depth) => { const zResults = new Array(depth); for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const offset = (z * height * width) + (y * width); yResults[y] = array.subarray(offset, offset + width); } zResults[z] = yResults; } return zResults; }, erectFloat: (array, width) => { const xResults = new Float32Array(width); let i = 0; for (let x = 0; x < width; x++) { xResults[x] = array[i]; i += 4; } return xResults; }, erect2DFloat: (array, width, height) => { const yResults = new Array(height); let i = 0; for (let y = 0; y < height; y++) { const xResults = new Float32Array(width); for (let x = 0; x < width; x++) { xResults[x] = array[i]; i += 4; } yResults[y] = xResults; } return yResults; }, erect3DFloat: (array, width, height, depth) => { const zResults = new Array(depth); let i = 0; for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Float32Array(width); for (let x = 0; x < width; x++) { xResults[x] = array[i]; i += 4; } yResults[y] = xResults; } zResults[z] = yResults; } return zResults; }, erectArray2: (array, width) => { const xResults = new Array(width); const xResultsMax = width * 4; let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x, x + 2); } return xResults; }, erect2DArray2: (array, width, height) => { const yResults = new Array(height); const XResultsMax = width * 4; for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = y * XResultsMax; let i = 0; for (let x = 0; x < XResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 2); } yResults[y] = xResults; } return yResults; }, erect3DArray2: (array, width, height, depth) => { const xResultsMax = width * 4; const zResults = new Array(depth); for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = (z * xResultsMax * height) + (y * xResultsMax); let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 2); } yResults[y] = xResults; } zResults[z] = yResults; } return zResults; }, erectArray3: (array, width) => { const xResults = new Array(width); const xResultsMax = width * 4; let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x, x + 3); } return xResults; }, erect2DArray3: (array, width, height) => { const xResultsMax = width * 4; const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = y * xResultsMax; let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 3); } yResults[y] = xResults; } return yResults; }, erect3DArray3: (array, width, height, depth) => { const xResultsMax = width * 4; const zResults = new Array(depth); for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = (z * xResultsMax * height) + (y * xResultsMax); let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 3); } yResults[y] = xResults; } zResults[z] = yResults; } return zResults; }, erectArray4: (array, width) => { const xResults = new Array(array); const xResultsMax = width * 4; let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x, x + 4); } return xResults; }, erect2DArray4: (array, width, height) => { const xResultsMax = width * 4; const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = y * xResultsMax; let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 4); } yResults[y] = xResults; } return yResults; }, erect3DArray4: (array, width, height, depth) => { const xResultsMax = width * 4; const zResults = new Array(depth); for (let z = 0; z < depth; z++) { const yResults = new Array(height); for (let y = 0; y < height; y++) { const xResults = new Array(width); const offset = (z * xResultsMax * height) + (y * xResultsMax); let i = 0; for (let x = 0; x < xResultsMax; x += 4) { xResults[i++] = array.subarray(x + offset, x + offset + 4); } yResults[y] = xResults; } zResults[z] = yResults; } return zResults; }, /** * * @param {String} source * @param {Object} settings * @return {String} */ flattenFunctionToString: (source, settings) => { const { findDependency, thisLookup, doNotDefine } = settings; let flattened = settings.flattened; if (!flattened) { flattened = settings.flattened = {}; } const ast = acorn.parse(source); const functionDependencies = []; let indent = 0; function flatten(ast) { if (Array.isArray(ast)) { const results = []; for (let i = 0; i < ast.length; i++) { results.push(flatten(ast[i])); } return results.join(''); } switch (ast.type) { case 'Program': return flatten(ast.body) + (ast.body[0].type === 'VariableDeclaration' ? ';' : ''); case 'FunctionDeclaration': return `function ${ast.id.name}(${ast.params.map(flatten).join(', ')}) ${ flatten(ast.body) }`; case 'BlockStatement': { const result = []; indent += 2; for (let i = 0; i < ast.body.length; i++) { const flat = flatten(ast.body[i]); if (flat) { result.push(' '.repeat(indent) + flat, ';\n'); } } indent -= 2; return `{\n${result.join('')}}`; } case 'VariableDeclaration': const declarations = utils.normalizeDeclarations(ast) .map(flatten) .filter(r => r !== null); if (declarations.length < 1) { return ''; } else { return `${ast.kind} ${declarations.join(',')}`; } case 'VariableDeclarator': if (ast.init.object && ast.init.object.type === 'ThisExpression') { const lookup = thisLookup(ast.init.property.name, true); if (lookup) { return `${ast.id.name} = ${flatten(ast.init)}`; } else { return null; } } else { return `${ast.id.name} = ${flatten(ast.init)}`; } case 'CallExpression': { if (ast.callee.property.name === 'subarray') { return `${flatten(ast.callee.object)}.${flatten(ast.callee.property)}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } if (ast.callee.object.name === 'gl' || ast.callee.object.name === 'context') { return `${flatten(ast.callee.object)}.${flatten(ast.callee.property)}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } if (ast.callee.object.type === 'ThisExpression') { functionDependencies.push(findDependency('this', ast.callee.property.name)); return `${ast.callee.property.name}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } else if (ast.callee.object.name) { const foundSource = findDependency(ast.callee.object.name, ast.callee.property.name); if (foundSource === null) { // we're not flattening it return `${ast.callee.object.name}.${ast.callee.property.name}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } else { functionDependencies.push(foundSource); // we're flattening it return `${ast.callee.property.name}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } } else if (ast.callee.object.type === 'MemberExpression') { return `${flatten(ast.callee.object)}.${ast.callee.property.name}(${ast.arguments.map(value => flatten(value)).join(', ')})`; } else { throw new Error('unknown ast.callee'); } } case 'ReturnStatement': return `return ${flatten(ast.argument)}`; case 'BinaryExpression': return `(${flatten(ast.left)}${ast.operator}${flatten(ast.right)})`; case 'UnaryExpression': if (ast.prefix) { return `${ast.operator} ${flatten(ast.argument)}`; } else { return `${flatten(ast.argument)} ${ast.operator}`; } case 'ExpressionStatement': return `${flatten(ast.expression)}`; case 'SequenceExpression': return `(${flatten(ast.expressions)})`; case 'ArrowFunctionExpression': return `(${ast.params.map(flatten).join(', ')}) => ${flatten(ast.body)}`; case 'Literal': return ast.raw; case 'Identifier': return ast.name; case 'MemberExpression': if (ast.object.type === 'ThisExpression') { return thisLookup(ast.property.name); } if (ast.computed) { return `${flatten(ast.object)}[${flatten(ast.property)}]`; } return flatten(ast.object) + '.' + flatten(ast.property); case 'ThisExpression': return 'this'; case 'NewExpression': return `new ${flatten(ast.callee)}(${ast.arguments.map(value => flatten(value)).join(', ')})`; case 'ForStatement': return `for (${flatten(ast.init)};${flatten(ast.test)};${flatten(ast.update)}) ${flatten(ast.body)}`; case 'AssignmentExpression': return `${flatten(ast.left)}${ast.operator}${flatten(ast.right)}`; case 'UpdateExpression': return `${flatten(ast.argument)}${ast.operator}`; case 'IfStatement': return `if (${flatten(ast.test)}) ${flatten(ast.consequent)}`; case 'ThrowStatement': return `throw ${flatten(ast.argument)}`; case 'ObjectPattern': return ast.properties.map(flatten).join(', '); case 'ArrayPattern': return ast.elements.map(flatten).join(', '); case 'DebuggerStatement': return 'debugger;'; case 'ConditionalExpression': return `${flatten(ast.test)}?${flatten(ast.consequent)}:${flatten(ast.alternate)}`; case 'Property': if (ast.kind === 'init') { return flatten(ast.key); } } throw new Error(`unhandled ast.type of ${ ast.type }`); } const result = flatten(ast); if (functionDependencies.length > 0) { const flattenedFunctionDependencies = []; for (let i = 0; i < functionDependencies.length; i++) { const functionDependency = functionDependencies[i]; if (!flattened[functionDependency]) { flattened[functionDependency] = true; } functionDependency ? flattenedFunctionDependencies.push(utils.flattenFunctionToString(functionDependency, settings) + '\n') : ''; } return flattenedFunctionDependencies.join('') + result; } return result; }, normalizeDeclarations: (ast) => { if (ast.type !== 'VariableDeclaration') throw new Error('Ast is not of type "VariableDeclaration"'); const normalizedDeclarations = []; for (let declarationIndex = 0; declarationIndex < ast.declarations.length; declarationIndex++) { const declaration = ast.declarations[declarationIndex]; if (declaration.id && declaration.id.type === 'ObjectPattern' && declaration.id.properties) { const { properties } = declaration.id; for (let propertyIndex = 0; propertyIndex < properties.length; propertyIndex++) { const property = properties[propertyIndex]; if (property.value.type === 'ObjectPattern' && property.value.properties) { for (let subPropertyIndex = 0; subPropertyIndex < property.value.properties.length; subPropertyIndex++) { const subProperty = property.value.properties[subPropertyIndex]; if (subProperty.type === 'Property') { normalizedDeclarations.push({ type: 'VariableDeclarator', id: { type: 'Identifier', name: subProperty.key.name }, init: { type: 'MemberExpression', object: { type: 'MemberExpression', object: declaration.init, property: { type: 'Identifier', name: property.key.name }, computed: false }, property: { type: 'Identifier', name: subProperty.key.name }, computed: false } }); } else { throw new Error('unexpected state'); } } } else if (property.value.type === 'Identifier') { normalizedDeclarations.push({ type: 'VariableDeclarator', id: { type: 'Identifier', name: property.value && property.value.name ? property.value.name : property.key.name }, init: { type: 'MemberExpression', object: declaration.init, property: { type: 'Identifier', name: property.key.name }, computed: false } }); } else { throw new Error('unexpected state'); } } } else if (declaration.id && declaration.id.type === 'ArrayPattern' && declaration.id.elements) { const { elements } = declaration.id; for (let elementIndex = 0; elementIndex < elements.length; elementIndex++) { const element = elements[elementIndex]; if (element.type === 'Identifier') { normalizedDeclarations.push({ type: 'VariableDeclarator', id: { type: 'Identifier', name: element.name }, init: { type: 'MemberExpression', object: declaration.init, property: { type: 'Literal', value: elementIndex, raw: elementIndex.toString(), start: element.start, end: element.end }, computed: true } }); } else { throw new Error('unexpected state'); } } } else { normalizedDeclarations.push(declaration); } } return normalizedDeclarations; }, /** * * @param {GPU} gpu * @param image * @return {Array} */ splitHTMLImageToRGB: (gpu, image) => { const rKernel = gpu.createKernel(function(a) { const pixel = a[this.thread.y][this.thread.x]; return pixel.r * 255; }, { output: [image.width, image.height], precision: 'unsigned', argumentTypes: { a: 'HTMLImage' }, }); const gKernel = gpu.createKernel(function(a) { const pixel = a[this.thread.y][this.thread.x]; return pixel.g * 255; }, { output: [image.width, image.height], precision: 'unsigned', argumentTypes: { a: 'HTMLImage' }, }); const bKernel = gpu.createKernel(function(a) { const pixel = a[this.thread.y][this.thread.x]; return pixel.b * 255; }, { output: [image.width, image.height], precision: 'unsigned', argumentTypes: { a: 'HTMLImage' }, }); const aKernel = gpu.createKernel(function(a) { const pixel = a[this.thread.y][this.thread.x]; return pixel.a * 255; }, { output: [image.width, image.height], precision: 'unsigned', argumentTypes: { a: 'HTMLImage' }, }); const result = [ rKernel(image), gKernel(image), bKernel(image), aKernel(image), ]; result.rKernel = rKernel; result.gKernel = gKernel; result.bKernel = bKernel; result.aKernel = aKernel; result.gpu = gpu; return result; }, /** * A visual debug utility * @param {GPU} gpu * @param rgba * @param width * @param height * @return {Object[]} */ splitRGBAToCanvases: (gpu, rgba, width, height) => { const visualKernelR = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(pixel.r / 255, 0, 0, 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelR(rgba); const visualKernelG = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(0, pixel.g / 255, 0, 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelG(rgba); const visualKernelB = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(0, 0, pixel.b / 255, 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelB(rgba); const visualKernelA = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(255, 255, 255, pixel.a / 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelA(rgba); return [ visualKernelR.canvas, visualKernelG.canvas, visualKernelB.canvas, visualKernelA.canvas, ]; }, getMinifySafeName: (fn) => { try { const ast = acorn.parse(`const value = ${fn.toString()}`); const { init } = ast.body[0].declarations[0]; return init.body.name || init.body.body[0].argument.name; } catch (e) { throw new Error('Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }'); } }, sanitizeName: function(name) { if (dollarSign.test(name)) { name = name.replace(dollarSign, 'S_S'); } if (doubleUnderscore.test(name)) { name = name.replace(doubleUnderscore, 'U_U'); } else if (singleUnderscore.test(name)) { name = name.replace(singleUnderscore, 'u_u'); } return name; } }; const dollarSign = /\$/; const doubleUnderscore = /__/; const singleUnderscore = /_/; const _systemEndianness = utils.getSystemEndianness(); module.exports = { utils }; ================================================ FILE: test/all-template.html ================================================ GPU.JS : Test All
{{test-files}} ================================================ FILE: test/all.html ================================================ GPU.JS : Test All
================================================ FILE: test/benchmark-faster.js ================================================ const { GPU } = require('../src/index.js'); const Benchmark = require('benchmark'); const suite = new Benchmark.Suite; const size = 512; const gpu = new GPU({ mode: 'gpu' }); const cpu = new GPU({ mode: 'cpu' }); const gpuKernel = gpu .createKernel(function(i, j) { return i[this.thread.x] + j[this.thread.x]; }) .setOutput([size, size]); const gpuArg1 = gpu .createKernel(function() { return 0.89; }) .setPipeline(true) .setOutput([size, size])(); const gpuArg2 = gpu .createKernel(function() { return this.thread.x; }) .setPipeline(true) .setOutput([size, size])(); const cpuKernel = cpu .createKernel(function(i, j) { return i[this.thread.x] + j[this.thread.x]; }) .setOutput([size, size]); const cpuArg1 = cpu .createKernel(function() { return 0.89; }) .setOutput([size, size])(); const cpuArg2 = cpu .createKernel(function() { return this.thread.x; }) .setOutput([size, size])(); suite .add('gpu', () => { gpuKernel(gpuArg1, gpuArg2); }) .add('cpu', () => { cpuKernel(cpuArg1, cpuArg2); }) .on('cycle', (event) => { console.log(String(event.target)); }) .on('complete', function () { gpu.destroy(); cpu.destroy(); console.log('Fastest is ' + this.filter('fastest').map('name')); }) .run(); ================================================ FILE: test/benchmark.js ================================================ const { GPU } = require('../src/index.js'); const Benchmark = require('benchmark'); const suite = new Benchmark.Suite(); const gpu = new GPU({ mode: 'gpu' }); const cpu = new GPU({ mode: 'cpu' }); const size = 1024; const a = randomMatrix(size, size); const b = randomMatrix(size, size); function randomMatrix(width, height) { const matrix = new Array(height); for (let y = 0; y < height; y++) { const row = matrix[y] = new Float32Array(width); for (let x = 0; x < width; x++) { row[x] = Math.random(); } } return matrix; } const gpuKernel = gpu .createKernel(function(a, b) { let sum = 0; for (let i = 0; i < this.constants.size; i++) { sum += a[this.thread.y][i] * b[i][this.thread.x]; } return sum; }) .setConstants({ size }) .setPipeline(false) .setPrecision('unsigned') .setOutput([size, size]); const cpuKernel = cpu .createKernel(function(a, b) { let sum = 0; for (let i = 0; i < this.constants.size; i++) { sum += a[this.thread.y][i] * b[i][this.thread.x]; } return sum; }) .setConstants({ size }) .setOutput([size, size]); // go ahead and build gpuKernel(a, b); cpuKernel(a, b); // add tests suite .add('gpu', () => { gpuKernel(a, b); }) .add('cpu', () => { cpuKernel(a, b); }) // add listeners .on('cycle', (event) => { console.log(String(event.target)); }) .on('complete', function () { gpu.destroy(); cpu.destroy(); console.log('Fastest is ' + this.filter('fastest').map('name')); }) .run({ async: false }); ================================================ FILE: test/browser-test-utils.js ================================================ function imageToArray(image) { const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; document.body.appendChild(canvas); document.body.appendChild(image); const ctx = canvas.getContext('2d'); ctx.drawImage(image, 0, 0); const { data } = ctx.getImageData(0, 0, image.width, image.height); document.body.removeChild(canvas); document.body.removeChild(image); let i = 0; const result = []; for (let y = 0; y < image.height; y++) { const row = []; result.unshift(row); for (let x = 0; x < image.width; x++) { const pixel = new Float32Array([ data[i++], data[i++], data[i++], data[i++], ]); row.push(pixel); } } return result; } function loadImage(image) { return new Promise((resolve) => { if (typeof image === 'string') { const src = image; image = new Image(); image.src = src; } image.onload = () => { resolve(image); }; }); } function loadImages(images) { return Promise.all(images.map(image => loadImage(image))); } function check2DImage(result, expected, channel) { const height = result.length; const width = result[0].length; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { if (result[y][x] !== expected[y][x][channel]) { throw new Error(`result[${y}][${x}] value does not match expected value of ${expected[y][x][channel]}`); } } } return true; } function greenCanvas(mode, width, height) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { this.color(0, 1, 0, 1); }, { output: [width, height], graphical: true }); kernel(); const canvas = kernel.canvas; gpu.destroy(); return canvas; } const _exports = { greenCanvas, imageToArray, loadImage, check2DImage, }; if (typeof window !== 'undefined') { window.browserTestUtils = _exports; } else { module.exports = _exports; } ================================================ FILE: test/features/add-custom-function.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: add custom function'); function inGPUInstanceSettings(mode) { function customAdder(a, b) { return a + b; } const gpu = new GPU({mode, functions: [customAdder] }); const kernel = gpu.createKernel(function (a, b) { return customAdder(a[this.thread.x], b[this.thread.x]); }, { output: [6] }); const a = [1, 2, 3, 5, 6, 7]; const b = [4, 5, 6, 1, 2, 3]; const result = kernel(a, b); const expected = [5, 7, 9, 6, 8, 10]; assert.deepEqual(Array.from(result), expected); gpu.destroy(); } test('in GPU instance settings auto', () => { inGPUInstanceSettings(null); }); test('in GPU instance settings gpu', () => { inGPUInstanceSettings('gpu'); }); (GPU.isWebGLSupported ? test : skip)('in GPU instance settings webgl', () => { inGPUInstanceSettings('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('in GPU instance settings webgl2', () => { inGPUInstanceSettings('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('in GPU instance settings headlessgl', () => { inGPUInstanceSettings('headlessgl'); }); test('in GPU instance settings cpu', () => { inGPUInstanceSettings('cpu'); }); function withGPUAddFunctionMethod(mode) { function customAdder(a, b) { return a + b; } const gpu = new GPU({ mode }) .addFunction(customAdder); const kernel = gpu.createKernel(function (a, b) { return customAdder(a[this.thread.x], b[this.thread.x]); }, { output: [6] }); const a = [1, 2, 3, 5, 6, 7]; const b = [4, 5, 6, 1, 2, 3]; const result = kernel(a, b); const expected = [5, 7, 9, 6, 8, 10]; assert.deepEqual(Array.from(result), expected); gpu.destroy(); } test('with GPU addFunction method auto', () => { withGPUAddFunctionMethod(null); }); test('with GPU addFunction method gpu', () => { withGPUAddFunctionMethod('gpu'); }); (GPU.isWebGLSupported ? test : skip)('with GPU addFunction method webgl', () => { withGPUAddFunctionMethod('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with GPU addFunction method webgl2', () => { withGPUAddFunctionMethod('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('with GPU addFunction method headlessgl', () => { withGPUAddFunctionMethod('headlessgl'); }); test('with GPU addFunction method cpu', () => { withGPUAddFunctionMethod('cpu'); }); function inKernelInstanceSettings(mode) { function customAdder(a, b) { return a + b; } const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function (a, b) { return customAdder(a[this.thread.x], b[this.thread.x]); }, { output: [6], functions: [ customAdder ], }); const a = [1, 2, 3, 5, 6, 7]; const b = [4, 5, 6, 1, 2, 3]; const result = kernel(a, b); const expected = [5, 7, 9, 6, 8, 10]; assert.deepEqual(Array.from(result), expected); gpu.destroy(); } test('in Kernel instance settings auto', () => { inKernelInstanceSettings(null); }); test('in Kernel instance settings gpu', () => { inKernelInstanceSettings('gpu'); }); (GPU.isWebGLSupported ? test : skip)('in Kernel instance settings webgl', () => { inKernelInstanceSettings('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('in Kernel instance settings webgl2', () => { inKernelInstanceSettings('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('in Kernel instance settings headlessgl', () => { inKernelInstanceSettings('headlessgl'); }); test('in Kernel instance settings cpu', () => { inKernelInstanceSettings('cpu'); }); function withKernelAddFunctionMethod(mode) { function customAdder(a, b) { return a + b; } const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function (a, b) { return customAdder(a[this.thread.x], b[this.thread.x]); }, { output: [6] }) .addFunction(customAdder); const a = [1, 2, 3, 5, 6, 7]; const b = [4, 5, 6, 1, 2, 3]; const result = kernel(a, b); const expected = [5, 7, 9, 6, 8, 10]; assert.deepEqual(Array.from(result), expected); gpu.destroy(); } test('with Kernel addFunction method auto', () => { withKernelAddFunctionMethod(null); }); test('with Kernel addFunction method gpu', () => { withKernelAddFunctionMethod('gpu'); }); (GPU.isWebGLSupported ? test : skip)('with Kernel addFunction method webgl', () => { withKernelAddFunctionMethod('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Kernel addFunction method webgl2', () => { withKernelAddFunctionMethod('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('with Kernel addFunction method headlessgl', () => { withKernelAddFunctionMethod('headlessgl'); }); test('with Kernel addFunction method cpu', () => { withKernelAddFunctionMethod('cpu'); }); describe('features: add custom function with `this.constants.width` in loop'); function sumAB(mode) { const gpu = new GPU({mode}); function customAdder(a, b) { let sum = 0; for (let i = 0; i < this.constants.width; i++) { sum += a[this.thread.x] + b[this.thread.x]; } return sum; } gpu.addFunction(customAdder); const kernel = gpu.createKernel(function (a, b) { return customAdder(a, b); }, { output: [6], constants: {width: 6}, precision: 'unsigned', }); assert.ok(kernel !== null, 'function generated test'); const a = [1, 2, 3, 5, 6, 7]; const b = [1, 1, 1, 1, 1, 1]; const result = kernel(a, b); const expected = [12, 18, 24, 36, 42, 48]; assert.deepEqual(Array.from(result), expected); gpu.destroy(); } test('sumAB auto', () => { sumAB(null); }); test('sumAB gpu', () => { sumAB('gpu'); }); (GPU.isWebGLSupported ? test : skip)('sumAB webgl', () => { sumAB('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('sumAB webgl2', () => { sumAB('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('sumAB headlessgl', () => { sumAB('headlessgl'); }); test('sumAB cpu', () => { sumAB('cpu'); }); describe('features: add custom function with `this.output.x` in loop'); function sumABThisOutputX(mode) { const gpu = new GPU({ mode, functions: [customAdder] }); function customAdder(a, b) { let sum = 0; for (let i = 0; i < this.output.x; i++) { sum += a[this.thread.x] + b[this.thread.x]; } return sum; } const kernel = gpu.createKernel(function(a, b) { return customAdder(a, b); }, { output : [6], }); assert.ok(kernel !== null, 'function generated test'); const a = [1, 2, 3, 5, 6, 7]; const b = [1, 1, 1, 1, 1, 1]; const result = kernel(a,b); const expected = [12, 18, 24, 36, 42, 48]; assert.deepEqual(Array.from(result), expected); gpu.destroy(); } test('sumABThisOutputX auto', () => { sumABThisOutputX(null); }); test('sumABThisOutputX gpu', () => { sumABThisOutputX('gpu'); }); (GPU.isWebGLSupported ? test : skip)('sumABThisOutputX webgl', () => { sumABThisOutputX('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('sumABThisOutputX webgl2', () => { sumABThisOutputX('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('sumABThisOutputX headlessgl', () => { sumABThisOutputX('headlessgl'); }); test('sumABThisOutputX cpu', () => { sumABThisOutputX('cpu'); }); describe('features: add custom private'); function addCustomPrivate(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(a, b) { function customAdder(a, b) { let sum = 0; for (let i = 0; i < this.output.x; i++) { sum += a[this.thread.x] + b[this.thread.x]; } return sum; } return customAdder(a, b); }, { output : [6], }); assert.ok(kernel !== null, 'function generated test'); const a = [1, 2, 3, 5, 6, 7]; const b = [1, 1, 1, 1, 1, 1]; const result = kernel(a,b); const expected = [12, 18, 24, 36, 42, 48]; assert.deepEqual(Array.from(result), expected); gpu.destroy(); } test('auto', () => { addCustomPrivate(null); }); test('gpu', () => { addCustomPrivate('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { addCustomPrivate('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { addCustomPrivate('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { addCustomPrivate('headlessgl'); }); test('cpu', () => { addCustomPrivate('cpu'); }); describe('features: setFunctions from array on kernel'); function testSetFunctionsFromArrayOnKernel(mode) { const gpu = new GPU({ mode }); function custom() { return 1; } const kernel = gpu.createKernel(function() { return custom(); }, { output: [1] }); kernel.setFunctions([custom]); assert.equal(kernel()[0], 1); gpu.destroy(); } test('auto', () => { testSetFunctionsFromArrayOnKernel(); }); test('gpu', () => { testSetFunctionsFromArrayOnKernel('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testSetFunctionsFromArrayOnKernel('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testSetFunctionsFromArrayOnKernel('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testSetFunctionsFromArrayOnKernel('headlessgl'); }); test('cpu', () => { testSetFunctionsFromArrayOnKernel('cpu'); }); describe('features: setFunctions from array on kernel'); function testSetFunctionsFromArrayOnGPU(mode) { const gpu = new GPU({ mode }); assert.equal(gpu.setFunctions([function custom() { return 1; }]), gpu); const kernel = gpu.createKernel(function() { return custom(); }, { output: [1] }); assert.equal(kernel()[0], 1); gpu.destroy(); } test('auto', () => { testSetFunctionsFromArrayOnGPU(); }); test('gpu', () => { testSetFunctionsFromArrayOnGPU('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testSetFunctionsFromArrayOnGPU('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testSetFunctionsFromArrayOnGPU('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testSetFunctionsFromArrayOnGPU('headlessgl'); }); test('cpu', () => { testSetFunctionsFromArrayOnGPU('cpu'); }); describe('features: setFunctions from array on kernel'); function testAddIGPUFunction(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return custom(value); }) .setOutput([1]) .addFunction({ name: 'custom', argumentTypes: { value: 'Number' }, source: `function custom(value) { return value + 1.0; }`, returnType: 'Number', }); assert.equal(kernel(1)[0], 2); gpu.destroy(); } test('auto', () => { testAddIGPUFunction(); }); test('gpu', () => { testAddIGPUFunction('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testAddIGPUFunction('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testAddIGPUFunction('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testAddIGPUFunction('headlessgl'); }); test('cpu', () => { testAddIGPUFunction('cpu'); }); ================================================ FILE: test/features/add-custom-native-function.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: add native'); const glslDivide = `float divide(float a, float b) { return a / b; }`; const jsDivide = `function divide(a, b) { return a / b; }`; function nativeDivide(mode, fn) { const gpu = new GPU({ mode }); gpu.addNativeFunction('divide', fn, { returnType: 'Number' }); const f = gpu.createKernel(function(a, b) { return divide(a[this.thread.x], b[this.thread.x]); }, { output : [6] }); assert.ok(f !== null, 'function generated test'); const a = [1, 4, 3, 5, 6, 3]; const b = [4, 2, 6, 1, 2, 3]; const res = f(a,b); const exp = [0.25, 2, 0.5, 5, 3, 1]; for(let i = 0; i < exp.length; ++i) { assert.equal(res[i], exp[i], 'Result arr idx: '+i); } gpu.destroy(); } test('nativeDivide auto', () => { nativeDivide(null, glslDivide); }); test('nativeDivide gpu', () => { nativeDivide('gpu', glslDivide); }); (GPU.isWebGLSupported ? test : skip)('nativeDivide webgl', () => { nativeDivide('webgl', glslDivide); }); (GPU.isWebGL2Supported ? test : skip)('nativeDivide webgl2', () => { nativeDivide('webgl2', glslDivide); }); (GPU.isHeadlessGLSupported ? test : skip)('nativeDivide headlessgl', () => { nativeDivide('headlessgl', glslDivide); }); test('nativeDivide cpu', () => { nativeDivide('cpu', jsDivide); }); describe('features: instantiate native and override'); function divideOverride(mode) { const gpu = new GPU({ mode, functions: [divide], nativeFunctions: [{ name: 'divide', // deliberately add, rather than divide, to ensure native functions are treated as more important than regular ones source: `float divide(float a, float b) { return a + b; }` }] }); function divide(a,b) { return a / b; } const kernel = gpu.createKernel(function(a, b) { return divide(a[this.thread.x], b[this.thread.x]); }, { output : [6] }); const a = [1, 4, 3, 5, 6, 3]; const b = [4, 2, 6, 1, 2, 3]; const res = kernel(a,b); const exp = [5, 6, 9, 6, 8, 6]; assert.deepEqual(Array.from(res), exp); gpu.destroy(); } test('divideOverride (GPU only) auto', () => { divideOverride(null); }); test('divideOverride (GPU only) gpu', () => { divideOverride('gpu'); }); (GPU.isWebGLSupported ? test : skip)('divideOverride (GPU only) webgl', () => { divideOverride('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('divideOverride (GPU only) webgl2', () => { divideOverride('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('divideOverride (GPU only) headlessgl', () => { divideOverride('headlessgl'); }); describe('features: argument casting'); function argumentCasting(mode) { const gpu = new GPU({ mode, functions: [divide], nativeFunctions: [{ // deliberately add, rather than divide, to ensure native functions are treated as more important than regular ones name: 'divide', source: `float divide(int a, int b) { return float(a + b); }` }] }); function divide(a,b) { return a / b; } const kernel = gpu.createKernel(function(a, b) { return divide(a[this.thread.x], b[this.thread.x]); }, { output : [6] }); const a = [1, 4, 3, 5, 6, 3]; const b = [4, 2, 6, 1, 2, 3]; const res = kernel(a,b); const exp = [5, 6, 9, 6, 8, 6]; assert.deepEqual(Array.from(res), exp); gpu.destroy(); } test('argumentCasting (GPU only) auto', () => { argumentCasting(null); }); test('argumentCasting (GPU only) gpu', () => { argumentCasting('gpu'); }); (GPU.isWebGLSupported ? test : skip)('argumentCasting (GPU only) webgl', () => { argumentCasting('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('argumentCasting (GPU only) webgl2', () => { argumentCasting('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('argumentCasting (GPU only) headlessgl', () => { argumentCasting('headlessgl'); }); describe('features: mixed argument casting'); function mixedArgumentCasting(mode) { const gpu = new GPU({ mode, functions: [divide], nativeFunctions: [{ // deliberately add, rather than divide, to ensure native functions are treated as more important than regular ones name: 'divide', source: `float divide(int a, float b) { return float(a + int(b)); }` }] }); function divide(a,b) { return a / b; } const kernel = gpu.createKernel(function(a, b) { return divide(a[this.thread.x], b[this.thread.x]); }, { output : [6] }); const a = [1, 4, 3, 5, 6, 3]; const b = [4, 2, 6, 1, 2, 3]; const res = kernel(a,b); const exp = [5, 6, 9, 6, 8, 6]; assert.deepEqual(Array.from(res), exp); gpu.destroy(); } test('mixedArgumentCasting (GPU only) auto', () => { mixedArgumentCasting(null); }); test('mixedArgumentCasting (GPU only) gpu', () => { mixedArgumentCasting('gpu'); }); (GPU.isWebGLSupported ? test : skip)('mixedArgumentCasting (GPU only) webgl', () => { mixedArgumentCasting('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('mixedArgumentCasting (GPU only) webgl2', () => { mixedArgumentCasting('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('mixedArgumentCasting (GPU only) headlessgl', () => { mixedArgumentCasting('headlessgl'); }); describe('features: return type casting'); function returnTypeCasting(mode) { const gpu = new GPU({ mode, functions: [divide], nativeFunctions: [{ // deliberately add, rather than divide, to ensure native functions are treated as more important than regular ones name: 'divide', source: `int divide(float a, float b) { return int(a + b); }` }] }); function divide(a,b) { return a / b; } const kernel = gpu.createKernel(function(a, b) { return divide(a[this.thread.x], b[this.thread.x]); }, { output : [6] }); const a = [1, 4, 3, 5, 6, 3]; const b = [4, 2, 6, 1, 2, 3]; const res = kernel(a,b); const exp = [5, 6, 9, 6, 8, 6]; assert.deepEqual(Array.from(res), exp); gpu.destroy(); } test('returnTypeCasting (GPU only) auto', () => { returnTypeCasting(null); }); test('returnTypeCasting (GPU only) gpu', () => { returnTypeCasting('gpu'); }); (GPU.isWebGLSupported ? test : skip)('returnTypeCasting (GPU only) webgl', () => { returnTypeCasting('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('returnTypeCasting (GPU only) webgl2', () => { returnTypeCasting('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('returnTypeCasting (GPU only) headlessgl', () => { returnTypeCasting('headlessgl'); }); describe('features: Adding nativeFunctions directly on kernel'); function testDirectlyOnKernelViaSettings(nativeFunctions, mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function (v) { return native(v[this.thread.x]); }, { output: [1], nativeFunctions }); assert.equal(kernel([1])[0], 2); gpu.destroy(); } test('via settings auto', () => { testDirectlyOnKernelViaSettings([ { name: 'native', source: `float native(float value) { return 1.0 + value; }` } ]) }); test('via settings gpu', () => { testDirectlyOnKernelViaSettings([ { name: 'native', source: `float native(float value) { return 1.0 + value; }` } ], 'gpu') }); (GPU.isWebGLSupported ? test : skip)('via settings webgl', () => { testDirectlyOnKernelViaSettings([ { name: 'native', source: `float native(float value) { return 1.0 + value; }` } ], 'webgl') }); (GPU.isWebGL2Supported ? test : skip)('via settings webgl2', () => { testDirectlyOnKernelViaSettings([ { name: 'native', source: `float native(float value) { return 1.0 + value; }` } ], 'webgl2') }); (GPU.isHeadlessGLSupported ? test : skip)('via settings headlessgl', () => { testDirectlyOnKernelViaSettings([ { name: 'native', source: `float native(float value) { return 1.0 + value; }` } ], 'headlessgl') }); test('via settings cpu', () => { testDirectlyOnKernelViaSettings([ { name: 'native', source: `function native(value) { return 1.0 + value; }`, returnType: 'Float' } ], 'cpu') }); describe('features: Adding nativeFunctions directly on kernel'); /** * * @param {IGPUNativeFunction[]} nativeFunctions * @param {GPUMode|GPUInternalMode} [mode] */ function testDirectlyOnKernelViaMethod(nativeFunctions, mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function (v) { return native(v[this.thread.x]); }, { output: [1] }) .setNativeFunctions(nativeFunctions); assert.equal(kernel([1])[0], 2); gpu.destroy(); } test('via method auto', () => { testDirectlyOnKernelViaMethod([ { name: 'native', source: `float native(float value) { return 1.0 + value; }` } ]) }); test('via method gpu', () => { testDirectlyOnKernelViaMethod([ { name: 'native', source: `float native(float value) { return 1.0 + value; }` } ], 'gpu') }); (GPU.isWebGLSupported ? test : skip)('via method webgl', () => { testDirectlyOnKernelViaMethod([ { name: 'native', source: `float native(float value) { return 1.0 + value; }` } ], 'webgl') }); (GPU.isWebGL2Supported ? test : skip)('via method webgl2', () => { testDirectlyOnKernelViaMethod([ { name: 'native', source: `float native(float value) { return 1.0 + value; }` } ], 'webgl2') }); (GPU.isHeadlessGLSupported ? test : skip)('via method headlessgl', () => { testDirectlyOnKernelViaMethod([ { name: 'native', source: `float native(float value) { return 1.0 + value; }` } ], 'headlessgl') }); test('via method cpu', () => { testDirectlyOnKernelViaMethod([ { name: 'native', source: `function native(value) { return 1.0 + value; }`, returnType: 'Float' } ], 'cpu') }); function testSetNativeFunctionsFromArrayOnGPU(nativeFunction, mode) { const gpu = new GPU({ mode }); assert.equal(gpu.setNativeFunctions([nativeFunction]), gpu); const kernel = gpu.createKernel(function() { return custom(); }, { output: [1] }); assert.equal(kernel()[0], 1); gpu.destroy(); } test('auto', () => { testSetNativeFunctionsFromArrayOnGPU({ name: 'custom', source: `float custom() { return 1.0; }` }); }); test('gpu', () => { testSetNativeFunctionsFromArrayOnGPU({ name: 'custom', source: `float custom() { return 1.0; }` },'gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testSetNativeFunctionsFromArrayOnGPU({ name: 'custom', source: `float custom() { return 1.0; }` },'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testSetNativeFunctionsFromArrayOnGPU({ name: 'custom', source: `float custom() { return 1.0; }` }, 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testSetNativeFunctionsFromArrayOnGPU({ name: 'custom', source: `float custom() { return 1.0; }` },'headlessgl'); }); test('cpu', () => { testSetNativeFunctionsFromArrayOnGPU({ name: 'custom', source: `function custom() { return 1.0; }`, returnType: 'Number' },'cpu'); }); ================================================ FILE: test/features/add-typed-functions.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: add typed functions vec2Test'); function vec2Test(mode) { const gpu = new GPU({ mode }); function typedFunction() { return [1, 2]; } gpu.addFunction(typedFunction, { returnType: 'Array(2)' }); const kernel = gpu.createKernel(function() { const result = typedFunction(); return result[0] + result[1]; }) .setOutput([1]); const result = kernel(); assert.equal(result[0], 3); gpu.destroy(); } test('Array(2) - auto', () => { vec2Test(null); }); test('Array(2) - gpu', () => { vec2Test('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Array(2) - webgl', () => { vec2Test('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Array(2) - webgl2', () => { vec2Test('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Array(2) - headlessgl', () => { vec2Test('headlessgl'); }); describe('features: add typed functions vec3Test'); function vec3Test(mode) { const gpu = new GPU({ mode }); function typedFunction() { return [1, 2, 3]; } gpu.addFunction(typedFunction, { returnType: 'Array(3)' }); const kernel = gpu.createKernel(function() { const result = typedFunction(); return result[0] + result[1] + result[2]; }) .setOutput([1]); const result = kernel(); assert.equal(result[0], 6); gpu.destroy(); } test('Array(3) - auto', () => { vec3Test(null); }); test('Array(3) - gpu', () => { vec3Test('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Array(3) - webgl', () => { vec3Test('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Array(3) - webgl2', () => { vec3Test('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Array(3) - headlessgl', () => { vec3Test('headlessgl'); }); describe('features: add typed functions vec4Test'); function vec4Test(mode) { const gpu = new GPU({ mode }); function typedFunction() { return [1, 2, 3, 4]; } gpu.addFunction(typedFunction, { returnType: 'Array(4)' }); const kernel = gpu.createKernel(function() { const result = typedFunction(); return result[0] + result[1] + result[2] + result[3]; }) .setOutput([1]); const result = kernel(); assert.equal(result[0], 10); gpu.destroy(); } test('Array(4) - auto', () => { vec4Test(null); }); test('Array(4) - gpu', () => { vec4Test('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Array(4) - webgl', () => { vec4Test('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Array(4) - webgl2', () => { vec4Test('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Array(4) - headlessgl', () => { vec4Test('headlessgl'); }); ================================================ FILE: test/features/argument-array-types.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('argument array types'); function testSinglePrecisionArray2(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[0] + value[1]; }, { output: [1], argumentTypes: { value: 'Array(2)' }, precision: 'single', }); const result = kernel(new Float32Array([1,2])); assert.equal(result[0], 3); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array(2) auto', () => { testSinglePrecisionArray2(); }); (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array(2) gpu', () => { testSinglePrecisionArray2('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision Array(2) webgl', () => { testSinglePrecisionArray2('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision Array(2) webgl2', () => { testSinglePrecisionArray2('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision Array(2) headlessgl', () => { testSinglePrecisionArray2('headlessgl'); }); test('single precision Array(2) cpu', () => { testSinglePrecisionArray2('cpu'); }); function testUnsignedPrecisionArray2(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[0] + value[1]; }, { output: [1], argumentTypes: { value: 'Array(2)' }, precision: 'unsigned', }); const result = kernel(new Float32Array([1,2])); assert.equal(result[0], 3); gpu.destroy(); } test('unsigned precision Array(2) auto', () => { testUnsignedPrecisionArray2(); }); test('unsigned precision Array(2) gpu', () => { testUnsignedPrecisionArray2('gpu'); }); (GPU.isWebGLSupported ? test : skip)('unsigned precision Array(2) webgl', () => { testUnsignedPrecisionArray2('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('unsigned precision Array(2) webgl2', () => { testUnsignedPrecisionArray2('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('unsigned precision Array(2) headlessgl', () => { testUnsignedPrecisionArray2('headlessgl'); }); test('unsigned precision Array(2) cpu', () => { testUnsignedPrecisionArray2('cpu'); }); function testSinglePrecisionArray3(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[0] + value[1] + value[2]; }, { output: [1], argumentTypes: { value: 'Array(3)' }, precision: 'single', }); const result = kernel(new Float32Array([1,2,3])); assert.equal(result[0], 6); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array(3) auto', () => { testSinglePrecisionArray3(); }); (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array(3) gpu', () => { testSinglePrecisionArray3('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision Array(3) webgl', () => { testSinglePrecisionArray3('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision Array(3) webgl2', () => { testSinglePrecisionArray3('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision Array(3) headlessgl', () => { testSinglePrecisionArray3('headlessgl'); }); test('single precision Array(3) cpu', () => { testSinglePrecisionArray3('cpu'); }); function testUnsignedPrecisionArray3(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[0] + value[1] + value[2]; }, { output: [1], argumentTypes: { value: 'Array(3)' }, precision: 'unsigned', }); const result = kernel(new Float32Array([1,2,3])); assert.equal(result[0], 6); gpu.destroy(); } test('unsigned precision Array(3) auto', () => { testUnsignedPrecisionArray3(); }); test('unsigned precision Array(3) gpu', () => { testUnsignedPrecisionArray3('gpu'); }); (GPU.isWebGLSupported ? test : skip)('unsigned precision Array(3) webgl', () => { testUnsignedPrecisionArray3('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('unsigned precision Array(3) webgl2', () => { testUnsignedPrecisionArray3('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('unsigned precision Array(3) headlessgl', () => { testUnsignedPrecisionArray3('headlessgl'); }); test('unsigned precision Array(3) cpu', () => { testUnsignedPrecisionArray3('cpu'); }); function testSinglePrecisionArray4(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[0] + value[1] + value[2] + value[3]; }, { output: [1], argumentTypes: { value: 'Array(4)' }, precision: 'single', }); const result = kernel(new Float32Array([1,2,3,4])); assert.equal(result[0], 10); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array(4) auto', () => { testSinglePrecisionArray4(); }); (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array(4) gpu', () => { testSinglePrecisionArray4('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision Array(4) webgl', () => { testSinglePrecisionArray4('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision Array(4) webgl2', () => { testSinglePrecisionArray4('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision Array(4) headlessgl', () => { testSinglePrecisionArray4('headlessgl'); }); test('single precision Array(4) cpu', () => { testSinglePrecisionArray4('cpu'); }); function testUnsignedPrecisionArray4(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[0] + value[1] + value[2] + value[3]; }, { output: [1], argumentTypes: { value: 'Array(4)' }, precision: 'unsigned', }); const result = kernel(new Float32Array([1,2,3,4])); assert.equal(result[0], 10); gpu.destroy(); } test('unsigned precision Array(4) auto', () => { testUnsignedPrecisionArray4(); }); test('unsigned precision Array(4) gpu', () => { testUnsignedPrecisionArray4('gpu'); }); (GPU.isWebGLSupported ? test : skip)('unsigned precision Array(4) webgl', () => { testUnsignedPrecisionArray4('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('unsigned precision Array(4) webgl2', () => { testUnsignedPrecisionArray4('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('unsigned precision Array(4) headlessgl', () => { testUnsignedPrecisionArray4('headlessgl'); }); test('unsigned precision Array(4) cpu', () => { testUnsignedPrecisionArray4('cpu'); }); ================================================ FILE: test/features/argument-array1d-types.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('argument array 1 types'); function testSinglePrecisionArray1D2(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.x]; }, { output: [4], argumentTypes: { value: 'Array1D(2)' }, precision: 'single', }); const value = [ new Float32Array([1,2]), new Float32Array([3,4]), new Float32Array([5,6]), new Float32Array([7,8]), ]; const result = kernel(value); assert.deepEqual(result, value); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array1D(2) auto', () => { testSinglePrecisionArray1D2(); }); (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array1D(2) gpu', () => { testSinglePrecisionArray1D2('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision Array1D(2) webgl', () => { testSinglePrecisionArray1D2('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision Array1D(2) webgl2', () => { testSinglePrecisionArray1D2('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision Array1D(2) headlessgl', () => { testSinglePrecisionArray1D2('headlessgl'); }); test('single precision Array1D(2) cpu', () => { testSinglePrecisionArray1D2('cpu'); }); function testUnsignedPrecisionArray1D2(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.x]; }, { output: [4], argumentTypes: { value: 'Array1D(2)' }, precision: 'unsigned', }); const value = [ new Float32Array([1,2]), new Float32Array([3,4]), new Float32Array([5,6]), new Float32Array([7,8]), ]; const result = kernel(value); assert.deepEqual(result, value); gpu.destroy(); } test('fallback unsigned precision Array1D(2) auto', () => { testUnsignedPrecisionArray1D2(); }); test('fallback unsigned precision Array1D(2) gpu', () => { testUnsignedPrecisionArray1D2('gpu'); }); (GPU.isWebGLSupported ? test : skip)('fallback unsigned precision Array1D(2) webgl', () => { testUnsignedPrecisionArray1D2('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('fallback unsigned precision Array1D(2) webgl2', () => { testUnsignedPrecisionArray1D2('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('fallback unsigned precision Array1D(2) headlessgl', () => { testUnsignedPrecisionArray1D2('headlessgl'); }); test('fallback unsigned precision Array1D(2) cpu', () => { testUnsignedPrecisionArray1D2('cpu'); }); function testSinglePrecisionArray1D3(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.x]; }, { output: [4], argumentTypes: { value: 'Array1D(3)' }, precision: 'single', }); const value = [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), new Float32Array([7,8,9]), new Float32Array([10,11,12]), ]; const result = kernel(value); assert.deepEqual(result, value); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array1D(3) auto', () => { testSinglePrecisionArray1D3(); }); (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array1D(3) gpu', () => { testSinglePrecisionArray1D3('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision Array1D(3) webgl', () => { testSinglePrecisionArray1D3('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision Array1D(3) webgl2', () => { testSinglePrecisionArray1D3('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision Array1D(3) headlessgl', () => { testSinglePrecisionArray1D3('headlessgl'); }); test('single precision Array1D(3) cpu', () => { testSinglePrecisionArray1D3('cpu'); }); function testUnsignedPrecisionArray1D3(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.x]; }, { output: [4], argumentTypes: { value: 'Array1D(3)' }, precision: 'unsigned', }); const value = [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), new Float32Array([7,8,9]), new Float32Array([10,11,12]), ]; const result = kernel(value); assert.deepEqual(result, value); assert.deepEqual(result, value); gpu.destroy(); } test('fallback unsigned precision Array1D(3) auto', () => { testUnsignedPrecisionArray1D3(); }); test('fallback unsigned precision Array1D(3) gpu', () => { testUnsignedPrecisionArray1D3('gpu'); }); (GPU.isWebGLSupported ? test : skip)('fallback unsigned precision Array1D(3) webgl', () => { testUnsignedPrecisionArray1D3('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('fallback unsigned precision Array1D(3) webgl2', () => { testUnsignedPrecisionArray1D3('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('fallback unsigned precision Array1D(3) headlessgl', () => { testUnsignedPrecisionArray1D3('headlessgl'); }); test('fallback unsigned precision Array1D(3) cpu', () => { testUnsignedPrecisionArray1D3('cpu'); }); function testUnsignedPrecisionArray1D4(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.x]; }, { output: [4], argumentTypes: { value: 'Array1D(4)' }, precision: 'unsigned', }); const value = [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ]; const result = kernel(value); assert.deepEqual(result, value); assert.deepEqual(result, value); gpu.destroy(); } test('fallback unsigned precision Array1D(4) auto', () => { testUnsignedPrecisionArray1D4(); }); test('fallback unsigned precision Array1D(4) gpu', () => { testUnsignedPrecisionArray1D4('gpu'); }); (GPU.isWebGLSupported ? test : skip)('fallback unsigned precision Array1D(4) webgl', () => { testUnsignedPrecisionArray1D4('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('fallback unsigned precision Array1D(4) webgl2', () => { testUnsignedPrecisionArray1D4('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('fallback unsigned precision Array1D(4) headlessgl', () => { testUnsignedPrecisionArray1D4('headlessgl'); }); test('fallback unsigned precision Array1D(4) cpu', () => { testUnsignedPrecisionArray1D4('cpu'); }); ================================================ FILE: test/features/argument-array2d-types.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('argument array 2 types'); function testSinglePrecisionArray2D2(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }, { output: [4, 2], argumentTypes: { value: 'Array2D(2)' }, precision: 'single', }); const value = [ [ new Float32Array([1,2]), new Float32Array([3,4]), new Float32Array([5,6]), new Float32Array([7,8]), ], [ new Float32Array([9,10]), new Float32Array([11,12]), new Float32Array([13,14]), new Float32Array([15,16]), ] ]; const result = kernel(value); assert.deepEqual(result, value); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array2D(2) auto', () => { testSinglePrecisionArray2D2(); }); (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array2D(2) gpu', () => { testSinglePrecisionArray2D2('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision Array2D(2) webgl', () => { testSinglePrecisionArray2D2('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision Array2D(2) webgl2', () => { testSinglePrecisionArray2D2('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision Array2D(2) headlessgl', () => { testSinglePrecisionArray2D2('headlessgl'); }); test('single precision Array2D(2) cpu', () => { testSinglePrecisionArray2D2('cpu'); }); function testUnsignedPrecisionArray2D2(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }, { output: [4, 2], argumentTypes: { value: 'Array2D(2)' }, precision: 'unsigned', }); const value = [ [ new Float32Array([1,2]), new Float32Array([3,4]), new Float32Array([5,6]), new Float32Array([7,8]), ], [ new Float32Array([9,10]), new Float32Array([11,12]), new Float32Array([13,14]), new Float32Array([15,16]), ] ]; const result = kernel(value); assert.deepEqual(result, value); gpu.destroy(); } test('fallback unsigned precision Array2D(2) auto', () => { testUnsignedPrecisionArray2D2(); }); test('fallback unsigned precision Array2D(2) gpu', () => { testUnsignedPrecisionArray2D2('gpu'); }); (GPU.isWebGLSupported ? test : skip)('fallback unsigned precision Array2D(2) webgl', () => { testUnsignedPrecisionArray2D2('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('fallback unsigned precision Array2D(2) webgl2', () => { testUnsignedPrecisionArray2D2('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('fallback unsigned precision Array(2) headlessgl', () => { testUnsignedPrecisionArray2D2('headlessgl'); }); test('fallback unsigned precision Array2D(2) cpu', () => { testUnsignedPrecisionArray2D2('cpu'); }); function testSinglePrecisionArray2D3(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }, { output: [4, 2], argumentTypes: { value: 'Array2D(3)' }, precision: 'single', }); const value = [ [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), new Float32Array([7,8,9]), new Float32Array([10,11,12]), ], [ new Float32Array([13,14,15]), new Float32Array([16,17,18]), new Float32Array([19,20,21]), new Float32Array([22,23,25]), ] ]; const result = kernel(value); assert.deepEqual(result, value); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array2D(3) auto', () => { testSinglePrecisionArray2D3(); }); (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array2D(3) gpu', () => { testSinglePrecisionArray2D3('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision Array2D(3) webgl', () => { testSinglePrecisionArray2D3('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision Array2D(3) webgl2', () => { testSinglePrecisionArray2D3('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision Array2D(3) headlessgl', () => { testSinglePrecisionArray2D3('headlessgl'); }); test('single precision Array2D(3) cpu', () => { testSinglePrecisionArray2D3('cpu'); }); function testUnsignedPrecisionArray2D3(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }, { output: [4, 2], argumentTypes: { value: 'Array2D(3)' }, precision: 'unsigned', }); const value = [ [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), new Float32Array([7,8,9]), new Float32Array([10,11,12]), ], [ new Float32Array([13,14,15]), new Float32Array([16,17,18]), new Float32Array([19,20,21]), new Float32Array([22,23,25]), ] ]; const result = kernel(value); assert.deepEqual(result, value); gpu.destroy(); } test('fallback unsigned precision Array2D(3) auto', () => { testUnsignedPrecisionArray2D3(); }); test('fallback unsigned precision Array2D(3) gpu', () => { testUnsignedPrecisionArray2D3('gpu'); }); (GPU.isWebGLSupported ? test : skip)('fallback unsigned precision Array2D(3) webgl', () => { testUnsignedPrecisionArray2D3('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('fallback unsigned precision Array2D(3) webgl2', () => { testUnsignedPrecisionArray2D3('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('fallback unsigned precision Array(3) headlessgl', () => { testUnsignedPrecisionArray2D3('headlessgl'); }); test('fallback unsigned precision Array2D(3) cpu', () => { testUnsignedPrecisionArray2D3('cpu'); }); function testSinglePrecisionArray2D4(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }, { output: [4, 2], argumentTypes: { value: 'Array2D(4)' }, precision: 'single', }); const value = [ [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ], [ new Float32Array([17,18,19,20]), new Float32Array([21,22,23,24]), new Float32Array([25,26,27,28]), new Float32Array([29,30,31,32]), ] ]; const result = kernel(value); assert.deepEqual(result, value); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array2D(4) auto', () => { testSinglePrecisionArray2D4(); }); (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array2D(4) gpu', () => { testSinglePrecisionArray2D4('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision Array2D(4) webgl', () => { testSinglePrecisionArray2D4('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision Array2D(4) webgl2', () => { testSinglePrecisionArray2D4('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision Array2D(4) headlessgl', () => { testSinglePrecisionArray2D4('headlessgl'); }); test('single precision Array2D(4) cpu', () => { testSinglePrecisionArray2D4('cpu'); }); function testUnsignedPrecisionArray2D4(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }, { output: [4, 2], argumentTypes: { value: 'Array2D(4)' }, precision: 'unsigned', }); const value = [ [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ], [ new Float32Array([17,18,19,20]), new Float32Array([21,22,23,24]), new Float32Array([25,26,27,28]), new Float32Array([29,30,31,32]), ] ]; const result = kernel(value); assert.deepEqual(result, value); gpu.destroy(); } test('fallback unsigned precision Array2D(4) auto', () => { testUnsignedPrecisionArray2D4(); }); test('fallback unsigned precision Array2D(4) gpu', () => { testUnsignedPrecisionArray2D4('gpu'); }); (GPU.isWebGLSupported ? test : skip)('fallback unsigned precision Array2D(4) webgl', () => { testUnsignedPrecisionArray2D4('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('fallback unsigned precision Array2D(4) webgl2', () => { testUnsignedPrecisionArray2D4('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('fallback unsigned precision Array(4) headlessgl', () => { testUnsignedPrecisionArray2D4('headlessgl'); }); test('fallback unsigned precision Array2D(4) cpu', () => { testUnsignedPrecisionArray2D4('cpu'); }); ================================================ FILE: test/features/argument-array3d-types.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('argument array 3 types'); function testSinglePrecisionArray3D2(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.z][this.thread.y][this.thread.x]; }, { output: [2,2,3], argumentTypes: { value: 'Array3D(2)' }, precision: 'single', }); const value = [ [ [ new Float32Array([1,2]), new Float32Array([3,4]), ],[ new Float32Array([5,6]), new Float32Array([7,8]), ] ],[ [ new Float32Array([9,10]), new Float32Array([11,12]), ],[ new Float32Array([13,14]), new Float32Array([15,16]), ] ],[ [ new Float32Array([17,18]), new Float32Array([19,20]), ],[ new Float32Array([21,22]), new Float32Array([23,24]), ] ] ]; const result = kernel(value); assert.deepEqual(result, value); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array3D(2) auto', () => { testSinglePrecisionArray3D2(); }); (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array3D(2) gpu', () => { testSinglePrecisionArray3D2('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision Array3D(2) webgl', () => { testSinglePrecisionArray3D2('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision Array3D(2) webgl2', () => { testSinglePrecisionArray3D2('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision Array3D(2) headlessgl', () => { testSinglePrecisionArray3D2('headlessgl'); }); test('single precision Array3D(2) cpu', () => { testSinglePrecisionArray3D2('cpu'); }); function testUnsignedPrecisionArray3D2(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.z][this.thread.y][this.thread.x]; }, { output: [2,2,3], argumentTypes: { value: 'Array2D(2)' }, precision: 'unsigned', }); const value = [ [ [ new Float32Array([1,2]), new Float32Array([3,4]), ],[ new Float32Array([5,6]), new Float32Array([7,8]), ] ],[ [ new Float32Array([9,10]), new Float32Array([11,12]), ],[ new Float32Array([13,14]), new Float32Array([15,16]), ] ],[ [ new Float32Array([17,18]), new Float32Array([19,20]), ],[ new Float32Array([21,22]), new Float32Array([23,24]), ] ] ]; const result = kernel(value); assert.deepEqual(result, value); gpu.destroy(); } test('fallback unsigned precision Array3D(3) auto', () => { testUnsignedPrecisionArray3D2(); }); test('fallback unsigned precision Array3D(3) gpu', () => { testUnsignedPrecisionArray3D2('gpu'); }); (GPU.isWebGLSupported ? test : skip)('fallback unsigned precision Array3D(3) webgl', () => { testUnsignedPrecisionArray3D2('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('fallback unsigned precision Array3D(3) webgl2', () => { testUnsignedPrecisionArray3D2('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('fallback unsigned precision Array3D(3) headlessgl', () => { testUnsignedPrecisionArray3D2('headlessgl'); }); test('fallback unsigned precision Array3D(3) cpu', () => { testUnsignedPrecisionArray3D2('cpu'); }); function testSinglePrecisionArray3D3(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.z][this.thread.y][this.thread.x]; }, { output: [2,2,3], argumentTypes: { value: 'Array3D(3)' }, precision: 'single', }); const value = [ [ [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), ],[ new Float32Array([7,8,9]), new Float32Array([10,11,12]), ] ],[ [ new Float32Array([13,14,15]), new Float32Array([16,17,18]), ],[ new Float32Array([19,20,21]), new Float32Array([22,23,24]), ] ],[ [ new Float32Array([25,26,27]), new Float32Array([28,29,30]), ],[ new Float32Array([31,32,33]), new Float32Array([34,35,36]), ] ] ]; const result = kernel(value); assert.deepEqual(result, value); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array3D(3) auto', () => { testSinglePrecisionArray3D3(); }); (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array3D(3) gpu', () => { testSinglePrecisionArray3D3('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision Array3D(3) webgl', () => { testSinglePrecisionArray3D3('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision Array3D(3) webgl2', () => { testSinglePrecisionArray3D3('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision Array3D(3) headlessgl', () => { testSinglePrecisionArray3D3('headlessgl'); }); test('single precision Array3D(3) cpu', () => { testSinglePrecisionArray3D3('cpu'); }); function testUnsignedPrecisionArray3D3(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.z][this.thread.y][this.thread.x]; }, { output: [2,2,3], argumentTypes: { value: 'Array2D(3)' }, precision: 'unsigned', }); const value = [ [ [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), ],[ new Float32Array([7,8,9]), new Float32Array([10,11,12]), ] ],[ [ new Float32Array([13,14,15]), new Float32Array([16,17,18]), ],[ new Float32Array([19,20,21]), new Float32Array([22,23,24]), ] ],[ [ new Float32Array([25,26,27]), new Float32Array([28,29,30]), ],[ new Float32Array([31,32,33]), new Float32Array([34,35,36]), ] ] ]; const result = kernel(value); assert.deepEqual(result, value); gpu.destroy(); } test('fallback unsigned precision Array3D(3) auto', () => { testUnsignedPrecisionArray3D3(); }); test('fallback unsigned precision Array3D(3) gpu', () => { testUnsignedPrecisionArray3D3('gpu'); }); (GPU.isWebGLSupported ? test : skip)('fallback unsigned precision Array3D(3) webgl', () => { testUnsignedPrecisionArray3D3('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('fallback unsigned precision Array3D(3) webgl2', () => { testUnsignedPrecisionArray3D3('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('fallback unsigned precision Array3D(3) headlessgl', () => { testUnsignedPrecisionArray3D3('headlessgl'); }); test('fallback unsigned precision Array3D(3) cpu', () => { testUnsignedPrecisionArray3D3('cpu'); }); function testSinglePrecisionArray3D4(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.z][this.thread.y][this.thread.x]; }, { output: [2,2,3], argumentTypes: { value: 'Array3D(4)' }, precision: 'single', }); const value = [ [ [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), ],[ new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ] ],[ [ new Float32Array([17,18,19,20]), new Float32Array([21,22,23,24]), ],[ new Float32Array([25,26,27,28]), new Float32Array([29,30,31,32]), ] ],[ [ new Float32Array([33,34,35,36]), new Float32Array([37,38,39,40]), ],[ new Float32Array([41,42,43,44]), new Float32Array([45,46,47,48]), ] ] ]; const result = kernel(value); assert.deepEqual(result, value); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array3D(4) auto', () => { testSinglePrecisionArray3D4(); }); (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array3D(4) gpu', () => { testSinglePrecisionArray3D4('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision Array3D(4) webgl', () => { testSinglePrecisionArray3D4('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision Array3D(4) webgl2', () => { testSinglePrecisionArray3D4('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision Array3D(4) headlessgl', () => { testSinglePrecisionArray3D4('headlessgl'); }); test('single precision Array3D(4) cpu', () => { testSinglePrecisionArray3D4('cpu'); }); function testUnsignedPrecisionArray3D4(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.z][this.thread.y][this.thread.x]; }, { output: [2,2,3], argumentTypes: { value: 'Array2D(3)' }, precision: 'unsigned', }); const value = [ [ [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), ],[ new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ] ],[ [ new Float32Array([17,18,19,20]), new Float32Array([21,22,23,24]), ],[ new Float32Array([25,26,27,28]), new Float32Array([29,30,31,32]), ] ],[ [ new Float32Array([33,34,35,36]), new Float32Array([37,38,39,40]), ],[ new Float32Array([41,42,43,44]), new Float32Array([45,46,47,48]), ] ] ]; const result = kernel(value); assert.deepEqual(result, value); gpu.destroy(); } test('fallback unsigned precision Array3D(4) auto', () => { testUnsignedPrecisionArray3D4(); }); test('fallback unsigned precision Array3D(4) gpu', () => { testUnsignedPrecisionArray3D4('gpu'); }); (GPU.isWebGLSupported ? test : skip)('fallback unsigned precision Array3D(4) webgl', () => { testUnsignedPrecisionArray3D4('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('fallback unsigned precision Array3D(4) webgl2', () => { testUnsignedPrecisionArray3D4('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('fallback unsigned precision Array3D(4) headlessgl', () => { testUnsignedPrecisionArray3D4('headlessgl'); }); test('fallback unsigned precision Array3D(4) cpu', () => { testUnsignedPrecisionArray3D4('cpu'); }); ================================================ FILE: test/features/arithmetic-operators.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: arithmetic operators'); function addition(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return 3 + 2; }, { output: [1] }); const result = kernel(); assert.equal(result[0], 3 + 2); gpu.destroy(); } test('addition auto', () => { addition(); }); (GPU.isGPUSupported ? test : skip)('addition gpu', () => { addition('gpu'); }); (GPU.isWebGLSupported ? test : skip)('addition webgl', () => { addition('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('addition webgl2', () => { addition('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('addition headlessgl', () => { addition('headlessgl'); }); test('addition cpu', () => { addition('cpu'); }); function subtraction(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return 3 - 2; }, { output: [1] }); const result = kernel(); assert.equal(result[0], 3 - 2); gpu.destroy(); } test('subtraction auto', () => { subtraction(); }); (GPU.isGPUSupported ? test : skip)('subtraction gpu', () => { subtraction('gpu'); }); (GPU.isWebGLSupported ? test : skip)('subtraction webgl', () => { subtraction('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('subtraction webgl2', () => { subtraction('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('subtraction headlessgl', () => { subtraction('headlessgl'); }); test('subtraction cpu', () => { subtraction('cpu'); }); function multiplication(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return 3 * 2; }, { output: [1] }); const result = kernel(); assert.equal(result[0], 3 * 2); gpu.destroy(); } test('multiplication auto', () => { multiplication(); }); (GPU.isGPUSupported ? test : skip)('multiplication gpu', () => { multiplication('gpu'); }); (GPU.isWebGLSupported ? test : skip)('multiplication webgl', () => { multiplication('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('multiplication webgl2', () => { multiplication('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('multiplication headlessgl', () => { multiplication('headlessgl'); }); test('multiplication cpu', () => { multiplication('cpu'); }); function exponential(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return 3 ** 2; }, { output: [1] }); const result = kernel(); assert.equal(result[0], 3 ** 2); gpu.destroy(); } test('exponential auto', () => { exponential(); }); (GPU.isGPUSupported ? test : skip)('exponential gpu', () => { exponential('gpu'); }); (GPU.isWebGLSupported ? test : skip)('exponential webgl', () => { exponential('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('exponential webgl2', () => { exponential('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('exponential headlessgl', () => { exponential('headlessgl'); }); test('exponential cpu', () => { exponential('cpu'); }); function division(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return 3 / 2; }, { output: [1] }); const result = kernel(); assert.equal(result[0], 3 / 2); gpu.destroy(); } test('division auto', () => { division(); }); (GPU.isGPUSupported ? test : skip)('division gpu', () => { division('gpu'); }); (GPU.isWebGLSupported ? test : skip)('division webgl', () => { division('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('division webgl2', () => { division('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('division headlessgl', () => { division('headlessgl'); }); test('division cpu', () => { division('cpu'); }); function modulus(mode) { const gpu = new GPU({ mode }); const kernel1 = gpu.createKernel(function() { return 3 % 2; }, { output: [1] }); assert.equal(kernel1()[0], 3 % 2); const kernel2 = gpu.createKernel(function() { return -126 % 63.5; }, { output: [1] }); assert.equal(kernel2()[0], -126 % 63.5); const kernel3 = gpu.createKernel(function() { return 126 % -63.5; }, { output: [1] }); assert.equal(kernel3()[0], 126 % -63.5); gpu.destroy(); } test('modulus auto', () => { modulus(); }); (GPU.isGPUSupported ? test : skip)('modulus gpu', () => { modulus('gpu'); }); (GPU.isWebGLSupported ? test : skip)('modulus webgl', () => { modulus('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('modulus webgl2', () => { modulus('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('modulus headlessgl', () => { modulus('headlessgl'); }); test('modulus cpu', () => { modulus('cpu'); }); function modulusVariable(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return 91 % 7; }, { output: [1] }); assert.equal(kernel(7)[0], 0); gpu.destroy(); } test('modulus variable auto', () => { modulusVariable(); }); function increment(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { let i = 3; i++; return i; }, { output: [1] }); const result = kernel(); let i = 3; i++; assert.equal(result[0], i); gpu.destroy(); } test('increment auto', () => { increment(); }); (GPU.isGPUSupported ? test : skip)('increment gpu', () => { increment('gpu'); }); (GPU.isWebGLSupported ? test : skip)('increment webgl', () => { increment('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('increment webgl2', () => { increment('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('increment headlessgl', () => { increment('headlessgl'); }); test('increment cpu', () => { increment('cpu'); }); function incrementEarlyReturn(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { let i = 3; return i++; }, { output: [1] }); const result = kernel(); let i = 3; assert.equal(result[0], i++); gpu.destroy(); } test('increment early return auto', () => { incrementEarlyReturn(); }); (GPU.isGPUSupported ? test : skip)('increment early return gpu', () => { incrementEarlyReturn('gpu'); }); (GPU.isWebGLSupported ? test : skip)('increment early return webgl', () => { incrementEarlyReturn('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('increment early return webgl2', () => { incrementEarlyReturn('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('increment early return headlessgl', () => { incrementEarlyReturn('headlessgl'); }); test('increment early return cpu', () => { incrementEarlyReturn('cpu'); }); function decrement(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { let i = 3; i--; return i; }, { output: [1] }); const result = kernel(); let i = 3; i--; assert.equal(result[0], i); gpu.destroy(); } test('decrement auto', () => { decrement(); }); (GPU.isGPUSupported ? test : skip)('decrement gpu', () => { decrement('gpu'); }); (GPU.isWebGLSupported ? test : skip)('decrement webgl', () => { decrement('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('decrement webgl2', () => { decrement('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('decrement headlessgl', () => { decrement('headlessgl'); }); test('decrement cpu', () => { decrement('cpu'); }); function decrementEarlyReturn(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { let i = 3; return i--; }, { output: [1] }); const result = kernel(); let i = 3; assert.equal(result[0], i--); gpu.destroy(); } test('decrement early return auto', () => { decrementEarlyReturn(); }); (GPU.isGPUSupported ? test : skip)('decrement early return gpu', () => { decrementEarlyReturn('gpu'); }); (GPU.isWebGLSupported ? test : skip)('decrement early return webgl', () => { decrementEarlyReturn('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('decrement early return webgl2', () => { decrementEarlyReturn('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('decrement early return headlessgl', () => { decrementEarlyReturn('headlessgl'); }); test('decrement early return cpu', () => { decrementEarlyReturn('cpu'); }); ================================================ FILE: test/features/assignment-operators.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: assignment operators'); function equal(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { let i = 3; return i; }, { output: [1] }); const result = kernel(); assert.equal(result[0], 3); gpu.destroy(); } test('equal auto', () => { equal(); }); (GPU.isGPUSupported ? test : skip)('equal gpu', () => { equal('gpu'); }); (GPU.isWebGLSupported ? test : skip)('equal webgl', () => { equal('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('equal webgl2', () => { equal('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('equal headlessgl', () => { equal('headlessgl'); }); test('equal cpu', () => { equal('cpu'); }); function plusEqual(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { let i = 3; i += 3; return i; }, { output: [1] }); const result = kernel(); let i = 3; i += 3; assert.equal(result[0], i); gpu.destroy(); } test('plus equal auto', () => { plusEqual(); }); (GPU.isGPUSupported ? test : skip)('plus equal gpu', () => { plusEqual('gpu'); }); (GPU.isWebGLSupported ? test : skip)('plus equal webgl', () => { plusEqual('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('plus equal webgl2', () => { plusEqual('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('plus equal headlessgl', () => { plusEqual('headlessgl'); }); test('plus equal cpu', () => { plusEqual('cpu'); }); function minusEqual(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { let i = 6; i -= 3; return i; }, { output: [1] }); const result = kernel(); let i = 6; i -= 3; assert.equal(result[0], i); gpu.destroy(); } test('minus equal auto', () => { minusEqual(); }); (GPU.isGPUSupported ? test : skip)('minus equal gpu', () => { minusEqual('gpu'); }); (GPU.isWebGLSupported ? test : skip)('minus equal webgl', () => { minusEqual('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('minus equal webgl2', () => { minusEqual('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('minus equal headlessgl', () => { minusEqual('headlessgl'); }); test('minus equal cpu', () => { minusEqual('cpu'); }); function multiplyEqual(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { let i = 6; i *= 3; return i; }, { output: [1] }); const result = kernel(); let i = 6; i *= 3; assert.equal(result[0], i); gpu.destroy(); } test('multiply equal auto', () => { multiplyEqual(); }); (GPU.isGPUSupported ? test : skip)('multiply equal gpu', () => { multiplyEqual('gpu'); }); (GPU.isWebGLSupported ? test : skip)('multiply equal webgl', () => { multiplyEqual('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('multiply equal webgl2', () => { multiplyEqual('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('multiply equal headlessgl', () => { multiplyEqual('headlessgl'); }); test('multiply equal cpu', () => { multiplyEqual('cpu'); }); function divideEqual(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { let i = 6; i /= 3; return i; }, { output: [1] }); const result = kernel(); let i = 6; i /= 3; assert.equal(result[0], i); gpu.destroy(); } test('divide equal auto', () => { divideEqual(); }); (GPU.isGPUSupported ? test : skip)('divide equal gpu', () => { divideEqual('gpu'); }); (GPU.isWebGLSupported ? test : skip)('divide equal webgl', () => { divideEqual('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('divide equal webgl2', () => { divideEqual('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('divide equal headlessgl', () => { divideEqual('headlessgl'); }); test('divide equal cpu', () => { divideEqual('cpu'); }); function modulusEqual(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { let i = 2; i %= 3; return i; }, { output: [1] }); const result = kernel(); let i = 2; i %= 3; assert.equal(result[0], i); gpu.destroy(); } test('modulus equal auto', () => { modulusEqual(); }); (GPU.isGPUSupported ? test : skip)('modulus equal gpu', () => { modulusEqual('gpu'); }); (GPU.isWebGLSupported ? test : skip)('modulus equal webgl', () => { modulusEqual('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('modulus equal webgl2', () => { divideEqual('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('modulus equal headlessgl', () => { modulusEqual('headlessgl'); }); test('modulus equal cpu', () => { modulusEqual('cpu'); }); function exponentialEqual(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { let i = 2; i **= 3; return i; }, { output: [1] }); const result = kernel(); let i = 2; i **= 3; assert.equal(result[0], i); gpu.destroy(); } test('exponential equal auto', () => { exponentialEqual(); }); (GPU.isGPUSupported ? test : skip)('exponential equal gpu', () => { exponentialEqual('gpu'); }); (GPU.isWebGLSupported ? test : skip)('exponential equal webgl', () => { exponentialEqual('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('exponential equal webgl2', () => { exponentialEqual('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('exponential equal headlessgl', () => { exponentialEqual('headlessgl'); }); test('exponential equal cpu', () => { exponentialEqual('cpu'); }); ================================================ FILE: test/features/basic-math.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: basic math'); function sumABTest(mode) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function(a, b) { return (a[this.thread.x] + b[this.thread.x]); }, { output : [6], mode : mode, }); assert.ok( f !== null, 'function generated test'); const a = [1, 2, 3, 5, 6, 7]; const b = [4, 5, 6, 1, 2, 3]; const res = f(a,b); const exp = [5, 7, 9, 6, 8, 10]; for(let i = 0; i < exp.length; ++i) { assert.equal(res[i], exp[i], 'Result arr idx: '+i); } gpu.destroy(); } test('sumAB auto', () => { sumABTest(null); }); test('sumAB gpu', () => { sumABTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('sumAB webgl', () => { sumABTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('sumAB webgl2', () => { sumABTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('sumAB headlessgl', () => { sumABTest('headlessgl'); }); test('sumAB cpu', () => { sumABTest('cpu'); }); function multABTest(mode) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function(a, b) { let sum = 0; sum += a[this.thread.y][0] * b[0][this.thread.x]; sum += a[this.thread.y][1] * b[1][this.thread.x]; sum += a[this.thread.y][2] * b[2][this.thread.x]; return sum; }, { output : [3, 3] }); assert.ok(f !== null, 'function generated test'); assert.deepEqual(f( [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ], [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]).map((object) => { return Array.from(object); }), [ [30, 36, 42], [66, 81, 96], [102, 126, 150] ], 'basic mult function test' ); gpu.destroy(); } test('multAB auto', () => { multABTest(null); }); test('multAB gpu', () => { multABTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('multAB webgl', () => { multABTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('multAB webgl2', () => { multABTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('multAB headlessgl', () => { multABTest('headlessgl'); }); test('multAB cpu', () => { multABTest('cpu'); }); ================================================ FILE: test/features/bitwise-operators.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('feature: bitwise operators'); function testBitwiseAndSinglePrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1, v2) { return v1 & v2; }) .setOutput([1]) .setPrecision('single'); for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { assert.equal(kernel(i, j)[0], i & j); } } gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('bitwise AND single precision auto', () => { testBitwiseAndSinglePrecision(); }); (GPU.isSinglePrecisionSupported ? test : skip)('bitwise AND single precision gpu', () => { testBitwiseAndSinglePrecision('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('bitwise AND single precision webgl', () => { testBitwiseAndSinglePrecision('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('bitwise AND single precision webgl2', () => { testBitwiseAndSinglePrecision('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('bitwise AND single precision headlessgl', () => { testBitwiseAndSinglePrecision('headlessgl'); }); test('bitwise AND single precision cpu', () => { testBitwiseAndSinglePrecision('cpu'); }); function testBitwiseAndUnsignedPrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1, v2) { return v1 & v2; }) .setOutput([1]) .setPrecision('unsigned'); for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { assert.equal(kernel(i, j)[0], i & j); } } gpu.destroy(); } test('bitwise AND unsigned precision auto', () => { testBitwiseAndUnsignedPrecision(); }); test('bitwise AND unsigned precision gpu', () => { testBitwiseAndUnsignedPrecision('gpu'); }); (GPU.isWebGLSupported ? test : skip)('bitwise AND unsigned precision webgl', () => { testBitwiseAndUnsignedPrecision('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('bitwise AND unsigned precision webgl2', () => { testBitwiseAndUnsignedPrecision('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('bitwise AND unsigned precision headlessgl', () => { testBitwiseAndUnsignedPrecision('headlessgl'); }); test('bitwise AND unsigned precision cpu', () => { testBitwiseAndUnsignedPrecision('cpu'); }); function testBitwiseOrSinglePrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1, v2) { return v1 | v2; }) .setOutput([1]) .setPrecision('single'); for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { assert.equal(kernel(i, j)[0], i | j); } } gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('bitwise OR single precision auto', () => { testBitwiseOrSinglePrecision(); }); (GPU.isSinglePrecisionSupported ? test : skip)('bitwise OR single precision gpu', () => { testBitwiseOrSinglePrecision('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('bitwise OR single precision webgl', () => { testBitwiseOrSinglePrecision('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('bitwise OR single precision webgl2', () => { testBitwiseOrSinglePrecision('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported? test : skip)('bitwise OR single precision headlessgl', () => { testBitwiseOrSinglePrecision('headlessgl'); }); test('bitwise OR single precision cpu', () => { testBitwiseOrSinglePrecision('cpu'); }); function testBitwiseOrUnsignedPrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1, v2) { return v1 | v2; }) .setOutput([1]) .setPrecision('unsigned'); for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { assert.equal(kernel(i, j)[0], i | j); } } gpu.destroy(); } test('bitwise OR unsigned precision auto', () => { testBitwiseOrUnsignedPrecision(); }); test('bitwise OR unsigned precision gpu', () => { testBitwiseOrUnsignedPrecision('gpu'); }); (GPU.isWebGLSupported ? test : skip)('bitwise OR unsigned precision webgl', () => { testBitwiseOrUnsignedPrecision('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('bitwise OR unsigned precision webgl2', () => { testBitwiseOrUnsignedPrecision('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('bitwise OR unsigned precision headlessgl', () => { testBitwiseOrUnsignedPrecision('headlessgl'); }); test('bitwise OR unsigned precision cpu', () => { testBitwiseOrUnsignedPrecision('cpu'); }); function testBitwiseXORSinglePrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1, v2) { return v1 ^ v2; }) .setOutput([1]) .setPrecision('single'); for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { assert.equal(kernel(i, j)[0], i ^ j); } } gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('bitwise XOR single precision auto', () => { testBitwiseXORSinglePrecision(); }); (GPU.isSinglePrecisionSupported ? test : skip)('bitwise XOR single precision gpu', () => { testBitwiseXORSinglePrecision('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('bitwise XOR single precision webgl', () => { testBitwiseXORSinglePrecision('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('bitwise XOR single precision webgl2', () => { testBitwiseXORSinglePrecision('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('bitwise XOR single precision headlessgl', () => { testBitwiseXORSinglePrecision('headlessgl'); }); test('bitwise XOR single precision cpu', () => { testBitwiseXORSinglePrecision('cpu'); }); function testBitwiseXORUnsignedPrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1, v2) { return v1 ^ v2; }) .setOutput([1]) .setPrecision('unsigned'); for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { assert.equal(kernel(i, j)[0], i ^ j); } } gpu.destroy(); } test('bitwise XOR unsigned precision auto', () => { testBitwiseXORUnsignedPrecision(); }); test('bitwise XOR unsigned precision gpu', () => { testBitwiseXORUnsignedPrecision('gpu'); }); (GPU.isWebGLSupported ? test : skip)('bitwise XOR unsigned precision webgl', () => { testBitwiseXORUnsignedPrecision('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('bitwise XOR unsigned precision webgl2', () => { testBitwiseXORUnsignedPrecision('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('bitwise XOR unsigned precision headlessgl', () => { testBitwiseXORUnsignedPrecision('headlessgl'); }); test('bitwise XOR unsigned precision cpu', () => { testBitwiseXORUnsignedPrecision('cpu'); }); function testBitwiseNotSinglePrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1) { return ~v1; }) .setOutput([1]) .setPrecision('single'); for (let i = 0; i < 10; i++) { assert.equal(kernel(i)[0], ~i); } gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('bitwise NOT single precision auto', () => { testBitwiseNotSinglePrecision(); }); (GPU.isSinglePrecisionSupported ? test : skip)('bitwise NOT single precision gpu', () => { testBitwiseNotSinglePrecision('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('bitwise NOT single precision webgl', () => { testBitwiseNotSinglePrecision('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('bitwise NOT single precision webgl2', () => { testBitwiseNotSinglePrecision('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('bitwise NOT single precision headlessgl', () => { testBitwiseNotSinglePrecision('headlessgl'); }); test('bitwise NOT single precision cpu', () => { testBitwiseNotSinglePrecision('cpu'); }); function testBitwiseNotUnsignedPrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1) { return ~v1; }) .setOutput([1]) .setPrecision('unsigned'); for (let i = 0; i < 10; i++) { assert.equal(kernel(i)[0], ~i); } gpu.destroy(); } test('bitwise NOT unsigned precision auto', () => { testBitwiseNotUnsignedPrecision(); }); test('bitwise NOT unsigned precision gpu', () => { testBitwiseNotUnsignedPrecision('gpu'); }); (GPU.isWebGLSupported ? test : skip)('bitwise NOT unsigned precision webgl', () => { testBitwiseNotUnsignedPrecision('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('bitwise NOT unsigned precision webgl2', () => { testBitwiseNotUnsignedPrecision('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('bitwise NOT unsigned precision headlessgl', () => { testBitwiseNotUnsignedPrecision('headlessgl'); }); test('bitwise NOT unsigned precision cpu', () => { testBitwiseNotUnsignedPrecision('cpu'); }); function testBitwiseZeroFillLeftShiftSinglePrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1, v2) { return v1 << v2; }) .setOutput([1]) .setPrecision('single'); for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { assert.equal(kernel(i, j)[0], i << j); } } gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('bitwise zero fill left shift single precision auto', () => { testBitwiseZeroFillLeftShiftSinglePrecision(); }); (GPU.isSinglePrecisionSupported ? test : skip)('bitwise zero fill left shift single precision gpu', () => { testBitwiseZeroFillLeftShiftSinglePrecision('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('bitwise zero fill left shift single precision webgl', () => { testBitwiseZeroFillLeftShiftSinglePrecision('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('bitwise zero fill left shift single precision webgl2', () => { testBitwiseZeroFillLeftShiftSinglePrecision('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('bitwise zero fill left shift single precision headlessgl', () => { testBitwiseZeroFillLeftShiftSinglePrecision('headlessgl'); }); test('bitwise zero fill left shift single precision cpu', () => { testBitwiseZeroFillLeftShiftSinglePrecision('cpu'); }); function testBitwiseZeroFillLeftShiftUnsignedPrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1, v2) { return v1 << v2; }) .setOutput([1]) .setPrecision('unsigned'); for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { assert.equal(kernel(i, j)[0], i << j); } } gpu.destroy(); } test('bitwise zero fill left shift unsigned precision auto', () => { testBitwiseZeroFillLeftShiftUnsignedPrecision(); }); test('bitwise zero fill left shift unsigned precision gpu', () => { testBitwiseZeroFillLeftShiftUnsignedPrecision('gpu'); }); (GPU.isWebGLSupported ? test : skip)('bitwise zero fill left shift unsigned precision webgl', () => { testBitwiseZeroFillLeftShiftUnsignedPrecision('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('bitwise zero fill left shift unsigned precision webgl2', () => { testBitwiseZeroFillLeftShiftUnsignedPrecision('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('bitwise zero fill left shift unsigned precision headlessgl', () => { testBitwiseZeroFillLeftShiftUnsignedPrecision('headlessgl'); }); test('bitwise zero fill left shift unsigned precision cpu', () => { testBitwiseZeroFillLeftShiftUnsignedPrecision('cpu'); }); function testBitwiseSignedRightShiftSinglePrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1, v2) { return v1 >> v2; }) .setOutput([1]) .setPrecision('single'); for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { assert.equal(kernel(i, j)[0], i >> j); } } gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('bitwise signed fill right shift single precision auto', () => { testBitwiseSignedRightShiftSinglePrecision(); }); (GPU.isSinglePrecisionSupported ? test : skip)('bitwise signed fill right shift single precision gpu', () => { testBitwiseSignedRightShiftSinglePrecision('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('bitwise signed fill right shift single precision webgl', () => { testBitwiseSignedRightShiftSinglePrecision('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('bitwise signed fill right shift single precision webgl2', () => { testBitwiseSignedRightShiftSinglePrecision('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('bitwise signed fill right shift single precision headlessgl', () => { testBitwiseSignedRightShiftSinglePrecision('headlessgl'); }); test('bitwise signed fill right shift single precision cpu', () => { testBitwiseSignedRightShiftSinglePrecision('cpu'); }); function testBitwiseSignedRightShiftUnsignedPrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1, v2) { return v1 >> v2; }) .setOutput([1]) .setPrecision('unsigned'); for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { assert.equal(kernel(i, j)[0], i >> j); } } gpu.destroy(); } test('bitwise signed fill right shift unsigned precision auto', () => { testBitwiseSignedRightShiftUnsignedPrecision(); }); test('bitwise signed fill right shift unsigned precision gpu', () => { testBitwiseSignedRightShiftUnsignedPrecision('gpu'); }); (GPU.isWebGLSupported ? test : skip)('bitwise signed fill right shift unsigned precision webgl', () => { testBitwiseSignedRightShiftUnsignedPrecision('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('bitwise signed fill right shift unsigned precision webgl2', () => { testBitwiseSignedRightShiftUnsignedPrecision('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('bitwise signed fill right shift unsigned precision headlessgl', () => { testBitwiseSignedRightShiftUnsignedPrecision('headlessgl'); }); test('bitwise signed fill right shift unsigned precision cpu', () => { testBitwiseSignedRightShiftUnsignedPrecision('cpu'); }); function testBitwiseZeroFillRightShiftSinglePrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1, v2) { return v1 >>> v2; }) .setOutput([1]) .setPrecision('single'); for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { assert.equal(kernel(i, j)[0], i >>> j); } } gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('bitwise zero fill right shift single precision auto', () => { testBitwiseZeroFillRightShiftSinglePrecision(); }); (GPU.isSinglePrecisionSupported ? test : skip)('bitwise zero fill right shift single precision gpu', () => { testBitwiseZeroFillRightShiftSinglePrecision('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('bitwise zero fill right shift single precision webgl', () => { testBitwiseZeroFillRightShiftSinglePrecision('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('bitwise zero fill right shift single precision webgl2', () => { testBitwiseZeroFillRightShiftSinglePrecision('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('bitwise zero fill right shift single precision headlessgl', () => { testBitwiseZeroFillRightShiftSinglePrecision('headlessgl'); }); test('bitwise zero fill right shift single precision cpu', () => { testBitwiseZeroFillRightShiftSinglePrecision('cpu'); }); function testBitwiseZeroFillRightShiftUnsignedPrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1, v2) { return v1 >>> v2; }) .setOutput([1]) .setPrecision('unsigned'); for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { assert.equal(kernel(i, j)[0], i >>> j); } } gpu.destroy(); } test('bitwise zero fill right shift unsigned precision auto', () => { testBitwiseZeroFillRightShiftUnsignedPrecision(); }); test('bitwise zero fill right shift unsigned precision gpu', () => { testBitwiseZeroFillRightShiftUnsignedPrecision('gpu'); }); (GPU.isWebGLSupported ? test : skip)('bitwise zero fill right shift unsigned precision webgl', () => { testBitwiseZeroFillRightShiftUnsignedPrecision('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('bitwise zero fill right shift unsigned precision webgl2', () => { testBitwiseZeroFillRightShiftUnsignedPrecision('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('bitwise zero fill right shift unsigned precision headlessgl', () => { testBitwiseZeroFillRightShiftUnsignedPrecision('headlessgl'); }); test('bitwise zero fill right shift unsigned precision cpu', () => { testBitwiseZeroFillRightShiftUnsignedPrecision('cpu'); }); ================================================ FILE: test/features/boolean-from-expression.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('feature: bitwise operators'); function testBooleanFromExpression(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { const result = 1 === 1 && 2 === 2; return result ? 1 : 0; }, { output: [1] }); assert.equal(kernel()[0], 1); gpu.destroy(); } test('auto', () => { testBooleanFromExpression(); }); test('gpu', () => { testBooleanFromExpression('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testBooleanFromExpression('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testBooleanFromExpression('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testBooleanFromExpression('headlessgl'); }); test('cpu', () => { testBooleanFromExpression('cpu'); }); ================================================ FILE: test/features/canvas.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); const { greenCanvas } = require('../browser-test-utils'); describe('features: canvas argument'); function canvasArgumentTest(mode) { const gpu = new GPU({ mode }); const canvas = greenCanvas(mode, 1, 1); const kernel = gpu.createKernel(function(canvas) { const pixel = canvas[this.thread.y][this.thread.x]; return pixel[1]; }, { output : [canvas.width, canvas.height] }); const result = kernel(canvas); assert.equal(result[0][0], 1); gpu.destroy(); } (typeof HTMLCanvasElement !== 'undefined' ? test : skip)('auto', () => { canvasArgumentTest(); }); (typeof HTMLCanvasElement !== 'undefined' ? test : skip)('gpu', () => { canvasArgumentTest('gpu'); }); (GPU.isWebGLSupported && typeof HTMLCanvasElement !== 'undefined' ? test : skip)('webgl', () => { canvasArgumentTest('webgl'); }); (GPU.isWebGL2Supported && typeof HTMLCanvasElement !== 'undefined' ? test : skip)('webgl2', () => { canvasArgumentTest('webgl2'); }); (typeof HTMLCanvasElement !== 'undefined' ? test : skip)('cpu', () => { canvasArgumentTest('cpu'); }); function canvasManuallyDefinedArgumentTest(mode) { const gpu = new GPU({ mode }); const canvas = greenCanvas(mode, 1, 1); const kernel = gpu.createKernel(function(canvas) { const pixel = canvas[this.thread.y][this.thread.x]; return pixel[1]; }, { output : [canvas.width, canvas.height], argumentTypes: { canvas: 'HTMLCanvas' } }); const result = kernel(canvas); assert.equal(result[0][0], 1); gpu.destroy(); } (typeof HTMLCanvasElement !== 'undefined' ? test : skip)('manually defined auto', () => { canvasManuallyDefinedArgumentTest(); }); (typeof HTMLCanvasElement !== 'undefined' ? test : skip)('manually defined gpu', () => { canvasManuallyDefinedArgumentTest('gpu'); }); (GPU.isWebGLSupported && typeof HTMLCanvasElement !== 'undefined' ? test : skip)('manually defined webgl', () => { canvasManuallyDefinedArgumentTest('webgl'); }); (GPU.isWebGL2Supported && typeof HTMLCanvasElement !== 'undefined' ? test : skip)('manually defined webgl2', () => { canvasManuallyDefinedArgumentTest('webgl2'); }); (typeof HTMLCanvasElement !== 'undefined' ? test : skip)('manually defined cpu', () => { canvasManuallyDefinedArgumentTest('cpu'); }); ================================================ FILE: test/features/clear-textures.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: clear textures'); function clearTexture(precision, mode) { const gpu = new GPU({ mode }); function makeTexture() { return (gpu.createKernel(function() { return this.thread.x; }, { output: [5], pipeline: true, precision }))(); } const texture = makeTexture(); assert.deepEqual(texture.toArray(), new Float32Array([0,1,2,3,4])); texture.clear(); const texture2 = makeTexture(); // put another texture in the way assert.deepEqual(texture.toArray(), new Float32Array([0,0,0,0,0])); assert.deepEqual(texture2.toArray(), new Float32Array([0,1,2,3,4])); gpu.destroy(); } test('unsigned precision auto', () => { clearTexture('unsigned'); }); (GPU.isWebGLSupported ? test : skip)('unsigned precision webgl', () => { clearTexture('unsigned', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('unsigned precision webgl2', () => { clearTexture('unsigned', 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('unsigned precision headlessgl', () => { clearTexture('unsigned', 'headlessgl'); }); (GPU.isSinglePrecisionSupported ? test : skip)('single precision auto', () => { clearTexture('single'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision webgl', () => { clearTexture('single', 'webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision webgl2', () => { clearTexture('single', 'webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision headlessgl', () => { clearTexture('single', 'headlessgl'); }); function clearClonedTexture(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return 1; }, { output: [1], pipeline: true, immutable: true }); const result = kernel(); assert.equal(result.toArray()[0], 1); const result2 = result.clone(); const result3 = result2.clone(); assert.equal(result2.toArray()[0], 1); assert.equal(result3.toArray()[0], 1); result2.clear(); assert.equal(result2.toArray()[0], 0); assert.equal(result3.toArray()[0], 1); gpu.destroy(); } test('clear cloned texture auto', () => { clearClonedTexture(); }); test('clear cloned texture gpu', () => { clearClonedTexture('gpu'); }); (GPU.isWebGLSupported ? test : skip)('clear cloned texture webgl', () => { clearClonedTexture('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('clear cloned texture webgl2', () => { clearClonedTexture('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('clear cloned texture headlessgl', () => { clearClonedTexture('headlessgl'); }); ================================================ FILE: test/features/clone-textures.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: clone textures'); function copy1DTexture(precision, mode) { const gpu = new GPU({ mode }); function makeTexture() { return (gpu.createKernel(function() { return this.thread.x; }, { output: [5], pipeline: true, precision }))(); } const texture = makeTexture(); const clone = texture.clone(); assert.notEqual(texture, clone); assert.equal(texture.texture, clone.texture); assert.deepEqual(texture.toArray(), clone.toArray()); gpu.destroy(); } test('1D unsigned precision auto', () => { copy1DTexture('unsigned'); }); (GPU.isWebGLSupported ? test : skip)('1D unsigned precision webgl', () => { copy1DTexture('unsigned', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('1D unsigned precision webgl2', () => { copy1DTexture('unsigned', 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('1D unsigned precision headlessgl', () => { copy1DTexture('unsigned', 'headlessgl'); }); (GPU.isSinglePrecisionSupported ? test : skip)('1D single precision auto', () => { copy1DTexture('single'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('1D single precision webgl', () => { copy1DTexture('single', 'webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('1D single precision webgl2', () => { copy1DTexture('single', 'webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('1D single precision headlessgl', () => { copy1DTexture('single', 'headlessgl'); }); function copy2DTexture(precision, mode) { const gpu = new GPU({ mode }); function makeTexture() { return (gpu.createKernel(function() { return this.thread.x + (this.thread.y * this.output.x); }, { output: [5, 5], pipeline: true, precision }))(); } const texture = makeTexture(); const clone = texture.clone(); assert.notEqual(texture, clone); assert.equal(texture.texture, clone.texture); assert.deepEqual(texture.toArray(), clone.toArray()); gpu.destroy(); } test('2D unsigned precision auto', () => { copy2DTexture('unsigned'); }); (GPU.isWebGLSupported ? test : skip)('2D unsigned precision webgl', () => { copy2DTexture('unsigned', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('2D unsigned precision webgl2', () => { copy2DTexture('unsigned', 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('2D unsigned precision headlessgl', () => { copy2DTexture('unsigned', 'headlessgl'); }); (GPU.isSinglePrecisionSupported ? test : skip)('2D single precision auto', () => { copy2DTexture('single'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('2D single precision webgl', () => { copy2DTexture('single', 'webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('2D single precision webgl2', () => { copy2DTexture('single', 'webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('2D single precision headlessgl', () => { copy2DTexture('single', 'headlessgl'); }); function copy3DTexture(precision, mode) { const gpu = new GPU({ mode }); function makeTexture() { return (gpu.createKernel(function() { return this.thread.x + (this.thread.y * this.output.x) * (this.output.x * this.output.y * this.thread.z); }, { output: [5, 5, 5], pipeline: true, precision }))(); } const texture = makeTexture(); const clone = texture.clone(); assert.notEqual(texture, clone); assert.equal(texture.texture, clone.texture); assert.deepEqual(texture.toArray(), clone.toArray()); gpu.destroy(); } test('3D unsigned precision auto', () => { copy3DTexture('unsigned'); }); (GPU.isWebGLSupported ? test : skip)('3D unsigned precision webgl', () => { copy3DTexture('unsigned', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('3D unsigned precision webgl2', () => { copy3DTexture('unsigned', 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('3D unsigned precision headlessgl', () => { copy3DTexture('unsigned', 'headlessgl'); }); (GPU.isSinglePrecisionSupported ? test : skip)('3D single precision auto', () => { copy3DTexture('single'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('3D single precision webgl', () => { copy3DTexture('single', 'webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('3D single precision webgl2', () => { copy3DTexture('single', 'webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('3D single precision headlessgl', () => { copy3DTexture('single', 'headlessgl'); }); ================================================ FILE: test/features/combine-kernels.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: combine kernels'); function combineKernels(mode) { const gpu = new GPU({ mode }); const kernel1 = gpu.createKernel(function(a, b) { return a[this.thread.x] + b[this.thread.x]; }, { output: [5] }); const kernel2 = gpu.createKernel(function(c, d) { return c[this.thread.x] * d[this.thread.x]; }, { output: [5] }); const superKernel = gpu.combineKernels(kernel1, kernel2, function(array1, array2, array3) { return kernel2(kernel1(array1, array2), array3); }); const result = superKernel([1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]); assert.deepEqual(Array.from(result), [2, 8, 18, 32, 50]); gpu.destroy() } test('combine kernel auto', () => { combineKernels(); }); test('combine kernel gpu', () => { combineKernels('gpu'); }); (GPU.isWebGLSupported ? test : skip)('combine kernel webgl', () => { combineKernels('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('combine kernel webgl2', () => { combineKernels('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('combine kernel headlessgl', () => { combineKernels('headlessgl'); }); test('combine kernel cpu', () => { combineKernels('cpu'); }); function combineKernelsSinglePrecision(mode) { const gpu = new GPU({ mode }); const kernel1 = gpu.createKernel(function(a, b) { return a[this.thread.x] + b[this.thread.x]; }, { output: [5], precision: 'single' }); const kernel2 = gpu.createKernel(function(c, d) { return c[this.thread.x] * d[this.thread.x]; }, { output: [5], precision: 'single' }); const superKernel = gpu.combineKernels(kernel1, kernel2, function(array1, array2, array3) { return kernel2(kernel1(array1, array2), array3); }); const result = superKernel([1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]); assert.deepEqual(Array.from(result), [2, 8, 18, 32, 50]); gpu.destroy() } (GPU.isSinglePrecisionSupported ? test : skip)('combine kernel single precision auto', () => { combineKernelsSinglePrecision(); }); (GPU.isSinglePrecisionSupported ? test : skip)('combine kernel single precision gpu', () => { combineKernelsSinglePrecision('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('combine kernel single precision webgl', () => { combineKernelsSinglePrecision('webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('combine kernel single precision webgl2', () => { combineKernelsSinglePrecision('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('combine kernel single precision headlessgl', () => { combineKernelsSinglePrecision('headlessgl'); }); test('combine kernel single precision cpu', () => { combineKernelsSinglePrecision('cpu'); }); function combineKernelsOptimizeFloatMemory(mode) { const gpu = new GPU({ mode }); const kernel1 = gpu.createKernel(function(a, b) { return a[this.thread.x] + b[this.thread.x]; }, { output: [5], precision: 'single', optimizeFloatMemory: true, }); const kernel2 = gpu.createKernel(function(c, d) { return c[this.thread.x] * d[this.thread.x]; }, { output: [5], precision: 'single', optimizeFloatMemory: true, }); const superKernel = gpu.combineKernels(kernel1, kernel2, function(array1, array2, array3) { return kernel2(kernel1(array1, array2), array3); }); const result = superKernel([1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]); assert.deepEqual(Array.from(result), [2, 8, 18, 32, 50]); gpu.destroy() } (GPU.isSinglePrecisionSupported ? test : skip)('combine kernel float textures auto', () => { combineKernelsOptimizeFloatMemory(); }); (GPU.isSinglePrecisionSupported ? test : skip)('combine kernel float textures gpu', () => { combineKernelsOptimizeFloatMemory('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('combine kernel float textures webgl', () => { combineKernelsOptimizeFloatMemory('webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('combine kernel float textures webgl2', () => { combineKernelsOptimizeFloatMemory('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('combine kernel float textures headlessgl', () => { combineKernelsOptimizeFloatMemory('headlessgl'); }); test('combine kernel float textures cpu', () => { combineKernelsOptimizeFloatMemory('cpu'); }); ================================================ FILE: test/features/constants-array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: constants array'); function feature(mode) { const gpu = new GPU({ mode }); const array = [200, 200]; const tryConst = gpu.createKernel(function() { return this.constants.array[this.thread.x]; }, { constants: { array }, output: [2] }); const result = tryConst(); assert.deepEqual(Array.from(result), [200, 200], 'array constant passed test'); gpu.destroy(); } test('auto', () => { feature(null); }); test('gpu', () => { feature('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { feature('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { feature('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { feature('headlessgl'); }); test('arrayConstantTest cpu', () => { feature('cpu'); }); ================================================ FILE: test/features/constants-bool.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('features: constants bool'); function boolTrueConstantTest(mode) { const gpu = new GPU({ mode }); const bool = true; const tryConst = gpu.createKernel( function() { return this.constants.bool ? 1 : 0; }, { constants: { bool }, output: [1] }, ); const result = tryConst(); assert.equal(result[0], 1, 'bool constant passed test'); gpu.destroy(); } test('true auto', () => { boolTrueConstantTest(null); }); test('true gpu', () => { boolTrueConstantTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('true webgl', () => { boolTrueConstantTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('true webgl2', () => { boolTrueConstantTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('true headlessgl', () => { boolTrueConstantTest('headlessgl'); }); test('true cpu', () => { boolTrueConstantTest('cpu'); }); function boolFalseConstantTest(mode) { const gpu = new GPU({ mode }); const bool = false; const tryConst = gpu.createKernel( function() { return this.constants.bool ? 1 : 0; }, { constants: { bool }, output: [1] }, ); const result = tryConst(); assert.equal(result[0], 0, 'bool constant passed test'); gpu.destroy(); } test('false auto', () => { boolFalseConstantTest(null); }); test('false gpu', () => { boolFalseConstantTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('false webgl', () => { boolFalseConstantTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('false webgl2', () => { boolFalseConstantTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('false headlessgl', () => { boolFalseConstantTest('headlessgl'); }); test('false cpu', () => { boolFalseConstantTest('cpu'); }); ================================================ FILE: test/features/constants-canvas.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); const { greenCanvas } = require('../browser-test-utils'); describe('features: constants canvas'); function canvasConstantTest(mode) { const gpu = new GPU({ mode }); const canvas = greenCanvas(mode, 1, 1); const kernel = gpu.createKernel( function() { const pixel = this.constants.canvas[this.thread.y][this.thread.x]; return pixel.g; }, { constants: { canvas }, output: [1, 1], } ); const result = kernel(); const test = result[0][0] > 0; assert.ok(test, 'image constant passed test'); gpu.destroy(); } (typeof HTMLCanvasElement !== 'undefined' ? test : skip)('auto', () => { canvasConstantTest(null); }); (typeof HTMLCanvasElement !== 'undefined' ? test : skip)('gpu', () => { canvasConstantTest('gpu'); }); (GPU.isWebGLSupported && typeof HTMLCanvasElement !== 'undefined' ? test : skip)('webgl', () => { canvasConstantTest('webgl'); }); (GPU.isWebGL2Supported && typeof HTMLCanvasElement !== 'undefined' ? test : skip)('webgl2', () => { canvasConstantTest('webgl2'); }); (typeof HTMLCanvasElement !== 'undefined' ? test : skip)('cpu', () => { canvasConstantTest('cpu'); }); ================================================ FILE: test/features/constants-float.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('features: constants float'); function floatConstantTest(mode) { const gpu = new GPU({ mode }); const float = 200.01; const tryConst = gpu.createKernel( function() { return this.constants.float; }, { constants: { float }, output: [2] }, ); const result = tryConst(); const match = new Float32Array([200.01, 200.01]); const test = ( result[0].toFixed(1) === match[0].toFixed(1) && result[1].toFixed(1) === match[1].toFixed(1) ); assert.ok(test, 'float constant passed test'); gpu.destroy(); } test('auto', () => { floatConstantTest(null); }); test('gpu', () => { floatConstantTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { floatConstantTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { floatConstantTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { floatConstantTest('headlessgl'); }); test('cpu', () => { floatConstantTest('cpu'); }); ================================================ FILE: test/features/constants-image-array.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU, WebGLKernel } = require('../../src'); describe('features: constants image array'); function feature(mode, done) { const gpu = new GPU({ mode }); const image = new Image(); const imageArray = [image, image]; function fn() { const pixel1 = this.constants.imageArray[0][this.thread.y][this.thread.x]; const pixel2 = this.constants.imageArray[1][this.thread.y][this.thread.x]; let color = 0; if (this.thread.z === 0) { color = (pixel1.r + pixel2.r) / 2; } if (this.thread.z === 1) { color = (pixel1.g + pixel2.g) / 2; } if (this.thread.z === 2) { color = (pixel1.b + pixel2.b) / 2; } if (this.thread.z === 3) { color = 1; } return Math.floor(255 * color); } const settings = { constants: { imageArray }, output: [1, 1, 4] }; if (mode === 'webgl' || gpu.Kernel === WebGLKernel) { // make fail early in this exact scenario gpu.createKernel(fn, settings)(); } image.src = 'jellyfish-1.jpeg'; image.onload = () => { settings[0] = image.width; settings[1] = image.height; const tryConst = gpu.createKernel(fn, settings); const result = tryConst(); assert.ok(result[0][0][0] > 0, 'image array constant passed test'); gpu.destroy(); done(); }; } (GPU.isGPUHTMLImageArraySupported && typeof Image !== 'undefined' ? test : skip)('auto', t => { feature(null, t.async()); }); (GPU.isGPUHTMLImageArraySupported && typeof Image !== 'undefined' ? test : skip)('gpu', t => { feature('gpu', t.async()); }); (GPU.isWebGLSupported && typeof Image !== 'undefined' ? test : skip)('webgl', t => { assert.throws(() => { feature('webgl') }, 'imageArray are not compatible with webgl'); }); (GPU.isWebGL2Supported && typeof Image !== 'undefined' ? test : skip)('webgl2', t => { feature('webgl2', t.async()); }); (typeof Image !== 'undefined' ? test : skip)('cpu', t => { feature('cpu', t.async()); }); ================================================ FILE: test/features/constants-image.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('features: constants image'); function imageConstantTest(mode, done) { const gpu = new GPU({ mode }); const image = new Image(); image.src = 'jellyfish-1.jpeg'; image.onload = function() { const width = image.width; const height = image.height; const tryConst = gpu.createKernel( function() { const pixel = this.constants.image[this.thread.y][this.thread.x]; let color = 0; if (this.thread.z === 0) { color = pixel.r; } if (this.thread.z === 1) { color = pixel.g; } if (this.thread.z === 2) { color = pixel.b; } return 255 * color; }, { constants: { image }, output: [width, height, 3], } ); const result = tryConst(); const test = result[0][0][0] > 0; assert.ok(test, 'image constant passed test'); gpu.destroy(); done(); } } (typeof Image !== 'undefined' ? test : skip)('auto', t => { imageConstantTest(null, t.async()); }); (typeof Image !== 'undefined' ? test : skip)('gpu', t => { imageConstantTest('gpu', t.async()); }); (GPU.isWebGLSupported && typeof Image !== 'undefined' ? test : skip)('webgl', t => { imageConstantTest('webgl', t.async()); }); (GPU.isWebGL2Supported && typeof Image !== 'undefined' ? test : skip)('webgl2', t => { imageConstantTest('webgl2', t.async()); }); (typeof Image !== 'undefined' ? test : skip)('cpu', t => { imageConstantTest('cpu', t.async()); }); ================================================ FILE: test/features/constants-integer.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: constants integer'); function integerConstantTest(mode) { const gpu = new GPU({ mode }); const int = 200; const tryConst = gpu.createKernel( function() { return this.constants.int; }, { constants: { int } } ).setOutput([2]); const result = tryConst(); const match = new Float32Array([200, 200]); const test = (result[0] === match[0] && result[1] === match[1]); assert.ok(test, 'int constant passed test'); gpu.destroy(); } test('auto', () => { integerConstantTest(null); }); test('gpu', () => { integerConstantTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { integerConstantTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { integerConstantTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { integerConstantTest('headlessgl'); }); test('cpu', () => { integerConstantTest('cpu'); }); ================================================ FILE: test/features/constants-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: constants texture 1d'); function test1D(mode) { const gpu = new GPU({ mode }); const createTexture = gpu .createKernel(function() { return 200; }) .setOutput([2]) .setPipeline(true); const texture = createTexture(); const tryConst = gpu.createKernel( function() { return this.constants.texture[this.thread.x]; }, { constants: { texture } } ).setOutput([2]); const result = tryConst(); const expected = new Float32Array([200, 200]); assert.deepEqual(result, expected, 'texture constant passed test'); gpu.destroy(); } test('auto', () => { test1D(null); }); test('gpu', () => { test1D('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', function () { test1D('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', function () { test1D('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', function () { test1D('headlessgl'); }); test('cpu', () => { test1D('cpu'); }); describe('features: constants texture 2d'); function test2D(mode) { const gpu = new GPU({ mode }); const createTexture = gpu .createKernel(function() { return 200; }) .setOutput([2, 2]) .setPipeline(true); const texture = createTexture(); const tryConst = gpu.createKernel( function() { return this.constants.texture[this.thread.y][this.thread.x]; }, { constants: { texture } } ).setOutput([2, 2]); const result = tryConst(); const expected = [new Float32Array([200, 200]), new Float32Array([200, 200])]; assert.deepEqual(result, expected, 'texture constant passed test'); gpu.destroy(); } test('auto', () => { test2D(null); }); test('gpu', () => { test2D('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', function () { test2D('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', function () { test2D('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', function () { test2D('headlessgl'); }); test('cpu', () => { test2D('cpu'); }); describe('features: constants texture 3d'); function test3D(mode) { const gpu = new GPU({ mode }); const createTexture = gpu .createKernel(function() { return 200; }) .setOutput([2, 2, 2]) .setPipeline(true); const texture = createTexture(); const tryConst = gpu.createKernel( function() { return this.constants.texture[this.thread.z][this.thread.y][this.thread.x]; }, { constants: { texture } } ).setOutput([2, 2, 2]); const result = tryConst(); const expected = [[new Float32Array([200, 200]), new Float32Array([200, 200])],[new Float32Array([200, 200]), new Float32Array([200, 200])]]; assert.deepEqual(result, expected, 'texture constant passed test'); gpu.destroy(); } test('auto', () => { test3D(null); }); test('gpu', () => { test3D('cpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', function () { test3D('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', function () { test3D('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', function () { test3D('headlessgl'); }); test('cpu', () => { test3D('cpu'); }); ================================================ FILE: test/features/cpu-with-textures.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: CPU with Textures'); function cpuWithTexturesNumberWithSinglePrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return this.thread.x; }, { output: [2], pipeline: true, precision: 'single', }); const texture = kernel(); assert.ok(texture.toArray); assert.deepEqual(Array.from(texture.toArray()), [0, 1]); const cpu = new GPU({ mode: 'cpu' }); const cpuKernel = cpu.createKernel(function(v) { return v[this.thread.x]; }, { output: [2] }); assert.notOk(cpuKernel.kernel.textureCache); const result = cpuKernel(texture); assert.ok(cpuKernel.kernel.textureCache); assert.deepEqual(Array.from(result), [0, 1]); let calledTwice = false; texture.toArray = () => { calledTwice = true; }; assert.deepEqual(Array.from(cpuKernel(texture)), [0, 1]); assert.equal(calledTwice, false); gpu.destroy(); } (GPU.isGPUSupported && GPU.isSinglePrecisionSupported ? test : skip)('number with single precision auto', () => { cpuWithTexturesNumberWithSinglePrecision(); }); (GPU.isGPUSupported && GPU.isSinglePrecisionSupported ? test : skip)('number with single precision gpu', () => { cpuWithTexturesNumberWithSinglePrecision('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('number with single precision webgl', () => { cpuWithTexturesNumberWithSinglePrecision('webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('number with single precision webgl2', () => { cpuWithTexturesNumberWithSinglePrecision('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('number with single precision headlessgl', () => { cpuWithTexturesNumberWithSinglePrecision('headlessgl'); }); function cpuWithTexturesMemoryOptimizedNumberWithSinglePrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return this.thread.x; }, { output: [2], pipeline: true, precision: 'single', optimizeFloatMemory: true, }); const texture = kernel(); assert.ok(texture.toArray); assert.deepEqual(Array.from(texture.toArray()), [0, 1]); const cpu = new GPU({ mode: 'cpu' }); const cpuKernel = cpu.createKernel(function(v) { return v[this.thread.x]; }, { output: [2] }); assert.notOk(cpuKernel.kernel.textureCache); const result = cpuKernel(texture); assert.ok(cpuKernel.kernel.textureCache); assert.deepEqual(Array.from(result), [0, 1]); let calledTwice = false; texture.toArray = () => { calledTwice = true; }; assert.deepEqual(Array.from(cpuKernel(texture)), [0, 1]); assert.equal(calledTwice, false); gpu.destroy(); } (GPU.isGPUSupported && GPU.isSinglePrecisionSupported ? test : skip)('memory optimized number with single precision auto', () => { cpuWithTexturesMemoryOptimizedNumberWithSinglePrecision(); }); (GPU.isGPUSupported && GPU.isSinglePrecisionSupported ? test : skip)('memory optimized number with single precision gpu', () => { cpuWithTexturesMemoryOptimizedNumberWithSinglePrecision('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('memory optimized number with single precision webgl', () => { cpuWithTexturesMemoryOptimizedNumberWithSinglePrecision('webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('memory optimized number with single precision webgl2', () => { cpuWithTexturesMemoryOptimizedNumberWithSinglePrecision('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('memory optimized number with single precision headlessgl', () => { cpuWithTexturesMemoryOptimizedNumberWithSinglePrecision('headlessgl'); }); function cpuWithTexturesArray2WithSinglePrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return [this.thread.x, this.thread.x]; }, { output: [2], pipeline: true, precision: 'single', }); const texture = kernel(); assert.ok(texture.toArray); assert.deepEqual(texture.toArray().map(value => Array.from(value)), [[0,0], [1,1]]); const cpu = new GPU({ mode: 'cpu' }); const cpuKernel = cpu.createKernel(function(v) { return v[this.thread.x]; }, { output: [2] }); assert.notOk(cpuKernel.kernel.textureCache); const result = cpuKernel(texture); assert.ok(cpuKernel.kernel.textureCache); assert.deepEqual(result.map(value => Array.from(value)), [[0,0], [1,1]]); let calledTwice = false; texture.toArray = () => { calledTwice = true; }; assert.deepEqual(cpuKernel(texture).map(value => Array.from(value)), [[0,0], [1,1]]); assert.equal(calledTwice, false); gpu.destroy(); } (GPU.isGPUSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(2) with single precision auto', () => { cpuWithTexturesArray2WithSinglePrecision(); }); (GPU.isGPUSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(2) with single precision gpu', () => { cpuWithTexturesArray2WithSinglePrecision('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(2) with single precision webgl', () => { cpuWithTexturesArray2WithSinglePrecision('webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('Array(2) with single precision webgl2', () => { cpuWithTexturesArray2WithSinglePrecision('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(2) with single precision headlessgl', () => { cpuWithTexturesArray2WithSinglePrecision('headlessgl'); }); function cpuWithTexturesArray3WithSinglePrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return [this.thread.x, this.thread.x, this.thread.x]; }, { output: [2], pipeline: true, precision: 'single', }); const texture = kernel(); assert.ok(texture.toArray); assert.deepEqual(texture.toArray().map(value => Array.from(value)), [[0,0,0], [1,1,1]]); const cpu = new GPU({ mode: 'cpu' }); const cpuKernel = cpu.createKernel(function(v) { return v[this.thread.x]; }, { output: [2] }); assert.notOk(cpuKernel.kernel.textureCache); const result = cpuKernel(texture); assert.ok(cpuKernel.kernel.textureCache); assert.deepEqual(result.map(value => Array.from(value)), [[0,0,0], [1,1,1]]); let calledTwice = false; texture.toArray = () => { calledTwice = true; }; assert.deepEqual(cpuKernel(texture).map(value => Array.from(value)), [[0,0,0], [1,1,1]]); assert.equal(calledTwice, false); gpu.destroy(); } (GPU.isGPUSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(3) with single precision auto', () => { cpuWithTexturesArray3WithSinglePrecision(); }); (GPU.isGPUSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(3) with single precision gpu', () => { cpuWithTexturesArray3WithSinglePrecision('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(3) with single precision webgl', () => { cpuWithTexturesArray3WithSinglePrecision('webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('Array(3) with single precision webgl2', () => { cpuWithTexturesArray3WithSinglePrecision('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(3) with single precision headlessgl', () => { cpuWithTexturesArray3WithSinglePrecision('headlessgl'); }); function cpuWithTexturesArray4WithSinglePrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return [this.thread.x, this.thread.x, this.thread.x, this.thread.x]; }, { output: [2], pipeline: true, precision: 'single', }); const texture = kernel(); assert.ok(texture.toArray); assert.deepEqual(texture.toArray().map(value => Array.from(value)), [[0,0,0,0], [1,1,1,1]]); const cpu = new GPU({ mode: 'cpu' }); const cpuKernel = cpu.createKernel(function(v) { return v[this.thread.x]; }, { output: [2] }); assert.notOk(cpuKernel.kernel.textureCache); const result = cpuKernel(texture); assert.ok(cpuKernel.kernel.textureCache); assert.deepEqual(result.map(value => Array.from(value)), [[0,0,0,0], [1,1,1,1]]); let calledTwice = false; texture.toArray = () => { calledTwice = true; }; assert.deepEqual(cpuKernel(texture).map(value => Array.from(value)), [[0,0,0,0], [1,1,1,1]]); assert.equal(calledTwice, false); gpu.destroy(); } (GPU.isGPUSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(4) with single precision auto', () => { cpuWithTexturesArray4WithSinglePrecision(); }); (GPU.isGPUSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(4) with single precision gpu', () => { cpuWithTexturesArray4WithSinglePrecision('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(4) with single precision webgl', () => { cpuWithTexturesArray4WithSinglePrecision('webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('Array(4) with single precision webgl2', () => { cpuWithTexturesArray4WithSinglePrecision('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(4) with single precision headlessgl', () => { cpuWithTexturesArray4WithSinglePrecision('headlessgl'); }); function cpuWithTexturesNumberWithUnsignedPrecision(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return this.thread.x; }, { output: [2], pipeline: true, precision: 'unsigned', }); const texture = kernel(); assert.ok(texture.toArray); assert.deepEqual(Array.from(texture.toArray()), [0, 1]); const cpu = new GPU({ mode: 'cpu' }); const cpuKernel = cpu.createKernel(function(v) { return v[this.thread.x]; }, { output: [2] }); assert.notOk(cpuKernel.kernel.textureCache); const result = cpuKernel(texture); assert.ok(cpuKernel.kernel.textureCache); assert.deepEqual(Array.from(result), [0, 1]); let calledTwice = false; texture.toArray = () => { calledTwice = true; }; assert.deepEqual(Array.from(cpuKernel(texture)), [0, 1]); assert.equal(calledTwice, false); gpu.destroy(); } (GPU.isGPUSupported && GPU.isSinglePrecisionSupported ? test : skip)('number with unsigned precision auto', () => { cpuWithTexturesNumberWithUnsignedPrecision(); }); (GPU.isGPUSupported && GPU.isSinglePrecisionSupported ? test : skip)('number with unsigned precision gpu', () => { cpuWithTexturesNumberWithUnsignedPrecision('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('number with unsigned precision webgl', () => { cpuWithTexturesNumberWithUnsignedPrecision('webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('number with unsigned precision webgl2', () => { cpuWithTexturesNumberWithUnsignedPrecision('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('number with unsigned precision headlessgl', () => { cpuWithTexturesNumberWithUnsignedPrecision('headlessgl'); }); ================================================ FILE: test/features/create-kernel-map.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, alias } = require('../../src'); describe('features: create kernel map'); function createPropertyKernels(gpu, output) { function divide(d1, d2) { return d1 / d2; } const adder = alias('adder', function add(a1, a2) { return a1 + a2; }); return gpu.createKernelMap({ addResult: adder, divideResult: divide }, function (k1, k2, k3) { return divide(adder(k1[this.thread.x], k2[this.thread.x]), k3[this.thread.x]); }).setOutput(output); } function createArrayKernels(gpu, output) { function add(a1, a2) { return a1 + a2; } function divide(d1, d2) { return d1 / d2; } return gpu.createKernelMap([ add, divide ], function (k1, k2, k3) { return divide(add(k1[this.thread.x], k2[this.thread.x]), k3[this.thread.x]); }).setOutput(output) } function createKernel(gpu, output) { return gpu.createKernel(function (a) { return a[this.thread.x]; }).setOutput(output); } function createKernelMapObject1Dimension1Length(mode) { const gpu = new GPU({ mode }); const superKernel = createPropertyKernels(gpu, [1]); const kernel = createKernel(gpu, [1]); const output = superKernel([2], [2], [0.5]); const result = Array.from(output.result); const addResult = Array.from(kernel(output.addResult)); const divideResult = Array.from(kernel(output.divideResult)); assert.deepEqual(result, [8]); assert.deepEqual(addResult, [4]); assert.deepEqual(divideResult, [8]); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('createKernelMap object 1 dimension 1 length auto', () => { createKernelMapObject1Dimension1Length(); }); (GPU.isKernelMapSupported ? test : skip)('createKernelMap object 1 dimension 1 length gpu', () => { createKernelMapObject1Dimension1Length('gpu'); }); (GPU.isWebGLSupported ? test : skip)('createKernelMap object 1 dimension 1 length webgl', () => { createKernelMapObject1Dimension1Length('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('createKernelMap object 1 dimension 1 length webgl2', () => { createKernelMapObject1Dimension1Length('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('createKernelMap object 1 dimension 1 length headlessgl', () => { createKernelMapObject1Dimension1Length('headlessgl'); }); test('createKernelMap object 1 dimension 1 length cpu', () => { createKernelMapObject1Dimension1Length('cpu'); }); function createKernelMapArray1Dimension1Length(mode) { const gpu = new GPU({ mode }); const superKernel = createArrayKernels(gpu, [1]); const kernel = createKernel(gpu, [1]); const output = superKernel([2], [2], [0.5]); const result = Array.from(output.result); const addResult = Array.from(kernel(output[0])); const divideResult = Array.from(kernel(output[1])); assert.deepEqual(result, [8]); assert.deepEqual(addResult, [4]); assert.deepEqual(divideResult, [8]); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('createKernelMap array 1 dimension 1 length auto', () => { createKernelMapArray1Dimension1Length(); }); (GPU.isKernelMapSupported ? test : skip)('createKernelMap array 1 dimension 1 length gpu', () => { createKernelMapArray1Dimension1Length('gpu'); }); (GPU.isWebGLSupported ? test : skip)('createKernelMap array 1 dimension 1 length webgl', () => { createKernelMapArray1Dimension1Length('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('createKernelMap array 1 dimension 1 length webgl2', () => { createKernelMapArray1Dimension1Length('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('createKernelMap array 1 dimension 1 length headlessgl', () => { createKernelMapArray1Dimension1Length('headlessgl'); }); test('createKernelMap array 1 dimension 1 length cpu', () => { createKernelMapArray1Dimension1Length('cpu'); }); function createKernelMapObject1Dimension5Length(mode) { const gpu = new GPU({ mode }); const superKernel = createPropertyKernels(gpu, [5]); const kernel = createKernel(gpu, [5]); const output = superKernel([1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]); const result = Array.from(output.result); const addResult = Array.from(kernel(output.addResult)); const divideResult = Array.from(kernel(output.divideResult)); assert.deepEqual(result, [2, 2, 2, 2, 2]); assert.deepEqual(addResult, [2, 4, 6, 8, 10]); assert.deepEqual(divideResult, [2, 2, 2, 2, 2]); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('createKernelMap object 1 dimension 5 length auto', () => { createKernelMapObject1Dimension5Length(); }); (GPU.isKernelMapSupported ? test : skip)('createKernelMap object 1 dimension 5 length gpu', () => { createKernelMapObject1Dimension5Length('gpu'); }); (GPU.isWebGLSupported ? test : skip)('createKernelMap object 1 dimension 5 length webgl', () => { createKernelMapObject1Dimension5Length('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('createKernelMap object 1 dimension 5 length webgl2', () => { createKernelMapObject1Dimension5Length('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('createKernelMap object 1 dimension 5 length headlessgl', () => { createKernelMapObject1Dimension5Length('headlessgl'); }); test('createKernelMap object 1 dimension 5 length cpu', () => { createKernelMapObject1Dimension5Length('cpu'); }); function createKernelMapArrayAuto(mode) { const gpu = new GPU({mode}); const superKernel = createArrayKernels(gpu, [5]); const kernel = createKernel(gpu, [5]); const output = superKernel([1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]); const result = Array.from(output.result); const addResult = Array.from(kernel(output[0])); const divideResult = Array.from(kernel(output[1])); assert.deepEqual(result, [2, 2, 2, 2, 2]); assert.deepEqual(addResult, [2, 4, 6, 8, 10]); assert.deepEqual(divideResult, [2, 2, 2, 2, 2]); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('createKernelMap array auto', () => { createKernelMapArrayAuto(); }); (GPU.isKernelMapSupported ? test : skip)('createKernelMap array gpu', () => { createKernelMapArrayAuto('gpu'); }); (GPU.isWebGLSupported ? test : skip)('createKernelMap array webgl', () => { createKernelMapArrayAuto('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('createKernelMap array webgl2', () => { createKernelMapArrayAuto('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('createKernelMap array headlessgl', () => { createKernelMapArrayAuto('headlessgl'); }); test('createKernelMap array cpu', () => { createKernelMapArrayAuto('cpu'); }); function createKernelMap3DAuto(mode) { const gpu = new GPU({ mode }); function saveTarget(value) { return value; } const kernel = gpu.createKernelMap({ target: saveTarget }, function(value) { return saveTarget(value); }).setOutput([3,3,3]); const result = kernel(1); const target = createKernel(gpu, [3,3,3])(result.target); assert.equal(result.result.length, 3); assert.equal(result.result[0].length, 3); assert.equal(result.result[0][0].length, 3); assert.equal(target.length, 3); assert.equal(target[0].length, 3); assert.equal(target[0][0].length, 3); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('createKernelMap 3d auto', () => { createKernelMap3DAuto(); }); (GPU.isKernelMapSupported ? test : skip)('createKernelMap 3d gpu', () => { createKernelMap3DAuto('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('createKernelMap 3d webgl', () => { createKernelMap3DAuto('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('createKernelMap 3d webgl2', () => { createKernelMap3DAuto('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('createKernelMap 3d headlessgl', () => { createKernelMap3DAuto('headlessgl'); }); test('createKernelMap 3d cpu', () => { createKernelMap3DAuto('cpu'); }); function createKernelMapArray2(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernelMap( { mapFunc: function mapFunc(mapFuncVal) { return mapFuncVal; } }, function main() { const mapFuncVal = [1, 2]; mapFunc(mapFuncVal); const returnValue = [3, 4]; return returnValue; }, { output: [1], returnType: 'Array(2)', } ); const { result, mapFunc } = kernel(); assert.deepEqual(Array.from(mapFunc[0]), [1, 2]); assert.deepEqual(Array.from(result[0]), [3, 4]); gpu.destroy(); } test('createKernelMap Array(2) auto', () => { createKernelMapArray2(); }); test('createKernelMap Array(2) gpu', () => { createKernelMapArray2('gpu'); }); (GPU.isWebGLSupported ? test : skip)('createKernelMap Array(2) webgl', () => { createKernelMapArray2('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('createKernelMap Array(2) webgl2', () => { createKernelMapArray2('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('createKernelMap Array(2) headlessgl', () => { createKernelMapArray2('headlessgl'); }); test('createKernelMap Array(2) cpu', () => { createKernelMapArray2('cpu'); }); function createKernelMapArray3(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernelMap( { mapFunc: function mapFunc(mapFuncVal) { return mapFuncVal; } }, function main() { const mapFuncVal = [1, 2, 3]; mapFunc(mapFuncVal); const returnValue = [4, 5, 6]; return returnValue; }, { output: [1], returnType: 'Array(3)', } ); const { result, mapFunc } = kernel(); assert.deepEqual(Array.from(mapFunc[0]), [1, 2, 3]); assert.deepEqual(Array.from(result[0]), [4, 5, 6]); gpu.destroy(); } test('createKernelMap Array(3) auto', () => { createKernelMapArray3(); }); test('createKernelMap Array(3) gpu', () => { createKernelMapArray3('gpu'); }); (GPU.isWebGLSupported ? test : skip)('createKernelMap Array(3) webgl', () => { createKernelMapArray3('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('createKernelMap Array(3) webgl2', () => { createKernelMapArray3('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('createKernelMap Array(3) headlessgl', () => { createKernelMapArray3('headlessgl'); }); test('createKernelMap Array(3) cpu', () => { createKernelMapArray3('cpu'); }); function createKernelMapArray4(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernelMap( { mapFunc: function mapFunc(mapFuncVal) { return mapFuncVal; } }, function main() { const mapFuncVal = [1, 2, 3, 4]; mapFunc(mapFuncVal); const returnValue = [5, 6, 7, 8]; return returnValue; }, { output: [1], returnType: 'Array(4)', } ); const { result, mapFunc } = kernel(); assert.deepEqual(Array.from(mapFunc[0]), [1, 2, 3, 4]); assert.deepEqual(Array.from(result[0]), [5, 6, 7, 8]); gpu.destroy(); } test('createKernelMap Array(4) auto', () => { createKernelMapArray4(); }); test('createKernelMap Array(4) gpu', () => { createKernelMapArray4('gpu'); }); (GPU.isWebGLSupported ? test : skip)('createKernelMap Array(4) webgl', () => { createKernelMapArray4('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('createKernelMap Array(4) webgl2', () => { createKernelMapArray4('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('createKernelMap Array(4) headlessgl', () => { createKernelMapArray4('headlessgl'); }); test('createKernelMap Array(4) cpu', () => { createKernelMapArray4('cpu'); }); ================================================ FILE: test/features/demo.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('features: demo'); function demo(mode) { const matrixSize = 6; let a = new Array(matrixSize * matrixSize); let b = new Array(matrixSize * matrixSize); a = splitArray(fillArrayRandom(a), matrixSize); b = splitArray(fillArrayRandom(b), matrixSize); function fillArrayRandom(array) { for(let i = 0; i < array.length; i++) { array[i] = Math.random(); } return array; } function splitArray(array, part) { const result = []; for(let i = 0; i < array.length; i += part) { result.push(array.slice(i, i + part)); } return result; } const gpu = new GPU({ mode }); const multiplyMatrix = gpu.createKernel(function(a, b) { let sum = 0; for (let i = 0; i < 6; i++) { sum += a[this.thread.y][i] * b[i][this.thread.x]; } return sum; }) .setOutput([6, 6]); assert.ok( multiplyMatrix !== null, "function generated test"); assert.equal(multiplyMatrix(a, b).length, 6, "basic return function test"); gpu.destroy(); } test("auto", () => { demo(); }); test("gpu", () => { demo('gpu'); }); (GPU.isWebGLSupported ? test : skip)("webgl", function () { demo('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("webgl2", function () { demo('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)("headlessgl", function () { demo('headlessgl'); }); test("cpu", () => { demo('cpu'); }); ================================================ FILE: test/features/destroy.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU, WebGLKernel } = require('../../src'); const sinon = require('sinon'); describe('features: destroy'); function testWithoutDestroyContext(done, mode) { const gpu = new GPU({ mode }); const destroyKernel = sinon.spy(); gpu.kernels.push({ kernel: { constructor: { destroyContext: null } }, destroy: destroyKernel }); gpu.destroy(); gpu.destroy() .then(() => { assert.equal(destroyKernel.callCount, 2); assert.ok(true); done(); }); } test('without destroy context', (t) => { const done = t.async(); testWithoutDestroyContext(done); }); function testWithDestroyContext(done, mode) { const gpu = new GPU({ mode }); const destroyKernel = sinon.spy(); const destroyContextSpy = sinon.spy(); gpu.kernels.push({ kernel: { constructor: { destroyContext: destroyContextSpy } }, destroy: destroyKernel }); gpu.destroy(); gpu.destroy() .then(() => { assert.equal(destroyKernel.callCount, 2); assert.equal(destroyContextSpy.callCount, 2); assert.ok(true); done(); }); } test('with destroy context', (t) => { const done = t.async(); testWithDestroyContext(done); }); function testTexturesAreDestroyed(done, mode) { const mockTexture1 = {}; const mockTexture2 = {}; const mockTexture3 = {}; const deleteTextureMock = sinon.spy(); const mockContext = { deleteTexture: deleteTextureMock, }; const mockKernelInstance = { textureCache: [mockTexture1, mockTexture2, mockTexture3], context: mockContext, destroyExtensions: () => {}, }; mockKernelInstance.destroy = WebGLKernel.prototype.destroy.bind(mockKernelInstance); GPU.prototype.destroy.call({ kernels: [mockKernelInstance] }) .then(() => { assert.equal(deleteTextureMock.callCount, 3); assert.ok(true); done(); }); } test('textures are destroyed', (t) => { const done = t.async(); testTexturesAreDestroyed(done); }); function testKernelTextureIsDeleted(done) { const webGLTexture = {}; const mockTextureDelete = sinon.spy(); const kernelTexture = { texture: webGLTexture, delete: mockTextureDelete, }; const mockContext = {}; const mockKernelInstance = { texture: kernelTexture, textureCache: [], context: mockContext, destroyExtensions: () => {}, }; mockKernelInstance.destroy = WebGLKernel.prototype.destroy.bind(mockKernelInstance); GPU.prototype.destroy.call({ kernels: [mockKernelInstance] }) .then(() => { assert.equal(mockTextureDelete.callCount, 1); assert.ok(true); done(); }); } test('kernel.texture is deleted', (t) => { const done = t.async(); testKernelTextureIsDeleted(done); }); function testKernelMappedTexturesAreDeleted(done) { const mockGPU = { kernels: [] }; const webGLTexture1 = {}; const mockTextureDelete1 = sinon.spy(); const kernelTexture1 = { texture: webGLTexture1, delete: mockTextureDelete1, }; const webGLTexture2 = {}; const mockTextureDelete2 = sinon.spy(); const kernelTexture2 = { texture: webGLTexture2, delete: mockTextureDelete2, }; const mockContext = {}; const mockKernelInstance = { gpu: mockGPU, mappedTextures: [kernelTexture1, kernelTexture2], textureCache: [], context: mockContext, destroyExtensions: () => {}, }; mockGPU.kernels.push(mockKernelInstance); mockKernelInstance.destroy = WebGLKernel.prototype.destroy.bind(mockKernelInstance); GPU.prototype.destroy.call({ kernels: [mockKernelInstance] }) .then(() => { assert.equal(mockTextureDelete1.callCount, 1); assert.equal(mockTextureDelete2.callCount, 1); assert.equal(mockGPU.kernels.length, 0); assert.ok(true); done(); }) .catch((e) => { console.error(e); }); } test('kernel.mappedTextures are deleted', (t) => { const done = t.async(); testKernelMappedTexturesAreDeleted(done); }); test('gpu.kernels is populated and removed by kernel', () => { const gpu = new GPU(); const kernel = gpu.createKernel(function() { return 1; }); assert.equal(gpu.kernels.length, 1); assert.equal(gpu.kernels.indexOf(kernel.kernel), 0); kernel.destroy(); assert.equal(gpu.kernels.length, 0); gpu.destroy(); }); test('gpu.kernels is populated and removed by gpu', t => { const done = t.async(); const gpu = new GPU(); const kernel = gpu.createKernel(function() { return 1; }); assert.equal(gpu.kernels.length, 1); assert.equal(gpu.kernels.indexOf(kernel.kernel), 0); gpu.destroy() .then(() => { assert.equal(gpu.kernels.length, 0); done(); }); }); ================================================ FILE: test/features/destructured-assignment.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: destructured assignment'); function testObject(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { const { thread: { x, y } } = this; return x + y; }, { output: [2, 2] }); assert.deepEqual(kernel(), [new Float32Array([0, 1]), new Float32Array([1, 2])]); } test('object auto', () => { testObject(); }); test('object gpu', () => { testObject('gpu'); }); (GPU.isWebGLSupported ? test : skip)('object webgl', () => { testObject('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('object webgl2', () => { testObject('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('object headlessgl', () => { testObject('headlessgl'); }); test('object cpu', () => { testObject('cpu'); }); function testNestedObject(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { const { x, y } = this.thread; return x + y; }, { output: [2, 2] }); assert.deepEqual(kernel(), [new Float32Array([0, 1]), new Float32Array([1, 2])]); } test('nested object auto', () => { testNestedObject(); }); test('nested object gpu', () => { testNestedObject('gpu'); }); (GPU.isWebGLSupported ? test : skip)('nested object webgl', () => { testNestedObject('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('nested object webgl2', () => { testNestedObject('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('nested object headlessgl', () => { testNestedObject('headlessgl'); }); test('nested object cpu', () => { testNestedObject('cpu'); }); function testArray(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(array) { const [first, second] = array; return first + second; }, { output: [1], argumentTypes: { array: 'Array(2)' } }); assert.deepEqual(kernel([1, 2]), new Float32Array([3])); } test('array auto', () => { testArray(); }); test('array gpu', () => { testArray('gpu'); }); (GPU.isWebGLSupported ? test : skip)('array webgl', () => { testArray('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('array webgl2', () => { testArray('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('array headlessgl', () => { testArray('headlessgl'); }); test('array cpu', () => { testArray('cpu'); }); ================================================ FILE: test/features/dev-mode.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, input } = require('../../src'); describe('features: dev mode'); test('are added to GPU instance .kernels property', () => { const gpu = new GPU({ mode: 'dev' }); const kernel = gpu.createKernel(function(value) { return value; }, { output: [1] }); assert.equal(gpu.kernels.length, 1); assert.deepEqual(kernel(1), new Float32Array([1])); gpu.destroy(); }); test('works with integer', () => { const gpu = new GPU({ mode: 'dev' }); const kernel = gpu.createKernel(function(value) { return value; }, { output: [1] }); assert.deepEqual(kernel(1), new Float32Array([1])); gpu.destroy(); }); test('works with float', () => { const gpu = new GPU({ mode: 'dev' }); const kernel = gpu.createKernel(function(value) { return value; }, { output: [1] }); assert.deepEqual(kernel(1.5), new Float32Array([1.5])); gpu.destroy(); }); test('works with array', () => { const gpu = new GPU({ mode: 'dev' }); const kernel = gpu.createKernel(function(value) { return value[this.thread.x]; }, { output: [4] }); assert.deepEqual(kernel([1,2,3,4]), new Float32Array([1,2,3,4])); gpu.destroy(); }); test('works with matrix', () => { const gpu = new GPU({ mode: 'dev' }); const kernel = gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }, { output: [4, 2] }); assert.deepEqual(kernel( [ [1,2,3,4], [5,6,7,8] ] ), [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), ]); gpu.destroy(); }); test('works with cube', () => { const gpu = new GPU({ mode: 'dev' }); const kernel = gpu.createKernel(function(value) { return value[this.thread.z][this.thread.y][this.thread.x]; }, { output: [4, 2, 2] }); assert.deepEqual(kernel( [ [ [1,2,3,4], [5,6,7,8] ], [ [9,10,11,12], [13,14,15,16] ] ] ), [ [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), ],[ new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ] ]); gpu.destroy(); }); test('works with input array', () => { const gpu = new GPU({ mode: 'dev' }); const kernel = gpu.createKernel(function(value) { return value[this.thread.x]; }, { output: [4] }); assert.deepEqual(kernel(input([1,2,3,4], [4])), new Float32Array([1,2,3,4])); gpu.destroy(); }); test('works with input matrix', () => { const gpu = new GPU({ mode: 'dev' }); const kernel = gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }, { output: [4, 2] }); assert.deepEqual(kernel(input([1,2,3,4,5,6,7,8], [4, 2])), [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), ]); gpu.destroy(); }); test('works with input cube', () => { const gpu = new GPU({ mode: 'dev' }); const kernel = gpu.createKernel(function(value) { return value[this.thread.z][this.thread.y][this.thread.x]; }, { output: [4, 2, 2] }); assert.deepEqual(kernel( input([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], [4,2,2]) ), [ [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), ],[ new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ] ]); gpu.destroy(); }); test('works with texture', () => { const texture = ((new GPU()).createKernel(function (cube) { return cube[this.thread.z][this.thread.y][this.thread.x]; }, { output: [4,2,2], pipeline: true }))([ [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), ],[ new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ] ]); assert.ok(texture.constructor.name.match('Texture')); const gpu = new GPU({ mode: 'dev' }); const kernel = gpu.createKernel(function(value) { return value[this.thread.z][this.thread.y][this.thread.x]; }, { output: [4, 2, 2] }); assert.deepEqual(kernel( texture ), [ [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), ],[ new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ] ]); gpu.destroy(); }); test('works with adding functions', () => { const gpu = new GPU({ mode: 'dev' }); function addOne(value) { return value + 1; } gpu.addFunction(addOne); const kernel = gpu.createKernel(function(value) { return addOne(value); }, { output: [1] }); assert.deepEqual(kernel(1), new Float32Array([2])); gpu.destroy(); }); ================================================ FILE: test/features/dynamic-arguments.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, input } = require('../../src'); describe('features: dynamic arguments'); function testHTMLImage(done, mode) { const image1 = new Image(); const image2 = new Image(); image1.src = 'jellyfish.jpeg'; image2.src = 'jellyfish-1.jpeg'; let loadedCount = 0; image1.onload = image2.onload = () => { loadedCount++; if (loadedCount === 2) loaded(); }; function loaded() { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(image) { const pixel = image[this.thread.y][this.thread.x]; return (pixel[0] + pixel[1] + pixel[2]) / 3; }) .setDynamicArguments(true) .setDynamicOutput(true) .setOutput([276, 183]); const pixels1 = kernel(image1); kernel.setOutput([138, 91]); const pixels2 = kernel(image2); assert.ok(pixels1[0][0] > .43); assert.ok(pixels1[0][0] < .45); assert.equal(pixels1.length, image1.height); assert.equal(pixels1[0].length, image1.width); assert.ok(pixels2[0][0] > .82); assert.ok(pixels2[0][0] < .83); assert.equal(pixels2.length, image2.height); assert.equal(pixels2[0].length, image2.width); gpu.destroy(); done(); } } (typeof Image !== 'undefined' ? test : skip)('HTML Image auto', t => { testHTMLImage(t.async()); }); (typeof Image !== 'undefined' && GPU.isWebGLSupported ? test : skip)('HTML Image webgl', t => { testHTMLImage(t.async(), 'webgl'); }); (typeof Image !== 'undefined' && GPU.isWebGL2Supported ? test : skip)('HTML Image webgl2', t => { testHTMLImage(t.async(), 'webgl2'); }); (typeof Image !== 'undefined' ? test : skip)('HTML Image cpu', t => { testHTMLImage(t.async(), 'cpu'); }); function testMemoryOptimizedNumberTexture(mode) { const gpu = new GPU({ mode }); const matrix4X4 = [ [1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16], ]; const texture4X4 = ( gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }) .setOutput([4, 4]) .setPrecision('single') .setOptimizeFloatMemory(true) .setPipeline(true) )(matrix4X4); const matrix3X3 = [ [1,2,3], [4,5,6], [7,8,9] ]; const texture3X3 = ( gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }) .setOutput([3, 3]) .setPrecision('single') .setOptimizeFloatMemory(true) .setPipeline(true) )(matrix3X3); const matrix2X2 = [ [1,2], [3,4] ]; const texture2X2 = ( gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }) .setOutput([2, 2]) .setPrecision('single') .setOptimizeFloatMemory(true) .setPipeline(true) )(matrix2X2); const kernel = gpu.createKernel(function(texture) { return texture[this.thread.y][this.thread.x]; }) .setDynamicArguments(true) .setDynamicOutput(true) .setOptimizeFloatMemory(true) .setOutput([4,4]); assert.deepEqual(kernel(texture4X4), [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ]); kernel.setOutput([3, 3]); assert.deepEqual(kernel(texture3X3), [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), new Float32Array([7,8,9]), ]); kernel.setOutput([2, 2]); assert.deepEqual(kernel(texture2X2), [ new Float32Array([1,2]), new Float32Array([3,4]), ]); assert.ok(kernel.kernelArguments[0].constructor.name.match('DynamicMemoryOptimizedNumberTexture')); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('MemoryOptimizedNumberTexture (GPU only) auto', () => { testMemoryOptimizedNumberTexture(); }); (GPU.isSinglePrecisionSupported ? test : skip)('MemoryOptimizedNumberTexture (GPU only) gpu', () => { testMemoryOptimizedNumberTexture('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('MemoryOptimizedNumberTexture (GPU only) webgl', () => { testMemoryOptimizedNumberTexture('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('MemoryOptimizedNumberTexture (GPU only) webgl2', () => { testMemoryOptimizedNumberTexture('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('MemoryOptimizedNumberTexture (GPU only) headlessgl', () => { testMemoryOptimizedNumberTexture('headlessgl'); }); function testNumberTexture(mode) { const gpu = new GPU({ mode }); const matrix4X4 = [ [1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16], ]; const texture4X4 = ( gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }) .setOutput([4, 4]) .setPrecision('single') .setPipeline(true) )(matrix4X4); const matrix3X3 = [ [1,2,3], [4,5,6], [7,8,9] ]; const texture3X3 = ( gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }) .setOutput([3, 3]) .setPrecision('single') .setPipeline(true) )(matrix3X3); const matrix2X2 = [ [1,2], [3,4] ]; const texture2X2 = ( gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }) .setOutput([2, 2]) .setPrecision('single') .setPipeline(true) )(matrix2X2); const kernel = gpu.createKernel(function(texture) { return texture[this.thread.y][this.thread.x]; }) .setDynamicArguments(true) .setDynamicOutput(true) .setOutput([4,4]); assert.deepEqual(kernel(texture4X4), [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ]); kernel.setOutput([3, 3]); assert.deepEqual(kernel(texture3X3), [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), new Float32Array([7,8,9]), ]); kernel.setOutput([2, 2]); assert.deepEqual(kernel(texture2X2), [ new Float32Array([1,2]), new Float32Array([3,4]), ]); assert.ok(kernel.kernelArguments[0].constructor.name.match('NumberTexture')); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('NumberTexture (GPU only) auto', () => { testNumberTexture(); }); (GPU.isSinglePrecisionSupported ? test : skip)('NumberTexture (GPU only) gpu', () => { testNumberTexture('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('NumberTexture (GPU only) webgl', () => { testNumberTexture('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('NumberTexture (GPU only) webgl2', () => { testNumberTexture('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('NumberTexture (GPU only) headlessgl', () => { testNumberTexture('headlessgl'); }); function testMixedNumberTexture(mode) { const gpu = new GPU({ mode }); const matrix4X4 = [ [1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16], ]; const texture4X4 = ( gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }) .setOutput([4, 4]) .setPrecision('single') .setOptimizeFloatMemory(true) .setPipeline(true) )(matrix4X4); const matrix3X3 = [ [1,2,3], [4,5,6], [7,8,9] ]; const texture3X3 = ( gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }) .setOutput([3, 3]) .setPrecision('single') .setOptimizeFloatMemory(true) .setPipeline(true) )(matrix3X3); const matrix2X2 = [ [1,2], [3,4] ]; const texture2X2 = ( gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }) .setOutput([2, 2]) .setPrecision('single') .setPipeline(true) )(matrix2X2); const kernel = gpu.createKernel(function(texture) { return texture[this.thread.y][this.thread.x]; }) .setDynamicArguments(true) .setDynamicOutput(true) .setOutput([4,4]); assert.deepEqual(kernel(texture4X4), [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ]); kernel.setOutput([3, 3]); assert.deepEqual(kernel(texture3X3), [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), new Float32Array([7,8,9]), ]); kernel.setOutput([2, 2]); assert.deepEqual(kernel(texture2X2), [ new Float32Array([1,2]), new Float32Array([3,4]), ]); assert.ok(kernel.kernelArguments[0].constructor.name.match('NumberTexture')); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Mixed NumberTexture (GPU only) auto', () => { testMixedNumberTexture(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Mixed NumberTexture (GPU only) gpu', () => { testMixedNumberTexture('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Mixed NumberTexture (GPU only) webgl', () => { testMixedNumberTexture('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Mixed NumberTexture (GPU only) webgl2', () => { testMixedNumberTexture('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Mixed NumberTexture (GPU only) headlessgl', () => { testMixedNumberTexture('headlessgl'); }); function testSingleArray1D2(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return v[this.thread.x]; }, { argumentTypes: { v: 'Array1D(2)' }, dynamicArguments: true, dynamicOutput: true }); const expected1 = [ new Float32Array([1,2]), new Float32Array([3,4]), ]; kernel.setOutput([expected1.length]); assert.deepEqual(kernel(expected1), expected1); const expected2 = [ new Float32Array([1,2]), new Float32Array([3,4]), new Float32Array([5,6]), new Float32Array([7,8]), ]; kernel.setOutput([expected2.length]); assert.deepEqual(kernel(expected2), expected2); gpu.destroy(); } test('Single Array1D2 auto', () => { testSingleArray1D2(); }); test('Single Array1D2 gpu', () => { testSingleArray1D2('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Single Array1D2 webgl', () => { testSingleArray1D2('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Single Array1D2 webgl2', () => { testSingleArray1D2('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Single Array1D2 headlessgl', () => { testSingleArray1D2('headlessgl'); }); test('Single Array1D2 cpu', () => { testSingleArray1D2('cpu'); }); function testSingleArray1D3(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return v[this.thread.x]; }, { argumentTypes: { v: 'Array1D(3)' }, dynamicArguments: true, dynamicOutput: true }); const expected1 = [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), ]; kernel.setOutput([expected1.length]); assert.deepEqual(kernel(expected1), expected1); const expected2 = [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), new Float32Array([7,8,9]), new Float32Array([10,11,12]), ]; kernel.setOutput([expected2.length]); assert.deepEqual(kernel(expected2), expected2); gpu.destroy(); } test('Single Array1D3 auto', () => { testSingleArray1D3(); }); test('Single Array1D3 gpu', () => { testSingleArray1D3('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Single Array1D3 webgl', () => { testSingleArray1D3('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Single Array1D3 webgl2', () => { testSingleArray1D3('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Single Array1D3 headlessgl', () => { testSingleArray1D3('headlessgl'); }); test('Single Array1D3 cpu', () => { testSingleArray1D3('cpu'); }); function testSingleArray1D4(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return v[this.thread.x]; }, { argumentTypes: { v: 'Array1D(4)' }, dynamicArguments: true, dynamicOutput: true }); const expected1 = [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), ]; kernel.setOutput([expected1.length]); assert.deepEqual(kernel(expected1), expected1); const expected2 = [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ]; kernel.setOutput([expected2.length]); assert.deepEqual(kernel(expected2), expected2); gpu.destroy(); } test('Single Array1D4 auto', () => { testSingleArray1D4(); }); test('Single Array1D4 gpu', () => { testSingleArray1D4('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Single Array1D4 webgl', () => { testSingleArray1D4('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Single Array1D4 webgl2', () => { testSingleArray1D4('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Single Array1D4 headlessgl', () => { testSingleArray1D4('headlessgl'); }); test('Single Array1D4 cpu', () => { testSingleArray1D4('cpu'); }); function testSingleArray2D2(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return v[this.thread.y][this.thread.x]; }, { argumentTypes: { v: 'Array2D(2)' }, dynamicArguments: true, dynamicOutput: true }); const expected1 = [ [ new Float32Array([1,2]), new Float32Array([3,4]), ],[ new Float32Array([5,6]), new Float32Array([7,8]), ] ]; kernel.setOutput([expected1[0].length, expected1.length]); assert.deepEqual(kernel(expected1), expected1); const expected2 = [ [ new Float32Array([1,2]), new Float32Array([3,4]), new Float32Array([5,6]), new Float32Array([7,8]), ],[ new Float32Array([9,10]), new Float32Array([11,12]), new Float32Array([13,14]), new Float32Array([15,16]), ] ]; kernel.setOutput([expected2[0].length, expected2.length]); assert.deepEqual(kernel(expected2), expected2); gpu.destroy(); } test('Single Array2D2 auto', () => { testSingleArray2D2(); }); test('Single Array2D2 gpu', () => { testSingleArray2D2('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Single Array2D2 webgl', () => { testSingleArray2D2('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Single Array2D2 webgl2', () => { testSingleArray2D2('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Single Array2D2 headlessgl', () => { testSingleArray2D2('headlessgl'); }); (GPU.isHeadlessGLSupported ? test : skip)('Single Array2D2 cpu', () => { testSingleArray2D2('cpu'); }); function testSingleArray2D3(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return v[this.thread.y][this.thread.x]; }, { argumentTypes: { v: 'Array2D(3)' }, dynamicArguments: true, dynamicOutput: true }); const expected1 = [ [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), ],[ new Float32Array([7,8,9]), new Float32Array([10,11,12]), ] ]; kernel.setOutput([expected1[0].length, expected1.length]); assert.deepEqual(kernel(expected1), expected1); const expected2 = [ [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), new Float32Array([7,8,9]), new Float32Array([10,11,12]), ],[ new Float32Array([13,14,15]), new Float32Array([16,17,18]), new Float32Array([19,20,21]), new Float32Array([22,23,24]), ] ]; kernel.setOutput([expected2[0].length, expected2.length]); assert.deepEqual(kernel(expected2), expected2); gpu.destroy(); } test('Single Array2D3 auto', () => { testSingleArray2D3(); }); test('Single Array2D3 gpu', () => { testSingleArray2D3('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Single Array2D3 webgl', () => { testSingleArray2D3('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Single Array2D3 webgl2', () => { testSingleArray2D3('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Single Array2D3 headlessgl', () => { testSingleArray2D3('headlessgl'); }); test('Single Array2D3 cpu', () => { testSingleArray2D3('cpu'); }); function testSingleArray2D4(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return v[this.thread.y][this.thread.x]; }, { argumentTypes: { v: 'Array2D(4)' }, dynamicArguments: true, dynamicOutput: true }); const expected1 = [ [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), ],[ new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ] ]; kernel.setOutput([expected1[0].length, expected1.length]); assert.deepEqual(kernel(expected1), expected1); const expected2 = [ [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ],[ new Float32Array([17,18,19,20]), new Float32Array([21,22,23,24]), new Float32Array([25,26,27,28]), new Float32Array([29,30,31,32]), ] ]; kernel.setOutput([expected2[0].length, expected2.length]); assert.deepEqual(kernel(expected2), expected2); gpu.destroy(); } test('Single Array2D4 auto', () => { testSingleArray2D4(); }); test('Single Array2D4 gpu', () => { testSingleArray2D4('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Single Array2D4 webgl', () => { testSingleArray2D4('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Single Array2D4 webgl2', () => { testSingleArray2D4('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Single Array2D4 headlessgl', () => { testSingleArray2D4('headlessgl'); }); test('Single Array2D4 cpu', () => { testSingleArray2D4('cpu'); }); function testSingleArray3D2(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return v[this.thread.z][this.thread.y][this.thread.x]; }, { argumentTypes: { v: 'Array3D(2)' }, dynamicArguments: true, dynamicOutput: true }); const expected1 = [ [ [ new Float32Array([1,2]), new Float32Array([3,4]), ],[ new Float32Array([5,6]), new Float32Array([7,8]), ] ],[ [ new Float32Array([9,10]), new Float32Array([11,12]), ],[ new Float32Array([13,14]), new Float32Array([15,16]), ] ] ]; kernel.setOutput([expected1[0][0].length, expected1[0].length, expected1.length]); assert.deepEqual(kernel(expected1), expected1); const expected2 = [ [ [ new Float32Array([1,2]), new Float32Array([3,4]), new Float32Array([5,6]), new Float32Array([7,8]), ],[ new Float32Array([9,10]), new Float32Array([11,12]), new Float32Array([13,14]), new Float32Array([15,16]), ] ],[ [ new Float32Array([17,18]), new Float32Array([19,20]), new Float32Array([21,22]), new Float32Array([23,24]), ],[ new Float32Array([25,26]), new Float32Array([27,28]), new Float32Array([29,30]), new Float32Array([31,32]), ] ] ]; kernel.setOutput([expected2[0][0].length, expected2[0].length, expected2.length]); assert.deepEqual(kernel(expected2), expected2); gpu.destroy(); } test('Single Array3D2 auto', () => { testSingleArray3D2(); }); test('Single Array3D2 gpu', () => { testSingleArray3D2('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Single Array3D2 webgl', () => { testSingleArray3D2('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Single Array3D2 webgl2', () => { testSingleArray3D2('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Single Array3D2 headlessgl', () => { testSingleArray3D2('headlessgl'); }); test('Single Array3D2 cpu', () => { testSingleArray3D2('cpu'); }); function testSingleArray3D3(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return v[this.thread.z][this.thread.y][this.thread.x]; }, { argumentTypes: { v: 'Array3D(3)' }, dynamicArguments: true, dynamicOutput: true }); const expected1 = [ [ [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), ],[ new Float32Array([7,8,9]), new Float32Array([10,11,12]), ] ],[ [ new Float32Array([13,14,15]), new Float32Array([16,17,18]), ],[ new Float32Array([19,20,21]), new Float32Array([22,23,24]), ] ] ]; kernel.setOutput([expected1[0][0].length, expected1[0].length, expected1.length]); assert.deepEqual(kernel(expected1), expected1); const expected2 = [ [ [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), new Float32Array([7,8,9]), new Float32Array([10,11,12]), ],[ new Float32Array([13,14,15]), new Float32Array([16,17,18]), new Float32Array([19,20,21]), new Float32Array([22,23,24]), ] ],[ [ new Float32Array([25,26,27]), new Float32Array([28,29,30]), new Float32Array([31,32,33]), new Float32Array([34,35,36]), ],[ new Float32Array([37,38,39]), new Float32Array([40,41,42]), new Float32Array([43,44,45]), new Float32Array([46,47,48]), ] ] ]; kernel.setOutput([expected2[0][0].length, expected2[0].length, expected2.length]); assert.deepEqual(kernel(expected2), expected2); gpu.destroy(); } test('Single Array3D3 auto', () => { testSingleArray3D3(); }); test('Single Array3D3 gpu', () => { testSingleArray3D3('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Single Array3D3 webgl', () => { testSingleArray3D3('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Single Array3D3 webgl2', () => { testSingleArray3D3('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Single Array3D3 headlessgl', () => { testSingleArray3D3('headlessgl'); }); test('Single Array3D3 cpu', () => { testSingleArray3D3('cpu'); }); function testSingleArray3D4(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return v[this.thread.z][this.thread.y][this.thread.x]; }, { argumentTypes: { v: 'Array3D(4)' }, dynamicArguments: true, dynamicOutput: true }); const expected1 = [ [ [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), ],[ new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ] ],[ [ new Float32Array([17,18,19,20]), new Float32Array([21,22,23,24]), ],[ new Float32Array([25,26,27,28]), new Float32Array([29,30,31,32]), ] ] ]; kernel.setOutput([expected1[0][0].length, expected1[0].length, expected1.length]); assert.deepEqual(kernel(expected1), expected1); const expected2 = [ [ [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ],[ new Float32Array([17,18,19,20]), new Float32Array([21,22,23,24]), new Float32Array([25,26,27,28]), new Float32Array([29,30,31,32]), ] ],[ [ new Float32Array([33,34,35,36]), new Float32Array([37,38,39,40]), new Float32Array([41,42,43,44]), new Float32Array([45,46,47,48]), ],[ new Float32Array([49,50,51,52]), new Float32Array([53,54,56,57]), new Float32Array([58,59,60,61]), new Float32Array([62,63,64,65]), ] ] ]; kernel.setOutput([expected2[0][0].length, expected2[0].length, expected2.length]); assert.deepEqual(kernel(expected2), expected2); gpu.destroy(); } test('Single Array3D4 auto', () => { testSingleArray3D4(); }); test('Single Array3D4 gpu', () => { testSingleArray3D4('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Single Array3D4 webgl', () => { testSingleArray3D4('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Single Array3D4 webgl2', () => { testSingleArray3D4('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Single Array3D4 headlessgl', () => { testSingleArray3D4('headlessgl'); }); test('Single Array3D4 cpu', () => { testSingleArray3D4('cpu'); }); function testUnsignedPrecisionArray(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(input) { return input[this.thread.x]; }) .setPrecision('unsigned') .setDynamicArguments(true) .setDynamicOutput(true) .setOutput([5]); assert.deepEqual(kernel([1,2,3,4,5]), new Float32Array([1,2,3,4,5])); kernel.setOutput([4]); assert.deepEqual(kernel([1,2,3,4]), new Float32Array([1,2,3,4])); kernel.setOutput([3]); assert.deepEqual(kernel([1,2,3]), new Float32Array([1,2,3])); kernel.setOutput([2]); assert.deepEqual(kernel([1,2]), new Float32Array([1,2])); gpu.destroy(); } test('unsigned precision Array auto', () => { testUnsignedPrecisionArray(); }); test('unsigned precision Array gpu', () => { testUnsignedPrecisionArray('gpu'); }); (GPU.isWebGLSupported ? test : skip)('unsigned precision Array webgl', () => { testUnsignedPrecisionArray('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('unsigned precision Array webgl2', () => { testUnsignedPrecisionArray('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('unsigned precision Array headlessgl', () => { testUnsignedPrecisionArray('headlessgl'); }); test('unsigned precision Array cpu', () => { testUnsignedPrecisionArray('cpu'); }); function testSinglePrecisionArray(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(input) { return input[this.thread.x]; }) .setPrecision('single') .setDynamicArguments(true) .setDynamicOutput(true) .setOutput([5]); assert.deepEqual(kernel([1,2,3,4,5]), new Float32Array([1,2,3,4,5])); kernel.setOutput([4]); assert.deepEqual(kernel([1,2,3,4]), new Float32Array([1,2,3,4])); kernel.setOutput([3]); assert.deepEqual(kernel([1,2,3]), new Float32Array([1,2,3])); kernel.setOutput([2]); assert.deepEqual(kernel([1,2]), new Float32Array([1,2])); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array auto', () => { testSinglePrecisionArray(); }); (GPU.isSinglePrecisionSupported ? test : skip)('single precision Array gpu', () => { testSinglePrecisionArray('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision Array webgl', () => { testSinglePrecisionArray('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision Array webgl2', () => { testSinglePrecisionArray('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision Array headlessgl', () => { testSinglePrecisionArray('headlessgl'); }); test('single precision Array cpu', () => { testSinglePrecisionArray('cpu'); }); function testUnsignedPrecisionMatrix(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(input) { return input[this.thread.y][this.thread.x]; }) .setPrecision('unsigned') .setDynamicArguments(true) .setDynamicOutput(true) .setOutput([4,4]); let matrix = [ [1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16] ]; assert.deepEqual(kernel(matrix), matrix.map(row => new Float32Array(row))); kernel.setOutput([3,3]); matrix = [ [1,2,3], [4,5,6], [7,8,9] ]; assert.deepEqual(kernel(matrix), matrix.map(row => new Float32Array(row))); kernel.setOutput([2,2]); matrix = [ [1,2], [3,4] ]; assert.deepEqual(kernel(matrix), matrix.map(row => new Float32Array(row))); gpu.destroy(); } test('unsigned precision Matrix auto', () => { testUnsignedPrecisionMatrix(); }); test('unsigned precision Matrix gpu', () => { testUnsignedPrecisionMatrix('gpu'); }); (GPU.isWebGLSupported ? test : skip)('unsigned precision Matrix webgl', () => { testUnsignedPrecisionMatrix('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('unsigned precision Matrix webgl2', () => { testUnsignedPrecisionMatrix('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('unsigned precision Matrix headlessgl', () => { testUnsignedPrecisionMatrix('headlessgl'); }); test('unsigned precision Matrix cpu', () => { testUnsignedPrecisionMatrix('cpu'); }); function testSinglePrecisionMatrix(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(input) { return input[this.thread.y][this.thread.x]; }) .setDynamicArguments(true) .setDynamicOutput(true) .setOutput([4,4]); let matrix = [ [1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16] ]; assert.deepEqual(kernel(matrix), matrix.map(row => new Float32Array(row))); kernel.setOutput([3,3]); matrix = [ [1,2,3], [4,5,6], [7,8,9] ]; assert.deepEqual(kernel(matrix), matrix.map(row => new Float32Array(row))); kernel.setOutput([2,2]); matrix = [ [1,2], [3,4] ]; assert.deepEqual(kernel(matrix), matrix.map(row => new Float32Array(row))); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('single precision Matrix auto', () => { testSinglePrecisionMatrix(); }); (GPU.isSinglePrecisionSupported ? test : skip)('single precision Matrix gpu', () => { testSinglePrecisionMatrix('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision Matrix webgl', () => { testSinglePrecisionMatrix('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision Matrix webgl2', () => { testSinglePrecisionMatrix('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision Matrix headlessgl', () => { testSinglePrecisionMatrix('headlessgl'); }); test('single precision Matrix cpu', () => { testSinglePrecisionMatrix('cpu'); }); function testUnsignedPrecisionInputMatrix(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(input) { return input[this.thread.y][this.thread.x]; }) .setPrecision('unsigned') .setDynamicArguments(true) .setDynamicOutput(true) .setOutput([4,4]); let matrix = input([ 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16 ], [4, 4]); assert.deepEqual(kernel(matrix), [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]), ]); kernel.setOutput([3,3]); matrix = input([ 1,2,3, 4,5,6, 7,8,9 ], [3,3]); assert.deepEqual(kernel(matrix), [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), new Float32Array([7,8,9]) ]); kernel.setOutput([2,2]); matrix = input([ 1,2, 3,4 ], [2,2]); assert.deepEqual(kernel(matrix), [ new Float32Array([1,2]), new Float32Array([3,4]) ]); gpu.destroy(); } test('unsigned precision Input Matrix auto', () => { testUnsignedPrecisionInputMatrix(); }); test('unsigned precision Input Matrix gpu', () => { testUnsignedPrecisionInputMatrix('gpu'); }); (GPU.isWebGLSupported ? test : skip)('unsigned precision Input Matrix webgl', () => { testUnsignedPrecisionInputMatrix('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('unsigned precision Input Matrix webgl2', () => { testUnsignedPrecisionInputMatrix('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('unsigned precision Input Matrix headlessgl', () => { testUnsignedPrecisionInputMatrix('headlessgl'); }); test('unsigned precision Input Matrix cpu', () => { testUnsignedPrecisionInputMatrix('cpu'); }); function testSinglePrecisionInputMatrix(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(input) { return input[this.thread.y][this.thread.x]; }) .setDynamicArguments(true) .setDynamicOutput(true) .setOutput([4,4]); let matrix = input([ 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16 ], [4, 4]); assert.deepEqual(kernel(matrix), [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]) ]); kernel.setOutput([3,3]); matrix = input([ 1,2,3, 4,5,6, 7,8,9 ], [3, 3]); assert.deepEqual(kernel(matrix), [ new Float32Array([1,2,3]), new Float32Array([4,5,6]), new Float32Array([7,8,9]) ]); kernel.setOutput([2,2]); matrix = input([ 1,2, 3,4 ], [2,2]); assert.deepEqual(kernel(matrix), [ new Float32Array([1,2]), new Float32Array([3,4]) ]); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('single precision Input Matrix auto', () => { testSinglePrecisionInputMatrix(); }); (GPU.isSinglePrecisionSupported ? test : skip)('single precision Input Matrix gpu', () => { testSinglePrecisionInputMatrix('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision Input Matrix webgl', () => { testSinglePrecisionInputMatrix('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision Input Matrix webgl2', () => { testSinglePrecisionInputMatrix('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision Input Matrix headlessgl', () => { testSinglePrecisionInputMatrix('headlessgl'); }); test('single precision Input Matrix cpu', () => { testSinglePrecisionInputMatrix('cpu'); }); ================================================ FILE: test/features/dynamic-output.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: dynamic output'); function dynamicOutput1DGrows(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return this.output.x + this.thread.x; }, { dynamicOutput: true }); kernel.setOutput([5]); let result = kernel(); assert.equal(result.length, 5); assert.deepEqual(Array.from(result), [5,6,7,8,9]); assert.deepEqual(Array.from(kernel.output), [5]); kernel.setOutput([10]); result = kernel(); assert.equal(result.length, 10); assert.deepEqual(Array.from(result), [10,11,12,13,14,15,16,17,18,19]); assert.deepEqual(Array.from(kernel.output), [10]); gpu.destroy(); } test('dynamic output 1d grows auto', () => { dynamicOutput1DGrows(); }); test('dynamic output 1d grows gpu', () => { dynamicOutput1DGrows('gpu'); }); (GPU.isWebGLSupported ? test : skip)('dynamic output 1d grows webgl', () => { dynamicOutput1DGrows('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('dynamic output 1d grows webgl2', () => { dynamicOutput1DGrows('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('dynamic output 1d grows headlessgl', () => { dynamicOutput1DGrows('headlessgl'); }); test('dynamic output 1d grows cpu', () => { dynamicOutput1DGrows('cpu'); }); function dynamicOutput1DShrinks(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return this.output.x + this.thread.x; }, { dynamicOutput: true }); kernel.setOutput([10]); let result = kernel(); assert.equal(result.length, 10); assert.deepEqual(Array.from(result), [10,11,12,13,14,15,16,17,18,19]); assert.deepEqual(Array.from(kernel.output), [10]); kernel.setOutput([5]); result = kernel(); assert.equal(result.length, 5); assert.deepEqual(Array.from(result), [5,6,7,8,9]); assert.deepEqual(Array.from(kernel.output), [5]); gpu.destroy(); } test('dynamic output 1d shrinks auto', () => { dynamicOutput1DShrinks(); }); test('dynamic output 1d shrinks gpu', () => { dynamicOutput1DShrinks('gpu'); }); (GPU.isWebGLSupported ? test : skip)('dynamic output 1d shrinks webgl', () => { dynamicOutput1DShrinks('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('dynamic output 1d shrinks webgl2', () => { dynamicOutput1DShrinks('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('dynamic output 1d shrinks headlessgl', () => { dynamicOutput1DShrinks('headlessgl'); }); test('dynamic output 1d shrinks cpu', () => { dynamicOutput1DShrinks('cpu'); }); function dynamicOutput1DKernelMapGrows(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernelMap({ result2: function map(v) { return v; } }, function() { return map(this.output.x + this.thread.x); }, { dynamicOutput: true }); kernel.setOutput([5]); let result = kernel(); assert.equal(result.result.length, 5); assert.equal(result.result2.length, 5); assert.deepEqual(Array.from(result.result), [5,6,7,8,9]); assert.deepEqual(Array.from(result.result2), [5,6,7,8,9]); assert.deepEqual(Array.from(kernel.output), [5]); kernel.setOutput([10]); result = kernel(); assert.equal(result.result.length, 10); assert.equal(result.result2.length, 10); assert.deepEqual(Array.from(result.result), [10,11,12,13,14,15,16,17,18,19]); assert.deepEqual(Array.from(result.result2), [10,11,12,13,14,15,16,17,18,19]); assert.deepEqual(Array.from(kernel.output), [10]); gpu.destroy(); } test('dynamic output 1d kernel map grows auto', () => { dynamicOutput1DKernelMapGrows(); }); test('dynamic output 1d kernel map grows gpu', () => { dynamicOutput1DKernelMapGrows('gpu'); }); (GPU.isWebGLSupported ? test : skip)('dynamic output 1d kernel map grows webgl', () => { dynamicOutput1DKernelMapGrows('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('dynamic output 1d kernel map grows webgl2', () => { dynamicOutput1DKernelMapGrows('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('dynamic output 1d kernel map grows headlessgl', () => { dynamicOutput1DKernelMapGrows('headlessgl'); }); test('dynamic output 1d kernel map grows cpu', () => { dynamicOutput1DKernelMapGrows('cpu'); }); function dynamicOutput1DKernelMapShrinks(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernelMap({ result2: function map(v) { return v; } }, function() { return map(this.output.x + this.thread.x); }, { dynamicOutput: true }); kernel.setOutput([10]); let result = kernel(); assert.equal(result.result.length, 10); assert.equal(result.result2.length, 10); assert.deepEqual(Array.from(result.result), [10,11,12,13,14,15,16,17,18,19]); assert.deepEqual(Array.from(result.result2), [10,11,12,13,14,15,16,17,18,19]); assert.deepEqual(Array.from(kernel.output), [10]); kernel.setOutput([5]); result = kernel(); assert.equal(result.result.length, 5); assert.equal(result.result2.length, 5); assert.deepEqual(Array.from(result.result), [5,6,7,8,9]); assert.deepEqual(Array.from(result.result2), [5,6,7,8,9]); assert.deepEqual(Array.from(kernel.output), [5]); gpu.destroy(); } test('dynamic output 1d kernel map shrinks auto', () => { dynamicOutput1DKernelMapShrinks(); }); test('dynamic output 1d kernel map shrinks gpu', () => { dynamicOutput1DKernelMapShrinks('gpu'); }); (GPU.isWebGLSupported ? test : skip)('dynamic output 1d kernel map shrinks webgl', () => { dynamicOutput1DKernelMapShrinks('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('dynamic output 1d kernel map shrinks webgl2', () => { dynamicOutput1DKernelMapShrinks('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('dynamic output 1d kernel map shrinks headlessgl', () => { dynamicOutput1DKernelMapShrinks('headlessgl'); }); test('dynamic output 1d kernel map shrinks cpu', () => { dynamicOutput1DKernelMapShrinks('cpu'); }); function dynamicOutput2DGrows(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return this.output.x + this.output.y + this.thread.x + this.thread.y; }, { dynamicOutput: true }); kernel.setOutput([2,2]); let result = kernel(); assert.equal(result.length, 2); assert.deepEqual(result.map(row => Array.from(row)), [[4,5],[5,6]]); assert.deepEqual(Array.from(kernel.output), [2,2]); kernel.setOutput([3,3]); result = kernel(); assert.equal(result.length, 3); assert.deepEqual(result.map(row => Array.from(row)), [[6,7,8],[7,8,9],[8,9,10]]); assert.deepEqual(Array.from(kernel.output), [3,3]); gpu.destroy(); } test('dynamic output 2d grows auto', () => { dynamicOutput2DGrows(); }); test('dynamic output 2d grows gpu', () => { dynamicOutput2DGrows('gpu'); }); (GPU.isWebGLSupported ? test : skip)('dynamic output 2d grows webgl', () => { dynamicOutput2DGrows('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('dynamic output 2d grows webgl2', () => { dynamicOutput2DGrows('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('dynamic output 2d grows headlessgl', () => { dynamicOutput2DGrows('headlessgl'); }); test('dynamic output 2d grows cpu', () => { dynamicOutput2DGrows('cpu'); }); function dynamicOutput2DShrinks(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return this.output.x + this.output.y + this.thread.x + this.thread.y; }, { dynamicOutput: true }); kernel.setOutput([3,3]); let result = kernel(); assert.equal(result.length, 3); assert.deepEqual(result.map(row => Array.from(row)), [[6,7,8],[7,8,9],[8,9,10]]); assert.deepEqual(Array.from(kernel.output), [3,3]); kernel.setOutput([2,2]); result = kernel(); assert.equal(result.length, 2); assert.deepEqual(result.map(row => Array.from(row)), [[4,5],[5,6]]); assert.deepEqual(Array.from(kernel.output), [2,2]); gpu.destroy(); } test('dynamic output 2d shrinks auto', () => { dynamicOutput2DShrinks(); }); test('dynamic output 2d shrinks gpu', () => { dynamicOutput2DShrinks('gpu'); }); (GPU.isWebGLSupported ? test : skip)('dynamic output 2d shrinks webgl', () => { dynamicOutput2DShrinks('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('dynamic output 2d shrinks webgl2', () => { dynamicOutput2DShrinks('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('dynamic output 2d shrinks headlessgl', () => { dynamicOutput2DShrinks('headlessgl'); }); test('dynamic output 2d shrinks cpu', () => { dynamicOutput2DShrinks('cpu'); }); function dynamicOutput2DKernelMapGrows(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernelMap({ result1: function map(v) { return v; } }, function() { return map(this.output.x + this.output.y + this.thread.x + this.thread.y); }, { dynamicOutput: true }); kernel.setOutput([2,2]); let result = kernel(); assert.equal(result.result.length, 2); assert.equal(result.result1.length, 2); assert.deepEqual(result.result.map(row => Array.from(row)), [[4,5],[5,6]]); assert.deepEqual(result.result1.map(row => Array.from(row)), [[4,5],[5,6]]); assert.deepEqual(Array.from(kernel.output), [2,2]); kernel.setOutput([3,3]); result = kernel(); assert.equal(result.result.length, 3); assert.equal(result.result1.length, 3); assert.deepEqual(result.result.map(row => Array.from(row)), [[6,7,8],[7,8,9],[8,9,10]]); assert.deepEqual(result.result1.map(row => Array.from(row)), [[6,7,8],[7,8,9],[8,9,10]]); assert.deepEqual(Array.from(kernel.output), [3,3]); gpu.destroy(); } test('dynamic output 2d kernel map grows auto', () => { dynamicOutput2DKernelMapGrows(); }); test('dynamic output 2d kernel map grows gpu', () => { dynamicOutput2DKernelMapGrows('gpu'); }); (GPU.isWebGLSupported ? test : skip)('dynamic output 2d kernel map grows webgl', () => { dynamicOutput2DKernelMapGrows('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('dynamic output 2d kernel map grows webgl2', () => { dynamicOutput2DKernelMapGrows('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('dynamic output 2d kernel map grows headlessgl', () => { dynamicOutput2DKernelMapGrows('headlessgl'); }); test('dynamic output 2d kernel map grows cpu', () => { dynamicOutput2DKernelMapGrows('cpu'); }); function dynamicOutput2DKernelMapShrinks(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernelMap({ result1: function map(v) { return v; } }, function() { return map(this.output.x + this.output.y + this.thread.x + this.thread.y); }, { dynamicOutput: true }); kernel.setOutput([3,3]); let result = kernel(); assert.equal(result.result.length, 3); assert.equal(result.result1.length, 3); assert.deepEqual(result.result.map(row => Array.from(row)), [[6,7,8],[7,8,9],[8,9,10]]); assert.deepEqual(result.result1.map(row => Array.from(row)), [[6,7,8],[7,8,9],[8,9,10]]); assert.deepEqual(Array.from(kernel.output), [3,3]); kernel.setOutput([2,2]); result = kernel(); assert.equal(result.result.length, 2); assert.equal(result.result1.length, 2); assert.deepEqual(result.result.map(row => Array.from(row)), [[4,5],[5,6]]); assert.deepEqual(result.result1.map(row => Array.from(row)), [[4,5],[5,6]]); assert.deepEqual(Array.from(kernel.output), [2,2]); gpu.destroy(); } test('dynamic output 2d shrinks auto', () => { dynamicOutput2DShrinks(); }); test('dynamic output 2d shrinks gpu', () => { dynamicOutput2DShrinks('gpu'); }); (GPU.isWebGLSupported ? test : skip)('dynamic output 2d shrinks webgl', () => { dynamicOutput2DShrinks('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('dynamic output 2d shrinks webgl2', () => { dynamicOutput2DShrinks('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('dynamic output 2d shrinks headlessgl', () => { dynamicOutput2DShrinks('headlessgl'); }); test('dynamic output 2d shrinks cpu', () => { dynamicOutput2DShrinks('cpu'); }); //TODO: function dynamicOutput2DGraphicalGrows(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { this.color(1,1,1,1); }, { graphical: true, dynamicOutput: true }); kernel.setOutput([2,2]); kernel(); let result = kernel.getPixels(); assert.equal(result.length, 2 * 2 * 4); assert.deepEqual(Array.from(result), [ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 ]); assert.deepEqual(Array.from(kernel.output), [2,2]); kernel.setOutput([3,3]); kernel(); result = kernel.getPixels(); assert.equal(result.length, 3 * 3 * 4); assert.deepEqual(Array.from(result), [ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, ]); assert.deepEqual(Array.from(kernel.output), [3,3]); gpu.destroy(); } test('dynamic output 2d graphical grows auto', () => { dynamicOutput2DGraphicalGrows(); }); test('dynamic output 2d graphical grows gpu', () => { dynamicOutput2DGraphicalGrows('gpu'); }); (GPU.isWebGLSupported ? test : skip)('dynamic output 2d graphical grows webgl', () => { dynamicOutput2DGraphicalGrows('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('dynamic output 2d graphical grows webgl2', () => { dynamicOutput2DGraphicalGrows('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('dynamic output 2d graphical grows headlessgl', () => { dynamicOutput2DGraphicalGrows('headlessgl'); }); (GPU.isCanvasSupported ? test : skip)('dynamic output 2d graphical grows cpu', () => { dynamicOutput2DGraphicalGrows('cpu'); }); function dynamicOutput2DGraphicalShrinks(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { this.color(1,1,1,1); }, { graphical: true, dynamicOutput: true }); kernel.setOutput([3,3]); kernel(); let result = kernel.getPixels(); assert.equal(result.length, 3 * 3 * 4); assert.deepEqual(Array.from(result), [ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, ]); assert.deepEqual(Array.from(kernel.output), [3,3]); kernel.setOutput([2,2]); kernel(); result = kernel.getPixels(); assert.equal(result.length, 2 * 2 * 4); assert.deepEqual(Array.from(result), [ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 ]); assert.deepEqual(Array.from(kernel.output), [2,2]); gpu.destroy(); } test('dynamic output 2d graphical shrinks auto', () => { dynamicOutput2DGraphicalShrinks(); }); test('dynamic output 2d graphical shrinks gpu', () => { dynamicOutput2DGraphicalShrinks('gpu'); }); (GPU.isWebGLSupported ? test : skip)('dynamic output 2d graphical shrinks webgl', () => { dynamicOutput2DGraphicalShrinks('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('dynamic output 2d graphical shrinks webgl2', () => { dynamicOutput2DGraphicalShrinks('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('dynamic output 2d graphical shrinks headlessgl', () => { dynamicOutput2DGraphicalShrinks('headlessgl'); }); (GPU.isCanvasSupported ? test : skip)('dynamic output 2d graphical shrinks cpu', () => { dynamicOutput2DGraphicalShrinks('cpu'); }); function dynamicOutput3DGrows(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return this.output.x + this.output.y + this.thread.z + this.thread.x + this.thread.y + this.thread.z; }, { dynamicOutput: true }); kernel.setOutput([2,2,2]); let result = kernel(); assert.equal(result.length, 2); assert.deepEqual(result.map(matrix => matrix.map(row => Array.from(row))), [[[4,5],[5,6]],[[6,7],[7,8]]]); assert.deepEqual(Array.from(kernel.output), [2,2,2]); kernel.setOutput([3,3,3]); result = kernel(); assert.equal(result.length, 3); assert.deepEqual(result.map(matrix => matrix.map(row => Array.from(row))), [ [ [6,7,8], [7,8,9], [8,9,10] ], [ [8,9,10], [9,10,11], [10,11,12] ], [ [10,11,12], [11,12,13], [12,13,14] ] ]); assert.deepEqual(Array.from(kernel.output), [3,3,3]); gpu.destroy(); } test('dynamic output 3d grows auto', () => { dynamicOutput3DGrows(); }); test('dynamic output 3d grows gpu', () => { dynamicOutput3DGrows('gpu'); }); (GPU.isWebGLSupported ? test : skip)('dynamic output 3d grows webgl', () => { dynamicOutput3DGrows('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('dynamic output 3d grows webgl2', () => { dynamicOutput3DGrows('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('dynamic output 3d grows headlessgl', () => { dynamicOutput3DGrows('headlessgl'); }); test('dynamic output 3d grows cpu', () => { dynamicOutput3DGrows('cpu'); }); function dynamicOutput3DShrinks(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return this.output.x + this.output.y + this.thread.z + this.thread.x + this.thread.y + this.thread.z; }, { dynamicOutput: true }); kernel.setOutput([3,3,3]); let result = kernel(); assert.equal(result.length, 3); assert.deepEqual(result.map(matrix => matrix.map(row => Array.from(row))), [ [ [6,7,8], [7,8,9], [8,9,10] ], [ [8,9,10], [9,10,11], [10,11,12] ], [ [10,11,12], [11,12,13], [12,13,14] ] ]); assert.deepEqual(Array.from(kernel.output), [3,3,3]); kernel.setOutput([2,2,2]); result = kernel(); assert.equal(result.length, 2); assert.deepEqual(result.map(matrix => matrix.map(row => Array.from(row))), [[[4,5],[5,6]],[[6,7],[7,8]]]); assert.deepEqual(Array.from(kernel.output), [2,2,2]); gpu.destroy(); } test('dynamic output 3d shrinks auto', () => { dynamicOutput3DShrinks(); }); test('dynamic output 3d shrinks gpu', () => { dynamicOutput3DShrinks('gpu'); }); (GPU.isWebGLSupported ? test : skip)('dynamic output 3d shrinks webgl', () => { dynamicOutput3DShrinks('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('dynamic output 3d shrinks webgl2', () => { dynamicOutput3DShrinks('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('dynamic output 3d shrinks headlessgl', () => { dynamicOutput3DShrinks('headlessgl'); }); test('dynamic output 3d shrinks cpu', () => { dynamicOutput3DShrinks('cpu'); }); function dynamicOutput3DKernelMapGrows(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernelMap({ result1: function map(v) { return v; } }, function() { return map(this.output.x + this.output.y + this.thread.z + this.thread.x + this.thread.y + this.thread.z); }, { dynamicOutput: true }); kernel.setOutput([2,2,2]); let result = kernel(); assert.equal(result.result.length, 2); assert.equal(result.result1.length, 2); assert.deepEqual(result.result.map(matrix => matrix.map(row => Array.from(row))), [[[4,5],[5,6]],[[6,7],[7,8]]]); assert.deepEqual(result.result1.map(matrix => matrix.map(row => Array.from(row))), [[[4,5],[5,6]],[[6,7],[7,8]]]); assert.deepEqual(Array.from(kernel.output), [2,2,2]); kernel.setOutput([3,3,3]); result = kernel(); assert.equal(result.result.length, 3); assert.equal(result.result1.length, 3); assert.deepEqual(result.result.map(matrix => matrix.map(row => Array.from(row))), [ [ [6,7,8], [7,8,9], [8,9,10] ], [ [8,9,10], [9,10,11], [10,11,12] ], [ [10,11,12], [11,12,13], [12,13,14] ] ]); assert.deepEqual(result.result1.map(matrix => matrix.map(row => Array.from(row))), [ [ [6,7,8], [7,8,9], [8,9,10] ], [ [8,9,10], [9,10,11], [10,11,12] ], [ [10,11,12], [11,12,13], [12,13,14] ] ]); assert.deepEqual(Array.from(kernel.output), [3,3,3]); gpu.destroy(); } test('dynamic output 3d kernel map grows auto', () => { dynamicOutput3DKernelMapGrows(); }); test('dynamic output 3d kernel map grows gpu', () => { dynamicOutput3DKernelMapGrows('gpu'); }); (GPU.isWebGLSupported ? test : skip)('dynamic output 3d kernel map grows webgl', () => { dynamicOutput3DKernelMapGrows('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('dynamic output 3d kernel map grows webgl2', () => { dynamicOutput3DKernelMapGrows('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('dynamic output 3d kernel map grows headlessgl', () => { dynamicOutput3DKernelMapGrows('headlessgl'); }); test('dynamic output 3d kernel map grows cpu', () => { dynamicOutput3DKernelMapGrows('cpu'); }); function dynamicOutput3DKernelMapShrinks(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernelMap({ result1: function map(v) { return v; } }, function() { return map(this.output.x + this.output.y + this.thread.z + this.thread.x + this.thread.y + this.thread.z); }, { dynamicOutput: true }); kernel.setOutput([3,3,3]); let result = kernel(); assert.equal(result.result.length, 3); assert.equal(result.result1.length, 3); assert.deepEqual(result.result.map(matrix => matrix.map(row => Array.from(row))), [ [ [6,7,8], [7,8,9], [8,9,10] ], [ [8,9,10], [9,10,11], [10,11,12] ], [ [10,11,12], [11,12,13], [12,13,14] ] ]); assert.deepEqual(result.result1.map(matrix => matrix.map(row => Array.from(row))), [ [ [6,7,8], [7,8,9], [8,9,10] ], [ [8,9,10], [9,10,11], [10,11,12] ], [ [10,11,12], [11,12,13], [12,13,14] ] ]); assert.deepEqual(Array.from(kernel.output), [3,3,3]); kernel.setOutput([2,2,2]); result = kernel(); assert.equal(result.result.length, 2); assert.equal(result.result1.length, 2); assert.deepEqual(result.result.map(matrix => matrix.map(row => Array.from(row))), [[[4,5],[5,6]],[[6,7],[7,8]]]); assert.deepEqual(result.result1.map(matrix => matrix.map(row => Array.from(row))), [[[4,5],[5,6]],[[6,7],[7,8]]]); assert.deepEqual(Array.from(kernel.output), [2,2,2]); gpu.destroy(); } test('dynamic output 3d kernel map shrinks auto', () => { dynamicOutput3DKernelMapShrinks(); }); test('dynamic output 3d kernel map shrinks gpu', () => { dynamicOutput3DKernelMapShrinks('gpu'); }); (GPU.isWebGLSupported ? test : skip)('dynamic output 3d kernel map shrinks webgl', () => { dynamicOutput3DKernelMapShrinks('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('dynamic output 3d kernel map shrinks webgl2', () => { dynamicOutput3DKernelMapShrinks('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('dynamic output 3d kernel map shrinks headlessgl', () => { dynamicOutput3DKernelMapShrinks('headlessgl'); }); test('dynamic output 3d kernel map shrinks cpu', () => { dynamicOutput3DKernelMapShrinks('cpu'); }); ================================================ FILE: test/features/function-return.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: function return'); function functionReturnFloat( mode ) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function() { return 42; }, { output : [1] }); assert.equal(f()[0], 42); gpu.destroy(); } test('float auto', () => { functionReturnFloat(null); }); test('float gpu', () => { functionReturnFloat('gpu'); }); (GPU.isWebGLSupported ? test : skip)('float webgl', () => { functionReturnFloat('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('float webgl2', () => { functionReturnFloat('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('float headlessgl', () => { functionReturnFloat('headlessgl'); }); test('float cpu', () => { functionReturnFloat('cpu'); }); function functionReturnArray2( mode ) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function() { return [42, 43]; }, { output : [1] }); const result = f(); assert.equal(result[0].constructor, Float32Array); assert.equal(result[0][0], 42); assert.equal(result[0][1], 43); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array(2) auto', () => { functionReturnArray2(null); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array(2) gpu', () => { functionReturnArray2('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(2) webgl', () => { functionReturnArray2('webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('Array(2) webgl2', () => { functionReturnArray2('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(2) headlessgl', () => { functionReturnArray2('headlessgl'); }); test('Array(2) cpu', () => { functionReturnArray2('cpu'); }); function functionReturnArray3( mode ) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function() { return [42, 43, 44]; }, { output : [1] }); const result = f(); assert.equal(result[0].constructor, Float32Array); assert.equal(result[0][0], 42); assert.equal(result[0][1], 43); assert.equal(result[0][2], 44); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array(3) auto', () => { functionReturnArray3(null); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array(3) gpu', () => { functionReturnArray3('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(3) webgl', () => { functionReturnArray3('webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('Array(3) webgl2', () => { functionReturnArray3('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(3) headlessgl', () => { functionReturnArray3('headlessgl'); }); test('Array(3) cpu', () => { functionReturnArray3('cpu'); }); function functionReturnArray4( mode ) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function() { return [42, 43, 44, 45]; }, { output : [1] }); const result = f(); assert.equal(result[0].constructor, Float32Array); assert.equal(result[0][0], 42); assert.equal(result[0][1], 43); assert.equal(result[0][2], 44); assert.equal(result[0][3], 45); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array(4) auto', () => { functionReturnArray4(null); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array(4) gpu', () => { functionReturnArray4('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(4) webgl', () => { functionReturnArray4('webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('Array(4) webgl2', () => { functionReturnArray4('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('Array(4) headlessgl', () => { functionReturnArray4('headlessgl'); }); test('Array(4) cpu', () => { functionReturnArray4('cpu'); }); function functionReturnArray4MemberExpression(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { let pixel = toIntArray4(value[this.thread.y][this.thread.x]); return pixel; function toIntArray4(pixel) { return [pixel[0] * 255, pixel[1] * 255, pixel[2] * 255, pixel[3] * 255]; } }, { output: [1, 1], argumentTypes: { value: 'Array2D(4)' }, }); const result = kernel([[[1,1,1,1]]]); assert.deepEqual(Array.from(result[0][0]), [255,255,255,255]); gpu.destroy(); } test('auto', () => { functionReturnArray4MemberExpression(); }); test('gpu', () => { functionReturnArray4MemberExpression('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { functionReturnArray4MemberExpression('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { functionReturnArray4MemberExpression('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { functionReturnArray4MemberExpression('headlessgl'); }); test('cpu', () => { functionReturnArray4MemberExpression('cpu'); }); ================================================ FILE: test/features/get-canvas.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('get canvas'); function getCanvasTest(mode ) { const gpu = new GPU(); assert.ok(gpu.context === null, 'context is initially null'); assert.ok(gpu.canvas === null, 'canvas is initially null'); const render = gpu.createKernel(function() { this.color(0, 0, 0, 1); }, { output : [30,30], mode : mode }).setGraphical(true); assert.ok(render !== null, 'function generated test'); assert.ok(render.canvas, 'testing for canvas after createKernel' ); assert.ok(render.context, 'testing for context after createKernel' ); assert.ok(gpu.canvas, 'testing for canvas after createKernel' ); assert.ok(gpu.context, 'testing for context after createKernel' ); render(); assert.ok(render.canvas, 'testing for canvas after render' ); assert.ok(render.context, 'testing for context after render' ); assert.ok(gpu.canvas, 'testing for canvas after render' ); assert.ok(gpu.context, 'testing for context after render' ); assert.equal(render.canvas, gpu.canvas); assert.equal(render.context, gpu.context); gpu.destroy(); } test('auto', () => { getCanvasTest(null); }); test('gpu', () => { getCanvasTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { getCanvasTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { getCanvasTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { getCanvasTest('headlessgl'); }); test('cpu', () => { getCanvasTest('cpu'); }); ================================================ FILE: test/features/get-pixels.js ================================================ const { assert, test, module: describe, only, skip } = require('qunit'); const { GPU } = require('../../src'); describe('features: getPixels'); function getPixelsStandard(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { this.color( v[this.thread.y][this.thread.x][0], v[this.thread.y][this.thread.x][1], v[this.thread.y][this.thread.x][2] ); }, { output: [2,2], graphical: true, }); kernel([ [ [.02,.04,.06,.08], [.10,.12,.14,.16] ], [ [.18,.20,.22,.24], [.26,.28,.30,.32] ] ]); const pixels = Array.from(kernel.getPixels()); gpu.destroy(); return pixels; } test('standard auto', () => { const pixels = getPixelsStandard(); assert.deepEqual(pixels, [ 46, 51, 56, 255, 66, 71, 76, 255, 5, 10, 15, 255, 25, 31, 36, 255 ]); }); test('standard gpu', () => { const pixels = getPixelsStandard('gpu'); assert.deepEqual(pixels, [ 46, 51, 56, 255, 66, 71, 76, 255, 5, 10, 15, 255, 25, 31, 36, 255 ]); }); (GPU.isWebGLSupported ? test : skip)('standard webgl', () => { const pixels = getPixelsStandard('webgl'); assert.deepEqual(pixels, [ 46, 51, 56, 255, 66, 71, 76, 255, 5, 10, 15, 255, 25, 31, 36, 255 ]); }); (GPU.isWebGL2Supported ? test : skip)('standard webgl2', () => { const pixels = getPixelsStandard('webgl2'); assert.deepEqual(pixels, [ 46, 51, 56, 255, 66, 71, 76, 255, 5, 10, 15, 255, 25, 31, 36, 255 ]); }); (GPU.isHeadlessGLSupported ? test : skip)('standard headlessgl', () => { const pixels = getPixelsStandard('headlessgl'); assert.deepEqual(pixels, [ 46, 51, 56, 255, 66, 71, 76, 255, 5, 10, 15, 255, 25, 31, 36, 255 ]); }); (GPU.isCanvasSupported ? test : skip)('standard cpu', () => { const pixels = getPixelsStandard('cpu'); assert.deepEqual(pixels, [ 45, 51, 56, 255, 66, 71, 76, 255, 5, 10, 15, 255, 25, 30, 35, 255 ]); }); function getPixelsFlipped(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { this.color( v[this.thread.y][this.thread.x][0], v[this.thread.y][this.thread.x][1], v[this.thread.y][this.thread.x][2] ); }, { output: [2,2], graphical: true, }); kernel([ [ [.02,.04,.06,.08], [.10,.12,.14,.16] ], [ [.18,.20,.22,.24], [.26,.28,.30,.32] ] ]); const pixels = Array.from(kernel.getPixels(true)); gpu.destroy(); return pixels; } test('flipped auto', () => { const pixels = getPixelsFlipped(); assert.deepEqual(pixels, [ 5, 10, 15, 255, 25, 31, 36, 255, 46, 51, 56, 255, 66, 71, 76, 255 ]); }); test('flipped gpu', () => { const pixels = getPixelsFlipped('gpu'); assert.deepEqual(pixels, [ 5, 10, 15, 255, 25, 31, 36, 255, 46, 51, 56, 255, 66, 71, 76, 255 ]); }); (GPU.isWebGLSupported ? test : skip)('flipped webgl', () => { const pixels = getPixelsFlipped('webgl'); assert.deepEqual(pixels, [ 5, 10, 15, 255, 25, 31, 36, 255, 46, 51, 56, 255, 66, 71, 76, 255 ]); }); (GPU.isWebGL2Supported ? test : skip)('flipped webgl2', () => { const pixels = getPixelsFlipped('webgl2'); assert.deepEqual(pixels, [ 5, 10, 15, 255, 25, 31, 36, 255, 46, 51, 56, 255, 66, 71, 76, 255 ]); }); (GPU.isHeadlessGLSupported ? test : skip)('flipped headlessgl', () => { const pixels = getPixelsFlipped('headlessgl'); assert.deepEqual(pixels, [ 5, 10, 15, 255, 25, 31, 36, 255, 46, 51, 56, 255, 66, 71, 76, 255 ]); }); (GPU.isCanvasSupported ? test : skip)('flipped cpu', () => { const pixels = getPixelsFlipped('cpu'); assert.deepEqual(pixels, [ 5, 10, 15, 255, 25, 30, 35, 255, 45, 51, 56, 255, 66, 71, 76, 255 ]); }); ================================================ FILE: test/features/if-else.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('if else boolean'); function ifElseBooleanTest(mode) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function() { let result = 0; if (true) { result = 4; } else { result = 2; } return result; }, { output : [1] }); assert.ok( f !== null, 'function generated test'); assert.equal(f()[0], 4, 'basic return function test'); gpu.destroy(); } test('auto', () => { ifElseBooleanTest(null); }); test('gpu', () => { ifElseBooleanTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { ifElseBooleanTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { ifElseBooleanTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { ifElseBooleanTest('headlessgl'); }); test('cpu', () => { ifElseBooleanTest('cpu'); }); describe('if else lookup'); function ifElseLookupTest( mode ) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function(x) { if (x[this.thread.x] > 0) { return 0; } else { return 1; } }, { output : [4] }); assert.ok( f !== null, 'function generated test'); assert.deepEqual(Array.from(f([1, 1, 0, 0])), [0, 0, 1, 1], 'basic return function test'); gpu.destroy(); } test('auto', () => { ifElseLookupTest(null); }); test('gpu', () => { ifElseLookupTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { ifElseLookupTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { ifElseLookupTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { ifElseLookupTest('headlessgl'); }); test('cpu', () => { ifElseLookupTest('cpu'); }); describe('if else if'); function ifElseIfTest( mode ) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function(x) { const v = x[this.thread.x]; if (v > 0) { return 0; } else if (v < 1) { return .5; } return 1; }, { output : [2] }); assert.deepEqual(Array.from(f([-1, 1])), [.5, 0], 'basic return function test'); gpu.destroy(); } test('auto', () => { ifElseIfTest(null); }); test('gpu', () => { ifElseIfTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { ifElseIfTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { ifElseIfTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { ifElseIfTest('headlessgl'); }); test('cpu', () => { ifElseIfTest('cpu'); }); ================================================ FILE: test/features/image-array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, CPUKernel } = require('../../src'); describe('features: image array'); function getImages(callback) { const imageSources = [ 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCABbAIoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDtjB/vL/wHP8qUBk//AGv8anjEr/7L/wC1z/hUhib+Lb/wHj+dfQOfc893WjK/+8u3/a6f5/OkU7Plb7nZun4Yqx5TJ93/ANB/w4pvkb/67cH8xS5kNW6htpCtRm2b7yv9duf1BNO2/wB75f8AaXj+dO4uVdGBWkI2UpXZ/Ezf72Qf/r1KsS/eXbRzE7Fb/d3Uv/AW/n/KrOyneXRzCKqbX+X/AMd6H8quww76jMKv97/P0qxC2z5W/BvX/wCvWc5aaAONtUDxbKtvLUON9RFvqBGq1JipAlCKzPuocihM06nrFsepNiVDkgKRs4n/AINv+7x/KmeTKn/LVvbdhh/iPzq3HJ/C303difT2PtU+2jna3HzSW5n/AL9PvKrf7uRSM8T/AOsiZf8Aa6/qKumHZ/q/l/2e3/1qbtV/9l/896OdBzLsVBEr/wCrfd/P86Ywli+8m5P5/wBKtPaL97b/AOyn8xTNsqfxbv8AZk4P5iq5gKwVX+aP7v8Ad/wBpEj2fd+51G3t6jB6VK6qn96Dd9Cuf5VG4/iWXa/5girTCxIP++v93r+VPUK/3agllaL5ZEX/AHucfgR0/HFSfvfvSbV9JFbj8Tjp+GKTDke5NspfL/haoVafzPmTcvZl53epA46VaRt393/DPTI7VDdhONiHbs+99z+96fX/ABqZVqbb/eqJJET5V3MvT2B9MmpcriJVjp0UVBbZHuZ4ok/vNz/hUIv7T7v21V/4DgfqKj3nsVYsiOneXTVli8vct1Gyd23KQPyxVT+29MHB1C0z/vCpipS2RSpyeyuUfKn/AIrhW/2vN4+hAUfrSJcT277ZNzJ2aPLAe3DVvgU14ll+WRVb/eXNae27o1VZdUY6ao3/ADyZk6D5GyfXHAx3/KnNqcb/AHopFbt0q81rsj2wttX/AJ5su5fy6j8KhO6L70W3/aVuD+fT86FKD2QOVJ7Rt8yuupx/db7/AF+6w/QrUy3cD/xr/wB9L/LOaZJEv3vs7f8AfJX9QSDVbyf+mUsUq9GVcj+fT2xVpRaIcab2v+BZNxbfd81f93qPyqu/2R/vSqqdmVuP/rfhT992ke1oo2/LP5cGkjWN/mkRWf8A2sqB+GMU1pqCiluQW9xI++NWgliVsDc4BYeuP0/ClS4+zx7Wib5ePlbr+Jx+tPDRyu/z7Zdxxtw2AMDucY46U77b5Ue5pYv9tVz26jB/pVPXoW4puyiPivYn/dq67P7sjBSPT6j3p8vyfeZV7/T15/z+fXOn1LTZZ/IbazbciaFOPx/qKqSXdy8nl2Hn/d5ZWyOuON3GKaotvt6m0MJKT2t67fedLDJE3zM3zc/MzZzjuO1NnuILe3/eN8zNkKq5ZmJyAB3Oa5wJ4it/lWJvK7fKGwPfr/Wov7H1O7f7RLcbZW6qzFcD0yP8MUfV4p+9JWN44CnH3qtVW8tWyxqOptLOvmI3m9Et1+bae+e2ahSy1K4/1zrAjdFVQT/WtLSxY6Z/q5W+0N/E0YbJ7gEdunetq2n1C4j+7Ay/7WVP5ZNVKt7NWgtPMU50qWlKK9WvyT0XzuctZ6TbS3yW0zK0rZKSN82SOcY7cZP4Vq/8I1EON1vx/sf/AF6uXtg1xG3k/u72P50WT2PUH/PXnFU18QQKoEthfrIBhgucA98VDr1Z6wZzTq1amrkzeFLSZozXCcgU1qUmmk1SEQtAv/LNmj/3en5VBI86fet/N/2o8fqDVyirT7jUrbq5nm+g8v8AiXsVkXp6+1RM8cv+p2+zbsEfQdPxP5GrV3brcSRfdV1yQ20Hkdv1P5Uxo28zbG8ay/7K8D684P061onG2hsvZ2utyv5WyPy47hW7/vMce+fWiJInkaHarfxbmYnr1AHIJzzn3qd1kf8Ac/uvvAlmXIb/AOv7fSnppkH3m+ZmxnaoUce3+etHOurHzJLViT2FpcQeXPZfJ1+7nB+oOazDoMtvJ5lle/PtIEMnAxnIHP5fia1xYKnzR7v93eRT/Lb7q3Esbf3ZMOp/E/40o1ZR0i9P69S6eInBcqlp2ev+ZXtNQlidYbuLypePl3AZPsc/596qXl0t7fPpUCSLt5uWXB2L1wMHnPcf1q9cRK8Hk3turRd/Qe4J+6fyrGutMl0+f7bDcSz2rYjkXzCrBeylhzjOBVU1Byvs+na5rh40nJuTs7adrmgkuiW/7mPy1+bDxqpYkHvjB74psWtLFO26KSW328MyZdPw5LD9frVhYrN7RGWw2pt3Iy4baRzkHr9akNnBLI+37/de49x6/wA/rUc0Nea7MZNdE/mWSIru0intLhZEZhsZW3D069vQj3NaCSRuit5mMgHBcAj8O1chPb32j3bzWn325kj/AIJhjrjs3vV3+3NGk+eS3cSNyw9+9TPDSaThqvIajfWJqbqN1V91Lupcpxk2+mFqZmkJppAPzS7qizRmnYRIdr/K1AC+XtX5VqPNKDRYdxQv7xFX+4fvc9SP8DTsyp/DuT9R9PWmj/WbvoPyz/jUgNJjuPR9/wAy0/G/71Q7f4l+V/5/WpFl/hb5W/Q/Q1D8hj1h2f6v/vlun/1qrta7N7W/7p2Uh7duEf6H+E+4/EVcBp/3/lao5mjSLsc9pVxPdR3vk/K0bMGsmwAO3GehOCeuOfrWnDLFcbJFVliZTjdwUx1Xg5GPQ+/pWbqGns2oytC7xy7VeOTqVIHIyTypGePUdQcUmm3Uj3UsckTLKu57iPkkdBuHqcncD1IK9xW00pJzidkoKcXKHT8P815/f3NO5gk8t9v71dvCt1UnsD3z1H/165d7iNXZcKMHGGBz+NdbA2/zVb+HCv8ATkg/1+lYE5fz5N1pEzbjklevNVh52umRSV2y+Gpd1QrThWnKeeS5pM0ykNTYCTdSbqjpafKBJmlBqOlFKwEwNOBqEVIKmwEympAN/wArVCtSCs2UhwLRf7UX5lf8RVlTUK0ltwJVHRTwPTgGoaNER3yr5luzfKrN5b+2eVP/AH0B+dZ0nlJrtr527zZEeEMvthlP5bgfcVpX6hrJlIyPMTj/AIEKxNTZm1OzBJI+XjPq65rSlHm09TqoPX1Vvv2/EtCT+ytZSOT5re4XyQ3XZjkZz2+bH+cVbksJGldlkwCxIFV9SUSW8e4Z4iP6mr8Mj+TH87fdHf2pSm4pS6m0G9Gt+p//2Q==', 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCABbAIoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD1ZOlIwpwjKH5ehprSgHB69MelepfsecRkUgXmrBTofWkK01ICAimkVOVppFNSArkUhFSsvNMK1aYEZ60lPxzSEVQCdKM80YpD0pgLmlzTMU4daQEq9aD1pueKXPFSJjWptONNqkI1XYopwM+1ZbTrPqMUKnKqGdztI6cY/WobvxRpaSDM6SqOixHdmp9ClS8lkuVBHyBcHHBJye/T/AVmqcqcXOSOj2copuSNIAMBjtQV4qQL+8agisLmViAik21MVppWqTEV2WmMOKsEVGRzVJiK5FNIqZhzSYrRMCEikxUpWm7aaYEeKMYp+KQincBmeaN1KRSYqgGlqN1JRTsIqXfhsSZRYFPGd6DBH0rJhkuNPu3t5Lp7eKVhIGiG0E+/p7jpXf2kkc8qskqSxmPcsq9GzzzjjtWRrmlrdNIURfMABB9Mc5/Wpo4tuXJU2OyFSSTiyxpF+9yXguAolxuVlz849a0ytcTo98YxFJ/zwcDj+6ex/X8hXdFRj5elc+Kp+znoYNFcimkVORTCKwUiWiAioytTkc0xulaJksgIpmOamNMIq0xDCKbjmpaaasCIimkU800mqTGMIppFPJqMmqQhpFJQTTc1aAmvdNm065e901QV8zf5QOOeCQfY5P0/GtCG+gvXt7tCyjzfLcNwUJXGD75wPzq9Yyx3mno4fzA2cuv16/yrldRl/sW8unLAxylSUK91wcj8MVyQvWfJL4kd9OnKpLkS1M+ytZItSvtKRdzm4ba57KST+g5rvYohFCsakkKAuT14rlvC8iXur3d7MrfaG+58pIVTyeex6V1veqxs25qL6Wv62Lx1P2dVxe+79X28iIjmo261M1RN1rlRwsjbpUZqRqibpWqIYw0w0400mrQhKaaU00mrQDDTG609jxUZq0Ah6VGaeTTD1q0AxutMp7dKZViuW9JZoAzW2N4Yb0B4cHlWGeM9vy5FUdens7/UrON0DYfLg9kwCQfQ5Q/5xUunTJY395A2VDLuT/fX5vyP+etYWqqxuftoYbp5d7D+7jp/n2qKdK9Zy+75n0eXUU6972009Wv0Op8IKg0yVtipI0zFgO3oPpXQGuV0W7ijsoDE8aXRzvhkfb5uScEH1x+fFbC6oNxSS0nVwOV4JH4Z/kPxrjxEJSqyZw4yEpVpNLqXmqJqSK5juY1lifzEbo3+eh7Y60jNWSTOCWmjI2qJjzTnaoWat4ozYrHimE8UwtzTS9aJCHE03PNNL00tVJAOJphNGaQmrSEIaYad3ppqgGt0plONNqhMj0KJtRivL6fDPHCYVPYNjn/PvVLWopI9Qa3ZT5Yyyt65A/rmtLwwxWDVQMAC6bAA6dR/ICqeruxuYWJyTbqD+lSpNVpW2t+iPrcNFxxcoLZbeXYuaalo2jW0N1DFLIqsoS4j4kwx6Ng/5B/HHv7/AM27SztbYxIxWMIH6OxAHI6rzn/gNWoWIvIwDgc8dv4/8BWAzM9/ZsScmRiefdv8BV0IKTbl1uzVYVqdSpe6ScrPbq9vkek2dt9ktI4twcgEs+MbmJyT9Sc5pzmnn7oqN+lecrt3Z8nOTk231IHNQualeq79a3ijMaTUZahqjNapCuPzSZplFVYB+aM0ylHWiwD6aaKQ9KAGmm0402qEz//Z', 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCABbAIoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD0hXp4eqSyVIJK91wPKuWt1IXqDfSF/ep5QuT76duqtupd9HKFyxvpQ9Vw9OD0uUZZDVKGqoHqRXqHEC2pqQGqqvUivWUojLamkY+XIJR904V/p61ErVJkFdp+6QQfes2jRMW+kEVo7tx04988VhyLHcC4mkYpA5MSuW6Lv4bPb7zc/wC7VLV9YeRjp8SgiEMZ2J+8AOAD2B459xUU93A0VuTM08QBLRxJsRD0wB/U8/06KdKUUu7PYw+BlyRk9L6/Lf8AHpc0xembS4ZJZf3shViUH3QoLYPpzkYpiapqGxfLmjEePlB647VTd2usxoX2KqbS5yAB6Z6dKP7JRvmJ5PJwTT5Yx+I744OnbXS/lciWWpFkx3rPElPEpr0XTPkLl/zaPNqj5h9ad5lT7MLl7zKXfVIS04Se9LkC5cD04PVMS04SVLgO5dD1Kr+9UBJUokqHAdy8slSq9UFkqRZKylAo0FkqUPWeslTLJWUoDTKusaJaalHK4UR3TKQJk4J4wN394fWuVsgyyLbTR+XMp2lC2fMXoefX+tdur4rK1vQ7fWIw2fKuUHyTL1z7j/J461pTqSUeRu1+vb/gHtZbmfsX7OtrD77enl5EdjLDkW0kmzJxBN0Vz2GTwGH93vj3qx/ZMg/vD2S9mRfwUAgD2HArkptB8SQhlWWO4U8ZD4L+mc4Bx75PvVddL1xVAGnSAAYAEygCuSphJyd1JM+gj9Vqe8q8V80v1RoCTNOD1TV6f5lfRuB+elrzDR5lVfMo8ylyCLokpwlqiJKd5nvR7Mdy6JPepBJ71QElSBz61DgO5fV6kElUBJTxLWbgVc0VkqRZKzllqVZazdMdzRWSpBL71nCanib3rN0x3NIS+9O833rOEvvTxL71Hsyrl7ePp+FLvH91aoed707zvep9mO5xCy0/zazxLUgkr6F0zluXPMpfNqn5lKJaXIFy6JKeHqkHp4kqeQZbElPWSqe+nK9Q4AXhJThJVMS04SVDgVcvCWnrLVASe9SCT3qHAdy+JaeJKoLJ71KJKhwGXRKfWneafWqe+jzPeo5ALnmn1pfO96oiSjzKXswuccstSCWqCye9SCSvecDkUy55lKJKqeZTg9TyFcxeWSnB6piSnCT3qHAq5c8yniSqQkp4epcCrlwPTvMqoJKXzKjkGXA59aeJPeqQk96cJKlwGXlkqUSe9UFkp4lqHAdy/wCbS+Z71S8yl8yp5BlzzKPMqp5opfMpcgHFLIakEtVQaXJr3nFHjqbRcEtOEtVATTgT61DgaKoy8JaUSe9Ugx9akyazcDRVLlwSe9PEnvVME+tPBPrU8pqplsSe9P8AMqmCfWnAn1qXEtSLYc+tOElVQT604E1HKirlsSVIJPeqgJpwJ9ankKuWhL707zaqAn1pcn1qeVDuWxJS+ZVTJ9aXJ9aXIO5//9k=', 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCABbAIoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDso4Esrr7RHsZSNrxyLuBx+owO49a0I7TzTuZcBsYwenoMn3oht44pUiuD+7mbYjnsxH3T6Z7fl1xlYrgtp1vCcieK6jgmz2ZXGfzwPzrvxGLV/c37nvQi4LR3emv9dinqK2tgmnsWBAY/Me6iNyST9AaybCQ6l4isYYlVfs4Bk2jhcrl8+vBA+rVjaxrPn+XAmGREIRAfvs5zj/vnaPo9dt4T0Q6VYefOCbudfnLdVGcgfXkk+7H2rSipQp+0n8jbMZrCYV8/xSul+Ov3M6Qtkf0qJzSlqhdhWcUfFEcjVWdqfI4qu710wiSxGamFqQtTC1bJEkm6jNRbqXdTsFyTNAPNR7qN1FguTbhQTUJak30coXHlqTdUZam7qqwmySS7RLV7XV12RkYDn5WHPGcdccHcMjjnb0HLaz4m8tntICJJ5fLBeLncyMNsg92XA9iuPepLfRdeuI2gldkt3Uqy3M5kH5YOfzArc0XwtYaPL9oI+0XZBBmk6jPXA7fz968iGEad5s+5q47BYNOXMpy6JbfN9PlfoUfCfhM2hTUdTTNx96OI8hM9z7+3auy3gZ96g34Hv60xpa62nLc+UxmNq4yq6tZ6/gvJE7SVA8tRNL71A8laRpnK2Pkkquz80xpOetQu9dEYENkxems/FV95z1prSVooE3J99OD1TMlKH96fIFy5vpN9VvMo3+9HIO5OXpPMquZKb5lNQFctb6TeKreZRv8AenyBc6EyZxxjHpSGQVR873pDL71yezNLlxpKheWq5l96ieWrjTE2TtL71C0tQNLULS1tGmS2TtJUTSe9QNLURkraMCWyw0mKYZarmSmb6tQFcsmSgSVVL+9AkquQLlvzKXzKqiSl8z3pcg7lgyc0hkqsXpN9CgJss+ZR5nvVUyUnmGq5BGuZuOtJ5x9ap+ZSebWKpl3LZlPrTGl96rGT3phk96pQAnaWojJzUReomf3rRQE2TNJUZkqJpKiaStFAlk5kppfiq5kpDJV8gix5lAeq2+jzKfIBbD8UGSq3mcUnmUuQZZ8yk8yq++ml+aagBYL0nmVWaSm+YapQIuavmUhkqt5lMMtZchsWjJ70wye9VjJTTJVqAiwZPeo2k96rmSmGSqUBMnZ6jL1C0nFMMlaKBLZMXpu+oC9NL8VagS2WfMo8yqvmUoejkFct+ZRvqrvo8yjkKuWt9NL1X300yUKAXJzJTfMqu0nNM8z3q1AycjTMlNMnvVfJ9aTJ9ajlRvcn8zmkMlV8nPWkJPrT5RNkxkphlqBic9aYSfWrUCHImMlMMlQkn1qNic9atRRm5k5k96aZarkn1ppJ9atQM3ULHm0ol96pkn1pyk+tHIJVC4JPel82quTjrRk0uVFqZZMtMMtQEn1qMk+tNQIlUJ2lpnmmoCTnrTc1ooHPKo2z/9k=' ]; const images = []; let finished = 0; function onload() { finished++; if (finished === imageSources.length) { callback(images); } } for (let i = 0; i < imageSources.length; i++) { const image = document.createElement('img'); image.onload = onload; image.src = imageSources[i]; images.push(image); } } function imageArrayTest(mode, done) { const gpu = new GPU({ mode }); const imageKernel = gpu.createKernel(function(images) { const pixel = images[this.thread.z][this.thread.y][this.thread.x]; this.color(pixel[0], pixel[1], pixel[2], pixel[3]); }, { graphical: true, output : [138, 91] }); getImages(function(images) { imageKernel(images); const pixels = imageKernel.getPixels(); assert.equal(pixels.length, 50232); // way too large to test the whole picture, just test the first pixel assert.equal(pixels[0], 147); assert.equal(pixels[1], 168); assert.equal(pixels[2], 251); assert.equal(pixels[3], 255); gpu.destroy(); done(imageKernel); }); } (typeof Image !== 'undefined' ? test : skip)('image array auto', t => { imageArrayTest(null, t.async()); }); (typeof Image !== 'undefined' ? test : skip)('image array gpu', t => { imageArrayTest('gpu', t.async()); }); (GPU.isWebGLSupported ? test : skip)('image array webgl', t => { const done = t.async(); imageArrayTest('webgl', kernel => { // They aren't supported, so test that kernel falls back assert.equal(kernel.kernel.constructor, CPUKernel); done(); }); }); (GPU.isWebGL2Supported ? test : skip)('image array webgl2', t => { imageArrayTest('webgl2', t.async()); }); (typeof Image !== 'undefined' ? test : skip)('image array cpu', t => { imageArrayTest('cpu', t.async()); }); ================================================ FILE: test/features/image.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('image'); function imageArgumentTest(mode, done) { const gpu = new GPU({ mode }); const image = document.createElement('img'); image.src = 'jellyfish-1.jpeg'; image.onload = function() { const imageKernel = gpu.createKernel(function(image) { const pixel = image[this.thread.y][this.thread.x]; this.color(pixel[0], pixel[1], pixel[2], pixel[3]); }, { graphical: true, output : [image.width, image.height] }); imageKernel(image); assert.equal(true, true, 'does not throw'); gpu.destroy(); done(); }; } (typeof Image !== 'undefined' ? test : skip)('image argument auto', t => { imageArgumentTest(null, t.async()); }); (typeof Image !== 'undefined' ? test : skip)('image argument gpu', t => { imageArgumentTest('gpu', t.async()); }); (GPU.isWebGLSupported && typeof Image !== 'undefined' ? test : skip)('image argument webgl', t => { imageArgumentTest('webgl', t.async()); }); (GPU.isWebGL2Supported && typeof Image !== 'undefined' ? test : skip)('image argument webgl2', t => { imageArgumentTest('webgl2', t.async()); }); (typeof Image !== 'undefined' ? test : skip)('image argument cpu', t => { imageArgumentTest('cpu', t.async()); }); ================================================ FILE: test/features/infinity.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('infinity'); function inputWithoutFloat(checks, mode) { const gpu = new GPU({ mode }); checks(gpu.createKernel(function() { return Infinity; }, { precision: 'unsigned' }) .setOutput([1])()); gpu.destroy(); } test("Infinity without float auto", () => { inputWithoutFloat((v) => assert.deepEqual(v[0], NaN)); }); test("Infinity without float cpu", () => { inputWithoutFloat((v) => assert.deepEqual(v[0], Infinity), 'cpu'); }); test("Infinity without float gpu", () => { inputWithoutFloat((v) => assert.deepEqual(v[0], NaN), 'gpu'); }); (GPU.isWebGLSupported ? test : skip)("Infinity without float webgl", () => { inputWithoutFloat((v) => assert.deepEqual(v[0], NaN), 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)("Infinity without float webgl2", () => { inputWithoutFloat((v) => assert.deepEqual(v[0], NaN), 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)("Infinity without float headlessgl", () => { inputWithoutFloat((v) => assert.deepEqual(v[0], NaN), 'headlessgl'); }); function inputWithFloat(checks, mode) { const gpu = new GPU({ mode }); checks(gpu.createKernel(function() { return Infinity; }, { precision: 'single' }) .setOutput([1])()); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)("Infinity with float auto", () => { inputWithFloat((v) => assert.deepEqual(v[0], 3.4028234663852886e+38)); }); (GPU.isSinglePrecisionSupported ? test : skip)("Infinity with float cpu", () => { inputWithFloat((v) => assert.deepEqual(v[0], Infinity), 'cpu'); }); (GPU.isSinglePrecisionSupported ? test : skip)("Infinity with float gpu", () => { inputWithFloat((v) => assert.deepEqual(v[0], 3.4028234663852886e+38), 'gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)("Infinity with float webgl", () => { inputWithFloat((v) => assert.deepEqual(v[0], 3.4028234663852886e+38), 'webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)("Infinity with float webgl2", () => { inputWithFloat((v) => assert.deepEqual(v[0], 3.4028234663852886e+38), 'webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)("Infinity with float headlessgl", () => { inputWithFloat((v) => assert.deepEqual(v[0], 3.4028234663852886e+38), 'headlessgl'); }); ================================================ FILE: test/features/inject-native.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: inject native'); function gpuAddAB(mode) { const gpu = new GPU({mode}); gpu .injectNative(` int customAdder(int a, int b) { return a + b; } `) .addNativeFunction('customAdderLink', `int customAdderLink(int a, int b) { return customAdder(a, b); }`); const kernel = gpu.createKernel(function (a, b) { return customAdderLink(a[this.thread.x], b[this.thread.x]); }, { output: [6], returnType: 'Integer' }); const a = [1, 2, 3, 5, 6, 7]; const b = [4, 5, 6, 1, 2, 3]; const result = kernel(a, b); const expected = [5, 7, 9, 6, 8, 10]; assert.deepEqual(Array.from(result), expected); gpu.destroy(); } test('addAB auto', () => { gpuAddAB(null); }); test('addAB gpu', () => { gpuAddAB('gpu'); }); (GPU.isWebGLSupported ? test : skip)('addAB webgl', () => { gpuAddAB('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('addAB webgl2', () => { gpuAddAB('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('addAB headlessgl', () => { gpuAddAB('headlessgl'); }); function cpuAddAB(mode) { function customAdder(a, b) { return a + b; } const gpu = new GPU({mode}); gpu .injectNative(customAdder.toString()); const kernel = gpu.createKernel(function (a, b) { return customAdder(a[this.thread.x], b[this.thread.x]); }, { output: [6], returnType: 'Integer' }); const a = [1, 2, 3, 5, 6, 7]; const b = [4, 5, 6, 1, 2, 3]; const result = kernel(a, b); const expected = [5, 7, 9, 6, 8, 10]; assert.deepEqual(Array.from(result), expected); gpu.destroy(); } test('addAB cpu', () => { cpuAddAB('cpu'); }); ================================================ FILE: test/features/input.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, input } = require('../../src'); describe('input'); function inputX(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(a) { return a[this.thread.x]; }) .setOutput([9]); const a = new Float32Array(9); a.set([1,2,3,4,5,6,7,8,9]); const result = kernel(input(a, [3, 3])); assert.deepEqual(Array.from(result), [1,2,3,4,5,6,7,8,9]); gpu.destroy(); } test("inputX auto", () => { inputX(); }); test("inputX gpu", () => { inputX('gpu'); }); (GPU.isWebGLSupported ? test : skip)("inputX webgl", () => { inputX('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("inputX webgl2", () => { inputX('webgl2'); }); test("inputX cpu", () => { inputX('cpu'); }); function inputXY(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(a) { return a[this.thread.y][this.thread.x]; }) .setOutput([9]); const a = new Float32Array(9); a.set([1,2,3,4,5,6,7,8,9]); const b = new Float32Array(9); b.set([1,2,3,4,5,6,7,8,9]); const result = kernel(input(a, [3, 3])); assert.deepEqual(Array.from(result), [1,2,3,4,5,6,7,8,9]); gpu.destroy(); } test("inputXY auto", () => { inputXY(); }); test("inputXY gpu", () => { inputXY('gpu'); }); (GPU.isWebGLSupported ? test : skip)("inputXY webgl", () => { inputXY('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("inputXY webgl2", () => { inputXY('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)("inputXY headlessgl", () => { inputXY('headlessgl'); }); test("inputXY cpu", () => { inputXY('cpu'); }); function inputYX(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(a) { return a[this.thread.y][this.thread.x]; }) .setOutput([3, 3]); const a = new Float32Array(9); a.set([1,2,3,4,5,6,7,8,9]); const result = kernel(input(a, [3, 3])); assert.deepEqual(result.map(function(v) { return Array.from(v); }), [[1,2,3],[4,5,6],[7,8,9]]); gpu.destroy(); } test("inputYX auto", () => { inputYX(); }); test("inputYX gpu", () => { inputYX('gpu'); }); (GPU.isWebGLSupported ? test : skip)("inputYX webgl", () => { inputYX('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("inputYX webgl2", () => { inputYX('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)("inputYX headlessgl", () => { inputYX('headlessgl'); }); test("inputYX cpu", () => { inputYX('cpu'); }); function inputYXOffset(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(a) { return a[this.thread.x][this.thread.y]; }) .setOutput([8, 2]); const a = new Float32Array(16); a.set([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]); const result = kernel(input(a, [2, 8])); assert.deepEqual(result.map(function(v) { return Array.from(v); }), [[1,3,5,7,9,11,13,15],[2,4,6,8,10,12,14,16]]); gpu.destroy(); } test("inputYXOffset auto", () => { inputYXOffset(); }); test("inputYXOffset gpu", () => { inputYXOffset('gpu'); }); (GPU.isWebGLSupported ? test : skip)("inputYXOffset webgl", () => { inputYXOffset('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("inputYXOffset webgl2", () => { inputYXOffset('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)("inputYXOffset headlessgl", () => { inputYXOffset('headlessgl'); }); test("inputYXOffset cpu", () => { inputYXOffset('cpu'); }); function inputYXOffsetPlus1(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(a) { return a[this.thread.x][this.thread.y]; }) .setOutput([2, 8]); const a = new Float32Array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]); const result = kernel(input(a, [8, 2])); assert.deepEqual(result.map(function(v) { return Array.from(v); }), [[1,9],[2,10],[3,11],[4,12],[5,13],[6,14],[7,15],[8,16]]); gpu.destroy(); } test("inputYXOffsetPlus1 auto", () => { inputYXOffsetPlus1(); }); test("inputYXOffsetPlus1 gpu", () => { inputYXOffsetPlus1('gpu'); }); (GPU.isWebGLSupported ? test : skip)("inputYXOffsetPlus1 webgl", () => { inputYXOffsetPlus1('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("inputYXOffsetPlus1 webgl2", () => { inputYXOffsetPlus1('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)("inputYXOffsetPlus1 headlessgl", () => { inputYXOffsetPlus1('headlessgl'); }); test("inputYXOffsetPlus1 cpu", () => { inputYXOffsetPlus1('cpu'); }); function inputZYX(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(a) { return a[this.thread.z][this.thread.y][this.thread.x]; }) .setOutput([2, 4, 4]); const a = new Float32Array(32); a.set([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32]); const result = kernel(input(a, [2, 4, 4])); assert.deepEqual(result.map(function(v) { return v.map(function(v) { return Array.from(v); }); }), [[[1,2],[3,4],[5,6],[7,8]],[[9,10],[11,12],[13,14],[15,16]],[[17,18],[19,20],[21,22],[23,24]],[[25,26],[27,28],[29,30],[31,32]]]); gpu.destroy(); } test("inputZYX auto", () => { inputZYX(); }); test("inputZYX gpu", () => { inputZYX('gpu'); }); (GPU.isWebGLSupported ? test : skip)("inputZYX webgl", () => { inputZYX('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("inputZYX webgl2", () => { inputZYX('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)("inputZYX headlessgl", () => { inputZYX('headlessgl'); }); test("inputZYX cpu", () => { inputZYX('cpu'); }); function inputZYXVariables(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(a, x, y, z) { return a[z][y][x]; }) .setOutput([1]); const a = new Float32Array(32); a.set([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32]); const aInput = input(a, [2, 4, 4]); assert.deepEqual(Array.from(kernel(aInput, 1, 2, 3)), [30]); assert.deepEqual(Array.from(kernel(aInput, 0, 2, 3)), [29]); assert.deepEqual(Array.from(kernel(aInput, 0, 2, 1)), [13]); assert.deepEqual(Array.from(kernel(aInput, 1, 2, 2)), [22]); assert.deepEqual(Array.from(kernel(aInput, 0, 2, 2)), [21]); gpu.destroy(); } test("inputZYXVariables auto", () => { inputZYXVariables(); }); test("inputZYXVariables gpu", () => { inputZYXVariables('gpu'); }); (GPU.isWebGLSupported ? test : skip)("inputZYXVariables webgl", () => { inputZYXVariables('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("inputZYXVariables webgl2", () => { inputZYXVariables('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)("inputZYXVariables headlessgl", () => { inputZYXVariables('headlessgl'); }); test("inputZYXVariables cpu", () => { inputZYXVariables('cpu'); }); function inputInt32ArrayX(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(a) { return a[this.thread.x]; }) .setPrecision('unsigned') .setOutput([9]); const a = new Int32Array([1,2,3,4,5,6,7,8,9]); const result = kernel(input(a, [3, 3])); assert.deepEqual(result, new Float32Array([1,2,3,4,5,6,7,8,9])); gpu.destroy(); } test("inputInt32ArrayX auto", () => { inputInt32ArrayX(); }); test("inputInt32ArrayX gpu", () => { inputInt32ArrayX('gpu'); }); (GPU.isWebGLSupported ? test : skip)("inputInt32ArrayX webgl", () => { inputInt32ArrayX('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("inputInt32ArrayX webgl2", () => { inputInt32ArrayX('webgl2'); }); test("inputInt32ArrayX cpu", () => { inputInt32ArrayX('cpu'); }); test('.toArray() with array', () => { assert.deepEqual(input([1,2,3,4], [4]).toArray(), [1,2,3,4]); }); test('.toArray() with matrix', () => { assert.deepEqual(input([1,2,3,4,5,6,7,8], [4,2]).toArray(), [new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8])]); }); test('.toArray() with grid', () => { assert.deepEqual( input([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], [4,2,2]).toArray(), [ [ new Float32Array([1,2,3,4]), new Float32Array([5,6,7,8]), ], [ new Float32Array([9,10,11,12]), new Float32Array([13,14,15,16]) ] ] ); }); ================================================ FILE: test/features/internally-defined-matrices.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: internally defined matrices'); function testMatrix2(mode) { const gpu = new GPU({ mode }); function getMatrix() { const matrix = [ [1,2], [3,4] ]; return matrix; } gpu.addFunction(getMatrix); const kernel = gpu.createKernel(function(y, x) { return getMatrix()[y][x]; }, { output: [1] }); assert.equal(kernel(0, 0)[0], 1); assert.equal(kernel(0, 1)[0], 2); assert.equal(kernel(1, 0)[0], 3); assert.equal(kernel(1, 1)[0], 4); gpu.destroy(); } test('matrix2 auto', () => { testMatrix2(); }); test('matrix2 gpu', () => { testMatrix2('gpu'); }); (GPU.isWebGLSupported ? test : skip)('matrix2 webgl', () => { testMatrix2('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('matrix2 webgl2', () => { testMatrix2('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('matrix2 headlessgl', () => { testMatrix2('headlessgl'); }); test('matrix2 cpu', () => { testMatrix2('cpu'); }); function testMatrix3(mode) { const gpu = new GPU({ mode }); function getMatrix() { const matrix = [ [1,2,3], [4,5,6], [7,8,9], ]; return matrix; } gpu.addFunction(getMatrix); const kernel = gpu.createKernel(function(y, x) { return getMatrix()[y][x]; }, { output: [1] }); assert.equal(kernel(0, 0)[0], 1); assert.equal(kernel(0, 1)[0], 2); assert.equal(kernel(0, 2)[0], 3); assert.equal(kernel(1, 0)[0], 4); assert.equal(kernel(1, 1)[0], 5); assert.equal(kernel(1, 2)[0], 6); assert.equal(kernel(2, 0)[0], 7); assert.equal(kernel(2, 1)[0], 8); assert.equal(kernel(2, 2)[0], 9); gpu.destroy(); } test('matrix3 auto', () => { testMatrix3(); }); test('matrix3 gpu', () => { testMatrix3('gpu'); }); (GPU.isWebGLSupported ? test : skip)('matrix3 webgl', () => { testMatrix3('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('matrix3 webgl2', () => { testMatrix3('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('matrix3 headlessgl', () => { testMatrix3('headlessgl'); }); test('matrix3 cpu', () => { testMatrix3('cpu'); }); function testMatrix4(mode) { const gpu = new GPU({ mode }); function getMatrix() { const matrix = [ [1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16], ]; return matrix; } gpu.addFunction(getMatrix); const kernel = gpu.createKernel(function(y, x) { return getMatrix()[y][x]; }, { output: [1] }); assert.equal(kernel(0, 0)[0], 1); assert.equal(kernel(0, 1)[0], 2); assert.equal(kernel(0, 2)[0], 3); assert.equal(kernel(0, 3)[0], 4); assert.equal(kernel(1, 0)[0], 5); assert.equal(kernel(1, 1)[0], 6); assert.equal(kernel(1, 2)[0], 7); assert.equal(kernel(1, 3)[0], 8); assert.equal(kernel(2, 0)[0], 9); assert.equal(kernel(2, 1)[0], 10); assert.equal(kernel(2, 2)[0], 11); assert.equal(kernel(2, 3)[0], 12); assert.equal(kernel(3, 0)[0], 13); assert.equal(kernel(3, 1)[0], 14); assert.equal(kernel(3, 2)[0], 15); assert.equal(kernel(3, 3)[0], 16); gpu.destroy(); } test('matrix4 auto', () => { testMatrix4(); }); test('matrix4 gpu', () => { testMatrix4('gpu'); }); (GPU.isWebGLSupported ? test : skip)('matrix4 webgl', () => { testMatrix4('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('matrix4 webgl2', () => { testMatrix4('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('matrix4 headlessgl', () => { testMatrix4('headlessgl'); }); test('matrix4 cpu', () => { testMatrix4('cpu'); }); ================================================ FILE: test/features/json.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('json serialize'); function testJSONSerialize(mode) { const gpu = new GPU({mode}); const kernel = gpu.createKernel(function (value) { return value; }, {output: [1]}); kernel(1); const json = kernel.toJSON(); const jsonKernel = gpu.createKernel(json); assert.equal(jsonKernel(3)[0], 3); } test('auto', () => { testJSONSerialize(); }); test('gpu', () => { testJSONSerialize('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testJSONSerialize('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testJSONSerialize('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testJSONSerialize('headlessgl'); }); test('cpu', () => { testJSONSerialize('cpu'); }); ================================================ FILE: test/features/legacy-encoder.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, HeadlessGLKernel, WebGLKernel, WebGL2Kernel } = require('../../src'); describe('features: legacy encoder'); function testLegacyEncoderOff(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return 1; }, { output: [1], precision: 'unsigned' }); assert.equal(kernel()[0], 1); gpu.destroy(); } test('off auto', () => { testLegacyEncoderOff(); }); (GPU.isWebGLSupported ? test : skip)('off webgl', () => { testLegacyEncoderOff('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('off webgl2', () => { testLegacyEncoderOff('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('off headlessgl', () => { testLegacyEncoderOff('headlessgl'); }); test('off cpu', () => { testLegacyEncoderOff('cpu'); }); function testLegacyEncoderOn(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return 1; }, { output: [1], precision: 'unsigned', useLegacyEncoder: true, }); assert.equal(kernel()[0], 1); gpu.destroy(); } test('on auto', () => { testLegacyEncoderOn(); }); (GPU.isWebGLSupported ? test : skip)('on webgl', () => { testLegacyEncoderOn('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('on webgl2', () => { testLegacyEncoderOn('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('on headlessgl', () => { testLegacyEncoderOn('headlessgl'); }); test('on cpu', () => { testLegacyEncoderOn('cpu'); }); function testSubKernelsLegacyEncoderOff(mode) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const kernel = gpu.createKernelMap([ addOne, ], function() { const result = addOne(1); return result + 1; }, { output: [1], precision: 'unsigned' }); assert.equal(kernel()[0][0], 2); assert.equal(kernel().result[0], 3); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('subKernels off auto', () => { testSubKernelsLegacyEncoderOff(); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('subKernels off webgl', () => { testSubKernelsLegacyEncoderOff('webgl'); }); (GPU.isWebGL2Supported && GPU.isKernelMapSupported ? test : skip)('subKernels off webgl2', () => { testSubKernelsLegacyEncoderOff('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('subKernels off headlessgl', () => { testSubKernelsLegacyEncoderOff('headlessgl'); }); test('subKernels off cpu', () => { testSubKernelsLegacyEncoderOff('cpu'); }); function testSubKernelsLegacyEncoderOn(mode) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const kernel = gpu.createKernelMap([ addOne, ], function() { const value = addOne(1); return value + 1; }, { output: [1], precision: 'unsigned', useLegacyEncoder: true, }); assert.equal(kernel()[0][0], 2); assert.equal(kernel().result[0], 3); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('subKernels on auto', () => { testSubKernelsLegacyEncoderOn(); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('subKernels on webgl', () => { testSubKernelsLegacyEncoderOn('webgl'); }); (GPU.isWebGL2Supported && GPU.isKernelMapSupported ? test : skip)('subKernels on webgl2', () => { testSubKernelsLegacyEncoderOn('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('subKernels on headlessgl', () => { testSubKernelsLegacyEncoderOn('headlessgl'); }); test('subKernels on cpu', () => { testSubKernelsLegacyEncoderOn('cpu'); }); test('HeadlessGLKernel.getMainResultKernelPackedPixels useLegacyEncoder = false', () => { const result = HeadlessGLKernel.prototype.getMainResultKernelPackedPixels.apply({ useLegacyEncoder: false }); assert.equal(result, ` threadId = indexTo3D(index, uOutputDim); kernel(); gl_FragData[0] = encode32(kernelResult); `); }); test('WebGLKernel.getMainResultKernelPackedPixels useLegacyEncoder = false', () => { const result = WebGLKernel.prototype.getMainResultKernelPackedPixels.apply({ useLegacyEncoder: false }); assert.equal(result, ` threadId = indexTo3D(index, uOutputDim); kernel(); gl_FragData[0] = encode32(kernelResult); `); }); test('WebGL2Kernel.getMainResultKernelPackedPixels useLegacyEncoder = false', () => { const result = WebGL2Kernel.prototype.getMainResultKernelPackedPixels.apply({ useLegacyEncoder: false }); assert.equal(result, ` threadId = indexTo3D(index, uOutputDim); kernel(); data0 = encode32(kernelResult); `); }); test('HeadlessGLKernel.getMainResultKernelPackedPixels useLegacyEncoder = true', () => { const result = HeadlessGLKernel.prototype.getMainResultKernelPackedPixels.apply({ useLegacyEncoder: true }); assert.equal(result, ` threadId = indexTo3D(index, uOutputDim); kernel(); gl_FragData[0] = legacyEncode32(kernelResult); `); }); test('WebGLKernel.getMainResultKernelPackedPixels useLegacyEncoder = true', () => { const result = WebGLKernel.prototype.getMainResultKernelPackedPixels.apply({ useLegacyEncoder: true }); assert.equal(result, ` threadId = indexTo3D(index, uOutputDim); kernel(); gl_FragData[0] = legacyEncode32(kernelResult); `); }); test('WebGL2Kernel.getMainResultKernelPackedPixels useLegacyEncoder = true', () => { const result = WebGL2Kernel.prototype.getMainResultKernelPackedPixels.apply({ useLegacyEncoder: true }); assert.equal(result, ` threadId = indexTo3D(index, uOutputDim); kernel(); data0 = legacyEncode32(kernelResult); `); }); test('HeadlessGLKernel.getMainResultSubKernelPackedPixels useLegacyEncoder = false', () => { const result = HeadlessGLKernel.prototype.getMainResultSubKernelPackedPixels.apply({ useLegacyEncoder: false, subKernels: [{ name: 'subKernel1' }] }); assert.equal(result, ` gl_FragData[1] = encode32(subKernelResult_subKernel1); `); }); test('WebGLKernel.getMainResultSubKernelPackedPixels useLegacyEncoder = false', () => { const result = WebGLKernel.prototype.getMainResultSubKernelPackedPixels.apply({ useLegacyEncoder: false, subKernels: [{ name: 'subKernel1' }] }); assert.equal(result, ` gl_FragData[1] = encode32(subKernelResult_subKernel1); `); }); test('WebGL2Kernel.getMainResultSubKernelPackedPixels useLegacyEncoder = false', () => { const result = WebGL2Kernel.prototype.getMainResultSubKernelPackedPixels.apply({ useLegacyEncoder: false, subKernels: [{ name: 'subKernel1' }] }); assert.equal(result, ` data1 = encode32(subKernelResult_subKernel1); `); }); test('HeadlessGLKernel.getMainResultSubKernelPackedPixels useLegacyEncoder = true', () => { const result = HeadlessGLKernel.prototype.getMainResultSubKernelPackedPixels.apply({ useLegacyEncoder: true, subKernels: [{ name: 'subKernel1' }] }); assert.equal(result, ` gl_FragData[1] = legacyEncode32(subKernelResult_subKernel1); `); }); test('WebGLKernel.getMainResultSubKernelPackedPixels useLegacyEncoder = true', () => { const result = WebGLKernel.prototype.getMainResultSubKernelPackedPixels.apply({ useLegacyEncoder: true, subKernels: [{ name: 'subKernel1' }] }); assert.equal(result, ` gl_FragData[1] = legacyEncode32(subKernelResult_subKernel1); `); }); test('WebGL2Kernel.getMainResultSubKernelPackedPixels useLegacyEncoder = true', () => { const result = WebGL2Kernel.prototype.getMainResultSubKernelPackedPixels.apply({ useLegacyEncoder: true, subKernels: [{ name: 'subKernel1' }] }); assert.equal(result, ` data1 = legacyEncode32(subKernelResult_subKernel1); `); }); ================================================ FILE: test/features/loops.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('loops - for'); function forLoopTest(mode) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function(a, b) { let x = 0; for (let i = 0; i < 10; i++) { x = x + 1; } return (a[this.thread.x] + b[this.thread.x] + x); }, { output : [6] }); assert.ok( f !== null, 'function generated test'); const a = [1, 2, 3, 5, 6, 7]; const b = [4, 5, 6, 1, 2, 3]; const res = f(a,b); const exp = [15, 17, 19, 16, 18, 20]; assert.deepEqual(Array.from(res), exp); gpu.destroy(); } test('auto', () => { forLoopTest(null); }); test('gpu', () => { forLoopTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { forLoopTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { forLoopTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { forLoopTest('headlessgl'); }); test('cpu', () => { forLoopTest('cpu'); }); describe('loops - for with constant'); function forWithConstantTest(mode) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function(a, b) { let x = 0; for(let i = 0; i < this.constants.max; i++) { x = x + 1; } return (a[this.thread.x] + b[this.thread.x] + x); }, { output : [6], constants: { max: 10 } }); assert.ok( f !== null, 'function generated test'); const a = [1, 2, 3, 5, 6, 7]; const b = [4, 5, 6, 1, 2, 3]; const res = f(a,b); const exp = [15, 17, 19, 16, 18, 20]; assert.deepEqual(Array.from(res), exp); gpu.destroy(); } test('forConstantLoopTest auto', () => { forWithConstantTest(null); }); test('forConstantLoopTest gpu', () => { forWithConstantTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('forConstantLoopTest webgl', () => { forWithConstantTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('forConstantLoopTest webgl2', () => { forWithConstantTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('forConstantLoopTest headlessgl', () => { forWithConstantTest('headlessgl'); }); test('forConstantLoopTest cpu', () => { forWithConstantTest('cpu'); }); describe('loops - while'); function whileLoopTest(mode) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function(a, b) { let x = 0; let i = 0; while (i++ < 10) { x = x + 1; } return (a[this.thread.x] + b[this.thread.x] + x); }, { output : [6] }); const a = [1, 2, 3, 5, 6, 7]; const b = [4, 5, 6, 1, 2, 3]; const res = f(a,b); const exp = [15, 17, 19, 16, 18, 20]; assert.deepEqual(Array.from(res), exp); gpu.destroy(); } test('auto', () => { whileLoopTest(null); }); test('gpu', () => { whileLoopTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { whileLoopTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { whileLoopTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { whileLoopTest('headlessgl'); }); test('cpu', () => { whileLoopTest('cpu'); }); describe('loops - while with constant'); function whileWithConstantTest(mode) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function(a, b) { let x = 0; let i = 0; while (i++ < this.constants.max) { x = x + 1; } return (a[this.thread.x] + b[this.thread.x] + x); }, { output : [6], constants: { max: 10 } }); assert.ok( f !== null, 'function generated test'); const a = [1, 2, 3, 5, 6, 7]; const b = [4, 5, 6, 1, 2, 3]; const res = f(a,b); const exp = [15, 17, 19, 16, 18, 20]; assert.deepEqual(Array.from(res), exp); gpu.destroy(); } test('auto', () => { whileWithConstantTest(null); }); test('gpu', () => { whileWithConstantTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { whileWithConstantTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { whileWithConstantTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { whileWithConstantTest('headlessgl'); }); test('cpu', () => { whileWithConstantTest('cpu'); }); describe('loops - evil while loop'); function evilWhileLoopTest(mode ) { function evilWhileKernelFunction(a, b) { let x = 0; let i = 0; //10000000 or 10 million is the approx upper limit on a chrome + GTX 780 while(i<100) { x = x + 1.0; ++i; } return (a[this.thread.x] + b[this.thread.x] + x); } const evil_while_a = [1, 2, 3, 5, 6, 7]; const evil_while_b = [4, 5, 6, 1, 2, 3]; const evil_while_cpuRef = new GPU({ mode: 'cpu' }); const evil_while_cpuRef_f = evil_while_cpuRef.createKernel(evilWhileKernelFunction, { output : [6], loopMaxIterations: 10000, }); const evil_while_exp = evil_while_cpuRef_f(evil_while_a,evil_while_b); const gpu = new GPU({ mode }); const f = gpu.createKernel(evilWhileKernelFunction, { output : [6] }); assert.ok( f !== null, 'function generated test'); const res = f(evil_while_a,evil_while_b); for(let i = 0; i < evil_while_exp.length; ++i) { assert.equal(evil_while_exp[i], res[i], 'Result arr idx: '+i); } evil_while_cpuRef.destroy(); gpu.destroy(); } test('auto', () => { evilWhileLoopTest(null); }); test('gpu', () => { evilWhileLoopTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { evilWhileLoopTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { evilWhileLoopTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { evilWhileLoopTest('headlessgl'); }); test('cpu', () => { evilWhileLoopTest('cpu'); }); describe('loops - do while'); function doWhileLoopTest(mode) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function(a, b) { let x = 0; let i = 0; do { x = x + 1; i++; } while (i < 10); return (a[this.thread.x] + b[this.thread.x] + x); }, { output : [6] }); assert.ok( f !== null, 'function generated test'); const a = [1, 2, 3, 5, 6, 7]; const b = [4, 5, 6, 1, 2, 3]; const res = f(a,b); const exp = [15, 17, 19, 16, 18, 20]; assert.deepEqual(Array.from(res), exp); gpu.destroy(); } test('auto', () => { doWhileLoopTest(null); }); test('gpu', () => { doWhileLoopTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { doWhileLoopTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { doWhileLoopTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { doWhileLoopTest('headlessgl'); }); test('cpu', () => { doWhileLoopTest('cpu'); }); describe('loops - do while with constant'); function doWhileWithConstantLoop(mode) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function(a, b) { let x = 0; let i = 0; do { x = x + 1; i++; } while (i < this.constants.max); return (a[this.thread.x] + b[this.thread.x] + x); }, { output : [6], constants: { max: 10 } }); assert.ok( f !== null, 'function generated test'); const a = [1, 2, 3, 5, 6, 7]; const b = [4, 5, 6, 1, 2, 3]; const res = f(a,b); const exp = [15, 17, 19, 16, 18, 20]; assert.deepEqual(Array.from(res), exp); gpu.destroy(); } test('auto', () => { doWhileWithConstantLoop(null); }); test('gpu', () => { doWhileWithConstantLoop('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { doWhileWithConstantLoop('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { doWhileWithConstantLoop('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { doWhileWithConstantLoop('headlessgl'); }); test('cpu', () => { doWhileWithConstantLoop('cpu'); }); ================================================ FILE: test/features/math-object.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: math object'); function mathProps(mode) { const props = ['E','LN10','LN2','LOG10E','LOG2E','PI','SQRT1_2','SQRT2']; const gpu = new GPU({ mode }); for (let i = 0; i < props.length; i++) { const prop = props[i]; const kernel = gpu.createKernel(`function() { return Math.${prop}; }`, { output: [1] }); assert.equal(kernel()[0].toFixed(6), Math[prop].toFixed(6)); } gpu.destroy(); } test('All Math properties auto', () => { mathProps(); }); test('All Math properties gpu', () => { mathProps('gpu'); }); (GPU.isWebGLSupported ? test : skip)('All Math properties webgl', () => { mathProps('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('All Math properties webgl2', () => { mathProps('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('All Math properties headlessgl', () => { mathProps('headlessgl'); }); test('All Math properties cpu', () => { mathProps('cpu'); }); function singleArgumentMathMethods(mode) { const methods = [ 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil', // 'clz32', // not supported, bits directly are hard 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', // 'hypot', // not supported, dynamically sized 'log', 'log10', 'log1p', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc', ]; const gpu = new GPU({ mode }); for (let i = 0; i < methods.length; i++) { const method = methods[i]; const kernel = gpu.createKernel(`function(value) { return Math.${method}(value); }`, { output: [1] }); for (let j = 0; j < 10; j++) { assert.equal(kernel(j / 10)[0].toFixed(3), Math[method](j / 10).toFixed(3), `Math.${method}(${j / 10})`); } } gpu.destroy(); } test('Single argument Math methods auto', () => { singleArgumentMathMethods(); }); test('Single argument Math methods gpu', () => { singleArgumentMathMethods('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Single argument Math methods webgl', () => { singleArgumentMathMethods('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Single argument Math methods webgl2', () => { singleArgumentMathMethods('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Single argument Math methods headlessgl', () => { singleArgumentMathMethods('headlessgl'); }); test('Single argument Math methods cpu', () => { singleArgumentMathMethods('cpu'); }); function twoArgumentMathMethods(mode) { const methods = [ 'atan2', 'imul', 'max', 'min', 'pow', ]; const gpu = new GPU({ mode }); for (let i = 0; i < methods.length; i++) { const method = methods[i]; const kernel = gpu.createKernel(`function(value1, value2) { return Math.${method}(value1, value2); }`, { output: [1] }); for (let j = 0; j < 10; j++) { const value1 = j / 10; const value2 = value1; assert.equal(kernel(value1, value2)[0].toFixed(3), Math[method](value1, value2).toFixed(3), `Math.${method}(${value1}, ${value2})`); } } gpu.destroy(); } test('Two argument Math methods auto', () => { twoArgumentMathMethods(); }); test('Two argument Math methods gpu', () => { twoArgumentMathMethods('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Two argument Math methods webgl', () => { twoArgumentMathMethods('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Two argument Math methods webgl2', () => { twoArgumentMathMethods('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Two argument Math methods headlessgl', () => { twoArgumentMathMethods('headlessgl'); }); test('Two argument Math methods cpu', () => { twoArgumentMathMethods('cpu'); }); function sqrtABTest(mode) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function(a, b) { return Math.sqrt(a[this.thread.x] * b[this.thread.x]); }, { output : [6] }); const a = [3, 4, 5, 6, 7, 8]; const b = [3, 4, 5, 6, 7, 8]; const res = f(a,b); const exp = [3, 4, 5, 6, 7, 8]; assert.deepEqual(Array.from(res), exp); gpu.destroy(); } test('sqrtAB auto', () => { sqrtABTest(null); }); test('sqrtAB gpu', () => { sqrtABTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('sqrtAB webgl', () => { sqrtABTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('sqrtAB webgl2', () => { sqrtABTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('sqrtAB headlessgl', () => { sqrtABTest('headlessgl'); }); test('sqrtAB cpu', () => { sqrtABTest('cpu'); }); function mathRandom(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return Math.random(); }, { output: [1] }); const result = kernel(); assert.ok(result[0] > 0 && result[0] < 1, `value was expected to be between o and 1, but was ${result[0]}`); } test('random auto', () => { mathRandom(); }); test('random gpu', () => { mathRandom('gpu'); }); (GPU.isWebGLSupported ? test : skip)('random webgl', () => { mathRandom('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('random webgl2', () => { mathRandom('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('random headlessgl', () => { mathRandom('headlessgl'); }); test('random cpu', () => { mathRandom('cpu'); }); ================================================ FILE: test/features/nested-function.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('nested function'); function nestedSumABTest(mode) { const gpu = new GPU({ mode }); const f = gpu.createKernel(function(a, b) { function custom_adder(a,b) { return a+b; } return custom_adder(a[this.thread.x], b[this.thread.x]); }, { output : [6] }); assert.ok(f !== null, 'function generated test'); const a = [1, 2, 3, 5, 6, 7]; const b = [4, 5, 6, 1, 2, 3]; const res = f(a,b); const exp = [5, 7, 9, 6, 8, 10]; assert.deepEqual(Array.from(res), exp); gpu.destroy(); } test('nested_sum auto', () => { nestedSumABTest(null); }); test('nested_sum gpu', () => { nestedSumABTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('nested_sum webgl', () => { nestedSumABTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('nested_sum webgl2', () => { nestedSumABTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('nested_sum headlessgl', () => { nestedSumABTest('headlessgl'); }); test('nested_sum cpu', () => { nestedSumABTest('cpu'); }); function testNestedInCustomFunction(mode) { function custom1() { function nested1() { return 1; } return nested1(); } const gpu = new GPU({ mode }); gpu.addFunction(custom1); const kernel = gpu.createKernel(function() { return custom1(); }, { output: [1] }); assert.deepEqual(kernel(), new Float32Array([1])); gpu.destroy(); } test('nested in custom auto', () => { testNestedInCustomFunction(); }); test('nested in custom gpu', () => { testNestedInCustomFunction('gpu'); }); (GPU.isWebGLSupported ? test : skip)('nested in custom webgl', () => { testNestedInCustomFunction('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('nested in custom webgl2', () => { testNestedInCustomFunction('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('nested in custom headlessgl', () => { testNestedInCustomFunction('headlessgl'); }); test('nested in custom cpu', () => { testNestedInCustomFunction('cpu'); }); ================================================ FILE: test/features/offscreen-canvas.js ================================================ if (typeof importScripts !== 'undefined') { // inside Worker importScripts('../../dist/gpu-browser.js'); onmessage = function (e) { const gpu = new GPU({ mode: e.data }); const a = [1,2,3]; const b = [3,2,1]; const kernel = gpu.createKernel(function(a, b) { return a[this.thread.x] - b[this.thread.x]; }) .setOutput([3]); postMessage({ mode: gpu.mode, result: kernel(a, b) }); gpu.destroy(); }; } else if (typeof isBrowser !== 'undefined' && isBrowser) { const { assert, skip, test, module: describe } = require('qunit'); describe('offscreen canvas'); function testOffscreenCanvas(mode, done) { const worker = new Worker('features/offscreen-canvas.js'); worker.onmessage = function (e) { const mode = e.data.mode; const result = e.data.result; assert.equal(mode, 'gpu', 'GPU mode used in Worker'); assert.deepEqual(result, Float32Array.from([-2, 0, 2])); done(); }; worker.postMessage(mode); } (GPU.isOffscreenCanvasSupported ? test : skip)('offscreen canvas auto', t => { testOffscreenCanvas(null, t.async()); }); (GPU.isOffscreenCanvasSupported ? test : skip)('offscreen canvas gpu', t => { testOffscreenCanvas('gpu', t.async()); }); (GPU.isOffscreenCanvasSupported ? test : skip)('offscreen canvas webgl', t => { testOffscreenCanvas('webgl', t.async()); }); (GPU.isOffscreenCanvasSupported ? test : skip)('offscreen canvas webgl2', t => { testOffscreenCanvas('webgl2', t.async()); }); (GPU.isOffscreenCanvasSupported ? test : skip)('offscreen canvas cpu', t => { testOffscreenCanvas('cpu', t.async()); }); } ================================================ FILE: test/features/optimize-float-memory.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, utils } = require('../../src'); describe('feature: optimizeFloatMemory'); function whenEnabledCallsCorrectRenderFunction(mode) { const gpu = new GPU({ mode }); const fn = gpu.createKernel(function() { return 1 }, { output: [1], precision: 'single', optimizeFloatMemory: true, }); const result = fn(); assert.equal(fn.TextureConstructor.name, 'GLTextureMemoryOptimized'); assert.equal(fn.formatValues, utils.erectMemoryOptimizedFloat); assert.equal(result[0], 1); } (GPU.isSinglePrecisionSupported && GPU.isGPUSupported ? test : skip)('when enabled calls correct render function gpu (GPU ONLY)', () => { whenEnabledCallsCorrectRenderFunction('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('when enabled calls correct render function webgl (GPU ONLY)', () => { whenEnabledCallsCorrectRenderFunction('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('when enabled calls correct render function webgl2 (GPU ONLY)', () => { whenEnabledCallsCorrectRenderFunction('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('when enabled calls correct render function headlessgl (GPU ONLY)', () => { whenEnabledCallsCorrectRenderFunction('headlessgl'); }); function whenEnabledCallsCorrectRenderFunction2D(mode) { const gpu = new GPU({ mode }); const fn = gpu.createKernel(function() { return 1 }, { output: [2, 2], precision: 'single', optimizeFloatMemory: true, }); const result = fn(); assert.equal(fn.TextureConstructor.name, 'GLTextureMemoryOptimized2D'); assert.equal(fn.formatValues, utils.erectMemoryOptimized2DFloat); assert.deepEqual(result.map(row => Array.from(row)), [[1,1],[1,1]]); } (GPU.isSinglePrecisionSupported && GPU.isGPUSupported ? test : skip)('when enabled calls correct render function 2d gpu (GPU ONLY)', () => { whenEnabledCallsCorrectRenderFunction2D('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('when enabled calls correct render function 2d webgl (GPU ONLY)', () => { whenEnabledCallsCorrectRenderFunction2D('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('when enabled calls correct render function 2d webgl2 (GPU ONLY)', () => { whenEnabledCallsCorrectRenderFunction2D('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('when enabled calls correct render function 2d headlessgl (GPU ONLY)', () => { whenEnabledCallsCorrectRenderFunction2D('headlessgl'); }); function whenEnabledCallsCorrectRenderFunction3D(mode) { const gpu = new GPU({ mode }); const fn = gpu.createKernel(function() { return 1 }, { output: [2, 2, 2], precision: 'single', optimizeFloatMemory: true, }); const result = fn(); assert.equal(fn.TextureConstructor.name, 'GLTextureMemoryOptimized3D'); assert.equal(fn.formatValues, utils.erectMemoryOptimized3DFloat); assert.deepEqual(result.map(matrix => matrix.map(row => Array.from(row))), [[[1,1],[1,1]],[[1,1],[1,1]]]); } (GPU.isSinglePrecisionSupported && GPU.isGPUSupported ? test : skip)('when enabled calls correct render function 3d gpu (GPU ONLY)', () => { whenEnabledCallsCorrectRenderFunction3D('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('when enabled calls correct render function 3d webgl (GPU ONLY)', () => { whenEnabledCallsCorrectRenderFunction3D('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('when enabled calls correct render function 3d webgl2 (GPU ONLY)', () => { whenEnabledCallsCorrectRenderFunction3D('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('when enabled calls correct render function 3d headlessgl (GPU ONLY)', () => { whenEnabledCallsCorrectRenderFunction3D('headlessgl'); }); function singlePrecision(mode) { const gpu = new GPU({ mode }); const array = [1,2,3,4,5]; const kernel = gpu.createKernel(function(array) { return array[this.thread.x]; }, { output: [5], optimizeFloatMemory: true, precision: 'single', }); const result = kernel(array); assert.deepEqual(Array.from(result), array); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isGPUSupported ? test : skip)('single precision auto', () => { singlePrecision(); }); (GPU.isSinglePrecisionSupported && GPU.isGPUSupported ? test : skip)('single precision gpu', () => { singlePrecision('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('single precision webgl', () => { singlePrecision('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('single precision webgl2', () => { singlePrecision('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('single precision headlessgl', () => { singlePrecision('headlessgl'); }); test('single precision cpu', () => { singlePrecision('cpu'); }); function float2DOutput(mode) { const gpu = new GPU({ mode }); const matrix = [ [1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], ]; const kernel = gpu.createKernel(function(matrix) { return matrix[this.thread.y][this.thread.x]; }, { output: [5, 3], optimizeFloatMemory: true, precision: 'single', }); const result = kernel(matrix); assert.deepEqual(result.map(row => Array.from(row)), matrix); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('float 2d output auto', () => { float2DOutput(); }); (GPU.isSinglePrecisionSupported && GPU.isGPUSupported ? test : skip)('float 2d output gpu', () => { float2DOutput('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('float 2d output webgl', () => { float2DOutput('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('float 2d output webgl2', () => { float2DOutput('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('float 2d output headlessgl', () => { float2DOutput('headlessgl'); }); test('float 2d output cpu', () => { float2DOutput('cpu'); }); function float3DOutput(mode) { const gpu = new GPU({ mode }); const cube = [ [ [1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], ], [ [16,17,18,19,20], [21,22,23,24,25], [26,27,28,29,30], ] ]; const kernel = gpu.createKernel(function(cube) { return cube[this.thread.z][this.thread.y][this.thread.x]; }, { output: [5, 3, 2], optimizeFloatMemory: true, precision: 'single', }); const result = kernel(cube); assert.deepEqual(result.map(matrix => matrix.map(row => Array.from(row))), cube); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('float 3d output auto', () => { float3DOutput(); }); (GPU.isSinglePrecisionSupported && GPU.isGPUSupported ? test : skip)('float 3d output gpu', () => { float3DOutput('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('float 3d output webgl', () => { float3DOutput('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('float 3d output webgl2', () => { float3DOutput('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('float 3d output headlessgl', () => { float3DOutput('headlessgl'); }); test('float 3d output cpu', () => { float3DOutput('cpu'); }); function floatPipelineOutput(mode) { const gpu = new GPU({ mode }); const array = [1,2,3,4,5]; const kernel = gpu.createKernel(function(array) { return array[this.thread.x]; }, { output: [5], optimizeFloatMemory: true, precision: 'single', pipeline: true, }); const result = kernel(array).toArray(); assert.deepEqual(Array.from(result), array); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isGPUSupported ? test : skip)('float pipeline output gpu (GPU only)', () => { floatPipelineOutput('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('float pipeline output webgl (GPU only)', () => { floatPipelineOutput('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('float pipeline output webgl2 (GPU only)', () => { floatPipelineOutput('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('float pipeline output headlessgl (GPU only)', () => { floatPipelineOutput('headlessgl'); }); function floatPipeline2DOutput(mode) { const gpu = new GPU({ mode }); const matrix = [ [1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], ]; const kernel = gpu.createKernel(function(matrix) { return matrix[this.thread.y][this.thread.x]; }, { output: [5, 3], optimizeFloatMemory: true, precision: 'single', pipeline: true, }); const texture = kernel(matrix); const result = texture.toArray(); assert.deepEqual(result.map(row => Array.from(row)), matrix); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isGPUSupported ? test : skip)('float pipeline 2d output gpu (GPU Only)', () => { floatPipeline2DOutput('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('float pipeline 2d output webgl (GPU Only)', () => { floatPipeline2DOutput('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('float pipeline 2d output webgl2 (GPU Only)', () => { floatPipeline2DOutput('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('float pipeline 2d output headlessgl (GPU Only)', () => { floatPipeline2DOutput('headlessgl'); }); function floatPipeline3DOutput(mode) { const gpu = new GPU({ mode }); const cube = [ [ [1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], ], [ [16,17,18,19,20], [21,22,23,24,25], [26,27,28,29,30], ] ]; const kernel = gpu.createKernel(function(cube) { return cube[this.thread.z][this.thread.y][this.thread.x]; }, { output: [5, 3, 2], optimizeFloatMemory: true, precision: 'single', pipeline: true, }); const result = kernel(cube).toArray(); assert.deepEqual(result.map(matrix => matrix.map(row => Array.from(row))), cube); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isGPUSupported ? test : skip)('float pipeline 3d output gpu (GPU only)', () => { floatPipeline3DOutput('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('float pipeline 3d output webgl (GPU only)', () => { floatPipeline3DOutput('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('float pipeline 3d output webgl2 (GPU only)', () => { floatPipeline3DOutput('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('float pipeline 3d output headlessgl (GPU only)', () => { floatPipeline3DOutput('headlessgl'); }); ================================================ FILE: test/features/output.js ================================================ const { assert, test, module: describe, only, skip } = require('qunit'); const { GPU } = require('../../src'); describe('features: output'); function outputArray(mode) { const gpu = new GPU({ mode }); const input = [1,2,3,4,5]; const kernel = gpu.createKernel(function(input) { return input[this.thread.x]; }, { output: [5] }); const result = kernel(input); assert.deepEqual(Array.from(result), input); gpu.destroy(); } test('output array auto', () => { outputArray(); }); test('output array gpu', () => { outputArray('gpu'); }); (GPU.isWebGLSupported ? test : skip)('output array webgl', () => { outputArray('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('output array webgl2', () => { outputArray('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('output array headlessgl', () => { outputArray('headlessgl'); }); test('output array cpu', () => { outputArray('cpu'); }); function outputMatrix(mode) { const gpu = new GPU({ mode }); const input = [ [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], ]; const kernel = gpu.createKernel(function(input) { return input[this.thread.y][this.thread.x]; }, { output: [5, 5] }); const result = kernel(input); assert.deepEqual(result.map(array => Array.from(array)), input); gpu.destroy(); } test('output matrix auto', () => { outputMatrix(); }); test('output matrix gpu', () => { outputMatrix('gpu'); }); (GPU.isWebGLSupported ? test : skip)('output matrix webgl', () => { outputMatrix('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('output matrix webgl2', () => { outputMatrix('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('output matrix headlessgl', () => { outputMatrix('headlessgl'); }); test('output matrix cpu', () => { outputMatrix('cpu'); }); function outputCube(mode) { const gpu = new GPU({ mode }); const input = [ [ [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], ], [ [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], ], [ [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], ], [ [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], ], [ [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], ] ]; const kernel = gpu.createKernel(function(input) { return input[this.thread.z][this.thread.y][this.thread.x]; }, { output: [5, 5, 5] }); const result = kernel(input); assert.deepEqual(result.map(matrix => matrix.map(array => Array.from(array))), input); gpu.destroy(); } test('output cube auto', () => { outputCube(); }); test('output cube gpu', () => { outputCube('gpu'); }); (GPU.isWebGLSupported ? test : skip)('output cube webgl', () => { outputCube('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('output cube webgl2', () => { outputCube('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('output cube headlessgl', () => { outputCube('headlessgl'); }); test('output cube cpu', () => { outputCube('cpu'); }); function outputGraphicalArray(mode) { const gpu = new GPU({ mode }); const mockContext = { getExtension: () => {} }; const mockCanvas = { getContext: () => mockContext, }; assert.throws(() => { const kernel = gpu.createKernel(function(input) { return input[this.thread.x]; }, { canvas: mockCanvas, output: [5], graphical: true }); kernel([1]); }, new Error('Output must have 2 dimensions on graphical mode')); gpu.destroy(); } test('graphical output array auto', () => { outputGraphicalArray(); }); test('graphical output array gpu', () => { outputGraphicalArray('gpu'); }); (GPU.isWebGLSupported ? test : skip)('graphical output array webgl', () => { outputGraphicalArray('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('graphical output array webgl2', () => { outputGraphicalArray('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('graphical output array headlessgl', () => { outputGraphicalArray('headlessgl'); }); test('graphical output array cpu', () => { outputGraphicalArray('cpu'); }); function outputGraphicalMatrix(mode, canvas, context) { const gpu = new GPU({ mode }); const input = [ [0.25,.50], [.75,1], ]; const kernel = gpu.createKernel(function(input) { const color = input[this.thread.y][this.thread.x]; this.color(color, color, color, color); }, { context, canvas, output: [2, 2], graphical: true }); const result = kernel(input); assert.equal(result, undefined); const pixels = Array.from(kernel.getPixels()); gpu.destroy(); return pixels; } (GPU.isWebGLSupported ? test : skip)('graphical output matrix webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl', { premultipliedAlpha: false }); const pixels = outputGraphicalMatrix('webgl', canvas, context); assert.deepEqual(pixels, [ 191, 191, 191, 191, 255, 255, 255, 255, 64, 64, 64, 64, 128, 128, 128, 128 ]); }); (GPU.isWebGL2Supported ? test : skip)('graphical output matrix webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2', { premultipliedAlpha: false }); const pixels = outputGraphicalMatrix('webgl2', canvas, context); assert.deepEqual(pixels, [ 191, 191, 191, 191, 255, 255, 255, 255, 64, 64, 64, 64, 128, 128, 128, 128 ]); }); (GPU.isHeadlessGLSupported ? test : skip)('graphical output matrix headlessgl', () => { const pixels = outputGraphicalMatrix('headlessgl'); assert.deepEqual(pixels, [ 191, 191, 191, 191, 255, 255, 255, 255, 64, 64, 64, 64, 128, 128, 128, 128 ]); }); (GPU.isCanvasSupported ? test : skip)('graphical output matrix cpu with real canvas', () => { const pixels = outputGraphicalMatrix('cpu'); assert.deepEqual(pixels, [ 191, 191, 191, 191, 255, 255, 255, 255, 63, 63, 63, 63, 127, 127, 127, 127 ]); }); test('graphical output matrix cpu with mocked canvas', () => { // allow tests on node or browser let outputImageData = null; const mockContext = { createImageData: () => { return { data: new Uint8ClampedArray(2 * 2 * 4) }; }, putImageData: (_outputImageData) => { outputImageData = _outputImageData; }, getImageData: () => { return outputImageData; }, getExtension: () => { return null; } }; const mockCanvas = { getContext: () => mockContext, }; const pixels = outputGraphicalMatrix('cpu', mockCanvas, mockContext); assert.deepEqual(pixels, [ 191, 191, 191, 191, 255, 255, 255, 255, 63, 63, 63, 63, 127, 127, 127, 127 ]); }); function outputGraphicalCube(mode) { const gpu = new GPU({ mode }); const mockContext = { getExtension: () => {} }; const mockCanvas = { getContext: () => mockContext }; assert.throws(() => { const kernel = gpu.createKernel(function(input) { return input[this.thread.x]; }, { canvas: mockCanvas, output: [5,5,5], graphical: true }); kernel([1]); }, new Error('Output must have 2 dimensions on graphical mode')); gpu.destroy(); } test('graphical output array auto', () => { outputGraphicalCube(); }); test('graphical output array gpu', () => { outputGraphicalCube('gpu'); }); (GPU.isWebGLSupported ? test : skip)('graphical output array webgl', () => { outputGraphicalCube('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('graphical output array webgl2', () => { outputGraphicalCube('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('graphical output array headlessgl', () => { outputGraphicalCube('headlessgl'); }); test('graphical output array cpu', () => { outputGraphicalCube('cpu'); }); ================================================ FILE: test/features/promise-api.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('features: promise api'); function promiseApiFunctionReturn(mode, done) { const gpu = new GPU({ mode }); const kernelFn = function() { return 42.0; }; const settings = { output : [1] }; // Setup kernel const kernel = gpu.createKernel(kernelFn, settings); // Get promise object const promiseObj = kernel.exec(); assert.ok(promiseObj !== null, 'Promise object generated test'); promiseObj .then((res) => { assert.equal(res[0], 42.0 ); gpu.destroy(); done(); }) .catch((err) => { throw err; }); } test('functionReturn auto', t => { promiseApiFunctionReturn(null, t.async()); }); test('functionReturn gpu', t => { promiseApiFunctionReturn('gpu', t.async()); }); (GPU.isWebGLSupported ? test : skip)('functionReturn webgl', t => { promiseApiFunctionReturn('webgl', t.async()); }); (GPU.isWebGL2Supported ? test : skip)('functionReturn webgl2', t => { promiseApiFunctionReturn('webgl2', t.async()); }); (GPU.isHeadlessGLSupported ? test : skip)('functionReturn headlessgl', t => { promiseApiFunctionReturn('headlessgl', t.async()); }); test('functionReturn cpu', t => { promiseApiFunctionReturn('cpu', t.async()); }); ================================================ FILE: test/features/raw-output.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('features: raw output'); function rawUnsignedPrecisionRenderOutput(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return v[this.thread.x]; }, { output: [1], precision: 'unsigned', }); kernel.build([1]); kernel.run([1]); const result = kernel.renderRawOutput(); assert.equal(result.constructor, Uint8Array); assert.deepEqual(result, new Uint8Array(new Float32Array([1]).buffer)); gpu.destroy(); } test('raw unsigned precision render output auto', () => { rawUnsignedPrecisionRenderOutput(); }); (GPU.isGPUSupported ? test : skip)('raw unsigned precision render output gpu', () => { rawUnsignedPrecisionRenderOutput('gpu'); }); (GPU.isWebGLSupported ? test : skip)('raw unsigned precision render output webgl', () => { rawUnsignedPrecisionRenderOutput('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('raw unsigned precision render output webgl2', () => { rawUnsignedPrecisionRenderOutput('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('raw unsigned precision render output headlessgl', () => { rawUnsignedPrecisionRenderOutput('headlessgl'); }); test('raw unsigned precision render output cpu', () => { assert.throws(() => { rawUnsignedPrecisionRenderOutput('cpu'); }); }); function rawSinglePrecisionRenderOutput(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return v[this.thread.x]; }, { output: [1], precision: 'single', }); kernel.build([1]); kernel.run([1]); const result = kernel.renderRawOutput(); assert.equal(result.constructor, Float32Array); // TODO: there is an odd bug in headless gl that causes this to output: // "0": 1, // "1": 2097761, // "2": 2.120494879387071e-36, // "3": -814303.375 // For the time being, just check the first value, until this is fixed // assert.deepEqual(result, new Float32Array([1, 0, 0, 0])); assert.deepEqual(result.length, 4); assert.deepEqual(result[0], 1); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('raw single precision render output auto', () => { rawSinglePrecisionRenderOutput(); }); (GPU.isGPUSupported && GPU.isSinglePrecisionSupported ? test : skip)('raw single precision render output gpu', () => { rawSinglePrecisionRenderOutput('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('raw single precision render output webgl', () => { rawSinglePrecisionRenderOutput('webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('raw single precision render output webgl2', () => { rawSinglePrecisionRenderOutput('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('raw single precision render output headlessgl', () => { rawSinglePrecisionRenderOutput('headlessgl'); }); test('raw single precision render output cpu', () => { assert.throws(() => { rawSinglePrecisionRenderOutput('cpu'); }); }); ================================================ FILE: test/features/read-color-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: read color texture'); function colorSyntaxTest(mode) { const gpu = new GPU({ mode }); const createTexture = gpu.createKernel( function(value) { this.color( value[this.thread.y][this.thread.x], value[this.thread.y][this.thread.x], value[this.thread.y][this.thread.x], value[this.thread.y][this.thread.x] ); } ) .setOutput([4, 4]) .setGraphical(true) .setPipeline(true); const readRTexture = gpu.createKernel( function(texture) { const pixel = texture[this.thread.y][this.thread.x]; return pixel.r; } ) .setOutput([4, 4]); const readGTexture = gpu.createKernel( function(texture) { const pixel = texture[this.thread.y][this.thread.x]; return pixel.g; } ) .setOutput([4, 4]); const readBTexture = gpu.createKernel( function(texture) { const pixel = texture[this.thread.y][this.thread.x]; return pixel.b; } ) .setOutput([4, 4]); const readATexture = gpu.createKernel( function(texture) { const pixel = texture[this.thread.y][this.thread.x]; return pixel.a; } ) .setOutput([4, 4]); const texture = createTexture([ [.01,.02,.03,.04], [.05,.06,.07,.08], [.09,.10,.11,.12], [.13,.14,.15,.16] ]); const resultR = readRTexture(texture); const resultG = readGTexture(texture); const resultB = readBTexture(texture); const resultA = readATexture(texture); assert.equal(texture.constructor.name, 'GLTextureGraphical'); // R assert.equal(resultR[0][0].toFixed(2), '0.01'); assert.equal(resultR[0][1].toFixed(2), '0.02'); assert.equal(resultR[0][2].toFixed(2), '0.03'); assert.equal(resultR[0][3].toFixed(2), '0.04'); assert.equal(resultR[1][0].toFixed(2), '0.05'); assert.equal(resultR[1][1].toFixed(2), '0.06'); assert.equal(resultR[1][2].toFixed(2), '0.07'); assert.equal(resultR[1][3].toFixed(2), '0.08'); assert.equal(resultR[2][0].toFixed(2), '0.09'); assert.equal(resultR[2][1].toFixed(2), '0.10'); assert.equal(resultR[2][2].toFixed(2), '0.11'); assert.equal(resultR[2][3].toFixed(2), '0.12'); assert.equal(resultR[3][0].toFixed(2), '0.13'); assert.equal(resultR[3][1].toFixed(2), '0.14'); assert.equal(resultR[3][2].toFixed(2), '0.15'); assert.equal(resultR[3][3].toFixed(2), '0.16'); // G assert.equal(resultG[0][0].toFixed(2), '0.01'); assert.equal(resultG[0][1].toFixed(2), '0.02'); assert.equal(resultG[0][2].toFixed(2), '0.03'); assert.equal(resultG[0][3].toFixed(2), '0.04'); assert.equal(resultG[1][0].toFixed(2), '0.05'); assert.equal(resultG[1][1].toFixed(2), '0.06'); assert.equal(resultG[1][2].toFixed(2), '0.07'); assert.equal(resultG[1][3].toFixed(2), '0.08'); assert.equal(resultG[2][0].toFixed(2), '0.09'); assert.equal(resultG[2][1].toFixed(2), '0.10'); assert.equal(resultG[2][2].toFixed(2), '0.11'); assert.equal(resultG[2][3].toFixed(2), '0.12'); assert.equal(resultG[3][0].toFixed(2), '0.13'); assert.equal(resultG[3][1].toFixed(2), '0.14'); assert.equal(resultG[3][2].toFixed(2), '0.15'); assert.equal(resultG[3][3].toFixed(2), '0.16'); // B assert.equal(resultB[0][0].toFixed(2), '0.01'); assert.equal(resultB[0][1].toFixed(2), '0.02'); assert.equal(resultB[0][2].toFixed(2), '0.03'); assert.equal(resultB[0][3].toFixed(2), '0.04'); assert.equal(resultB[1][0].toFixed(2), '0.05'); assert.equal(resultB[1][1].toFixed(2), '0.06'); assert.equal(resultB[1][2].toFixed(2), '0.07'); assert.equal(resultB[1][3].toFixed(2), '0.08'); assert.equal(resultB[2][0].toFixed(2), '0.09'); assert.equal(resultB[2][1].toFixed(2), '0.10'); assert.equal(resultB[2][2].toFixed(2), '0.11'); assert.equal(resultB[2][3].toFixed(2), '0.12'); assert.equal(resultB[3][0].toFixed(2), '0.13'); assert.equal(resultB[3][1].toFixed(2), '0.14'); assert.equal(resultB[3][2].toFixed(2), '0.15'); assert.equal(resultB[3][3].toFixed(2), '0.16'); // A assert.equal(resultA[0][0].toFixed(2), '0.01'); assert.equal(resultA[0][1].toFixed(2), '0.02'); assert.equal(resultA[0][2].toFixed(2), '0.03'); assert.equal(resultA[0][3].toFixed(2), '0.04'); assert.equal(resultA[1][0].toFixed(2), '0.05'); assert.equal(resultA[1][1].toFixed(2), '0.06'); assert.equal(resultA[1][2].toFixed(2), '0.07'); assert.equal(resultA[1][3].toFixed(2), '0.08'); assert.equal(resultA[2][0].toFixed(2), '0.09'); assert.equal(resultA[2][1].toFixed(2), '0.10'); assert.equal(resultA[2][2].toFixed(2), '0.11'); assert.equal(resultA[2][3].toFixed(2), '0.12'); assert.equal(resultA[3][0].toFixed(2), '0.13'); assert.equal(resultA[3][1].toFixed(2), '0.14'); assert.equal(resultA[3][2].toFixed(2), '0.15'); assert.equal(resultA[3][3].toFixed(2), '0.16'); gpu.destroy(); } test('colorSyntaxTest auto', () => { colorSyntaxTest(null); }); test('colorSyntaxTest gpu', () => { colorSyntaxTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('colorSyntaxTest webgl', () => { colorSyntaxTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('colorSyntaxTest webgl2', () => { colorSyntaxTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('colorSyntaxTest headlessgl', () => { colorSyntaxTest('headlessgl'); }); test('colorSyntaxTest (cpu) throws', () => { assert.throws(() => { colorSyntaxTest('cpu'); }); }); ================================================ FILE: test/features/read-from-texture.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU, HeadlessGLKernel } = require('../../src'); describe('features: read from texture'); function readWithoutTextureKernels(mode) { const gpu = new GPU({ mode }); function add(m, n) { return m + n; } const kernels = gpu.createKernelMap({ addResult: add }, function (a, b) { return add(a[this.thread.x], b[this.thread.x]); }) .setOutput([5]); const result = kernels([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]); const nonTextureResult = result.addResult; assert.deepEqual(Array.from(result.result), [2, 4, 6, 8, 10]); assert.deepEqual(Array.from(nonTextureResult), [2, 4, 6, 8, 10]); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('Read without texture auto', () => { readWithoutTextureKernels(); }); (GPU.isKernelMapSupported ? test : skip)('Read without texture gpu', () => { readWithoutTextureKernels('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Read without texture webgl', () => { readWithoutTextureKernels('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Read without texture webgl2', () => { readWithoutTextureKernels('webgl2'); }); (GPU.isHeadlessGLSupported && HeadlessGLKernel.features.kernelMap ? test : skip)('Read without texture headlessgl', () => { readWithoutTextureKernels('headlessgl'); }); function readFromTextureKernels(mode) { const gpu = new GPU({ mode }); function add(m, n) { return m + n; } const kernels = gpu.createKernelMap({ addResult: add }, function (a, b) { return add(a[this.thread.x], b[this.thread.x]); }) .setPipeline(true) .setOutput([5]); const result = kernels([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]); const textureResult = result.addResult; assert.deepEqual(Array.from(result.result.toArray()), [2, 4, 6, 8, 10]); assert.deepEqual(Array.from(textureResult.toArray()), [2, 4, 6, 8, 10]); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('Read from Texture auto', () => { readFromTextureKernels(); }); (GPU.isKernelMapSupported ? test : skip)('Read from Texture gpu', () => { readFromTextureKernels('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Read from Texture webgl', () => { readFromTextureKernels('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Read from Texture webgl2', () => { readFromTextureKernels('webgl2'); }); (GPU.isHeadlessGLSupported && HeadlessGLKernel.features.kernelMap ? test : skip)('Read from Texture headlessgl', () => { readFromTextureKernels('headlessgl'); }); ================================================ FILE: test/features/read-image-bitmap.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('features: read from image bitmap'); function readImageBitmap(mode, done) { const gpu = new GPU({ mode }); const image = new Image(); image.src = 'jellyfish.jpeg'; const kernel = gpu.createKernel(function(image) { const pixel = image[this.thread.y][this.thread.x]; return pixel[0] + pixel[1] + pixel[2] + pixel[3]; }, { output: [1] }); image.onload = async function() { const imageBitmapPromise = createImageBitmap(image, 0, 0, 1, 1); const imageBitmap = await imageBitmapPromise; const result = kernel(imageBitmap); assert.equal(result.length, 1); assert.equal(result[0].toFixed(2), 3.22); await gpu.destroy(); done(); }; } (typeof Image !== 'undefined' ? test : skip)('readImageBitmap auto', (assert) => { readImageBitmap(null, assert.async()); }); (typeof Image !== 'undefined' ? test : skip)('readImageBitmap gpu', (assert) => { readImageBitmap('gpu', assert.async()); }); (GPU.isWebGLSupported && typeof Image !== 'undefined' ? test : skip)('readImageBitmap webgl', (assert) => { readImageBitmap('webgl', assert.async()); }); (GPU.isWebGL2Supported && typeof Image !== 'undefined' ? test : skip)('readImageBitmap webgl2', (assert) => { readImageBitmap('webgl2', assert.async()); }); (GPU.isHeadlessGLSupported && typeof Image !== 'undefined' ? test : skip)('readImageBitmap headlessgl', (assert) => { readImageBitmap('headlessgl', assert.async()); }); (typeof Image !== 'undefined' ? test : skip)('readImageBitmap cpu', (assert) => { readImageBitmap('cpu', assert.async()); }); ================================================ FILE: test/features/read-image-data.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('features: read from image data'); function readImageData(mode) { const gpu = new GPU({ mode }); const dataArray = new Uint8ClampedArray([255, 255, 255, 255]); const imageData = new ImageData(dataArray, 1, 1); const kernel = gpu.createKernel(function(imageData) { const pixel = imageData[this.thread.y][this.thread.x]; return pixel[0] + pixel[1] + pixel[2] + pixel[3]; }, { output: [1] }); const result = kernel(imageData); assert.equal(result.length, 1); assert.equal(result[0], 4); gpu.destroy(); } (typeof ImageData !== 'undefined' ? test : skip)('readImageData auto', () => { readImageData(null); }); (typeof ImageData !== 'undefined' ? test : skip)('readImageData gpu', () => { readImageData('gpu'); }); (GPU.isWebGLSupported && typeof ImageData !== 'undefined' ? test : skip)('readImageData webgl', () => { readImageData('webgl'); }); (GPU.isWebGL2Supported && typeof ImageData !== 'undefined' ? test : skip)('readImageData webgl2', () => { readImageData('webgl2'); }); (GPU.isHeadlessGLSupported && typeof ImageData !== 'undefined' ? test : skip)('readImageData headlessgl', () => { readImageData('headlessgl'); }); (typeof ImageData !== 'undefined' ? test : skip)('readImageData cpu', () => { readImageData('cpu'); }); ================================================ FILE: test/features/read-offscreen-canvas.js ================================================ if (typeof importScripts !== 'undefined') { // inside Worker importScripts('../../dist/gpu-browser.js'); onmessage = function (e) { const gpu = new GPU({ mode: e.data }); const kernel1 = gpu.createKernel(function() { this.color(1, 1, 1, 1); }, { output: [1, 1], graphical: true, }); kernel1(); const { canvas } = kernel1; const kernel2 = gpu.createKernel(function(canvas) { const pixel = canvas[0][this.thread.x]; return pixel[0] + pixel[1] + pixel[2] + pixel[3]; }, { output: [1], }); postMessage({ mode: gpu.mode, result: kernel2(canvas) }); gpu.destroy(); }; } else if (typeof isBrowser !== 'undefined' && isBrowser) { const { assert, skip, test, module: describe } = require('qunit'); describe('read offscreen canvas'); function testReadOffscreenCanvas(mode, done) { const worker = new Worker('features/read-offscreen-canvas.js'); worker.onmessage = function (e) { const { result } = e.data; if (mode) assert.equal(e.data.mode, mode, 'GPU mode used in Worker'); assert.deepEqual(result, Float32Array.from([4])); done(); }; worker.postMessage(mode); } (GPU.isOffscreenCanvasSupported ? test : skip)('read offscreen canvas auto', t => { testReadOffscreenCanvas(null, t.async()); }); (GPU.isOffscreenCanvasSupported ? test : skip)('read offscreen canvas gpu', t => { testReadOffscreenCanvas('gpu', t.async()); }); (GPU.isOffscreenCanvasSupported ? test : skip)('read offscreen canvas webgl', t => { testReadOffscreenCanvas('webgl', t.async()); }); (GPU.isOffscreenCanvasSupported ? test : skip)('read offscreen canvas webgl2', t => { testReadOffscreenCanvas('webgl2', t.async()); }); (GPU.isOffscreenCanvasSupported ? test : skip)('read offscreen canvas cpu', t => { testReadOffscreenCanvas('cpu', t.async()); }); } ================================================ FILE: test/features/return-arrays.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('features: return arrays'); function returnArray2FromKernel(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return [1, 2]; }, { output: [1], precision: 'single' }); const result = kernel(); assert.deepEqual(result.map(v => Array.from(v)), [[1, 2]]); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('return Array(2) from kernel auto', () => { returnArray2FromKernel(); }); (GPU.isSinglePrecisionSupported ? test : skip)('return Array(2) from kernel gpu', () => { returnArray2FromKernel('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('return Array(2) from kernel webgl', () => { returnArray2FromKernel('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('return Array(2) from kernel webgl2', () => { returnArray2FromKernel('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('return Array(2) from kernel headlessgl', () => { returnArray2FromKernel('headlessgl'); }); test('return Array(2) from kernel cpu', () => { returnArray2FromKernel('cpu'); }); function returnArray2D2FromKernel(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return [this.thread.x, this.thread.y]; }, { output : [3, 7], precision: 'single' }); const res = kernel(); for (let y = 0; y < 7; ++y) { for (let x = 0; x < 3; ++x) { assert.equal(res[y][x][0], x); assert.equal(res[y][x][1], y); } } gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('return Array2D(2) from kernel auto', () => { returnArray2D2FromKernel(); }); (GPU.isSinglePrecisionSupported ? test : skip)('return Array2D(2) from kernel gpu', () => { returnArray2D2FromKernel('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('return Array2D(2) from kernel webgl', () => { returnArray2D2FromKernel('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('return Array2D(2) from kernel webgl2', () => { returnArray2D2FromKernel('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('return Array2D(2) from kernel headlessgl', () => { returnArray2D2FromKernel('headlessgl'); }); test('return Array2D(2) from kernel cpu', () => { returnArray2D2FromKernel('cpu'); }); function returnArray3D2FromKernel(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return [this.thread.y, this.thread.z]; }, { output : [3, 5, 7], precision: 'single' }); const res = kernel(); for (let z = 0; z < 7; ++z) { for (let y = 0; y < 5; ++y) { for (let x = 0; x < 3; ++x) { assert.equal(res[z][y][x][0], y); assert.equal(res[z][y][x][1], z); } } } gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('return Array3D(2) from kernel auto', () => { returnArray3D2FromKernel(); }); (GPU.isSinglePrecisionSupported ? test : skip)('return Array3D(2) from kernel gpu', () => { returnArray3D2FromKernel('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('return Array3D(2) from kernel webgl', () => { returnArray3D2FromKernel('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('return Array3D(2) from kernel webgl2', () => { returnArray3D2FromKernel('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('return Array3D(2) from kernel headlessgl', () => { returnArray3D2FromKernel('headlessgl'); }); test('return Array3D(2) from kernel cpu', () => { returnArray3D2FromKernel('cpu'); }); function returnArray3FromKernel(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return [1, 2, 3]; }, { output: [1], precision: 'single' }); const result = kernel(); assert.deepEqual(Array.from(result.map(v => Array.from(v))), [[1, 2, 3]]); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('return Array(3) from kernel auto', () => { returnArray3FromKernel(); }); (GPU.isSinglePrecisionSupported ? test : skip)('return Array(3) from kernel gpu', () => { returnArray3FromKernel('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('return Array(3) from kernel webgl', () => { returnArray3FromKernel('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('return Array(3) from kernel webgl2', () => { returnArray3FromKernel('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('return Array(3) from kernel headlessgl', () => { returnArray3FromKernel('headlessgl'); }); test('return Array(3) from kernel cpu', () => { returnArray3FromKernel('cpu'); }); function returnArray2D3FromKernel(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return [this.thread.x, this.thread.y, this.thread.x * this.thread.y]; }, { output : [3, 7] ,precision: 'single' }); const res = kernel(); for (let y = 0; y < 7; ++y) { for (let x = 0; x < 3; ++x) { assert.equal(res[y][x][0], x); assert.equal(res[y][x][1], y); assert.equal(res[y][x][2], x * y); } } gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('return Array2D(3) from kernel auto', () => { returnArray2D3FromKernel(); }); (GPU.isSinglePrecisionSupported ? test : skip)('return Array2D(3) from kernel gpu', () => { returnArray2D3FromKernel('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('return Array2D(3) from kernel webgl', () => { returnArray2D3FromKernel('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('return Array2D(3) from kernel webgl2', () => { returnArray2D3FromKernel('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('return Array2D(3) from kernel headlessgl', () => { returnArray2D3FromKernel('headlessgl'); }); test('return Array2D(3) from kernel cpu', () => { returnArray2D3FromKernel('cpu'); }); function returnArray3D3FromKernel(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return [this.thread.x, this.thread.y, this.thread.z]; }, { output : [3, 5, 7] ,precision: 'single' }); const res = kernel(); for (let z = 0; z < 7; ++z) { for (let y = 0; y < 5; ++y) { for (let x = 0; x < 3; ++x) { assert.equal(res[z][y][x][0], x); assert.equal(res[z][y][x][1], y); assert.equal(res[z][y][x][2], z); } } } gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('return Array3D(3) from kernel auto', () => { returnArray3D3FromKernel(); }); (GPU.isSinglePrecisionSupported ? test : skip)('return Array3D(3) from kernel gpu', () => { returnArray3D3FromKernel('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('return Array3D(3) from kernel webgl', () => { returnArray3D3FromKernel('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('return Array3D(3) from kernel webgl2', () => { returnArray3D3FromKernel('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('return Array3D(3) from kernel headlessgl', () => { returnArray3D3FromKernel('headlessgl'); }); test('return Array3D(3) from kernel cpu', () => { returnArray3D3FromKernel('cpu'); }); function returnArray4FromKernel(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return [1, 2, 3, 4]; }, { output: [1], precision: 'single' }); const result = kernel(); assert.deepEqual(result.map(v => Array.from(v)), [[1, 2, 3, 4]]); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('return Array(4) from kernel auto', () => { returnArray4FromKernel(); }); (GPU.isSinglePrecisionSupported ? test : skip)('return Array(4) from kernel gpu', () => { returnArray4FromKernel('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('return Array(4) from kernel webgl', () => { returnArray4FromKernel('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('return Array(4) from kernel webgl2', () => { returnArray4FromKernel('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('return Array(4) from kernel headlessgl', () => { returnArray4FromKernel('headlessgl'); }); test('return Array(4) from kernel cpu', () => { returnArray4FromKernel('cpu'); }); function returnArray2D4FromKernel(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return [this.thread.x, this.thread.y, this.thread.x * this.thread.y, this.thread.x - this.thread.y]; }, { output : [3, 7], precision: 'single' }); const res = kernel(); for (let y = 0; y < 3; ++y) { for (let x = 0; x < 3; ++x) { assert.equal(res[y][x][0], x); assert.equal(res[y][x][1], y); assert.equal(res[y][x][2], x * y); assert.equal(res[y][x][3], x - y); } } gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('return Array2D(4) from kernel auto', () => { returnArray2D4FromKernel(); }); (GPU.isSinglePrecisionSupported ? test : skip)('return Array2D(4) from kernel gpu', () => { returnArray2D4FromKernel('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('return Array2D(4) from kernel webgl', () => { returnArray2D4FromKernel('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('return Array2D(4) from kernel webgl2', () => { returnArray2D4FromKernel('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('return Array2D(4) from kernel headlessgl', () => { returnArray2D4FromKernel('headlessgl'); }); test('return Array2D(4) from kernel cpu', () => { returnArray2D4FromKernel('cpu'); }); function returnArray3D4FromKernel(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return [this.thread.x, this.thread.y, this.thread.z, this.thread.x * this.thread.y * this.thread.z]; }, { output : [3, 5, 7], precision: 'single' }); const res = kernel(); for (let z = 0; z < 7; ++z) { for (let y = 0; y < 5; ++y) { for (let x = 0; x < 3; ++x) { assert.equal(res[z][y][x][0], x); assert.equal(res[z][y][x][1], y); assert.equal(res[z][y][x][2], z); assert.equal(res[z][y][x][3], x * y * z); } } } gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('return Array3D(4) from kernel auto', () => { returnArray3D4FromKernel(); }); (GPU.isSinglePrecisionSupported ? test : skip)('return Array3D(4) from kernel gpu', () => { returnArray3D4FromKernel('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('return Array3D(4) from kernel webgl', () => { returnArray3D4FromKernel('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('return Array3D(4) from kernel webgl2', () => { returnArray3D4FromKernel('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('return Array3D(4) from kernel headlessgl', () => { returnArray3D4FromKernel('headlessgl'); }); test('return Array3D(4) from kernel cpu', () => { returnArray3D4FromKernel('cpu'); }); function returnArray2FromKernelVariables33Length(mode) { const array = [ 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23, 24,25,26,27, 28,29,30,31, 32,33]; const sixteen = new Uint16Array(array); const eight = new Uint8Array(array); const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1, v2) { return [v1[this.thread.x], v2[this.thread.x]]; }, { output: [33] }); const result = kernel(sixteen, eight); assert.deepEqual(result.map(v => Array.from(v)), array.map(v => [v,v])); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('return Array(2) from kernel variables 33 in length auto', () => { returnArray2FromKernelVariables33Length(); }); (GPU.isSinglePrecisionSupported && GPU.isGPUSupported ? test : skip)('return Array(2) from kernel variables 33 in length gpu', () => { returnArray2FromKernelVariables33Length('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('return Array(2) from kernel variables 33 in length webgl', () => { returnArray2FromKernelVariables33Length('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('return Array(2) from kernel variables 33 in length webgl2', () => { returnArray2FromKernelVariables33Length('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('return Array(2) from kernel variables 33 in length headlessgl', () => { returnArray2FromKernelVariables33Length('headlessgl'); }); test('return Array(2) from kernel variables 33 in length cpu', () => { returnArray2FromKernelVariables33Length('cpu'); }); function returnArray3FromKernelVariables33Length(mode) { const array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33]; const thirtyTwo = new Float32Array(array); const sixteen = new Uint16Array(array); const eight = new Uint8Array(array); const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1, v2, v3) { return [v1[this.thread.x], v2[this.thread.x], v3[this.thread.x]]; }, { output: [33] }); const result = kernel(thirtyTwo, sixteen, eight); assert.deepEqual(result.map(v => Array.from(v)), array.map(v => [v,v,v])); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('return Array(3) from kernel variables 33 in length auto', () => { returnArray3FromKernelVariables33Length(); }); (GPU.isSinglePrecisionSupported && GPU.isGPUSupported ? test : skip)('return Array(3) from kernel variables 33 in length gpu', () => { returnArray3FromKernelVariables33Length('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('return Array(3) from kernel variables 33 in length webgl', () => { returnArray3FromKernelVariables33Length('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('return Array(3) from kernel variables 33 in length webgl2', () => { returnArray3FromKernelVariables33Length('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('return Array(3) from kernel variables 33 in length headlessgl', () => { returnArray3FromKernelVariables33Length('headlessgl'); }); test('return Array(3) from kernel variables 33 in length cpu', () => { returnArray3FromKernelVariables33Length('cpu'); }); function returnArray4FromKernelVariables33Length(mode) { const array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33]; const thirtyTwo = new Float32Array(array); const sixteen = new Uint16Array(array); const eight = new Uint8Array(array); const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v1, v2, v3, v4) { return [v1[this.thread.x], v2[this.thread.x], v3[this.thread.x], v4[this.thread.x]]; }, { output: [33] }); const result = kernel(array, thirtyTwo, sixteen, eight); assert.deepEqual(result.map(v => Array.from(v)), array.map(v => [v,v,v,v])); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('return Array(4) from kernel variables 33 in length auto', () => { returnArray4FromKernelVariables33Length(); }); (GPU.isSinglePrecisionSupported && GPU.isGPUSupported ? test : skip)('return Array(4) from kernel variables 33 in length gpu', () => { returnArray4FromKernelVariables33Length('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('return Array(4) from kernel variables 33 in length webgl', () => { returnArray4FromKernelVariables33Length('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('return Array(4) from kernel variables 33 in length webgl2', () => { returnArray4FromKernelVariables33Length('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('return Array(4) from kernel variables 33 in length headlessgl', () => { returnArray4FromKernelVariables33Length('headlessgl'); }); test('return Array(4) from kernel variables 33 in length cpu', () => { returnArray4FromKernelVariables33Length('cpu'); }); ================================================ FILE: test/features/single-precision-textures.js ================================================ const { assert, skip, test, only, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('features: single precision textures'); function singlePrecisionTexturesWithArray(mode) { const original = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.x]; }, { output: [9], precision: 'single' }); const result = kernel(original); assert.deepEqual(Array.from(result), original); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Array auto', () => { singlePrecisionTexturesWithArray(); }); test('with Array cpu', () => { singlePrecisionTexturesWithArray('cpu'); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Array gpu', () => { singlePrecisionTexturesWithArray('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Array webgl', () => { singlePrecisionTexturesWithArray('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('with Array webgl2', () => { singlePrecisionTexturesWithArray('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Array headlessgl', () => { singlePrecisionTexturesWithArray('headlessgl'); }); function singlePrecisionTexturesWithFloat32Array(mode) { const original = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9]); const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.x]; }, { output: [9], precision: 'single' }); const result = kernel(original); assert.deepEqual(Array.from(result), Array.from(original)); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array auto', () => { singlePrecisionTexturesWithFloat32Array(); }); test('with Float32Array cpu', () => { singlePrecisionTexturesWithFloat32Array('cpu'); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array gpu', () => { singlePrecisionTexturesWithFloat32Array('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array webgl', () => { singlePrecisionTexturesWithFloat32Array('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('with Float32Array webgl2', () => { singlePrecisionTexturesWithFloat32Array('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array headlessgl', () => { singlePrecisionTexturesWithFloat32Array('headlessgl'); }); function singlePrecisionTexturesWithUint16Array(mode) { const original = new Uint16Array([1, 2, 3, 4, 5, 6, 7, 8, 9]); const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.x]; }, { output: [9], precision: 'single', }); const result = kernel(original); assert.deepEqual(Array.from(result), Array.from(original)); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array auto', () => { singlePrecisionTexturesWithUint16Array(); }); test('with Uint16Array cpu', () => { singlePrecisionTexturesWithUint16Array('cpu'); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array gpu', () => { singlePrecisionTexturesWithUint16Array('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array webgl', () => { singlePrecisionTexturesWithUint16Array('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('with Uint16Array webgl2', () => { singlePrecisionTexturesWithUint16Array('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array headlessgl', () => { singlePrecisionTexturesWithUint16Array('headlessgl'); }); function singlePrecisionTexturesWithUint8Array(mode) { const original = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]); const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.x]; }, { output: [9], precision: 'single' }); const result = kernel(original); assert.deepEqual(Array.from(result), Array.from(original)); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array auto', () => { singlePrecisionTexturesWithUint8Array(); }); test('with Uint8Array cpu', () => { singlePrecisionTexturesWithUint8Array('cpu'); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array gpu', () => { singlePrecisionTexturesWithUint8Array('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array webgl', () => { singlePrecisionTexturesWithUint8Array('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('with Uint8Array webgl2', () => { singlePrecisionTexturesWithUint8Array('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array headlessgl', () => { singlePrecisionTexturesWithUint8Array('headlessgl'); }); function singlePrecisionTexturesWithUint8ClampedArray(mode) { const original = new Uint8ClampedArray([1, 2, 3, 4, 5, 6, 7, 8, 9]); const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.x]; }, { output: [9], precision: 'single' }); const result = kernel(original); assert.deepEqual(Array.from(result), Array.from(original)); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray auto', () => { singlePrecisionTexturesWithUint8ClampedArray(); }); test('with Uint8ClampedArray cpu', () => { singlePrecisionTexturesWithUint8ClampedArray('cpu'); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray gpu', () => { singlePrecisionTexturesWithUint8ClampedArray('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray webgl', () => { singlePrecisionTexturesWithUint8ClampedArray('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('with Uint8ClampedArray webgl2', () => { singlePrecisionTexturesWithUint8ClampedArray('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray headlessgl', () => { singlePrecisionTexturesWithUint8ClampedArray('headlessgl'); }); function singlePrecisionTexturesWithArray2D(mode) { const original = [ [1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 18, 19], ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.y][this.thread.x]; }, { output: [9, 2], precision: 'single' }); const result = kernel(original); assert.deepEqual(result.map(array => Array.from(array)), original.map(array => Array.from(array))); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Array2D auto', () => { singlePrecisionTexturesWithArray2D(); }); test('with Array2D cpu', () => { singlePrecisionTexturesWithArray2D('cpu'); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Array2D gpu', () => { singlePrecisionTexturesWithArray2D('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Array2D webgl', () => { singlePrecisionTexturesWithArray2D('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('with Array2D webgl2', () => { singlePrecisionTexturesWithArray2D('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Array2D headlessgl', () => { singlePrecisionTexturesWithArray2D('headlessgl'); }); function singlePrecisionTexturesWithFloat32Array2D(mode) { const original = [ new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Float32Array([10, 11, 12, 13, 14, 15, 16, 18, 19]), ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.y][this.thread.x]; }, { output: [9, 2], precision: 'single' }); const result = kernel(original); assert.deepEqual(result.map(array => Array.from(array)), original.map(array => Array.from(array))); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array2D auto', () => { singlePrecisionTexturesWithFloat32Array2D(); }); test('with Float32Array2D cpu', () => { singlePrecisionTexturesWithFloat32Array2D('cpu'); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array2D gpu', () => { singlePrecisionTexturesWithFloat32Array2D('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array2D webgl', () => { singlePrecisionTexturesWithFloat32Array2D('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('with Float32Array2D webgl2', () => { singlePrecisionTexturesWithFloat32Array2D('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array2D headlessgl', () => { singlePrecisionTexturesWithFloat32Array2D('headlessgl'); }); function singlePrecisionTexturesWithUint16Array2D(mode) { const original = [ new Uint16Array([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Uint16Array([10, 11, 12, 13, 14, 15, 16, 18, 19]), ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.y][this.thread.x]; }, { output: [9, 2], precision: 'single' }); const result = kernel(original); assert.deepEqual(result.map(array => Array.from(array)), original.map(array => Array.from(array))); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array2D auto', () => { singlePrecisionTexturesWithUint16Array2D(); }); test('with Uint16Array2D cpu', () => { singlePrecisionTexturesWithUint16Array2D('cpu'); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array2D gpu', () => { singlePrecisionTexturesWithUint16Array2D('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array2D webgl', () => { singlePrecisionTexturesWithUint16Array2D('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('with Uint16Array2D webgl2', () => { singlePrecisionTexturesWithUint16Array2D('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array2D headlessgl', () => { singlePrecisionTexturesWithUint16Array2D('headlessgl'); }); function singlePrecisionTexturesWithUint8Array2D(mode) { const original = [ new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Uint8Array([10, 11, 12, 13, 14, 15, 16, 18, 19]), ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.y][this.thread.x]; }, { output: [9, 2], precision: 'single' }); const result = kernel(original); assert.deepEqual(result.map(array => Array.from(array)), original.map(array => Array.from(array))); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array2D auto', () => { singlePrecisionTexturesWithUint8Array2D(); }); test('with Uint8Array2D cpu', () => { singlePrecisionTexturesWithUint8Array2D('cpu'); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array2D gpu', () => { singlePrecisionTexturesWithUint8Array2D('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array2D webgl', () => { singlePrecisionTexturesWithUint8Array2D('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('with Uint8Array2D webgl2', () => { singlePrecisionTexturesWithUint8Array2D('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array2D headlessgl', () => { singlePrecisionTexturesWithUint8Array2D('headlessgl'); }); function singlePrecisionTexturesWithUint8ClampedArray2D(mode) { const original = [ new Uint8ClampedArray([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Uint8ClampedArray([10, 11, 12, 13, 14, 15, 16, 18, 19]), ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.y][this.thread.x]; }, { output: [9, 2], precision: 'single' }); const result = kernel(original); assert.deepEqual(result.map(array => Array.from(array)), original.map(array => Array.from(array))); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray2D auto', () => { singlePrecisionTexturesWithUint8ClampedArray2D(); }); test('with Uint8ClampedArray2D cpu', () => { singlePrecisionTexturesWithUint8ClampedArray2D('cpu'); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray2D gpu', () => { singlePrecisionTexturesWithUint8ClampedArray2D('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray2D webgl', () => { singlePrecisionTexturesWithUint8ClampedArray2D('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('with Uint8ClampedArray2D webgl2', () => { singlePrecisionTexturesWithUint8ClampedArray2D('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray2D headlessgl', () => { singlePrecisionTexturesWithUint8ClampedArray2D('headlessgl'); }); function singlePrecisionTexturesWithArray3D(mode) { const original = [ [ [1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 18, 19], ], [ [20, 21, 22, 23, 24, 25, 26, 27, 28], [29, 30, 31, 32, 33, 34, 35, 36, 37], ] ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.z][this.thread.y][this.thread.x]; }, { output: [9, 2, 2], precision: 'single' }); const result = kernel(original); assert.deepEqual(result.map(matrix => matrix.map(array => Array.from(array))), original); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Array3D auto', () => { singlePrecisionTexturesWithArray3D(); }); test('with Array3D cpu', () => { singlePrecisionTexturesWithArray3D('cpu'); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Array3D gpu', () => { singlePrecisionTexturesWithArray3D('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Array3D webgl', () => { singlePrecisionTexturesWithArray3D('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('with Array3D webgl2', () => { singlePrecisionTexturesWithArray3D('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Array3D headlessgl', () => { singlePrecisionTexturesWithArray3D('headlessgl'); }); function singlePrecisionTexturesWithFloat32Array3D(mode) { const original = [ [ new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Float32Array([10, 11, 12, 13, 14, 15, 16, 18, 19]), ], [ new Float32Array([20, 21, 22, 23, 24, 25, 26, 27, 28]), new Float32Array([29, 30, 31, 32, 33, 34, 35, 36, 37]), ] ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.z][this.thread.y][this.thread.x]; }, { output: [9, 2, 2], precision: 'single' }); const result = kernel(original); assert.deepEqual(result.map(matrix => matrix.map(array => Array.from(array))), original.map(matrix => matrix.map(array => Array.from(array)))); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array3D auto', () => { singlePrecisionTexturesWithFloat32Array3D(); }); test('with Float32Array3D cpu', () => { singlePrecisionTexturesWithFloat32Array3D('cpu'); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array3D gpu', () => { singlePrecisionTexturesWithFloat32Array3D('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array3D webgl', () => { singlePrecisionTexturesWithFloat32Array3D('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('with Float32Array3D webgl2', () => { singlePrecisionTexturesWithFloat32Array3D('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array3D headlessgl', () => { singlePrecisionTexturesWithFloat32Array3D('headlessgl'); }); function singlePrecisionTexturesWithUint16Array3D(mode) { const original = [ [ new Uint16Array([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Uint16Array([10, 11, 12, 13, 14, 15, 16, 18, 19]), ], [ new Uint16Array([20, 21, 22, 23, 24, 25, 26, 27, 28]), new Uint16Array([29, 30, 31, 32, 33, 34, 35, 36, 37]), ] ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.z][this.thread.y][this.thread.x]; }, { output: [9, 2, 2], precision: 'single' }); const result = kernel(original); assert.deepEqual(result.map(matrix => matrix.map(array => Array.from(array))), original.map(matrix => matrix.map(array => Array.from(array)))); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array3D auto', () => { singlePrecisionTexturesWithUint16Array3D(); }); test('with Uint16Array3D cpu', () => { singlePrecisionTexturesWithUint16Array3D('cpu'); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array3D gpu', () => { singlePrecisionTexturesWithUint16Array3D('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array3D webgl', () => { singlePrecisionTexturesWithUint16Array3D('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('with Uint16Array3D webgl2', () => { singlePrecisionTexturesWithUint16Array3D('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array3D headlessgl', () => { singlePrecisionTexturesWithUint16Array3D('headlessgl'); }); function singlePrecisionTexturesWithUint8Array3D(mode) { const original = [ [ new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Uint8Array([10, 11, 12, 13, 14, 15, 16, 18, 19]), ], [ new Uint8Array([20, 21, 22, 23, 24, 25, 26, 27, 28]), new Uint8Array([29, 30, 31, 32, 33, 34, 35, 36, 37]), ] ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.z][this.thread.y][this.thread.x]; }, { output: [9, 2, 2], precision: 'single' }); const result = kernel(original); assert.deepEqual(result.map(matrix => matrix.map(array => Array.from(array))), original.map(matrix => matrix.map(array => Array.from(array)))); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array3D auto', () => { singlePrecisionTexturesWithUint8Array3D(); }); test('with Uint8Array3D cpu', () => { singlePrecisionTexturesWithUint8Array3D('cpu'); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array3D gpu', () => { singlePrecisionTexturesWithUint8Array3D('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array3D webgl', () => { singlePrecisionTexturesWithUint8Array3D('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('with Uint8Array3D webgl2', () => { singlePrecisionTexturesWithUint8Array3D('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array3D headlessgl', () => { singlePrecisionTexturesWithUint8Array3D('headlessgl'); }); function singlePrecisionTexturesWithUint8ClampedArray3D(mode) { const original = [ [ new Uint8ClampedArray([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Uint8ClampedArray([10, 11, 12, 13, 14, 15, 16, 18, 19]), ], [ new Uint8ClampedArray([20, 21, 22, 23, 24, 25, 26, 27, 28]), new Uint8ClampedArray([29, 30, 31, 32, 33, 34, 35, 36, 37]), ] ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.z][this.thread.y][this.thread.x]; }, { output: [9, 2, 2], precision: 'single' }); const result = kernel(original); assert.deepEqual(result.map(matrix => matrix.map(array => Array.from(array))), original.map(matrix => matrix.map(array => Array.from(array)))); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray3D auto', () => { singlePrecisionTexturesWithUint8ClampedArray3D(); }); test('with Uint8ClampedArray3D cpu', () => { singlePrecisionTexturesWithUint8ClampedArray3D('cpu'); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray3D gpu', () => { singlePrecisionTexturesWithUint8ClampedArray3D('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray3D webgl', () => { singlePrecisionTexturesWithUint8ClampedArray3D('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('with Uint8ClampedArray3D webgl2', () => { singlePrecisionTexturesWithUint8ClampedArray3D('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray3D headlessgl', () => { singlePrecisionTexturesWithUint8ClampedArray3D('headlessgl'); }); function testImmutableDoesNotCollideWithKernelTexture(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return v[this.thread.x] + 1; }, { output: [1], precision: 'single', pipeline: true, immutable: true, }); const v = [1]; const result1 = kernel(v); assert.deepEqual(result1.toArray(), new Float32Array([2])); // kernel is getting ready to recompile, because a new type of input const result2 = kernel(result1); assert.deepEqual(result2.toArray(), new Float32Array([3])); // now the kernel textures match, this would fail, and this is that this test is testing const result3 = kernel(result2); assert.deepEqual(result3.toArray(), new Float32Array([4])); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('immutable does not collide with kernel texture auto', () => { testImmutableDoesNotCollideWithKernelTexture(); }); (GPU.isSinglePrecisionSupported ? test : skip)('immutable does not collide with kernel texture gpu', () => { testImmutableDoesNotCollideWithKernelTexture('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('immutable does not collide with kernel texture webgl', () => { testImmutableDoesNotCollideWithKernelTexture('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('immutable does not collide with kernel texture webgl2', () => { testImmutableDoesNotCollideWithKernelTexture('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('immutable does not collide with kernel texture headlessgl', () => { testImmutableDoesNotCollideWithKernelTexture('headlessgl'); }); ================================================ FILE: test/features/single-precision.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('features: single precision'); function singlePrecisionKernel(mode) { const lst = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8]); const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(lst) { return lst[this.thread.x]; }, { precision: 'single', output: [lst.length] }); assert.deepEqual(kernel(lst), lst); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)("auto", () => { singlePrecisionKernel(null); }); test("cpu", () => { singlePrecisionKernel('cpu'); }); (GPU.isSinglePrecisionSupported ? test : skip)("gpu", () => { singlePrecisionKernel('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)("webgl", () => { singlePrecisionKernel('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("webgl2", () => { singlePrecisionKernel('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)("headlessgl", () => { singlePrecisionKernel('headlessgl'); }); ================================================ FILE: test/features/switches.js ================================================ const { assert, skip, test, only, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('features: switches'); function testBasic(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { switch (value) { case 1: return 1; case 2: return 2; case 3: return 3; } return 0; }, { argumentTypes: ['Integer'], output: [1], }); assert.equal(kernel(1)[0], 1); assert.equal(kernel(2)[0], 2); assert.equal(kernel(3)[0], 3); assert.equal(kernel(4)[0], 0); gpu.destroy(); } test('basic auto', () => { testBasic(); }); test('basic gpu', () => { testBasic('gpu'); }); (GPU.isWebGLSupported ? test : skip)('basic webgl', () => { testBasic('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('basic webgl2', () => { testBasic('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('basic headlessgl', () => { testBasic('headlessgl'); }); test('basic cpu', () => { testBasic('cpu'); }); function testOnlyDefault(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { switch (value) { default: return 3; } }, { argumentTypes: ['Integer'], output: [1] }); assert.equal(kernel(1)[0], 3); assert.equal(kernel(2)[0], 3); assert.equal(kernel(3)[0], 3); assert.equal(kernel(4)[0], 3); gpu.destroy(); } test('only default auto', () => { testOnlyDefault(); }); test('only default gpu', () => { testOnlyDefault('gpu'); }); (GPU.isWebGLSupported ? test : skip)('only default webgl', () => { testOnlyDefault('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('only default webgl2', () => { testOnlyDefault('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('only default headlessgl', () => { testOnlyDefault('headlessgl'); }); test('only default cpu', () => { testOnlyDefault('cpu'); }); function testDefault(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { switch (value) { case 1: return 1; case 2: return 2; default: return 3; } }, { argumentTypes: ['Integer'], output: [1] }); assert.equal(kernel(1)[0], 1); assert.equal(kernel(2)[0], 2); assert.equal(kernel(3)[0], 3); assert.equal(kernel(4)[0], 3); gpu.destroy(); } test('default auto', () => { testDefault(); }); test('default gpu', () => { testDefault('gpu'); }); (GPU.isWebGLSupported ? test : skip)('default webgl', () => { testDefault('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('default webgl2', () => { testDefault('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('default headlessgl', () => { testDefault('headlessgl'); }); test('default cpu', () => { testDefault('cpu'); }); function testEarlyDefault(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { switch (value) { default: return 3; case 1: return 1; case 2: return 2; } }, { argumentTypes: ['Integer'], output: [1], }); assert.equal(kernel(1)[0], 1); assert.equal(kernel(2)[0], 2); assert.equal(kernel(3)[0], 3); assert.equal(kernel(4)[0], 3); gpu.destroy(); } test('early default auto', () => { testEarlyDefault(); }); test('early default gpu', () => { testEarlyDefault('gpu'); }); (GPU.isWebGLSupported ? test : skip)('early default webgl', () => { testEarlyDefault('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('early default webgl2', () => { testEarlyDefault('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('early default headlessgl', () => { testEarlyDefault('headlessgl'); }); test('early default cpu', () => { testEarlyDefault('cpu'); }); function testFallThrough(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { switch (value) { case 1: case 2: return 1; default: return 3; } }, { argumentTypes: ['Integer'], output: [1] }); assert.equal(kernel(1)[0], 1); assert.equal(kernel(2)[0], 1); assert.equal(kernel(3)[0], 3); assert.equal(kernel(4)[0], 3); gpu.destroy(); } test('fall through auto', () => { testFallThrough(); }); test('fall through gpu', () => { testFallThrough('gpu'); }); (GPU.isWebGLSupported ? test : skip)('fall through webgl', () => { testFallThrough('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('fall through webgl2', () => { testFallThrough('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('fall through headlessgl', () => { testFallThrough('headlessgl'); }); test('fall through cpu', () => { testFallThrough('cpu'); }); ================================================ FILE: test/features/tactic.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('internal: tactic'); function speedTest(mode) { const gpu = new GPU({ mode }); const add = gpu.createKernel(function(a, b) { return a + b; }) .setOutput([1]) .setTactic('speed'); let addResult = add(0.1, 0.2)[0]; assert.equal(addResult.toFixed(7), (0.1 + 0.2).toFixed(7)); gpu.destroy(); } test('speed auto', () => { speedTest(); }); test('speed gpu', () => { speedTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('speed webgl', () => { speedTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('speed webgl2', () => { speedTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('speed headlessgl', () => { speedTest('headlessgl'); }); test('speed cpu', () => { speedTest('cpu'); }); function balancedTest(mode) { const gpu = new GPU({ mode }); const add = gpu.createKernel(function(a, b) { return a + b; }) .setOutput([1]) .setTactic('balanced'); let addResult = add(0.1, 0.2)[0]; assert.equal(addResult.toFixed(7), (0.1 + 0.2).toFixed(7)); gpu.destroy(); } test('balanced auto', () => { balancedTest(); }); test('balanced gpu', () => { balancedTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('balanced webgl', () => { balancedTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('balanced webgl2', () => { balancedTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('balanced headlessgl', () => { balancedTest('headlessgl'); }); test('balanced cpu', () => { balancedTest('cpu'); }); function precisionTest(mode) { const gpu = new GPU({ mode }); const add = gpu.createKernel(function(a, b) { return a + b; }) .setOutput([1]) .setTactic('precision'); let addResult = add(0.1, 0.2)[0]; assert.equal(addResult.toFixed(7), (0.1 + 0.2).toFixed(7)); gpu.destroy(); } test('precision auto', () => { precisionTest(); }); test('precision gpu', () => { precisionTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('precision webgl', () => { precisionTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('precision webgl2', () => { precisionTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('precision headlessgl', () => { precisionTest('headlessgl'); }); test('precision cpu', () => { precisionTest('cpu'); }); ================================================ FILE: test/features/ternary.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('feature: Ternary'); function ternaryTest(mode) { const gpu = new GPU({ mode }); function ternaryFunction(value) { return (value > 1 ? 1 : 0); } const kernel = gpu.createKernel(ternaryFunction, { output: [1] }); const truthyResult = kernel(100); const falseyResult = kernel(-100); assert.equal(truthyResult[0], 1); assert.equal(falseyResult[0], 0); gpu.destroy(); } test('auto', () => { ternaryTest(); }); test('gpu', () => { ternaryTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { ternaryTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { ternaryTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { ternaryTest('headlessgl'); }); test('cpu', () => { ternaryTest('cpu'); }); function ternaryWithVariableUsage(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value1) { const value2 = value1 + 1; return value2 > 10 ? 1 : 0; }, { output: [1] }); assert.equal(kernel(9)[0], 0); assert.equal(kernel(10)[0], 1); gpu.destroy(); } test('with variable usage auto', () => { ternaryWithVariableUsage(); }); test('with variable usage gpu', () => { ternaryWithVariableUsage('gpu'); }); (GPU.isWebGLSupported ? test : skip)('with variable usage webgl', () => { ternaryWithVariableUsage('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with variable usage webgl2', () => { ternaryWithVariableUsage('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('with variable usage headlessgl', () => { ternaryWithVariableUsage('headlessgl'); }); test('with variable usage cpu', () => { ternaryWithVariableUsage('cpu'); }); ================================================ FILE: test/features/to-string/as-file.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../src'); describe('features: to-string as file'); function toStringAsFileTest(mode) { const path = __dirname + `/to-string-as-file-${mode}.js`; const fs = require('fs'); if (fs.existsSync(path)) { fs.unlinkSync(path); } const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return v[this.thread.y][this.thread.x] + 1; }, { output: [1, 1] }); const a = [[1]]; const expected = kernel(a); assert.deepEqual(expected, [new Float32Array([2])]); const kernelAsString = kernel.toString(a); fs.writeFileSync(path, `module.exports = ${kernelAsString};`); const toStringAsFile = require(path); const restoredKernel = toStringAsFile({ context: kernel.context }); const result = restoredKernel(a); assert.deepEqual(result, expected); fs.unlinkSync(path); gpu.destroy(); } (GPU.isHeadlessGLSupported ? test : skip)('can save and restore function headlessgl', () => { toStringAsFileTest('headlessgl'); }); (GPU.isHeadlessGLSupported ? test : skip)('can save and restore function cpu', () => { toStringAsFileTest('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/arguments/array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision arguments Array'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return a[this.thread.x]; }, { canvas, context, output: [4], precision: 'single', }); const a = [1, 2, 3, 4]; const expected = new Float32Array([1,2,3,4]); const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newKernel = new Function('return ' + kernelString)()({ context }); const newResult = newKernel(a); assert.deepEqual(newResult, expected); const b = [4,3,2,1]; const expected2 = new Float32Array([4,3,2,1]); const newResult2 = newKernel(b); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/arguments/array2.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision arguments Array(2)'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return a; }, { canvas, context, output: [1], precision: 'single', argumentTypes: { a: 'Array(2)' } }); const a = new Float32Array([1, 2]); const expected = [new Float32Array([1,2])]; const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newKernel = new Function('return ' + kernelString)()({ context }); const newResult = newKernel(a); assert.deepEqual(newResult, expected); const b = new Float32Array([2, 1]); const expected2 = [new Float32Array([2,1])]; const newResult2 = newKernel(b); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/arguments/array2d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision arguments Array2D'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { let sum = 0; for (let y = 0; y < 4; y++) { sum += a[y][this.thread.x]; } return sum; }, { canvas, context, output: [4], precision: 'single', }); const a = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]; const b = [ [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], ]; const expected = new Float32Array([28,32,36,40]); const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newKernel = new Function('return ' + kernelString)()({ context }); const newResult = newKernel(a); assert.deepEqual(newResult, expected); const expected2 = new Float32Array([4,4,4,4]); const newResult2 = newKernel(b); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/arguments/array2d2.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision arguments Array2D(2)'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { const array2 = a[this.thread.y][this.thread.x]; return [array2[0] + 1, array2[1] + 1]; }, { canvas, context, output: [2,2], precision: 'single', argumentTypes: { a: 'Array2D(2)' } }); const a = [ [ [1, 2], [3, 4], ], [ [5, 6], [7, 8], ] ]; const expected = [ [ new Float32Array([2, 3]), new Float32Array([4, 5]), ], [ new Float32Array([6, 7]), new Float32Array([8, 9]), ] ]; const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newKernel = new Function('return ' + kernelString)()({ context }) const newResult = newKernel(a); assert.deepEqual(newResult, expected); const b = [ [ [1, 1], [1, 1], ], [ [1, 1], [1, 1], ] ]; const expected2 = [ [ new Float32Array([2, 2]), new Float32Array([2, 2]), ], [ new Float32Array([2, 2]), new Float32Array([2, 2]), ] ]; const newResult2 = newKernel(b); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/arguments/array2d3.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision arguments Array2D(3)'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { const array3 = a[this.thread.y][this.thread.x]; return [array3[0] + 1, array3[1] + 1, array3[2] + 1]; }, { canvas, context, output: [2,2], precision: 'single', dynamicOutput: true, argumentTypes: { a: 'Array2D(3)' } }); const a = [ [ [1, 2, 3], [4, 5, 6], ], [ [7, 8, 9], [10, 11, 12], ] ]; const expected = [ [ new Float32Array([2, 3, 4]), new Float32Array([5, 6, 7]), ], [ new Float32Array([8, 9, 10]), new Float32Array([11, 12, 13]), ] ]; const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newKernel = new Function('return ' + kernelString)()({ context }) const newResult = newKernel(a); assert.deepEqual(newResult, expected); const b = [ [ [1, 1, 1], [1, 1, 1], ], [ [1, 1, 1], [1, 1, 1], ] ]; const expected2 = [ [ new Float32Array([2, 2, 2]), new Float32Array([2, 2, 2]), ], [ new Float32Array([2, 2, 2]), new Float32Array([2, 2, 2]), ] ]; const newResult2 = newKernel(b); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/arguments/array3.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision arguments Array(3)'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return a; }, { canvas, context, output: [1], precision: 'single', argumentTypes: { a: 'Array(3)' } }); const a = new Float32Array([1, 2, 3]); const expected = [new Float32Array([1,2,3])]; const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newKernel = new Function('return ' + kernelString)()({ context }); const newResult = newKernel(a); assert.deepEqual(newResult, expected); const b = new Float32Array([1, 1, 1]); const expected2 = [new Float32Array([1,1,1])]; const newResult2 = newKernel(b); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/arguments/array3d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision arguments Array3D'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { let sum = 0; for (let z = 0; z < 2; z++) { for (let y = 0; y < 2; y++) { sum += a[z][y][this.thread.x]; } } return sum; }, { canvas, context, output: [2], precision: 'single', }); const a = [ [ [1, 2], [3, 4], ], [ [5, 6], [7, 8], ] ]; const expected = new Float32Array([16, 20]); const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newKernel = new Function('return ' + kernelString)()({ context }); const newResult = newKernel(a); assert.deepEqual(newResult, expected); const b = [ [ [1, 1], [1, 1], ], [ [1, 1], [1, 1], ] ]; const expected2 = new Float32Array([4, 4]); const newResult2 = newKernel(b); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/arguments/array4.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision arguments Array(4)'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return a; }, { canvas, context, output: [1], precision: 'single', argumentTypes: { a: 'Array(4)' } }); const a = new Float32Array([1, 2, 3, 4]); const expected = [new Float32Array([1,2,3,4])]; const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newKernel = new Function('return ' + kernelString)()({ context }); const newResult = newKernel(a); assert.deepEqual(newResult, expected); const b = new Float32Array([1, 1, 1, 1]); const expected2 = [new Float32Array([1,1,1,1])]; const newResult2 = newKernel(b); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/arguments/boolean.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision arguments Boolean'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return a ? 42 : -42; }, { canvas, context, output: [1], precision: 'single', }); assert.deepEqual(originalKernel(true)[0], 42); assert.deepEqual(originalKernel(false)[0], -42); const kernelString = originalKernel.toString(true); const newKernel = new Function('return ' + kernelString)()({ context }); assert.deepEqual(newKernel(true)[0], 42); assert.deepEqual(newKernel(false)[0], -42); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/arguments/float.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision arguments Float'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return Math.floor(a) === 100 ? 42 : -42; }, { canvas, context, output: [1], precision: 'single', argumentTypes: { a: 'Float' }, }); assert.equal(originalKernel.argumentTypes[0], 'Float'); assert.deepEqual(originalKernel(100)[0], 42); assert.deepEqual(originalKernel(10)[0], -42); const kernelString = originalKernel.toString(100); const newKernel = new Function('return ' + kernelString)()({ context }); assert.deepEqual(newKernel(100)[0], 42); assert.deepEqual(newKernel(10)[0], -42); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/arguments/html-canvas.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); const { greenCanvas } = require('../../../../../browser-test-utils'); describe('feature: to-string single precision arguments HTMLCanvas'); function testArgument(mode, done) { const canvasInput1 = greenCanvas(mode, 1, 1); const canvasInput2 = greenCanvas(mode, 1, 1); const gpu = new GPU({mode}); const originalKernel = gpu.createKernel(function (canvas1, canvas2) { const pixel1 = canvas1[this.thread.y][this.thread.x]; const pixel2 = canvas2[this.thread.y][this.thread.x]; return pixel1[1] + pixel2[1]; }, { output: [1], precision: 'single', argumentTypes: ['HTMLCanvas', 'HTMLCanvas'], }); const canvas = originalKernel.canvas; const context = originalKernel.context; assert.deepEqual(originalKernel(canvasInput1, canvasInput2)[0], 2); const kernelString = originalKernel.toString(canvasInput1, canvasInput2); const newKernel = new Function('return ' + kernelString)()({context, canvas}); const canvasInput3 = greenCanvas(mode, 1, 1); const canvasInput4 = greenCanvas(mode, 1, 1); assert.deepEqual(newKernel(canvasInput3, canvasInput4)[0], 2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { testArgument('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testArgument('webgl2'); }); ================================================ FILE: test/features/to-string/precision/single/arguments/html-image-array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, CPUKernel } = require('../../../../../../src'); describe('feature: to-string single precision arguments HTMLImageArray'); function testArgument(mode, done) { loadImages([ 'jellyfish-1.jpeg', 'jellyfish-2.jpeg', 'jellyfish-3.jpeg', 'jellyfish-4.jpeg', ]) .then(([image1, image2, image3, image4]) => { const imagesArray1 = [image1, image2]; const imagesArray2 = [image3, image4]; const gpu = new GPU({mode}); const originalKernel = gpu.createKernel(function (a, selection) { const image0 = a[0][0][0]; const image1 = a[1][0][0]; switch (selection) { case 0: return image0.r * 255; case 1: return image1.r * 255; case 2: return image0.g * 255; case 3: return image1.g * 255; } }, { output: [1], precision: 'single', argumentTypes: ['HTMLImageArray', 'Integer'], }); assert.deepEqual(originalKernel(imagesArray1, 0)[0], 172); assert.deepEqual(originalKernel(imagesArray1, 1)[0], 255); assert.deepEqual(originalKernel(imagesArray2, 2)[0], 87); assert.deepEqual(originalKernel(imagesArray2, 3)[0], 110); const kernelString = originalKernel.toString(imagesArray1, 0); const canvas = originalKernel.canvas; const context = originalKernel.context; const newKernel = new Function('return ' + kernelString)()({context, canvas}); assert.deepEqual(newKernel(imagesArray1, 0)[0], 172); assert.deepEqual(newKernel(imagesArray1, 1)[0], 255); assert.deepEqual(newKernel(imagesArray2, 2)[0], 87); assert.deepEqual(newKernel(imagesArray2, 3)[0], 110); gpu.destroy(); done(originalKernel, newKernel); }); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', t => { const done = t.async(); testArgument('webgl', (kernel) => { // They aren't supported, so test that kernel falls back assert.equal(kernel.kernel.constructor, CPUKernel); done(); }); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', t => { testArgument('webgl2', t.async()); }); ================================================ FILE: test/features/to-string/precision/single/arguments/html-image.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision arguments HTMLImage'); function testArgument(mode, done) { loadImages(['jellyfish-1.jpeg', 'jellyfish-2.jpeg']) .then(([image1, image2]) => { const gpu = new GPU({mode}); const originalKernel = gpu.createKernel(function (a) { const pixel = a[0][0]; return pixel.b * 255; }, { output: [1], precision: 'single', argumentTypes: ['HTMLImage'], }); const canvas = originalKernel.canvas; const context = originalKernel.context; assert.deepEqual(originalKernel(image1)[0], 253); const kernelString = originalKernel.toString(image1); const newKernel = new Function('return ' + kernelString)()({context, canvas}); assert.deepEqual(newKernel(image1)[0], 253); assert.deepEqual(newKernel(image2)[0], 255); gpu.destroy(); done(); }); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', t => { testArgument('webgl', t.async()); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', t => { testArgument('webgl2', t.async()); }); ================================================ FILE: test/features/to-string/precision/single/arguments/html-video.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision arguments HTMLVideo'); function testArgument(mode, done) { const video = document.createElement('video'); video.currentTime = 2; video.src = 'jellyfish.webm'; video.oncanplay = (e) => { video.oncanplay = null; setTimeout(() => { const gpu = new GPU({mode}); const originalKernel = gpu.createKernel(function (a) { const pixel = a[0][0]; return pixel.g * 255; }, { output: [1], precision: 'single', argumentTypes: ['HTMLVideo'], }); const canvas = originalKernel.canvas; const context = originalKernel.context; assert.deepEqual(originalKernel(video)[0], 125); const kernelString = originalKernel.toString(video); const newKernel = new Function('return ' + kernelString)()({context, canvas}); assert.deepEqual(newKernel(video)[0], 125); gpu.destroy(); done(); }, 1000); } } (GPU.isWebGLSupported ? test : skip)('webgl', t => { testArgument('webgl', t.async()); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', t => { testArgument('webgl2', t.async()); }); ================================================ FILE: test/features/to-string/precision/single/arguments/input.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, input } = require('../../../../../../src'); describe('feature: to-string single precision arguments Input'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { let sum = 0; for (let y = 0; y < 2; y++) { for (let x = 0; x < 2; x++) { sum += a[y][x]; } } return sum; }, { canvas, context, output: [1], precision: 'single', }); const arg1 = input([1,2,3,4],[2,2]); const arg2 = input([5,6,7,8],[2,2]); assert.deepEqual(originalKernel(arg1)[0], 10); assert.deepEqual(originalKernel(arg2)[0], 26); const kernelString = originalKernel.toString(arg1); const newKernel = new Function('return ' + kernelString)()({ context }); assert.deepEqual(newKernel(arg1)[0], 10); assert.deepEqual(newKernel(arg2)[0], 26); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/arguments/integer.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision arguments Integer'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return Math.floor(a) === 100 ? 42 : -42; }, { canvas, context, output: [1], precision: 'single', argumentTypes: { a: 'Integer' }, }); assert.equal(originalKernel.argumentTypes[0], 'Integer'); assert.deepEqual(originalKernel(100)[0], 42); assert.deepEqual(originalKernel(10)[0], -42); const kernelString = originalKernel.toString(100); const newKernel = new Function('return ' + kernelString)()({ context }); assert.deepEqual(newKernel(100)[0], 42); assert.deepEqual(newKernel(10)[0], -42); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/arguments/memory-optimized-number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision arguments MemoryOptimizedNumberTexture'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode, context, canvas }); const texture1 = gpu.createKernel(function() { return this.thread.x; }, { output: [4], optimizeFloatMemory: true, precision: 'single', pipeline: true, })(); const texture2 = gpu.createKernel(function() { return 4 - this.thread.x; }, { output: [4], optimizeFloatMemory: true, precision: 'single', pipeline: true, })(); const originalKernel = gpu.createKernel(function(a) { return a[this.thread.x]; }, { canvas, context, output: [4], precision: 'single' }); assert.deepEqual(originalKernel(texture1), new Float32Array([0,1,2,3])); assert.deepEqual(originalKernel(texture2), new Float32Array([4,3,2,1])); const kernelString = originalKernel.toString(texture1); const newKernel = new Function('return ' + kernelString)()({ context }); assert.deepEqual(newKernel(texture1), new Float32Array([0,1,2,3])); assert.deepEqual(newKernel(texture2), new Float32Array([4,3,2,1])); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/arguments/number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision arguments NumberTexture'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode, context, canvas }); const texture1 = gpu.createKernel(function() { return this.thread.x; }, { output: [4], optimizeFloatMemory: false, precision: 'single', pipeline: true, })(); const texture2 = gpu.createKernel(function() { return 4 - this.thread.x; }, { output: [4], optimizeFloatMemory: false, precision: 'single', pipeline: true, })(); const originalKernel = gpu.createKernel(function(a) { return a[this.thread.x]; }, { canvas, context, output: [4], precision: 'single' }); assert.deepEqual(originalKernel(texture1), new Float32Array([0,1,2,3])); assert.deepEqual(originalKernel(texture2), new Float32Array([4,3,2,1])); const kernelString = originalKernel.toString(texture1); const newKernel = new Function('return ' + kernelString)()({ context }); assert.deepEqual(newKernel(texture1), new Float32Array([0,1,2,3])); assert.deepEqual(newKernel(texture2), new Float32Array([4,3,2,1])); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/constants/array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision constants Array'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function() { return this.constants.a[this.thread.x]; }, { canvas, context, output: [4], precision: 'single', constants: { a: [1, 2, 3, 4] } }); const expected = new Float32Array([1,2,3,4]); const originalResult = originalKernel(); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(); const newResult = new Function('return ' + kernelString)()({ context, constants: { a: [1, 2, 3, 4] } })(); assert.deepEqual(newResult, expected); const expected2 = new Float32Array([4,3,2,1]); const newResult2 = new Function('return ' + kernelString)()({ context, constants: { a: [4, 3, 2, 1] } })(); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/constants/array2.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision constants Array(2)'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function() { return this.constants.a; }, { canvas, context, output: [1], precision: 'single', constants: { a: new Float32Array([1, 2]) }, constantTypes: { a: 'Array(2)' } }); const expected = [new Float32Array([1, 2])]; const originalResult = originalKernel(); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newResult = Kernel({ context, constants: { a: new Float32Array([1, 2]) } })(); assert.deepEqual(newResult, expected); // Array(2) is "sticky" as a constant, and cannot reset const newResult2 = Kernel({ context, constants: { a: new Float32Array([2, 1]) } })(); assert.deepEqual(newResult2, expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/constants/array2d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision constants 2d Array'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const a = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]; const originalKernel = gpu.createKernel(function() { let sum = 0; for (let y = 0; y < 4; y++) { sum += this.constants.a[y][this.thread.x]; } return sum; }, { canvas, context, output: [4], precision: 'single', constants: { a } }); const expected = new Float32Array([28,32,36,40]); const originalResult = originalKernel(); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newResult = Kernel({ context, constants: { a } })(); assert.deepEqual(newResult, expected); const b = [ [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], ]; const expected2 = new Float32Array([4,4,4,4]); const newResult2 = Kernel({ context, constants: { a: b } })(); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/constants/array3.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision constants Array(3)'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function() { return this.constants.a; }, { canvas, context, output: [1], precision: 'single', constants: { a: new Float32Array([1, 2, 3]) }, constantTypes: { a: 'Array(3)' } }); const expected = [new Float32Array([1, 2, 3])]; const originalResult = originalKernel(); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newResult = Kernel({ context, constants: { a: new Float32Array([1, 2, 3]) } })(); assert.deepEqual(newResult, expected); // Array(3) is "sticky" as a constant, and cannot reset const newResult2 = Kernel({ context, constants: { a: new Float32Array([3, 2, 1]) } })(); assert.deepEqual(newResult2, expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/constants/array3d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision constants 3d Array'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const a = [ [ [1, 2], [3, 4], ], [ [5, 6], [7, 8], ] ]; const originalKernel = gpu.createKernel(function() { let sum = 0; for (let z = 0; z < 2; z++) { for (let y = 0; y < 2; y++) { sum += this.constants.a[z][y][this.thread.x]; } } return sum; }, { canvas, context, output: [2], precision: 'single', constants: { a } }); const expected = new Float32Array([16, 20]); const originalResult = originalKernel(); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newResult = Kernel({ context, constants: { a } })(); assert.deepEqual(newResult, expected); const b = [ [ [1, 1], [1, 1], ], [ [1, 1], [1, 1], ] ]; const newResult2 = Kernel({ context, constants: { a: b } })(); const expected2 = new Float32Array([4, 4]); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/constants/array4.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision constants Array(4)'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const a = new Float32Array([1, 2, 3, 4]); const originalKernel = gpu.createKernel(function() { return this.constants.a; }, { canvas, context, output: [1], precision: 'single', constants: { a }, constantTypes: { a: 'Array(4)' } }); const expected = [new Float32Array([1, 2, 3, 4])]; const originalResult = originalKernel(); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(); const newResult = new Function('return ' + kernelString)()({ context, constants: { a } })(); assert.deepEqual(newResult, expected); // Array(3) is "sticky" as a constant, and cannot reset const b = new Float32Array([4, 3, 2, 1]); const expected2 = [new Float32Array([1, 2, 3, 4])]; const newResult2 = new Function('return ' + kernelString)()({ context, constants: { a: b } })(); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/constants/boolean.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision constants Boolean'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel1 = gpu.createKernel(function() { return this.constants.a ? 42 : -42; }, { canvas, context, output: [1], precision: 'single', constants: { a: true } }); const originalKernel2 = gpu.createKernel(function() { return this.constants.a ? 42 : -42; }, { canvas, context, output: [1], precision: 'single', constants: { a: false } }); assert.deepEqual(originalKernel1()[0], 42); assert.deepEqual(originalKernel2()[0], -42); const kernelString1 = originalKernel1.toString(); const kernelString2 = originalKernel2.toString(); const Kernel1 = new Function('return ' + kernelString1)(); const Kernel2 = new Function('return ' + kernelString2)(); const newKernel1 = Kernel1({ context, constants: { a: true } }); const newKernel2 = Kernel1({ context, constants: { a: false } }); const newKernel3 = Kernel2({ context, constants: { a: false } }); const newKernel4 = Kernel2({ context, constants: { a: true } }); // Boolean is "sticky" as a constant, and cannot reset assert.deepEqual(newKernel1()[0], 42); assert.deepEqual(newKernel2()[0], 42); assert.deepEqual(newKernel3()[0], -42); assert.deepEqual(newKernel4()[0], -42); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/constants/float.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision constants Float'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function() { return Math.floor(this.constants.a) === 100 ? 42 : -42; }, { canvas, context, output: [1], precision: 'single', constants: { a: 100 }, constantTypes: { a: 'Float' } }); assert.equal(originalKernel.constantTypes.a, 'Float'); assert.deepEqual(originalKernel()[0], 42); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); // Float is "sticky" as a constant, and cannot reset const newKernel = Kernel({ context, constants: { a: 100 } }); assert.deepEqual(newKernel()[0], 42); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/constants/html-canvas.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); const { greenCanvas } = require('../../../../../browser-test-utils'); describe('feature: to-string single precision constants HTMLCanvas'); function testArgument(mode, done) { const canvasInput1 = greenCanvas(mode, 1, 1); const canvasInput2 = greenCanvas(mode, 1, 1); const gpu = new GPU({mode}); const originalKernel = gpu.createKernel(function () { const pixel1 = this.constants.canvas1[this.thread.y][this.thread.x]; const pixel2 = this.constants.canvas2[this.thread.y][this.thread.x]; return pixel1[1] + pixel2[1]; }, { output: [1], precision: 'single', constants: { canvas1: canvasInput1, canvas2: canvasInput2 } }); const canvas = originalKernel.canvas; const context = originalKernel.context; assert.deepEqual(originalKernel()[0], 2); const kernelString = originalKernel.toString(); const canvasInput3 = greenCanvas(mode, 1, 1); const canvasInput4 = greenCanvas(mode, 1, 1); const newKernel = new Function('return ' + kernelString)()({ context, canvas, constants: { canvas1: canvasInput3, canvas2: canvasInput4 } }); assert.deepEqual(newKernel()[0], 2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { testArgument('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testArgument('webgl2'); }); ================================================ FILE: test/features/to-string/precision/single/constants/html-image-array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, CPUKernel } = require('../../../../../../src'); describe('feature: to-string single precision constants HTMLImageArray'); function testArgument(mode, done) { loadImages([ 'jellyfish-1.jpeg', 'jellyfish-2.jpeg', 'jellyfish-3.jpeg', 'jellyfish-4.jpeg', ]) .then(([image1, image2, image3, image4]) => { const images1 = [image1, image2]; const images2 = [image3, image4]; const gpu = new GPU({mode}); const originalKernel = gpu.createKernel(function (selection) { const image0 = this.constants.a[0][0][0]; const image1 = this.constants.a[1][0][0]; switch (selection) { case 0: return image0.r * 255; case 1: return image1.r * 255; case 2: return image0.b * 255; case 3: return image1.b * 255; } }, { output: [1], precision: 'single', argumentTypes: ['Integer'], constants: { a: images1, } }); assert.deepEqual(originalKernel(0)[0], 172); assert.deepEqual(originalKernel(1)[0], 255); assert.deepEqual(originalKernel(2)[0], 253); assert.deepEqual(originalKernel(3)[0], 255); const kernelString = originalKernel.toString(0); const canvas = originalKernel.canvas; const context = originalKernel.context; const Kernel = new Function('return ' + kernelString)(); const newKernel1 = Kernel({context, canvas, constants: { a: images1 }}); assert.deepEqual(newKernel1(0)[0], 172); assert.deepEqual(newKernel1(1)[0], 255); assert.deepEqual(newKernel1(2)[0], 253); assert.deepEqual(newKernel1(3)[0], 255); const newKernel2 = Kernel({context, canvas, constants: { a: images2 }}); assert.deepEqual(newKernel2(0)[0], 0); assert.deepEqual(newKernel2(1)[0], 73); assert.deepEqual(newKernel2(2)[0], 255); assert.deepEqual(newKernel2(3)[0], 253); gpu.destroy(); done(originalKernel, newKernel1); }); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', t => { const done = t.async(); testArgument('webgl', (kernel) => { // They aren't supported, so test that kernel falls back assert.equal(kernel.kernel.constructor, CPUKernel); done(); }); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', t => { testArgument('webgl2', t.async()); }); (GPU.isSinglePrecisionSupported && (GPU.isWebGLSupported || GPU.isWebGL2Supported) ? test : skip)('cpu', t => { testArgument('cpu', t.async()); }); ================================================ FILE: test/features/to-string/precision/single/constants/html-image.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision constants HTMLImage'); function testArgument(mode, done) { loadImages(['jellyfish-1.jpeg', 'jellyfish-2.jpeg']) .then(([image1, image2]) => { const gpu = new GPU({mode}); const originalKernel = gpu.createKernel(function () { const pixel = this.constants.a[0][0]; return pixel.b * 255; }, { output: [1], precision: 'single', constants: { a: image1 } }); const canvas = originalKernel.canvas; const context = originalKernel.context; assert.deepEqual(originalKernel()[0], 253); const kernelString = originalKernel.toString(); const newKernel = new Function('return ' + kernelString)()({context, canvas, constants: { a: image2 } }); assert.deepEqual(newKernel(image2)[0], 255); gpu.destroy(); done(); }); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', t => { testArgument('webgl', t.async()); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', t => { testArgument('webgl2', t.async()); }); (GPU.isSinglePrecisionSupported && (GPU.isWebGLSupported || GPU.isWebGL2Supported) ? test : skip)('cpu', t => { testArgument('cpu', t.async()); }); ================================================ FILE: test/features/to-string/precision/single/constants/input.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, input } = require('../../../../../../src'); describe('feature: to-string single precision constants Input'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const a = input([1,2,3,4],[2,2]); const originalKernel = gpu.createKernel(function() { let sum = 0; for (let y = 0; y < 2; y++) { for (let x = 0; x < 2; x++) { sum += this.constants.a[y][x]; } } return sum; }, { canvas, context, output: [1], precision: 'single', constants: { a } }); assert.deepEqual(originalKernel()[0], 10); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newKernel = Kernel({ context, constants: { a } }); assert.deepEqual(newKernel()[0], 10); const b = input([1,1,1,1],[2,2]); const newKernel2 = Kernel({ context, constants: { a: b } }); assert.deepEqual(newKernel2()[0], 4); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/constants/integer.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision constants Integer'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function() { return Math.floor(this.constants.a) === 100 ? 42 : -42; }, { canvas, context, output: [1], precision: 'single', constants: { a: 100 }, constantTypes: { a: 'Integer' } }); assert.equal(originalKernel.constantTypes.a, 'Integer'); assert.deepEqual(originalKernel()[0], 42); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newKernel = Kernel({ context, constants: { a: 100 } }); assert.deepEqual(newKernel()[0], 42); // Integer is "sticky" as a constant, and cannot reset const newKernel2 = Kernel({ context, constants: { a: 200 } }); assert.deepEqual(newKernel2()[0], 42); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/constants/memory-optimized-number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision constants MemoryOptimizedNumberTexture'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode, context, canvas }); const texture = gpu.createKernel(function() { return this.thread.x; }, { output: [4], optimizeFloatMemory: true, precision: 'single', pipeline: true, })(); const texture2 = gpu.createKernel(function() { return this.output.x - this.thread.x; }, { output: [4], optimizeFloatMemory: true, precision: 'single', pipeline: true, })(); const originalKernel = gpu.createKernel(function() { return this.constants.a[this.thread.x]; }, { output: [4], precision: 'single', constants: { a: texture } }); assert.deepEqual(originalKernel(), new Float32Array([0,1,2,3])); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newKernel = Kernel({ context, constants: { a: texture } }); const newKernel2 = Kernel({ context, constants: { a: texture2 } }); assert.deepEqual(texture2.toArray ? texture2.toArray() : texture2, new Float32Array([4,3,2,1])); assert.deepEqual(texture.toArray ? texture.toArray() : texture, new Float32Array([0,1,2,3])); assert.deepEqual(newKernel(), new Float32Array([0,1,2,3])); assert.deepEqual(newKernel2(), new Float32Array([4,3,2,1])); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/constants/number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision constants NumberTexture'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode, context, canvas }); const texture = gpu.createKernel(function() { return this.thread.x; }, { output: [4], optimizeFloatMemory: false, precision: 'single', pipeline: true, })(); const texture2 = gpu.createKernel(function() { return this.output.x - this.thread.x; }, { output: [4], optimizeFloatMemory: false, precision: 'single', pipeline: true, })(); const originalKernel = gpu.createKernel(function() { return this.constants.a[this.thread.x]; }, { canvas, context, output: [4], precision: 'single', constants: { a: texture } }); assert.deepEqual(originalKernel(), new Float32Array([0,1,2,3])); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newKernel = Kernel({ context, constants: { a: texture } }); const newKernel2 = Kernel({ context, constants: { a: texture2 } }); assert.deepEqual(texture2.toArray ? texture2.toArray() : texture2, new Float32Array([4,3,2,1])); assert.deepEqual(texture.toArray ? texture.toArray() : texture, new Float32Array([0,1,2,3])); assert.deepEqual(newKernel(), new Float32Array([0,1,2,3])); assert.deepEqual(newKernel2(), new Float32Array([4,3,2,1])); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/graphical.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../src'); describe('feature: to-string single precision graphical'); function testGraphical(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function() { this.color(1,1,1,1); }, { canvas, context, output: [2,2], precision: 'single', graphical: true, }); const expected = new Uint8ClampedArray([ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, ]); originalKernel(); assert.deepEqual(originalKernel.getPixels(), expected); const kernelString = originalKernel.toString(); const newKernel = new Function('return ' + kernelString)()({ canvas, context }); newKernel(); assert.deepEqual(newKernel.getPixels(), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testGraphical('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testGraphical('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testGraphical('headlessgl', require('gl')(1, 1), null); }); (GPU.isCanvasSupported ? test : skip)('cpu', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); testGraphical('cpu', context, canvas); }); ================================================ FILE: test/features/to-string/precision/single/kernel-map/array/array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string single precision array style kernel map returns Array'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap([addOne], function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [6], precision: 'single', }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const expectedZero = new Float32Array([3, 4, 5, 6, 7, 8]); const originalResult = originalKernel(a); assert.deepEqual(originalResult.result, expected); assert.deepEqual(originalResult[0], expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result, expected); assert.deepEqual(newResult[0], expectedZero); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/kernel-map/array/array2d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string single precision array style kernel map returns 2D Array'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap([addOne], function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [2, 2], precision: 'single', }); const a = [1, 2, 3, 4, 5, 6]; const expected = [ new Float32Array([2, 3]), new Float32Array([2, 3]), ]; const expectedZero = [ new Float32Array([3, 4]), new Float32Array([3, 4]), ]; const originalResult = originalKernel(a); assert.deepEqual(originalResult.result, expected); assert.deepEqual(originalResult[0], expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result, expected); assert.deepEqual(newResult[0], expectedZero); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/kernel-map/array/array3d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string single precision array style kernel map returns Array3d'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap([addOne], function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [2, 2, 2], precision: 'single', }); const a = [1, 2]; const expected = [ [ new Float32Array([2, 3]), new Float32Array([2, 3]), ], [ new Float32Array([2, 3]), new Float32Array([2, 3]), ] ]; const expectedZero = [ [ new Float32Array([3, 4]), new Float32Array([3, 4]), ], [ new Float32Array([3, 4]), new Float32Array([3, 4]), ] ]; const originalResult = originalKernel(a); assert.deepEqual(originalResult.result, expected); assert.deepEqual(originalResult[0], expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result, expected); assert.deepEqual(newResult[0], expectedZero); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/kernel-map/array/memory-optimized-number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string single precision array style kernel map returns MemoryOptimizedNumberTexture'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap([addOne], function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [6], precision: 'single', pipeline: true, optimizeFloatMemory: true, }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const expectedZero = new Float32Array([3, 4, 5, 6, 7, 8]); const originalResult = originalKernel(a); assert.deepEqual(originalResult.result.toArray(), expected); assert.deepEqual(originalResult[0].toArray(), expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result.toArray(), expected); assert.deepEqual(newResult[0].toArray(), expectedZero); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); ================================================ FILE: test/features/to-string/precision/single/kernel-map/array/number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string single precision array style kernel map returns NumberTexture'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap([addOne], function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [6], precision: 'single', pipeline: true, }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const expectedZero = new Float32Array([3, 4, 5, 6, 7, 8]); const originalResult = originalKernel(a); assert.deepEqual(originalResult.result.toArray(), expected); assert.deepEqual(originalResult[0].toArray(), expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result.toArray(), expected); assert.deepEqual(newResult[0].toArray(), expectedZero); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); ================================================ FILE: test/features/to-string/precision/single/kernel-map/object/array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string single precision object style returns Array'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap({ addOneResult: addOne }, function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [6], precision: 'single', }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const expectedZero = new Float32Array([3, 4, 5, 6, 7, 8]); const originalResult = originalKernel(a); assert.deepEqual(originalResult.result, expected); assert.deepEqual(originalResult.addOneResult, expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result, expected); assert.deepEqual(newResult.addOneResult, expectedZero); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/kernel-map/object/array2d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string single precision object style returns Array2D'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap({ addOneResult: addOne }, function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [2, 2], precision: 'single', }); const a = [1, 2, 3, 4, 5, 6]; const expected = [ new Float32Array([2, 3]), new Float32Array([2, 3]), ]; const expectedZero = [ new Float32Array([3, 4]), new Float32Array([3, 4]), ]; const originalResult = originalKernel(a); assert.deepEqual(originalResult.result, expected); assert.deepEqual(originalResult.addOneResult, expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result, expected); assert.deepEqual(newResult.addOneResult, expectedZero); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/kernel-map/object/array3d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string single precision object style returns Array3d'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap({ addOneResult: addOne }, function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [2, 2, 2], precision: 'single', }); const a = [1, 2]; const expected = [ [ new Float32Array([2, 3]), new Float32Array([2, 3]), ], [ new Float32Array([2, 3]), new Float32Array([2, 3]), ] ] const expectedZero = [ [ new Float32Array([3, 4]), new Float32Array([3, 4]), ], [ new Float32Array([3, 4]), new Float32Array([3, 4]), ] ]; const originalResult = originalKernel(a); assert.deepEqual(originalResult.result, expected); assert.deepEqual(originalResult.addOneResult, expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result, expected); assert.deepEqual(newResult.addOneResult, expectedZero); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/kernel-map/object/memory-optimized-number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string single precision object style kernel map returns MemoryOptimizedNumberTexture'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap({ addOneResult: addOne }, function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [6], precision: 'single', pipeline: true, optimizeFloatMemory: true, }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const expectedZero = new Float32Array([3, 4, 5, 6, 7, 8]); const originalResult = originalKernel(a); assert.deepEqual(originalResult.result.toArray(), expected); assert.deepEqual(originalResult.addOneResult.toArray(), expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result.toArray(), expected); assert.deepEqual(newResult.addOneResult.toArray(), expectedZero); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); ================================================ FILE: test/features/to-string/precision/single/kernel-map/object/number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string single precision object style kernel map returns NumberTexture'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap({ addOneResult: addOne }, function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [6], precision: 'single', pipeline: true, }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const expectedZero = new Float32Array([3, 4, 5, 6, 7, 8]); const originalResult = originalKernel(a); assert.deepEqual(originalResult.result.toArray(), expected); assert.deepEqual(originalResult.addOneResult.toArray(), expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result.toArray(), expected); assert.deepEqual(newResult.addOneResult.toArray(), expectedZero); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); ================================================ FILE: test/features/to-string/precision/single/returns/array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision returns Array'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return a[this.thread.x] + 1; }, { canvas, context, output: [6], precision: 'single', }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult, expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/returns/array2d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision returns Array2D'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a, b) { return a[this.thread.x] + b[this.thread.y]; }, { canvas, context, output: [2, 2], precision: 'single', }); const a = [1, 2]; const b = [2, 3]; const expected = [ new Float32Array([3, 4]), new Float32Array([4, 5]), ]; const originalResult = originalKernel(a, b); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a, b); const newResult = new Function('return ' + kernelString)()({ context })(a, b); assert.deepEqual(newResult, expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/returns/array3d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision returns Array3d'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a, b, c) { return a[this.thread.x] + b[this.thread.y] + c[this.thread.z]; }, { canvas, context, output: [2, 2, 2], precision: 'single', }); const a = [1, 2]; const b = [3, 4]; const c = [5, 6]; const expected = [ [ new Float32Array([9,10]), new Float32Array([10,11]), ],[ new Float32Array([10,11]), new Float32Array([11,12]), ] ]; const originalResult = originalKernel(a, b, c); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a, b, c); const newResult = new Function('return ' + kernelString)()({ context })(a, b, c); assert.deepEqual(newResult, expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/single/returns/texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string single precision returns Texture'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return a[this.thread.x] + 1; }, { canvas, context, output: [6], precision: 'single', pipeline: true, }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const originalResult = originalKernel(a); assert.equal(originalResult.constructor.name, 'GLTextureFloat'); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.toArray(), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision arguments Array'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return a[this.thread.x]; }, { canvas, context, output: [4], precision: 'unsigned', }); const a = [1, 2, 3, 4]; const expected = new Float32Array([1,2,3,4]); const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newKernel = new Function('return ' + kernelString)()({ context }); const newResult = newKernel(a); assert.deepEqual(newResult, expected); const b = [4,3,2,1]; const expected2 = new Float32Array([4,3,2,1]); const newResult2 = newKernel(b); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/array2.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision arguments Array(2)'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return a; }, { canvas, context, output: [1], precision: 'unsigned', argumentTypes: { a: 'Array(2)' } }); const a = new Float32Array([1, 2]); const expected = [new Float32Array([1,2])]; const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newKernel = new Function('return ' + kernelString)()({ context }); const newResult = newKernel(a); assert.deepEqual(newResult, expected); const b = new Float32Array([2, 1]); const expected2 = [new Float32Array([2,1])]; const newResult2 = newKernel(b); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/array2d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision arguments Array2D'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { let sum = 0; for (let y = 0; y < 4; y++) { sum += a[y][this.thread.x]; } return sum; }, { canvas, context, output: [4], precision: 'unsigned', }); const a = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]; const b = [ [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], ]; const expected = new Float32Array([28,32,36,40]); const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newKernel = new Function('return ' + kernelString)()({ context }); const newResult = newKernel(a); assert.deepEqual(newResult, expected); const expected2 = new Float32Array([4,4,4,4]); const newResult2 = newKernel(b); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/array3.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision arguments Array(3)'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return a; }, { canvas, context, output: [1], precision: 'unsigned', argumentTypes: { a: 'Array(3)' } }); const a = new Float32Array([1, 2, 3]); const expected = [new Float32Array([1,2,3])]; const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newKernel = new Function('return ' + kernelString)()({ context }); const newResult = newKernel(a); assert.deepEqual(newResult, expected); const b = new Float32Array([1, 1, 1]); const expected2 = [new Float32Array([1,1,1])]; const newResult2 = newKernel(b); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/array3d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision arguments Array3D'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { let sum = 0; for (let z = 0; z < 2; z++) { for (let y = 0; y < 2; y++) { sum += a[z][y][this.thread.x]; } } return sum; }, { canvas, context, output: [2], precision: 'unsigned', }); const a = [ [ [1, 2], [3, 4], ], [ [5, 6], [7, 8], ] ]; const expected = new Float32Array([16, 20]); const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newKernel = new Function('return ' + kernelString)()({ context }); const newResult = newKernel(a); assert.deepEqual(newResult, expected); const b = [ [ [1, 1], [1, 1], ], [ [1, 1], [1, 1], ] ]; const expected2 = new Float32Array([4, 4]); const newResult2 = newKernel(b); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/array4.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision arguments Array(4)'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return a; }, { canvas, context, output: [1], precision: 'unsigned', argumentTypes: { a: 'Array(4)' } }); const a = new Float32Array([1, 2, 3, 4]); const expected = [new Float32Array([1,2,3,4])]; const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newKernel = new Function('return ' + kernelString)()({ context }); const newResult = newKernel(a); assert.deepEqual(newResult, expected); const b = new Float32Array([1, 1, 1, 1]); const expected2 = [new Float32Array([1,1,1,1])]; const newResult2 = newKernel(b); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/boolean.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision arguments Boolean'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return a ? 42 : -42; }, { canvas, context, output: [1], precision: 'unsigned', }); assert.deepEqual(originalKernel(true)[0], 42); assert.deepEqual(originalKernel(false)[0], -42); const kernelString = originalKernel.toString(true); const newKernel = new Function('return ' + kernelString)()({ context }); assert.deepEqual(newKernel(true)[0], 42); assert.deepEqual(newKernel(false)[0], -42); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/float.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision arguments Float'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return Math.floor(a) === 100 ? 42 : -42; }, { canvas, context, output: [1], precision: 'unsigned', argumentTypes: { a: 'Float' }, }); assert.equal(originalKernel.argumentTypes[0], 'Float'); assert.deepEqual(originalKernel(100)[0], 42); assert.deepEqual(originalKernel(10)[0], -42); const kernelString = originalKernel.toString(100); const newKernel = new Function('return ' + kernelString)()({ context }); assert.deepEqual(newKernel(100)[0], 42); assert.deepEqual(newKernel(10)[0], -42); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/html-canvas.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); const { greenCanvas } = require('../../../../../browser-test-utils'); describe('feature: to-string unsigned precision arguments HTMLCanvas'); function testArgument(mode, done) { const canvasInput1 = greenCanvas(mode, 1, 1); const canvasInput2 = greenCanvas(mode, 1, 1); const gpu = new GPU({mode}); const originalKernel = gpu.createKernel(function (canvas1, canvas2) { const pixel1 = canvas1[this.thread.y][this.thread.x]; const pixel2 = canvas2[this.thread.y][this.thread.x]; return pixel1[1] + pixel2[1]; }, { output: [1], precision: 'unsigned', argumentTypes: ['HTMLCanvas', 'HTMLCanvas'], }); const canvas = originalKernel.canvas; const context = originalKernel.context; assert.deepEqual(originalKernel(canvasInput1, canvasInput2)[0], 2); const kernelString = originalKernel.toString(canvasInput1, canvasInput2); const newKernel = new Function('return ' + kernelString)()({context, canvas}); const canvasInput3 = greenCanvas(mode, 1, 1); const canvasInput4 = greenCanvas(mode, 1, 1); assert.deepEqual(newKernel(canvasInput3, canvasInput4)[0], 2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { testArgument('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testArgument('webgl2'); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/html-image-array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, CPUKernel } = require('../../../../../../src'); describe('feature: to-string unsigned precision arguments HTMLImageArray'); function testArgument(mode, done) { loadImages([ 'jellyfish-1.jpeg', 'jellyfish-2.jpeg', 'jellyfish-3.jpeg', 'jellyfish-4.jpeg', ]) .then(([image1, image2, image3, image4]) => { const imagesArray1 = [image1, image2]; const imagesArray2 = [image3, image4]; const gpu = new GPU({mode}); const originalKernel = gpu.createKernel(function (a, selection) { const image0 = a[0][0][0]; const image1 = a[1][0][0]; switch (selection) { case 0: return image0.r * 255; case 1: return image1.r * 255; case 2: return image0.g * 255; case 3: return image1.g * 255; } }, { output: [1], precision: 'unsigned', argumentTypes: ['HTMLImageArray', 'Integer'], }); assert.deepEqual(originalKernel(imagesArray1, 0)[0], 172); assert.deepEqual(originalKernel(imagesArray1, 1)[0], 255); assert.deepEqual(originalKernel(imagesArray2, 2)[0], 87); assert.deepEqual(originalKernel(imagesArray2, 3)[0], 110); const kernelString = originalKernel.toString(imagesArray1, 0); const canvas = originalKernel.canvas; const context = originalKernel.context; const newKernel = new Function('return ' + kernelString)()({context, canvas}); assert.deepEqual(newKernel(imagesArray1, 0)[0], 172); assert.deepEqual(newKernel(imagesArray1, 1)[0], 255); assert.deepEqual(newKernel(imagesArray2, 2)[0], 87); assert.deepEqual(newKernel(imagesArray2, 3)[0], 110); gpu.destroy(); done(originalKernel, newKernel); }); } (GPU.isWebGLSupported ? test : skip)('webgl', t => { const done = t.async(); testArgument('webgl', (kernel) => { // They aren't supported, so test that kernel falls back assert.equal(kernel.kernel.constructor, CPUKernel); done(); }); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', t => { testArgument('webgl2', t.async()); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/html-image.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision arguments HTMLImage'); function testArgument(mode, done) { loadImages(['jellyfish-1.jpeg', 'jellyfish-2.jpeg']) .then(([image1, image2]) => { const gpu = new GPU({mode}); const originalKernel = gpu.createKernel(function (a) { const pixel = a[0][0]; return pixel.b * 255; }, { output: [1], precision: 'unsigned', argumentTypes: ['HTMLImage'], }); const canvas = originalKernel.canvas; const context = originalKernel.context; assert.deepEqual(originalKernel(image1)[0], 253); const kernelString = originalKernel.toString(image1); const newKernel = new Function('return ' + kernelString)()({context, canvas}); assert.deepEqual(newKernel(image1)[0], 253); assert.deepEqual(newKernel(image2)[0], 255); gpu.destroy(); done(); }); } (GPU.isWebGLSupported ? test : skip)('webgl', t => { testArgument('webgl', t.async()); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', t => { testArgument('webgl2', t.async()); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/html-video.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision arguments HTMLVideo'); function testArgument(mode, done) { const video = document.createElement('video'); video.currentTime = 2; video.src = 'jellyfish.webm'; video.oncanplay = (e) => { video.oncanplay = null; setTimeout(() => { const gpu = new GPU({mode}); const originalKernel = gpu.createKernel(function (a) { const pixel = a[0][0]; return pixel.g * 255; }, { output: [1], precision: 'unsigned', argumentTypes: ['HTMLVideo'], }); const canvas = originalKernel.canvas; const context = originalKernel.context; assert.deepEqual(originalKernel(video)[0], 125); const kernelString = originalKernel.toString(video); const newKernel = new Function('return ' + kernelString)()({context, canvas}); assert.deepEqual(newKernel(video)[0], 125); gpu.destroy(); done(); }, 1000); } } (GPU.isWebGLSupported ? test : skip)('webgl', t => { testArgument('webgl', t.async()); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', t => { testArgument('webgl2', t.async()); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/input.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, input } = require('../../../../../../src'); describe('feature: to-string unsigned precision arguments Input'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { let sum = 0; for (let y = 0; y < 2; y++) { for (let x = 0; x < 2; x++) { sum += a[y][x]; } } return sum; }, { canvas, context, output: [1], precision: 'unsigned', }); const arg1 = input([1,2,3,4],[2,2]); const arg2 = input([5,6,7,8],[2,2]); assert.deepEqual(originalKernel(arg1)[0], 10); assert.deepEqual(originalKernel(arg2)[0], 26); const kernelString = originalKernel.toString(arg1); const newKernel = new Function('return ' + kernelString)()({ context }); assert.deepEqual(newKernel(arg1)[0], 10); assert.deepEqual(newKernel(arg2)[0], 26); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/integer.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision arguments Integer'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return Math.floor(a) === 100 ? 42 : -42; }, { canvas, context, output: [1], precision: 'unsigned', argumentTypes: { a: 'Integer' }, }); assert.equal(originalKernel.argumentTypes[0], 'Integer'); assert.deepEqual(originalKernel(100)[0], 42); assert.deepEqual(originalKernel(10)[0], -42); const kernelString = originalKernel.toString(100); const newKernel = new Function('return ' + kernelString)()({ context }); assert.deepEqual(newKernel(100)[0], 42); assert.deepEqual(newKernel(10)[0], -42); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/memory-optimized-number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision arguments MemoryOptimizedNumberTexture'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode, context, canvas }); const texture1 = gpu.createKernel(function() { return this.thread.x; }, { output: [4], optimizeFloatMemory: true, precision: 'unsigned', pipeline: true, })(); const texture2 = gpu.createKernel(function() { return 4 - this.thread.x; }, { output: [4], optimizeFloatMemory: true, precision: 'unsigned', pipeline: true, })(); const originalKernel = gpu.createKernel(function(a) { return a[this.thread.x]; }, { canvas, context, output: [4], precision: 'unsigned' }); assert.deepEqual(originalKernel(texture1), new Float32Array([0,1,2,3])); assert.deepEqual(originalKernel(texture2), new Float32Array([4,3,2,1])); const kernelString = originalKernel.toString(texture1); const newKernel = new Function('return ' + kernelString)()({ context }); assert.deepEqual(newKernel(texture1), new Float32Array([0,1,2,3])); assert.deepEqual(newKernel(texture2), new Float32Array([4,3,2,1])); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/arguments/number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision arguments NumberTexture'); function testArgument(mode, context, canvas) { const gpu = new GPU({ mode, context, canvas }); const texture1 = gpu.createKernel(function() { return this.thread.x; }, { output: [4], optimizeFloatMemory: false, precision: 'unsigned', pipeline: true, })(); const texture2 = gpu.createKernel(function() { return 4 - this.thread.x; }, { output: [4], optimizeFloatMemory: false, precision: 'unsigned', pipeline: true, })(); const originalKernel = gpu.createKernel(function(a) { return a[this.thread.x]; }, { canvas, context, output: [4], precision: 'unsigned' }); assert.deepEqual(originalKernel(texture1), new Float32Array([0,1,2,3])); assert.deepEqual(originalKernel(texture2), new Float32Array([4,3,2,1])); const kernelString = originalKernel.toString(texture1); const newKernel = new Function('return ' + kernelString)()({ context }); assert.deepEqual(newKernel(texture1), new Float32Array([0,1,2,3])); assert.deepEqual(newKernel(texture2), new Float32Array([4,3,2,1])); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testArgument('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testArgument('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testArgument('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testArgument('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/constants/array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision constants Array'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function() { return this.constants.a[this.thread.x]; }, { canvas, context, output: [4], precision: 'unsigned', constants: { a: [1, 2, 3, 4] } }); const expected = new Float32Array([1,2,3,4]); const originalResult = originalKernel(); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(); const newResult = new Function('return ' + kernelString)()({ context, constants: { a: [1, 2, 3, 4] } })(); assert.deepEqual(newResult, expected); const expected2 = new Float32Array([4,3,2,1]); const newResult2 = new Function('return ' + kernelString)()({ context, constants: { a: [4, 3, 2, 1] } })(); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/constants/array2.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision constants Array(2)'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function() { return this.constants.a; }, { canvas, context, output: [1], precision: 'unsigned', constants: { a: new Float32Array([1, 2]) }, constantTypes: { a: 'Array(2)' } }); const expected = [new Float32Array([1, 2])]; const originalResult = originalKernel(); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newResult = Kernel({ context, constants: { a: new Float32Array([1, 2]) } })(); assert.deepEqual(newResult, expected); // Array(2) is "sticky" as a constant, and cannot reset const newResult2 = Kernel({ context, constants: { a: new Float32Array([2, 1]) } })(); assert.deepEqual(newResult2, expected); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/constants/array2d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision constants Array2D'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const a = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]; const originalKernel = gpu.createKernel(function() { let sum = 0; for (let y = 0; y < 4; y++) { sum += this.constants.a[y][this.thread.x]; } return sum; }, { canvas, context, output: [4], precision: 'unsigned', constants: { a } }); const expected = new Float32Array([28,32,36,40]); const originalResult = originalKernel(); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newResult = Kernel({ context, constants: { a } })(); assert.deepEqual(newResult, expected); const b = [ [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], ]; const expected2 = new Float32Array([4,4,4,4]); const newResult2 = Kernel({ context, constants: { a: b } })(); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/constants/array3.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision constants Array(3)'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function() { return this.constants.a; }, { canvas, context, output: [1], precision: 'unsigned', constants: { a: new Float32Array([1, 2, 3]) }, constantTypes: { a: 'Array(3)' } }); const expected = [new Float32Array([1, 2, 3])]; const originalResult = originalKernel(); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newResult = Kernel({ context, constants: { a: new Float32Array([1, 2, 3]) } })(); assert.deepEqual(newResult, expected); // Array(3) is "sticky" as a constant, and cannot reset const newResult2 = Kernel({ context, constants: { a: new Float32Array([3, 2, 1]) } })(); assert.deepEqual(newResult2, expected); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/constants/array3d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision constants Array3D'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const a = [ [ [1, 2], [3, 4], ], [ [5, 6], [7, 8], ] ]; const originalKernel = gpu.createKernel(function() { let sum = 0; for (let z = 0; z < 2; z++) { for (let y = 0; y < 2; y++) { sum += this.constants.a[z][y][this.thread.x]; } } return sum; }, { canvas, context, output: [2], precision: 'unsigned', constants: { a } }); const expected = new Float32Array([16, 20]); const originalResult = originalKernel(); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newResult = Kernel({ context, constants: { a } })(); assert.deepEqual(newResult, expected); const b = [ [ [1, 1], [1, 1], ], [ [1, 1], [1, 1], ] ]; const newResult2 = Kernel({ context, constants: { a: b } })(); const expected2 = new Float32Array([4, 4]); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/constants/array4.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision constants Array(4)'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const a = new Float32Array([1, 2, 3, 4]); const originalKernel = gpu.createKernel(function() { return this.constants.a; }, { canvas, context, output: [1], precision: 'unsigned', constants: { a }, constantTypes: { a: 'Array(4)' } }); const expected = [new Float32Array([1, 2, 3, 4])]; const originalResult = originalKernel(); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(); const newResult = new Function('return ' + kernelString)()({ context, constants: { a } })(); assert.deepEqual(newResult, expected); // Array(3) is "sticky" as a constant, and cannot reset const b = new Float32Array([4, 3, 2, 1]); const expected2 = [new Float32Array([1, 2, 3, 4])]; const newResult2 = new Function('return ' + kernelString)()({ context, constants: { a: b } })(); assert.deepEqual(newResult2, expected2); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/constants/boolean.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision constants Boolean'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel1 = gpu.createKernel(function() { return this.constants.a ? 42 : -42; }, { canvas, context, output: [1], precision: 'unsigned', constants: { a: true } }); const originalKernel2 = gpu.createKernel(function() { return this.constants.a ? 42 : -42; }, { canvas, context, output: [1], precision: 'unsigned', constants: { a: false } }); assert.deepEqual(originalKernel1()[0], 42); assert.deepEqual(originalKernel2()[0], -42); const kernelString1 = originalKernel1.toString(); const kernelString2 = originalKernel2.toString(); const Kernel1 = new Function('return ' + kernelString1)(); const Kernel2 = new Function('return ' + kernelString2)(); const newKernel1 = Kernel1({ context, constants: { a: true } }); const newKernel2 = Kernel1({ context, constants: { a: false } }); const newKernel3 = Kernel2({ context, constants: { a: false } }); const newKernel4 = Kernel2({ context, constants: { a: true } }); // Boolean is "sticky" as a constant, and cannot reset assert.deepEqual(newKernel1()[0], 42); assert.deepEqual(newKernel2()[0], 42); assert.deepEqual(newKernel3()[0], -42); assert.deepEqual(newKernel4()[0], -42); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/constants/float.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision constants Float'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function() { return Math.floor(this.constants.a) === 100 ? 42 : -42; }, { canvas, context, output: [1], precision: 'unsigned', constants: { a: 100 }, constantTypes: { a: 'Float' } }); assert.equal(originalKernel.constantTypes.a, 'Float'); assert.deepEqual(originalKernel()[0], 42); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); // Float is "sticky" as a constant, and cannot reset const newKernel = Kernel({ context, constants: { a: 100 } }); assert.deepEqual(newKernel()[0], 42); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/constants/html-canvas.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); const { greenCanvas } = require('../../../../../browser-test-utils'); describe('feature: to-string unsigned precision constants HTMLCanvas'); function testArgument(mode, done) { const canvasInput1 = greenCanvas(mode, 1, 1); const canvasInput2 = greenCanvas(mode, 1, 1); const gpu = new GPU({mode}); const originalKernel = gpu.createKernel(function () { const pixel1 = this.constants.canvas1[this.thread.y][this.thread.x]; const pixel2 = this.constants.canvas2[this.thread.y][this.thread.x]; return pixel1[1] + pixel2[1]; }, { output: [1], precision: 'unsigned', constants: { canvas1: canvasInput1, canvas2: canvasInput2 } }); const canvas = originalKernel.canvas; const context = originalKernel.context; assert.deepEqual(originalKernel()[0], 2); const kernelString = originalKernel.toString(); const canvasInput3 = greenCanvas(mode, 1, 1); const canvasInput4 = greenCanvas(mode, 1, 1); const newKernel = new Function('return ' + kernelString)()({ context, canvas, constants: { canvas1: canvasInput3, canvas2: canvasInput4 } }); assert.deepEqual(newKernel()[0], 2); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { testArgument('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testArgument('webgl2'); }); ================================================ FILE: test/features/to-string/precision/unsigned/constants/html-image-array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, CPUKernel } = require('../../../../../../src'); describe('feature: to-string unsigned precision constants HTMLImageArray'); function testArgument(mode, done) { loadImages([ 'jellyfish-1.jpeg', 'jellyfish-2.jpeg', 'jellyfish-3.jpeg', 'jellyfish-4.jpeg', ]) .then(([image1, image2, image3, image4]) => { const images1 = [image1, image2]; const images2 = [image3, image4]; const gpu = new GPU({mode}); const originalKernel = gpu.createKernel(function (selection) { const image0 = this.constants.a[0][0][0]; const image1 = this.constants.a[1][0][0]; switch (selection) { case 0: return image0.r * 255; case 1: return image1.r * 255; case 2: return image0.b * 255; case 3: return image1.b * 255; } }, { output: [1], precision: 'unsigned', argumentTypes: ['Integer'], constants: { a: images1, } }); assert.deepEqual(originalKernel(0)[0], 172); assert.deepEqual(originalKernel(1)[0], 255); assert.deepEqual(originalKernel(2)[0], 253); assert.deepEqual(originalKernel(3)[0], 255); const kernelString = originalKernel.toString(0); const canvas = originalKernel.canvas; const context = originalKernel.context; const Kernel = new Function('return ' + kernelString)(); const newKernel1 = Kernel({context, canvas, constants: { a: images1 }}); assert.deepEqual(newKernel1(0)[0], 172); assert.deepEqual(newKernel1(1)[0], 255); assert.deepEqual(newKernel1(2)[0], 253); assert.deepEqual(newKernel1(3)[0], 255); const newKernel2 = Kernel({context, canvas, constants: { a: images2 }}); assert.deepEqual(newKernel2(0)[0], 0); assert.deepEqual(newKernel2(1)[0], 73); assert.deepEqual(newKernel2(2)[0], 255); assert.deepEqual(newKernel2(3)[0], 253); gpu.destroy(); done(originalKernel, newKernel1); }); } (GPU.isWebGLSupported ? test : skip)('webgl', t => { const done = t.async(); testArgument('webgl', (kernel) => { // They aren't supported, so test that kernel falls back assert.equal(kernel.kernel.constructor, CPUKernel); done(); }); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', t => { testArgument('webgl2', t.async()); }); ================================================ FILE: test/features/to-string/precision/unsigned/constants/html-image.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, utils } = require('../../../../../../src'); const { loadImage, imageToArray, check2DImage } = require('../../../../../browser-test-utils'); describe('feature: to-string unsigned precision constants HTMLImage'); function testArgument(mode, done) { loadImages(['jellyfish-1.jpeg', 'jellyfish-2.jpeg']) .then(([image1, image2]) => { const gpu = new GPU({mode}); const originalKernel = gpu.createKernel(function () { const pixel = this.constants.a[0][0]; return pixel.b * 255; }, { output: [1], precision: 'unsigned', constants: { a: image1 } }); const canvas = originalKernel.canvas; const context = originalKernel.context; assert.deepEqual(originalKernel()[0], 253); const kernelString = originalKernel.toString(); const newKernel = new Function('return ' + kernelString)()({ context, canvas, constants: { a: image2 } }); assert.deepEqual(newKernel()[0], 255); gpu.destroy(); done(); }); } (GPU.isWebGLSupported ? test : skip)('webgl', t => { testArgument('webgl', t.async()); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', t => { testArgument('webgl2', t.async()); }); ================================================ FILE: test/features/to-string/precision/unsigned/constants/input.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, input } = require('../../../../../../src'); describe('feature: to-string unsigned precision constants Input'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const a = input([1,2,3,4],[2,2]); const originalKernel = gpu.createKernel(function() { let sum = 0; for (let y = 0; y < 2; y++) { for (let x = 0; x < 2; x++) { sum += this.constants.a[y][x]; } } return sum; }, { canvas, context, output: [1], precision: 'unsigned', constants: { a } }); assert.deepEqual(originalKernel()[0], 10); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newKernel = Kernel({ context, constants: { a } }); assert.deepEqual(newKernel()[0], 10); const b = input([1,1,1,1],[2,2]); const newKernel2 = Kernel({ context, constants: { a: b } }); assert.deepEqual(newKernel2()[0], 4); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/constants/integer.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision constants Integer'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function() { return Math.floor(this.constants.a) === 100 ? 42 : -42; }, { canvas, context, output: [1], precision: 'unsigned', constants: { a: 100 }, constantTypes: { a: 'Integer' } }); assert.equal(originalKernel.constantTypes.a, 'Integer'); assert.deepEqual(originalKernel()[0], 42); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newKernel = Kernel({ context, constants: { a: 100 } }); assert.deepEqual(newKernel()[0], 42); // Integer is "sticky" as a constant, and cannot reset const newKernel2 = Kernel({ context, constants: { a: 200 } }); assert.deepEqual(newKernel2()[0], 42); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/constants/memory-optimized-number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision constants MemoryOptimizedNumberTexture'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode, context, canvas }); const texture = gpu.createKernel(function() { return this.thread.x; }, { output: [4], optimizeFloatMemory: true, precision: 'unsigned', pipeline: true, })(); const texture2 = gpu.createKernel(function() { return this.output.x - this.thread.x; }, { output: [4], optimizeFloatMemory: true, precision: 'unsigned', pipeline: true, })(); const originalKernel = gpu.createKernel(function() { return this.constants.a[this.thread.x]; }, { output: [4], precision: 'unsigned', constants: { a: texture } }); assert.deepEqual(originalKernel(), new Float32Array([0,1,2,3])); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newKernel = Kernel({ context, constants: { a: texture } }); const newKernel2 = Kernel({ context, constants: { a: texture2 } }); assert.deepEqual(texture2.toArray ? texture2.toArray() : texture2, new Float32Array([4,3,2,1])); assert.deepEqual(texture.toArray ? texture.toArray() : texture, new Float32Array([0,1,2,3])); assert.deepEqual(newKernel(), new Float32Array([0,1,2,3])); assert.deepEqual(newKernel2(), new Float32Array([4,3,2,1])); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/constants/number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision constants NumberTexture'); function testConstant(mode, context, canvas) { const gpu = new GPU({ mode, context, canvas }); const texture = gpu.createKernel(function() { return this.thread.x; }, { output: [4], optimizeFloatMemory: false, precision: 'unsigned', pipeline: true, })(); const texture2 = gpu.createKernel(function() { return this.output.x - this.thread.x; }, { output: [4], optimizeFloatMemory: false, precision: 'unsigned', pipeline: true, })(); const originalKernel = gpu.createKernel(function() { return this.constants.a[this.thread.x]; }, { canvas, context, output: [4], precision: 'unsigned', constants: { a: texture } }); assert.deepEqual(originalKernel(), new Float32Array([0,1,2,3])); const kernelString = originalKernel.toString(); const Kernel = new Function('return ' + kernelString)(); const newKernel = Kernel({ context, constants: { a: texture } }); const newKernel2 = Kernel({ context, constants: { a: texture2 } }); assert.deepEqual(texture2.toArray ? texture2.toArray() : texture2, new Float32Array([4,3,2,1])); assert.deepEqual(texture.toArray ? texture.toArray() : texture, new Float32Array([0,1,2,3])); assert.deepEqual(newKernel(), new Float32Array([0,1,2,3])); assert.deepEqual(newKernel2(), new Float32Array([4,3,2,1])); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testConstant('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testConstant('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testConstant('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testConstant('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/graphical.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../src'); describe('feature: to-string unsigned precision graphical'); function testGraphical(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function() { this.color(1,1,1,1); }, { canvas, context, output: [2,2], precision: 'unsigned', graphical: true, }); const expected = new Uint8ClampedArray([ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, ]); originalKernel(); assert.deepEqual(originalKernel.getPixels(), expected); const kernelString = originalKernel.toString(); const newKernel = new Function('return ' + kernelString)()({ canvas, context }); newKernel(); assert.deepEqual(newKernel.getPixels(), expected); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testGraphical('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testGraphical('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testGraphical('headlessgl', require('gl')(1, 1), null); }); (GPU.isCanvasSupported ? test : skip)('cpu', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); testGraphical('cpu', context, canvas); }); ================================================ FILE: test/features/to-string/precision/unsigned/kernel-map/array/array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string unsigned precision array style kernel map returns Array'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap([addOne], function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [6], precision: 'unsigned', }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const expectedZero = new Float32Array([3, 4, 5, 6, 7, 8]); const originalResult = originalKernel(a); assert.deepEqual(originalResult.result, expected); assert.deepEqual(originalResult[0], expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result, expected); assert.deepEqual(newResult[0], expectedZero); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/kernel-map/array/array2d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string unsigned precision array style kernel map returns Array2D'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap([addOne], function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [2, 2], precision: 'unsigned', }); const a = [1, 2, 3, 4, 5, 6]; const expected = [ new Float32Array([2, 3]), new Float32Array([2, 3]), ]; const expectedZero = [ new Float32Array([3, 4]), new Float32Array([3, 4]), ]; const originalResult = originalKernel(a); assert.deepEqual(originalResult.result, expected); assert.deepEqual(originalResult[0], expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result, expected); assert.deepEqual(newResult[0], expectedZero); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/kernel-map/array/array3d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string unsigned precision array style kernel map returns Array3d'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap([addOne], function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [2, 2, 2], precision: 'unsigned', }); const a = [1, 2]; const expected = [ [ new Float32Array([2, 3]), new Float32Array([2, 3]), ], [ new Float32Array([2, 3]), new Float32Array([2, 3]), ] ]; const expectedZero = [ [ new Float32Array([3, 4]), new Float32Array([3, 4]), ], [ new Float32Array([3, 4]), new Float32Array([3, 4]), ] ]; const originalResult = originalKernel(a); assert.deepEqual(originalResult.result, expected); assert.deepEqual(originalResult[0], expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result, expected); assert.deepEqual(newResult[0], expectedZero); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/kernel-map/array/memory-optimized-number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string unsigned precision array style kernel map returns MemoryOptimizedNumberTexture'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap([addOne], function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [6], precision: 'unsigned', pipeline: true, optimizeFloatMemory: true, }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const expectedZero = new Float32Array([3, 4, 5, 6, 7, 8]); const originalResult = originalKernel(a); assert.deepEqual(originalResult.result.toArray(), expected); assert.deepEqual(originalResult[0].toArray(), expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result.toArray(), expected); assert.deepEqual(newResult[0].toArray(), expectedZero); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); ================================================ FILE: test/features/to-string/precision/unsigned/kernel-map/array/number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string unsigned precision array style kernel map returns NumberTexture'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap([addOne], function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [6], precision: 'unsigned', pipeline: true, }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const expectedZero = new Float32Array([3, 4, 5, 6, 7, 8]); const originalResult = originalKernel(a); assert.deepEqual(originalResult.result.toArray(), expected); assert.deepEqual(originalResult[0].toArray(), expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result.toArray(), expected); assert.deepEqual(newResult[0].toArray(), expectedZero); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); ================================================ FILE: test/features/to-string/precision/unsigned/kernel-map/object/array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string unsigned precision object style returns Array'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap({ addOneResult: addOne }, function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [6], precision: 'unsigned', }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const expectedZero = new Float32Array([3, 4, 5, 6, 7, 8]); const originalResult = originalKernel(a); assert.deepEqual(originalResult.result, expected); assert.deepEqual(originalResult.addOneResult, expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result, expected); assert.deepEqual(newResult.addOneResult, expectedZero); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/kernel-map/object/array2d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string unsigned precision object style returns Array2D'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap({ addOneResult: addOne }, function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [2, 2], precision: 'unsigned', }); const a = [1, 2, 3, 4, 5, 6]; const expected = [ new Float32Array([2, 3]), new Float32Array([2, 3]), ]; const expectedZero = [ new Float32Array([3, 4]), new Float32Array([3, 4]), ]; const originalResult = originalKernel(a); assert.deepEqual(originalResult.result, expected); assert.deepEqual(originalResult.addOneResult, expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result, expected); assert.deepEqual(newResult.addOneResult, expectedZero); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/kernel-map/object/array3d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string unsigned precision object style returns Array3d'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap({ addOneResult: addOne }, function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [2, 2, 2], precision: 'unsigned', }); const a = [1, 2]; const expected = [ [ new Float32Array([2, 3]), new Float32Array([2, 3]), ], [ new Float32Array([2, 3]), new Float32Array([2, 3]), ] ]; const expectedZero = [ [ new Float32Array([3, 4]), new Float32Array([3, 4]), ], [ new Float32Array([3, 4]), new Float32Array([3, 4]), ] ]; const originalResult = originalKernel(a); assert.deepEqual(originalResult.result, expected); assert.deepEqual(originalResult.addOneResult, expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result, expected); assert.deepEqual(newResult.addOneResult, expectedZero); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/kernel-map/object/memory-optimized-number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string unsigned precision object style kernel map returns MemoryOptimizedNumberTexture'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap({ addOneResult: addOne }, function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [6], precision: 'unsigned', pipeline: true, optimizeFloatMemory: true, }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const expectedZero = new Float32Array([3, 4, 5, 6, 7, 8]); const originalResult = originalKernel(a); assert.deepEqual(originalResult.result.toArray(), expected); assert.deepEqual(originalResult.addOneResult.toArray(), expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result.toArray(), expected); assert.deepEqual(newResult.addOneResult.toArray(), expectedZero); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); ================================================ FILE: test/features/to-string/precision/unsigned/kernel-map/object/number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../../src'); describe('feature: to-string unsigned precision object style kernel map returns NumberTexture'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); function addOne(value) { return value + 1; } const originalKernel = gpu.createKernelMap({ addOneResult: addOne }, function(a) { const result = a[this.thread.x] + 1; addOne(result); return result; }, { canvas, context, output: [6], precision: 'unsigned', pipeline: true, }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const expectedZero = new Float32Array([3, 4, 5, 6, 7, 8]); const originalResult = originalKernel(a); assert.deepEqual(originalResult.result.toArray(), expected); assert.deepEqual(originalResult.addOneResult.toArray(), expectedZero); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.result.toArray(), expected); assert.deepEqual(newResult.addOneResult.toArray(), expectedZero); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); ================================================ FILE: test/features/to-string/precision/unsigned/returns/array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision returns Array'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return a[this.thread.x] + 1; }, { canvas, context, output: [6], precision: 'unsigned', }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const originalResult = originalKernel(a); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult, expected); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/returns/array2d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision returns Array2D'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a, b) { return a[this.thread.x] + b[this.thread.y]; }, { canvas, context, output: [2, 2], precision: 'unsigned', }); const a = [1, 2]; const b = [2, 3]; const expected = [ new Float32Array([3, 4]), new Float32Array([4, 5]), ]; const originalResult = originalKernel(a, b); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a, b); const newResult = new Function('return ' + kernelString)()({ context })(a, b); assert.deepEqual(newResult, expected); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/returns/array3d.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision returns Array3d'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a, b, c) { return a[this.thread.x] + b[this.thread.y] + c[this.thread.z]; }, { canvas, context, output: [2, 2, 2], precision: 'unsigned', }); const a = [1, 2]; const b = [3, 4]; const c = [5, 6]; const expected = [ [ new Float32Array([9,10]), new Float32Array([10,11]), ],[ new Float32Array([10,11]), new Float32Array([11,12]), ] ]; const originalResult = originalKernel(a, b, c); assert.deepEqual(originalResult, expected); const kernelString = originalKernel.toString(a, b, c); const newResult = new Function('return ' + kernelString)()({ context })(a, b, c); assert.deepEqual(newResult, expected); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); test('cpu', () => { testReturn('cpu'); }); ================================================ FILE: test/features/to-string/precision/unsigned/returns/texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../../../../../src'); describe('feature: to-string unsigned precision returns Texture'); function testReturn(mode, context, canvas) { const gpu = new GPU({ mode }); const originalKernel = gpu.createKernel(function(a) { return a[this.thread.x] + 1; }, { canvas, context, output: [6], precision: 'unsigned', pipeline: true, }); const a = [1, 2, 3, 4, 5, 6]; const expected = new Float32Array([2, 3, 4, 5, 6, 7]); const originalResult = originalKernel(a); assert.equal(originalResult.constructor.name, 'GLTextureUnsigned'); const kernelString = originalKernel.toString(a); const newResult = new Function('return ' + kernelString)()({ context })(a); assert.deepEqual(newResult.toArray(), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testReturn('webgl', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testReturn('webgl2', context, canvas); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testReturn('headlessgl', require('gl')(1, 1), null); }); ================================================ FILE: test/features/type-management.js ================================================ const { assert, test, module: describe, only, skip } = require('qunit'); const { GPU, WebGLFunctionNode, WebGL2FunctionNode, CPUFunctionNode } = require('../../src'); describe('features: type management'); test('arrays directly - Array(2) webgl', () => { const node = new WebGLFunctionNode((function direct() { return [0, 0]; }).toString(), { returnType: 'Array(2)', output: [1] }); assert.equal(node.toString(), 'vec2 direct() {\n\ return vec2(0.0, 0.0);\n\ }'); }); test('arrays directly - Array(2) webgl2', () => { const node = new WebGL2FunctionNode((function direct() { return [0, 0]; }).toString(), { returnType: 'Array(2)', output: [1] }); assert.equal(node.toString(), 'vec2 direct() {\n\ return vec2(0.0, 0.0);\n\ }'); }); test('arrays directly - Array(2) cpu', () => { const node = new CPUFunctionNode((function direct() { return [0, 0]; }).toString(), { returnType: 'Array(2)', output: [1] }); assert.equal(node.toString(), 'function direct() {\n\ return new Float32Array([0, 0]);\n\ }'); }); test('arrays directly - Array(3) webgl', () => { const node = new WebGLFunctionNode((function direct() { return [0, 0, 0]; }).toString(), { returnType: 'Array(3)', output: [1] }); assert.equal(node.toString(), 'vec3 direct() {\n\ return vec3(0.0, 0.0, 0.0);\n\ }'); }); test('arrays directly - Array(3) webgl2', () => { const node = new WebGL2FunctionNode((function direct() { return [0, 0, 0]; }).toString(), { returnType: 'Array(3)', output: [1] }); assert.equal(node.toString(), 'vec3 direct() {\n\ return vec3(0.0, 0.0, 0.0);\n\ }'); }); test('arrays directly - Array(3) cpu', () => { const node = new CPUFunctionNode((function direct() { return [0, 0, 0]; }).toString(), { returnType: 'Array(3)', output: [1] }); assert.equal(node.toString(), 'function direct() {\n\ return new Float32Array([0, 0, 0]);\n\ }'); }); test('arrays directly - Array(4) webgl', () => { const node = new WebGLFunctionNode((function direct() { return [0, 0, 0, 0]; }).toString(), { returnType: 'Array(4)', output: [1] }); assert.equal(node.toString(), 'vec4 direct() {\n\ return vec4(0.0, 0.0, 0.0, 0.0);\n\ }'); }); test('arrays directly - Array(4) webgl2', () => { const node = new WebGL2FunctionNode((function direct() { return [0, 0, 0, 0]; }).toString(), { returnType: 'Array(4)', output: [1] }); assert.equal(node.toString(), 'vec4 direct() {\n\ return vec4(0.0, 0.0, 0.0, 0.0);\n\ }'); }); test("arrays directly - Array(4) cpu", function(assert) { const node = new CPUFunctionNode((function direct() { return [0, 0, 0, 0]; }).toString(), { returnType: 'Array(4)', output: [1] }); assert.equal(node.toString(), 'function direct() {\n\ return new Float32Array([0, 0, 0, 0]);\n\ }'); }); test('arrays referenced directly - Array(2) webgl', () => { const node = new WebGLFunctionNode((function refDirect() { const array = [0, 0]; return array; }).toString(), { returnType: 'Array(2)', output: [1] }); assert.equal(node.toString(), 'vec2 refDirect() {\n\ vec2 user_array=vec2(0.0, 0.0);\n\ return user_array;\n\ }'); }); test('arrays referenced directly - Array(2) webgl2', () => { const node = new WebGL2FunctionNode((function refDirect() { const array = [0, 0]; return array; }).toString(), { returnType: 'Array(2)', output: [1] }); assert.equal(node.toString(), 'vec2 refDirect() {\n\ vec2 user_array=vec2(0.0, 0.0);\n\ return user_array;\n\ }'); }); test('arrays referenced directly - Array(2) cpu', () => { const node = new CPUFunctionNode((function refDirect() { const array = [0, 0]; return array; }).toString(), { returnType: 'Array(2)', output: [1] }); assert.equal(node.toString(), 'function refDirect() {\n\ const user_array=new Float32Array([0, 0]);\n\ return user_array;\n\ }'); }); test('arrays referenced directly - Array(3) webgl', () => { const node = new WebGLFunctionNode((function refDirect() { const array = [0, 0, 0]; return array; }).toString(), { returnType: 'Array(3)', output: [1] }); assert.equal(node.toString(), 'vec3 refDirect() {\n\ vec3 user_array=vec3(0.0, 0.0, 0.0);\n\ return user_array;\n\ }'); }); test('arrays referenced directly - Array(3) webgl2', () => { const node = new WebGL2FunctionNode((function refDirect() { const array = [0, 0, 0]; return array; }).toString(), { returnType: 'Array(3)', output: [1] }); assert.equal(node.toString(), 'vec3 refDirect() {\n\ vec3 user_array=vec3(0.0, 0.0, 0.0);\n\ return user_array;\n\ }'); }); test('arrays referenced directly - Array(3) cpu', () => { const node = new CPUFunctionNode((function refDirect() { const array = [0, 0, 0]; return array; }).toString(), { returnType: 'Array(3)', output: [1] }); assert.equal(node.toString(), 'function refDirect() {\n\ const user_array=new Float32Array([0, 0, 0]);\n\ return user_array;\n\ }'); }); test('arrays referenced directly - Array(4) webgl', () => { const node = new WebGLFunctionNode((function refDirect() { const array = [0, 0, 0, 0]; return array; }).toString(), { returnType: 'Array(4)', output: [1] }); assert.equal(node.toString(), 'vec4 refDirect() {\n\ vec4 user_array=vec4(0.0, 0.0, 0.0, 0.0);\n\ return user_array;\n\ }'); }); test('arrays referenced directly - Array(4) webgl2', () => { const node = new WebGL2FunctionNode((function refDirect() { const array = [0, 0, 0, 0]; return array; }).toString(), { returnType: 'Array(4)', output: [1] }); assert.equal(node.toString(), 'vec4 refDirect() {\n\ vec4 user_array=vec4(0.0, 0.0, 0.0, 0.0);\n\ return user_array;\n\ }'); }); test('arrays referenced directly - Array(4) cpu', () => { const node = new CPUFunctionNode((function refDirect() { const array = [0, 0, 0, 0]; return array; }).toString(), { returnType: 'Array(4)', output: [1] }); assert.equal(node.toString(), 'function refDirect() {\n\ const user_array=new Float32Array([0, 0, 0, 0]);\n\ return user_array;\n\ }'); }); test('arrays referenced indirectly - Array(2) webgl', () => { const node = new WebGLFunctionNode((function indirect() { const array = [0, 0]; const array2 = array; return array2; }).toString(), { returnType: 'Array(2)', output: [1] }); assert.equal(node.toString(), 'vec2 indirect() {\n\ vec2 user_array=vec2(0.0, 0.0);\n\ vec2 user_array2=user_array;\n\ return user_array2;\n\ }'); }); test('arrays referenced indirectly - Array(2) webgl2', () => { const node = new WebGL2FunctionNode((function indirect() { const array = [0, 0]; const array2 = array; return array2; }).toString(), { returnType: 'Array(2)', output: [1] }); assert.equal(node.toString(), 'vec2 indirect() {\n\ vec2 user_array=vec2(0.0, 0.0);\n\ vec2 user_array2=user_array;\n\ return user_array2;\n\ }'); }); test('arrays referenced indirectly - Array(2) cpu', () => { const node = new CPUFunctionNode((function indirect() { const array = [0, 0]; const array2 = array; return array2; }).toString(), { returnType: 'Array(2)', output: [1] }); assert.equal(node.toString(), 'function indirect() {\n\ const user_array=new Float32Array([0, 0]);\n\ const user_array2=user_array;\n\ return user_array2;\n\ }'); }); test('arrays referenced indirectly - Array(3) webgl', () => { const node = new WebGLFunctionNode((function indirect() { const array = [0, 0, 0]; const array2 = array; return array2; }).toString(), { returnType: 'Array(3)', output: [1] }); assert.equal(node.toString(), 'vec3 indirect() {\n\ vec3 user_array=vec3(0.0, 0.0, 0.0);\n\ vec3 user_array2=user_array;\n\ return user_array2;\n\ }'); }); test('arrays referenced indirectly - Array(3) webgl2', () => { const node = new WebGL2FunctionNode((function indirect() { const array = [0, 0, 0]; const array2 = array; return array2; }).toString(), { returnType: 'Array(3)', output: [1] }); assert.equal(node.toString(), 'vec3 indirect() {\n\ vec3 user_array=vec3(0.0, 0.0, 0.0);\n\ vec3 user_array2=user_array;\n\ return user_array2;\n\ }'); }); test('arrays referenced indirectly - Array(3) cpu', () => { const node = new CPUFunctionNode((function indirect() { const array = [0, 0, 0]; const array2 = array; return array2; }).toString(), { returnType: 'Array(3)', output: [1] }); assert.equal(node.toString(), 'function indirect() {\n\ const user_array=new Float32Array([0, 0, 0]);\n\ const user_array2=user_array;\n\ return user_array2;\n\ }'); }); test('arrays referenced indirectly - Array(4) webgl', () => { const node = new WebGLFunctionNode((function indirect() { const array = [0, 0, 0, 0]; const array2 = array; return array2; }).toString(), { returnType: 'Array(4)', output: [1] }); assert.equal(node.toString(), 'vec4 indirect() {\n\ vec4 user_array=vec4(0.0, 0.0, 0.0, 0.0);\n\ vec4 user_array2=user_array;\n\ return user_array2;\n\ }'); }); test('arrays referenced indirectly - Array(4) webgl2', () => { const node = new WebGL2FunctionNode((function indirect() { const array = [0, 0, 0, 0]; const array2 = array; return array2; }).toString(), { returnType: 'Array(4)', output: [1] }); assert.equal(node.toString(), 'vec4 indirect() {\n\ vec4 user_array=vec4(0.0, 0.0, 0.0, 0.0);\n\ vec4 user_array2=user_array;\n\ return user_array2;\n\ }'); }); test('arrays referenced indirectly - Array(4) cpu', () => { const node = new CPUFunctionNode((function indirect() { const array = [0, 0, 0, 0]; const array2 = array; return array2; }).toString(), { returnType: 'Array(4)', output: [1] }); assert.equal(node.toString(), 'function indirect() {\n\ const user_array=new Float32Array([0, 0, 0, 0]);\n\ const user_array2=user_array;\n\ return user_array2;\n\ }'); }); test('arrays arguments - Array(2) webgl', () => { const node = new WebGLFunctionNode((function arrayArguments(array, array2) { const array3 = [0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(2)', 'Array(2)'], output: [1] }); assert.equal(node.toString(), 'vec2 arrayArguments(vec2 user_array, vec2 user_array2) {\n\ vec2 user_array3=vec2(0.0, 0.0);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays arguments - Array(2) webgl2', () => { const node = new WebGL2FunctionNode((function arrayArguments(array, array2) { const array3 = [0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(2)', 'Array(2)'], output: [1] }); assert.equal(node.toString(), 'vec2 arrayArguments(vec2 user_array, vec2 user_array2) {\n\ vec2 user_array3=vec2(0.0, 0.0);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays arguments - Array(2) cpu', () => { const node = new CPUFunctionNode((function arrayArguments(array, array2) { const array3 = [0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(2)', 'Array(2)'], output: [1] }); assert.equal(node.toString(), 'function arrayArguments(user_array, user_array2) {\n\ const user_array3=new Float32Array([0, 0]);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays arguments - Array(3) webgl', () => { const node = new WebGLFunctionNode((function arrayArguments(array, array2) { const array3 = [0, 0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(3)', 'Array(3)'], output: [1] }); assert.equal(node.toString(), 'vec3 arrayArguments(vec3 user_array, vec3 user_array2) {\n\ vec3 user_array3=vec3(0.0, 0.0, 0.0);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays arguments - Array(3) webgl2', () => { const node = new WebGL2FunctionNode((function arrayArguments(array, array2) { const array3 = [0, 0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(3)', 'Array(3)'], output: [1] }); assert.equal(node.toString(), 'vec3 arrayArguments(vec3 user_array, vec3 user_array2) {\n\ vec3 user_array3=vec3(0.0, 0.0, 0.0);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays arguments - Array(3) cpu', () => { const node = new CPUFunctionNode((function arrayArguments(array, array2) { const array3 = [0, 0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(3)', 'Array(3)'], output: [1] }); assert.equal(node.toString(), 'function arrayArguments(user_array, user_array2) {\n\ const user_array3=new Float32Array([0, 0, 0]);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays arguments - Array(4) webgl', () => { const node = new WebGLFunctionNode((function arrayArguments(array, array2) { const array3 = [0, 0, 0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(4)', 'Array(4)'], output: [1] }); assert.equal(node.toString(), 'vec4 arrayArguments(vec4 user_array, vec4 user_array2) {\n\ vec4 user_array3=vec4(0.0, 0.0, 0.0, 0.0);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays arguments - Array(4) webgl2', () => { const node = new WebGL2FunctionNode((function arrayArguments(array, array2) { const array3 = [0, 0, 0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(4)', 'Array(4)'], output: [1] }); assert.equal(node.toString(), 'vec4 arrayArguments(vec4 user_array, vec4 user_array2) {\n\ vec4 user_array3=vec4(0.0, 0.0, 0.0, 0.0);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays arguments - Array(4) cpu', () => { const node = new CPUFunctionNode((function arrayArguments(array, array2) { const array3 = [0, 0, 0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(4)', 'Array(4)'], output: [1] }); assert.equal(node.toString(), 'function arrayArguments(user_array, user_array2) {\n\ const user_array3=new Float32Array([0, 0, 0, 0]);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays inherited - Array(2) webgl', () => { const node = new WebGLFunctionNode((function inherited(array, array2) { const array3 = [0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(2)', 'Array(2)'], returnType: 'Array(2)', output: [1] }); assert.equal(node.toString(), 'vec2 inherited(vec2 user_array, vec2 user_array2) {\n\ vec2 user_array3=vec2(0.0, 0.0);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays inherited - Array(2) webgl2', () => { const node = new WebGL2FunctionNode((function inherited(array, array2) { const array3 = [0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(2)', 'Array(2)'], returnType: 'Array(2)', output: [1] }); assert.equal(node.toString(), 'vec2 inherited(vec2 user_array, vec2 user_array2) {\n\ vec2 user_array3=vec2(0.0, 0.0);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays inherited - Array(2) cpu', () => { const node = new CPUFunctionNode((function inherited(array, array2) { const array3 = [0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(2)', 'Array(2)'], returnType: 'Array(2)', output: [1] }); assert.equal(node.toString(), 'function inherited(user_array, user_array2) {\n\ const user_array3=new Float32Array([0, 0]);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays inherited - Array(3) webgl', () => { const node = new WebGLFunctionNode((function inherited(array, array2) { const array3 = [0, 0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(3)', 'Array(3)'], returnType: 'Array(3)', output: [1] }); assert.equal(node.toString(), 'vec3 inherited(vec3 user_array, vec3 user_array2) {\n\ vec3 user_array3=vec3(0.0, 0.0, 0.0);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays inherited - Array(3) webgl2', () => { const node = new WebGL2FunctionNode((function inherited(array, array2) { const array3 = [0, 0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(3)', 'Array(3)'], returnType: 'Array(3)', output: [1] }); assert.equal(node.toString(), 'vec3 inherited(vec3 user_array, vec3 user_array2) {\n\ vec3 user_array3=vec3(0.0, 0.0, 0.0);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays inherited - Array(3) cpu', () => { const node = new CPUFunctionNode((function inherited(array, array2) { const array3 = [0, 0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(3)', 'Array(3)'], returnType: 'Array(3)', output: [1] }); assert.equal(node.toString(), 'function inherited(user_array, user_array2) {\n\ const user_array3=new Float32Array([0, 0, 0]);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays inherited - Array(4) webgl', () => { const node = new WebGLFunctionNode((function inherited(array, array2) { const array3 = [0, 0, 0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(4)', 'Array(4)'], returnType: 'Array(4)', output: [1] }); assert.equal(node.toString(), 'vec4 inherited(vec4 user_array, vec4 user_array2) {\n\ vec4 user_array3=vec4(0.0, 0.0, 0.0, 0.0);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('arrays inherited - Array(4) webgl2', () => { const node = new WebGL2FunctionNode((function inherited(array, array2) { const array3 = [0, 0, 0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(4)', 'Array(4)'], returnType: 'Array(4)', output: [1] }); assert.equal(node.toString(), 'vec4 inherited(vec4 user_array, vec4 user_array2) {' + '\nvec4 user_array3=vec4(0.0, 0.0, 0.0, 0.0);' + '\nuser_array3[0]=user_array[0];' + '\nuser_array3[1]=(user_array[1]*user_array2[1]);' + '\nreturn user_array3;' + '\n}'); }); test('arrays inherited - Array(4) cpu', () => { const node = new CPUFunctionNode((function inherited(array, array2) { const array3 = [0, 0, 0, 0]; array3[0] = array[0]; array3[1] = array[1] * array2[1]; return array3; }).toString(), { argumentTypes: ['Array(4)', 'Array(4)'], returnType: 'Array(4)', output: [1] }); assert.equal(node.toString(), 'function inherited(user_array, user_array2) {\n\ const user_array3=new Float32Array([0, 0, 0, 0]);\n\ user_array3[0]=user_array[0];\n\ user_array3[1]=(user_array[1]*user_array2[1]);\n\ return user_array3;\n\ }'); }); test('auto detect float, array, array2d, array3d - webgl', () => { const node = new WebGLFunctionNode(`function advancedUsed(int, array, array2d, array3d) { let allValues = this.constants.float; allValues += this.constants.int; allValues += this.constants.array[this.thread.x]; allValues += this.constants.array2d[this.thread.x][this.thread.y]; allValues += this.constants.array3d[this.thread.x][this.thread.y][this.thread.z]; allValues += int; allValues += array[this.thread.x]; allValues += array2d[this.thread.x][this.thread.y]; allValues += array3d[this.thread.x][this.thread.y][this.thread.z]; return allValues * Math.random(); }`, { returnType: 'Number', output: [1], argumentTypes: ['Integer', 'Array', 'Array2D', 'Array3D'], constants: { float: 1, int: 1, array: [1], array2d: [[1]], array3d: [[[1]]] }, constantTypes: { float: 'Float', int: 'Integer', array: 'Array', array2d: 'Array2D', array3d: 'Array3D' }, constantBitRatios: { float: 0, int: 0, array: 4, array2d: 4, array3d: 4 }, lookupFunctionArgumentBitRatio: () => 4, }); assert.equal(node.toString(), 'float advancedUsed(int user_int, sampler2D user_array,ivec2 user_arraySize,ivec3 user_arrayDim, sampler2D user_array2d,ivec2 user_array2dSize,ivec3 user_array2dDim, sampler2D user_array3d,ivec2 user_array3dSize,ivec3 user_array3dDim) {' + '\nfloat user_allValues=constants_float;' + '\nuser_allValues+=float(constants_int);' + '\nuser_allValues+=get32(constants_array, constants_arraySize, constants_arrayDim, 0, 0, threadId.x);' + '\nuser_allValues+=get32(constants_array2d, constants_array2dSize, constants_array2dDim, 0, threadId.x, threadId.y);' + '\nuser_allValues+=get32(constants_array3d, constants_array3dSize, constants_array3dDim, threadId.x, threadId.y, threadId.z);' + '\nuser_allValues+=float(user_int);' + '\nuser_allValues+=get32(user_array, user_arraySize, user_arrayDim, 0, 0, threadId.x);' + '\nuser_allValues+=get32(user_array2d, user_array2dSize, user_array2dDim, 0, threadId.x, threadId.y);' + '\nuser_allValues+=get32(user_array3d, user_array3dSize, user_array3dDim, threadId.x, threadId.y, threadId.z);' + '\nreturn (user_allValues*random());' + '\n}'); }); function notDefined(mode) { const gpu = new GPU({ mode }); const kernel1 = gpu.createKernel(function() { return result; }, { output: [1] }); assert.throws(() => { kernel1(); }, new Error('Identifier is not defined on line 1, position 0:\n result')); const kernel2 = gpu.createKernel(function() { return result[0]; }, { output: [1] }); assert.throws(() => { kernel2(); }, new Error('Identifier is not defined on line 1, position 0:\n result')); const kernel3 = gpu.createKernel(function() { return result[0][0]; }, { output: [1] }); assert.throws(() => { kernel3(); }, new Error('Identifier is not defined on line 1, position 0:\n result')); const kernel4 = gpu.createKernel(function() { return result[0][0][0]; }, { output: [1] }); assert.throws(() => { kernel4(); }, new Error('Identifier is not defined on line 1, position 0:\n result')); const kernel5 = gpu.createKernel(function() { return result[0][0][0][0]; }, { output: [1] }); assert.throws(() => { kernel5(); }, new Error('Identifier is not defined on line 1, position 1:\n result')); gpu.destroy(); } test('not defined auto', () => { notDefined(); }); test('not defined gpu', () => { notDefined('gpu'); }); (GPU.isWebGLSupported ? test : skip)('not defined webgl', () => { notDefined('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('not defined webgl2', () => { notDefined('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('not defined headlessgl', () => { notDefined('headlessgl'); }); test('not defined cpu', () => { notDefined('cpu'); }); ================================================ FILE: test/features/unsigned-precision-textures.js ================================================ const { assert, skip, test, only, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('features: unsigned precision textures'); function unsignedPrecisionTexturesWithArray(mode) { const original = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.x]; }, { output: [9], precision: 'unsigned' }); const result = kernel(original); assert.deepEqual(Array.from(result), original); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('with Array auto', () => { unsignedPrecisionTexturesWithArray(); }); test('with Array cpu', () => { unsignedPrecisionTexturesWithArray('cpu'); }); (GPU.isKernelMapSupported ? test : skip)('with Array gpu', () => { unsignedPrecisionTexturesWithArray('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Array webgl', () => { unsignedPrecisionTexturesWithArray('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Array webgl2', () => { unsignedPrecisionTexturesWithArray('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Array headlessgl', () => { unsignedPrecisionTexturesWithArray('headlessgl'); }); function unsignedPrecisionTexturesWithFloat32Array(mode) { const original = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9]); const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.x]; }, { output: [9], precision: 'unsigned' }); const result = kernel(original); assert.deepEqual(Array.from(result), Array.from(original)); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('with Float32Array auto', () => { unsignedPrecisionTexturesWithFloat32Array(); }); test('with Float32Array cpu', () => { unsignedPrecisionTexturesWithFloat32Array('cpu'); }); (GPU.isKernelMapSupported ? test : skip)('with Float32Array gpu', () => { unsignedPrecisionTexturesWithFloat32Array('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array webgl', () => { unsignedPrecisionTexturesWithFloat32Array('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Float32Array webgl2', () => { unsignedPrecisionTexturesWithFloat32Array('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array headlessgl', () => { unsignedPrecisionTexturesWithFloat32Array('headlessgl'); }); function unsignedPrecisionTexturesWithUint16Array(mode) { const original = new Uint16Array([1, 2, 3, 4, 5, 6, 7, 8, 9]); const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.x]; }, { output: [9], precision: 'unsigned', }); const result = kernel(original); assert.deepEqual(Array.from(result), Array.from(original)); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('with Uint16Array auto', () => { unsignedPrecisionTexturesWithUint16Array(); }); test('with Uint16Array cpu', () => { unsignedPrecisionTexturesWithUint16Array('cpu'); }); (GPU.isKernelMapSupported ? test : skip)('with Uint16Array gpu', () => { unsignedPrecisionTexturesWithUint16Array('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array webgl', () => { unsignedPrecisionTexturesWithUint16Array('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Uint16Array webgl2', () => { unsignedPrecisionTexturesWithUint16Array('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array headlessgl', () => { unsignedPrecisionTexturesWithUint16Array('headlessgl'); }); function unsignedPrecisionTexturesWithUint8Array(mode) { const original = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]); const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.x]; }, { output: [9], precision: 'unsigned' }); const result = kernel(original); assert.deepEqual(Array.from(result), Array.from(original)); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('with Uint8Array auto', () => { unsignedPrecisionTexturesWithUint8Array(); }); test('with Uint8Array cpu', () => { unsignedPrecisionTexturesWithUint8Array('cpu'); }); (GPU.isKernelMapSupported ? test : skip)('with Uint8Array gpu', () => { unsignedPrecisionTexturesWithUint8Array('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array webgl', () => { unsignedPrecisionTexturesWithUint8Array('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Uint8Array webgl2', () => { unsignedPrecisionTexturesWithUint8Array('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array headlessgl', () => { unsignedPrecisionTexturesWithUint8Array('headlessgl'); }); function unsignedPrecisionTexturesWithUint8ClampedArray(mode) { const original = new Uint8ClampedArray([1, 2, 3, 4, 5, 6, 7, 8, 9]); const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.x]; }, { output: [9], precision: 'unsigned' }); const result = kernel(original); assert.deepEqual(Array.from(result), Array.from(original)); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray auto', () => { unsignedPrecisionTexturesWithUint8ClampedArray(); }); test('with Uint8ClampedArray cpu', () => { unsignedPrecisionTexturesWithUint8ClampedArray('cpu'); }); (GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray gpu', () => { unsignedPrecisionTexturesWithUint8ClampedArray('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray webgl', () => { unsignedPrecisionTexturesWithUint8ClampedArray('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Uint8ClampedArray webgl2', () => { unsignedPrecisionTexturesWithUint8ClampedArray('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray headlessgl', () => { unsignedPrecisionTexturesWithUint8ClampedArray('headlessgl'); }); function unsignedPrecisionTexturesWithArray2D(mode) { const original = [ [1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 18, 19], ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.y][this.thread.x]; }, { output: [9, 2], precision: 'unsigned' }); const result = kernel(original); assert.deepEqual(result.map(array => Array.from(array)), original.map(array => Array.from(array))); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('with Array2D auto', () => { unsignedPrecisionTexturesWithArray2D(); }); test('with Array2D cpu', () => { unsignedPrecisionTexturesWithArray2D('cpu'); }); (GPU.isKernelMapSupported ? test : skip)('with Array2D gpu', () => { unsignedPrecisionTexturesWithArray2D('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Array2D webgl', () => { unsignedPrecisionTexturesWithArray2D('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Array2D webgl2', () => { unsignedPrecisionTexturesWithArray2D('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Array2D headlessgl', () => { unsignedPrecisionTexturesWithArray2D('headlessgl'); }); function unsignedPrecisionTexturesWithFloat32Array2D(mode) { const original = [ new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Float32Array([10, 11, 12, 13, 14, 15, 16, 18, 19]), ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.y][this.thread.x]; }, { output: [9, 2], precision: 'unsigned' }); const result = kernel(original); assert.deepEqual(result.map(array => Array.from(array)), original.map(array => Array.from(array))); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('with Float32Array2D auto', () => { unsignedPrecisionTexturesWithFloat32Array2D(); }); test('with Float32Array2D cpu', () => { unsignedPrecisionTexturesWithFloat32Array2D('cpu'); }); (GPU.isKernelMapSupported ? test : skip)('with Float32Array2D gpu', () => { unsignedPrecisionTexturesWithFloat32Array2D('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array2D webgl', () => { unsignedPrecisionTexturesWithFloat32Array2D('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Float32Array2D webgl2', () => { unsignedPrecisionTexturesWithFloat32Array2D('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array2D headlessgl', () => { unsignedPrecisionTexturesWithFloat32Array2D('headlessgl'); }); function unsignedPrecisionTexturesWithUint16Array2D(mode) { const original = [ new Uint16Array([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Uint16Array([10, 11, 12, 13, 14, 15, 16, 18, 19]), ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.y][this.thread.x]; }, { output: [9, 2], precision: 'unsigned' }); const result = kernel(original); assert.deepEqual(result.map(array => Array.from(array)), original.map(array => Array.from(array))); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('with Uint16Array2D auto', () => { unsignedPrecisionTexturesWithUint16Array2D(); }); test('with Uint16Array2D cpu', () => { unsignedPrecisionTexturesWithUint16Array2D('cpu'); }); (GPU.isKernelMapSupported ? test : skip)('with Uint16Array2D gpu', () => { unsignedPrecisionTexturesWithUint16Array2D('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array2D webgl', () => { unsignedPrecisionTexturesWithUint16Array2D('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Uint16Array2D webgl2', () => { unsignedPrecisionTexturesWithUint16Array2D('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array2D headlessgl', () => { unsignedPrecisionTexturesWithUint16Array2D('headlessgl'); }); function unsignedPrecisionTexturesWithUint8Array2D(mode) { const original = [ new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Uint8Array([10, 11, 12, 13, 14, 15, 16, 18, 19]), ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.y][this.thread.x]; }, { output: [9, 2], precision: 'unsigned' }); const result = kernel(original); assert.deepEqual(result.map(array => Array.from(array)), original.map(array => Array.from(array))); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('with Uint8Array2D auto', () => { unsignedPrecisionTexturesWithUint8Array2D(); }); test('with Uint8Array2D cpu', () => { unsignedPrecisionTexturesWithUint8Array2D('cpu'); }); (GPU.isKernelMapSupported ? test : skip)('with Uint8Array2D gpu', () => { unsignedPrecisionTexturesWithUint8Array2D('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array2D webgl', () => { unsignedPrecisionTexturesWithUint8Array2D('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Uint8Array2D webgl2', () => { unsignedPrecisionTexturesWithUint8Array2D('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array2D headlessgl', () => { unsignedPrecisionTexturesWithUint8Array2D('headlessgl'); }); function unsignedPrecisionTexturesWithUint8ClampedArray2D(mode) { const original = [ new Uint8ClampedArray([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Uint8ClampedArray([10, 11, 12, 13, 14, 15, 16, 18, 19]), ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.y][this.thread.x]; }, { output: [9, 2], precision: 'unsigned' }); const result = kernel(original); assert.deepEqual(result.map(array => Array.from(array)), original.map(array => Array.from(array))); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray2D auto', () => { unsignedPrecisionTexturesWithUint8ClampedArray2D(); }); test('with Uint8ClampedArray2D cpu', () => { unsignedPrecisionTexturesWithUint8ClampedArray2D('cpu'); }); (GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray2D gpu', () => { unsignedPrecisionTexturesWithUint8ClampedArray2D('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray2D webgl', () => { unsignedPrecisionTexturesWithUint8ClampedArray2D('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Uint8ClampedArray2D webgl2', () => { unsignedPrecisionTexturesWithUint8ClampedArray2D('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray2D headlessgl', () => { unsignedPrecisionTexturesWithUint8ClampedArray2D('headlessgl'); }); function unsignedPrecisionTexturesWithArray3D(mode) { const original = [ [ [1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 18, 19], ], [ [20, 21, 22, 23, 24, 25, 26, 27, 28], [29, 30, 31, 32, 33, 34, 35, 36, 37], ] ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.z][this.thread.y][this.thread.x]; }, { output: [9, 2, 2], precision: 'unsigned' }); const result = kernel(original); assert.deepEqual(result.map(matrix => matrix.map(array => Array.from(array))), original); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('with Array3D auto', () => { unsignedPrecisionTexturesWithArray3D(); }); test('with Array3D cpu', () => { unsignedPrecisionTexturesWithArray3D('cpu'); }); (GPU.isKernelMapSupported ? test : skip)('with Array3D gpu', () => { unsignedPrecisionTexturesWithArray3D('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Array3D webgl', () => { unsignedPrecisionTexturesWithArray3D('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Array3D webgl2', () => { unsignedPrecisionTexturesWithArray3D('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Array3D headlessgl', () => { unsignedPrecisionTexturesWithArray3D('headlessgl'); }); function unsignedPrecisionTexturesWithFloat32Array3D(mode) { const original = [ [ new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Float32Array([10, 11, 12, 13, 14, 15, 16, 18, 19]), ], [ new Float32Array([20, 21, 22, 23, 24, 25, 26, 27, 28]), new Float32Array([29, 30, 31, 32, 33, 34, 35, 36, 37]), ] ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.z][this.thread.y][this.thread.x]; }, { output: [9, 2, 2], precision: 'unsigned' }); const result = kernel(original); assert.deepEqual(result.map(matrix => matrix.map(array => Array.from(array))), original.map(matrix => matrix.map(array => Array.from(array)))); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('with Float32Array3D auto', () => { unsignedPrecisionTexturesWithFloat32Array3D(); }); test('with Float32Array3D cpu', () => { unsignedPrecisionTexturesWithFloat32Array3D('cpu'); }); (GPU.isKernelMapSupported ? test : skip)('with Float32Array3D gpu', () => { unsignedPrecisionTexturesWithFloat32Array3D('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array3D webgl', () => { unsignedPrecisionTexturesWithFloat32Array3D('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Float32Array3D webgl2', () => { unsignedPrecisionTexturesWithFloat32Array3D('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Float32Array3D headlessgl', () => { unsignedPrecisionTexturesWithFloat32Array3D('headlessgl'); }); function unsignedPrecisionTexturesWithUint16Array3D(mode) { const original = [ [ new Uint16Array([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Uint16Array([10, 11, 12, 13, 14, 15, 16, 18, 19]), ], [ new Uint16Array([20, 21, 22, 23, 24, 25, 26, 27, 28]), new Uint16Array([29, 30, 31, 32, 33, 34, 35, 36, 37]), ] ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.z][this.thread.y][this.thread.x]; }, { output: [9, 2, 2], precision: 'unsigned' }); const result = kernel(original); assert.deepEqual(result.map(matrix => matrix.map(array => Array.from(array))), original.map(matrix => matrix.map(array => Array.from(array)))); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('with Uint16Array3D auto', () => { unsignedPrecisionTexturesWithUint16Array3D(); }); test('with Uint16Array3D cpu', () => { unsignedPrecisionTexturesWithUint16Array3D('cpu'); }); (GPU.isKernelMapSupported ? test : skip)('with Uint16Array3D gpu', () => { unsignedPrecisionTexturesWithUint16Array3D('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array3D webgl', () => { unsignedPrecisionTexturesWithUint16Array3D('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Uint16Array3D webgl2', () => { unsignedPrecisionTexturesWithUint16Array3D('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint16Array3D headlessgl', () => { unsignedPrecisionTexturesWithUint16Array3D('headlessgl'); }); function unsignedPrecisionTexturesWithUint8Array3D(mode) { const original = [ [ new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Uint8Array([10, 11, 12, 13, 14, 15, 16, 18, 19]), ], [ new Uint8Array([20, 21, 22, 23, 24, 25, 26, 27, 28]), new Uint8Array([29, 30, 31, 32, 33, 34, 35, 36, 37]), ] ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.z][this.thread.y][this.thread.x]; }, { output: [9, 2, 2], precision: 'unsigned' }); const result = kernel(original); assert.deepEqual(result.map(matrix => matrix.map(array => Array.from(array))), original.map(matrix => matrix.map(array => Array.from(array)))); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('with Uint8Array3D auto', () => { unsignedPrecisionTexturesWithUint8Array3D(); }); test('with Uint8Array3D cpu', () => { unsignedPrecisionTexturesWithUint8Array3D('cpu'); }); (GPU.isKernelMapSupported ? test : skip)('with Uint8Array3D gpu', () => { unsignedPrecisionTexturesWithUint8Array3D('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array3D webgl', () => { unsignedPrecisionTexturesWithUint8Array3D('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Uint8Array3D webgl2', () => { unsignedPrecisionTexturesWithUint8Array3D('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8Array3D headlessgl', () => { unsignedPrecisionTexturesWithUint8Array3D('headlessgl'); }); function unsignedPrecisionTexturesWithUint8ClampedArray3D(mode) { const original = [ [ new Uint8ClampedArray([1, 2, 3, 4, 5, 6, 7, 8, 9]), new Uint8ClampedArray([10, 11, 12, 13, 14, 15, 16, 18, 19]), ], [ new Uint8ClampedArray([20, 21, 22, 23, 24, 25, 26, 27, 28]), new Uint8ClampedArray([29, 30, 31, 32, 33, 34, 35, 36, 37]), ] ]; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(packed) { return packed[this.thread.z][this.thread.y][this.thread.x]; }, { output: [9, 2, 2], precision: 'unsigned' }); const result = kernel(original); assert.deepEqual(result.map(matrix => matrix.map(array => Array.from(array))), original.map(matrix => matrix.map(array => Array.from(array)))); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray3D auto', () => { unsignedPrecisionTexturesWithUint8ClampedArray3D(); }); test('with Uint8ClampedArray3D cpu', () => { unsignedPrecisionTexturesWithUint8ClampedArray3D('cpu'); }); (GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray3D gpu', () => { unsignedPrecisionTexturesWithUint8ClampedArray3D('gpu'); }); (GPU.isWebGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray3D webgl', () => { unsignedPrecisionTexturesWithUint8ClampedArray3D('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('with Uint8ClampedArray3D webgl2', () => { unsignedPrecisionTexturesWithUint8ClampedArray3D('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('with Uint8ClampedArray3D headlessgl', () => { unsignedPrecisionTexturesWithUint8ClampedArray3D('headlessgl'); }); function testImmutableDoesNotCollideWithKernelTexture(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return v[this.thread.x] + 1; }, { output: [1], precision: 'unsigned', pipeline: true, immutable: true, }); const v = [1]; const result1 = kernel(v); assert.deepEqual(result1.toArray(), new Float32Array([2])); // kernel is getting ready to recompile, because a new type of input const result2 = kernel(result1); assert.deepEqual(result2.toArray(), new Float32Array([3])); // now the kernel textures match, this would fail, and this is that this test is testing const result3 = kernel(result2); assert.deepEqual(result3.toArray(), new Float32Array([4])); gpu.destroy(); } test('immutable does not collide with kernel texture auto', () => { testImmutableDoesNotCollideWithKernelTexture(); }); test('immutable does not collide with kernel texture gpu', () => { testImmutableDoesNotCollideWithKernelTexture('gpu'); }); (GPU.isWebGLSupported ? test : skip)('immutable does not collide with kernel texture webgl', () => { testImmutableDoesNotCollideWithKernelTexture('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('immutable does not collide with kernel texture webgl2', () => { testImmutableDoesNotCollideWithKernelTexture('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('immutable does not collide with kernel texture headlessgl', () => { testImmutableDoesNotCollideWithKernelTexture('headlessgl'); }); ================================================ FILE: test/features/video.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('video'); function videoArgumentTest(mode, done) { const video = document.createElement('video'); video.src = 'jellyfish.webm'; setTimeout(() => { const gpu = new GPU({mode}); const videoKernel = gpu.createKernel(function (a) { const pixel = a[this.thread.y][this.thread.x]; return pixel.g * 255; }, { output: [200], precision: 'unsigned', argumentTypes: ['HTMLVideo'], }); const pixelResult = videoKernel(video)[0]; // CPU captures a bit different of a color assert.ok(pixelResult <= 127 && pixelResult >= 121); assert.equal(true, true, 'does not throw'); gpu.destroy(); done(); }, 1000); } (typeof HTMLVideoElement !== 'undefined' ? test : skip)('video argument auto', t => { videoArgumentTest(null, t.async()); }); (typeof HTMLVideoElement !== 'undefined' ? test : skip)('video argument gpu', t => { videoArgumentTest('gpu', t.async()); }); (GPU.isWebGLSupported && typeof HTMLVideoElement !== 'undefined' ? test : skip)('video argument webgl', t => { videoArgumentTest('webgl', t.async()); }); (GPU.isWebGL2Supported && typeof HTMLVideoElement !== 'undefined' ? test : skip)('video argument webgl2', t => { videoArgumentTest('webgl2', t.async()); }); (typeof HTMLVideoElement !== 'undefined' ? test : skip)('video argument cpu', t => { videoArgumentTest('cpu', t.async()); }); ================================================ FILE: test/index.js ================================================ const { expect } = require('chai'); const GPU = require('../src/index.js'); describe('Test Node GPU', () => { describe('gpu mode', () => { it('should find and use gpu runner', () => { const gpu = new GPU({ mode: 'gpu' }); const kernel = gpu.createKernel(function() { return 1; }).setOutput([1]); const result = kernel(); expect(gpu.runner.constructor).to.equal(GPU.HeadlessGLRunner); expect(result[0]).to.equal(1); }); it('supports 2x2 size', () => { const gpu = new GPU({ mode: 'gpu' }); const kernel = gpu.createKernel(function() { return this.thread.x * this.thread.y; }).setOutput([2, 2]); const result = kernel(); expect(gpu.runner.constructor).to.equal(GPU.HeadlessGLRunner); expect(result).to.deep.equal( [ Float32Array.from([0,0]), Float32Array.from([0,1]) ] ); }); }); describe('cpu mode', () => { it('should find and use gpu runner', () => { const gpu = new GPU({ mode: 'cpu' }); const kernel = gpu.createKernel(function() { return 1; }).setOutput([1]); const result = kernel(); expect(gpu.runner.constructor).to.equal(GPU.CPURunner); expect(result[0]).to.equal(1); }); it('supports 2x2 size', () => { const gpu = new GPU({ mode: 'cpu' }); const kernel = gpu.createKernel(function() { return this.thread.x * this.thread.y; }).setOutput([2, 2]); const result = kernel(); expect(gpu.runner.constructor).to.equal(GPU.CPURunner); expect(result).to.deep.equal( [ Float32Array.from([0,0]), Float32Array.from([0,1]) ] ); }); }); }); ================================================ FILE: test/internal/argument-texture-switching.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('internal: argument texture switching'); function testArrayWithoutTypeDefined(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return this.thread.x; }) .setOutput([10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function(value) { return value[this.thread.x]; }) .setOutput([10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Float32Array); assert.deepEqual(kernel(texture), expected); assert.deepEqual(kernel(expected), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array without type defined (GPU only) auto', () => { testArrayWithoutTypeDefined(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array without type defined (GPU only) gpu', () => { testArrayWithoutTypeDefined('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array without type defined (GPU only) webgl', () => { testArrayWithoutTypeDefined('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array without type defined (GPU only) webgl2', () => { testArrayWithoutTypeDefined('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array without type defined (GPU only) headlessgl', () => { testArrayWithoutTypeDefined('headlessgl'); }); function testArrayWithTypeDefined(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return this.thread.x; }) .setOutput([10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function(value) { return value[this.thread.x]; }) .setArgumentTypes({ value: 'Array' }) .setOutput([10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Float32Array); assert.deepEqual(kernel(texture), expected); assert.deepEqual(kernel(expected), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array with type defined (GPU only) auto', () => { testArrayWithTypeDefined(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array with type defined (GPU only) gpu', () => { testArrayWithTypeDefined('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array with type defined (GPU only) webgl', () => { testArrayWithTypeDefined('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array with type defined (GPU only) webgl2', () => { testArrayWithTypeDefined('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array with type defined (GPU only) headlessgl', () => { testArrayWithTypeDefined('headlessgl'); }); function testArray1D2(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [this.thread.x, this.thread.x + 1]; }) .setOutput([10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function(value) { return value[this.thread.x]; }) .setArgumentTypes({ value: 'Array1D(2)' }) .setOutput([10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(texture), expected); assert.deepEqual(kernel(expected), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(2) (GPU only) auto', () => { testArray1D2(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(2) (GPU only) gpu', () => { testArray1D2('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array1D(2) (GPU only) webgl', () => { testArray1D2('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array1D(2) (GPU only) webgl2', () => { testArray1D2('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array1D(2) (GPU only) headlessgl', () => { testArray1D2('headlessgl'); }); function testArray1D3(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [this.thread.x, this.thread.x + 1, this.thread.x + 2]; }) .setOutput([10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function(value) { return value[this.thread.x]; }) .setArgumentTypes({ value: 'Array1D(3)' }) .setOutput([10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(texture), expected); assert.deepEqual(kernel(expected), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(3) (GPU only) auto', () => { testArray1D3(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(3) (GPU only) gpu', () => { testArray1D3('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array1D(3) (GPU only) webgl', () => { testArray1D3('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array1D(3) (GPU only) webgl2', () => { testArray1D3('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array1D(3) (GPU only) headlessgl', () => { testArray1D3('headlessgl'); }); function testArray1D4(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [this.thread.x, this.thread.x + 1, this.thread.x + 2, this.thread.x + 3]; }) .setOutput([10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function(value) { return value[this.thread.x]; }) .setArgumentTypes({ value: 'Array1D(4)' }) .setOutput([10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(texture), expected); assert.deepEqual(kernel(expected), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(4) (GPU only) auto', () => { testArray1D4(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(4) (GPU only) gpu', () => { testArray1D4('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array1D(4) (GPU only) webgl', () => { testArray1D4('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array1D(4) (GPU only) webgl2', () => { testArray1D4('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array1D(4) (GPU only) headlessgl', () => { testArray1D4('headlessgl'); }); function testArray2D2(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [this.thread.x, this.thread.y]; }) .setOutput([10, 10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }) .setArgumentTypes({ value: 'Array2D(2)' }) .setOutput([10, 10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(texture), expected); assert.deepEqual(kernel(expected), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array2D(2) (GPU only) auto', () => { testArray2D2(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array2D(2) (GPU only) gpu', () => { testArray2D2('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array2D(2) (GPU only) webgl', () => { testArray2D2('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array2D(2) (GPU only) webgl2', () => { testArray2D2('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array2D(2) (GPU only) headlessgl', () => { testArray2D2('headlessgl'); }); function testArray2D3(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [this.thread.x, this.thread.y, this.thread.x * this.thread.y]; }) .setOutput([10, 10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }) .setArgumentTypes({ value: 'Array2D(3)' }) .setOutput([10, 10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(texture), expected); assert.deepEqual(kernel(expected), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array2D(3) (GPU only) auto', () => { testArray2D3(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(3) (GPU only) gpu', () => { testArray2D3('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array2D(3) (GPU only) webgl', () => { testArray2D3('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array2D(3) (GPU only) webgl2', () => { testArray2D3('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array2D(3) (GPU only) headlessgl', () => { testArray2D3('headlessgl'); }); function testArray2D4(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [ this.thread.x, this.thread.y, this.thread.x * this.thread.y, this.thread.x / this.thread.y ]; }) .setOutput([10, 10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function(value) { return value[this.thread.y][this.thread.x]; }) .setArgumentTypes({ value: 'Array2D(4)' }) .setOutput([10, 10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(texture), expected); assert.deepEqual(kernel(expected), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array2D(4) (GPU only) auto', () => { testArray2D4(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(4) (GPU only) gpu', () => { testArray2D4('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array2D(4) (GPU only) webgl', () => { testArray2D4('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array2D(4) (GPU only) webgl2', () => { testArray2D4('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array2D(4) (GPU only) headlessgl', () => { testArray2D4('headlessgl'); }); function testArray3D2(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [this.thread.x, this.thread.x * this.thread.y * this.thread.z]; }) .setOutput([10, 10, 10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function(value) { return value[this.thread.z][this.thread.y][this.thread.x]; }) .setArgumentTypes({ value: 'Array3D(2)' }) .setOutput([10, 10, 10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(texture), expected); assert.deepEqual(kernel(expected), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array3D(2) (GPU only) auto', () => { testArray3D2(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array3D(2) (GPU only) gpu', () => { testArray3D2('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array3D(2) (GPU only) webgl', () => { testArray3D2('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array3D(2) (GPU only) webgl2', () => { testArray3D2('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array3D(2) (GPU only) headlessgl', () => { testArray3D2('headlessgl'); }); function testArray3D3(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [this.thread.x, this.thread.y, this.thread.z]; }) .setOutput([10, 10, 10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function(value) { return value[this.thread.z][this.thread.y][this.thread.x]; }) .setArgumentTypes({ value: 'Array3D(3)' }) .setOutput([10, 10, 10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(texture), expected); assert.deepEqual(kernel(expected), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array3D(3) (GPU only) auto', () => { testArray3D3(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array3D(3) (GPU only) gpu', () => { testArray3D3('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array3D(3) (GPU only) webgl', () => { testArray3D3('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array3D(3) (GPU only) webgl2', () => { testArray3D3('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array3D(3) (GPU only) headlessgl', () => { testArray3D3('headlessgl'); }); function testArray3D4(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [ this.thread.x, this.thread.y, this.thread.z, this.thread.x * this.thread.y * this.thread.z ]; }) .setOutput([10, 10, 10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function(value) { return value[this.thread.z][this.thread.y][this.thread.x]; }) .setArgumentTypes({ value: 'Array3D(4)' }) .setOutput([10, 10, 10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(texture), expected); assert.deepEqual(kernel(expected), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array3D(4) (GPU only) auto', () => { testArray3D4(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array3D(4) (GPU only) gpu', () => { testArray3D4('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array3D(4) (GPU only) webgl', () => { testArray3D4('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array3D(4) (GPU only) webgl2', () => { testArray3D4('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array3D(4) (GPU only) headlessgl', () => { testArray3D4('headlessgl'); }); ================================================ FILE: test/internal/backend/cpu-kernel.js ================================================ const sinon = require('sinon'); const { assert, skip, test, module: describe, only } = require('qunit'); const { CPUKernel } = require('../../../src'); describe('internal: CPUKernel'); test('.build() checks if already built, and returns early if true', () => { const mockContext = { built: true, setupConstants: sinon.spy(), }; CPUKernel.prototype.build.apply(mockContext); assert.equal(mockContext.setupConstants.callCount, 0); }); ================================================ FILE: test/internal/backend/function-node/isSafe.js ================================================ const { assert, test, module: describe, only } = require('qunit'); const { FunctionNode } = require(process.cwd() + '/src'); describe('FunctionNode.isSafe()'); test('calls this.getDependencies(ast) and then this.isSafeDependencies()', () => { const mockAst = {}; const dependenciesMock = { dependencies: [] }; let calls = 0; FunctionNode.prototype.isSafe.call({ getDependencies: (ast) => { assert.equal(ast, mockAst); assert.equal(calls++, 0); return dependenciesMock; }, isSafeDependencies: (dependencies) => { assert.equal(calls++, 1); assert.equal(dependencies, dependenciesMock); } }, mockAst); assert.equal(calls, 2); }); ================================================ FILE: test/internal/backend/function-node/isSafeDependencies.js ================================================ const { assert, test, module: describe, only } = require('qunit'); const { FunctionNode } = require(process.cwd() + '/src'); describe('FunctionNode.isSafeDependencies()'); test('calls if dependencies are falsey, returns true', () => { assert.equal(FunctionNode.prototype.isSafeDependencies(null), true); }); test('calls if dependencies have all isSafe that are true, returns true', () => { assert.equal(FunctionNode.prototype.isSafeDependencies([ { isSafe: true }, { isSafe: true }, { isSafe: true } ]), true); }); test('calls if dependencies have any isSafe that are false, returns false', () => { assert.equal(FunctionNode.prototype.isSafeDependencies([ { isSafe: true }, { isSafe: false }, { isSafe: true } ]), false); }); ================================================ FILE: test/internal/backend/gl-kernel.js ================================================ const { assert, test, module: describe, only, skip } = require('qunit'); const sinon = require('sinon'); const { GLKernel, GPU } = require(process.cwd() + '/src'); describe('GLKernel'); test('nativeFunctionArguments() parse simple function', () => { const result = GLKernel.nativeFunctionArguments(`vec2 myFunction(vec2 longName) { return vec2(1, 1); }`); assert.deepEqual(result, { argumentNames: ['longName'], argumentTypes: ['Array(2)'] }); }); test('nativeFunctionArguments() parse simple function with argument that has number', () => { const result = GLKernel.nativeFunctionArguments(`vec2 myFunction(vec2 longName123) { return vec2(1, 1); }`); assert.deepEqual(result, { argumentNames: ['longName123'], argumentTypes: ['Array(2)'] }); }); test('nativeFunctionArguments() parse simple function, multiple arguments', () => { const result = GLKernel.nativeFunctionArguments(`vec2 myFunction(vec3 a,vec3 b,float c) { return vec2(1, 1); }`); assert.deepEqual(result, { argumentNames: ['a', 'b', 'c'], argumentTypes: ['Array(3)', 'Array(3)', 'Number'] }); }); test('nativeFunctionArguments() parse simple function, multiple arguments with comments', () => { const result = GLKernel.nativeFunctionArguments(`vec2 myFunction(vec3 a /* vec4 b */,vec2 c, /* vec4 d */ float e) { return vec2(1, 1); }`); assert.deepEqual(result, { argumentNames: ['a', 'c', 'e'], argumentTypes: ['Array(3)', 'Array(2)', 'Number'] }); }); test('nativeFunctionArguments() parse simple function, multiple arguments on multi line with spaces', () => { const result = GLKernel.nativeFunctionArguments(`vec2 myFunction( vec4 a, vec3 b, float c ) { vec3 delta = a - b; }`); assert.deepEqual(result, { argumentNames: ['a', 'b', 'c'], argumentTypes: ['Array(4)', 'Array(3)', 'Number'] }); }); test('nativeFunctionArguments() parse simple function, multiple arguments on multi line with spaces and multi-line-comments', () => { const result = GLKernel.nativeFunctionArguments(`vec2 myFunction( vec2 a, /* test 1 */ vec3 b, /* test 2 */ float c /* test 3 */ ) { vec3 delta = a - b; }`); assert.deepEqual(result, { argumentNames: ['a', 'b', 'c'], argumentTypes: ['Array(2)', 'Array(3)', 'Number'] }); }); test('nativeFunctionArguments() parse simple function, multiple arguments on multi line with spaces and in-line-comments', () => { const result = GLKernel.nativeFunctionArguments(`vec2 myFunction( vec2 a, // test 1 vec4 b, // test 2 int c // test 3 ) { vec3 delta = a - b; }`); assert.deepEqual(result, { argumentNames: ['a', 'b', 'c'], argumentTypes: ['Array(2)', 'Array(4)', 'Integer'] }); }); test('nativeFunctionArguments() parse simple function that is cut short', () => { const result = GLKernel.nativeFunctionArguments(`vec2 myFunction( vec2 a, vec3 b, float c )`); assert.deepEqual(result, { argumentNames: ['a', 'b', 'c'], argumentTypes: ['Array(2)', 'Array(3)', 'Number'] }); }); test('getVariablePrecisionString() when tactic is set to "speed" returns "lowp"', () => { assert.equal(GLKernel.prototype.getVariablePrecisionString.call({ tactic: 'speed' }), 'lowp'); }); test('getVariablePrecisionString() when tactic is set to "balanced" returns "mediump"', () => { assert.equal(GLKernel.prototype.getVariablePrecisionString.call({ tactic: 'balanced' }), 'mediump'); }); test('getVariablePrecisionString() when tactic is set to "precision" returns "highp"', () => { assert.equal(GLKernel.prototype.getVariablePrecisionString.call({ tactic: 'precision' }), 'highp'); }); test('getVariablePrecisionString() when tactic is not set and texSize is within lowFloatPrecision', () => { const mockInstance = { tactic: null, constructor: { features: { lowFloatPrecision: { rangeMax: Math.log2(3 * 3) }, mediumFloatPrecision: { rangeMax: Math.log2(4 * 4) }, highFloatPrecision: { rangeMax: Math.log2(5 * 5) }, isSpeedTacticSupported: true, } } }; const textureSize = [2, 2]; assert.equal(GLKernel.prototype.getVariablePrecisionString.call(mockInstance, textureSize), 'lowp'); }); test('getVariablePrecisionString() when tactic is not set and texSize is within mediumFloatPrecision', () => { const mockInstance = { tactic: null, constructor: { features: { lowFloatPrecision: { rangeMax: Math.log2(3 * 3) }, mediumFloatPrecision: { rangeMax: Math.log2(4 * 4) }, highFloatPrecision: { rangeMax: Math.log2(5 * 5) }, isSpeedTacticSupported: true, } } }; const textureSize = [4, 4]; assert.equal(GLKernel.prototype.getVariablePrecisionString.call(mockInstance, textureSize), 'mediump'); }); test('getVariablePrecisionString() when tactic is not set and texSize is within highFloatPrecision', () => { const mockInstance = { tactic: null, constructor: { features: { lowFloatPrecision: { rangeMax: Math.log2(3 * 3) }, mediumFloatPrecision: { rangeMax: Math.log2(4 * 4) }, highFloatPrecision: { rangeMax: Math.log2(5 * 5) }, isSpeedTacticSupported: true, } } }; const textureSize = [5, 5]; assert.equal(GLKernel.prototype.getVariablePrecisionString.call(mockInstance, textureSize), 'highp'); }); test('getVariablePrecisionString() when tactic is not set and texSize is outside highFloatPrecision', () => { const mockInstance = { tactic: null, constructor: { features: { lowFloatPrecision: { rangeMax: Math.log2(3 * 3) }, mediumFloatPrecision: { rangeMax: Math.log2(4 * 4) }, highFloatPrecision: { rangeMax: Math.log2(5 * 5) }, isSpeedTacticSupported: true, } } }; const textureSize = [6, 6]; assert.throws(() => GLKernel.prototype.getVariablePrecisionString.call(mockInstance, textureSize)); }); test('getVariablePrecisionString() when tactic is not set and texSize is within lowIntPrecision', () => { const mockInstance = { tactic: null, constructor: { features: { lowIntPrecision: { rangeMax: Math.log2(3 * 3) }, mediumIntPrecision: { rangeMax: Math.log2(4 * 4) }, highIntPrecision: { rangeMax: Math.log2(5 * 5) }, isSpeedTacticSupported: true, } } }; const textureSize = [2, 2]; assert.equal(GLKernel.prototype.getVariablePrecisionString.call(mockInstance, textureSize, null, true), 'lowp'); }); test('getVariablePrecisionString() when tactic is not set and texSize is within mediumIntPrecision', () => { const mockInstance = { tactic: null, constructor: { features: { lowIntPrecision: { rangeMax: Math.log2(3 * 3) }, mediumIntPrecision: { rangeMax: Math.log2(4 * 4) }, highIntPrecision: { rangeMax: Math.log2(5 * 5) }, isSpeedTacticSupported: true, } } }; const textureSize = [4, 4]; assert.equal(GLKernel.prototype.getVariablePrecisionString.call(mockInstance, textureSize, null, true), 'mediump'); }); test('getVariablePrecisionString() when tactic is not set and texSize is within highIntPrecision', () => { const mockInstance = { tactic: null, constructor: { features: { lowIntPrecision: { rangeMax: Math.log2(3 * 3) }, mediumIntPrecision: { rangeMax: Math.log2(4 * 4) }, highIntPrecision: { rangeMax: Math.log2(5 * 5) }, isSpeedTacticSupported: true, } } }; const textureSize = [5, 5]; assert.equal(GLKernel.prototype.getVariablePrecisionString.call(mockInstance, textureSize, null, true), 'highp'); }); test('getVariablePrecisionString() when tactic is not set and texSize is outside highIntPrecision', () => { const mockInstance = { tactic: null, constructor: { features: { lowIntPrecision: { rangeMax: Math.log2(3 * 3) }, mediumIntPrecision: { rangeMax: Math.log2(4 * 4) }, highIntPrecision: { rangeMax: Math.log2(5 * 5) }, isSpeedTacticSupported: true, } } }; const textureSize = [6, 6]; assert.throws(() => GLKernel.prototype.getVariablePrecisionString.call(mockInstance, textureSize, null, true)); }); test('getVariablePrecisionString() when features.isSpeedTacticSupported is false returns "highp"', () => { const mockInstance = { tactic: null, constructor: { features: { isSpeedTacticSupported: false, } } }; const textureSize = [1, 1]; assert.equal(GLKernel.prototype.getVariablePrecisionString.call(mockInstance, textureSize, null, true), 'highp'); }); function testGetFeatures(canvas, context) { const gpu = new GPU({ canvas, context }); const { Kernel } = gpu; Kernel.setupFeatureChecks(); const features = Kernel.getFeatures(); assert.ok(typeof features.isFloatRead === 'boolean'); assert.ok(typeof features.isIntegerDivisionAccurate === 'boolean'); assert.ok(typeof features.isSpeedTacticSupported === 'boolean'); assert.ok(typeof features.isTextureFloat === 'boolean'); assert.ok(typeof features.isDrawBuffers === 'boolean'); assert.ok(typeof features.kernelMap === 'boolean'); assert.ok(typeof features.channelCount === 'number'); assert.ok(typeof features.maxTextureSize === 'number'); assert.ok(typeof features.lowIntPrecision.rangeMax === 'number'); assert.ok(typeof features.mediumIntPrecision.rangeMax === 'number'); assert.ok(typeof features.highIntPrecision.rangeMax === 'number'); assert.ok(typeof features.lowFloatPrecision.rangeMax === 'number'); assert.ok(typeof features.mediumFloatPrecision.rangeMax === 'number'); assert.ok(typeof features.highFloatPrecision.rangeMax === 'number'); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('getFeatures() webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); testGetFeatures(canvas, context); }); (GPU.isWebGL2Supported ? test : skip)('getFeatures() webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); testGetFeatures(canvas, context); }); (GPU.isHeadlessGLSupported ? test : skip)('getFeatures() headlessgl', () => { const canvas = null; const context = require('gl')(1, 1); testGetFeatures(canvas, context); }); test('setOutput() throws when not dynamicOutput and already compiled', () => { assert.throws(() => { GLKernel.prototype.setOutput.call({ program: {}, toKernelOutput: () => {}, dynamicOutput: false }); }, new Error('Resizing a kernel with dynamicOutput: false is not possible')); }); test('setOutput() when not dynamicOutput and not already compiled', () => { const mockInstance = { toKernelOutput: () => [100, 100], dynamicOutput: false, output: null, }; GLKernel.prototype.setOutput.call(mockInstance, [100, 100]); assert.deepEqual(mockInstance.output, [100, 100]); }); test('setOutput() when does not need to trigger recompile', () => { const mockContext = { bindFramebuffer: sinon.spy(), FRAMEBUFFER: 'FRAMEBUFFER', viewport: sinon.spy() }; const mockTexture = { delete: sinon.spy(), }; const mockMappedTexture = { delete: sinon.spy() }; const mock_setupOutputTexture = sinon.spy(); const mock_setupSubOutputTextures = sinon.spy(); const mockInstance = { context: mockContext, program: {}, texSize: [1, 1], framebuffer: { width: 0, height: 0, }, toKernelOutput: GLKernel.prototype.toKernelOutput, dynamicOutput: true, getVariablePrecisionString: () => { return 'lowp'; }, switchKernels: sinon.spy(), updateMaxTexSize: sinon.spy(), maxTexSize: [123, 321], canvas: { width: 0, height: 0, }, texture: mockTexture, mappedTextures: [ mockMappedTexture ], _setupOutputTexture: mock_setupOutputTexture, _setupSubOutputTextures: mock_setupSubOutputTextures, }; GLKernel.prototype.setOutput.call(mockInstance, [100, 100]); assert.equal(mockContext.bindFramebuffer.callCount, 1); assert.equal(mockContext.bindFramebuffer.args[0][0], 'FRAMEBUFFER'); assert.equal(mockContext.bindFramebuffer.args[0][1], mockInstance.framebuffer); assert.equal(mockInstance.updateMaxTexSize.callCount, 1); assert.equal(mockInstance.framebuffer.width, 100); assert.equal(mockInstance.framebuffer.height, 100); assert.equal(mockContext.viewport.callCount, 1); assert.equal(mockContext.viewport.args[0][0], 0); assert.equal(mockContext.viewport.args[0][1], 0); assert.equal(mockContext.viewport.args[0][2], 123); assert.equal(mockContext.viewport.args[0][3], 321); assert.equal(mockInstance.canvas.width, 123); assert.equal(mockInstance.canvas.height, 321); assert.equal(mockInstance.texture, null); assert.equal(mockInstance.mappedTextures, null); assert.ok(mockTexture.delete.called); assert.ok(mockMappedTexture.delete.called); assert.ok(mock_setupOutputTexture.called); assert.ok(mock_setupSubOutputTextures.called); }); test('setOutput() when needs to trigger recompile', () => { const mockInstance = { program: {}, texSize: [1, 1], toKernelOutput: GLKernel.prototype.toKernelOutput, dynamicOutput: true, getVariablePrecisionString: (textureSize) => { if (textureSize[0] === 1) return 'lowp'; return 'highp'; }, switchKernels: sinon.spy() }; GLKernel.prototype.setOutput.call(mockInstance, [100, 100]); assert.ok(mockInstance.switchKernels.callCount, 1); }); ================================================ FILE: test/internal/backend/headless-gl/kernel/index.js ================================================ const { assert, test, module: describe, only, skip } = require('qunit'); describe('internal: HeadlessGLKernel'); (typeof global !== 'undefined' ? test : skip)('.setupFeatureChecks() should not blow up, even if global WebGLRenderingContext is available', () => { global.WebGLRenderingContext = {}; global.document = { createElement: () => { return {}; } }; // this is done late on purpose! Do not change this, as it causes HeadlessGL to initialize with certain values const { HeadlessGLKernel } = require('../../../../../src'); HeadlessGLKernel.setupFeatureChecks(); assert.ok(true); delete global.document; delete global.WebGLRenderingContext; }); ================================================ FILE: test/internal/backend/web-gl/function-node/astBinaryExpression.js ================================================ const { assert, test, module: describe, only } = require('qunit'); const { WebGLFunctionNode } = require(process.cwd() + '/src'); describe('WebGLFunctionNode.astBinaryExpression()'); test('divide float & float', () => { const node = new WebGLFunctionNode(`function kernel(left, right) { return left / right; }`, { returnType: 'Number', output: [1], argumentTypes: ['Number', 'Number'] }); assert.equal(node.toString(), 'float kernel(float user_left, float user_right) {' + '\nreturn (user_left/user_right);' + '\n}'); }); test('divide float & int', () => { const node = new WebGLFunctionNode(`function kernel(left, right) { return left / right; }`, { returnType: 'Number', output: [1], argumentTypes: ['Number', 'Integer'] }); assert.equal(node.toString(), 'float kernel(float user_left, int user_right) {' + '\nreturn (user_left/float(user_right));' + '\n}'); }); test('divide float & literal float', () => { const node = new WebGLFunctionNode(`function kernel(left) { return left / 1.1; }`, { returnType: 'Number', output: [1], argumentTypes: ['Number'] }); assert.equal(node.toString(), 'float kernel(float user_left) {' + '\nreturn (user_left/1.1);' + '\n}'); }); test('divide float & literal integer', () => { const node = new WebGLFunctionNode(`function kernel(left) { return left / 1; }`, { returnType: 'Number', output: [1], argumentTypes: ['Number'] }); assert.equal(node.toString(), 'float kernel(float user_left) {' + '\nreturn (user_left/1.0);' + '\n}'); }); test('divide float & Input', () => { const node = new WebGLFunctionNode(`function kernel(left, right) { return left / right[this.thread.x]; }`, { returnType: 'Number', output: [1], argumentTypes: ['Number', 'Input'], lookupFunctionArgumentBitRatio: () => 4, }); assert.equal(node.toString(), 'float kernel(float user_left, sampler2D user_right,ivec2 user_rightSize,ivec3 user_rightDim) {' + '\nreturn (user_left/get32(user_right, user_rightSize, user_rightDim, 0, 0, threadId.x));' + '\n}'); }); test('divide int & float', () => { const node = new WebGLFunctionNode(`function kernel(left, right) { return left / right; }`, { returnType: 'Number', output: [1], argumentTypes: ['Integer', 'Number'] }); assert.equal(node.toString(), 'float kernel(int user_left, float user_right) {' + '\nreturn float((user_left/int(user_right)));' + '\n}'); }); test('divide int & int', () => { const node = new WebGLFunctionNode(`function kernel(left, right) { return left / right; }`, { returnType: 'Number', output: [1], argumentTypes: ['Integer', 'Integer'] }); assert.equal(node.toString(), 'float kernel(int user_left, int user_right) {' + '\nreturn float((user_left/user_right));' + '\n}'); }); test('divide int & literal float', () => { const node = new WebGLFunctionNode(`function kernel(left) { return left / 1.1; }`, { returnType: 'Number', output: [1], argumentTypes: ['Integer'] }); assert.equal(node.toString(), 'float kernel(int user_left) {' + '\nreturn float((user_left/1));' + '\n}'); }); test('divide int & literal integer', () => { const node = new WebGLFunctionNode(`function kernel(left) { return left / 1; }`, { returnType: 'Number', output: [1], argumentTypes: ['Integer'] }); assert.equal(node.toString(), 'float kernel(int user_left) {' + '\nreturn float((user_left/1));' + '\n}'); }); test('divide int & Input', () => { const node = new WebGLFunctionNode(`function kernel(left, right) { return left / right[this.thread.x]; }`, { returnType: 'Number', output: [1], argumentTypes: ['Integer', 'Input'], lookupFunctionArgumentBitRatio: () => 4, }); assert.equal(node.toString(), 'float kernel(int user_left, sampler2D user_right,ivec2 user_rightSize,ivec3 user_rightDim) {' + '\nreturn float((user_left/int(get32(user_right, user_rightSize, user_rightDim, 0, 0, threadId.x))));' + '\n}'); }); test('divide literal integer & float', () => { const node = new WebGLFunctionNode(`function kernel(left) { return 1 / left; }`, { returnType: 'Number', output: [1], argumentTypes: ['Number'] }); assert.equal(node.toString(), 'float kernel(float user_left) {' + '\nreturn (1.0/user_left);' + '\n}'); }); test('divide literal integer & int', () => { const node = new WebGLFunctionNode(`function kernel(left) { return 1 / left; }`, { returnType: 'Number', output: [1], argumentTypes: ['Integer'] }); assert.equal(node.toString(), 'float kernel(int user_left) {' + '\nreturn float((1/user_left));' + '\n}'); }); test('divide literal integer & literal float', () => { const node = new WebGLFunctionNode(`function kernel() { return 1 / 1.1; }`, { returnType: 'Number', output: [1], argumentTypes: [] }); assert.equal(node.toString(), 'float kernel() {' + '\nreturn (1.0/1.1);' + '\n}'); }); test('divide literal integer & literal integer', () => { const node = new WebGLFunctionNode(`function kernel() { return 1 / 1; }`, { returnType: 'Number', output: [1], argumentTypes: [] }); assert.equal(node.toString(), 'float kernel() {' + '\nreturn (1.0/1.0);' + '\n}'); }); test('divide literal integer & Input', () => { const node = new WebGLFunctionNode(`function kernel(v) { return 1 / v[this.thread.x]; }`, { returnType: 'Number', output: [1], argumentTypes: ['Input'], lookupFunctionArgumentBitRatio: () => 4, }); assert.equal(node.toString(), 'float kernel(sampler2D user_v,ivec2 user_vSize,ivec3 user_vDim) {' + '\nreturn (1.0/get32(user_v, user_vSize, user_vDim, 0, 0, threadId.x));' + '\n}'); }); test('divide literal float & float', () => { const node = new WebGLFunctionNode(`function kernel(right) { return 1.1 / right; }`, { returnType: 'Number', output: [1], argumentTypes: ['Number'] }); assert.equal(node.toString(), 'float kernel(float user_right) {' + '\nreturn (1.1/user_right);' + '\n}'); }); test('divide literal float & int', () => { const node = new WebGLFunctionNode(`function kernel(right) { return 1.1 / right; }`, { returnType: 'Number', output: [1], argumentTypes: ['Integer'] }); assert.equal(node.toString(), 'float kernel(int user_right) {' + '\nreturn (1.1/float(user_right));' + '\n}'); }); test('divide literal float & literal float', () => { const node = new WebGLFunctionNode(`function kernel() { return 1.1 / 1.1; }`, { returnType: 'Number', output: [1], argumentTypes: [] }); assert.equal(node.toString(), 'float kernel() {' + '\nreturn (1.1/1.1);' + '\n}'); }); test('divide literal float & literal integer', () => { const node = new WebGLFunctionNode(`function kernel() { return 1.1 / 1; }`, { returnType: 'Number', output: [1], argumentTypes: [] }); assert.equal(node.toString(), 'float kernel() {' + '\nreturn (1.1/1.0);' + '\n}'); }); test('divide literal float & Input', () => { const node = new WebGLFunctionNode(`function kernel(v) { return 1.1 / v[this.thread.x]; }`, { returnType: 'Number', output: [1], argumentTypes: ['Input'], lookupFunctionArgumentBitRatio: () => 4, }); assert.equal(node.toString(), 'float kernel(sampler2D user_v,ivec2 user_vSize,ivec3 user_vDim) {' + '\nreturn (1.1/get32(user_v, user_vSize, user_vDim, 0, 0, threadId.x));' + '\n}'); }); test('divide this.thread.x by this.output.x and multiple, integer, integer, and float with this.fixIntegerDivisionAccuracy = false', () => { const node = new WebGLFunctionNode(`function kernel() { return (this.thread.x / this.output.x) * 4; }`, { returnType: 'Number', output: [1], argumentTypes: [], lookupFunctionArgumentBitRatio: () => 4, fixIntegerDivisionAccuracy: false, }); assert.equal(node.toString(), 'float kernel() {' + '\nreturn float(((threadId.x/1)*4));' + '\n}'); }); test('divide this.thread.x by this.output.x and multiple, integer, integer, and float with this.fixIntegerDivisionAccuracy = true', () => { const node = new WebGLFunctionNode(`function kernel() { return (this.thread.x / this.output.x) * 4; }`, { returnType: 'Number', output: [1], argumentTypes: [], lookupFunctionArgumentBitRatio: () => 4, fixIntegerDivisionAccuracy: true, }); assert.equal(node.toString(), 'float kernel() {' + '\nreturn (divWithIntCheck(float(threadId.x), 1.0)*4.0);' + '\n}'); }); test('multiply Input and Input', () => { const node = new WebGLFunctionNode('function kernel(v1, v2) {' + '\n return v1[this.thread.x] * v2[this.thread.x];' + '\n}', { output: [1], argumentTypes: ['Input', 'Input'], lookupFunctionArgumentBitRatio: () => 4, }); assert.equal(node.toString(), 'float kernel(sampler2D user_v1,ivec2 user_v1Size,ivec3 user_v1Dim, sampler2D user_v2,ivec2 user_v2Size,ivec3 user_v2Dim) {' + '\nreturn (get32(user_v1, user_v1Size, user_v1Dim, 0, 0, threadId.x)*get32(user_v2, user_v2Size, user_v2Dim, 0, 0, threadId.x));' + '\n}'); }); test('multiply Input and int', () => { const node = new WebGLFunctionNode('function kernel(v1, v2) {' + '\n return v1[this.thread.x] * v2;' + '\n}', { output: [1], argumentTypes: ['Input', 'Integer'], lookupFunctionArgumentBitRatio: () => 4, }); assert.equal(node.toString(), 'float kernel(sampler2D user_v1,ivec2 user_v1Size,ivec3 user_v1Dim, int user_v2) {' + '\nreturn (get32(user_v1, user_v1Size, user_v1Dim, 0, 0, threadId.x)*float(user_v2));' + '\n}'); }); test('multiply Input and float', () => { const node = new WebGLFunctionNode('function kernel(v1, v2) {' + '\n return v1[this.thread.x] * v2;' + '\n}', { output: [1], argumentTypes: ['Input', 'Float'], lookupFunctionArgumentBitRatio: () => 4, }); assert.equal(node.toString(), 'float kernel(sampler2D user_v1,ivec2 user_v1Size,ivec3 user_v1Dim, float user_v2) {' + '\nreturn (get32(user_v1, user_v1Size, user_v1Dim, 0, 0, threadId.x)*user_v2);' + '\n}'); }); test('multiply Input and Number', () => { const node = new WebGLFunctionNode('function kernel(v1, v2) {' + '\n return v1[this.thread.x] * v2;' + '\n}', { output: [1], argumentTypes: ['Input', 'Number'], lookupFunctionArgumentBitRatio: () => 4, }); assert.equal(node.toString(), 'float kernel(sampler2D user_v1,ivec2 user_v1Size,ivec3 user_v1Dim, float user_v2) {' + '\nreturn (get32(user_v1, user_v1Size, user_v1Dim, 0, 0, threadId.x)*user_v2);' + '\n}'); }); ================================================ FILE: test/internal/backend/web-gl/function-node/astCallExpression.js ================================================ const { assert, test, module: describe, only } = require('qunit'); const { WebGLFunctionNode } = require(process.cwd() + '/src'); describe('WebGLFunctionNode.astCallExpression()'); test('handles Math.abs with floats', () => { const node = new WebGLFunctionNode(`function kernel(v) { return Math.abs(v); }`, { output: [1], argumentTypes: ['Number'] }); assert.equal(node.toString(), 'float kernel(float user_v) {' + '\nreturn abs(user_v);' + '\n}'); }); test('handles Math.abs with ints', () => { const node = new WebGLFunctionNode(`function kernel(v) { return Math.abs(v); }`, { output: [1], argumentTypes: ['Integer'] }); assert.equal(node.toString(), 'float kernel(int user_v) {' + '\nreturn abs(float(user_v));' + '\n}'); }); test('handles Math.pow with floats', () => { const node = new WebGLFunctionNode(`function kernel(v, v2) { return Math.pow(v, v2); }`, { output: [1], argumentTypes: ['Number', 'Number'] }); assert.equal(node.toString(), 'float kernel(float user_v, float user_v2) {' + '\nreturn _pow(user_v, user_v2);' + '\n}'); }); test('handles Math.pow with mixed 1', () => { const node = new WebGLFunctionNode(`function kernel(v, v2) { return Math.pow(v, v2); }`, { output: [1], argumentTypes: ['Number', 'Integer'] }); assert.equal(node.toString(), 'float kernel(float user_v, int user_v2) {' + '\nreturn _pow(user_v, float(user_v2));' + '\n}'); }); test('handles Math.pow with mixed 2', () => { const node = new WebGLFunctionNode(`function kernel(v, v2) { return Math.pow(v, v2); }`, { output: [1], argumentTypes: ['Integer', 'Number'] }); assert.equal(node.toString(), 'float kernel(int user_v, float user_v2) {' + '\nreturn _pow(float(user_v), user_v2);' + '\n}'); }); test('handles Math.pow with ints', () => { const node = new WebGLFunctionNode(`function kernel(v, v2) { return Math.pow(v, v2); }`, { output: [1], argumentTypes: ['Integer', 'Integer'] }); assert.equal(node.toString(), 'float kernel(int user_v, int user_v2) {' + '\nreturn _pow(float(user_v), float(user_v2));' + '\n}'); }); test('handles argument of type Input', () => { let lookupReturnTypeCalls = 0; let lookupFunctionArgumentTypes = 0; const node = new WebGLFunctionNode('function kernel(v) {' + '\n return childFunction(v);' + '\n}', { output: [1], argumentTypes: ['Input'], needsArgumentType: () => false, lookupReturnType: (functionName) => { lookupReturnTypeCalls++; if (functionName === 'childFunction') { return 'Number'; } throw new Error(`unhanded lookupReturnType for ${functionName}`); }, lookupFunctionArgumentTypes: (functionName) => { lookupFunctionArgumentTypes++; if (functionName === 'childFunction') { return ['Input']; } throw new Error(`unhanded lookupFunctionArgumentTypes for ${functionName}`); }, triggerImplyArgumentBitRatio: () => {}, assignArgumentType: () => {} }); assert.equal(node.toString(), 'float kernel(sampler2D user_v,ivec2 user_vSize,ivec3 user_vDim) {' + '\nreturn childFunction(user_v,user_vSize,user_vDim);' + '\n}'); assert.equal(lookupReturnTypeCalls, 2); assert.equal(lookupFunctionArgumentTypes, 1); }); test('handles argument of type HTMLImageArray', () => { let lookupReturnTypeCalls = 0; let lookupFunctionArgumentTypes = 0; const node = new WebGLFunctionNode('function kernel(v) {' + '\n return childFunction(v);' + '\n}', { output: [1], argumentTypes: ['HTMLImageArray'], needsArgumentType: () => false, lookupReturnType: (functionName) => { lookupReturnTypeCalls++; if (functionName === 'childFunction') { return 'Number'; } throw new Error(`unhanded lookupReturnType for ${functionName}`); }, lookupFunctionArgumentTypes: (functionName) => { lookupFunctionArgumentTypes++; if (functionName === 'childFunction') { return ['HTMLImageArray']; } throw new Error(`unhanded lookupFunctionArgumentTypes for ${functionName}`); }, triggerImplyArgumentBitRatio: () => {}, assignArgumentType: () => {} }); assert.equal(node.toString(), 'float kernel(sampler2DArray user_v,ivec2 user_vSize,ivec3 user_vDim) {' + '\nreturn childFunction(user_v,user_vSize,user_vDim);' + '\n}'); assert.equal(lookupReturnTypeCalls, 2); assert.equal(lookupFunctionArgumentTypes, 1); }); test('handles argument types of CallExpression that return arrays', () => { const node = new WebGLFunctionNode(`function kernel() { const p = [this.thread.x, this.thread.y]; const z = array2(array2(p, 0.01), 0.02); return 1.0; }`, { output: [1, 1], lookupReturnType: () => 'Number', needsArgumentType: () => false, lookupFunctionArgumentTypes: () => [], triggerImplyArgumentType: () => {} }); assert.equal(node.toString(), `float kernel() { vec2 user_p=vec2(threadId.x, threadId.y); float user_z=array2(array2(user_p, 0.01), 0.02); return 1.0; }`); }); ================================================ FILE: test/internal/backend/web-gl/function-node/astForStatement.js ================================================ const { assert, test, module: describe, only } = require('qunit'); const { WebGLFunctionNode } = require(process.cwd() + '/src'); describe('WebGLFunctionNode.astForStatement()'); test('with safe loop with init', () => { const node = new WebGLFunctionNode(`function kernel() { let sum = 0; for (let i = 0;i < 100; i++) { sum++; } return sum; }`, { output: [1] }); assert.equal(node.toString(), 'float kernel() {' + '\nint user_sum=0;' + '\nfor (int user_i=0;(user_i<100);user_i++){' + '\nuser_sum++;}' + '\n' + '\nreturn float(user_sum);' + '\n}'); }); test('with safe loop with init and if', () => { const node = new WebGLFunctionNode(`function kernel() { let sum = 0; for (let i = 0;i < 100; i++) { if (i > 50) { sum++; } } return sum; }`, { output: [1] }); assert.equal(node.toString(), 'float kernel() {' + '\nint user_sum=0;' + '\nfor (int user_i=0;(user_i<100);user_i++){' + '\nif ((user_i>50)){' + '\nuser_sum++;}' + '\n}' + '\n' + '\nreturn float(user_sum);' + '\n}'); }); test('with safe loop with no init', () => { const node = new WebGLFunctionNode(`function kernel() { let sum = 0; const i = 0; for (;i < 100; i++) { sum++; } return sum; }`, { output: [1] }); assert.equal(node.toString(), 'float kernel() {' + '\nint user_sum=0;' + '\nint user_i=0;' + '\nfor (int safeI=0;safeI { const node = new WebGLFunctionNode(`function kernel() { let sum = 0; for (let i = 0;; i++) { if (i > 100) break; sum++; } return sum; }`, { output: [1] }); assert.equal(node.toString(), 'float kernel() {' + '\nint user_sum=0;' + '\nint user_i=0;' + '\nfor (int safeI=0;safeI100)) {' + '\nbreak;' + '\n}' + '\nuser_sum++;' + '\nuser_i++;}' + '\n' + '\nreturn float(user_sum);' + '\n}'); }); test('with unsafe loop with init', () => { const node = new WebGLFunctionNode(`function kernel(arg1) { let sum = 0; for (let i = 0 + arg1;i < 100; i++) { sum++; } return sum; }`, { output: [1], argumentTypes: ['Number'] }); assert.equal(node.toString(), 'float kernel(float user_arg1) {' + '\nint user_sum=0;' + '\nfloat user_i=(0.0+user_arg1);' + '\nfor (int safeI=0;safeI { const node = new WebGLFunctionNode(`function kernel(arg1) { let sum = 0; let i = 0 + arg1; for (;i < 100; i++) { sum++; } return sum; }`, { output: [1], argumentTypes: ['Number'] }); assert.equal(node.toString(), 'float kernel(float user_arg1) {' + '\nint user_sum=0;' + '\nfloat user_i=(0.0+user_arg1);' + '\nfor (int safeI=0;safeI { const node = new WebGLFunctionNode(`function kernel(arg1) { let sum = 0; let i = 0 + arg1; for (;100 > i; i++) { sum++; } return sum; }`, { output: [1], argumentTypes: ['Number'] }); assert.equal(node.toString(), 'float kernel(float user_arg1) {' + '\nint user_sum=0;' + '\nfloat user_i=(0.0+user_arg1);' + '\nfor (int safeI=0;safeIuser_i)) break;' + '\nuser_sum++;' + '\nuser_i++;}' + '\n' + '\nreturn float(user_sum);' + '\n}'); }); test('nested safe loop', () => { const node = new WebGLFunctionNode(`function kernel() { let sum = 0; for (let i = 0; i < 100; i++) { for (let j = 0; j < 100; j++) { sum++; } } return sum; }`, { output: [1] }); assert.equal(node.toString(), 'float kernel() {' + '\nint user_sum=0;' + '\nfor (int user_i=0;(user_i<100);user_i++){' + '\nfor (int user_j=0;(user_j<100);user_j++){' + '\nuser_sum++;}' + '\n}' + '\n' + '\nreturn float(user_sum);' + '\n}'); }); test('nested unsafe loop', () => { const node = new WebGLFunctionNode(`function kernel(arg1, arg2) { let sum = 0; for (let i = arg1; i < 100; i++) { for (let j = arg2; j < 100; j++) { sum++; } } return sum; }`, { argumentTypes: ['Number', 'Number'], output: [1] }); assert.equal(node.toString(), 'float kernel(float user_arg1, float user_arg2) {' + '\nint user_sum=0;' + '\nfloat user_i=user_arg1;' + '\nfor (int safeI2=0;safeI2 { const node = new WebGLFunctionNode(`function kernel() { let sum = 0; for (let i = 0; i < this.output.x; i++) { sum += 1; } return sum; }`, { argumentTypes: [], output: [1] }); assert.equal(node.toString(), 'float kernel() {' + '\nfloat user_sum=0.0;' + '\nfor (int user_i=0;(user_i<1);user_i++){' + '\nuser_sum+=1.0;}' + '\n' + '\nreturn user_sum;' + '\n}'); }); test('this.thread.x usage inside loop', () => { const node = new WebGLFunctionNode(`function kernel() { let sum = 0; for (let i = 0; i < this.thread.x; i++) { sum += 1; } return sum; }`, { argumentTypes: [], output: [1] }); assert.equal(node.toString(), 'float kernel() {' + '\nfloat user_sum=0.0;' + '\nfor (int user_i=0;(user_i { const node = new WebGLFunctionNode(`function kernel() { let sum = 0; let x = this.thread.x; for (let i = 0; i < x; i++) { sum += 1; } return sum; }`, { argumentTypes: [], output: [1] }); assert.equal(node.toString(), 'float kernel() {' + '\nfloat user_sum=0.0;' + '\nfloat user_x=float(threadId.x);' + '\nfor (int user_i=0;(user_i { assert.equal(run('const value = it', { argumentNames: ['it'], argumentTypes: ['Number'] }), 'float user_value=user_it;'); }); test('value int', () => { assert.equal(run('const value = it', { argumentNames: ['it'], argumentTypes: ['Integer'] }), 'float user_value=float(user_it);'); }); test('value[] float', () => { assert.equal(run('const value = it[1]', { argumentNames: ['it'], argumentTypes: ['Array'], lookupFunctionArgumentBitRatio: () => 4, }), 'float user_value=get32(user_it, user_itSize, user_itDim, 0, 0, 1);'); }); test('value[][] float', () => { assert.equal(run('const value = it[1][2]', { argumentNames: ['it'], argumentTypes: ['Array2D'], lookupFunctionArgumentBitRatio: () => 4, }), 'float user_value=get32(user_it, user_itSize, user_itDim, 0, 1, 2);'); }); test('value[][][] float', () => { assert.equal(run('const value = it[1][2][3]', { argumentNames: ['it'], argumentTypes: ['Array3D'], lookupFunctionArgumentBitRatio: () => 4, }), 'float user_value=get32(user_it, user_itSize, user_itDim, 1, 2, 3);'); }); test('Array2 value[] from value[]', () => { assert.equal(run('const value = [arg1[0], arg2[0]];', { argumentNames: ['arg1', 'arg2'], argumentTypes: ['Array', 'Array'], lookupFunctionArgumentBitRatio: () => 4, }), 'vec2 user_value=vec2(' + 'get32(user_arg1, user_arg1Size, user_arg1Dim, 0, 0, 0), ' + 'get32(user_arg2, user_arg2Size, user_arg2Dim, 0, 0, 0)' + ');'); }); test('Array3 value[] from value[]', () => { assert.equal(run('const value = [arg1[0], arg2[0], arg3[0]];', { argumentNames: ['arg1', 'arg2', 'arg3'], argumentTypes: ['Array', 'Array', 'Array'], lookupFunctionArgumentBitRatio: () => 4, }), 'vec3 user_value=vec3(' + 'get32(user_arg1, user_arg1Size, user_arg1Dim, 0, 0, 0), ' + 'get32(user_arg2, user_arg2Size, user_arg2Dim, 0, 0, 0), ' + 'get32(user_arg3, user_arg3Size, user_arg3Dim, 0, 0, 0)' + ');'); }); test('Array4 value[] from value[]', () => { assert.equal(run('const value = [arg1[0], arg2[0], arg3[0], arg4[0]];', { argumentNames: ['arg1', 'arg2', 'arg3', 'arg4'], argumentTypes: ['Array', 'Array', 'Array', 'Array'], lookupFunctionArgumentBitRatio: () => 4, }), 'vec4 user_value=vec4(' + 'get32(user_arg1, user_arg1Size, user_arg1Dim, 0, 0, 0), ' + 'get32(user_arg2, user_arg2Size, user_arg2Dim, 0, 0, 0), ' + 'get32(user_arg3, user_arg3Size, user_arg3Dim, 0, 0, 0), ' + 'get32(user_arg4, user_arg4Size, user_arg4Dim, 0, 0, 0)' + ');'); }); test('float, Array2, Array3 chain values', () => { assert.equal(run('const value1 = 1, ' + 'value2 = [arg1[0], arg2[0]], ' + 'value3 = [arg1[0], arg2[0], arg3[0]], ' + 'value4 = [arg1[0], arg2[0], arg3[0], arg4[0]];', { argumentNames: ['arg1', 'arg2', 'arg3', 'arg4'], argumentTypes: ['Array', 'Array', 'Array', 'Array'], lookupFunctionArgumentBitRatio: () => 4, }), 'float user_value1=1.0;' + 'vec2 user_value2=vec2(' + 'get32(user_arg1, user_arg1Size, user_arg1Dim, 0, 0, 0), ' + 'get32(user_arg2, user_arg2Size, user_arg2Dim, 0, 0, 0)' + ');' + 'vec3 user_value3=vec3(' + 'get32(user_arg1, user_arg1Size, user_arg1Dim, 0, 0, 0), ' + 'get32(user_arg2, user_arg2Size, user_arg2Dim, 0, 0, 0), ' + 'get32(user_arg3, user_arg3Size, user_arg3Dim, 0, 0, 0)' + ');' + 'vec4 user_value4=vec4(' + 'get32(user_arg1, user_arg1Size, user_arg1Dim, 0, 0, 0), ' + 'get32(user_arg2, user_arg2Size, user_arg2Dim, 0, 0, 0), ' + 'get32(user_arg3, user_arg3Size, user_arg3Dim, 0, 0, 0), ' + 'get32(user_arg4, user_arg4Size, user_arg4Dim, 0, 0, 0)' + ');'); }); test('float, Array2, Array3, Array4 multiple values', () => { assert.equal(run('const value1 = 1, ' + 'value2 = [arg1[0], arg2[0]], ' + 'value3 = [arg1[0], arg2[0], arg3[0]], ' + 'value4 = [arg1[0], arg2[0], arg3[0], arg4[0]];', { argumentNames: ['arg1', 'arg2', 'arg3', 'arg4'], argumentTypes: ['Array', 'Array', 'Array', 'Array'], lookupFunctionArgumentBitRatio: () => 4, }), 'float user_value1=1.0;' + 'vec2 user_value2=vec2(' + 'get32(user_arg1, user_arg1Size, user_arg1Dim, 0, 0, 0), ' + 'get32(user_arg2, user_arg2Size, user_arg2Dim, 0, 0, 0)' + ');' + 'vec3 user_value3=vec3(' + 'get32(user_arg1, user_arg1Size, user_arg1Dim, 0, 0, 0), ' + 'get32(user_arg2, user_arg2Size, user_arg2Dim, 0, 0, 0), ' + 'get32(user_arg3, user_arg3Size, user_arg3Dim, 0, 0, 0)' + ');' + 'vec4 user_value4=vec4(' + 'get32(user_arg1, user_arg1Size, user_arg1Dim, 0, 0, 0), ' + 'get32(user_arg2, user_arg2Size, user_arg2Dim, 0, 0, 0), ' + 'get32(user_arg3, user_arg3Size, user_arg3Dim, 0, 0, 0), ' + 'get32(user_arg4, user_arg4Size, user_arg4Dim, 0, 0, 0)' + ');'); }); test('float, float, Array4, Array4, Array4 chain values', () => { assert.equal(run('const value1 = 1, value2 = 1.5, ' + 'value3 = [arg1[0], arg2[0], arg3[0], arg4[0]], ' + 'value4 = [arg4[4], arg3[4], arg2[4], arg1[4]], ' + 'value5 = [arg2[1], arg2[2], arg2[3], arg2[4]];', { argumentNames: ['arg1', 'arg2', 'arg3', 'arg4'], argumentTypes: ['Array', 'Array', 'Array', 'Array'], lookupFunctionArgumentBitRatio: () => 4, }), 'float user_value1=1.0,user_value2=1.5;' + 'vec4 user_value3=vec4(' + 'get32(user_arg1, user_arg1Size, user_arg1Dim, 0, 0, 0), ' + 'get32(user_arg2, user_arg2Size, user_arg2Dim, 0, 0, 0), ' + 'get32(user_arg3, user_arg3Size, user_arg3Dim, 0, 0, 0), ' + 'get32(user_arg4, user_arg4Size, user_arg4Dim, 0, 0, 0)' + '),' + 'user_value4=vec4(' + 'get32(user_arg4, user_arg4Size, user_arg4Dim, 0, 0, 4), ' + 'get32(user_arg3, user_arg3Size, user_arg3Dim, 0, 0, 4), ' + 'get32(user_arg2, user_arg2Size, user_arg2Dim, 0, 0, 4), ' + 'get32(user_arg1, user_arg1Size, user_arg1Dim, 0, 0, 4)' + '),' + 'user_value5=vec4(' + 'get32(user_arg2, user_arg2Size, user_arg2Dim, 0, 0, 1), ' + 'get32(user_arg2, user_arg2Size, user_arg2Dim, 0, 0, 2), ' + 'get32(user_arg2, user_arg2Size, user_arg2Dim, 0, 0, 3), ' + 'get32(user_arg2, user_arg2Size, user_arg2Dim, 0, 0, 4)' + ');'); }); test('float literal, float literal, multiple values', () => { assert.equal(run('const value1 = 0, ' + 'value2 = 0;', { argumentNames: [], argumentTypes: [] }), 'float user_value1=0.0,user_value2=0.0;'); }); test('float literal, float literal, multiple values', () => { assert.equal(run('const value1 = 0, ' + 'value2 = 0;', { argumentNames: [], argumentTypes: [] }), 'float user_value1=0.0,user_value2=0.0;'); }); test('this.constant.value throws', () => { assert.throws(() => { run('const value=this.constant.it'); }); }); test('this.constants.value without constantTypes declared', () => { assert.throws(() => { run('const value=this.constants.it') }); }); test('this.constants.value float', () => { assert.equal(run('const value = this.constants.it', { constantTypes: { it: 'Number' } }), 'float user_value=constants_it;'); }); test('this.constants.value int', () => { assert.equal(run('const value = this.constants.it', { constantTypes: { it: 'Integer' } }), 'float user_value=float(constants_it);'); }); test('this.constants.value[] float', () => { assert.equal(run('const value = this.constants.it[1]', { constantTypes: { it: 'Array' }, constantBitRatios: { it: 4 }, }), 'float user_value=get32(constants_it, constants_itSize, constants_itDim, 0, 0, 1);'); }); test('this.constants.value[][] float', () => { assert.equal(run('const value = this.constants.it[1][2]', { constantTypes: { it: 'Array2D' }, constantBitRatios: { it: 4 }, }), 'float user_value=get32(constants_it, constants_itSize, constants_itDim, 0, 1, 2);'); }); test('this.constants.value[][][] float', () => { assert.equal(run('const value = this.constants.it[1][2][3]', { constantTypes: { it: 'Array3D' }, constantBitRatios: { it: 4 }, }), 'float user_value=get32(constants_it, constants_itSize, constants_itDim, 1, 2, 3);'); }); test('this.thread.x float', () => { assert.equal(run('const value = this.thread.x'), 'float user_value=float(threadId.x);'); }); test('this.thread.y float', () => { assert.equal(run('const value = this.thread.y'), 'float user_value=float(threadId.y);'); }); test('this.thread.z float', () => { assert.equal(run('const value = this.thread.z'), 'float user_value=float(threadId.z);'); }); test('this.output.x float', () => { assert.equal(run('const value = this.output.x'), 'float user_value=1.0;'); }); test('this.output.y float', () => { assert.equal(run('const value = this.output.y'), 'float user_value=2.0;'); }); test('this.output.z float', () => { assert.equal(run('const value = this.output.z'), 'float user_value=3.0;'); }); test('this.outputs.z throws', () => { assert.throws(() => { run('const value = this.outputs.z'); }); }); test('Math.E Number float', () => { assert.equal(run('const value = Math.E'), `float user_value=${Math.E.toString()};`); }); test('Math.E Number float', () => { assert.equal(run('const value = Math.E'), `float user_value=${Math.E.toString()};`); }); ================================================ FILE: test/internal/backend/web-gl/function-node/contexts.js ================================================ const { assert, test, module: describe, only } = require('qunit'); const { WebGLFunctionNode } = require(process.cwd() + '/src'); describe('WebGLFunctionNode.contexts'); test('safe from literal 1', () => { const node = new WebGLFunctionNode(`function kernel() { const const1 = 1; const const2 = const1 + 2; const const3 = const2 + 3; let sum = 0; for (let i = 0; i < const3; i++) { sum += const3; } }`, { output: [1] }); node.toString(); const { const1, const2, const3 } = node.contexts[1]; assert.equal(const1.isSafe, true); assert.deepEqual(const1.dependencies, [ { origin: 'literal', value: 1, isSafe: true, } ]); assert.equal(const2.isSafe, true); assert.deepEqual(const2.dependencies, [ { name: 'const1', origin: 'declaration', isSafe: true },{ origin: 'literal', value: 2, isSafe: true, } ]); assert.equal(const3.isSafe, true); assert.deepEqual(const3.dependencies, [ { name: 'const2', origin: 'declaration', isSafe: true },{ origin: 'literal', value: 3, isSafe: true, } ]); }); test('safe from argument', () => { const node = new WebGLFunctionNode(`function kernel(arg1) { const const1 = arg1 + 3; const const2 = const1 + 2; const const3 = const2 + 1; let sum = 0; for (let i = 0; i < const3; i++) { sum += const3; } }`, { output: [1], argumentTypes: ['Number'] }); node.toString(); const { const1, const2, const3 } = node.contexts[1]; assert.equal(const1.isSafe, false); assert.deepEqual(const1.dependencies, [ { name: 'arg1', origin: 'argument', isSafe: false },{ origin: 'literal', value: 3, isSafe: true, } ]); assert.equal(const2.isSafe, false); assert.deepEqual(const2.dependencies, [ { name: 'const1', origin: 'declaration', isSafe: false },{ origin: 'literal', value: 2, isSafe: true, } ]); assert.equal(const3.isSafe, false); assert.deepEqual(const3.dependencies, [ { name: 'const2', origin: 'declaration', isSafe: false },{ origin: 'literal', value: 1, isSafe: true, } ]); }); test('safe from multiplication', () => { const node = new WebGLFunctionNode(`function kernel() { const const1 = 555; const const2 = const1 + .555; const const3 = const2 * .1; let sum = 0; for (let i = 0; i < const3; i++) { sum += const3; } }`, { output: [1] }); node.toString(); const { const1, const2, const3 } = node.contexts[1]; assert.deepEqual(const1.dependencies, [ { origin: 'literal', value: 555, isSafe: true, } ]); assert.deepEqual(const2.dependencies, [ { name: 'const1', origin: 'declaration', isSafe: true, },{ origin: 'literal', value: .555, isSafe: true, } ]); assert.deepEqual(const3.dependencies, [ { name: 'const2', origin: 'declaration', isSafe: false, },{ origin: 'literal', value: .1, isSafe: false, } ]); }); test('safe from multiplication deep', () => { const node = new WebGLFunctionNode(`function kernel() { const const1 = 555 * 1; const const2 = const1 + .555; const const3 = .1 - const2; const const4 = const3 - .1; const const5 = .1 - const4; const const6 = const5 - .1; const const7 = .1 - const6; const const8 = const7 - .1; const const9 = .1 - const8; const const10 = const9 + 10; let sum = 0; for (let i = 0; i < const3; i++) { sum += const3; } }`, { output: [1] }); node.toString(); const { const1, const10 } = node.contexts[1]; assert.ok(const1.dependencies.every(dependency => dependency.isSafe === false)); assert.deepEqual(const10.dependencies, [ { name: 'const9', origin: 'declaration', isSafe: false, },{ origin: 'literal', value: 10, isSafe: true, } ]); }); test('safe from division', () => { const node = new WebGLFunctionNode(`function kernel() { const const1 = 555; const const2 = const1 + .555; const const3 = const2 / .1; let sum = 0; for (let i = 0; i < const3; i++) { sum += const3; } }`, { output: [1] }); node.toString(); const { const1, const2, const3 } = node.contexts[1]; assert.deepEqual(const1.dependencies, [ { origin: 'literal', value: 555, isSafe: true, } ]); assert.deepEqual(const2.dependencies, [ { name: 'const1', origin: 'declaration', isSafe: true, },{ origin: 'literal', value: .555, isSafe: true, } ]); assert.deepEqual(const3.dependencies, [ { name: 'const2', origin: 'declaration', isSafe: false, },{ origin: 'literal', value: .1, isSafe: false, } ]); }); test('safe from division deep', () => { const node = new WebGLFunctionNode(`function kernel() { const const1 = 555 / 1; const const2 = const1 + .555; const const3 = .1 - const2; const const4 = .1 - const3; const const5 = const4 - .1; const const6 = const5 - .1; const const7 = .1 - const6; const const8 = const7 - .1; const const9 = .1 - const8; const const10 = const9 + 10; let sum = 0; for (let i = 0; i < const3; i++) { sum += const3; } }`, { output: [1] }); node.toString(); const { const1, const10 } = node.contexts[1]; assert.ok(const1.dependencies.every(dependency => dependency.isSafe === false)); assert.deepEqual(const10.dependencies, [ { name: 'const9', origin: 'declaration', isSafe: false, },{ origin: 'literal', value: 10, isSafe: true, } ]); }); ================================================ FILE: test/internal/backend/web-gl/function-node/firstAvailableTypeFromAst.js ================================================ const { assert, test, module: describe, only } = require('qunit'); const { WebGLFunctionNode } = require(process.cwd() + '/src'); describe('WebGLFunctionNode.getType()'); function run(value, settings) { const node = new WebGLFunctionNode(`function fn(value, value2, value3) { ${ value }; }`, Object.assign({ output: [1] }, settings)); const ast = node.getJsAST(); node.traceFunctionAST(ast); assert.equal(ast.type, 'FunctionExpression'); assert.equal(ast.body.type, 'BlockStatement'); assert.equal(ast.body.body[0].type, 'ExpressionStatement'); return node.getType(ast.body.body[0].expression); } test('literal 0', () => { assert.equal(run('0'), 'LiteralInteger'); }); test('literal 0.1', () => { assert.equal(run('0.1'), 'Number'); }); test('unknown value from arguments', () => { assert.throws(() => { run('value'); }); }); test('value Number from arguments', () => { assert.equal(run('value', { argumentNames: ['value'], argumentTypes: ['Fake Type'] }), 'Fake Type'); }); test('value[] Number from arguments', () => { assert.equal(run('value[0]', { argumentNames: ['value'], argumentTypes: ['Array'] }), 'Number'); }); test('value[][] Number from arguments', () => { assert.equal(run('value[0][0]', { argumentNames: ['value'], argumentTypes: ['Array'] }), 'Number'); }); test('value[][][] Number from arguments', () => { assert.equal(run('value[0][0][0]', { argumentNames: ['value'], argumentTypes: ['Array'] }), 'Number'); }); test('this.constants.value Integer', () => { assert.equal(run('this.constants.value', { constants: { value: 1 }, constantTypes: { value: 'Integer' } }), 'Integer'); }); test('this.constants.value[] Number', () => { assert.equal(run('this.constants.value[0]', { constants: { value: [1] }, constantTypes: { value: 'Array' } }), 'Number'); }); test('this.constants.value[][] Number', () => { assert.equal(run('this.constants.value[0][0]', { constants: { value: [[1]] }, constantTypes: { value: 'Array' } }), 'Number'); }); test('this.constants.value[][][] Number', () => { assert.equal(run('this.constants.value[0][0][0]', { constants: { value: [[[1]]] }, constantTypes: { value: 'Array' } }), 'Number'); }); test('this.thread.x', () => { assert.equal(run('this.thread.x'), 'Integer'); }); test('this.thread.y', () => { assert.equal(run('this.thread.y'), 'Integer'); }); test('this.thread.z', () => { assert.equal(run('this.thread.z'), 'Integer'); }); test('this.output.x', () => { assert.equal(run('this.output.x'), 'LiteralInteger'); }); test('this.output.y', () => { assert.equal(run('this.output.y'), 'LiteralInteger'); }); test('this.output.y', () => { assert.equal(run('this.output.y'), 'LiteralInteger'); }); test('bogus this.outputs.y', () => { assert.throws(() => { run('this.outputs.y'); }); }); test('bogus this.threads.y', () => { assert.throws(() => { run('this.threads.y'); }); }); test('unknown function call', () => { assert.throws(() => { assert.equal(run('value()'), null); }); }); test('function call', () => { assert.equal(run('value()', { lookupReturnType: (name, ast, node) => name === 'value' ? 'Fake Type' : null, }), 'Fake Type'); }); test('simple unknown expression', () => { assert.throws(() => { run('value + value2'); }); }); test('simple expression', () => { assert.equal(run('value + otherValue', { argumentNames: ['value'], argumentTypes: ['Number'] }), 'Number'); }); test('simple right expression', () => { assert.equal(run('value + value2', { argumentNames: ['value', 'value2'], argumentTypes: ['Number', 'Number'] }), 'Number'); }); test('function call expression', () => { assert.equal(run('otherFunction() + value', { lookupReturnType: (name, ast, node) => name === 'otherFunction' ? 'Fake Type' : null, }), 'Fake Type'); }); test('Math.E', () => { assert.equal(run('Math.E'), 'Number'); }); test('Math.PI', () => { assert.equal(run('Math.PI'), 'Number'); }); test('Math.SQRT2', () => { assert.equal(run('Math.SQRT2'), 'Number'); }); test('Math.SQRT1_2', () => { assert.equal(run('Math.SQRT1_2'), 'Number'); }); test('Math.LN2', () => { assert.equal(run('Math.LN2'), 'Number'); }); test('Math.LN10', () => { assert.equal(run('Math.LN10'), 'Number'); }); test('Math.LOG2E', () => { assert.equal(run('Math.LOG2E'), 'Number'); }); test('Math.LOG10E', () => { assert.equal(run('Math.LOG10E'), 'Number'); }); test('Math.abs(value)', () => { assert.equal(run('Math.abs(value)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.acos(value)', () => { assert.equal(run('Math.acos(value)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.atan(value)', () => { assert.equal(run('Math.atan(value)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.atan2(value, value2)', () => { assert.equal(run('Math.atan2(value, value2)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.ceil(value)', () => { assert.equal(run('Math.ceil(value)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.cos(value)', () => { assert.equal(run('Math.cos(value)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.exp(value)', () => { assert.equal(run('Math.exp(value)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.floor(value)', () => { assert.equal(run('Math.floor(value)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.log(value)', () => { assert.equal(run('Math.log(value)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.max(value, value2, value3)', () => { assert.equal(run('Math.max(value, value2, value3)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.min(value, value2, value3)', () => { assert.equal(run('Math.min(value, value2, value3)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.pow(value, value2)', () => { assert.equal(run('Math.pow(value, value2)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.random()', () => { assert.equal(run('Math.random()', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.round(value)', () => { assert.equal(run('Math.random(value)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.sin(value)', () => { assert.equal(run('Math.sin(value)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.sqrt(value)', () => { assert.equal(run('Math.sqrt(value)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.tan(value)', () => { assert.equal(run('Math.tan(value)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); test('Math.tanh(value)', () => { assert.equal(run('Math.tanh(value)', { argumentTypes: ['Number', 'Number', 'Number'] }), 'Number'); }); ================================================ FILE: test/internal/backend/web-gl/function-node/getVariableSignature.js ================================================ const { assert, test, module: describe, only } = require('qunit'); const { WebGLFunctionNode } = require(process.cwd() + '/src'); describe('WebGLFunctionNode.getVariableSignature()'); function run(value) { const mockInstance = { source: `function() { ${value}; }`, traceFunctionAST: () => {} }; const ast = WebGLFunctionNode.prototype.getJsAST.call(mockInstance); const expression = ast.body.body[0].expression; return WebGLFunctionNode.prototype.getVariableSignature.call({ isAstVariable: WebGLFunctionNode.prototype.isAstVariable }, expression); } test('value', () => { assert.equal(run('value'), 'value'); }); test('value[number]', () => { assert.equal(run('value[0]'), 'value[]'); }); test('value[variable]', () => { assert.equal(run('value[a]'), 'value[]'); }); test('value[variable] with conflicting names x', () => { assert.equal(run('value[x]'), 'value[]'); }); test('value[variable] with conflicting names y', () => { assert.equal(run('value[y]'), 'value[]'); }); test('value[variable] with conflicting names z', () => { assert.equal(run('value[z]'), 'value[]'); }); test('value[this.thread.x]', () => { assert.equal(run('value[this.thread.x]'), 'value[]'); }); test('value[this.thread.x][variable]', () => { assert.equal(run('value[this.thread.x][a]'), 'value[][]'); }); test('value[variable] with conflicting names constants', () => { assert.equal(run('value[constants]'), 'value[]'); }); test('value[variable] with conflicting names constants', () => { assert.equal(run('value[output]'), 'value[]'); }); test('value[variable] with conflicting names thread', () => { assert.equal(run('value[thread]'), 'value[]'); }); test('value[number][number]', () => { assert.equal(run('value[0][0]'), 'value[][]'); }); test('value[variable][variable]', () => { assert.equal(run('value[a][b]'), 'value[][]'); }); test('value[number][number][number]', () => { assert.equal(run('value[0][0][0]'), 'value[][][]'); }); test('value[variable][variable][variable]', () => { assert.equal(run('value[a][b][c]'), 'value[][][]'); }); test('this.thread.value', () => { assert.equal(run('this.thread.x'), 'this.thread.value'); assert.equal(run('this.thread.y'), 'this.thread.value'); assert.equal(run('this.thread.z'), 'this.thread.value'); }); test('this.output.value', () => { assert.equal(run('this.output.x'), 'this.output.value'); assert.equal(run('this.output.y'), 'this.output.value'); assert.equal(run('this.output.z'), 'this.output.value'); }); test('this.constants.value', () => { assert.equal(run('this.constants.value'), 'this.constants.value'); }); test('this.constants.value[]', () => { assert.equal(run('this.constants.value[0]'), 'this.constants.value[]'); }); test('this.constants.value[][]', () => { assert.equal(run('this.constants.value[0][0]'), 'this.constants.value[][]'); }); test('this.constants.value[][][]', () => { assert.equal(run('this.constants.value[0][0][0]'), 'this.constants.value[][][]'); }); test('this.constants.texture[this.thread.z][this.thread.y][this.thread.x]', () => { assert.equal(run('this.constants.texture[this.thread.z][this.thread.y][this.thread.x]'), 'this.constants.value[][][]'); }); test('this.whatever.value', () => { assert.equal(run('this.whatever.value'), null); }); test('this.constants.value[][][][]', () => { assert.equal(run('this.constants.value[0][0][0][0]'), 'this.constants.value[][][][]'); }); test('this.constants.value.something', () => { assert.equal(run('this.constants.value.something'), null); }); test('this.constants.value[].something', () => { assert.equal(run('this.constants.value[0].something'), null); }); test('this.constants.value[][].something', () => { assert.equal(run('this.constants.value[0][0].something'), null); }); test('this.constants.value[][][][]', () => { assert.equal(run('this.constants.value[0][0][0].something'), null); }); test('complex nested this.constants.value[][][]', () => { assert.equal(run(` this.constants.value[ this.constants.value[i + 1] ] [ Math.random() * 1 + this.thread.x ] [ this.thread.x - 100 ] `), 'this.constants.value[][][]'); }); test('complex nested with function call this.constants.value[][][]', () => { assert.equal(run(` this.constants.value[ something() ] [ Math.random() * 1 + this.thread.x ] [ this.thread.x - 100 ] `), 'this.constants.value[][][]') }); test('non-existent something', () => { assert.equal(run('this.constants.value[0][0].something'), null); }); test('non-existent constants', () => { assert.equal(run('this.constants.value[0][0].constants'), null); }); test('function call', () => { assert.throws(() => { run('Math.random()'); }); }); test('binary expression add', () => { assert.throws(() => { run('value[0] + value[0]'); }); }); test('binary expression divide', () => { assert.throws(() => { run('value[0] / value[0]'); }); }); ================================================ FILE: test/internal/backend/web-gl/function-node/getVariableType.js ================================================ const { assert, test, module: describe, only } = require('qunit'); const { WebGLFunctionNode, GLKernel } = require(process.cwd() + '/src'); describe('WebGLFunctionNode.getVariableType()'); test('Native function > detects same native argument type float, and no cast', () => { const nativeFunction = `float nativeFunction(float value) { return value + 1.0; }`; const returnType = GLKernel.nativeFunctionReturnType(nativeFunction); const { argumentTypes } = GLKernel.nativeFunctionArguments(nativeFunction); const node = new WebGLFunctionNode(`function kernel(value) { return nativeFunction(value); }`, { output: [1], argumentTypes: ['Number'], lookupReturnType: (name, ast, node) => { if (name === 'nativeFunction') return returnType; throw new Error('unknown function'); }, lookupFunctionArgumentTypes: (functionName) => { if (functionName === 'nativeFunction') return argumentTypes; throw new Error('unknown function'); }, needsArgumentType: () => false }); assert.equal(node.toString(), 'float kernel(float user_value) {' + '\nreturn nativeFunction(user_value);' + '\n}'); }); test('Native function > detects same native argument type int, and no cast', () => { const nativeFunction = `float nativeFunction(int value) { return float(value + 1); }`; const returnType = GLKernel.nativeFunctionReturnType(nativeFunction); const { argumentTypes } = GLKernel.nativeFunctionArguments(nativeFunction); const node = new WebGLFunctionNode(`function kernel(value) { return nativeFunction(value); }`, { output: [1], argumentTypes: ['Integer'], lookupReturnType: (name, ast, node) => { if (name === 'nativeFunction') return returnType; throw new Error('unknown function'); }, lookupFunctionArgumentTypes: (functionName) => { if (functionName === 'nativeFunction') return argumentTypes; throw new Error('unknown function'); }, needsArgumentType: () => false }); assert.equal(node.toString(), 'float kernel(int user_value) {' + '\nreturn nativeFunction(user_value);' + '\n}'); }); test('Native function > detects different native argument type int from literal, and cast to it from float', () => { const nativeFunction = `float nativeFunction(int value) { return float(value + 1); }`; const returnType = GLKernel.nativeFunctionReturnType(nativeFunction); const { argumentTypes } = GLKernel.nativeFunctionArguments(nativeFunction); const node = new WebGLFunctionNode(`function kernel(value) { return nativeFunction(1.5); }`, { output: [1], argumentTypes: ['Number'], lookupReturnType: (name, ast, node) => { if (name === 'nativeFunction') return returnType; throw new Error('unknown function'); }, lookupFunctionArgumentTypes: (functionName) => { if (functionName === 'nativeFunction') return argumentTypes; throw new Error('unknown function'); }, needsArgumentType: () => false }); assert.equal(node.toString(), 'float kernel(float user_value) {' + '\nreturn nativeFunction(int(1.5));' + '\n}'); }); test('Native function > detects different native argument type float from literal, and cast to it from int', () => { const nativeFunction = `float nativeFunction(int value) { return float(value + 1); }`; const returnType = GLKernel.nativeFunctionReturnType(nativeFunction); const { argumentTypes } = GLKernel.nativeFunctionArguments(nativeFunction); const node = new WebGLFunctionNode(`function kernel(value) { return nativeFunction(1); }`, { output: [1], argumentTypes: ['Number'], lookupReturnType: (name, ast, node) => { if (name === 'nativeFunction') return returnType; throw new Error('unknown function'); }, lookupFunctionArgumentTypes: (functionName) => { if (functionName === 'nativeFunction') return argumentTypes; throw new Error('unknown function'); }, needsArgumentType: () => false }); assert.equal(node.toString(), 'float kernel(float user_value) {' + '\nreturn nativeFunction(1);' + '\n}'); }); test('Native function > detects different native argument type int, and cast to it from float', () => { const nativeFunction = `float nativeFunction(int value) { return float(value + 1); }`; const returnType = GLKernel.nativeFunctionReturnType(nativeFunction); const { argumentTypes } = GLKernel.nativeFunctionArguments(nativeFunction); const node = new WebGLFunctionNode(`function kernel(value) { return nativeFunction(value); }`, { output: [1], argumentTypes: ['Number'], lookupReturnType: (name, ast, node) => { if (name === 'nativeFunction') return returnType; throw new Error('unknown function'); }, lookupFunctionArgumentTypes: (functionName) => { if (functionName === 'nativeFunction') return argumentTypes; throw new Error('unknown function'); }, needsArgumentType: () => false }); assert.equal(node.toString(), 'float kernel(float user_value) {' + '\nreturn nativeFunction(int(user_value));' + '\n}'); }); test('Native function > detects different native argument type float, and cast to it from int', () => { const nativeFunction = `float nativeFunction(float value) { return value + 1.0; }`; const returnType = GLKernel.nativeFunctionReturnType(nativeFunction); const { argumentTypes } = GLKernel.nativeFunctionArguments(nativeFunction); const node = new WebGLFunctionNode(`function kernel(value) { return nativeFunction(value); }`, { output: [1], argumentTypes: ['Integer'], lookupReturnType: (name, ast, node) => { if (name === 'nativeFunction') return returnType; throw new Error('unknown function'); }, lookupFunctionArgumentTypes: (functionName) => { if (functionName === 'nativeFunction') return argumentTypes; throw new Error('unknown function'); }, needsArgumentType: () => false }); assert.equal(node.toString(), 'float kernel(int user_value) {' + '\nreturn nativeFunction(float(user_value));' + '\n}'); }); ================================================ FILE: test/internal/backend/web-gl/kernel/index.js ================================================ const sinon = require('sinon'); const { assert, skip, test, module: describe, only } = require('qunit'); const { WebGLKernel } = require('../../../../../src'); describe('internal: WebGLKernel'); (typeof global !== 'undefined' ? test : skip)('.setupFeatureChecks() if context is available, but .getExtension() is falsey', () => { const mockContext = { getExtension: null // this is important }; const mockElement = { getContext: () => mockContext, }; const mockDocument = { createElement: () => { return mockElement; } }; global.document = mockDocument; WebGLKernel.setupFeatureChecks(); assert.ok(true); delete global.document; }); test('.validateSettings() checks output texture size - too large', () => { const mockContext = { constructor: { features: { maxTextureSize: 1, }, }, checkOutput: () => {}, output: [2], validate: true, checkTextureSize: WebGLKernel.prototype.checkTextureSize, }; assert.throws(() => { WebGLKernel.prototype.validateSettings.apply(mockContext, []); }, new Error('Texture size [1,2] generated by kernel is larger than supported size [1,1]')); }); test('.validateSettings() checks output texture size - ok', () => { const mockContext = { constructor: { features: { maxTextureSize: 1, }, }, checkOutput: () => {}, output: [1], validate: true, checkTextureSize: WebGLKernel.prototype.checkTextureSize, }; WebGLKernel.prototype.validateSettings.apply(mockContext, []); assert.ok(true); }); test('.build() checks if already built, and returns early if true', () => { const mockContext = { built: true, initExtensions: sinon.spy(), }; WebGLKernel.prototype.build.apply(mockContext); assert.equal(mockContext.initExtensions.callCount, 0); }); ================================================ FILE: test/internal/backend/web-gl/kernel/setupArguments.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { WebGLKernel, input } = require('../../../../../src'); describe('internal WebGLKernel.setupArguments Array'); const gl = { TEXTURE0: 0, TEXTURE_2D: 'TEXTURE_2D', RGBA: 'RGBA', UNSIGNED_BYTE: 'UNSIGNED_BYTE', FLOAT: 'FLOAT', TEXTURE_WRAP_S: 'TEXTURE_WRAP_S', CLAMP_TO_EDGE: 'CLAMP_TO_EDGE', TEXTURE_WRAP_T: 'TEXTURE_WRAP_T', TEXTURE_MIN_FILTER: 'TEXTURE_MIN_FILTER', TEXTURE_MAG_FILTER: 'TEXTURE_MAG_FILTER', NEAREST: 'NEAREST', UNPACK_FLIP_Y_WEBGL: 'UNPACK_FLIP_Y_WEBGL', }; function setupArgumentsTestSuite(testSuiteSettings) { const { gpuSettings, argument, expectedPixels, expectedBitRatio, expectedDim, expectedSize, expectedType, expectedArgumentTextureCount, expectedPixelStorei, } = testSuiteSettings; let texImage2DCalled = false; let activeTextureCalled = false; let bindTextureCalled = false; let texParameteriCalls = 0; let getUniformLocationCalls = 0; let uniform3ivCalled = false; let uniform2ivCalled = false; let uniform1iCalled = false; const mockContext = Object.assign({ activeTexture: (index) => { assert.equal(index, 0); activeTextureCalled = true; }, bindTexture: (target, texture) => { assert.equal(target, 'TEXTURE_2D'); assert.equal(texture, 'TEXTURE'); bindTextureCalled = true; }, texParameteri: (target, pname, param) => { switch (texParameteriCalls) { case 0: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_WRAP_S'); assert.equal(param, 'CLAMP_TO_EDGE'); texParameteriCalls++; break; case 1: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_WRAP_T'); assert.equal(param, 'CLAMP_TO_EDGE'); texParameteriCalls++; break; case 2: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_MIN_FILTER'); assert.equal(param, 'NEAREST'); texParameteriCalls++; break; case 3: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_MAG_FILTER'); assert.equal(param, 'NEAREST'); texParameteriCalls++; break; default: throw new Error('called too many times'); } }, pixelStorei: (pname, param) => { assert.equal(pname, 'UNPACK_FLIP_Y_WEBGL'); assert.equal(param, expectedPixelStorei); }, createTexture: () => 'TEXTURE', getUniformLocation: (program, name) => { assert.equal(program, 'program'); if (getUniformLocationCalls > 3) { throw new Error('called too many times'); } getUniformLocationCalls++; return { user_vDim: 'user_vDimLocation', user_vSize: 'user_vSizeLocation', user_v: 'user_vLocation', }[name]; }, uniform3iv: (location, value) => { assert.equal(location, 'user_vDimLocation'); assert.deepEqual(value, expectedDim); uniform3ivCalled = true; }, uniform2iv: (location, value) => { assert.equal(location, 'user_vSizeLocation'); assert.deepEqual(value, expectedSize); uniform2ivCalled = true; }, uniform1i: (location, value) => { assert.equal(location, 'user_vLocation'); assert.equal(value, 0); uniform1iCalled = true; }, texImage2D: (target, level, internalFormat, width, height, border, format, type, pixels) => { assert.equal(target, gl.TEXTURE_2D); assert.equal(level, 0); assert.equal(internalFormat, gl.RGBA); assert.equal(width, expectedSize[0]); assert.equal(height, expectedSize[1]); assert.equal(border, 0); assert.equal(format, gl.RGBA); assert.equal(type, expectedType); assert.equal(pixels.length, expectedPixels.length); assert.deepEqual(pixels, expectedPixels); texImage2DCalled = true; } }, gl); const source = `function(v) { return v[this.thread.x]; }`; const settings = { context: mockContext, }; const kernel = new WebGLKernel(source, Object.assign({}, settings, gpuSettings)); kernel.constructor = { lookupKernelValueType: WebGLKernel.lookupKernelValueType, features: { maxTextureSize: 9999 } }; const args = [argument]; kernel.program = 'program'; assert.equal(kernel.argumentTextureCount, 0); kernel.setupArguments(args); assert.equal(kernel.argumentBitRatios[0], expectedBitRatio); assert.equal(kernel.kernelArguments.length, 1); kernel.kernelArguments[0].updateValue(argument); assert.equal(kernel.argumentTextureCount, expectedArgumentTextureCount); assert.ok(texImage2DCalled); assert.ok(activeTextureCalled); assert.ok(bindTextureCalled); assert.equal(texParameteriCalls, 4); assert.equal(getUniformLocationCalls, 1); assert.notOk(uniform3ivCalled); assert.notOk(uniform2ivCalled); assert.ok(uniform1iCalled); } // NOTE: Take special note of how the `argument` and `expectedPixels` are formatted // requires at least 5 entire pixels test('Array with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, argument: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ], expectedBitRatio: 4, expectedPixels: new Uint8Array(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, argument: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 * 1 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, argument: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([2,2]), // 2 * 2 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: new Uint8Array([ 1, 2, 3, 4, 5 ]), expectedBitRatio: 1, expectedPixels: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), // 1 * 2 * 4 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Array with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ], expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ]), // upconverted from 1 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Array with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ], expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0, ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33, ]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33,0, 0,0, 0,0, 0,0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([4,5]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33 ]), expectedBitRatio: 1, expectedPixels: new Uint8Array( new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33,0,0,0 ]).buffer), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Array with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ], expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), // upconverted from 1 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); describe('internal WebGLKernel.setupArguments Input'); // requires at least 5 entire pixels test('Input(Array) with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, argument: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5, 0 ], [2,3]), expectedBitRatio: 4, expectedPixels: new Uint8Array(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, argument: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ]), [5]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 * 1 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, argument: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5, 0, ]), [2,3]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([2,2]), // 2 * 2 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: input(new Uint8Array([ 1, 2, 3, 4, 5,0 ]),[2, 3]), expectedBitRatio: 1, expectedPixels: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), // 1 * 2 * 4 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Array) with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ], [2,3]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ]),[2,3]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ]), [2,3]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: input(new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ]), [2,3]), // upconverted from 1 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Array) with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ], [33]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ]), [33]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0, ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33, ]), [33]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33,0, 0,0, 0,0, 0,0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([4,5]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: input(new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33 ]), [33]), expectedBitRatio: 1, expectedPixels: new Uint8Array( new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33,0,0,0 ]).buffer), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Array) with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ], [33]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), [33]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), [33]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: input(new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA (8 bit, but upconverted to float32), so only 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), [33]), // upconverted to float32 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA (8 bit, but upconverted to float32), so only 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); ================================================ FILE: test/internal/backend/web-gl/kernel/setupConstants.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { WebGLKernel, input } = require('../../../../../src'); describe('internal WebGLKernel.setupConstants Array'); const gl = { TEXTURE0: 0, TEXTURE_2D: 'TEXTURE_2D', RGBA: 'RGBA', UNSIGNED_BYTE: 'UNSIGNED_BYTE', FLOAT: 'FLOAT', TEXTURE_WRAP_S: 'TEXTURE_WRAP_S', CLAMP_TO_EDGE: 'CLAMP_TO_EDGE', TEXTURE_WRAP_T: 'TEXTURE_WRAP_T', TEXTURE_MIN_FILTER: 'TEXTURE_MIN_FILTER', TEXTURE_MAG_FILTER: 'TEXTURE_MAG_FILTER', NEAREST: 'NEAREST', UNPACK_FLIP_Y_WEBGL: 'UNPACK_FLIP_Y_WEBGL', }; function setupConstantsTestSuite(testSuiteSettings) { const { gpuSettings, constant, expectedPixels, expectedBitRatio, expectedDim, expectedSize, expectedType, expectedConstantTextureCount, expectedPixelStorei, } = testSuiteSettings; let texImage2DCalled = false; let activeTextureCalled = false; let bindTextureCalled = false; let texParameteriCalls = 0; let getUniformLocationCalls = 0; let uniform3ivCalled = false; let uniform2ivCalled = false; let uniform1iCalled = false; const mockContext = Object.assign({ activeTexture: (index) => { assert.equal(index, 0); activeTextureCalled = true; }, bindTexture: (target, texture) => { assert.equal(target, 'TEXTURE_2D'); assert.equal(texture, 'TEXTURE'); bindTextureCalled = true; }, texParameteri: (target, pname, param) => { switch (texParameteriCalls) { case 0: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_WRAP_S'); assert.equal(param, 'CLAMP_TO_EDGE'); texParameteriCalls++; break; case 1: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_WRAP_T'); assert.equal(param, 'CLAMP_TO_EDGE'); texParameteriCalls++; break; case 2: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_MIN_FILTER'); assert.equal(param, 'NEAREST'); texParameteriCalls++; break; case 3: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_MAG_FILTER'); assert.equal(param, 'NEAREST'); texParameteriCalls++; break; default: throw new Error('called too many times'); } }, pixelStorei: (pname, param) => { assert.equal(pname, 'UNPACK_FLIP_Y_WEBGL'); assert.equal(param, expectedPixelStorei); }, createTexture: () => 'TEXTURE', getUniformLocation: (program, name) => { assert.equal(program, 'program'); if (getUniformLocationCalls > 3) { throw new Error('called too many times'); } getUniformLocationCalls++; return { constants_vDim: 'constants_vDimLocation', constants_vSize: 'constants_vSizeLocation', constants_v: 'constants_vLocation', }[name]; }, uniform3iv: (location, value) => { assert.equal(location, 'constants_vDimLocation'); assert.deepEqual(value, expectedDim); uniform3ivCalled = true; }, uniform2iv: (location, value) => { assert.equal(location, 'constants_vSizeLocation'); assert.deepEqual(value, expectedSize); uniform2ivCalled = true; }, uniform1i: (location, value) => { assert.equal(location, 'constants_vLocation'); assert.equal(value, 0); uniform1iCalled = true; }, texImage2D: (target, level, internalFormat, width, height, border, format, type, pixels) => { assert.equal(target, gl.TEXTURE_2D); assert.equal(level, 0); assert.equal(internalFormat, gl.RGBA); assert.equal(width, expectedSize[0]); assert.equal(height, expectedSize[1]); assert.equal(border, 0); assert.equal(format, gl.RGBA); assert.equal(type, expectedType); assert.equal(pixels.length, expectedPixels.length); assert.deepEqual(pixels, expectedPixels); texImage2DCalled = true; } }, gl); const source = `function(v) { return this.constants.v[this.thread.x]; }`; const settings = { context: mockContext, }; const kernel = new WebGLKernel(source, Object.assign({ constants: { v: constant } }, settings, gpuSettings)); kernel.constructor = { lookupKernelValueType: WebGLKernel.lookupKernelValueType, features: { maxTextureSize: 9999 } }; kernel.program = 'program'; assert.equal(kernel.constantTextureCount, 0); kernel.setupConstants(); assert.equal(kernel.constantBitRatios.v, expectedBitRatio); assert.equal(kernel.kernelConstants.length, 1); kernel.kernelConstants[0].updateValue(constant); assert.equal(kernel.constantTextureCount, expectedConstantTextureCount); assert.ok(texImage2DCalled); assert.ok(activeTextureCalled); assert.ok(bindTextureCalled); assert.equal(texParameteriCalls, 4); assert.equal(getUniformLocationCalls, 1); assert.notOk(uniform3ivCalled); assert.notOk(uniform2ivCalled); assert.ok(uniform1iCalled); } // NOTE: Take special note of how the `constant` and `expectedPixels` are formatted // requires at least 5 entire pixels test('Array with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, constant: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ], expectedBitRatio: 4, expectedPixels: new Uint8Array(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, constant: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 * 1 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, constant: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([2,2]), // 2 * 2 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: new Uint8Array([ 1, 2, 3, 4, 5 ]), expectedBitRatio: 1, expectedPixels: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), // 1 * 2 * 4 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Array with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ], expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ]), // upconverted from 1 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Array with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ], expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0, ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33, ]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33,0, 0,0, 0,0, 0,0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([4,5]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33 ]), expectedBitRatio: 1, expectedPixels: new Uint8Array( new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33,0,0,0 ]).buffer), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Array with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ], expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), // upconverted from 1 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); describe('internal WebGL2Kernel.setupConstants Input'); // requires at least 5 entire pixels test('Input(Array) with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, constant: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5, 0 ], [2,3]), expectedBitRatio: 4, expectedPixels: new Uint8Array(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, constant: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ]), [5]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 * 1 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, constant: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5, 0, ]), [2,3]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([2,2]), // 2 * 2 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: input(new Uint8Array([ 1, 2, 3, 4, 5,0 ]),[2, 3]), expectedBitRatio: 1, expectedPixels: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), // 1 * 2 * 4 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Array) with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ], [2,3]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ]),[2,3]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ]), [2,3]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: input(new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ]), [2,3]), // upconverted from 1 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Array) with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ], [33]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ]), [33]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0, ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33, ]), [33]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33,0, 0,0, 0,0, 0,0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([4,5]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: input(new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33 ]), [33]), expectedBitRatio: 1, expectedPixels: new Uint8Array( new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33,0,0,0 ]).buffer), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Array) with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ], [33]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), [33]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), [33]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: input(new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA (8 bit, but upconverted to float32), so only 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), [33]), // upconverted to float32 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA (8 bit, but upconverted to float32), so only 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/dynamic-html-image.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueDynamicHTMLImage'); test('.updateValue() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const v = new webGLKernelValueMaps.unsigned.dynamic.HTMLImage({ width: 1, height: 1 }, { kernel: mockKernel, name: 'test', type: 'HTMLImage', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue({ width: 1, height: 2 }); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.updateValue() checks too large width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const v = new webGLKernelValueMaps.unsigned.dynamic.HTMLImage({ width: 1, height: 1 }, { kernel: mockKernel, name: 'test', type: 'HTMLImage', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue({ height: 1, width: 2, }) }, new Error('Argument texture width of 2 larger than maximum size of 1 for your GPU')); }); test('.updateValue() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 2 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.unsigned.dynamic.HTMLImage({ width: 2, height: 2 }, { kernel: mockKernel, name: 'test', type: 'HTMLImage', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); v.updateValue({ height: 1, width: 1, }); assert.equal(v.constructor.name, 'WebGLKernelValueDynamicHTMLImage'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/dynamic-memory-optimized-number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueDynamicMemoryOptimizedNumberTexture'); test('.updateValue() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const v = new webGLKernelValueMaps.unsigned.dynamic.MemoryOptimizedNumberTexture({ size: [1, 1] }, { kernel: mockKernel, name: 'test', type: 'MemoryOptimizedNumberTexture', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue({ size: [1, 2] }); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.updateValue() checks too large width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const v = new webGLKernelValueMaps.unsigned.dynamic.MemoryOptimizedNumberTexture({ size: [1, 1] }, { kernel: mockKernel, name: 'test', type: 'MemoryOptimizedNumberTexture', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue({ size: [2,1] }) }, new Error('Argument texture width of 2 larger than maximum size of 1 for your GPU')); }); test('.updateValue() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 2 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.unsigned.dynamic.MemoryOptimizedNumberTexture({ size: [2,2], context: mockContext }, { kernel: mockKernel, name: 'test', type: 'MemoryOptimizedNumberTexture', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); v.updateValue({ size: [1,1], context: mockContext, texture: {} }); assert.equal(v.constructor.name, 'WebGLKernelValueDynamicMemoryOptimizedNumberTexture'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/dynamic-number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueDynamicNumberTexture'); test('.updateValue() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const v = new webGLKernelValueMaps.unsigned.dynamic.NumberTexture({ size: [1, 1] }, { kernel: mockKernel, name: 'test', type: 'NumberTexture', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue({ size: [1, 2] }); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.updateValue() checks too large width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const v = new webGLKernelValueMaps.unsigned.dynamic.NumberTexture({ size: [1, 1] }, { kernel: mockKernel, name: 'test', type: 'NumberTexture', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue({ size: [2,1] }) }, new Error('Argument texture width of 2 larger than maximum size of 1 for your GPU')); }); test('.updateValue() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 2 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.unsigned.dynamic.NumberTexture({ size: [2,2], context: mockContext }, { kernel: mockKernel, name: 'test', type: 'NumberTexture', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); v.updateValue({ size: [1,1], context: mockContext, texture: {} }); assert.equal(v.constructor.name, 'WebGLKernelValueDynamicNumberTexture'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/dynamic-single-array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueDynamicSingleArray'); test('.updateValue() checks too large', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const v = new webGLKernelValueMaps.single.dynamic.Array([1,2], { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue(new Array([1,2,3,4,5,6,7,8])); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.updateValue() checks ok', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.single.dynamic.Array([1,2], { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); v.updateValue(new Array([2,1])); assert.equal(v.constructor.name, 'WebGLKernelValueDynamicSingleArray'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/dynamic-single-array1d-i.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueDynamicSingleArray1DI'); test('.updateValue() checks too large', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const v = new webGLKernelValueMaps.single.dynamic["Array1D(2)"]([[1,2]], { kernel: mockKernel, name: 'test', type: 'Array1D(2)', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue([[1,2],[3,4],[5,6],[7,8]]); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.updateValue() checks ok', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.single.dynamic["Array1D(2)"]([[1,2]], { kernel: mockKernel, name: 'test', type: 'Array1D(2)', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); v.updateValue(new Array(new Array([2,1]))); assert.equal(v.constructor.name, 'WebGLKernelValueDynamicSingleArray1DI'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/dynamic-single-array2d-i.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueDynamicSingleArray2DI'); test('.updateValue() checks too large', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const v = new webGLKernelValueMaps.single.dynamic["Array2D(2)"]([[[1,2]]], { kernel: mockKernel, name: 'test', type: 'Array2D(2)', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue([[[1,2],[3,4],[5,6],[7,8]]]); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.updateValue() checks ok', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.single.dynamic["Array2D(2)"]([[[1,2]]], { kernel: mockKernel, name: 'test', type: 'Array2D(2)', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); v.updateValue([[[2,1]]]); assert.equal(v.constructor.name, 'WebGLKernelValueDynamicSingleArray2DI'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/dynamic-single-array3d-i.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueDynamicSingleArray3DI'); test('.updateValue() checks too large', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const v = new webGLKernelValueMaps.single.dynamic["Array3D(2)"]([[[[1,2]]]], { kernel: mockKernel, name: 'test', type: 'Array3D(2)', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue([[[[1,2],[3,4],[5,6],[7,8]]]]); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.updateValue() checks ok', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.single.dynamic["Array3D(2)"]([[[[1,2]]]], { kernel: mockKernel, name: 'test', type: 'Array3D(2)', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); v.updateValue([[[[2,1]]]]); assert.equal(v.constructor.name, 'WebGLKernelValueDynamicSingleArray3DI'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/dynamic-single-input.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueDynamicSingleInput'); test('.updateValue() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const v = new webGLKernelValueMaps.single.dynamic.Input({ size: [1, 1], value: [0] }, { kernel: mockKernel, name: 'test', type: 'Input', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue({ size: [4,4] }); }, new Error('Argument texture height and width of 2 larger than maximum size of 1 for your GPU')); }); test('.updateValue() checks too large width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const v = new webGLKernelValueMaps.single.dynamic.Input({ size: [1, 1], value: [0] }, { kernel: mockKernel, name: 'test', type: 'Input', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue({ size: [3,3] }) }, new Error('Argument texture width of 3 larger than maximum size of 1 for your GPU')); }); test('.updateValue() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.single.dynamic.Input({ size: [2,2], context: mockContext, value: [0] }, { kernel: mockKernel, name: 'test', type: 'Input', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); v.updateValue({ size: [1,1], context: mockContext, value: [0] }); assert.equal(v.constructor.name, 'WebGLKernelValueDynamicSingleInput'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/dynamic-unsigned-array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueDynamicUnsignedArray'); test('.updateValue() checks too large', () => { const mockKernel = { constructor: { features: { maxTextureSize: 2 }, }, validate: true, }; const v = new webGLKernelValueMaps.unsigned.dynamic.Array([1,2], { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue(new Array([1,2,3,4,5,6,7,8])); }, new Error('Argument texture width of 4 larger than maximum size of 2 for your GPU')); }); test('.updateValue() checks ok', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.unsigned.dynamic.Array([1,2], { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); v.updateValue(new Array([2,1])); assert.equal(v.constructor.name, 'WebGLKernelValueDynamicUnsignedArray'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/dynamic-unsigned-input.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueUnsignedSingleInput'); test('.updateValue() checks too large', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, }; const v = new webGLKernelValueMaps.unsigned.dynamic.Input({ size: [1, 1], value: [0] }, { kernel: mockKernel, name: 'test', type: 'Input', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue({ size: [8,8], value: [0] }); }, new Error('Argument texture height and width of 8 larger than maximum size of 4 for your GPU')); }); test('.updateValue() checks ok', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.unsigned.dynamic.Input({ size: [2,2], context: mockContext, value: [0] }, { kernel: mockKernel, name: 'test', type: 'Input', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); v.updateValue({ size: [1,1], context: mockContext, value: [0] }); assert.equal(v.constructor.name, 'WebGLKernelValueDynamicUnsignedInput'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/html-image.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueHTMLImage'); test('.constructor() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; assert.throws(() => { new webGLKernelValueMaps.unsigned.static.HTMLImage({ width: 1, height: 2 }, { kernel: mockKernel, name: 'test', type: 'HTMLImage', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks too large width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; assert.throws(() => { new webGLKernelValueMaps.unsigned.static.HTMLImage({ width: 2, height: 1 }, { kernel: mockKernel, name: 'test', type: 'HTMLImage', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture width of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 2 }, }, validate: true, }; const v = new webGLKernelValueMaps.unsigned.static.HTMLImage({ width: 2, height: 2 }, { kernel: mockKernel, name: 'test', type: 'HTMLImage', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.equal(v.constructor.name, 'WebGLKernelValueHTMLImage'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/memory-optimized-number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueMemoryOptimizedNumberTexture'); test('.constructor() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; assert.throws(() => { new webGLKernelValueMaps.unsigned.static.MemoryOptimizedNumberTexture({ size: [1, 2] }, { kernel: mockKernel, name: 'test', type: 'MemoryOptimizedNumberTexture', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks too large width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; assert.throws(() => { new webGLKernelValueMaps.unsigned.static.MemoryOptimizedNumberTexture({ size: [2, 1] }, { kernel: mockKernel, name: 'test', type: 'MemoryOptimizedNumberTexture', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture width of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 2 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.unsigned.static.MemoryOptimizedNumberTexture({ size: [2,2], context: mockContext }, { kernel: mockKernel, name: 'test', type: 'MemoryOptimizedNumberTexture', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.equal(v.constructor.name, 'WebGLKernelValueMemoryOptimizedNumberTexture'); }); test('.updateValue() should set uploadValue when a pipeline kernel has no texture', () => { const mockKernel = { constructor: { features: { maxTextureSize: 2 }, }, validate: true, pipeline: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.unsigned.static.MemoryOptimizedNumberTexture({ size: [2,2], context: mockContext }, { kernel: mockKernel, name: 'test', type: 'MemoryOptimizedNumberTexture', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); const newMockTexture = {} v.updateValue({ size: [2,2], context: mockContext, texture: newMockTexture }) assert.equal(v.uploadValue, newMockTexture) }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/number-texture.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueNumberTexture'); test('.constructor() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; assert.throws(() => { new webGLKernelValueMaps.unsigned.static.NumberTexture({ size: [1, 2] }, { kernel: mockKernel, name: 'test', type: 'NumberTexture', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks too large width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; assert.throws(() => { new webGLKernelValueMaps.unsigned.static.NumberTexture({ size: [2, 1] }, { kernel: mockKernel, name: 'test', type: 'NumberTexture', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture width of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 2 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.unsigned.static.NumberTexture({ size: [2,2], context: mockContext }, { kernel: mockKernel, name: 'test', type: 'NumberTexture', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.equal(v.constructor.name, 'WebGLKernelValueNumberTexture'); }); test('.updateValue() should set uploadValue when a pipeline kernel has no texture', () => { const mockKernel = { constructor: { features: { maxTextureSize: 2 }, }, pipeline: true, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.unsigned.static.NumberTexture({ size: [2,2], context: mockContext }, { kernel: mockKernel, name: 'test', type: 'NumberTexture', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); const newMockTexture = {} v.updateValue({ size: [2,2], context: mockContext, texture: newMockTexture }) assert.equal(v.uploadValue, newMockTexture) }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/single-array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueSingleArray'); test('.constructor() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; assert.throws(() => { const row = new Float32Array(5); new webGLKernelValueMaps.single.static.Array(row, { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.single.static.Array([1,2], { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.equal(v.constructor.name, 'WebGLKernelValueSingleArray'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/single-array1d-i.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueSingleArray1DI'); test('.constructor() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; assert.throws(() => { const row = new Float32Array(5); new webGLKernelValueMaps.single.static["Array1D(2)"]([row], { kernel: mockKernel, name: 'test', type: 'Array1D(2)', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.single.static["Array1D(2)"]([[1,2]], { kernel: mockKernel, name: 'test', type: 'Array1D(2)', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.equal(v.constructor.name, 'WebGLKernelValueSingleArray1DI'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/single-array2d-i.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueSingleArray2DI'); test('.constructor() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const row = new Float32Array(5); assert.throws(() => { new webGLKernelValueMaps.single.static["Array2D(2)"]([[row]], { kernel: mockKernel, name: 'test', type: 'Array2D(2)', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.single.static["Array2D(2)"]([[[1,2]]], { kernel: mockKernel, name: 'test', type: 'Array2D(2)', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.equal(v.constructor.name, 'WebGLKernelValueSingleArray2DI'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/single-array3d-i.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueSingleArray3DI'); test('.constructor() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; assert.throws(() => { const row = new Float32Array(5); new webGLKernelValueMaps.single.static["Array3D(2)"]([[row]], { kernel: mockKernel, name: 'test', type: 'Array3D(2)', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.single.static["Array3D(2)"]([[[1,2]]], { kernel: mockKernel, name: 'test', type: 'Array3D(2)', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.equal(v.constructor.name, 'WebGLKernelValueSingleArray3DI'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/single-input.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueSingleInput'); test('.constructor() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; assert.throws(() => { new webGLKernelValueMaps.single.static.Input({ size: [5,1], value: [1,2] }, { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.single.static.Input({ size: [1,2], value: [1,2] }, { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.equal(v.constructor.name, 'WebGLKernelValueSingleInput'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/unsigned-array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueUnsignedArray'); test('.constructor() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; assert.throws(() => { new webGLKernelValueMaps.unsigned.static.Array([1,2], { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture height and width of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.unsigned.static.Array([1,2], { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.equal(v.constructor.name, 'WebGLKernelValueUnsignedArray'); }); ================================================ FILE: test/internal/backend/web-gl/kernel-value/unsigned-input.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGLKernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueUnsignedInput'); test('.constructor() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; assert.throws(() => { new webGLKernelValueMaps.unsigned.static.Input({ size: [2,1], value: [1,2] }, { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture height and width of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGLKernelValueMaps.unsigned.static.Input({ size: [1,2], value: [1,2] }, { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.equal(v.constructor.name, 'WebGLKernelValueUnsignedInput'); }); ================================================ FILE: test/internal/backend/web-gl2/kernel/index.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { WebGL2Kernel } = require('../../../../../src'); describe('internal: WebGL2Kernel'); (typeof global !== 'undefined' ? test : skip)('.setupFeatureChecks() if context is available, but .getExtension() is falsey', () => { const mockContext = { getExtension: null // this is important }; const mockElement = { getContext: () => mockContext, }; const mockDocument = { createElement: () => { return mockElement; } }; global.document = mockDocument; WebGL2Kernel.setupFeatureChecks(); assert.ok(true); delete global.document; }); test('.validateSettings() checks output texture size - too large', () => { const mockContext = { constructor: { features: { maxTextureSize: 1, }, }, checkOutput: () => {}, output: [2], validate: true, checkTextureSize: WebGL2Kernel.prototype.checkTextureSize, }; assert.throws(() => { WebGL2Kernel.prototype.validateSettings.apply(mockContext, []); }, new Error('Texture size [1,2] generated by kernel is larger than supported size [1,1]')); }); test('.validateSettings() checks output texture size - ok', () => { const mockContext = { constructor: { features: { maxTextureSize: 1, }, }, checkOutput: () => {}, output: [1], validate: true, checkTextureSize: WebGL2Kernel.prototype.checkTextureSize, }; WebGL2Kernel.prototype.validateSettings.apply(mockContext, []); assert.ok(true); }); ================================================ FILE: test/internal/backend/web-gl2/kernel/setupArguments.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { WebGL2Kernel, input } = require('../../../../../src'); describe('internal WebGL2Kernel.setupArguments Array'); const gl = { TEXTURE0: 0, TEXTURE_2D: 'TEXTURE_2D', RGBA: 'RGBA', RGBA32F: 'RGBA32F', UNSIGNED_BYTE: 'UNSIGNED_BYTE', FLOAT: 'FLOAT', TEXTURE_WRAP_S: 'TEXTURE_WRAP_S', CLAMP_TO_EDGE: 'CLAMP_TO_EDGE', TEXTURE_WRAP_T: 'TEXTURE_WRAP_T', TEXTURE_MIN_FILTER: 'TEXTURE_MIN_FILTER', TEXTURE_MAG_FILTER: 'TEXTURE_MAG_FILTER', NEAREST: 'NEAREST', UNPACK_FLIP_Y_WEBGL: 'UNPACK_FLIP_Y_WEBGL', }; function setupArgumentsTestSuite(testSuiteSettings) { const { gpuSettings, argument, expectedPixels, expectedBitRatio, expectedDim, expectedSize, expectedType, expectedArgumentTextureCount, expectedPixelStorei, } = testSuiteSettings; let texImage2DCalled = false; let activeTextureCalled = false; let bindTextureCalled = false; let texParameteriCalls = 0; let getUniformLocationCalls = 0; let uniform3ivCalled = false; let uniform2ivCalled = false; let uniform1iCalled = false; const mockContext = Object.assign({ activeTexture: (index) => { assert.equal(index, 0); activeTextureCalled = true; }, bindTexture: (target, texture) => { assert.equal(target, 'TEXTURE_2D'); assert.equal(texture, 'TEXTURE'); bindTextureCalled = true; }, texParameteri: (target, pname, param) => { switch (texParameteriCalls) { case 0: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_WRAP_S'); assert.equal(param, 'CLAMP_TO_EDGE'); texParameteriCalls++; break; case 1: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_WRAP_T'); assert.equal(param, 'CLAMP_TO_EDGE'); texParameteriCalls++; break; case 2: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_MIN_FILTER'); assert.equal(param, 'NEAREST'); texParameteriCalls++; break; case 3: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_MAG_FILTER'); assert.equal(param, 'NEAREST'); texParameteriCalls++; break; default: throw new Error('called too many times'); } }, pixelStorei: (pname, param) => { assert.equal(pname, 'UNPACK_FLIP_Y_WEBGL'); assert.equal(param, expectedPixelStorei); }, createTexture: () => 'TEXTURE', getUniformLocation: (program, name) => { assert.equal(program, 'program'); if (getUniformLocationCalls > 3) { throw new Error('called too many times'); } getUniformLocationCalls++; return { user_vDim: 'user_vDimLocation', user_vSize: 'user_vSizeLocation', user_v: 'user_vLocation', }[name]; }, uniform3iv: (location, value) => { assert.equal(location, 'user_vDimLocation'); assert.deepEqual(value, expectedDim); uniform3ivCalled = true; }, uniform2iv: (location, value) => { assert.equal(location, 'user_vSizeLocation'); assert.deepEqual(value, expectedSize); uniform2ivCalled = true; }, uniform1i: (location, value) => { assert.equal(location, 'user_vLocation'); assert.equal(value, 0); uniform1iCalled = true; }, texImage2D: (target, level, internalFormat, width, height, border, format, type, pixels) => { assert.equal(target, gl.TEXTURE_2D); assert.equal(level, 0); assert.equal(internalFormat, gpuSettings.precision === 'single' ? gl.RGBA32F : gl.RGBA); assert.equal(width, expectedSize[0]); assert.equal(height, expectedSize[1]); assert.equal(border, 0); assert.equal(format, gl.RGBA); assert.equal(type, expectedType); assert.equal(pixels.length, expectedPixels.length); assert.deepEqual(pixels, expectedPixels); texImage2DCalled = true; } }, gl); const source = `function(v) { return v[this.thread.x]; }`; const settings = { context: mockContext, }; const kernel = new WebGL2Kernel(source, Object.assign({}, settings, gpuSettings)); kernel.constructor = { lookupKernelValueType: WebGL2Kernel.lookupKernelValueType, features: { maxTextureSize: 9999 } }; const args = [argument]; kernel.program = 'program'; assert.equal(kernel.argumentTextureCount, 0); kernel.setupArguments(args); assert.equal(kernel.argumentBitRatios[0], expectedBitRatio); assert.equal(kernel.kernelArguments.length, 1); kernel.kernelArguments[0].updateValue(argument); assert.equal(kernel.argumentTextureCount, expectedArgumentTextureCount); assert.ok(texImage2DCalled); assert.ok(activeTextureCalled); assert.ok(bindTextureCalled); assert.equal(texParameteriCalls, 4); assert.equal(getUniformLocationCalls, 1); assert.notOk(uniform3ivCalled); assert.notOk(uniform2ivCalled); assert.ok(uniform1iCalled); } // NOTE: Take special note of how the `argument` and `expectedPixels` are formatted // requires at least 5 entire pixels test('Array with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, argument: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ], expectedBitRatio: 4, expectedPixels: new Uint8Array(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, argument: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 * 1 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, argument: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([2,2]), // 2 * 2 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: new Uint8Array([ 1, 2, 3, 4, 5 ]), expectedBitRatio: 1, expectedPixels: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), // 1 * 2 * 4 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Array with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ], expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ]), // upconverted from 1 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Array with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ], expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0, ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33, ]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33,0, 0,0, 0,0, 0,0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([4,5]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33 ]), expectedBitRatio: 1, expectedPixels: new Uint8Array( new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33,0,0,0 ]).buffer), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Array with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ], expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), // upconverted from 1 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); describe('internal WebGL2Kernel.setupArguments Input'); // requires at least 5 entire pixels test('Input(Array) with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, argument: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5, 0 ], [2,3]), expectedBitRatio: 4, expectedPixels: new Uint8Array(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, argument: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ]), [5]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 * 1 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, argument: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5, 0, ]), [2,3]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([2,2]), // 2 * 2 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with unsigned precision 5 length', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: input(new Uint8Array([ 1, 2, 3, 4, 5,0 ]),[2, 3]), expectedBitRatio: 1, expectedPixels: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), // 1 * 2 * 4 = 8 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Array) with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ], [2,3]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ]),[2,3]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ]), [2,3]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with single precision', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, argument: input(new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ]), [2,3]), // upconverted from 1 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Array) with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ], [33]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ]), [33]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0, ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33, ]), [33]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33,0, 0,0, 0,0, 0,0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([4,5]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with unsigned precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, argument: input(new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33 ]), [33]), expectedBitRatio: 1, expectedPixels: new Uint8Array( new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33,0,0,0 ]).buffer), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Array) with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ], [33]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), [33]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), [33]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with single precision length 33', () => { setupArgumentsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, argument: input(new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA (8 bit, but upconverted to float32), so only 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), [33]), // upconverted to float32 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA (8 bit, but upconverted to float32), so only 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedArgumentTextureCount: 1, expectedPixelStorei: false, }); }); ================================================ FILE: test/internal/backend/web-gl2/kernel/setupConstants.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { WebGL2Kernel, input } = require('../../../../../src'); describe('internal WebGL2Kernel.setupConstants Array'); const gl = { TEXTURE0: 0, TEXTURE_2D: 'TEXTURE_2D', RGBA: 'RGBA', RGBA32F: 'RGBA32F', UNSIGNED_BYTE: 'UNSIGNED_BYTE', FLOAT: 'FLOAT', TEXTURE_WRAP_S: 'TEXTURE_WRAP_S', CLAMP_TO_EDGE: 'CLAMP_TO_EDGE', TEXTURE_WRAP_T: 'TEXTURE_WRAP_T', TEXTURE_MIN_FILTER: 'TEXTURE_MIN_FILTER', TEXTURE_MAG_FILTER: 'TEXTURE_MAG_FILTER', NEAREST: 'NEAREST', UNPACK_FLIP_Y_WEBGL: 'UNPACK_FLIP_Y_WEBGL', }; function setupConstantsTestSuite(testSuiteSettings) { const { gpuSettings, constant, expectedPixels, expectedBitRatio, expectedDim, expectedSize, expectedType, expectedConstantTextureCount, expectedPixelStorei, } = testSuiteSettings; let texImage2DCalled = false; let activeTextureCalled = false; let bindTextureCalled = false; let texParameteriCalls = 0; let getUniformLocationCalls = 0; let uniform3ivCalled = false; let uniform2ivCalled = false; let uniform1iCalled = false; const mockContext = Object.assign({ activeTexture: (index) => { assert.equal(index, 0); activeTextureCalled = true; }, bindTexture: (target, texture) => { assert.equal(target, 'TEXTURE_2D'); assert.equal(texture, 'TEXTURE'); bindTextureCalled = true; }, texParameteri: (target, pname, param) => { switch (texParameteriCalls) { case 0: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_WRAP_S'); assert.equal(param, 'CLAMP_TO_EDGE'); texParameteriCalls++; break; case 1: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_WRAP_T'); assert.equal(param, 'CLAMP_TO_EDGE'); texParameteriCalls++; break; case 2: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_MIN_FILTER'); assert.equal(param, 'NEAREST'); texParameteriCalls++; break; case 3: assert.equal(target, 'TEXTURE_2D'); assert.equal(pname, 'TEXTURE_MAG_FILTER'); assert.equal(param, 'NEAREST'); texParameteriCalls++; break; default: throw new Error('called too many times'); } }, pixelStorei: (pname, param) => { assert.equal(pname, 'UNPACK_FLIP_Y_WEBGL'); assert.equal(param, expectedPixelStorei); }, createTexture: () => 'TEXTURE', getUniformLocation: (program, name) => { assert.equal(program, 'program'); if (getUniformLocationCalls > 3) { throw new Error('called too many times'); } getUniformLocationCalls++; return { constants_vDim: 'constants_vDimLocation', constants_vSize: 'constants_vSizeLocation', constants_v: 'constants_vLocation', }[name]; }, uniform3iv: (location, value) => { assert.equal(location, 'constants_vDimLocation'); assert.deepEqual(value, expectedDim); uniform3ivCalled = true; }, uniform2iv: (location, value) => { assert.equal(location, 'constants_vSizeLocation'); assert.deepEqual(value, expectedSize); uniform2ivCalled = true; }, uniform1i: (location, value) => { assert.equal(location, 'constants_vLocation'); assert.equal(value, 0); uniform1iCalled = true; }, texImage2D: (target, level, internalFormat, width, height, border, format, type, pixels) => { assert.equal(target, gl.TEXTURE_2D); assert.equal(level, 0); assert.equal(internalFormat, gpuSettings.precision === 'single' ? gl.RGBA32F : gl.RGBA); assert.equal(width, expectedSize[0]); assert.equal(height, expectedSize[1]); assert.equal(border, 0); assert.equal(format, gl.RGBA); assert.equal(type, expectedType); assert.equal(pixels.length, expectedPixels.length); assert.deepEqual(pixels, expectedPixels); texImage2DCalled = true; } }, gl); const source = `function(v) { return this.constants.v[this.thread.x]; }`; const settings = { context: mockContext, }; const kernel = new WebGL2Kernel(source, Object.assign({ constants: { v: constant } }, settings, gpuSettings)); kernel.constructor = { lookupKernelValueType: WebGL2Kernel.lookupKernelValueType, features: { maxTextureSize: 9999 } }; kernel.program = 'program'; assert.equal(kernel.constantTextureCount, 0); kernel.setupConstants(); assert.equal(kernel.constantBitRatios.v, expectedBitRatio); assert.equal(kernel.kernelConstants.length, 1); kernel.kernelConstants[0].updateValue(constant); assert.equal(kernel.constantTextureCount, expectedConstantTextureCount); assert.ok(texImage2DCalled); assert.ok(activeTextureCalled); assert.ok(bindTextureCalled); assert.equal(texParameteriCalls, 4); assert.equal(getUniformLocationCalls, 1); assert.notOk(uniform3ivCalled); assert.notOk(uniform2ivCalled); assert.ok(uniform1iCalled); } // NOTE: Take special note of how the `constant` and `expectedPixels` are formatted // requires at least 5 entire pixels test('Array with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, constant: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ], expectedBitRatio: 4, expectedPixels: new Uint8Array(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, constant: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 * 1 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, constant: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([2,2]), // 2 * 2 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: new Uint8Array([ 1, 2, 3, 4, 5 ]), expectedBitRatio: 1, expectedPixels: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), // 1 * 2 * 4 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Array with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ], expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5 ]), // upconverted from 1 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Array with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ], expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0, ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33, ]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33,0, 0,0, 0,0, 0,0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([4,5]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33 ]), expectedBitRatio: 1, expectedPixels: new Uint8Array( new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33,0,0,0 ]).buffer), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Array with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: [ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ], expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Float32Array with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint16Array with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Uint8Array with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), // upconverted from 1 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); describe('internal WebGL2Kernel.setupConstants Input'); // requires at least 5 entire pixels test('Input(Array) with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, constant: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5, 0 ], [2,3]), expectedBitRatio: 4, expectedPixels: new Uint8Array(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, constant: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5 ]), [5]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([5,1,1]), expectedSize: new Int32Array([4,2]), // 4 * 2 * 1 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [4] }, constant: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1, 2, 3, 4, 5, 0, ]), [2,3]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]).buffer ), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([2,2]), // 2 * 2 * 2 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with unsigned precision 5 length', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: input(new Uint8Array([ 1, 2, 3, 4, 5,0 ]),[2, 3]), expectedBitRatio: 1, expectedPixels: new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), // 1 * 2 * 4 = 8 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Array) with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ], [2,3]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ]),[2,3]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedTextureWidth: 1, expectedTextureHeight: 2, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ]), [2,3]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with single precision', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [4] }, constant: input(new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0 ]), [2,3]), // upconverted from 1 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look 1,2,3,4, 5,0,0,0 ]), expectedDim: new Int32Array([2,3,1]), expectedSize: new Int32Array([1,2]), expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Array) with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ], [33]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ]), [33]), expectedBitRatio: 4, expectedPixels: new Uint8Array( new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 1 per RGBA, so only 1 of the 4 channels is used // NOTE: 6x6 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 0, 0, 0, ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([6,6]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33, ]), [33]), expectedBitRatio: 2, expectedPixels: new Uint8Array( new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 2 per RGBA, so only 2 of the 4 channels is used // NOTE: 4x5 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, 13,14, 15,16, 17,18, 19,20, 21,22, 23,24, 25,26, 27,28, 29,30, 31,32, 33,0, 0,0, 0,0, 0,0 ]).buffer ), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([4,5]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with unsigned precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'unsigned', output: [5] }, constant: input(new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33 ]), [33]), expectedBitRatio: 1, expectedPixels: new Uint8Array( new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so only 2 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26, 27,28, 29,30,31,32, 33,0,0,0 ]).buffer), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.UNSIGNED_BYTE, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Array) with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: input([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ], [33]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Float32Array) with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: input(new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), [33]), expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 34 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint16Array) with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: input(new Uint16Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), [33]), // upconverted from 2 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA, so 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); test('Input(Uint8Array) with single precision length 33', () => { setupConstantsTestSuite({ gpuSettings: { precision: 'single', output: [5] }, constant: input(new Uint8Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA (8 bit, but upconverted to float32), so only 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33 ]), [33]), // upconverted to float32 expectedBitRatio: 4, expectedPixels: new Float32Array([ // NOTE: formatted like rectangle on purpose, so you can see how the texture should look // NOTE: Packing is 4 per RGBA (8 bit, but upconverted to float32), so only 4 of the 4 channels is used // NOTE: 3x3 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24, 25,26,27,28, 29,30,31,32, 33,0,0,0 ]), expectedDim: new Int32Array([33,1,1]), expectedSize: new Int32Array([3,3]), // 3 * 3 = 9 * 4 = 36 expectedType: gl.FLOAT, expectedConstantTextureCount: 1, expectedPixelStorei: false, }); }); ================================================ FILE: test/internal/backend/web-gl2/kernel-value/dynamic-html-image-array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGL2KernelValueMaps } = require('../../../../../src'); describe('internal: WebGL2KernelValueDynamicHTMLImage'); test('.updateValue() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const v = new webGL2KernelValueMaps.unsigned.dynamic.HTMLImageArray([{ width: 1, height: 1 }], { kernel: mockKernel, name: 'test', type: 'HTMLImage', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue([{ width: 1, height: 2 }]); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.updateValue() checks too large width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const v = new webGL2KernelValueMaps.unsigned.dynamic.HTMLImageArray([{ width: 1, height: 1 }], { kernel: mockKernel, name: 'test', type: 'HTMLImageArray', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue([{ height: 1, width: 2, }]) }, new Error('Argument texture width of 2 larger than maximum size of 1 for your GPU')); }); test('.updateValue() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 2 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage3D: () => {}, texSubImage3D: () => {}, }; const v = new webGL2KernelValueMaps.unsigned.dynamic.HTMLImageArray([{ width: 2, height: 2 }], { kernel: mockKernel, name: 'test', type: 'HTMLImageArray', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); v.updateValue([{ height: 1, width: 1, }]); assert.equal(v.constructor.name, 'WebGL2KernelValueDynamicHTMLImageArray'); }); ================================================ FILE: test/internal/backend/web-gl2/kernel-value/dynamic-single-array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGL2KernelValueMaps } = require('../../../../../src'); describe('internal: WebGL2KernelValueDynamicSingleArray'); test('.updateValue() checks too large', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; const v = new webGL2KernelValueMaps.single.dynamic.Array([1,2], { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue(new Array([1,2,3,4,5,6,7,8])); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.updateValue() checks ok', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGL2KernelValueMaps.single.dynamic.Array([1,2], { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); v.updateValue(new Array([2,1])); assert.equal(v.constructor.name, 'WebGL2KernelValueDynamicSingleArray'); }); ================================================ FILE: test/internal/backend/web-gl2/kernel-value/dynamic-single-input.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGL2KernelValueMaps } = require('../../../../../src'); describe('internal: WebGLKernelValueDynamicSingleInput'); test('.updateValue() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, }; const v = new webGL2KernelValueMaps.single.dynamic.Input({ size: [5, 5], value: [0] }, { kernel: mockKernel, name: 'test', type: 'Input', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue({ size: [16,16] }); }, new Error('Argument texture height and width of 8 larger than maximum size of 4 for your GPU')); }); test('.updateValue() checks too large width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, }; const v = new webGL2KernelValueMaps.single.dynamic.Input({ size: [1, 1], value: [0] }, { kernel: mockKernel, name: 'test', type: 'Input', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.throws(() => { v.updateValue({ size: [12,12] }) }, new Error('Argument texture height and width of 6 larger than maximum size of 4 for your GPU')); }); test('.updateValue() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGL2KernelValueMaps.single.dynamic.Input({ size: [2,2], context: mockContext, value: [0] }, { kernel: mockKernel, name: 'test', type: 'Input', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); v.updateValue({ size: [1,1], context: mockContext, value: [0] }); assert.equal(v.constructor.name, 'WebGL2KernelValueDynamicSingleInput'); }); ================================================ FILE: test/internal/backend/web-gl2/kernel-value/html-image-array.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGL2KernelValueMaps } = require('../../../../../src'); describe('internal: WebGL2KernelValueHTMLImageArray'); test('.constructor() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; assert.throws(() => { new webGL2KernelValueMaps.unsigned.static.HTMLImageArray([{ width: 1, height: 2 }], { kernel: mockKernel, name: 'test', type: 'HTMLImageArray', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks too large width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; assert.throws(() => { new webGL2KernelValueMaps.unsigned.static.HTMLImageArray([{ width: 2, height: 1 }], { kernel: mockKernel, name: 'test', type: 'HTMLImageArray', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture width of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 2 }, }, validate: true, }; const v = new webGL2KernelValueMaps.unsigned.static.HTMLImageArray([{ width: 2, height: 2 }], { kernel: mockKernel, name: 'test', type: 'HTMLImageArray', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.equal(v.constructor.name, 'WebGL2KernelValueHTMLImageArray'); }); ================================================ FILE: test/internal/backend/web-gl2/kernel-value/single-input.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { webGL2KernelValueMaps } = require('../../../../../src'); describe('internal: WebGL2KernelValueSingleInput'); test('.constructor() checks too large height', () => { const mockKernel = { constructor: { features: { maxTextureSize: 1 }, }, validate: true, }; assert.throws(() => { new webGL2KernelValueMaps.single.static.Input({ size: [8,1], value: [1,2] }, { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); }, new Error('Argument texture height of 2 larger than maximum size of 1 for your GPU')); }); test('.constructor() checks ok height & width', () => { const mockKernel = { constructor: { features: { maxTextureSize: 4 }, }, validate: true, setUniform3iv: () => {}, setUniform2iv: () => {}, setUniform1i: () => {}, }; const mockContext = { activeTexture: () => {}, bindTexture: () => {}, texParameteri: () => {}, pixelStorei: () => {}, texImage2D: () => {}, }; const v = new webGL2KernelValueMaps.single.static.Input({ size: [1,2], value: [1,2] }, { kernel: mockKernel, name: 'test', type: 'Array', origin: 'user', tactic: 'speed', context: mockContext, onRequestContextHandle: () => 1, onRequestTexture: () => null, onRequestIndex: () => 1 }); assert.equal(v.constructor.name, 'WebGL2KernelValueSingleInput'); }); ================================================ FILE: test/internal/boolean.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('internal: boolean'); function booleanLiteral(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { const v = true === true; if (v) { return 1; } return 0; }, { output: [1], }); const result = kernel(); assert.ok(result[0]); gpu.destroy(); } test('boolean literal auto', () => { booleanLiteral(); }); test('boolean literal gpu', () => { booleanLiteral('gpu'); }); (GPU.isWebGLSupported ? test : skip)('boolean literal webgl', () => { booleanLiteral('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('boolean literal webgl2', () => { booleanLiteral('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('boolean literal headlessgl', () => { booleanLiteral('headlessgl'); }); test('boolean literal cpu', () => { booleanLiteral('cpu'); }); function booleanArgumentTrue(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { if (v) { return 1; } return 0; }, { output: [1], }); const result = kernel(true); assert.ok(result[0]); gpu.destroy(); } test('boolean argument true auto', () => { booleanArgumentTrue(); }); test('boolean argument true gpu', () => { booleanArgumentTrue('gpu'); }); (GPU.isWebGLSupported ? test : skip)('boolean argument true webgl', () => { booleanArgumentTrue('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('boolean argument true webgl2', () => { booleanArgumentTrue('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('boolean argument true headlessgl', () => { booleanArgumentTrue('headlessgl'); }); test('boolean argument true cpu', () => { booleanArgumentTrue('cpu'); }); function booleanArgumentFalse(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { if (v) { return 1; } return 0; }, { output: [1], }); const result = kernel(false); assert.notOk(result[0]); gpu.destroy(); } test('boolean argument false auto', () => { booleanArgumentFalse(); }); test('boolean argument false gpu', () => { booleanArgumentFalse('gpu'); }); (GPU.isWebGLSupported ? test : skip)('boolean argument false webgl', () => { booleanArgumentFalse('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('boolean argument false webgl2', () => { booleanArgumentFalse('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('boolean argument false headlessgl', () => { booleanArgumentFalse('headlessgl'); }); test('boolean argument false cpu', () => { booleanArgumentFalse('cpu'); }); function booleanVariableTrue(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { const v = true; if (v) { return 1; } return 0; }, { output: [1], }); const result = kernel(); assert.ok(result[0]); gpu.destroy(); } test('boolean variable true auto', () => { booleanVariableTrue(); }); test('boolean variable true gpu', () => { booleanVariableTrue('gpu'); }); (GPU.isWebGLSupported ? test : skip)('boolean variable true webgl', () => { booleanVariableTrue('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('boolean variable true webgl2', () => { booleanVariableTrue('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('boolean variable true headlessgl', () => { booleanVariableTrue('headlessgl'); }); test('boolean variable true cpu', () => { booleanVariableTrue('cpu'); }); function booleanVariableFalse(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { const v = false; if (v) { return 1; } return 0; }, { output: [1], }); const result = kernel(); assert.notOk(result[0]); gpu.destroy(); } test('boolean variable false auto', () => { booleanVariableFalse(); }); test('boolean variable false gpu', () => { booleanVariableFalse('gpu'); }); (GPU.isWebGLSupported ? test : skip)('boolean variable false webgl', () => { booleanVariableFalse('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('boolean variable false webgl2', () => { booleanVariableFalse('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('boolean variable false headlessgl', () => { booleanVariableFalse('headlessgl'); }); test('boolean variable false cpu', () => { booleanVariableFalse('cpu'); }); function booleanExpressionTrue(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { const v = 1 > 0; if (v) { return 1; } return 0; }, { output: [1], }); const result = kernel(); assert.ok(result[0]); gpu.destroy(); } test('boolean expression true auto', () => { booleanExpressionTrue(); }); test('boolean expression true gpu', () => { booleanExpressionTrue('gpu'); }); (GPU.isWebGLSupported ? test : skip)('boolean expression true webgl', () => { booleanExpressionTrue('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('boolean expression true webgl2', () => { booleanExpressionTrue('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('boolean expression true headlessgl', () => { booleanExpressionTrue('headlessgl'); }); test('boolean expression true cpu', () => { booleanExpressionTrue('cpu'); }); function booleanExpressionFalse(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { const v = 1 < 0; if (v) { return 1; } return 0; }, { output: [1], }); const result = kernel(); assert.notOk(result[0]); gpu.destroy(); } test('boolean expression false auto', () => { booleanExpressionFalse(); }); test('boolean expression false gpu', () => { booleanExpressionFalse('gpu'); }); (GPU.isWebGLSupported ? test : skip)('boolean expression false webgl', () => { booleanExpressionFalse('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('boolean expression false webgl2', () => { booleanExpressionFalse('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('boolean expression false headlessgl', () => { booleanExpressionFalse('headlessgl'); }); test('boolean expression false cpu', () => { booleanExpressionFalse('cpu'); }); ================================================ FILE: test/internal/casting.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('internal: casting'); function castingOffsetByThreadXAndOutputX(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function (value) { // value will be a number // this.thread.x is an integer // this.output.x is treated as a literal, so can be either integer or float // return value will be float return this.thread.x + (this.output.x * value); }, { output: [1], strictIntegers: true, }); const result = kernel(1); assert.equal(result[0], 1); assert.deepEqual(kernel.argumentTypes, ['Integer']); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('casting offset by this.thread.x and this.output.x webgl', () => { castingOffsetByThreadXAndOutputX('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('casting offset by this.thread.x and this.output.x webgl2', () => { castingOffsetByThreadXAndOutputX('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('casting offset by this.thread.x and this.output.x headlessgl', () => { castingOffsetByThreadXAndOutputX('headlessgl'); }); function handleCastingIntsWithNativeFunctions(mode) { const gpu = new GPU({ mode }); gpu.addNativeFunction('add', ` int add(int value1, int value2) { return value1 + value2; } `); const kernel = gpu.createKernel(function(value1, value2) { return add(value1, value2); }, { output: [1] }); const result = kernel(0.5, 2.5); assert.deepEqual(Array.from(result), [2]); assert.deepEqual(kernel.argumentTypes, ['Float', 'Float']); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('handle casting ints with native functions webgl', () => { handleCastingIntsWithNativeFunctions('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('handle casting ints with native functions webgl2', () => { handleCastingIntsWithNativeFunctions('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('handle casting ints with native functions headlessgl', () => { handleCastingIntsWithNativeFunctions('headlessgl'); }); function handleCastingFloatsWithNativeFunctions(mode) { const gpu = new GPU({ mode }); gpu.addNativeFunction('add', ` float add(float value1, float value2) { return value1 + value2; } `); const kernel = gpu.createKernel(function(value1, value2) { return add(value1, value2); }, { argumentTypes: ['Integer', 'Integer'], output: [1], strictIntegers: true, }); const result = kernel(1, 2); assert.deepEqual(Array.from(result), [3]); assert.deepEqual(kernel.argumentTypes, ['Integer', 'Integer']); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('handle casting floats with native functions webgl', () => { handleCastingFloatsWithNativeFunctions('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('handle casting floats with native functions webgl2', () => { handleCastingFloatsWithNativeFunctions('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('handle casting floats with native functions headlessgl', () => { handleCastingFloatsWithNativeFunctions('headlessgl'); }); function handleCastingMixedWithNativeFunctions(mode) { const gpu = new GPU({ mode }); gpu.addNativeFunction('add', ` float add(float value1, int value2) { return value1 + float(value2); } `); const kernel = gpu.createKernel(function(value1, value2) { return add(value1, value2); }, { output: [1], strictIntegers: true, }); const result = kernel(1, 2.5); assert.deepEqual(Array.from(result), [3]); assert.deepEqual(kernel.argumentTypes, ['Integer', 'Float']); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('handle casting mixed with native functions webgl', () => { handleCastingMixedWithNativeFunctions('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('handle casting mixed with native functions webgl2', () => { handleCastingMixedWithNativeFunctions('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('handle casting mixed with native functions headlessgl', () => { handleCastingMixedWithNativeFunctions('headlessgl'); }); function handleCastingFloat(mode) { const gpu = new GPU({ mode }); function add(value1, value2) { return value1 + value2; } gpu.addFunction(add, { argumentTypes: ['Float', 'Float'], returnType: 'Float' }); const kernel = gpu.createKernel(function(value1, value2) { return add(value1, value2); }, { output: [1], argumentTypes: ['Integer', 'Integer'], }); const result = kernel(1, 2); assert.equal(result[0], 3); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('handle casting float webgl', () => { handleCastingFloat('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('handle casting float webgl2', () => { handleCastingFloat('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('handle casting float headlessgl', () => { handleCastingFloat('headlessgl'); }); function handleCastingBeforeReturn(mode) { const gpu = new GPU({ mode }); function addOne(v) { return v + v; } gpu.addFunction(addOne, { argumentTypes: { v: 'Float' }, returnType: 'Integer', }); const kernel = gpu.createKernel(function(v) { return addOne(v); }, { output: [1] }); assert.equal(kernel(1)[0], 2); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('handle casting before return webgl', () => { handleCastingBeforeReturn('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('handle casting before return webgl2', () => { handleCastingBeforeReturn('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('handle casting before return headlessgl', () => { handleCastingBeforeReturn('headlessgl'); }); ================================================ FILE: test/internal/constants-texture-switching.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('internal: constants texture switching'); function testArray1D2(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [this.thread.x, this.thread.x + 1]; }) .setOutput([10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function() { return this.constants.value[this.thread.x]; }) .setConstants({ value: texture }) .setConstantTypes({ value: 'Array1D(2)' }) .setOutput([10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(2) (GPU only) auto', () => { testArray1D2(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(2) (GPU only) gpu', () => { testArray1D2('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array1D(2) (GPU only) webgl', () => { testArray1D2('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array1D(2) (GPU only) webgl2', () => { testArray1D2('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array1D(2) (GPU only) headlessgl', () => { testArray1D2('headlessgl'); }); function testArray1D3(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [this.thread.x, this.thread.x + 1, this.thread.x + 2]; }) .setOutput([10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function() { return this.constants.value[this.thread.x]; }) .setConstants({ value: texture }) .setConstantTypes({ value: 'Array1D(2)' }) .setOutput([10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(3) (GPU only) auto', () => { testArray1D3(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(3) (GPU only) gpu', () => { testArray1D3('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array1D(3) (GPU only) webgl', () => { testArray1D3('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array1D(3) (GPU only) webgl2', () => { testArray1D3('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array1D(3) (GPU only) headlessgl', () => { testArray1D3('headlessgl'); }); function testArray1D4(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [this.thread.x, this.thread.x + 1, this.thread.x + 2, this.thread.x + 3]; }) .setOutput([10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function() { return this.constants.value[this.thread.x]; }) .setConstants({ value: texture }) .setConstantTypes({ value: 'Array1D(2)' }) .setOutput([10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(4) (GPU only) auto', () => { testArray1D4(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(4) (GPU only) gpu', () => { testArray1D4('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array1D(4) (GPU only) webgl', () => { testArray1D4('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array1D(4) (GPU only) webgl2', () => { testArray1D4('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array1D(4) (GPU only) headlessgl', () => { testArray1D4('headlessgl'); }); function testArray2D2(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [this.thread.x, this.thread.y]; }) .setOutput([10, 10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function() { return this.constants.value[this.thread.y][this.thread.x]; }) .setConstants({ value: texture }) .setConstantTypes({ value: 'Array1D(2)' }) .setOutput([10, 10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array2D(2) (GPU only) auto', () => { testArray2D2(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array2D(2) (GPU only) gpu', () => { testArray2D2('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array2D(2) (GPU only) webgl', () => { testArray2D2('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array2D(2) (GPU only) webgl2', () => { testArray2D2('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array2D(2) (GPU only) headlessgl', () => { testArray2D2('headlessgl'); }); function testArray2D3(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [this.thread.x, this.thread.y, this.thread.x * this.thread.y]; }) .setOutput([10, 10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function() { return this.constants.value[this.thread.y][this.thread.x]; }) .setConstants({ value: texture }) .setConstantTypes({ value: 'Array1D(2)' }) .setOutput([10, 10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array2D(3) (GPU only) auto', () => { testArray2D3(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(3) (GPU only) gpu', () => { testArray2D3('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array2D(3) (GPU only) webgl', () => { testArray2D3('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array2D(3) (GPU only) webgl2', () => { testArray2D3('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array2D(3) (GPU only) headlessgl', () => { testArray2D3('headlessgl'); }); function testArray2D4(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [ this.thread.x, this.thread.y, this.thread.x * this.thread.y, this.thread.x / this.thread.y ]; }) .setOutput([10, 10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function() { return this.constants.value[this.thread.y][this.thread.x]; }) .setConstants({ value: texture }) .setConstantTypes({ value: 'Array1D(2)' }) .setOutput([10, 10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array2D(4) (GPU only) auto', () => { testArray2D4(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array1D(4) (GPU only) gpu', () => { testArray2D4('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array2D(4) (GPU only) webgl', () => { testArray2D4('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array2D(4) (GPU only) webgl2', () => { testArray2D4('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array2D(4) (GPU only) headlessgl', () => { testArray2D4('headlessgl'); }); function testArray3D2(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [this.thread.x, this.thread.x * this.thread.y * this.thread.z]; }) .setOutput([10, 10, 10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function() { return this.constants.value[this.thread.z][this.thread.y][this.thread.x]; }) .setConstants({ value: texture }) .setConstantTypes({ value: 'Array1D(2)' }) .setOutput([10, 10, 10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array3D(2) (GPU only) auto', () => { testArray3D2(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array3D(2) (GPU only) gpu', () => { testArray3D2('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array3D(2) (GPU only) webgl', () => { testArray3D2('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array3D(2) (GPU only) webgl2', () => { testArray3D2('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array3D(2) (GPU only) headlessgl', () => { testArray3D2('headlessgl'); }); function testArray3D3(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [this.thread.x, this.thread.y, this.thread.z]; }) .setOutput([10, 10, 10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function() { return this.constants.value[this.thread.z][this.thread.y][this.thread.x]; }) .setConstants({ value: texture }) .setConstantTypes({ value: 'Array1D(2)' }) .setOutput([10, 10, 10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array3D(3) (GPU only) auto', () => { testArray3D3(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array3D(3) (GPU only) gpu', () => { testArray3D3('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array3D(3) (GPU only) webgl', () => { testArray3D3('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array3D(3) (GPU only) webgl2', () => { testArray3D3('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array3D(3) (GPU only) headlessgl', () => { testArray3D3('headlessgl'); }); function testArray3D4(mode) { const gpu = new GPU({ mode }); const texture = ( gpu.createKernel(function() { return [ this.thread.x, this.thread.y, this.thread.z, this.thread.x * this.thread.y * this.thread.z ]; }) .setOutput([10, 10, 10]) .setPipeline(true) .setPrecision('single') )(); const expected = texture.toArray(); const kernel = gpu.createKernel(function() { return this.constants.value[this.thread.z][this.thread.y][this.thread.x]; }) .setConstants({ value: texture }) .setConstantTypes({ value: 'Array1D(2)' }) .setOutput([10, 10, 10]) .setPipeline(false) .setPrecision('single'); assert.notEqual(texture.constructor, Array); assert.equal(expected.constructor, Array); assert.deepEqual(kernel(), expected); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Array3D(4) (GPU only) auto', () => { testArray3D4(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Array3D(4) (GPU only) gpu', () => { testArray3D4('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Array3D(4) (GPU only) webgl', () => { testArray3D4('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Array3D(4) (GPU only) webgl2', () => { testArray3D4('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Array3D(4) (GPU only) headlessgl', () => { testArray3D4('headlessgl'); }); ================================================ FILE: test/internal/constructor-features.js ================================================ const { assert, test, module: describe, only, skip } = require('qunit'); const { GPU } = require('../../src'); describe('internal: constructor features'); function channelCount(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return 1; }, { output: [1] }); kernel(); assert.ok(kernel.kernel.constructor.features.channelCount >= 1); gpu.destroy(); } (GPU.isGPUSupported ? test : skip)('channelCount auto', () => { channelCount(); }); (GPU.isGPUSupported ? test : skip)('channelCount gpu', () => { channelCount('gpu'); }); (GPU.isWebGLSupported ? test : skip)('channelCount webgl', () => { channelCount('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('channelCount webgl2', () => { channelCount('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('channelCount headlessgl', () => { channelCount('headlessgl'); }); ================================================ FILE: test/internal/context-inheritance.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, WebGLKernel, WebGL2Kernel, HeadlessGLKernel } = require('../../src'); describe('internal: context inheritance'); (GPU.isWebGLSupported ? test : skip)('webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); const gpu = new GPU({ context: context }); const simpleKernel = gpu.createKernel(function() { return 1 + 1; }, { output: [1] }); assert.equal(simpleKernel()[0], 2); assert.equal(gpu.Kernel, WebGLKernel); assert.equal(simpleKernel.context, context); gpu.destroy(); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); const gpu = new GPU({ context: context }); const simpleKernel = gpu.createKernel(function() { return 1 + 1; }, { output: [1] }); assert.equal(simpleKernel()[0], 2); assert.equal(gpu.Kernel, WebGL2Kernel); assert.equal(simpleKernel.context, context); gpu.destroy(); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { const context = require('gl')(1,1); const gpu = new GPU({ context: context }); const simpleKernel = gpu.createKernel(function() { return 1 + 1; }, { output: [1] }); assert.equal(simpleKernel()[0], 2); assert.equal(gpu.Kernel, HeadlessGLKernel); assert.equal(simpleKernel.context, context); gpu.destroy(); }); ================================================ FILE: test/internal/deep-types.js ================================================ const sinon = require('sinon'); const { assert, test, module: describe, only, skip } = require('qunit'); const { GPU, FunctionBuilder } = require('../../src'); describe('internal: deep types'); function oneLayerDeepFloat(mode) { const gpu = new GPU({ mode }); function childFunction(childFunctionArgument1) { return childFunctionArgument1 + 1; } gpu.addFunction(childFunction); const kernel = gpu.createKernel(function(kernelArgument1) { return childFunction(kernelArgument1); }, { output: [1] }); sinon.spy(FunctionBuilder.prototype, 'lookupReturnType'); try { const result = kernel(1.5); assert.equal(result[0], 2.5); assert.equal(FunctionBuilder.prototype.lookupReturnType.callCount, 1); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[0][0], 'childFunction'); } finally { FunctionBuilder.prototype.lookupReturnType.restore(); } } (GPU.isWebGLSupported ? test : skip)('one layer deep float WebGL', () => { oneLayerDeepFloat('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('one layer deep float WebGL2', () => { oneLayerDeepFloat('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('one layer deep float HeadlessGL', () => { oneLayerDeepFloat('headlessgl'); }); function twoLayerDeepFloat(mode) { const gpu = new GPU({ mode }); function child1Function(child1FunctionArgument1) { return child2Function(child1FunctionArgument1); } function child2Function(child2FunctionArgument1) { return child2FunctionArgument1 + 1; } gpu .addFunction(child1Function) .addFunction(child2Function); const kernel = gpu.createKernel(function(kernelArgument1) { return child1Function(kernelArgument1); }, { output: [1] }); sinon.spy(FunctionBuilder.prototype, 'lookupReturnType'); try { const result = kernel(1.5); assert.equal(result[0], 2.5); assert.equal(FunctionBuilder.prototype.lookupReturnType.callCount, 3); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[0][0], 'child1Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[1][0], 'child2Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[2][0], 'child2Function'); } finally { FunctionBuilder.prototype.lookupReturnType.restore(); } } (GPU.isWebGLSupported ? test : skip)('two layer deep float WebGL', () => { twoLayerDeepFloat('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('two layer deep float WebGL2', () => { twoLayerDeepFloat('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('two layer deep float HeadlessGL', () => { twoLayerDeepFloat('headlessgl'); }); function twoArgumentLayerDeepFloat(mode) { const gpu = new GPU({ mode }); function child1Function(child1FunctionArgument1) { return child1FunctionArgument1 + 1; } function child2Function(child2FunctionArgument1) { return child2FunctionArgument1 + 1; } gpu .addFunction(child1Function) .addFunction(child2Function); const kernel = gpu.createKernel(function(kernelArgument1) { return child1Function(child2Function(kernelArgument1)); }, { output: [1] }); sinon.spy(FunctionBuilder.prototype, 'lookupReturnType'); try { const result = kernel(1.5); assert.equal(kernel.returnType, 'Float'); assert.equal(result[0], 3.5); assert.equal(FunctionBuilder.prototype.lookupReturnType.callCount, 3); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[0][0], 'child2Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[1][0], 'child1Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[2][0], 'child2Function'); } finally { FunctionBuilder.prototype.lookupReturnType.restore(); } } (GPU.isWebGLSupported ? test : skip)('two argument layer deep float WebGL', () => { twoArgumentLayerDeepFloat('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('two argument layer deep float WebGL2', () => { twoArgumentLayerDeepFloat('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('two argument layer deep float HeadlessGL', () => { twoArgumentLayerDeepFloat('headlessgl'); }); function threeLayerDeepFloat(mode) { const gpu = new GPU({ mode }); function child1Function(child1FunctionArgument1) { return child2Function(child1FunctionArgument1); } function child2Function(child2FunctionArgument1) { return child3Function(child2FunctionArgument1 + 1); } function child3Function(child3FunctionArgument1) { return child3FunctionArgument1 + 1; } gpu .addFunction(child1Function) .addFunction(child2Function) .addFunction(child3Function); const kernel = gpu.createKernel(function(kernelArgument1) { return child1Function(kernelArgument1); }, { output: [1] }); sinon.spy(FunctionBuilder.prototype, 'lookupReturnType'); try { const result = kernel(1.5); assert.equal(result[0], 3.5); assert.equal(FunctionBuilder.prototype.lookupReturnType.callCount, 5); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[0][0], 'child1Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[1][0], 'child2Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[2][0], 'child3Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[3][0], 'child2Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[4][0], 'child3Function'); } finally { FunctionBuilder.prototype.lookupReturnType.restore(); } } (GPU.isWebGLSupported ? test : skip)('three layer deep float WebGL', () => { threeLayerDeepFloat('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('three layer deep float WebGL2', () => { threeLayerDeepFloat('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('three layer deep float HeadlessGL', () => { threeLayerDeepFloat('headlessgl'); }); function threeArgumentLayerDeepFloat(mode) { const gpu = new GPU({ mode }); function child1Function(child1FunctionArgument1) { return child1FunctionArgument1 + 1; } function child2Function(child2FunctionArgument1) { return child2FunctionArgument1 + 1; } function child3Function(child3FunctionArgument1) { return child3FunctionArgument1 + 1; } gpu .addFunction(child1Function) .addFunction(child2Function) .addFunction(child3Function); const kernel = gpu.createKernel(function(kernelArgument1) { return child1Function(child2Function(child3Function(kernelArgument1))); }, { output: [1] }); sinon.spy(FunctionBuilder.prototype, 'lookupReturnType'); try { const result = kernel(1.5); assert.equal(result[0], 4.5); assert.equal(FunctionBuilder.prototype.lookupReturnType.callCount, 5); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[0][0], 'child3Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[1][0], 'child2Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[2][0], 'child1Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[3][0], 'child2Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[4][0], 'child3Function'); } finally { FunctionBuilder.prototype.lookupReturnType.restore(); } } (GPU.isWebGLSupported ? test : skip)('three argument layer deep float WebGL', () => { threeArgumentLayerDeepFloat('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('three argument layer deep float WebGL2', () => { threeArgumentLayerDeepFloat('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('three argument layer deep float HeadlessGL', () => { threeArgumentLayerDeepFloat('headlessgl'); }); function threeArgumentLayerDeepNumberTexture1(mode) { const gpu = new GPU({ mode }); const texture = gpu.createKernel(function() { return 1.5; }, { output: [1], pipeline: true, precision: 'single' })(); function child1Function(child1FunctionArgument1) { return child1FunctionArgument1 + 1; } function child2Function(child2FunctionArgument1) { return child2FunctionArgument1 + 1; } function child3Function(child3FunctionArgument1) { return child3FunctionArgument1[this.thread.x] + 1; } gpu .addFunction(child1Function) .addFunction(child2Function) .addFunction(child3Function); const kernel = gpu.createKernel(function(kernelArgument1) { return child1Function(child2Function(child3Function(kernelArgument1))); }, { output: [1] }); sinon.spy(FunctionBuilder.prototype, 'lookupReturnType'); try { const result = kernel(texture); assert.equal(result[0], 4.5); assert.equal(FunctionBuilder.prototype.lookupReturnType.callCount, 5); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[0][0], 'child3Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[1][0], 'child2Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[2][0], 'child1Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[3][0], 'child2Function'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[4][0], 'child3Function'); } finally { FunctionBuilder.prototype.lookupReturnType.restore(); } } (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('three argument layer deep NumberTexture(1) WebGL', () => { threeArgumentLayerDeepNumberTexture1('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('three argument layer deep NumberTexture(1) WebGL2', () => { threeArgumentLayerDeepNumberTexture1('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('three argument layer deep NumberTexture(1) HeadlessGL', () => { threeArgumentLayerDeepNumberTexture1('headlessgl'); }); function circlicalLogic(mode) { const gpu = new GPU({ mode }); function child1Function(child1FunctionArgument1) { return child1Function(child1FunctionArgument1); } gpu .addFunction(child1Function); const kernel = gpu.createKernel(function(kernelArgument1) { return child1Function(kernelArgument1); }, { output: [1] }); assert.throws(() => { kernel(1.5); }); } (GPU.isWebGLSupported ? test : skip)('circlical logic webgl', () => { circlicalLogic('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('circlical logic webgl2', () => { circlicalLogic('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('circlical logic headlessgl', () => { circlicalLogic('headlessgl'); }); function arrayTexture1(mode) { const gpu = new GPU({ mode }); function addOne(functionValue) { return functionValue[this.thread.x] + 1; } gpu.addFunction(addOne); const texture1 = gpu.createKernel(function() { return 1; }, { output: [1], precision: 'single', pipeline: true, })(); if (mode !== 'cpu') { assert.equal(texture1.type, 'ArrayTexture(1)'); } const kernel = gpu.createKernel(function(kernelValue) { return addOne(kernelValue); }, { output: [1] }); const result = kernel(texture1); assert.equal(result[0], 2); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('ArrayTexture(1) auto', ()=> { arrayTexture1(); }); (GPU.isSinglePrecisionSupported ? test : skip)('ArrayTexture(1) gpu', ()=> { arrayTexture1('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('ArrayTexture(1) webgl', ()=> { arrayTexture1('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('ArrayTexture(1) webgl2', ()=> { arrayTexture1('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('ArrayTexture(1) headlessgl', ()=> { arrayTexture1('headlessgl'); }); (GPU.isSinglePrecisionSupported ? test : skip)('ArrayTexture(1) cpu', ()=> { arrayTexture1('cpu'); }); function arrayTexture2(mode) { const gpu = new GPU({ mode }); function addOne(functionValue) { const declaredValue = functionValue[this.thread.x]; return declaredValue[0] + 1 + declaredValue[1] + 1; } gpu.addFunction(addOne); const texture1 = gpu.createKernel(function() { return [1,2]; }, { output: [1], precision: 'single', pipeline: true, })(); if (mode !== 'cpu') { assert.equal(texture1.type, 'ArrayTexture(2)'); } const kernel = gpu.createKernel(function(kernelValue) { return addOne(kernelValue); }, { output: [1] }); const result = kernel(texture1); assert.equal(result[0], 5); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('ArrayTexture(2) auto', ()=> { arrayTexture2(); }); (GPU.isSinglePrecisionSupported ? test : skip)('ArrayTexture(2) gpu', ()=> { arrayTexture2('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('ArrayTexture(2) webgl', ()=> { arrayTexture2('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('ArrayTexture(2) webgl2', ()=> { arrayTexture2('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('ArrayTexture(2) headlessgl', ()=> { arrayTexture2('headlessgl'); }); (GPU.isSinglePrecisionSupported ? test : skip)('ArrayTexture(2) cpu', ()=> { arrayTexture2('cpu'); }); function arrayTexture3(mode) { const gpu = new GPU({ mode }); function addOne(functionValue) { const declaredValue = functionValue[this.thread.x]; return declaredValue[0] + 1 + declaredValue[1] + 1 + declaredValue[2] + 1; } gpu.addFunction(addOne); const texture1 = gpu.createKernel(function() { return [1,2,3]; }, { output: [1], precision: 'single', pipeline: true, })(); if (mode !== 'cpu') { assert.equal(texture1.type, 'ArrayTexture(3)'); } const kernel = gpu.createKernel(function(kernelValue) { return addOne(kernelValue); }, { output: [1] }); const result = kernel(texture1); assert.equal(result[0], 9); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('ArrayTexture(3) auto', ()=> { arrayTexture3(); }); (GPU.isSinglePrecisionSupported ? test : skip)('ArrayTexture(3) gpu', ()=> { arrayTexture3('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('ArrayTexture(3) webgl', ()=> { arrayTexture3('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('ArrayTexture(3) webgl2', ()=> { arrayTexture3('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('ArrayTexture(3) headlessgl', ()=> { arrayTexture3('headlessgl'); }); (GPU.isSinglePrecisionSupported ? test : skip)('ArrayTexture(3) cpu', ()=> { arrayTexture3('cpu'); }); function arrayTexture4(mode) { const gpu = new GPU({ mode }); function addOne(functionValue) { const declaredValue = functionValue[this.thread.x]; return declaredValue[0] + 1 + declaredValue[1] + 1 + declaredValue[2] + 1 + declaredValue[3] + 1; } gpu.addFunction(addOne); const texture1 = gpu.createKernel(function() { return [1,2,3,4]; }, { output: [1], precision: 'single', pipeline: true, })(); if (mode !== 'cpu') { assert.equal(texture1.type, 'ArrayTexture(4)'); } const kernel = gpu.createKernel(function(kernelValue) { return addOne(kernelValue); }, { output: [1] }); const result = kernel(texture1); assert.equal(result[0], 14); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('ArrayTexture(4) auto', ()=> { arrayTexture4(); }); (GPU.isSinglePrecisionSupported ? test : skip)('ArrayTexture(4) gpu', ()=> { arrayTexture4('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('ArrayTexture(4) webgl', ()=> { arrayTexture4('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('ArrayTexture(4) webgl2', ()=> { arrayTexture4('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('ArrayTexture(4) headlessgl', ()=> { arrayTexture4('headlessgl'); }); (GPU.isSinglePrecisionSupported ? test : skip)('ArrayTexture(4) cpu', ()=> { arrayTexture4('cpu'); }); function testTortureTest(mode) { const gpu = new GPU({ mode }); function addFloatArray(addFloatArrayArgument1, addFloatArrayArgument2) { return addFloatArrayArgument1 + addFloatArrayArgument2[this.thread.x]; } function addArrayFloat(addArrayFloatArgument1, addArrayFloatArgument2) { return addArrayFloatArgument1[this.thread.x] + addArrayFloatArgument2; } function addArrayArray(addArrayArrayArgument1, addArrayArrayArgument2) { return addArrayArrayArgument1[this.thread.x] + addArrayArrayArgument2[this.thread.x]; } function addFloatFloat(addFloatFloatArgument1, addFloatFloatArgument2) { return addFloatFloatArgument1 + addFloatFloatArgument2; } gpu .addFunction(addFloatArray) .addFunction(addArrayFloat) .addFunction(addArrayArray) .addFunction(addFloatFloat); const texture = gpu.createKernel(function() { return 2; }, { output: [1], precision: 'single' })(); // sinon.spy(FunctionBuilder.prototype, 'lookupArgumentType'); sinon.spy(FunctionBuilder.prototype, 'lookupReturnType'); try { const kernel = gpu.createKernel(function (v1, v2, v3, v4, v5) { return addFloatFloat(v4, addArrayFloat(v3, addFloatArray(addArrayArray(v1, v5), v2))); }, {output: [1]}); const result = kernel([1], texture, [3], 4, new Float32Array([5])); assert.equal(result[0], 1 + 2 + 3 + 4 + 5); assert.equal(FunctionBuilder.prototype.lookupReturnType.callCount, 7); assert.equal(FunctionBuilder.prototype.lookupReturnType.returnValues.length, 7); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[0][0], 'addArrayArray'); assert.equal(FunctionBuilder.prototype.lookupReturnType.returnValues[0], 'Number'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[1][0], 'addFloatArray'); assert.equal(FunctionBuilder.prototype.lookupReturnType.returnValues[1], 'Number'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[2][0], 'addArrayFloat'); assert.equal(FunctionBuilder.prototype.lookupReturnType.returnValues[2], 'Number'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[3][0], 'addFloatFloat'); assert.equal(FunctionBuilder.prototype.lookupReturnType.returnValues[3], 'Float'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[4][0], 'addArrayFloat'); assert.equal(FunctionBuilder.prototype.lookupReturnType.returnValues[4], 'Number'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[5][0], 'addFloatArray'); assert.equal(FunctionBuilder.prototype.lookupReturnType.returnValues[5], 'Number'); assert.equal(FunctionBuilder.prototype.lookupReturnType.args[6][0], 'addArrayArray'); assert.equal(FunctionBuilder.prototype.lookupReturnType.returnValues[6], 'Number'); } finally { FunctionBuilder.prototype.lookupReturnType.restore(); } } (GPU.isSinglePrecisionSupported ? test : skip)('torture test auto', () => { testTortureTest(); }); (GPU.isSinglePrecisionSupported ? test : skip)('torture test gpu', () => { testTortureTest('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('torture test webgl', () => { testTortureTest('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('torture test webgl2', () => { testTortureTest('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('torture test headlessgl', () => { testTortureTest('headlessgl'); }); test('torture test cpu', () => { testTortureTest('cpu'); }); function testKernelMap(mode) { const gpu = new GPU({ mode }); function calc1(v1, v2) { return v2[this.thread.x] - v1; } function calc2(v1, v2) { return v1 * v2; } const kernelMap = gpu.createKernelMap({ calc1, calc2, }, function (outputs, targets) { const output = outputs[this.thread.x]; return calc2(calc1(output, targets), output); }, { output: [1], pipeline: true }); try { const result = kernelMap([1], [3]); assert.equal(result.calc1.toArray()[0], 2); assert.equal(result.calc2.toArray()[0], 2); assert.equal(result.result.toArray()[0], 2); } finally { gpu.destroy(); } } (GPU.isWebGLSupported ? test : skip)('kernel map webgl', () => { testKernelMap('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('kernel map webgl2', () => { testKernelMap('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('kernel map headlessgl', () => { testKernelMap('headlessgl'); }); ================================================ FILE: test/internal/deprecated.js ================================================ const { assert, test, module: describe, only, skip } = require('qunit'); const { GPU, Kernel } = require('../../src'); describe('internal: deprecated'); test('GPU.createKernel settings floatOutput true', () => { const gpu = new GPU(); const kernel = gpu.createKernel(function() {}, { floatOutput: true }); assert.equal(kernel.precision, 'single'); assert.notOk(kernel.kernel.hasOwnProperty('floatOutput')); gpu.destroy(); }); test('GPU.createKernel settings floatOutput false', () => { const gpu = new GPU(); const kernel = gpu.createKernel(function() {}, { floatOutput: false }); assert.equal(kernel.precision, 'unsigned'); assert.notOk(kernel.kernel.hasOwnProperty('floatOutput')); gpu.destroy(); }); test('GPU.createKernel settings outputToTexture true', () => { const gpu = new GPU(); const kernel = gpu.createKernel(function() {}, { outputToTexture: true }); assert.equal(kernel.pipeline, true); assert.notOk(kernel.kernel.hasOwnProperty('outputToTexture')); gpu.destroy(); }); test('GPU.createKernel settings outputToTexture false', () => { const gpu = new GPU(); const kernel = gpu.createKernel(function() {}, { outputToTexture: false }); assert.equal(kernel.pipeline, false); assert.notOk(kernel.kernel.hasOwnProperty('outputToTexture')); gpu.destroy(); }); test('GPU.createKernel settings outputImmutable true', () => { const gpu = new GPU(); const kernel = gpu.createKernel(function() {}, { outputImmutable: true }); assert.equal(kernel.immutable, true); assert.notOk(kernel.kernel.hasOwnProperty('outputImmutable')); gpu.destroy(); }); test('GPU.createKernel settings outputImmutable false', () => { const gpu = new GPU(); const kernel = gpu.createKernel(function() {}, { outputImmutable: false }); assert.equal(kernel.immutable, false); assert.notOk(kernel.kernel.hasOwnProperty('outputImmutable')); gpu.destroy(); }); test('GPU.createKernel settings floatTextures true', () => { const gpu = new GPU(); const kernel = gpu.createKernel(function() {}, { floatTextures: true }); assert.equal(kernel.optimizeFloatMemory, true); assert.notOk(kernel.kernel.hasOwnProperty('floatTextures')); gpu.destroy(); }); test('GPU.createKernel settings floatTextures false', () => { const gpu = new GPU(); const kernel = gpu.createKernel(function() {}, { floatTextures: false }); assert.equal(kernel.optimizeFloatMemory, false); assert.notOk(kernel.kernel.hasOwnProperty('floatTextures')); gpu.destroy(); }); test('Kernel.getCanvas', () => { const canvas = {}; const kernel = new Kernel(`function() {}`); kernel.initContext = () => {}; kernel.initPlugins = () => {}; kernel.mergeSettings({ canvas }); assert.equal(kernel.getCanvas(), canvas); }); test('Kernel.getWebGl', () => { const canvas = {}; const context = {}; const kernel = new Kernel(`function() {}`); kernel.initContext = () => {}; kernel.initPlugins = () => {}; kernel.mergeSettings({ canvas, context }); assert.equal(kernel.getWebGl(), context); }); test('Kernel.setOutputToTexture', () => { const kernel = new Kernel(`function() {}`); kernel.setOutputToTexture(true); assert.equal(kernel.pipeline, true); }); ================================================ FILE: test/internal/different-texture-cloning.js ================================================ const { assert, test, module: describe, only, skip } = require('qunit'); const { GPU } = require('../../src'); describe('internal: different texture cloning'); function testArrayThenArray1D4(mode) { const gpu = new GPU({ mode }); function createTextureOf(value, type) { return (gpu.createKernel(function(value) { return value[this.thread.x]; }, { output: [1], pipeline: true, argumentTypes: { value: type } }))(value); } const arrayTexture = createTextureOf([1], 'Array'); const arrayTextureClone = arrayTexture.clone(); const array4Texture = createTextureOf([[1,2,3,4]], 'Array1D(4)'); const array4TextureClone = array4Texture.clone(); assert.notEqual(arrayTextureClone, array4TextureClone); assert.deepEqual(arrayTextureClone.toArray(), new Float32Array([1])); assert.deepEqual(array4TextureClone.toArray(), [new Float32Array([1,2,3,4])]); gpu.destroy(); } test('Array then Array1D(4) auto', () => { testArrayThenArray1D4(); }); (GPU.isWebGLSupported ? test : skip)('Array then Array1D(4) webgl', () => { testArrayThenArray1D4('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Array then Array1D(4) webgl2', () => { testArrayThenArray1D4('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Array then Array1D(4) headlessgl', () => { testArrayThenArray1D4('headlessgl'); }); function testArray1D4ThenArray(mode) { const gpu = new GPU({ mode }); function createTextureOf(value, type) { return (gpu.createKernel(function(value) { return value[this.thread.x]; }, { output: [1], pipeline: true, argumentTypes: { value: type } }))(value); } const array4Texture = createTextureOf([[1,2,3,4]], 'Array1D(4)'); const array4TextureClone = array4Texture.clone(); const arrayTexture = createTextureOf([1], 'Array'); const arrayTextureClone = arrayTexture.clone(); assert.notEqual(array4TextureClone, arrayTextureClone); assert.deepEqual(array4TextureClone.toArray(), [new Float32Array([1,2,3,4])]); assert.deepEqual(arrayTextureClone.toArray(), new Float32Array([1])); gpu.destroy(); } test('Array1D(4) then Array auto', () => { testArray1D4ThenArray(); }); (GPU.isWebGLSupported ? test : skip)('Array1D(4) then Array webgl', () => { testArray1D4ThenArray('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Array1D(4) then Array webgl2', () => { testArray1D4ThenArray('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Array1D(4) then Array headlessgl', () => { testArray1D4ThenArray('headlessgl'); }); ================================================ FILE: test/internal/function-builder.js ================================================ const { assert, test, module: describe, only } = require('qunit'); const { FunctionBuilder, CPUFunctionNode, WebGL2FunctionNode, WebGLFunctionNode } = require('../../src'); describe('internal: function builder'); // Three layer template for multiple tests function threeLayerTemplate(FunctionNode) { function layerOne() { return 42; } function layerTwo() { return layerOne() * 2; } function layerThree() { return layerTwo() * 2; } // Create a function hello node return new FunctionBuilder({ functionNodes: [ new FunctionNode(layerOne.toString(), { output: [1], lookupReturnType: () => 'Number', lookupFunctionArgumentTypes: () => {} }), new FunctionNode(layerTwo.toString(), { output: [1], lookupReturnType: () => 'Number', lookupFunctionArgumentTypes: () => {} }), new FunctionNode(layerThree.toString(), { output: [1], lookupReturnType: () => 'Number', lookupFunctionArgumentTypes: () => {} }), ], output: [1] }); } /// Test the function tracing of 3 layers test('traceFunctionCalls: 3 layer test cpu', () => { const builder = threeLayerTemplate(CPUFunctionNode); assert.deepEqual(builder.traceFunctionCalls('layerOne'), ['layerOne']); assert.deepEqual(builder.traceFunctionCalls('layerTwo'), ['layerTwo', 'layerOne']); assert.deepEqual(builder.traceFunctionCalls('layerThree'), ['layerThree', 'layerTwo', 'layerOne']); }); test('traceFunctionCalls: 3 layer test webgl', () => { const builder = threeLayerTemplate(WebGLFunctionNode); assert.deepEqual(builder.traceFunctionCalls('layerOne'), ['layerOne']); assert.deepEqual(builder.traceFunctionCalls('layerTwo'), ['layerTwo', 'layerOne']); assert.deepEqual(builder.traceFunctionCalls('layerThree'), ['layerThree', 'layerTwo', 'layerOne']); }); test('traceFunctionCalls: 3 layer test webgl2', () => { const builder = threeLayerTemplate(WebGL2FunctionNode); assert.deepEqual(builder.traceFunctionCalls('layerOne'), ['layerOne']); assert.deepEqual(builder.traceFunctionCalls('layerTwo'), ['layerTwo', 'layerOne']); assert.deepEqual(builder.traceFunctionCalls('layerThree'), ['layerThree', 'layerTwo', 'layerOne']); }); /// Test the function tracing of 3 layers test('webglString: 3 layer test cpu', () => { const builder = threeLayerTemplate(CPUFunctionNode); assert.equal( builder.getStringFromFunctionNames(['layerOne']), 'function layerOne() {\nreturn 42;\n}' ); assert.equal( builder.getString('layerOne'), builder.getStringFromFunctionNames(['layerOne']) ); assert.equal( builder.getStringFromFunctionNames(['layerOne','layerTwo']), 'function layerOne() {\nreturn 42;\n}\nfunction layerTwo() {\nreturn (layerOne()*2);\n}' ); assert.equal( builder.getString('layerTwo'), builder.getStringFromFunctionNames(['layerOne','layerTwo']) ); assert.equal( builder.getStringFromFunctionNames(['layerOne','layerTwo','layerThree']), 'function layerOne() {\nreturn 42;\n}\nfunction layerTwo() {\nreturn (layerOne()*2);\n}\nfunction layerThree() {\nreturn (layerTwo()*2);\n}' ); assert.equal( builder.getString('layerThree'), builder.getStringFromFunctionNames(['layerOne','layerTwo','layerThree']) ); assert.equal( builder.getString(null), builder.getString('layerThree') ); }); test('webglString: 3 layer test webgl', () => { const builder = threeLayerTemplate(WebGLFunctionNode); assert.equal( builder.getStringFromFunctionNames(['layerOne']), 'float layerOne() {\nreturn 42.0;\n}' ); assert.equal( builder.getString('layerOne'), builder.getStringFromFunctionNames(['layerOne']) ); assert.equal( builder.getStringFromFunctionNames(['layerOne','layerTwo']), 'float layerOne() {\nreturn 42.0;\n}\nfloat layerTwo() {\nreturn (layerOne()*2.0);\n}' ); assert.equal( builder.getString('layerTwo'), builder.getStringFromFunctionNames(['layerOne','layerTwo']) ); assert.equal( builder.getStringFromFunctionNames(['layerOne','layerTwo','layerThree']), 'float layerOne() {\nreturn 42.0;\n}\nfloat layerTwo() {\nreturn (layerOne()*2.0);\n}\nfloat layerThree() {\nreturn (layerTwo()*2.0);\n}' ); assert.equal( builder.getString('layerThree'), builder.getStringFromFunctionNames(['layerOne','layerTwo','layerThree']) ); assert.equal( builder.getString(null), builder.getString('layerThree') ); }); test('webglString: 3 layer test webgl2', () => { const builder = threeLayerTemplate(WebGL2FunctionNode); assert.notEqual(builder, null, 'class creation check'); assert.equal( builder.getStringFromFunctionNames(['layerOne']), 'float layerOne() {\nreturn 42.0;\n}' ); assert.equal( builder.getString('layerOne'), builder.getStringFromFunctionNames(['layerOne']) ); assert.equal( builder.getStringFromFunctionNames(['layerOne','layerTwo']), 'float layerOne() {\nreturn 42.0;\n}\nfloat layerTwo() {\nreturn (layerOne()*2.0);\n}' ); assert.equal( builder.getString('layerTwo'), builder.getStringFromFunctionNames(['layerOne','layerTwo']) ); assert.equal( builder.getStringFromFunctionNames(['layerOne','layerTwo','layerThree']), 'float layerOne() {\nreturn 42.0;\n}\nfloat layerTwo() {\nreturn (layerOne()*2.0);\n}\nfloat layerThree() {\nreturn (layerTwo()*2.0);\n}' ); assert.equal( builder.getString('layerThree'), builder.getStringFromFunctionNames(['layerOne','layerTwo','layerThree']) ); assert.equal( builder.getString(null), builder.getString('layerThree') ); }); ================================================ FILE: test/internal/function-composition.js ================================================ const { assert, test, skip, module: describe, only } = require('qunit'); const sinon = require('sinon'); const { CPUFunctionNode, FunctionBuilder, GPU, WebGL2FunctionNode, WebGLFunctionNode } = require('../../src'); describe('internal: function composition return values'); function functionCompositionReturnValuesTest(mode) { const gpu = new GPU({ mode }); return gpu.createKernel(function(oneToFour, fourToOne) { function add(left, right) { return left[this.thread.x] + right[this.thread.x]; } return add(oneToFour, fourToOne); }, { output: [4] })([1,2,3,4], [4,3,2,1]); } test('auto', () => { assert.deepEqual(Array.from(functionCompositionReturnValuesTest()), [5,5,5,5]); }); test('gpu', () => { assert.deepEqual(Array.from(functionCompositionReturnValuesTest('gpu')), [5,5,5,5]); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { assert.deepEqual(Array.from(functionCompositionReturnValuesTest('webgl')), [5,5,5,5]); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { assert.deepEqual(Array.from(functionCompositionReturnValuesTest('webgl2')), [5,5,5,5]); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { assert.deepEqual(Array.from(functionCompositionReturnValuesTest('headlessgl')), [5,5,5,5]); }); test('cpu', () => { assert.deepEqual(Array.from(functionCompositionReturnValuesTest('cpu')), [5,5,5,5]); }); describe('internal: function composition FunctionNode'); function functionCompositionFunctionNode(FunctionNode) { const output = [1]; const node = new FunctionNode(`function kernel() { function inner() { return 1; } return inner(); }`, { output, onNestedFunction: sinon.spy(), lookupReturnType: () => 'Number', lookupFunctionArgumentTypes: () => {} }); const string = node.toString(); assert.equal(node.onNestedFunction.callCount, 1); return string; } test('CPUFunctionNode', () => { assert.equal(functionCompositionFunctionNode(CPUFunctionNode), 'function kernel() {' + '\n' + '\nreturn inner();' + '\n}'); }); test('WebGLFunctionNode', () => { assert.equal(functionCompositionFunctionNode(WebGLFunctionNode), 'float kernel() {' + '\n' + '\nreturn inner();' + '\n}'); }); test('WebGL2FunctionNode', () => { assert.equal(functionCompositionFunctionNode(WebGL2FunctionNode), 'float kernel() {' + '\n' + '\nreturn inner();' + '\n}'); }); describe('internal: number function composition FunctionBuilder'); function numberFunctionCompositionFunctionBuilder(FunctionNode) { const output = [1]; const builder = FunctionBuilder.fromKernel({ source: `function kernel() { function inner() { return 1; } return inner(); }`, argumentTypes: [], argumentNames: [], kernelArguments: [], kernelConstants: [], output, leadingReturnStatement: 'resultX[x] = ' }, FunctionNode); return builder.getPrototypeString('kernel'); } test('CPUFunctionNode', () => { assert.equal(numberFunctionCompositionFunctionBuilder(CPUFunctionNode), 'function inner() {' + '\nreturn 1;' + '\n}' + '\nresultX[x] = inner();\ncontinue;'); }); test('WebGLFunctionNode', () => { assert.equal(numberFunctionCompositionFunctionBuilder(WebGLFunctionNode), 'float inner() {' + '\nreturn 1.0;' + '\n}' + '\nvoid kernel() {' + '\n' + '\nkernelResult = inner();return;' + '\n}'); }); test('WebGL2FunctionNode', () => { assert.equal(numberFunctionCompositionFunctionBuilder(WebGL2FunctionNode), 'float inner() {' + '\nreturn 1.0;' + '\n}' + '\nvoid kernel() {' + '\n' + '\nkernelResult = inner();return;' + '\n}'); }); describe('internal: Array(2) function composition FunctionBuilder'); function array2FunctionCompositionFunctionBuilder(FunctionNode) { const output = [1]; const builder = FunctionBuilder.fromKernel({ source: `function kernel() { function inner() { return [1,2,3,4]; } return inner()[0]; }`, argumentTypes: [], argumentNames: [], kernelArguments: [], kernelConstants: [], output, leadingReturnStatement: 'resultX[x] = ' }, FunctionNode); return builder.getPrototypeString('kernel'); } test('CPUFunctionNode', () => { assert.equal(array2FunctionCompositionFunctionBuilder(CPUFunctionNode), 'function inner() {' + '\nreturn new Float32Array([1, 2, 3, 4]);' + '\n}' + '\nresultX[x] = inner()[0];\ncontinue;'); }); test('WebGLFunctionNode', () => { assert.equal(array2FunctionCompositionFunctionBuilder(WebGLFunctionNode), 'vec4 inner() {' + '\nreturn vec4(1.0, 2.0, 3.0, 4.0);' + '\n}' + '\nvoid kernel() {' + '\n' + '\nkernelResult = inner()[0];return;' + '\n}'); }); test('WebGL2FunctionNode', () => { assert.equal(array2FunctionCompositionFunctionBuilder(WebGL2FunctionNode), 'vec4 inner() {' + '\nreturn vec4(1.0, 2.0, 3.0, 4.0);' + '\n}' + '\nvoid kernel() {' + '\n' + '\nkernelResult = inner()[0];return;' + '\n}'); }); ================================================ FILE: test/internal/function-node.js ================================================ const { assert, test, module: describe, only } = require('qunit'); const { CPUFunctionNode, WebGLFunctionNode, WebGL2FunctionNode } = require('../../src'); describe('internal: function node'); /// Test the creation of a hello_world function test('hello_world: just return magic 42 cpu', () => { // Create a function hello node const node = new CPUFunctionNode( (function() { return 42; }).toString(), { name: 'hello_world', output: [1] } ); assert.notEqual(node.getJsAST(), null, 'AST fetch check'); assert.equal( node.toString(), 'function hello_world() {' + '\nreturn 42;' + '\n}', 'function conversion check' ); }); test('hello_world: just return magic 42 webgl', () => { // Create a function hello node const node = new WebGLFunctionNode( (function() { return 42; }).toString(), { name: 'hello_world', output: [1] } ); assert.notEqual(node.getJsAST(), null, 'AST fetch check'); assert.equal( node.toString(), 'float hello_world() {' + '\nreturn 42.0;' + '\n}', 'function conversion check' ); }); test('hello_world: just return magic 42 webgl2', () => { // Create a function hello node const node = new WebGL2FunctionNode( (function() { return 42; }).toString(), { name: 'hello_world', output: [1] } ); assert.notEqual(node.getJsAST(), null, 'AST fetch check'); assert.equal( node.toString(), 'float hello_world() {' + '\nreturn 42.0;' + '\n}', 'function conversion check' ); }); /// Test creation of function, that calls another function test('hello_inner: call a function inside a function cpu', () => { function inner() { return 42; } // Create a function hello node const node = new CPUFunctionNode( (function() { return inner(); }).toString(), { name: 'hello_inner', output: [1], lookupReturnType: () => 'Number', lookupFunctionArgumentTypes: () => {} } ); assert.notEqual(node.getJsAST(), null, 'AST fetch check'); assert.equal( node.toString(), 'function hello_inner() {' + '\nreturn inner();' + '\n}', 'function conversion check' ); assert.deepEqual(node.calledFunctions, ['inner'] ); }); test('hello_inner: call a function inside a function webgl', () => { function inner() { return 42; } // Create a function hello node const node = new WebGLFunctionNode( (function() { return inner(); }).toString(), { name: 'hello_inner', output: [1], lookupReturnType: () => 'Number', lookupFunctionArgumentTypes: () => {} } ); assert.notEqual(node.getJsAST(), null, 'AST fetch check'); assert.equal( node.toString(), 'float hello_inner() {' + '\nreturn inner();' + '\n}', 'function conversion check' ); assert.deepEqual(node.calledFunctions, ['inner'] ); }); /// Test creation of function, that calls another function test('hello_inner: call a function inside a function webgl2', () => { function inner() { return 42; } // Create a function hello node const node = new WebGL2FunctionNode( (function() { return inner(); }).toString(), { name: 'hello_inner', output: [1], lookupReturnType: () => 'Number', lookupFunctionArgumentTypes: () => {} } ); assert.notEqual(node.getJsAST(), null, 'AST fetch check'); assert.equal( node.toString(), 'float hello_inner() {' + '\nreturn inner();' + '\n}', 'function conversion check' ); assert.deepEqual(node.calledFunctions, ['inner'] ); }); /// Test creation of function, that calls another function, with ARGS test('Math.round implementation: A function with arguments cpu', () => { // Math.round node const node = new CPUFunctionNode( (function(a) { return Math.floor(a + 0.5); }).toString(), { name: 'foo', output: [1], argumentTypes: ['Number'], lookupFunctionArgumentTypes: () => {}, triggerImplyArgumentType: () => {}, } ); assert.notEqual(node.getJsAST(), null, 'AST fetch check'); assert.equal( node.toString(), 'function foo(user_a) {' + '\nreturn Math.floor((user_a+0.5));' + '\n}', 'function conversion check' ); assert.deepEqual(node.calledFunctions, ['Math.floor']); }); test('Math.round implementation: A function with arguments webgl', () => { // Math.round node const node = new WebGLFunctionNode( (function(a) { return Math.floor(a + 0.5); }).toString(), { name: 'foo', output: [1], argumentTypes: ['Number'] } ); assert.notEqual(node.getJsAST(), null, 'AST fetch check'); assert.equal( node.toString(), 'float foo(float user_a) {' + '\nreturn floor((user_a+0.5));' + '\n}', 'function conversion check' ); assert.deepEqual(node.calledFunctions, ['floor'] ); }); test('Math.round implementation: A function with arguments webgl2', () => { // Math.round node const node = new WebGL2FunctionNode( (function(a) { return Math.floor(a + 0.5); }).toString(), { name: 'foo', output: [1], argumentTypes: ['Number'] } ); assert.notEqual(node.getJsAST(), null, 'AST fetch check'); assert.equal( node.toString(), 'float foo(float user_a) {' + '\nreturn floor((user_a+0.5));' + '\n}', 'function conversion check' ); assert.deepEqual(node.calledFunctions, ['floor'] ); }); /// Test creation of function, that calls another function, with ARGS test('Two arguments test webgl', function(assert){ const node = new WebGLFunctionNode( (function(a,b) { return a+b; }).toString(), { name: 'add_together', output: [1], argumentTypes: ['Number', 'Number'] } ); assert.notEqual(node.getJsAST(), null, 'AST fetch check'); assert.equal( node.toString(), 'float add_together(float user_a, float user_b) {' + '\nreturn (user_a+user_b);' + '\n}', 'function conversion check' ); }); test('Two arguments test webgl2', function(assert){ const node = new WebGL2FunctionNode( (function(a,b) { return a+b; }).toString(), { name: 'add_together', output: [1], argumentTypes: ['Number', 'Number'] } ); assert.notEqual(node.getJsAST(), null, 'AST fetch check'); assert.equal( node.toString(), 'float add_together(float user_a, float user_b) {' + '\nreturn (user_a+user_b);' + '\n}', 'function conversion check' ); }); /// Test the creation of a hello_world function test('Automatic naming support cpu', () => { function hello_world() { return 42; } // Create a function hello node const node = new CPUFunctionNode(hello_world.toString(), { output: [1] }); assert.notEqual(node, null, 'class creation check'); assert.equal(node.name, 'hello_world'); }); test('Automatic naming support webgl', () => { function hello_world() { return 42; } // Create a function hello node const node = new WebGLFunctionNode(hello_world.toString(), { output: [1] }); assert.notEqual(node, null, 'class creation check'); assert.equal(node.name, 'hello_world'); }); test('Automatic naming support webgl2', () => { function hello_world() { return 42; } // Create a function hello node const node = new WebGL2FunctionNode(hello_world.toString(), { output: [1] }); assert.notEqual(node, null, 'class creation check'); assert.equal(node.name, 'hello_world'); }); ================================================ FILE: test/internal/function-return-type-detection.js ================================================ const { assert, test, skip, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('internal: Function return type detection'); function canDetectNumberFromAddedFunction(mode) { const gpu = new GPU({ mode }); function number() { return 1; } gpu.addFunction(number); const kernel = gpu.createKernel(function() { const values = number(); return values + values; }, { output: [1] }); const result = kernel(); assert.equal(result[0], 2); gpu.destroy(); } test('can detect Number auto', () => { canDetectNumberFromAddedFunction(); }); test('can detect Number gpu', () => { canDetectNumberFromAddedFunction('gpu'); }); (GPU.isWebGLSupported ? test : skip)('can detect Number webgl', () => { canDetectNumberFromAddedFunction('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('can detect Number webgl2', () => { canDetectNumberFromAddedFunction('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('can detect Number headlessgl', () => { canDetectNumberFromAddedFunction('headlessgl'); }); test('can detect Number cpu', () => { canDetectNumberFromAddedFunction('cpu'); }); function canDetectArray2FromAddedFunction(mode) { const gpu = new GPU({ mode }); function array2() { return [1, 2]; } gpu.addFunction(array2); const kernel = gpu.createKernel(function() { const values = array2(); return values[0] + values[1]; }, { output: [1] }); const result = kernel(); assert.equal(result[0], 3); gpu.destroy(); } test('can detect Array(2) auto', () => { canDetectArray2FromAddedFunction(); }); test('can detect Array(2) gpu', () => { canDetectArray2FromAddedFunction('gpu'); }); (GPU.isWebGLSupported ? test : skip)('can detect Array(2) webgl', () => { canDetectArray2FromAddedFunction('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('can detect Array(2) webgl2', () => { canDetectArray2FromAddedFunction('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('can detect Array(2) headlessgl', () => { canDetectArray2FromAddedFunction('headlessgl'); }); test('can detect Array(2) cpu', () => { canDetectArray2FromAddedFunction('cpu'); }); function canDetectArray3FromAddedFunction(mode) { const gpu = new GPU({ mode }); function array2() { return [1, 2, 3]; } gpu.addFunction(array2); const kernel = gpu.createKernel(function() { const values = array2(); return values[0] + values[1] + values[2]; }, { output: [1] }); const result = kernel(); assert.equal(result[0], 6); gpu.destroy(); } test('can detect Array(3) auto', () => { canDetectArray3FromAddedFunction(); }); test('can detect Array(3) gpu', () => { canDetectArray3FromAddedFunction('gpu'); }); (GPU.isWebGLSupported ? test : skip)('can detect Array(3) webgl', () => { canDetectArray3FromAddedFunction('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('can detect Array(3) webgl2', () => { canDetectArray3FromAddedFunction('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('can detect Array(3) headlessgl', () => { canDetectArray3FromAddedFunction('headlessgl'); }); test('can detect Array(3) cpu', () => { canDetectArray3FromAddedFunction('cpu'); }); function canDetectArray4FromAddedFunction(mode) { const gpu = new GPU({ mode }); function array2() { return [1, 2, 3, 4]; } gpu.addFunction(array2); const kernel = gpu.createKernel(function() { const values = array2(); return values[0] + values[1] + values[2] + values[3]; }, { output: [1] }); const result = kernel(); assert.equal(result[0], 10); gpu.destroy(); } test('can detect Array(4) auto', () => { canDetectArray4FromAddedFunction(); }); test('can detect Array(4) gpu', () => { canDetectArray4FromAddedFunction('gpu'); }); (GPU.isWebGLSupported ? test : skip)('can detect Array(4) webgl', () => { canDetectArray4FromAddedFunction('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('can detect Array(4) webgl2', () => { canDetectArray4FromAddedFunction('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('can detect Array(4) headlessgl', () => { canDetectArray4FromAddedFunction('headlessgl'); }); test('can detect Array(4) cpu', () => { canDetectArray4FromAddedFunction('cpu'); }); ================================================ FILE: test/internal/function-tracer.js ================================================ const { assert, test, skip, module: describe, only } = require('qunit'); const sinon = require('sinon'); const acorn = require('acorn'); const { FunctionTracer } = require('../../src'); describe('internal: FunctionTracer'); test('works with Program', () => { const ast = acorn.parse(`var i;`); const functionTracer = new FunctionTracer(ast); assert.ok(functionTracer.functionContexts.length > 0); }); test('works with BlockStatement', () => { const mockBody = {}; let called = false; let calledBody = null; const mockInstance = { contexts: [], runningContexts: [], newContext: FunctionTracer.prototype.newContext, scan: (body) => { called = true; calledBody = body; } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'BlockStatement', body: mockBody }); assert.ok(called); assert.equal(calledBody, mockBody); assert.equal(mockInstance.contexts.length, 1); }); test('works with AssignmentExpression', () => { const mockLeft = {}; const mockRight = {}; let called = false; let calledSides = []; const mockInstance = { scan: (side) => { called = true; calledSides.push(side); } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'AssignmentExpression', left: mockLeft, right: mockRight }); assert.ok(called); assert.deepEqual(calledSides, [mockLeft, mockRight]); }); test('works with LogicalExpression', () => { const mockLeft = {}; const mockRight = {}; let called = false; let calledSides = []; const mockInstance = { scan: (side) => { called = true; calledSides.push(side); } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'LogicalExpression', left: mockLeft, right: mockRight }); assert.ok(called); assert.deepEqual(calledSides, [mockLeft, mockRight]); }); test('works with BinaryExpression', () => { const mockLeft = {}; const mockRight = {}; let called = false; let calledSides = []; const mockInstance = { scan: (side) => { called = true; calledSides.push(side); } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'BinaryExpression', left: mockLeft, right: mockRight }); assert.ok(called); assert.deepEqual(calledSides, [mockLeft, mockRight]); }); test('works with UpdateExpression', () => { const mockArgument = {}; let called = false; let calledBody = null; const mockInstance = { scan: (argument) => { called = true; calledBody = argument; } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'UpdateExpression', argument: mockArgument }); assert.ok(called); assert.equal(calledBody, mockArgument); }); test('works with UnaryExpression', () => { const mockArgument = {}; let called = false; let calledArgument = null; const mockInstance = { scan: (argument) => { called = true; calledArgument = argument; } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'UpdateExpression', argument: mockArgument }); assert.ok(called); assert.equal(calledArgument, mockArgument); }); test('works with VariableDeclaration', () => { const mockDeclarations = []; let called = false; let calledDeclarations = null; const mockInstance = { scan: (declarations) => { called = true; calledDeclarations = declarations; } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'VariableDeclaration', declarations: mockDeclarations }); assert.ok(called); assert.deepEqual(calledDeclarations, mockDeclarations); }); test('works with generic VariableDeclarator', () => { const ast = acorn.parse('var bob = 0;'); const functionTracer = new FunctionTracer(ast); const { bob } = functionTracer.contexts[0]; assert.equal(bob.ast, ast.body[0].declarations[0]); assert.equal(bob.context, functionTracer.contexts[0]); assert.equal(bob.name, 'bob'); assert.equal(bob.origin, 'declaration'); assert.equal(bob.assignable, true); assert.equal(bob.inForLoopTest, null); assert.equal(bob.inForLoopInit, false); assert.equal(functionTracer.declarations[0], bob); }); test('works with var VariableDeclarator', () => { const ast = acorn.parse('var bob = 0;'); const functionTracer = new FunctionTracer(ast); const { bob } = functionTracer.contexts[0]; assert.equal(bob.context['@contextType'], 'function'); }); test('works with let VariableDeclarator', () => { const ast = acorn.parse('let bob = 0;'); const functionTracer = new FunctionTracer(ast); const { bob } = functionTracer.contexts[0]; assert.equal(bob.context['@contextType'], 'function'); }); test('works with var & let VariableDeclarator together', () => { const ast = acorn.parse(`var bob = 0; for (let i = 0; i < 1; i++) { let pop = 0; }`); const functionTracer = new FunctionTracer(ast); assert.equal(functionTracer.contexts[0].bob.context['@contextType'], 'function'); assert.equal(functionTracer.contexts[0].i, undefined); assert.equal(functionTracer.contexts[0].pop, undefined); assert.equal(functionTracer.contexts[1].bob.context['@contextType'], 'function'); assert.equal(functionTracer.contexts[1].i.context['@contextType'], 'function'); assert.equal(functionTracer.contexts[1].pop, undefined); assert.equal(functionTracer.contexts[2].bob.context['@contextType'], 'function'); assert.equal(functionTracer.contexts[2].i.context['@contextType'], 'function'); assert.equal(functionTracer.contexts[2].pop, undefined); assert.equal(functionTracer.contexts[3].bob.context['@contextType'], 'function'); assert.equal(functionTracer.contexts[3].i.context['@contextType'], 'function'); assert.equal(functionTracer.contexts[3].pop.context['@contextType'], 'function'); }); test('works with FunctionExpression when runningContexts.length = 0', () => { const mockBody = {}; let called = false; let calledBody = null; const mockInstance = { runningContexts: [], functions: [], scan: (body) => { called = true; calledBody = body; } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'FunctionExpression', body: mockBody }); assert.ok(called); assert.equal(calledBody, mockBody); assert.equal(mockInstance.functions.length, 0); }); test('works with FunctionDeclaration when runningContexts.length = 0', () => { const mockBody = {}; let called = false; let calledBody = null; const mockInstance = { runningContexts: [], functions: [], scan: (body) => { called = true; calledBody = body; } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'FunctionDeclaration', body: mockBody }); assert.ok(called); assert.equal(calledBody, mockBody); assert.equal(mockInstance.functions.length, 0); }); test('works with FunctionExpression when runningContexts.length > 0', () => { const mockBody = {}; const mockInstance = { functions: [], runningContexts: [null], scan: () => { throw new Error('should not be called'); } }; const mockAst = { type: 'FunctionExpression', body: mockBody }; FunctionTracer.prototype.scan.call(mockInstance, mockAst); assert.equal(mockInstance.functions.length, 1); assert.equal(mockInstance.functions[0], mockAst); }); test('works with FunctionDeclaration when runningContexts.length > 0', () => { const mockBody = {}; const mockInstance = { functions: [], runningContexts: [null], scan: () => { throw new Error('should not be called'); } }; const mockAst = { type: 'FunctionDeclaration', body: mockBody }; FunctionTracer.prototype.scan.call(mockInstance, mockAst); assert.equal(mockInstance.functions.length, 1); assert.equal(mockInstance.functions[0], mockAst); }); test('works with IfStatement', () => { const mockTest = {}; const mockConsequent = {}; const mockAlternate = {}; let called = false; let calledArgs = []; const mockInstance = { scan: (arg) => { called = true; calledArgs.push(arg); } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'IfStatement', test: mockTest, consequent: mockConsequent, alternate: mockAlternate, }); assert.ok(called); assert.deepEqual(calledArgs, [mockTest, mockConsequent, mockAlternate]); }); test('works with ForStatement', () => { const ast = acorn.parse(`for (let i = 0; i < 1; i++) { call(); }`); const functionTracer = new FunctionTracer(ast.body[0]); assert.equal(functionTracer.declarations[0].name, 'i'); assert.equal(functionTracer.contexts.length, 4); }); test('works with DoWhileStatement', () => { const mockBody = {}; const mockTest = {}; let called = false; let calledArgs = []; const mockInstance = { contexts: [], runningContexts: [], newContext: FunctionTracer.prototype.newContext, scan: (arg) => { called = true; calledArgs.push(arg); } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'DoWhileStatement', body: mockBody, test: mockTest }); assert.ok(called); assert.deepEqual(calledArgs, [mockBody, mockTest]); }); test('works with WhileStatement', () => { const mockBody = {}; const mockTest = {}; let called = false; let calledArgs = []; const mockInstance = { contexts: [], runningContexts: [], newContext: FunctionTracer.prototype.newContext, scan: (arg) => { called = true; calledArgs.push(arg); } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'WhileStatement', body: mockBody, test: mockTest }); assert.ok(called); assert.deepEqual(calledArgs, [mockBody, mockTest]); }); test('works with Identifier', () => { const mockCurrentContext = {}; const mockIsState = sinon.spy(); const mockGetDeclaration = sinon.spy(() => 123); const mockInstance = { identifiers: [], currentContext: mockCurrentContext, isState: mockIsState, getDeclaration: mockGetDeclaration, }; const mockAst = { type: 'Identifier', name: 'x' }; FunctionTracer.prototype.scan.call(mockInstance, mockAst); assert.ok(mockGetDeclaration.called); assert.equal(mockGetDeclaration.args[0][0], 'x'); assert.deepEqual(mockInstance.identifiers, [ { context: mockInstance.currentContext, ast: mockAst, declaration: 123 } ]); assert.equal(mockIsState.args[0][0], 'trackIdentifiers'); }); test('works with ReturnStatement', () => { const mockArgument = {}; let called = false; let calledArgument = null; const mockInstance = { returnStatements: [], scan: (argument) => { called = true; calledArgument = argument; } }; const mockAst = { type: 'ReturnStatement', argument: mockArgument }; FunctionTracer.prototype.scan.call(mockInstance, mockAst); assert.ok(called); assert.equal(calledArgument, mockArgument); assert.equal(mockInstance.returnStatements[0], mockAst); }); test('works with MemberExpression', () => { const mockBody = {}; const mockProperty = {}; const mockPushState = sinon.spy(); const mockPopState = sinon.spy(); const mockScan = sinon.spy(); const mockInstance = { scan: mockScan, pushState: mockPushState, popState: mockPopState, }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'MemberExpression', object: mockBody, property: mockProperty }); assert.ok(mockScan.called); assert.equal(mockScan.args[0][0], mockBody); assert.equal(mockScan.args[1][0], mockProperty); assert.equal(mockPushState.args[0][0], 'memberExpression'); assert.equal(mockPopState.args[0][0], 'memberExpression'); }); test('works with ExpressionStatement', () => { const mockExpression = {}; let called = false; let calledExpression = null; const mockInstance = { scan: (body) => { called = true; calledExpression = body; } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'ExpressionStatement', expression: mockExpression }); assert.ok(called); assert.equal(calledExpression, mockExpression); }); test('works with SequenceExpression', () => { const mockExpression = {}; const mockExpressions = [mockExpression]; let called = false; let calledExpression = null; const mockInstance = { scan: (body) => { called = true; calledExpression = body; } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'SequenceExpression', expressions: mockExpressions }); assert.ok(called); assert.equal(calledExpression, mockExpressions); }); test('works with CallExpression', () => { const mockArguments = {}; let called = false; let calledArguments = null; const mockCurrentContext = {}; const mockInstance = { currentContext: mockCurrentContext, functionCalls: [], scan: (_arguments) => { called = true; calledArguments = _arguments; } }; const mockAst = { type: 'CallExpression', arguments: mockArguments }; FunctionTracer.prototype.scan.call(mockInstance, mockAst); assert.ok(called); assert.equal(calledArguments, mockArguments); assert.deepEqual(mockInstance.functionCalls, [ { context: mockCurrentContext, ast: mockAst } ]); }); test('works with ArrayExpression', () => { const mockElements = {}; let called = false; let calledElements = null; const mockInstance = { scan: (elements) => { called = true; calledElements = elements; } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'ArrayExpression', elements: mockElements }); assert.ok(called); assert.equal(calledElements, mockElements); }); test('works with ConditionalExpression', () => { const mockTest = {}; const mockAlternate = {}; const mockConsequent = {}; let called = false; let calledArgs = []; const mockInstance = { scan: (arg) => { called = true; calledArgs.push(arg); } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'ConditionalExpression', test: mockTest, alternate: mockAlternate, consequent: mockConsequent }); assert.ok(called); assert.deepEqual(calledArgs, [mockTest, mockConsequent, mockConsequent]); }); test('works with SwitchStatement', () => { const mockDiscriminant = {}; const mockCases = {}; let called = false; let calledArgs = []; const mockInstance = { scan: (arg) => { called = true; calledArgs.push(arg); } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'SwitchStatement', discriminant: mockDiscriminant, cases: mockCases }); assert.ok(called); assert.deepEqual(calledArgs, [mockDiscriminant, mockCases]); }); test('works with SwitchCase', () => { const mockTest = {}; const mockConsequent = {}; let called = false; let calledArgs = []; const mockInstance = { scan: (arg) => { called = true; calledArgs.push(arg); } }; FunctionTracer.prototype.scan.call(mockInstance, { type: 'SwitchCase', test: mockTest, consequent: mockConsequent }); assert.ok(called); assert.deepEqual(calledArgs, [mockTest, mockConsequent]); }); test('does nothing with un-scan-ables', () => { let called = false; const mockInstance = { scan: () => { called = true; } }; [ 'ThisExpression', 'Literal', 'DebuggerStatement', 'EmptyStatement', 'BreakStatement', 'ContinueStatement' ].forEach(type => { FunctionTracer.prototype.scan.call(mockInstance, { type }); }); assert.ok(!called); }); test('when called with fake type, throws', () => { assert.throws(() => { FunctionTracer.prototype.scan.call({}, { type: 'Made Up' }); }); }); test('can handle direct arrays', () => { const mockBlockBody = {}; const mockProgramBody = {}; const asts = [ { type: 'BlockStatement' }, { type: 'Program' }, ]; const calledAsts = []; const mockInstance = { scan: (ast) => { calledAsts.push(ast); } }; FunctionTracer.prototype.scan.call(mockInstance, asts); assert.deepEqual(calledAsts, asts); }); ================================================ FILE: test/internal/gpu-methods.js ================================================ const { assert, test, skip, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('internal: GPU methods'); test('.createKernelMap() object map with settings', () => { const gpu = new GPU(); let source = null; let settings = null; function bob() {} function tom() {} class MockKernel { constructor(_source, _settings) { source = _source; settings = _settings; this.context = 'context'; this.canvas = 'canvas'; this.subKernels = _settings.subKernels; } } gpu.Kernel = MockKernel; const subKernels = { bobResult: bob, tomResult: tom }; const kernelSource = function() {}; const masterSettings = {}; const kernel = gpu.createKernelMap(subKernels, kernelSource, masterSettings); assert.equal(source, kernelSource.toString()); assert.notEqual(settings, masterSettings); assert.equal(gpu.canvas, 'canvas'); assert.equal(gpu.context, 'context'); assert.equal(settings.functions, gpu.functions); assert.equal(settings.nativeFunctions, gpu.nativeFunctions); assert.equal(settings.gpu, gpu); assert.equal(settings.validate, true); assert.deepEqual(kernel.subKernels, [ { name: 'bob', source: bob.toString(), property: 'bobResult' }, { name: 'tom', source: tom.toString(), property: 'tomResult' } ]); }); test('.createKernelMap() array map with settings', () => { const gpu = new GPU(); let source = null; let settings = null; function bob() {} function tom() {} class MockKernel { constructor(_source, _settings) { source = _source; settings = _settings; this.context = 'context'; this.canvas = 'canvas'; this.subKernels = _settings.subKernels; } } gpu.Kernel = MockKernel; const subKernels = [bob, tom]; const kernelSource = function() {}; const masterSettings = {}; const kernel = gpu.createKernelMap(subKernels, kernelSource, masterSettings); assert.equal(source, kernelSource.toString()); assert.notEqual(settings, masterSettings); assert.equal(gpu.canvas, 'canvas'); assert.equal(gpu.context, 'context'); assert.equal(settings.functions, gpu.functions); assert.equal(settings.nativeFunctions, gpu.nativeFunctions); assert.equal(settings.gpu, gpu); assert.equal(settings.validate, true); assert.deepEqual(kernel.subKernels, [ { name: 'bob', source: bob.toString(), property: 0 }, { name: 'tom', source: tom.toString(), property: 1 } ]); }); ================================================ FILE: test/internal/implied-else.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('internal: Implied else'); function neverReachedWhenEarlyReturn(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(check, v1, v2) { if (check) { return v1; } return v2; }, { output: [1] }); const result = kernel(true, 123, 321); assert.equal(result[0], 123); gpu.destroy(); } test('never reached when early return auto', () => { neverReachedWhenEarlyReturn(); }); test('never reached when early return gpu', () => { neverReachedWhenEarlyReturn('gpu'); }); (GPU.isWebGLSupported ? test : skip)('never reached when early return webgl', () => { neverReachedWhenEarlyReturn('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('never reached when early return webgl2', () => { neverReachedWhenEarlyReturn('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('never reached when early return headlessgl', () => { neverReachedWhenEarlyReturn('headlessgl'); }); test('never reached when early return cpu', () => { neverReachedWhenEarlyReturn('cpu'); }); function handlesImpliedElse(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(check, v1, v2) { if (check) { return v1; } return v2; }, { output: [1] }); const result = kernel(true, 123, 321); assert.equal(result[0], 123); gpu.destroy(); } test('handles implied else auto', () => { handlesImpliedElse(); }); test('handles implied else gpu', () => { handlesImpliedElse('gpu'); }); (GPU.isWebGLSupported ? test : skip)('handles implied else webgl', () => { handlesImpliedElse('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('handles implied else webgl2', () => { handlesImpliedElse('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('handles implied else headlessgl', () => { handlesImpliedElse('headlessgl'); }); test('handles implied else cpu', () => { handlesImpliedElse('cpu'); }); ================================================ FILE: test/internal/kernel-run-shortcut.js ================================================ const { assert, test, module: describe, skip } = require('qunit'); const sinon = require('sinon'); const { GPU } = require('../../src'); describe('internal: kernelRunShortcut'); function testImmutableSavesSwitchedKernel(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[0] + 1; }, { output: [1], pipeline: true, immutable: true, }); const one = kernel(new Float32Array([0])); const arrayKernel = kernel.kernel; const arrayKernelSpy = sinon.spy(arrayKernel, 'onRequestSwitchKernel'); // recompile kernel const two = kernel(one); assert.equal(arrayKernelSpy.callCount, 1); const textureKernel = kernel.kernel; const textureKernelSpy = sinon.spy(textureKernel, 'onRequestSwitchKernel'); assert.ok(kernel.kernel !== arrayKernel); assert.ok(kernel.kernel === textureKernel); // reuse existing kernel a few times, ensure no overwriting const three = kernel(two); assert.equal(arrayKernelSpy.callCount, 1); assert.equal(textureKernelSpy.callCount, 0); assert.ok(kernel.kernel === textureKernel); const four = kernel(three); assert.equal(arrayKernelSpy.callCount, 1); assert.equal(textureKernelSpy.callCount, 0); assert.ok(kernel.kernel === textureKernel); const five = kernel(four); assert.equal(arrayKernelSpy.callCount, 1); assert.equal(textureKernelSpy.callCount, 0); assert.ok(kernel.kernel === textureKernel); const six = kernel(five); assert.equal(arrayKernelSpy.callCount, 1); assert.equal(textureKernelSpy.callCount, 0); assert.ok(kernel.kernel === textureKernel); // switch back to original kernel, don't recompile assert.deepEqual(six.toArray(), new Float32Array([6])); const seven = kernel(six.toArray()); assert.ok(kernel.kernel === arrayKernel); assert.equal(arrayKernelSpy.callCount, 1); assert.equal(textureKernelSpy.callCount, 1); // ensure output has been correct all along assert.deepEqual(one.toArray(), new Float32Array([1])); assert.deepEqual(two.toArray(), new Float32Array([2])); assert.deepEqual(three.toArray(), new Float32Array([3])); assert.deepEqual(four.toArray(), new Float32Array([4])); assert.deepEqual(five.toArray(), new Float32Array([5])); assert.deepEqual(six.toArray(), new Float32Array([6])); assert.deepEqual(seven.toArray(), new Float32Array([7])); gpu.destroy(); } test('immutable saves switched kernel auto', () => { testImmutableSavesSwitchedKernel(); }); test('immutable saves switched kernel gpu', () => { testImmutableSavesSwitchedKernel('gpu'); }); (GPU.isWebGLSupported ? test : skip)('immutable saves switched kernel webgl', () => { testImmutableSavesSwitchedKernel('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('immutable saves switched kernel webgl2', () => { testImmutableSavesSwitchedKernel('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('immutable saves switched kernel headlessgl', () => { testImmutableSavesSwitchedKernel('headlessgl'); }); ================================================ FILE: test/internal/kernel.js ================================================ const { assert, test, module: describe, skip } = require('qunit'); const { GPU, CPUKernel, WebGLKernel, WebGL2Kernel, HeadlessGLKernel, Kernel } = require('../../src'); describe('internal: kernel'); /** * * @param {Kernel} Kernel */ function argumentTypesTest(Kernel) { const kernel = new Kernel(`function(value) { return value[this.thread.x]; }`, { output: [1], functionBuilder: { addKernel: function() {}, addFunctions: function() {}, getPrototypes: function() { return []; }, addNativeFunctions: function() {} }, }); kernel.build([1]); assert.equal(kernel.argumentTypes.length, 1); assert.equal(kernel.argumentTypes[0], 'Array'); kernel.destroy(); } test('CPUKernel argumentTypes', () => { argumentTypesTest(CPUKernel); }); (GPU.isWebGLSupported ? test : skip)('WebGLKernel argumentTypes', () => { argumentTypesTest(WebGLKernel); }); (GPU.isWebGL2Supported ? test : skip)('WebGL2Kernel argumentTypes', () => { argumentTypesTest(WebGL2Kernel); }); (GPU.isHeadlessGLSupported ? test : skip)('HeadlessGLKernel argumentTypes', () => { argumentTypesTest(HeadlessGLKernel); }); /** * * @param {Kernel} Kernel */ function setUniform1fTest(Kernel) { const canvas = {}; const context = { uniform1f: () => { if (throws) new Error('This should not get called'); }, getUniformLocation: (name) => { return name; } }; const kernel = new Kernel('function() {}', { canvas, context, output: [1] }); let throws = false; kernel.setUniform1f('test', 1); assert.equal(kernel.uniform1fCache['test'], 1); throws = true; kernel.setUniform1f('test', 1); assert.equal(kernel.uniform1fCache['test'], 1); throws = false; kernel.setUniform1f('test', 2); assert.equal(kernel.uniform1fCache['test'], 2); kernel.destroy(); } test('WebGLKernel.setUniform1f only calls context when values change', () => { setUniform1fTest(WebGLKernel); }); test('WebGL2Kernel.setUniform1f only calls context when values change', () => { setUniform1fTest(WebGL2Kernel); }); (GPU.isHeadlessGLSupported ? test : skip)('HeadlessGLKernel.setUniform1f only calls context when values change', () => { setUniform1fTest(HeadlessGLKernel); }); /** * * @param {Kernel} Kernel */ function setUniform1iTest(Kernel) { const canvas = {}; const context = { uniform1i: () => { if (throws) new Error('This should not get called'); }, getUniformLocation: (name) => { return name; } }; const kernel = new Kernel('function() {}', { canvas, context, output: [1] }); let throws = false; kernel.setUniform1i('test', 1); assert.equal(kernel.uniform1iCache['test'], 1); throws = true; kernel.setUniform1i('test', 1); assert.equal(kernel.uniform1iCache['test'], 1); throws = false; kernel.setUniform1i('test', 2); assert.equal(kernel.uniform1iCache['test'], 2); kernel.destroy(); } test('WebGLKernel.setUniform1i only calls context when values change', () => { setUniform1iTest(WebGLKernel); }); test('WebGL2Kernel.setUniform1i only calls context when values change', () => { setUniform1iTest(WebGL2Kernel); }); (GPU.isHeadlessGLSupported ? test : skip)('HeadlessGLKernel.setUniform1i only calls context when values change', () => { setUniform1iTest(HeadlessGLKernel); }); /** * * @param {Kernel} Kernel */ function setUniform2fTest(Kernel) { const canvas = {}; const context = { uniform2f: () => { if (throws) new Error('This should not get called'); }, getUniformLocation: (name) => { return name; } }; const kernel = new Kernel('function() {}', { canvas, context, output: [1] }); let throws = false; kernel.setUniform2f('test', 1, 2); assert.deepEqual(kernel.uniform2fCache['test'], [1, 2]); throws = true; kernel.setUniform2f('test', 1, 2); assert.deepEqual(kernel.uniform2fCache['test'], [1, 2]); throws = false; kernel.setUniform2f('test', 3, 4); assert.deepEqual(kernel.uniform2fCache['test'], [3, 4]); kernel.destroy(); } test('WebGLKernel.setUniform2f only calls context when values change', () => { setUniform2fTest(WebGLKernel); }); test('WebGL2Kernel.setUniform2f only calls context when values change', () => { setUniform2fTest(WebGL2Kernel); }); (GPU.isHeadlessGLSupported ? test : skip)('HeadlessGLKernel.setUniform2f only calls context when values change', () => { setUniform2fTest(HeadlessGLKernel); }); /** * * @param {Kernel} Kernel */ function setUniform2fvTest(Kernel) { const canvas = {}; const context = { uniform2fv: () => { if (throws) new Error('This should not get called'); }, getUniformLocation: (name) => { return name; } }; const kernel = new Kernel('function() {}', { canvas, context, output: [1] }); let throws = false; kernel.setUniform2fv('test', [1, 2]); assert.deepEqual(kernel.uniform2fvCache['test'], [1, 2]); throws = true; kernel.setUniform2fv('test', [1, 2]); assert.deepEqual(kernel.uniform2fvCache['test'], [1, 2]); throws = false; kernel.setUniform2fv('test', [2, 3]); assert.deepEqual(kernel.uniform2fvCache['test'], [2, 3]); kernel.destroy(); } test('WebGLKernel.setUniform2fv only calls context when values change', () => { setUniform2fvTest(WebGLKernel); }); test('WebGL2Kernel.setUniform2fv only calls context when values change', () => { setUniform2fvTest(WebGL2Kernel); }); test('HeadlessGLKernel.setUniform2fv only calls context when values change', () => { setUniform2fvTest(HeadlessGLKernel); }); /** * * @param {Kernel} Kernel */ function setUniform3fvTest(Kernel) { const canvas = {}; const context = { uniform3fv: () => { if (throws) new Error('This should not get called'); }, getUniformLocation: (name) => { return name; } }; const kernel = new Kernel('function() {}', { canvas, context, output: [1] }); let throws = false; kernel.setUniform3fv('test', [1, 2, 3]); assert.deepEqual(kernel.uniform3fvCache['test'], [1, 2, 3]); throws = true; kernel.setUniform3fv('test', [1, 2, 3]); assert.deepEqual(kernel.uniform3fvCache['test'], [1, 2, 3]); throws = false; kernel.setUniform3fv('test', [2, 3, 4]); assert.deepEqual(kernel.uniform3fvCache['test'], [2, 3, 4]); kernel.destroy(); } test('WebGLKernel.setUniform3fv only calls context when values change', () => { setUniform3fvTest(WebGLKernel); }); test('WebGL2Kernel.setUniform3fv only calls context when values change', () => { setUniform3fvTest(WebGL2Kernel); }); test('HeadlessGLKernel.setUniform3fv only calls context when values change', () => { setUniform3fvTest(HeadlessGLKernel); }); /** * * @param {Kernel} Kernel */ function setUniform4ivTest(Kernel) { const canvas = {}; const context = { uniform4iv: () => { if (throws) new Error('This should not get called'); }, getUniformLocation: (name) => { return name; } }; const kernel = new Kernel('function() {}', { canvas, context, output: [1] }); let throws = false; kernel.setUniform4iv('test', [1, 2, 3, 4]); assert.deepEqual(kernel.uniform4ivCache['test'], [1, 2, 3, 4]); throws = true; kernel.setUniform4iv('test', [1, 2, 3, 4]); assert.deepEqual(kernel.uniform4ivCache['test'], [1, 2, 3, 4]); throws = false; kernel.setUniform4iv('test', [2, 3, 4, 5]); assert.deepEqual(kernel.uniform4ivCache['test'], [2, 3, 4, 5]); kernel.destroy(); } test('WebGLKernel.setUniform4iv only calls context when values change', () => { setUniform4ivTest(WebGLKernel); }); test('WebGL2Kernel.setUniform4iv only calls context when values change', () => { setUniform4ivTest(WebGL2Kernel); }); test('HeadlessGLKernel.setUniform4iv only calls context when values change', () => { setUniform4ivTest(HeadlessGLKernel); }); /** * * @param {Kernel} Kernel */ function setUniform4fvTest(Kernel) { const canvas = {}; const context = { uniform4fv: () => { if (throws) new Error('This should not get called'); }, getUniformLocation: (name) => { return name; } }; const kernel = new Kernel('function() {}', { canvas, context, output: [1] }); let throws = false; kernel.setUniform4fv('test', [1, 2, 3, 4]); assert.deepEqual(kernel.uniform4fvCache['test'], [1, 2, 3, 4]); throws = true; kernel.setUniform4fv('test', [1, 2, 3, 4]); assert.deepEqual(kernel.uniform4fvCache['test'], [1, 2, 3, 4]); throws = false; kernel.setUniform4fv('test', [2, 3, 4, 5]); assert.deepEqual(kernel.uniform4fvCache['test'], [2, 3, 4, 5]); kernel.destroy(); } test('WebGLKernel.setUniform4fv only calls context when values change', () => { setUniform4fvTest(WebGLKernel); }); test('WebGL2Kernel.setUniform4fv only calls context when values change', () => { setUniform4fvTest(WebGL2Kernel); }); test('HeadlessGLKernel.setUniform4fv only calls context when values change', () => { setUniform4fvTest(HeadlessGLKernel); }); test('functionToIFunction with function', () => { const fn = function name() {}; const result = Kernel.prototype.functionToIGPUFunction(fn); assert.deepEqual(result, { name: 'name', source: fn.toString(), argumentTypes: [], returnType: null }); }); test('functionToIFunction with function and argumentTypes array', () => { const fn = function name(a, b) {}; const argumentTypes = ['number','string']; const result = Kernel.prototype.functionToIGPUFunction(fn, { argumentTypes }); assert.deepEqual(result, { name: 'name', source: fn.toString(), argumentTypes: ['number', 'string'], returnType: null, }); }); test('functionToIFunction with function and argumentTypes object', () => { const fn = function name(a, b) {}; const argumentTypes = { a: 'number', b: 'string' }; const result = Kernel.prototype.functionToIGPUFunction(fn, { argumentTypes }); assert.deepEqual(result, { name: 'name', source: fn.toString(), argumentTypes: ['number', 'string'], returnType: null, }); }); test('functionToIGPUFunction with function and returnType', () => { const fn = function name(a, b) {}; const result = Kernel.prototype.functionToIGPUFunction(fn, { returnType: 'string' }); assert.deepEqual(result, { name: 'name', source: fn.toString(), argumentTypes: [], returnType: 'string', }); }); ================================================ FILE: test/internal/loop-int.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, WebGLFunctionNode, WebGL2FunctionNode } = require('../../src'); describe('internal: loop int'); test('loop int constant output webgl', () => { function kernel(a) { let sum = 0; for (let i = 0; i < this.constants.max; i++) { sum += a[this.thread.x][i]; } return sum; } const functionNode = new WebGLFunctionNode(kernel.toString(), { isRootKernel: true, output: [1], constantTypes: { max: 'Integer' }, argumentTypes: ['Array'], lookupFunctionArgumentBitRatio: () => 4, }); assert.equal( functionNode.toString(), 'void kernel() {' + '\nfloat user_sum=0.0;' + '\nfor (int user_i=0;(user_i { function kernel(a) { let sum = 0; for (let i = 0; i < this.constants.max; i++) { sum += a[this.thread.x][i]; } return sum; } const functionNode = new WebGL2FunctionNode(kernel.toString(), { isRootKernel: true, output: [1], constantTypes: { max: 'Integer' }, argumentTypes: ['Array'], lookupFunctionArgumentBitRatio: () => 4, }); assert.equal( functionNode.toString(), 'void kernel() {' + '\nfloat user_sum=0.0;' + '\nfor (int user_i=0;(user_i { function kernel(a) { let sum = 0; for (let i = 0; i < this.constants.max; i++) { sum += a[this.thread.x][i]; } return sum; } const gpu = new GPU({ mode: 'webgl' }); const output = gpu.createKernel(kernel, { constants: { max: 3 }, output: [1] })([[1,2,3]]); assert.equal( output, 6 ); gpu.destroy(); }); (GPU.isWebGL2Supported ? test : skip)('loop int constant webgl2', () => { function kernel(a) { let sum = 0; for (let i = 0; i < this.constants.max; i++) { sum += a[this.thread.x][i]; } return sum; } const gpu = new GPU({ mode: 'webgl2' }); const output = gpu.createKernel(kernel, { constants: { max: 3 }, output: [1] })([[1,2,3]]); assert.equal( output, 6 ); gpu.destroy(); }); (GPU.isHeadlessGLSupported ? test : skip)('loop int constant headlessgl', () => { function kernel(a) { let sum = 0; for (let i = 0; i < this.constants.max; i++) { sum += a[this.thread.x][i]; } return sum; } const gpu = new GPU({ mode: 'headlessgl' }); const output = gpu.createKernel(kernel, { constants: { max: 3 }, output: [1] })([[1,2,3]]); assert.equal( output, 6 ); gpu.destroy(); }); test('loop int literal output webgl', () => { function kernel(a) { let sum = 0; for (let i = 0; i < 10; i++) { sum += a[this.thread.x][i]; } return sum; } const functionNode = new WebGLFunctionNode(kernel.toString(), { isRootKernel: true, output: [1], argumentTypes: ['Array'], lookupFunctionArgumentBitRatio: () => 4, }); assert.equal( functionNode.toString(), 'void kernel() {' + '\nfloat user_sum=0.0;' + '\nfor (int user_i=0;(user_i<10);user_i++){' + '\nuser_sum+=get32(user_a, user_aSize, user_aDim, 0, threadId.x, user_i);}' + '\n' + '\nkernelResult = user_sum;return;' + '\n}'); }); test('loop int literal output webgl2', () => { function kernel(a) { let sum = 0; for (let i = 0; i < 10; i++) { sum += a[this.thread.x][i]; } return sum; } const functionNode = new WebGL2FunctionNode(kernel.toString(), { isRootKernel: true, output: [1], argumentTypes: ['Array'], lookupFunctionArgumentBitRatio: () => 4, }); assert.equal( functionNode.toString(), 'void kernel() {' + '\nfloat user_sum=0.0;' + '\nfor (int user_i=0;(user_i<10);user_i++){' + '\nuser_sum+=get32(user_a, user_aSize, user_aDim, 0, threadId.x, user_i);}' + '\n' + '\nkernelResult = user_sum;return;' + '\n}'); }); (GPU.isWebGLSupported ? test : skip)('loop int literal webgl', () => { function kernel(a) { let sum = 0; for (let i = 0; i < 3; i++) { sum += a[this.thread.x][i]; } return sum; } const gpu = new GPU({ mode: 'webgl' }); const output = gpu.createKernel(kernel, { output: [1] })([[1,2,3]]); assert.equal( output, 6 ); gpu.destroy(); }); (GPU.isWebGL2Supported ? test : skip)('loop int literal webgl2', () => { function kernel(a) { let sum = 0; for (let i = 0; i < 3; i++) { sum += a[this.thread.x][i]; } return sum; } const gpu = new GPU({ mode: 'webgl2' }); const output = gpu.createKernel(kernel, { output: [1] })([[1,2,3]]); assert.equal( output, 6 ); gpu.destroy(); }); (GPU.isHeadlessGLSupported ? test : skip)('loop int literal headlessgl', () => { function kernel(a) { let sum = 0; for (let i = 0; i < 3; i++) { sum += a[this.thread.x][i]; } return sum; } const gpu = new GPU({ mode: 'headlessgl' }); const output = gpu.createKernel(kernel, { output: [1] })([[1,2,3]]); assert.equal( output, 6 ); gpu.destroy(); }); test('loop int parameter output webgl', () => { function kernel(a, b) { let sum = 0; for (let i = 0; i < a; i++) { sum += b[this.thread.x][i]; } return sum; } const functionNode = new WebGLFunctionNode(kernel.toString(), { isRootKernel: true, output: [1], argumentTypes: ['Number', 'Array'], lookupFunctionArgumentBitRatio: () => 4 }); assert.equal( functionNode.toString(), 'void kernel() {' + '\nfloat user_sum=0.0;' + '\nint user_i=0;' + '\nfor (int safeI=0;safeI { function kernel(a, b) { let sum = 0; for (let i = 0; i < a; i++) { sum += b[this.thread.x][i]; } return sum; } const functionNode = new WebGL2FunctionNode(kernel.toString(), { isRootKernel: true, output: [1], argumentTypes: ['Number', 'Array'], lookupFunctionArgumentBitRatio: () => 4, }); assert.equal( functionNode.toString(), 'void kernel() {' + '\nfloat user_sum=0.0;' + '\nint user_i=0;' + '\nfor (int safeI=0;safeI { function kernel(a, b) { let sum = 0; for (let i = 0; i < a; i++) { sum += b[this.thread.x][i]; } return sum; } const gpu = new GPU({ mode: 'webgl' }); const output = gpu.createKernel(kernel, { output: [1] })(3, [[1,2,3]]); assert.equal( output, 6 ); gpu.destroy(); }); (GPU.isWebGL2Supported ? test : skip)('loop int parameter webgl2', () => { function kernel(a, b) { let sum = 0; for (let i = 0; i < a; i++) { sum += b[this.thread.x][i]; } return sum; } const gpu = new GPU({ mode: 'webgl2' }); const output = gpu.createKernel(kernel, { output: [1] })(3, [[1,2,3]]); assert.equal( output, 6 ); gpu.destroy(); }); (GPU.isHeadlessGLSupported ? test : skip)('loop int parameter headlessgl', () => { function kernel(a, b) { let sum = 0; for (let i = 0; i < a; i++) { sum += b[this.thread.x][i]; } return sum; } const gpu = new GPU({ mode: 'headlessgl' }); const output = gpu.createKernel(kernel, { output: [1] })(3, [[1,2,3]]); assert.equal( output, 6 ); gpu.destroy(); }); (GPU.isWebGLSupported ? test : skip)('loop int dynamic output webgl', () => { function kernel(a) { let sum = 0; for (let i = 0; i < this.output.x; i++) { sum += a[this.thread.x][i]; } return sum; } const gpu = new GPU({ mode: 'webgl' }); const output = gpu.createKernel(kernel, { dynamicOutput: true, output: [1], })([[3]]); assert.deepEqual( Array.from(output), [3] ); gpu.destroy(); }); (GPU.isWebGL2Supported ? test : skip)('loop int dynamic output webgl2', () => { function kernel(a) { let sum = 0; for (let i = 0; i < this.output.x; i++) { sum += a[this.thread.x][i]; } return sum; } const gpu = new GPU({ mode: 'webgl2' }); const output = gpu.createKernel(kernel, { dynamicOutput: true, output: [1] })([[3]]); assert.deepEqual( Array.from(output), [3] ); gpu.destroy(); }); (GPU.isHeadlessGLSupported ? test : skip)('loop int dynamic output headlessgl', () => { function kernel(a) { let sum = 0; for (let i = 0; i < this.output.x; i++) { sum += a[this.thread.x][i]; } return sum; } const gpu = new GPU({ mode: 'headlessgl' }); const output = gpu.createKernel(kernel, { dynamicOutput: true, output: [1], })([[3]]); assert.deepEqual( Array.from(output), [3] ); gpu.destroy(); }); ================================================ FILE: test/internal/loop-max.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, WebGLFunctionNode, WebGL2FunctionNode } = require('../../src'); describe('internal: loop max'); test('loop max output webgl', () => { const functionNode = new WebGLFunctionNode((function(a, b) { let sum = 0; for (let i = 0; i < a; i++) { sum += b[this.thread.x][i]; } return sum; }).toString(), { isRootKernel: true, name: 'kernel', output: [1], argumentTypes: ['Number', 'Array'], lookupFunctionArgumentBitRatio: () => 4, }); assert.equal( functionNode.toString(), 'void kernel() {' + '\nfloat user_sum=0.0;' + '\nint user_i=0;' + '\nfor (int safeI=0;safeI { const functionNode = new WebGL2FunctionNode((function(a, b) { let sum = 0; for (let i = 0; i < a; i++) { sum += b[this.thread.x][i]; } return sum; }).toString(), { isRootKernel: true, name: 'kernel', output: [1], argumentTypes: ['Number', 'Array'], lookupFunctionArgumentBitRatio: () => 4, }); assert.equal( functionNode.toString(), 'void kernel() {' + '\nfloat user_sum=0.0;' + '\nint user_i=0;' + '\nfor (int safeI=0;safeI { const gpu = new GPU({mode: 'webgl'}); const add = gpu.createKernel(function(a, b) { let sum = 0; for (let i = 0; i < a; i++) { sum += b[this.thread.x][i]; } return sum; }).setOutput([1]); const output = add(1, [[1]]); assert.equal( output[0], 1 ); gpu.destroy(); }); (GPU.isWebGL2Supported ? test : skip)('loop max webgl2', () => { const gpu = new GPU({mode: 'webgl2'}); const add = gpu.createKernel(function(a, b) { let sum = 0; for (let i = 0; i < a; i++) { sum += b[this.thread.x][i]; } return sum; }).setOutput([1]); const output = add(1, [[1]]); assert.equal( output[0], 1 ); gpu.destroy(); }); (GPU.isHeadlessGLSupported ? test : skip)('loop max headlessgl', () => { const gpu = new GPU({ mode: 'headlessgl' }); const add = gpu.createKernel(function(a, b) { let sum = 0; for (let i = 0; i < a; i++) { sum += b[this.thread.x][i]; } return sum; }) .setOutput([1]); const output = add(1, [[1]]); assert.equal( output[0], 1 ); gpu.destroy(); }); ================================================ FILE: test/internal/math.random.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const sinon = require('sinon'); const { GPU, plugins: { mathRandom } } = require('../../src'); describe('Math.random() unique'); function mathRandomUnique(mode) { const gpu = new GPU({ mode }); const checkCount = 20; let seed1 = Math.random(); let seed2 = Math.random(); let stub = sinon.stub(mathRandom, 'onBeforeRun').callsFake((kernel) => { kernel.setUniform1f('randomSeed1', seed1); kernel.setUniform1f('randomSeed2', seed2); }); try { gpu.addNativeFunction('getSeed', `highp float getSeed() { return randomSeedShift; }`); const kernel = gpu.createKernel(function () { const v = Math.random(); return getSeed(); }, {output: [1]}); const results = []; for (let i = 0; i < checkCount; i++) { const result = kernel(); assert.ok(results.indexOf(result[0]) === -1, `duplication at index ${results.indexOf(result[0])} from new value ${result[0]}. Values ${JSON.stringify(results)}`); results.push(result[0]); seed2 = result[0]; assert.ok(stub.called); stub.restore(); stub.callsFake((kernel) => { kernel.setUniform1f('randomSeed1', seed1); kernel.setUniform1f('randomSeed2', seed2); }); } } finally { stub.restore(); gpu.destroy(); } } test('unique every time auto', () => { mathRandomUnique(); }); test('unique every time gpu', () => { mathRandomUnique('gpu'); }); (GPU.isWebGLSupported ? test : skip)('unique every time webgl', () => { mathRandomUnique('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('unique every time webgl2', () => { mathRandomUnique('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('unique every time headlessgl', () => { mathRandomUnique('headlessgl'); }); describe('never above 1'); function mathRandomNeverAboveOne(mode) { const gpu = new GPU({ mode }); const checkCount = 20; const checkSource = []; for (let i = 0; i < checkCount; i++) { checkSource.push(`const check${ i } = Math.random();`); } for (let i = 0; i < checkCount; i++) { for (let j = 0; j < checkCount; j++) { if (i === j) continue; checkSource.push(`if (check${i} >= 1) return 1;`); } } const kernel = gpu.createKernel(`function() { ${checkSource.join('\n')} return 0; }`, { output: [1] }); const result = kernel(); assert.ok(result.every(value => value === 0)); } test('never above 1 every time auto', () => { mathRandomNeverAboveOne(); }); test('never above 1 every time gpu', () => { mathRandomNeverAboveOne('gpu'); }); (GPU.isWebGLSupported ? test : skip)('never above 1 every time webgl', () => { mathRandomNeverAboveOne('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('never above 1 every time webgl2', () => { mathRandomNeverAboveOne('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('never above 1 every time headlessgl', () => { mathRandomNeverAboveOne('headlessgl'); }); test('never above 1 every time cpu', () => { mathRandomNeverAboveOne('cpu'); }); ================================================ FILE: test/internal/matrix-multiply-precision.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('internal: matrix multiply precision'); function vanillaMatrixMultiply(a, b) { const width = a.length; const height = b.length; const result = new Array(height); for (let y = 0; y < height; y++) { const row = new Float32Array(width); for (let x = 0; x < width; x++) { let sum = 0; for (let i = 0; i < width; i++) { sum += a[y][i] * b[i][x]; } row[x] = sum; } result[y] = row; } return result; } function filledMatrix(width, height) { const matrix = new Array(height); for (let y = 0; y < height; y++) { const row = matrix[y] = new Float32Array(width); for (let x = 0; x < width; x++) { row[x] = Math.random() * 10; } } return matrix; } function test512x512Matrix(precision, mode) { const width = 512; const height = 512; const a = filledMatrix(width, height); const b = filledMatrix(width, height); const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(a, b) { let sum = 0; for (let i = 0; i < this.constants.width; i++) { sum += a[this.thread.y][i] * b[i][this.thread.x]; } return sum; }, { output: [width, height], precision, constants: { width } }); const cpuResult = vanillaMatrixMultiply(a, b, width, height); const gpuResult = kernel(a, b); let closeEnough = true; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const singleGPUResult = gpuResult[y][x]; const singleCPUResult = cpuResult[y][x]; if (Math.abs(singleGPUResult - singleCPUResult) > 1) { closeEnough = false; break; } } } assert.ok(closeEnough); gpu.destroy(); } test('512x512 unsigned precision auto', () => { test512x512Matrix('unsigned'); }); test('512x512 unsigned precision gpu', () => { test512x512Matrix('unsigned', 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('512x512 unsigned precision webgl', () => { test512x512Matrix('unsigned', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('512x512 unsigned precision webgl2', () => { test512x512Matrix('unsigned', 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('512x512 unsigned precision headlessgl', () => { test512x512Matrix('unsigned', 'headlessgl'); }); test('512x512 unsigned precision cpu', () => { test512x512Matrix('unsigned', 'cpu'); }); function test10x512Matrix(precision, mode) { const width = 10; const height = 512; const a = filledMatrix(width, height); const b = filledMatrix(width, height); const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(a, b) { let sum = 0; for (let i = 0; i < this.constants.width; i++) { sum += a[this.thread.y][i] * b[i][this.thread.x]; } return sum; }, { output: [width, height], precision, constants: { width } }); const cpuResult = vanillaMatrixMultiply(a, b, width, height); const gpuResult = kernel(a, b); let closeEnough = true; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const singleGPUResult = gpuResult[y][x]; const singleCPUResult = cpuResult[y][x]; if (Math.abs(singleGPUResult - singleCPUResult) > 1) { closeEnough = false; break; } } } assert.ok(closeEnough); gpu.destroy(); } test('10x512 unsigned precision auto', () => { test10x512Matrix('unsigned'); }); test('10x512 unsigned precision gpu', () => { test10x512Matrix('unsigned', 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('10x512 unsigned precision webgl', () => { test10x512Matrix('unsigned', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('10x512 unsigned precision webgl2', () => { test10x512Matrix('unsigned', 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('10x512 unsigned precision headlessgl', () => { test10x512Matrix('unsigned', 'headlessgl'); }); test('10x512 unsigned precision cpu', () => { test10x512Matrix('unsigned', 'cpu'); }); (GPU.isSinglePrecisionSupported ? test : skip)('512x512 single precision auto', () => { test512x512Matrix('single'); }); (GPU.isSinglePrecisionSupported ? test : skip)('512x512 single precision gpu', () => { test512x512Matrix('single', 'gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('512x512 single precision webgl', () => { test512x512Matrix('single', 'webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('512x512 single precision webgl2', () => { test512x512Matrix('single', 'webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('512x512 single precision headlessgl', () => { test512x512Matrix('single', 'headlessgl'); }); test('512x512 single precision cpu', () => { test512x512Matrix('single', 'cpu'); }); (GPU.isSinglePrecisionSupported ? test : skip)('10x512 single precision auto', () => { test10x512Matrix('single'); }); (GPU.isSinglePrecisionSupported ? test : skip)('10x512 single precision gpu', () => { test10x512Matrix('single', 'gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('10x512 single precision webgl', () => { test10x512Matrix('single', 'webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('10x512 single precision webgl2', () => { test10x512Matrix('single', 'webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('10x512 single precision headlessgl', () => { test10x512Matrix('single', 'headlessgl'); }); test('10x512 single precision cpu', () => { test10x512Matrix('precision', 'cpu'); }); ================================================ FILE: test/internal/mixed-memory-optimize.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('internal: mixed memory optimize'); function getOffKernel(gpu) { return gpu.createKernel(function(value) { return value[this.thread.x]; }) // getFloatFromSampler2D .setPrecision('single') .setOutput([10]) .setPipeline(true) .setOptimizeFloatMemory(false); } function getOnKernel(gpu) { return gpu.createKernel(function(value) { return value[this.thread.x]; }) // getMemoryOptimized32 .setPrecision('single') .setOutput([10]) .setPipeline(true) .setOptimizeFloatMemory(true); } function offOnOff(mode) { const gpu = new GPU({ mode }); const offKernel = getOffKernel(gpu); const onKernel = getOnKernel(gpu); const value = [1,2,3,4,5,6,7,8,9,10]; const textureResult = offKernel(value); assert.deepEqual(Array.from(textureResult.toArray()), value); assert.deepEqual(Array.from(onKernel(offKernel(value)).toArray()), value); const result = offKernel(onKernel(offKernel(value))).toArray(); assert.deepEqual(Array.from(result), value); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('off on off auto', () => { offOnOff(); }); (GPU.isGPUSupported && GPU.isSinglePrecisionSupported ? test : skip)('off on off gpu', () => { offOnOff('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('off on off webgl', () => { offOnOff('webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('off on off webgl2', () => { offOnOff('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('off on off headlessgl', () => { offOnOff('headlessgl'); }); test('off on off cpu', () => { assert.throws(() => { offOnOff('cpu'); }); }); function onOffOn(mode) { const gpu = new GPU({ mode }); const onKernel = getOnKernel(gpu); const offKernel = getOffKernel(gpu); const value = [1,2,3,4,5,6,7,8,9,10]; const textureResult1 = onKernel(value); const textureResult2 = offKernel(onKernel(value)); const textureResult3 = onKernel(offKernel(onKernel(value))); const result1 = Array.from(textureResult1.toArray()); const result2 = Array.from(textureResult2.toArray()); const result3 = Array.from(textureResult3.toArray()); assert.deepEqual(Array.from(result1), value); assert.deepEqual(Array.from(result2), value); assert.deepEqual(Array.from(result3), value); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('on off on auto', () => { onOffOn(); }); (GPU.isGPUSupported && GPU.isSinglePrecisionSupported ? test : skip)('on off on gpu', () => { onOffOn('gpu'); }); (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('on off on webgl', () => { onOffOn('webgl'); }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('on off on webgl2', () => { onOffOn('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('on off on headlessgl', () => { onOffOn('headlessgl'); }); test('on off on cpu', () => { assert.throws(() => { onOffOn('cpu'); }); }); ================================================ FILE: test/internal/modes.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU, WebGLKernel, WebGL2Kernel, HeadlessGLKernel, CPUKernel } = require('../../src'); describe('internal: modes'); test('modes no settings auto', () => { const gpu = new GPU(); if (GPU.isHeadlessGLSupported) { assert.equal(gpu.Kernel, HeadlessGLKernel); } else if (GPU.isWebGL2Supported) { assert.equal(gpu.Kernel, WebGL2Kernel); } else if (GPU.isWebGLSupported) { assert.equal(gpu.Kernel, WebGLKernel); } }); test('modes null settings auto', () => { const gpu = new GPU(null); if (GPU.isHeadlessGLSupported) { assert.equal(gpu.Kernel, HeadlessGLKernel); } else if (GPU.isWebGL2Supported) { assert.equal(gpu.Kernel, WebGL2Kernel); } else if (GPU.isWebGLSupported) { assert.equal(gpu.Kernel, WebGLKernel); } }); test('modes empty object auto', () => { const gpu = new GPU({}); if (GPU.isHeadlessGLSupported) { assert.equal(gpu.Kernel, HeadlessGLKernel); } else if (GPU.isWebGL2Supported) { assert.equal(gpu.Kernel, WebGL2Kernel); } else if (GPU.isWebGLSupported) { assert.equal(gpu.Kernel, WebGLKernel); } }); test('modes gpu', () => { const gpu = new GPU({ mode: 'gpu' }); if (GPU.isHeadlessGLSupported) { assert.equal(gpu.Kernel, HeadlessGLKernel); } else if (GPU.isWebGL2Supported) { assert.equal(gpu.Kernel, WebGL2Kernel); } else if (GPU.isWebGLSupported) { assert.equal(gpu.Kernel, WebGLKernel); } }); test('modes cpu', () => { const gpu = new GPU({ mode: 'cpu' }); assert.equal(gpu.Kernel, CPUKernel); }); (GPU.isWebGLSupported ? test : skip)('modes webgl', () => { const gpu = new GPU({ mode: 'webgl' }); assert.equal(gpu.Kernel, WebGLKernel); }); (GPU.isWebGL2Supported ? test : skip)('modes webgl2', () => { const gpu = new GPU({ mode: 'webgl2' }); assert.equal(gpu.Kernel, WebGL2Kernel); }); (GPU.isHeadlessGLSupported ? test : skip)('modes headlessgl', () => { const gpu = new GPU({ mode: 'headlessgl' }); assert.equal(gpu.Kernel, HeadlessGLKernel ); }); ================================================ FILE: test/internal/overloading.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('internal: overloading'); // TODO: planned for after v2, overload generated functions so as to cut down on casting // TODO: Complain with incompatible signatures // TODO: Cast actual return type to addFunction's returnType when they do not match. // TODO: Look into test('with Han', () => { const gpu = new GPU(); gpu.addFunction(function dbl(v) { return v + v; }, { returnType: "Float", argumentTypes: { v: "Float" } }); try { const kernel = gpu.createKernel(function(v) { // const output2 = dbl(2); let sum = 0; for (let i = 0; i < 1; i++) { dbl(i); } // const output1 dbl(Math.PI); return sum; }, { output: [1] }); } finally { gpu.destroy(); } assert.ok(1); }); ================================================ FILE: test/internal/precision.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('internal: precision'); (GPU.isWebGLSupported ? test : skip)('WebGL Decimal Precision', () => { const gpu = new GPU({mode: 'webgl'}); const add = gpu.createKernel(function(a, b) { return a + b; }).setOutput([1]); let addResult = add(0.1, 0.2)[0]; assert.equal(addResult.toFixed(7), (0.1 + 0.2).toFixed(7)); const reflectValue = gpu.createKernel(function(a) { return a; }).setOutput([1]); //Just for sanity's sake, recurse the value to see if it spirals out of control for (let i = 0; i < 100; i++) { const newAddResult = reflectValue(addResult)[0]; assert.equal(newAddResult, addResult); addResult = newAddResult; } gpu.destroy(); }); (GPU.isWebGL2Supported ? test : skip)('WebGL2 Decimal Precision', () => { const gpu = new GPU({mode: 'webgl2'}); const add = gpu.createKernel(function(a, b) { return a + b; }).setOutput([1]); let addResult = add(0.1, 0.2)[0]; assert.equal(addResult.toFixed(7), (0.1 + 0.2).toFixed(7)); const reflectValue = gpu.createKernel(function(a) { return a; }).setOutput([1]); //Just for sanity's sake, recurse the value to see if it spirals out of control for (let i = 0; i < 100; i++) { const newAddResult = reflectValue(addResult)[0]; assert.equal(newAddResult, addResult); addResult = newAddResult; } gpu.destroy(); }); (GPU.isHeadlessGLSupported ? test : skip)('HeadlessGL Decimal Precision', () => { const gpu = new GPU({mode: 'headlessgl'}); const add = gpu.createKernel(function(a, b) { return a + b; }).setOutput([1]); let addResult = add(0.1, 0.2)[0]; assert.equal(addResult.toFixed(7), (0.1 + 0.2).toFixed(7)); const reflectValue = gpu.createKernel(function(a) { return a; }).setOutput([1]); //Just for sanity's sake, recurse the value to see if it spirals out of control for (let i = 0; i < 100; i++) { const newAddResult = reflectValue(addResult)[0]; assert.equal(newAddResult, addResult); addResult = newAddResult; } gpu.destroy(); }); ================================================ FILE: test/internal/recycling.js ================================================ const sinon = require('sinon'); const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('internal: recycling'); function testImmutableKernelTextureRecycling(precision, mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(v) { return v[0] + 1; }, { output: [1], pipeline: true, immutable: true, precision, }); let result = kernel([0]); const newTextureSpy = sinon.spy(kernel.texture.constructor.prototype, 'newTexture'); for (let i = 0; i < 10; i++) { let lastResult = result; result = kernel(result); lastResult.delete(); } assert.deepEqual(result.toArray(), new Float32Array([11])); assert.equal(newTextureSpy.callCount, 1); assert.equal(gpu.kernels.length, 2); newTextureSpy.restore(); gpu.destroy(); } test('immutable single precision kernel auto', () => { testImmutableKernelTextureRecycling('single') }); test('immutable single precision kernel gpu', () => { testImmutableKernelTextureRecycling('single', 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('immutable single precision kernel webgl', () => { testImmutableKernelTextureRecycling('single', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('immutable single precision kernel webgl2', () => { testImmutableKernelTextureRecycling('single', 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('immutable single precision kernel headlessgl', () => { testImmutableKernelTextureRecycling('single', 'headlessgl'); }); test('immutable unsigned precision kernel auto', () => { testImmutableKernelTextureRecycling('unsigned') }); test('immutable unsigned precision kernel gpu', () => { testImmutableKernelTextureRecycling('unsigned', 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('immutable unsigned precision kernel webgl', () => { testImmutableKernelTextureRecycling('unsigned', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('immutable unsigned precision kernel webgl2', () => { testImmutableKernelTextureRecycling('unsigned', 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('immutable unsigned precision headlessgl', () => { testImmutableKernelTextureRecycling('unsigned', 'headlessgl'); }); function testImmutableMappedKernelTextureRecycling(precision, mode) { const gpu = new GPU({ mode }); function oneOff(value) { return value; } const kernel = gpu.createKernelMap({ oneOffValue: oneOff },function(value1, value2) { oneOff(value2[0] - 1); return value1[0] + 1; }, { output: [1], pipeline: true, immutable: true, precision, }); let map = kernel([0], [11]); const newTextureSpy = sinon.spy(kernel.texture.constructor.prototype, 'newTexture'); for (let i = 0; i < 10; i++) { let lastResults = map; map = kernel(map.result, map.oneOffValue); lastResults.result.delete(); lastResults.oneOffValue.delete(); } assert.deepEqual(map.result.toArray(), new Float32Array([11])); assert.deepEqual(map.oneOffValue.toArray(), new Float32Array([0])); assert.equal(newTextureSpy.callCount, 2); assert.equal(gpu.kernels.length, 2); newTextureSpy.restore(); gpu.destroy(); } test('immutable single precision mapped kernel auto', () => { testImmutableMappedKernelTextureRecycling('single') }); test('immutable single precision mapped kernel gpu', () => { testImmutableMappedKernelTextureRecycling('single', 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('immutable single precision mapped kernel webgl', () => { testImmutableMappedKernelTextureRecycling('single', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('immutable single precision mapped kernel webgl2', () => { testImmutableMappedKernelTextureRecycling('single', 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('immutable single precision mapped kernel headlessgl', () => { testImmutableMappedKernelTextureRecycling('single', 'headlessgl'); }); test('immutable unsigned precision mapped kernel auto', () => { testImmutableMappedKernelTextureRecycling('unsigned') }); test('immutable unsigned precision mapped kernel gpu', () => { testImmutableMappedKernelTextureRecycling('unsigned', 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('immutable unsigned precision mapped kernel webgl', () => { testImmutableMappedKernelTextureRecycling('unsigned', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('immutable unsigned precision mapped kernel webgl2', () => { testImmutableMappedKernelTextureRecycling('unsigned', 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('immutable unsigned precision mapped kernel headlessgl', () => { testImmutableMappedKernelTextureRecycling('unsigned', 'headlessgl'); }); function testImmutableTextureDelete(precision, done, mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return this.thread.x; }, { output: [1], pipeline: true, immutable: true, precision, }); const result = kernel(); assert.equal(result.texture._refs, 2); const clone1 = result.clone(); assert.equal(result.texture._refs, 3); const clone2 = result.clone(); assert.equal(result.texture._refs, 4); const clone3 = result.clone(); assert.equal(result.texture._refs, 5); const clone4 = result.clone(); assert.equal(result.texture._refs, 6); const clone5 = result.clone(); assert.equal(result.texture._refs, 7); clone1.delete(); assert.equal(result.texture._refs, 6); clone2.delete(); assert.equal(result.texture._refs, 5); clone3.delete(); assert.equal(result.texture._refs, 4); clone4.delete(); assert.equal(result.texture._refs, 3); clone5.delete(); assert.equal(result.texture._refs, 2); result.delete(); assert.equal(result.texture._refs, 1); const spy = sinon.spy(kernel.kernel.context, 'deleteTexture'); gpu.destroy() .then(() => { assert.equal(result.texture._refs, 0); assert.equal(spy.callCount, 1); assert.ok(spy.calledWith(result.texture)); spy.restore(); done(); }); } test('immutable single precision texture delete auto', t => { testImmutableTextureDelete('single', t.async()); }); test('immutable single precision texture delete gpu', t => { testImmutableTextureDelete('single', t.async(), 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('immutable single precision texture delete webgl', t => { testImmutableTextureDelete('single', t.async(), 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('immutable single precision texture delete webgl2', t => { testImmutableTextureDelete('single', t.async(), 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('immutable single precision texture delete headlessgl', t => { testImmutableTextureDelete('single', t.async(), 'headlessgl'); }); test('immutable unsigned precision texture delete auto', t => { testImmutableTextureDelete('unsigned', t.async() ); }); test('immutable unsigned precision texture delete gpu', t => { testImmutableTextureDelete('unsigned', t.async(), 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('immutable unsigned precision texture delete webgl', t => { testImmutableTextureDelete('unsigned', t.async(), 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('immutable unsigned precision texture delete webgl2', t => { testImmutableTextureDelete('unsigned', t.async(), 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('immutable unsigned precision texture delete headlessgl', t => { testImmutableTextureDelete('unsigned', t.async(), 'headlessgl'); }); function testImmutableKernelTextureDoesNotLeak(precision, done, mode) { const gpu = new GPU({ mode }); const toTexture = gpu.createKernel(function(value) { return value[this.thread.x]; }, { output: [1], pipeline: true, immutable: true, precision, }); const one = toTexture([1]); assert.equal(one.texture._refs, 2); // one's texture will be used in two places at first, in one and toTexture.texture assert.equal(toTexture.texture.texture, one.texture); // very important, a clone was mode, but not a deep clone assert.notEqual(one, toTexture.texture); const two = toTexture([2]); assert.equal(one.texture._refs, 1); // was tracked on toTexture.texture, and deleted assert.equal(toTexture.texture.texture, two.texture); assert.notEqual(toTexture.texture.texture, one.texture); assert.equal(two.texture._refs, 2); one.delete(); two.delete(); assert.equal(one.texture._refs, 0); assert.equal(two.texture._refs, 1); // still used by toTexture.texture two.delete(); // already deleted assert.equal(two.texture._refs, 1); // still used by toTexture gpu.destroy() .then(() => { assert.equal(two.texture._refs, 0); done(); }); } test('immutable unsigned precision kernel.texture does not leak auto', t => { testImmutableKernelTextureDoesNotLeak('unsigned', t.async()); }); test('immutable unsigned precision kernel.texture does not leak gpu', t => { testImmutableKernelTextureDoesNotLeak('unsigned', t.async(), 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('immutable unsigned precision kernel.texture does not leak webgl', t => { testImmutableKernelTextureDoesNotLeak('unsigned', t.async(), 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('immutable unsigned precision kernel.texture does not leak webgl2', t => { testImmutableKernelTextureDoesNotLeak('unsigned', t.async(), 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('immutable unsigned precision kernel.texture does not leak headlessgl', t => { testImmutableKernelTextureDoesNotLeak('unsigned', t.async(), 'headlessgl'); }); test('immutable single precision kernel.texture does not leak auto', t => { testImmutableKernelTextureDoesNotLeak('single', t.async()); }); test('immutable single precision kernel.texture does not leak gpu', t => { testImmutableKernelTextureDoesNotLeak('single', t.async(), 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('immutable single precision kernel.texture does not leak webgl', t => { testImmutableKernelTextureDoesNotLeak('single', t.async(), 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('immutable single precision kernel.texture does not leak webgl2', t => { testImmutableKernelTextureDoesNotLeak('single', t.async(), 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('immutable single precision kernel.texture does not leak headlessgl', t => { testImmutableKernelTextureDoesNotLeak('single', t.async(), 'headlessgl'); }); function testImmutableKernelMappedTexturesDoesNotLeak(precision, done, mode) { const gpu = new GPU({ mode }); function saveValue(value) { return value; } const toTextures = gpu.createKernelMap([saveValue],function(value1, value2) { saveValue(value1[this.thread.x]); return value2[this.thread.x]; }, { output: [1], pipeline: true, immutable: true, precision, }); const { result: one, 0: two } = toTextures([1], [2]); assert.equal(one.texture._refs, 2); // one's texture will be used in two places at first, in one and toTexture.texture assert.equal(two.texture._refs, 2); // one's texture will be used in two places at first, in one and toTexture.mappedTextures[0] assert.equal(toTextures.texture.texture, one.texture); // very important, a clone was mode, but not a deep clone assert.equal(toTextures.mappedTextures[0].texture, two.texture); // very important, a clone was mode, but not a deep clone assert.notEqual(one, toTextures.texture); assert.notEqual(one, toTextures.mappedTextures[0]); const { result: three, 0: four } = toTextures([3], [4]); assert.equal(one.texture._refs, 1); // was tracked on toTexture.texture, and deleted assert.equal(two.texture._refs, 1); // was tracked on toTexture.mappedTextures[0], and deleted assert.equal(toTextures.texture.texture, three.texture); assert.equal(toTextures.mappedTextures[0].texture, four.texture); assert.notEqual(toTextures.texture.texture, one.texture); assert.notEqual(toTextures.mappedTextures[0].texture, two.texture); assert.equal(three.texture._refs, 2); assert.equal(four.texture._refs, 2); one.delete(); two.delete(); three.delete(); four.delete(); assert.equal(one.texture._refs, 0); assert.equal(two.texture._refs, 0); assert.equal(three.texture._refs, 1); // still used by toTexture.texture assert.equal(four.texture._refs, 1); // still used by toTexture.mappedTextures[0] three.delete(); // already deleted four.delete(); // already deleted assert.equal(three.texture._refs, 1); // still used by toTexture assert.equal(four.texture._refs, 1); // still used by toTexture gpu.destroy() .then(() => { assert.equal(one.texture._refs, 0); assert.equal(two.texture._refs, 0); assert.equal(three.texture._refs, 0); assert.equal(four.texture._refs, 0); done(); }); } test('immutable unsigned precision kernel.mappedTextures does not leak auto', t => { testImmutableKernelMappedTexturesDoesNotLeak('unsigned', t.async()); }); test('immutable unsigned precision kernel.mappedTextures does not leak gpu', t => { testImmutableKernelMappedTexturesDoesNotLeak('unsigned', t.async(), 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('immutable unsigned precision kernel.mappedTextures does not leak webgl', t => { testImmutableKernelMappedTexturesDoesNotLeak('unsigned', t.async(), 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('immutable unsigned precision kernel.mappedTextures does not leak webgl2', t => { testImmutableKernelMappedTexturesDoesNotLeak('unsigned', t.async(), 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('immutable unsigned precision kernel.mappedTextures does not leak headlessgl', t => { testImmutableKernelMappedTexturesDoesNotLeak('unsigned', t.async(), 'headlessgl'); }); test('immutable single precision kernel.mappedTextures does not leak auto', t => { testImmutableKernelMappedTexturesDoesNotLeak('single', t.async()); }); test('immutable single precision kernel.mappedTextures does not leak gpu', t => { testImmutableKernelMappedTexturesDoesNotLeak('single', t.async(), 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('immutable single precision kernel.mappedTextures does not leak webgl', t => { testImmutableKernelMappedTexturesDoesNotLeak('single', t.async(), 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('immutable single precision kernel.mappedTextures does not leak webgl2', t => { testImmutableKernelMappedTexturesDoesNotLeak('single', t.async(), 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('immutable single precision kernel.mappedTextures does not leak headlessgl', t => { testImmutableKernelMappedTexturesDoesNotLeak('single', t.async(), 'headlessgl'); }); function testCloning(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[0] + 1; }, { output: [1], pipeline: true }); const texture = kernel([1]); const { size } = texture; // set size to something unique, for tracking texture.size = [size[0] + 0.1, size[1] + 0.2]; texture.cloneTexture(); assert.equal(texture._framebuffer.width, size[0] + 0.1); assert.equal(texture._framebuffer.height, size[1] + 0.2); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('cloning sets up framebuffer with correct size webgl', () => { testCloning('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('cloning sets up framebuffer with correct size webgl2', () => { testCloning('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('cloning sets up framebuffer with correct size headlessgl', () => { testCloning('headlessgl'); }); function testMutableLeak(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return 1; }, { output: [1], pipeline: true }); kernel.build(); const cloneTextureSpy = sinon.spy(kernel.texture.constructor.prototype, 'beforeMutate'); const texture1 = kernel(); const texture2 = kernel(); assert.equal(cloneTextureSpy.callCount, 0); assert.equal(texture1.texture._refs, 1); assert.ok(texture1 === texture2); cloneTextureSpy.restore(); gpu.destroy(); } test('test mutable leak auto', () => { testMutableLeak(); }); test('test mutable leak gpu', () => { testMutableLeak('gpu'); }); (GPU.isWebGLSupported ? test : skip)('test mutable leak webgl', () => { testMutableLeak('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('test mutable leak webgl2', () => { testMutableLeak('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('test mutable leak headlessgl', () => { testMutableLeak('headlessgl'); }); describe('internal: cpu recycling behaviour'); test('recycle CPU array', () => { const gpu = new GPU({ mode: 'cpu' }); const kernel = gpu.createKernel(function(v) { return this.thread.x + v[0]; }, { output: [1], pipeline: true, immutable: false, }); const result1 = kernel(new Float32Array([1])); assert.equal(result1[0], 1); const result2 = kernel(new Float32Array([2])); assert.equal(result1[0], 2); assert.equal(result1, result2); gpu.destroy(); }); test('recycle CPU matrix', () => { const gpu = new GPU({ mode: 'cpu' }); const kernel = gpu.createKernel(function(v) { return (this.thread.x + (this.thread.y * this.output.x)) + v[0]; }, { output: [2, 2], pipeline: true, immutable: false, }); const result1 = kernel(new Float32Array([1])); assert.equal(result1[0][0], 1); assert.equal(result1[0][1], 2); assert.equal(result1[1][0], 3); assert.equal(result1[1][1], 4); const result2 = kernel(new Float32Array([2])); assert.equal(result1[0][0], 2); assert.equal(result1[0][1], 3); assert.equal(result1[1][0], 4); assert.equal(result1[1][1], 5); assert.equal(result1, result2); gpu.destroy(); }); test('recycle CPU cube', () => { const gpu = new GPU({ mode: 'cpu' }); const kernel = gpu.createKernel(function(v) { return (this.thread.x + (this.thread.y * this.output.x) + (this.thread.z * this.output.y * this.output.x)) + v[0]; }, { output: [2, 2, 2], pipeline: true, immutable: false, }); const result1 = kernel(new Float32Array([1])); assert.equal(result1[0][0][0], 1); assert.equal(result1[0][0][1], 2); assert.equal(result1[0][1][0], 3); assert.equal(result1[0][1][1], 4); assert.equal(result1[1][0][0], 5); assert.equal(result1[1][0][1], 6); assert.equal(result1[1][1][0], 7); assert.equal(result1[1][1][1], 8); const result2 = kernel(new Float32Array([2])); assert.equal(result1[0][0][0], 2); assert.equal(result1[0][0][1], 3); assert.equal(result1[0][1][0], 4); assert.equal(result1[0][1][1], 5); assert.equal(result1[1][0][0], 6); assert.equal(result1[1][0][1], 7); assert.equal(result1[1][1][0], 8); assert.equal(result1[1][1][1], 9); assert.equal(result1, result2); gpu.destroy(); }); describe('internal: cpu non-recycling behaviour'); test('non-recycle CPU array', () => { const gpu = new GPU({ mode: 'cpu' }); const kernel = gpu.createKernel(function(v) { return this.thread.x + v[0]; }, { output: [1], pipeline: true, immutable: true, }); const result1 = kernel(new Float32Array([1])); assert.equal(result1[0], 1); const result2 = kernel(new Float32Array([2])); assert.equal(result1[0], 1); assert.equal(result2[0], 2); assert.notEqual(result1, result2); gpu.destroy(); }); test('non-recycle CPU matrix', () => { const gpu = new GPU({ mode: 'cpu' }); const kernel = gpu.createKernel(function(v) { return (this.thread.x + (this.thread.y * this.output.x)) + v[0]; }, { output: [2, 2], pipeline: true, immutable: true, }); const result1 = kernel(new Float32Array([1])); assert.equal(result1[0][0], 1); assert.equal(result1[0][1], 2); assert.equal(result1[1][0], 3); assert.equal(result1[1][1], 4); const result2 = kernel(new Float32Array([2])); // untouched assert.equal(result1[0][0], 1); assert.equal(result1[0][1], 2); assert.equal(result1[1][0], 3); assert.equal(result1[1][1], 4); assert.equal(result2[0][0], 2); assert.equal(result2[0][1], 3); assert.equal(result2[1][0], 4); assert.equal(result2[1][1], 5); assert.notEqual(result1, result2); gpu.destroy(); }); test('non-recycle CPU cube', () => { const gpu = new GPU({ mode: 'cpu' }); const kernel = gpu.createKernel(function(v) { return (this.thread.x + (this.thread.y * this.output.x) + (this.thread.z * this.output.y * this.output.x)) + v[0]; }, { output: [2, 2, 2], pipeline: true, immutable: true, }); const result1 = kernel(new Float32Array([1])); assert.equal(result1[0][0][0], 1); assert.equal(result1[0][0][1], 2); assert.equal(result1[0][1][0], 3); assert.equal(result1[0][1][1], 4); assert.equal(result1[1][0][0], 5); assert.equal(result1[1][0][1], 6); assert.equal(result1[1][1][0], 7); assert.equal(result1[1][1][1], 8); const result2 = kernel(new Float32Array([2])); // untouched assert.equal(result1[0][0][0], 1); assert.equal(result1[0][0][1], 2); assert.equal(result1[0][1][0], 3); assert.equal(result1[0][1][1], 4); assert.equal(result1[1][0][0], 5); assert.equal(result1[1][0][1], 6); assert.equal(result1[1][1][0], 7); assert.equal(result1[1][1][1], 8); assert.equal(result2[0][0][0], 2); assert.equal(result2[0][0][1], 3); assert.equal(result2[0][1][0], 4); assert.equal(result2[0][1][1], 5); assert.equal(result2[1][0][0], 6); assert.equal(result2[1][0][1], 7); assert.equal(result2[1][1][0], 8); assert.equal(result2[1][1][1], 9); assert.notEqual(result1, result2); gpu.destroy(); }); function testSameSourceDestinationFromResultThrows(error, precision, mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.x] + 1; }, { output: [1], pipeline: true, immutable: false, precision, }); let result = kernel([0]); assert.equal((result.toArray ? result.toArray() : result)[0], 1); assert.throws(() => kernel(result), error); gpu.destroy(); } const gpuError = new Error('Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()'); const cpuError = new Error('Source and destination arrays are the same. Use immutable = true'); test('single precision same source and destination from result mutable throws auto', () => { testSameSourceDestinationFromResultThrows(gpuError,'single'); }); test('single precision same source and destination from result mutable throws gpu', () => { testSameSourceDestinationFromResultThrows(gpuError, 'single', 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('single precision same source and destination from result mutable throws webgl', () => { testSameSourceDestinationFromResultThrows(gpuError, 'single', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('single precision same source and destination from result mutable throws webgl2', () => { testSameSourceDestinationFromResultThrows(gpuError, 'single', 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('single precision same source and destination from result mutable throws headlessgl', () => { testSameSourceDestinationFromResultThrows(gpuError, 'single', 'headlessgl'); }); test('single precision same source and destination from result mutable throws cpu', () => { testSameSourceDestinationFromResultThrows(cpuError, 'single', 'cpu'); }); test('unsigned precision same source and destination from result mutable throws auto', () => { testSameSourceDestinationFromResultThrows(gpuError, 'unsigned'); }); test('unsigned precision same source and destination from result mutable throws gpu', () => { testSameSourceDestinationFromResultThrows(gpuError, 'unsigned', 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('unsigned precision same source and destination from result mutable throws webgl', () => { testSameSourceDestinationFromResultThrows(gpuError, 'unsigned', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('unsigned precision same source and destination from result mutable throws webgl2', () => { testSameSourceDestinationFromResultThrows(gpuError, 'unsigned', 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('unsigned precision same source and destination from result mutable throws headlessgl', () => { testSameSourceDestinationFromResultThrows(gpuError, 'unsigned', 'headlessgl'); }); test('unsigned precision same source and destination from result mutable throws cpu', () => { testSameSourceDestinationFromResultThrows(cpuError, 'unsigned', 'cpu'); }); function testSameSourceDestinationFromMappedResultThrows(error, precision, mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernelMap({ mappedResult: function map(v) { return v; } }, function(value) { return map(value[this.thread.x] + 1); }, { output: [1], pipeline: true, immutable: false, precision, }); let { result, mappedResult } = kernel([0]); assert.equal((mappedResult.toArray ? mappedResult.toArray() : mappedResult)[0], 1); assert.throws(() => kernel(mappedResult), error); assert.throws(() => kernel(result), error); gpu.destroy(); } test('single precision same source and destination from mapped result mutable throws auto', () => { testSameSourceDestinationFromMappedResultThrows(gpuError, 'single'); }); test('single precision same source and destination from mapped result mutable throws gpu', () => { testSameSourceDestinationFromMappedResultThrows(gpuError, 'single', 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('single precision same source and destination from mapped result mutable throws webgl', () => { testSameSourceDestinationFromMappedResultThrows(gpuError, 'single', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('single precision same source and destination from mapped result mutable throws webgl2', () => { testSameSourceDestinationFromMappedResultThrows(gpuError, 'single', 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('single precision same source and destination from mapped result mutable throws headlessgl', () => { testSameSourceDestinationFromMappedResultThrows(gpuError, 'single', 'headlessgl'); }); test('single precision same source and destination from mapped result mutable throws cpu', () => { testSameSourceDestinationFromMappedResultThrows(cpuError, 'single', 'cpu'); }); test('unsigned precision same source and destination from mapped result mutable throws auto', () => { testSameSourceDestinationFromMappedResultThrows(gpuError, 'unsigned'); }); test('unsigned precision same source and destination from mapped result mutable throws gpu', () => { testSameSourceDestinationFromMappedResultThrows(gpuError, 'unsigned', 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('unsigned precision same source and destination from mapped result mutable throws webgl', () => { testSameSourceDestinationFromMappedResultThrows(gpuError, 'unsigned', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('unsigned precision same source and destination from mapped result mutable throws webgl2', () => { testSameSourceDestinationFromMappedResultThrows(gpuError, 'unsigned', 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('unsigned precision same source and destination from mapped result mutable throws headlessgl', () => { testSameSourceDestinationFromMappedResultThrows(gpuError, 'unsigned', 'headlessgl'); }); test('unsigned precision same source and destination from mapped result mutable throws cpu', () => { testSameSourceDestinationFromMappedResultThrows(cpuError, 'unsigned', 'cpu'); }); function testOutputTextureIsClonedWhenRecompiling(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.x] + 1; }, { output: [1], immutable: true, pipeline: true }); const result1 = kernel([1]); assert.equal(result1.toArray()[0], 2); const result2 = kernel(result1); result1.delete(); assert.equal(result2.toArray()[0], 3); result2.delete(); const result3 = kernel([3]); assert.equal(result3.toArray()[0], 4); const result4 = kernel(result3); result3.delete(); assert.equal(result4.toArray()[0], 5); result4.delete(); gpu.destroy(); } test('output texture is cloned when recompiling auto', () => { testOutputTextureIsClonedWhenRecompiling(); }); test('output texture is cloned when recompiling gpu', () => { testOutputTextureIsClonedWhenRecompiling('gpu'); }); (GPU.isWebGLSupported ? test : skip)('output texture is cloned when recompiling webgl', () => { testOutputTextureIsClonedWhenRecompiling('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('output texture is cloned when recompiling webgl2', () => { testOutputTextureIsClonedWhenRecompiling('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('output texture is cloned when recompiling headlessgl', () => { testOutputTextureIsClonedWhenRecompiling('headlessgl'); }); function testMappedOutputTextureIsClonedWhenRecompiling(mode) { const gpu = new GPU({ mode }); function setValue(value) { return value * 10; } const kernel = gpu.createKernelMap({ value: setValue, },function(value1, value2) { setValue(value2[this.thread.x]); return value1[this.thread.x] + 1; }, { output: [1], immutable: true, pipeline: true }); const map1 = kernel([1], [1]); assert.equal(map1.result.toArray()[0], 2); assert.equal(map1.value.toArray()[0], 10); const map2 = kernel(map1.result, map1.value); map1.result.delete(); map1.value.delete(); assert.equal(map2.result.toArray()[0], 3); assert.equal(map2.value.toArray()[0], 100); map2.value.delete(); map2.result.delete(); const map3 = kernel([3], [3]); assert.equal(map3.result.toArray()[0], 4); assert.equal(map3.value.toArray()[0], 30); const map4 = kernel(map3.result, map3.value); map3.result.delete(); map3.value.delete(); assert.equal(map4.result.toArray()[0], 5); assert.equal(map4.value.toArray()[0], 300); map4.result.delete(); map4.value.delete(); gpu.destroy(); } test('mapped output texture is cloned when recompiling auto', () => { testMappedOutputTextureIsClonedWhenRecompiling(); }); test('mapped output texture is cloned when recompiling gpu', () => { testMappedOutputTextureIsClonedWhenRecompiling('gpu'); }); (GPU.isWebGLSupported ? test : skip)('mapped output texture is cloned when recompiling webgl', () => { testMappedOutputTextureIsClonedWhenRecompiling('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('mapped output texture is cloned when recompiling webgl2', () => { testMappedOutputTextureIsClonedWhenRecompiling('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('mapped output texture is cloned when recompiling headlessgl', () => { testMappedOutputTextureIsClonedWhenRecompiling('headlessgl'); }); ================================================ FILE: test/internal/texture-index.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('internal: texture index'); function createKernelWithNumberConstants(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return this.constants.v1 + this.constants.v2; }, { output: [1], constants: { v1: 1, v2: 1 } }); kernel(); assert.equal(kernel.kernelConstants.length, 2); assert.equal(kernel.kernelConstants[0].contextHandle, null); assert.equal(kernel.kernelConstants[1].contextHandle, null); assert.equal(kernel.kernelArguments.length, 0); gpu.destroy(); } test('createKernel with number constants auto', () => { createKernelWithNumberConstants(); }); (GPU.isWebGL2Supported ? test : skip)('createKernel with number constants gpu', () => { createKernelWithNumberConstants('gpu'); }); (GPU.isWebGL2Supported ? test : skip)('createKernel with number constants webgl', () => { createKernelWithNumberConstants('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('createKernel with number constants webgl2', () => { createKernelWithNumberConstants('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('createKernel with number constants headlessgl', () => { createKernelWithNumberConstants('headlessgl'); }); function createKernelWithArrayConstants(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return this.constants.v1[this.thread.x] + this.constants.v2[this.thread.x]; }, { output: [1], constants: { v1: [1], v2: [1] } }); kernel(); const gl = kernel.context; assert.equal(kernel.kernelConstants.length, 2); assert.equal(kernel.kernelConstants[0].contextHandle, gl.TEXTURE0); assert.equal(kernel.kernelConstants[1].contextHandle, gl.TEXTURE0 + 1); assert.equal(kernel.kernelArguments.length, 0); gpu.destroy(); } test('createKernel with array constants auto', () => { createKernelWithArrayConstants(); }); (GPU.isGPUSupported ? test : skip)('createKernel with array constants gpu', () => { createKernelWithArrayConstants('gpu'); }); (GPU.isWebGLSupported ? test : skip)('createKernel with array constants webgl', () => { createKernelWithArrayConstants('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('createKernel with array constants webgl2', () => { createKernelWithArrayConstants('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('createKernel with array constants headlessgl', () => { createKernelWithArrayConstants('headlessgl'); }); function creatKernelWithNumberConstantsAndArrayArguments(mode) { const gpu = new GPU({ mode }); const textureGetter = gpu.createKernel(function() { return 1; }, { output: [1], pipeline: true }); const texture1 = textureGetter(); const texture2 = textureGetter(); const kernel = gpu.createKernel(function(value1, value2) { return value1[this.thread.x] + value2[this.thread.x] + this.constants.v1 + this.constants.v2; }, { output: [1], constants: { v1: 1, v2: 1 } }); const output = kernel(texture1, texture2); const gl = kernel.context; assert.equal(kernel.kernelConstants.length, 2); assert.equal(kernel.kernelConstants[0].contextHandle, null); assert.equal(kernel.kernelConstants[1].contextHandle, null); assert.equal(kernel.kernelArguments.length, 2); assert.equal(kernel.kernelArguments[0].contextHandle, gl.TEXTURE0); assert.equal(kernel.kernelArguments[1].contextHandle, gl.TEXTURE0 + 1); gpu.destroy(); } test('createKernel with number constants & array arguments auto', () => { creatKernelWithNumberConstantsAndArrayArguments(); }); (GPU.isGPUSupported ? test : skip)('createKernel with number constants & array arguments gpu', () => { creatKernelWithNumberConstantsAndArrayArguments('gpu'); }); (GPU.isWebGLSupported ? test : skip)('createKernel with number constants & array arguments webgl', () => { creatKernelWithNumberConstantsAndArrayArguments('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('createKernel with number constants & array arguments webgl2', () => { creatKernelWithNumberConstantsAndArrayArguments('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('createKernel with number constants & array arguments headlessgl', () => { creatKernelWithNumberConstantsAndArrayArguments('headlessgl'); }); function createKernelMapWithArrayConstantsAndTextureArguments(mode) { const gpu = new GPU({ mode }); function calcValue1(v) { return v; } function calcValue2(v) { return v; } const textureGetter = gpu.createKernel(function() { return 1; }, { output: [1], pipeline: true }); const texture1 = textureGetter(); const texture2 = textureGetter(); const kernel = gpu.createKernelMap({ mappedValue1: calcValue1, mappedValue2: calcValue2, }, function(value1, value2) { return calcValue1(value1[this.thread.x] + value2[this.thread.x]) + calcValue2(this.constants.v1[this.thread.x] + this.constants.v2[this.thread.x]); }, { output: [1], constants: { v1: [1], v2: [1] } }); kernel(texture1, texture2); const gl = kernel.context; assert.equal(kernel.kernelConstants.length, 2); assert.equal(kernel.kernelConstants[0].contextHandle, gl.TEXTURE0); assert.equal(kernel.kernelConstants[1].contextHandle, gl.TEXTURE0 + 1); assert.equal(kernel.kernelArguments.length, 2); assert.equal(kernel.kernelArguments[0].contextHandle, gl.TEXTURE0 + 2); assert.equal(kernel.kernelArguments[1].contextHandle, gl.TEXTURE0 + 3); gpu.destroy(); } test('createKernelMap with array constants & texture arguments auto', () => { createKernelMapWithArrayConstantsAndTextureArguments(); }); (GPU.isGPUSupported ? test : skip)('createKernelMap with array constants & texture arguments gpu', () => { createKernelMapWithArrayConstantsAndTextureArguments('gpu'); }); (GPU.isWebGLSupported ? test : skip)('createKernelMap with array constants & texture arguments webgl', () => { createKernelMapWithArrayConstantsAndTextureArguments('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('createKernelMap with array constants & texture arguments webgl2', () => { createKernelMapWithArrayConstantsAndTextureArguments('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('createKernelMap with array constants & texture arguments headlessgl', () => { createKernelMapWithArrayConstantsAndTextureArguments('headlessgl'); }); ================================================ FILE: test/internal/underscores.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('internal: underscores'); function testNumberArgument(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value_1) { return value_1; }, { output: [1], }); assert.equal(kernel(1)[0], 1); gpu.destroy(); } test('number argument auto', () => { testNumberArgument(); }); test('number argument gpu', () => { testNumberArgument('gpu'); }); (GPU.isWebGLSupported ? test : skip)('number argument webgl', () => { testNumberArgument('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('number argument webgl2', () => { testNumberArgument('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('number argument headlessgl', () => { testNumberArgument('headlessgl'); }); test('number argument cpu', () => { testNumberArgument('cpu'); }); function testArrayArgument(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value_1) { return value_1[this.thread.x]; }, { output: [1], }); assert.equal(kernel([1])[0], 1); gpu.destroy(); } test('array argument auto', () => { testArrayArgument(); }); test('array argument gpu', () => { testArrayArgument('gpu'); }); (GPU.isWebGLSupported ? test : skip)('array argument webgl', () => { testArrayArgument('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('array argument webgl2', () => { testArrayArgument('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('array argument headlessgl', () => { testArrayArgument('headlessgl'); }); test('array argument cpu', () => { testArrayArgument('cpu'); }); function testTextureArgument(mode) { const gpu = new GPU({ mode }); const texture = gpu.createKernel(function() { return 1; }, { output: [1], pipeline: true })(); const kernel = gpu.createKernel(function(value_1) { return value_1[this.thread.x]; }, { output: [1], }); assert.equal(kernel(texture)[0], 1); gpu.destroy(); } test('texture argument auto', () => { testTextureArgument(); }); test('texture argument gpu', () => { testTextureArgument('gpu'); }); (GPU.isWebGLSupported ? test : skip)('texture argument webgl', () => { testTextureArgument('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('texture argument webgl2', () => { testTextureArgument('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('texture argument headlessgl', () => { testTextureArgument('headlessgl'); }); test('texture argument cpu', () => { testTextureArgument('cpu'); }); function testArray2TextureArgument(mode) { const gpu = new GPU({ mode }); const texture = gpu.createKernel(function() { return [1, 1]; }, { output: [1], pipeline: true })(); const kernel = gpu.createKernel(function(value_1) { debugger; return value_1[this.thread.x]; }, { output: [1], }); assert.deepEqual(kernel(texture)[0], new Float32Array([1, 1])); gpu.destroy(); } test('array2 texture argument auto', () => { testArray2TextureArgument(); }); test('array2 texture argument gpu', () => { testArray2TextureArgument('gpu'); }); (GPU.isWebGLSupported ? test : skip)('array2 texture argument webgl', () => { testArray2TextureArgument('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('array2 texture argument webgl2', () => { testArray2TextureArgument('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('array2 texture argument headlessgl', () => { testArray2TextureArgument('headlessgl'); }); function testNumberConstant(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return this.constants.value_1; }, { output: [1], constants: { value_1: 1 }, }); assert.equal(kernel()[0], 1); gpu.destroy(); } test('number constant auto', () => { testNumberConstant(); }); test('number constant gpu', () => { testNumberConstant('gpu'); }); (GPU.isWebGLSupported ? test : skip)('number constant webgl', () => { testNumberConstant('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('number constant webgl2', () => { testNumberConstant('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('number constant headlessgl', () => { testNumberConstant('headlessgl'); }); test('number constant cpu', () => { testNumberConstant('cpu'); }); function testArrayConstant(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return this.constants.value_1[0]; }, { output: [1], constants: { value_1: [1] }, }); assert.equal(kernel()[0], 1); gpu.destroy(); } test('array constant auto', () => { testArrayConstant(); }); test('array constant gpu', () => { testArrayConstant('gpu'); }); (GPU.isWebGLSupported ? test : skip)('array constant webgl', () => { testArrayConstant('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('array constant webgl2', () => { testArrayConstant('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('array constant headlessgl', () => { testArrayConstant('headlessgl'); }); test('array constant cpu', () => { testArrayConstant('cpu'); }); function testTextureConstant(mode) { const gpu = new GPU({ mode }); const texture = gpu.createKernel(function() { return 1; }, { output: [1], pipeline: true })(); const kernel = gpu.createKernel(function() { return this.constants.value_1[0]; }, { output: [1], constants: { value_1: texture }, }); assert.equal(kernel()[0], 1); gpu.destroy(); } test('texture constant auto', () => { testTextureConstant(); }); test('texture constant gpu', () => { testTextureConstant('gpu'); }); (GPU.isWebGLSupported ? test : skip)('texture constant webgl', () => { testTextureConstant('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('texture constant webgl2', () => { testTextureConstant('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('texture constant headlessgl', () => { testTextureConstant('headlessgl'); }); ================================================ FILE: test/internal/utils.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { utils } = require('../../src'); describe('internal: utils'); test('systemEndianness not null', () => { assert.ok(utils.systemEndianness() !== null, 'not null check'); assert.ok(utils.systemEndianness() === 'LE' || utils.systemEndianness() === 'BE', 'value = ' + utils.systemEndianness()); }); test('isFunction', () => { assert.ok(utils.isFunction(function() { })); assert.notOk(utils.isFunction({})); }); test('isFunctionString', () => { assert.ok(utils.isFunctionString('function() { }')); assert.notOk(utils.isFunctionString({})); }); test('getFunctionName_fromString', () => { assert.equal('test', utils.getFunctionNameFromString('function test() { }')); }); test('getParamNames_fromString', () => { assert.deepEqual(['a','b','c'], utils.getArgumentNamesFromString('function test(a,b,c) { }')); }); test('closestSquareDimensions 2', () => { assert.deepEqual(Array.from(utils.closestSquareDimensions(2)), [1,2]); }); test('closestSquareDimensions 5', () => { assert.deepEqual(Array.from(utils.closestSquareDimensions(5)), [2,3]); }); test('closestSquareDimensions 6', () => { assert.deepEqual(Array.from(utils.closestSquareDimensions(6)), [2,3]); }); test('closestSquareDimensions 7', () => { assert.deepEqual(Array.from(utils.closestSquareDimensions(7)), [4,2]); }); test('getDimensions Array of 6, padded', () => { assert.deepEqual(Array.from(utils.getDimensions(new Array(6).fill(1), true)), [6,1,1]); }); test('getDimensions Array of 6,1,1, padded', () => { assert.deepEqual(Array.from(utils.getDimensions([[[1,1,1,1,1,1]]], true)), [6,1,1]); }); test('getDimensions Array of 1,6,1, padded', () => { assert.deepEqual(Array.from(utils.getDimensions([[[1],[1],[1],[1],[1],[1]]], true)), [1,6,1]); }); test('getDimensions Array of 1,1,6, padded', () => { assert.deepEqual(Array.from(utils.getDimensions([[[1]],[[1]],[[1]],[[1]],[[1]],[[1]]], true)), [1,1,6]); }); test('getMemoryOptimizedFloatTextureSize [6,1,1], bitRatio 4', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedFloatTextureSize([6, 1, 1], 4)), [1, 2]); }); test('getMemoryOptimizedFloatTextureSize [1,6,1], bitRatio 4', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedFloatTextureSize([1, 6, 1], 4)), [1, 2]); }); test('getMemoryOptimizedFloatTextureSize [1,1,6], bitRatio 4', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedFloatTextureSize([1, 1, 6], 4)), [1, 2]); }); test('getMemoryOptimizedFloatTextureSize [6,1,1], bitRatio 2', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedFloatTextureSize([6, 1, 1], 2)), [2, 2]); }); test('getMemoryOptimizedFloatTextureSize [1,6,1], bitRatio 2', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedFloatTextureSize([1, 6, 1], 2)), [2, 2]); }); test('getMemoryOptimizedFloatTextureSize [1,1,6], bitRatio 2', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedFloatTextureSize([1, 1, 6], 2)), [2, 2]); }); test('getMemoryOptimizedFloatTextureSize [6,1,1], bitRatio 1', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedFloatTextureSize([6, 1, 1], 1)), [4, 2]); }); test('getMemoryOptimizedFloatTextureSize [1,6,1], bitRatio 1', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedFloatTextureSize([1, 6, 1], 1)), [4, 2]); }); test('getMemoryOptimizedFloatTextureSize [1,1,6], bitRatio 1', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedFloatTextureSize([1, 1, 6], 1)), [4, 2]); }); test('getMemoryOptimizedPackedTextureSize [6,1,1], bitRatio 4', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedPackedTextureSize([6, 1, 1], 4)), [4, 2]); }); test('getMemoryOptimizedPackedTextureSize [1,6,1], bitRatio 4', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedPackedTextureSize([1, 6, 1], 4)), [4, 2]); }); test('getMemoryOptimizedPackedTextureSize [1,1,6], bitRatio 4', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedPackedTextureSize([1, 1, 6], 4)), [4, 2]); }); test('getMemoryOptimizedPackedTextureSize [6,1,1], bitRatio 2', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedPackedTextureSize([6, 1, 1], 2)), [2, 2]); }); test('getMemoryOptimizedPackedTextureSize [1,6,1], bitRatio 2', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedPackedTextureSize([1, 6, 1], 2)), [2, 2]); }); test('getMemoryOptimizedPackedTextureSize [1,1,6], bitRatio 2', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedPackedTextureSize([1, 1, 6], 2)), [2, 2]); }); test('getMemoryOptimizedPackedTextureSize [6,1,1], bitRatio 1', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedPackedTextureSize([6, 1, 1], 1)), [1, 2]); }); test('getMemoryOptimizedPackedTextureSize [1,6,1], bitRatio 1', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedPackedTextureSize([1, 6, 1], 1)), [1, 2]); }); test('getMemoryOptimizedPackedTextureSize [1,1,6], bitRatio 1', () => { assert.deepEqual(Array.from(utils.getMemoryOptimizedPackedTextureSize([1, 1, 6], 1)), [1, 2]); }); test('getKernelTextureSize for [1,2] output, optimizeFloatMemory = true, and precision = "unsigned"', () => { const textureSize = utils.getKernelTextureSize({ optimizeFloatMemory: true, precision: 'unsigned', }, [1,2]); assert.deepEqual(textureSize, new Int32Array([1,2])); }); test('getKernelTextureSize for [2,3] output, optimizeFloatMemory = true, and precision = "unsigned"', () => { const textureSize = utils.getKernelTextureSize({ optimizeFloatMemory: true, precision: 'unsigned', }, [2,3]); assert.deepEqual(textureSize, new Int32Array([2,3])); }); test('getKernelTextureSize for [4,2] output, optimizeFloatMemory = true, and precision = "unsigned"', () => { const textureSize = utils.getKernelTextureSize({ optimizeFloatMemory: true, precision: 'unsigned', }, [4,2]); assert.deepEqual(textureSize, new Int32Array([4,2])); }); test('getKernelTextureSize for [6,1,1] output, optimizeFloatMemory = true, and precision = "unsigned"', () => { const textureSize = utils.getKernelTextureSize({ optimizeFloatMemory: true, precision: 'unsigned', }, [6,1,1]); assert.deepEqual(textureSize, new Int32Array([2,3])); }); test('getKernelTextureSize for [1,6,1] output, optimizeFloatMemory = true, and precision = "unsigned"', () => { const textureSize = utils.getKernelTextureSize({ optimizeFloatMemory: true, precision: 'unsigned', }, [1,6,1]); assert.deepEqual(textureSize, new Int32Array([1,6])); }); test('getKernelTextureSize for [1,1,6] output, optimizeFloatMemory = true, and precision = "unsigned"', () => { const textureSize = utils.getKernelTextureSize({ optimizeFloatMemory: true, precision: 'unsigned', }, [1,1,6]); assert.deepEqual(textureSize, new Int32Array([2,3])); }); test('getKernelTextureSize for [1,2] output, optimizeFloatMemory = true, and precision = "single"', () => { const textureSize = utils.getKernelTextureSize({ optimizeFloatMemory: true, precision: 'single', }, [1,2]); assert.deepEqual(textureSize, new Int32Array([1,1])); }); test('getKernelTextureSize for [2,3] output, optimizeFloatMemory = true, and precision = "single"', () => { const textureSize = utils.getKernelTextureSize({ optimizeFloatMemory: true, precision: 'single', }, [2,3]); assert.deepEqual(textureSize, new Int32Array([1,2])); }); test('getKernelTextureSize for [4,2] output, optimizeFloatMemory = true, and precision = "single"', () => { const textureSize = utils.getKernelTextureSize({ optimizeFloatMemory: true, precision: 'single', }, [4,2]); assert.deepEqual(textureSize, new Int32Array([1,2])); }); test('getKernelTextureSize for [6,1,1] output, optimizeFloatMemory = true, and precision = "single"', () => { const textureSize = utils.getKernelTextureSize({ optimizeFloatMemory: true, precision: 'single', }, [6,1,1]); assert.deepEqual(textureSize, new Int32Array([1,2])); }); test('getKernelTextureSize for [1,6,1] output, optimizeFloatMemory = true, and precision = "single"', () => { const textureSize = utils.getKernelTextureSize({ optimizeFloatMemory: true, precision: 'single', }, [1,6,1]); assert.deepEqual(textureSize, new Int32Array([1,2])); }); test('getKernelTextureSize for [1,1,6] output, optimizeFloatMemory = true, and precision = "single"', () => { const textureSize = utils.getKernelTextureSize({ optimizeFloatMemory: true, precision: 'single', }, [1,1,6]); assert.deepEqual(textureSize, new Int32Array([1,2])); }); test('erectPackedFloat', () => { const array = new Float32Array([0,1,2,3,4,5,0,0]); const result = utils.erectPackedFloat(array, 6); assert.deepEqual(result, new Float32Array([0,1,2,3,4,5])); }); test('erect2DPackedFloat', () => { const array = new Float32Array([0,1,2,3,4,5,6,7,8,0,0,0,0]); const result = utils.erect2DPackedFloat(array, 3, 3); assert.deepEqual(result, [ new Float32Array([0,1,2]), new Float32Array([3,4,5]), new Float32Array([6,7,8]) ]); }); test('erect3DPackedFloat', () => { const array = new Float32Array([0,1,2,3,4,5,6,7,0,0,0,0,0]); const result = utils.erect3DPackedFloat(array, 2, 2, 2); assert.deepEqual(result, [ [ new Float32Array([0,1]), new Float32Array([2,3]), ],[ new Float32Array([4,5]), new Float32Array([6,7]), ] ]); }); test('erectMemoryOptimizedFloat', () => { const array = new Float32Array([0,1,2,3,4,5,0,0]); const result = utils.erectMemoryOptimizedFloat(array, 6); assert.deepEqual(result, new Float32Array([0,1,2,3,4,5])); }); test('erectMemoryOptimized2DFloat', () => { const array = new Float32Array([0,1,2,3,4,5,6,7,8,0,0,0,0]); const result = utils.erectMemoryOptimized2DFloat(array, 3, 3); assert.deepEqual(result, [ new Float32Array([0,1,2]), new Float32Array([3,4,5]), new Float32Array([6,7,8]) ]); }); test('erectMemoryOptimized3DFloat', () => { const array = new Float32Array([0,1,2,3,4,5,6,7,0,0,0,0,0]); const result = utils.erectMemoryOptimized3DFloat(array, 2, 2, 2); assert.deepEqual(result, [ [ new Float32Array([0,1]), new Float32Array([2,3]), ],[ new Float32Array([4,5]), new Float32Array([6,7]), ] ]); }); test('erectFloat', () => { const array = new Float32Array([ 0,0,0,0, 1,0,0,0, 2,0,0,0, 3,0,0,0, 4,0,0,0, 5,0,0,0 ]); const result = utils.erectFloat(array, 6); assert.deepEqual(result, new Float32Array([0,1,2,3,4,5])); }); test('erect2DFloat', () => { const array = new Float32Array([ 0,0,0,0, 1,0,0,0, 2,0,0,0, 3,0,0,0, 4,0,0,0, 5,0,0,0, 6,0,0,0, 7,0,0,0, 8,0,0,0, 0,0,0,0 ]); const result = utils.erect2DFloat(array, 3, 3); assert.deepEqual(result, [ new Float32Array([0,1,2]), new Float32Array([3,4,5]), new Float32Array([6,7,8]) ]); }); test('erect3DFloat', () => { const array = new Float32Array([ 0,0,0,0, 1,0,0,0, 2,0,0,0, 3,0,0,0, 4,0,0,0, 5,0,0,0, 6,0,0,0, 7,0,0,0, 0,0,0,0 ]); const result = utils.erect3DFloat(array, 2, 2, 2); assert.deepEqual(result, [ [ new Float32Array([0,1]), new Float32Array([2,3]), ],[ new Float32Array([4,5]), new Float32Array([6,7]), ] ]); }); test('erectArray2', () => { const array = new Float32Array([ 0,1,0,0, 2,3,0,0, 4,5,0,0, 6,7,0,0 ]); const result = utils.erectArray2(array, 4); assert.deepEqual(result, [ new Float32Array([0,1]), new Float32Array([2,3]), new Float32Array([4,5]), new Float32Array([6,7]), ]); }); test('erect2DArray2', () => { const array = new Float32Array([ 0,1,0,0, 2,3,0,0, 4,5,0,0, 6,7,0,0 ]); const result = utils.erect2DArray2(array, 2, 2); assert.deepEqual(result, [ [ new Float32Array([0,1]), new Float32Array([2,3]), ], [ new Float32Array([4,5]), new Float32Array([6,7]), ] ]); }); test('erect3DArray2', () => { const array = new Float32Array([ 0,1,0,0, 2,3,0,0, 4,5,0,0, 6,7,0,0, 8,9,0,0, 10,11,0,0, 12,13,0,0, 14,15,0,0, ]); const result = utils.erect3DArray2(array, 2, 2, 2); assert.deepEqual(result, [ [ [ new Float32Array([0,1]), new Float32Array([2,3]), ], [ new Float32Array([4,5]), new Float32Array([6,7]), ] ], [ [ new Float32Array([8,9]), new Float32Array([10,11]), ], [ new Float32Array([12,13]), new Float32Array([14,15]), ] ] ]); }); test('erectArray3', () => { const array = new Float32Array([ 0,1,2,0, 3,4,5,0, 6,7,8,0, 9,10,11,0 ]); const result = utils.erectArray3(array, 4); assert.deepEqual(result, [ new Float32Array([0,1,2]), new Float32Array([3,4,5]), new Float32Array([6,7,8]), new Float32Array([9,10,11]), ]); }); test('erect2DArray3', () => { const array = new Float32Array([ 0,1,2,0, 3,4,5,0, 6,7,8,0, 9,10,11,0, ]); const result = utils.erect2DArray3(array, 2, 2); assert.deepEqual(result, [ [ new Float32Array([0,1,2]), new Float32Array([3,4,5]), ], [ new Float32Array([6,7,8]), new Float32Array([9,10,11]), ] ]); }); test('erect3DArray3', () => { const array = new Float32Array([ 0,1,2,0, 3,4,5,0, 6,7,8,0, 9,10,11,0, 12,13,14,0, 15,16,17,0, 18,19,20,0, 21,22,23,0, ]); const result = utils.erect3DArray3(array, 2, 2, 2); assert.deepEqual(result, [ [ [ new Float32Array([0,1,2]), new Float32Array([3,4,5]), ], [ new Float32Array([6,7,8]), new Float32Array([9,10,11]), ] ], [ [ new Float32Array([12,13,14]), new Float32Array([15,16,17]), ], [ new Float32Array([18,19,20]), new Float32Array([21,22,23]), ] ] ]); }); test('erectArray4', () => { const array = new Float32Array([ 0,1,2,3, 4,5,6,7, 8,9,10,11, 12,13,14,15, ]); const result = utils.erectArray4(array, 4); assert.deepEqual(result, [ new Float32Array([0,1,2,3]), new Float32Array([4,5,6,7]), new Float32Array([8,9,10,11]), new Float32Array([12,13,14,15]), ]); }); test('erect2DArray4', () => { const array = new Float32Array([ 0,1,2,3, 4,5,6,7, 8,9,10,11, 12,13,14,15, ]); const result = utils.erect2DArray4(array, 2, 2); assert.deepEqual(result, [ [ new Float32Array([0,1,2,3]), new Float32Array([4,5,6,7]), ], [ new Float32Array([8,9,10,11]), new Float32Array([12,13,14,15]), ] ]); }); test('erect3DArray4', () => { const array = new Float32Array([ 0,1,2,3, 4,5,6,7, 8,9,10,11, 12,13,14,15, 16,17,18,19, 20,21,22,23, 24,25,26,27, 28,29,30,31, ]); const result = utils.erect3DArray4(array, 2, 2, 2); assert.deepEqual(result, [ [ [ new Float32Array([0,1,2,3]), new Float32Array([4,5,6,7]), ], [ new Float32Array([8,9,10,11]), new Float32Array([12,13,14,15]), ] ], [ [ new Float32Array([16,17,18,19]), new Float32Array([20,21,22,23]), ], [ new Float32Array([24,25,26,27]), new Float32Array([28,29,30,31]), ] ] ]); }); test('flattenFunctionToString', () => { // since we use this internally, currently just testing if parsing simply works [ utils.erectPackedFloat, utils.erect2DPackedFloat, utils.erect3DPackedFloat, utils.erectMemoryOptimizedFloat, utils.erectMemoryOptimized2DFloat, utils.erectMemoryOptimized3DFloat, utils.erectFloat, utils.erect2DFloat, utils.erect3DFloat, utils.erectArray2, utils.erect2DArray2, utils.erect3DArray2, utils.erectArray3, utils.erect2DArray3, utils.erect3DArray3, utils.erectArray4, utils.erect2DArray4, utils.erect3DArray4 ].forEach(fn => eval(utils.flattenFunctionToString(fn, { findDependency: () => {}, thisLookup: () => {}, }))); assert.ok(true); }); test('improper getMinifySafeName usage with arrow function', () => { assert.throws(() => { utils.getMinifySafeName(() => {}); }, 'Unrecognized function type.'); }); test('improper getMinifySafeName usage with regular function', () => { assert.throws(() => { utils.getMinifySafeName(function() {}); }, 'Unrecognized function type.'); }); test('proper getMinifySafeName usage with arrow function', () => { function n() {} const safeName = utils.getMinifySafeName(() => n); assert.equal(safeName, 'n'); }); test('proper getMinifySafeName usage with regular function', () => { function n() {} const safeName = utils.getMinifySafeName(function () { return n; }); assert.equal(safeName, 'n'); }); ================================================ FILE: test/issues/114-create-kernel-map-run-second-time.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue # 114'); function secondKernelMap(mode) { const gpu = new GPU({ mode }); const A = [1, 2, 3, 4, 5]; const B = [1, 2, 3, 4, 5]; function add(a,b){ return a + b; } const kernels = gpu.createKernelMap([add], function(a, b) { return add(a[this.thread.x], b[this.thread.x]); }) .setOutput([5]); const E = kernels(A, B).result; const F = kernels(A, B).result; const G = kernels(A, B).result; assert.deepEqual(Array.from(E), [2, 4, 6, 8, 10]); assert.deepEqual(Array.from(F), [2, 4, 6, 8, 10]); assert.deepEqual(Array.from(G), [2, 4, 6, 8, 10]); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)("Issue #114 - run createKernelMap the second time auto", () => { secondKernelMap(); }); (GPU.isKernelMapSupported ? test : skip)("Issue #114 - run createKernelMap the second time gpu", () => { secondKernelMap('gpu'); }); (GPU.isWebGLSupported ? test : skip)("Issue #114 - run createKernelMap the second time webgl", () => { secondKernelMap('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("Issue #114 - run createKernelMap the second time webgl2", () => { secondKernelMap('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)("Issue #114 - run createKernelMap the second time headlessgl", () => { secondKernelMap('headlessgl'); }); ================================================ FILE: test/issues/116-multiple-kernels-run-again.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #116'); function multipleKernels(mode) { const gpu = new GPU({ mode }); const A = [1, 2, 3, 4, 5]; const B = [1, 2, 3, 4, 5]; const sizes = [2, 5, 1]; function add(a, b, x){ return a[x] + b[x]; } const layerForward = []; for (let i = 0; i < 2; i++) { const kernels = gpu.createKernelMap([add],function(a, b){ return add(a,b, this.thread.x); }) .setOutput([sizes[i + 1]]); // First: 5. Second: 1. layerForward.push(kernels); } const E = layerForward[0](A, B).result; const F = layerForward[1](A, B).result; const G = layerForward[0](A, B).result; assert.deepEqual(Array.from(E), [2, 4, 6, 8, 10]); assert.deepEqual(Array.from(F), [2]); assert.deepEqual(Array.from(G), [2, 4, 6, 8, 10]); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)("Issue #116 - multiple kernels run again auto", () => { multipleKernels(); }); (GPU.isKernelMapSupported ? test : skip)("Issue #116 - multiple kernels run again gpu", () => { multipleKernels('gpu'); }); (GPU.isWebGLSupported ? test : skip)("Issue #116 - multiple kernels run again webgl", () => { multipleKernels('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("Issue #116 - multiple kernels run again webgl2", () => { multipleKernels('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)("Issue #116 - multiple kernels run again headlessgl", () => { multipleKernels('headlessgl'); }); test("Issue #116 - multiple kernels run again cpu", () => { multipleKernels('cpu'); }); ================================================ FILE: test/issues/130-typed-array.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #130'); function typedArrays(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(changes) { return changes[this.thread.y][this.thread.x]; }) .setOutput([2, 1]); const values = [new Float32Array(2)]; values[0][0] = 0; values[0][1] = 0; const result = kernel(values); assert.equal(result[0][0], 0); assert.equal(result[0][1], 0); gpu.destroy(); } test("Issue #130 - typed array auto", () => { typedArrays(null); }); test("Issue #130 - typed array gpu", () => { typedArrays('gpu'); }); (GPU.isWebGLSupported ? test : skip)("Issue #130 - typed array webgl", () => { typedArrays('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("Issue #130 - typed array webgl2", () => { typedArrays('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)("Issue #130 - typed array headlessgl", () => { typedArrays('headlessgl'); }); test("Issue #130 - typed array cpu", () => { typedArrays('cpu'); }); ================================================ FILE: test/issues/147-missing-constant.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #147'); function missingConstant(mode) { const gpu = new GPU({ mode }); function getPi() { return this.constants.pi; } gpu.addFunction(getPi); const kernel = gpu.createKernel(function() { return getPi(); }) .setOutput([1]) .setConstants({ pi: Math.PI }); const result = kernel(); assert.equal(result[0].toFixed(7), Math.PI.toFixed(7)); gpu.destroy(); } test("Issue #147 - missing constant auto", () => { missingConstant(null); }); test("Issue #147 - missing constant gpu", () => { missingConstant('gpu'); }); (GPU.isWebGLSupported ? test : skip)("Issue #147 - missing constant webgl", () => { missingConstant('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("Issue #147 - missing constant webgl2", () => { missingConstant('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)("Issue #147 - missing constant headlessgl", () => { missingConstant('headlessgl'); }); test("Issue #147 - missing constant cpu", () => { missingConstant('cpu'); }); ================================================ FILE: test/issues/152-for-vars.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #152'); function forVars(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { let sum = 0; for (let i = 0; i < 2; i++) { sum += i; } return sum; }) .setOutput([1, 1]); const result = kernel(); assert.equal(result.length, 1); assert.equal(result[0], 1); gpu.destroy(); } test('Issue #152 - for vars cpu', () => { forVars('cpu'); }); test('Issue #152 - for vars auto', () => { forVars('gpu'); }); test('Issue #152 - for vars gpu', () => { forVars('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Issue #152 - for vars webgl', () => { forVars('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #152 - for vars webgl2', () => { forVars('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #152 - for vars headlessgl', () => { forVars('headlessgl'); }); ================================================ FILE: test/issues/159-3d.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); describe('issue # 159'); (function() { const { GPU } = require('../../src'); function threeD(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(grid) { return grid[this.thread.y][this.thread.x]; }) .setOutput([5, 5]); //This would cause the above to fail gpu.createKernel(function() { return 0; }) .setOutput([5, 5, 5]) .build(); const result = kernel([ [0,1,2,3,4], [1,2,3,4,5], [2,3,4,5,6], [3,4,5,6,7], [4,5,6,7,8] ]); assert.equal(result.length, 5); assert.deepEqual(result.map(function(v) { return Array.from(v); }), [ [0,1,2,3,4], [1,2,3,4,5], [2,3,4,5,6], [3,4,5,6,7], [4,5,6,7,8] ]); gpu.destroy(); } test('Issue #159 - for vars auto', () => { threeD(null); }); test('Issue #159 - for vars gpu', () => { threeD('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Issue #159 - for vars webgl', () => { threeD('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #159 - for vars webgl2', () => { threeD('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #159 - for vars headlessgl', () => { threeD('headlessgl'); }); test('Issue #159 - for vars cpu', () => { threeD('cpu'); }); })(); ================================================ FILE: test/issues/174-webgl-context-warning.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue # 174'); const input = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]; // recursive! function manyKernels(mode, kernelCount, t) { if (kernelCount < 1) return; const done = t.async(); kernelCount--; const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(inp) { return inp[this.thread.y][this.thread.x]; }, { output: [3, 3] }); const kernel2 = gpu.createKernel(function() { return this.thread.y * this.thread.x; }, { output: [1024, 1024], pipeline: true }); kernel(input); kernel2(); assert.strictEqual(kernel.context, kernel2.context, "contexts should be the same object"); manyKernels(mode, kernelCount, t); const canvas = kernel.canvas; const eventListener = canvas.addEventListener('webglcontextlost', (e) => { canvas.removeEventListener('webglcontextlost', eventListener); done(); }); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('Issue #174 - webgl context leak webgl', t => { manyKernels('webgl', 10, t); }); (GPU.isWebGL2Supported ? test : skip)('Issue #174 - webgl context leak webgl2', t => { manyKernels('webgl2', 10, t); }); ================================================ FILE: test/issues/195-read-from-texture2d.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #195'); function makeKernel(gpu) { return gpu.createKernel(function(a){ return a[this.thread.y][this.thread.x]; }) .setOutput([matrixSize, matrixSize]); } function splitArray(array, part) { const result = []; for(let i = 0; i < array.length; i += part) { result.push(array.slice(i, i + part)); } return result; } const matrixSize = 4; const A = splitArray(Array.apply(null, Array(matrixSize * matrixSize)).map((_, i) => i), matrixSize); function readFromTexture(mode) { const gpu = new GPU({ mode }); const noTexture = makeKernel(gpu); const texture = makeKernel(gpu) .setPipeline(true); const result = noTexture(A); const textureResult = texture(A).toArray(gpu); assert.deepEqual(result.map((v) => Array.from(v)), A); assert.deepEqual(textureResult.map((v) => Array.from(v)), A); assert.deepEqual(textureResult, result); gpu.destroy(); } test("Issue #195 Read from Texture 2D (GPU only) auto", () => { readFromTexture(); }); test("Issue #195 Read from Texture 2D (GPU only) gpu", () => { readFromTexture('gpu'); }); (GPU.isWebGLSupported ? test : skip)("Issue #195 Read from Texture 2D (GPU only) webgl", () => { readFromTexture('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("Issue #195 Read from Texture 2D (GPU Only) webgl2", () => { readFromTexture('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)("Issue #195 Read from Texture 2D (GPU Only) headlessgl", () => { readFromTexture('headlessgl'); }); ================================================ FILE: test/issues/207-same-function-reuse.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #207'); function sameFunctionReuse(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(kernelArg1, kernelArg2) { function someFun1(someFun1Arg1, someFun1Arg2) { return customAdder(someFun1Arg1, someFun1Arg2); } function someFun2(someFun2Arg1, someFun2Arg2) { return customAdder(someFun2Arg1, someFun2Arg2); } function customAdder(customAdderArg1, customAdderArg2) { return customAdderArg1 + customAdderArg2; } return someFun1(1, 2) + someFun2(kernelArg1[this.thread.x], kernelArg2[this.thread.x]); }) .setOutput([6]); const a = [1, 2, 3, 5, 6, 7]; const b = [4, 5, 6, 1, 2, 3]; const result = kernel(a,b); assert.deepEqual(Array.from(result), [8, 10, 12, 9, 11, 13]); gpu.destroy(); } test('Issue #207 - same function reuse auto', () => { sameFunctionReuse(null); }); test('Issue #207 - same function reuse gpu', () => { sameFunctionReuse('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Issue #207 - same function reuse webgl', () => { sameFunctionReuse('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #207 - same function reuse webgl2', () => { sameFunctionReuse('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #207 - same function reuse headlessgl', () => { sameFunctionReuse('headlessgl'); }); test('Issue #207 - same function reuse cpu', () => { sameFunctionReuse('cpu'); }); ================================================ FILE: test/issues/212-funky-function-support.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #212'); function funky(mode) { const gpu = new GPU({ mode }); gpu.addFunction(function add(value1, value2) { return value1 + value2; }); const kernel = gpu.createKernel(`function(v1, v2) { return (0, _add.add)(v1[this.thread.y][this.thread.x], v2[this.thread.y][this.thread.x]); }`) .setOutput([2, 2]); const result = kernel([ [0,1], [1,2] ], [ [0,1], [1,2] ]); assert.deepEqual(result.map((v) => Array.from(v)), [ [0,2], [2,4] ]); gpu.destroy(); } test('Issue #212 - funky function support auto', () => { funky('gpu'); }); test('Issue #212 - funky function support gpu', () => { funky('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Issue #212 - funky function support webgl', () => { funky('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #212 - funky function support webgl2', () => { funky('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #212 - funky function support headlessgl', () => { funky('headlessgl'); }); test('Issue #212 - funky function support cpu', () => { funky('cpu'); }); ================================================ FILE: test/issues/233-kernel-map-single-precision.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue # 233'); //TODO: Write for 2D and 3D and textures //TODO: Write for pipeline as well function kernelMapSinglePrecision(mode) { const lst = [1, 2, 3, 4, 5, 6, 7]; const gpu = new GPU({ mode }); const kernels = gpu.createKernelMap({ stepA: function (x) { return x * x; }, stepB: function (x) { return x + 1; } }, function (lst) { const val = lst[this.thread.x]; stepA(val); stepB(val); return val; }, { precision: 'single', output: [lst.length] }); const result = kernels(lst); const unwrap = gpu.createKernel(function(x) { return x[this.thread.x]; }, { output: [lst.length], precision: 'single', optimizeFloatMemory: true, }); const stepAResult = unwrap(result.stepA); const stepBResult = unwrap(result.stepB); assert.deepEqual(Array.from(stepAResult), lst.map((x) => x * x)); assert.deepEqual(Array.from(stepBResult), lst.map((x) => x + 1)); assert.deepEqual(Array.from(result.result), lst); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('Issue #233 - kernel map with single precision auto', () => { kernelMapSinglePrecision(); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('Issue #233 - kernel map with single precision gpu', () => { kernelMapSinglePrecision('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Issue #233 - kernel map with single precision webgl', () => { kernelMapSinglePrecision('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #233 - kernel map with single precision webgl2', () => { kernelMapSinglePrecision('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('Issue #233 - kernel map with single precision headlessgl', () => { kernelMapSinglePrecision('headlessgl'); }); test('Issue #233 - kernel map with single precision cpu', () => { kernelMapSinglePrecision('cpu'); }); function kernelMapSinglePrecision2D(mode) { const lst = [ [1,2,3], [4,5,6], [7,8,9] ]; const stepAExpected = [ [1,4,9], [16,25,36], [49,64,81], ]; const stepBExpected = [ [2,3,4], [5,6,7], [8,9,10] ]; const gpu = new GPU({ mode }); const kernels = gpu.createKernelMap({ stepA: function (x) { return x * x; }, stepB: function (x) { return x + 1; } }, function (lst) { const val = lst[this.thread.y][this.thread.x]; stepA(val); stepB(val); return val; }, { precision: 'single', output: [3, 3] }); const result = kernels(lst); assert.deepEqual(result.stepA.map(v => Array.from(v)), stepAExpected); assert.deepEqual(result.stepB.map(v => Array.from(v)), stepBExpected); assert.deepEqual(result.result.map(v => Array.from(v)), lst); const memoryOptimize = gpu.createKernel(function(x) { return x[this.thread.y][this.thread.x]; }, { output: [3, 3], precision: 'single', optimizeFloatMemory: true, }); const stepAOptimized = memoryOptimize(result.stepA); const stepBOptimized = memoryOptimize(result.stepB); const resultOptimized = memoryOptimize(result.result); assert.deepEqual(stepAOptimized.map(v => Array.from(v)), stepAExpected); assert.deepEqual(stepBOptimized.map(v => Array.from(v)), stepBExpected); assert.deepEqual(resultOptimized.map(v => Array.from(v)), lst); gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('Issue #233 - kernel map with single precision 2d auto', () => { kernelMapSinglePrecision2D(); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('Issue #233 - kernel map with single precision 2d gpu', () => { kernelMapSinglePrecision2D('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Issue #233 - kernel map with single precision 2d webgl', () => { kernelMapSinglePrecision2D('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #233 - kernel map with single precision 2d webgl2', () => { kernelMapSinglePrecision2D('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('Issue #233 - kernel map with single precision 2d headlessgl', () => { kernelMapSinglePrecision2D('headlessgl'); }); test('Issue #233 - kernel map with single precision 2d cpu', () => { kernelMapSinglePrecision2D('cpu'); }); function kernelMapSinglePrecision3D(mode) { const lst = [ [ [1,2,3], [4,5,6], [7,8,9] ], [ [10,11,12], [13,14,15], [16,17,18] ] ]; const stepAExpected = [ [ [1,4,9], [16,25,36], [49,64,81], ], [ [100,121,144], [169,196,225], [256,289,324], ] ]; const stepBExpected = [ [ [2,3,4], [5,6,7], [8,9,10] ], [ [11,12,13], [14,15,16], [17,18,19] ] ]; const gpu = new GPU({ mode }); const kernels = gpu.createKernelMap({ stepA: function (x) { return x * x; }, stepB: function (x) { return x + 1; } }, function (lst) { const val = lst[this.thread.z][this.thread.y][this.thread.x]; stepA(val); stepB(val); return val; }, { precision: 'single', output: [3, 3, 2] }); const result = kernels(lst); assert.deepEqual(arrayFromCube(result.stepA), stepAExpected); assert.deepEqual(arrayFromCube(result.stepB), stepBExpected); assert.deepEqual(arrayFromCube(result.result), lst); const memoryOptimize = gpu.createKernel(function(x) { return x[this.thread.z][this.thread.y][this.thread.x]; }, { output: [3, 3, 2], precision: 'single', optimizeFloatMemory: true, }); const stepAOptimized = memoryOptimize(result.stepA); const stepBOptimized = memoryOptimize(result.stepB); const resultOptimized = memoryOptimize(result.result); assert.deepEqual(arrayFromCube(stepAOptimized), stepAExpected); assert.deepEqual(arrayFromCube(stepBOptimized), stepBExpected); assert.deepEqual(arrayFromCube(resultOptimized), lst); function arrayFromCube(cube) { return cube.map(matrix => matrix.map(row => Array.from(row))); } gpu.destroy(); } (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('Issue #233 - kernel map with single precision 3d auto', () => { kernelMapSinglePrecision3D(); }); (GPU.isSinglePrecisionSupported && GPU.isKernelMapSupported ? test : skip)('Issue #233 - kernel map with single precision 3d gpu', () => { kernelMapSinglePrecision3D('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Issue #233 - kernel map with single precision 3d webgl', () => { kernelMapSinglePrecision3D('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #233 - kernel map with single precision 3d webgl2', () => { kernelMapSinglePrecision3D('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('Issue #233 - kernel map with single precision 3d headlessgl', () => { kernelMapSinglePrecision3D('headlessgl'); }); test('Issue #233 - kernel map with single precision 3d cpu', () => { kernelMapSinglePrecision3D('cpu'); }); ================================================ FILE: test/issues/241-CPU-vs-GPU-maps-output-differently.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #241'); // this is actually equiv to // return this.thread.y * 3 + this.thread.x; const input = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]; function buildIndexTestKernel(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(inp) { return inp[this.thread.y][this.thread.x]; }, { output: [3, 3] }); const result = kernel(input).map((v) => Array.from(v)); assert.deepEqual(result, input); gpu.destroy(); } test('Issue #241 small 2d array input output test auto', () => { buildIndexTestKernel(); }); test('Issue #241 small 2d array input output test gpu', () => { buildIndexTestKernel('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Issue #241 small 2d array input output test webgl', () => { buildIndexTestKernel('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #241 small 2d array input output test webgl2', () => { buildIndexTestKernel('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #241 small 2d array input output test headlessgl', () => { buildIndexTestKernel('headlessgl'); }); test('Issue #241 small 2d array input output test cpu', () => { buildIndexTestKernel('cpu'); }); ================================================ FILE: test/issues/259-atan2.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #259'); function buildAtan2KernelResult(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function() { return Math.atan2(1, 2); }, { output: [1], }); assert.equal(kernel()[0].toFixed(7), 0.4636476); gpu.destroy(); } test('Issue #259 atan2 - auto', () => { buildAtan2KernelResult(); }); test('Issue #259 atan2 - gpu', () => { buildAtan2KernelResult('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Issue #259 atan2 - webgl', () => { buildAtan2KernelResult('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #259 atan2 - webgl2', () => { buildAtan2KernelResult('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #259 atan2 - headlessgl', () => { buildAtan2KernelResult('headlessgl'); }); test('Issue #259 atan2 - cpu', () => { buildAtan2KernelResult('cpu'); }); ================================================ FILE: test/issues/263-to-string.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #263'); function toString(mode, context, canvas) { const gpu = new GPU({ mode, context, canvas }); const kernel = gpu.createKernel(function() { return 1; }, { output: [1] }); kernel.build(); const string = kernel.toString(); const kernel2 = new Function('return ' + string)()({ context, canvas }); const result = kernel2(); assert.equal(result[0], 1); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('Issue #263 toString single function - webgl', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl'); toString('webgl', context, canvas); }); (GPU.isWebGL2Supported ? test : skip)('Issue #263 toString single function - webgl2', () => { const canvas = document.createElement('canvas'); const context = canvas.getContext('webgl2'); toString('webgl2', context, canvas); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #263 toString single function - headlessgl', () => { toString('headlessgl', require('gl')(1, 1), null); }); test('Issue #263 toString single function - cpu', () => { toString('cpu'); }); ================================================ FILE: test/issues/267-immutable-sub-kernels.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #267 kernel'); function immutableKernelWithoutFloats(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function (v) { return v[this.thread.x] + 1; }, { output: [1], immutable: true, pipeline: true, precision: 'unsigned', }); // start with a value on CPU const output1 = kernel([1]); const result1 = output1.toArray()[0]; // reuse that output, simulating that this value will be monitored, and updated via the same kernel // this is often used in neural networks const output2 = kernel(output1); const result2 = output2.toArray()[0]; const output3 = kernel(output2); const result3 = output3.toArray()[0]; assert.equal(result1, 2); assert.equal(result2, 3); assert.equal(result3, 4); gpu.destroy(); } test('Issue #267 immutable kernel output without floats - auto', () => { immutableKernelWithoutFloats(); }); test('Issue #267 immutable kernel output without floats - gpu', () => { immutableKernelWithoutFloats('gpu'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #267 immutable kernel output without floats - webgl', () => { immutableKernelWithoutFloats('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #267 immutable kernel output without floats - webgl2', () => { immutableKernelWithoutFloats('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #267 immutable kernel output without floats - headlessgl', () => { immutableKernelWithoutFloats('headlessgl'); }); function immutableKernelWithFloats(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function (v) { return v[this.thread.x] + 1; }, { output: [1], immutable: true, pipeline: true, precision: 'single', }); // start with a value on CPU // reuse that output, simulating that this value will be monitored, and updated via the same kernel // this is often used in neural networks const output1 = kernel([1]); const output2 = kernel(output1); const output3 = kernel(output2); assert.equal(output1.toArray()[0], 2); assert.equal(output2.toArray()[0], 3); assert.equal(output3.toArray()[0], 4); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Issue #267 immutable kernel output with floats - auto', () => { immutableKernelWithFloats(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Issue #267 immutable kernel output with floats - gpu', () => { immutableKernelWithFloats('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Issue #267 immutable kernel output with floats - webgl', () => { immutableKernelWithFloats('webgl'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGL2Supported ? test : skip)('Issue #267 immutable kernel output with floats - webgl2', () => { immutableKernelWithFloats('webgl2'); }); (GPU.isSinglePrecisionSupported && GPU.isHeadlessGLSupported ? test : skip)('Issue #267 immutable kernel output with floats - headlessgl', () => { immutableKernelWithFloats('headlessgl'); }); describe('issue #267 sub kernel'); function immutableSubKernelsWithoutFloats(mode) { function value1(value) { return value + 1; } function value2(value) { return value + 1; } const gpu = new GPU({ mode }); const kernel = gpu.createKernelMap( { valueOutput1: value1, valueOutput2: value2 }, function (a, b) { value1(a[this.thread.x]); return value2(b[this.thread.x]); }, { output: [1], immutable: true, pipeline: true, precision: 'unsigned', } ); // start with a value on CPU const output1 = kernel([1], [2]); const result1 = output1.valueOutput1.toArray()[0]; // reuse that output, simulating that this value will be monitored, and updated via the same kernel // this is often used in neural networks const output2 = kernel(output1.valueOutput1, output1.valueOutput2); const result2 = output2.valueOutput1.toArray()[0]; const output3 = kernel(output2.valueOutput1, output2.valueOutput2); const result3 = output3.valueOutput1.toArray()[0]; assert.equal(result1, 2); assert.equal(result2, 3); assert.equal(result3, 4); gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('Issue #267 immutable sub-kernel output - auto', () => { immutableSubKernelsWithoutFloats(); }); (GPU.isKernelMapSupported ? test : skip)('Issue #267 immutable sub-kernel output - gpu', () => { immutableSubKernelsWithoutFloats('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Issue #267 immutable sub-kernel output - webgl', () => { immutableSubKernelsWithoutFloats('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #267 immutable sub-kernel output - webgl2', () => { immutableSubKernelsWithoutFloats('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('Issue #267 immutable sub-kernel output - headlessgl', () => { immutableSubKernelsWithoutFloats('headlessgl'); }); describe('issue #267 sub kernels mixed'); function immutableKernelsMixedWithoutFloats(mode) { function value1(value) { return value + 10; } function value2(value) { return value + 50; } const gpu = new GPU({ mode }); const kernel = gpu.createKernelMap( { valueOutput1: value1, valueOutput2: value2, }, function (a, b) { value1(a[this.thread.x]); return value2(b[this.thread.x]) + 100; }, { output: [1], immutable: true, pipeline: true, precision: 'unsigned', } ); // start with a value on CPU const output1 = kernel([10], [20]); // reuse that output, simulating that this value will be monitored, and updated via the same kernel // this is often used in neural networks const output2 = kernel(output1.result, output1.valueOutput2); const output3 = kernel(output2.result, output2.valueOutput2); function toArray(value) { return value.toArray ? value.toArray() : value; } assert.equal(toArray(output1.valueOutput1)[0], 20); // 10 + 10 assert.equal(toArray(output1.valueOutput2)[0], 70); // 20 + 50 assert.equal(toArray(output1.result)[0], 170); // (20 + 50) + 100 assert.equal(toArray(output2.valueOutput1)[0], 180); // 170 + 10 assert.equal(toArray(output2.valueOutput2)[0], 120); // 70 + 50 assert.equal(toArray(output2.result)[0], 220); // (70 + 50) + 100 assert.equal(toArray(output3.valueOutput1)[0], 230); // 220 + 10 assert.equal(toArray(output3.valueOutput2)[0], 170); // 120 + 50 assert.equal(toArray(output3.result)[0], 270); // (120 + 50) + 100 gpu.destroy(); } (GPU.isKernelMapSupported ? test : skip)('Issue #267 immutable kernel & sub-kernel output without floats - auto', () => { immutableKernelsMixedWithoutFloats(); }); (GPU.isKernelMapSupported ? test : skip)('Issue #267 immutable kernel & sub-kernel output without floats - gpu', () => { immutableKernelsMixedWithoutFloats('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Issue #267 immutable kernel & sub-kernel output without floats - webgl', () => { immutableKernelsMixedWithoutFloats('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #267 immutable kernel & sub-kernel output without floats - webgl2', () => { immutableKernelsMixedWithoutFloats('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)('Issue #267 immutable kernel & sub-kernel output without floats - headlessgl', () => { immutableKernelsMixedWithoutFloats('headlessgl'); }); test('Issue #267 immutable kernel & sub-kernel output without floats - cpu', () => { immutableKernelsMixedWithoutFloats('cpu'); }); ================================================ FILE: test/issues/270-cache.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { WebGLKernel } = require('../../src'); describe('issue # 270'); test('Issue #270 WebGlKernel getUniformLocation caches falsey - gpu', () => { const canvas = {}; const context = { getUniformLocation() { throw new Error('tried to get getUniformLocation when falsey'); } }; const kernel = new WebGLKernel('function() {}', { canvas, context }); kernel.programUniformLocationCache.test = false; assert.equal(kernel.getUniformLocation('test'), false); }); ================================================ FILE: test/issues/279-wrong-canvas-size.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #279'); const WIDTH = 600; const HEIGHT = 400; function wrongCanvasSizeOptimized(mode) { const gpu = new GPU({ mode }); const initMatrix = gpu.createKernel(function(value) { return value; }) .setOptimizeFloatMemory(true) .setOutput([WIDTH, HEIGHT]); const render = gpu.createKernel(function(matrix) { const i = matrix[this.thread.y][this.thread.x]; this.color(i, i, i, 1); }) .setOutput([WIDTH, HEIGHT]) .setGraphical(true); const matrix = initMatrix(0.5); render(matrix); const canvas = render.canvas; assert.equal(canvas.width, WIDTH); assert.equal(canvas.height, HEIGHT); gpu.destroy(); } (GPU.isCanvasSupported ? test : skip)('Issue #279 wrong canvas size optimized - cpu', () => { wrongCanvasSizeOptimized('cpu'); }); test('Issue #279 wrong canvas size optimized - gpu', () => { wrongCanvasSizeOptimized('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Issue #279 wrong canvas size optimized - webgl', () => { wrongCanvasSizeOptimized('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #279 wrong canvas size optimized - webgl2', () => { wrongCanvasSizeOptimized('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #279 wrong canvas size optimized - headlessgl', () => { wrongCanvasSizeOptimized('headlessgl'); }); function wrongCanvasSizeUnoptimized(mode) { const gpu = new GPU({ mode }); const initMatrix = gpu.createKernel(function(value) { return value; }) .setOptimizeFloatMemory(false) .setOutput([WIDTH, HEIGHT]); const render = gpu.createKernel(function(matrix) { const i = matrix[this.thread.y][this.thread.x]; this.color(i, i, i, 1); }) .setOutput([WIDTH, HEIGHT]) .setGraphical(true); const matrix = initMatrix(0.5); render(matrix); const canvas = render.canvas; assert.equal(canvas.width, WIDTH); assert.equal(canvas.height, HEIGHT); gpu.destroy(); } (GPU.isCanvasSupported ? test : skip)('Issue #279 wrong canvas size unoptimized - cpu', () => { wrongCanvasSizeUnoptimized('cpu'); }); test('Issue #279 wrong canvas size unoptimized - gpu', () => { wrongCanvasSizeUnoptimized('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Issue #279 wrong canvas size unoptimized - webgl', () => { wrongCanvasSizeUnoptimized('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #279 wrong canvas size unoptimized - webgl2', () => { wrongCanvasSizeUnoptimized('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #279 wrong canvas size unoptimized - headlessgl', () => { wrongCanvasSizeUnoptimized('headlessgl'); }); ================================================ FILE: test/issues/300-nested-array-index.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #300'); function nestedArrayIndex(mode) { const gpu1 = new GPU({ mode }); const gpu2 = new GPU({ mode }); // these 2 should be equivalent const broken = gpu1.createKernel(function(input, lookup) { return lookup[input[this.thread.x]]; }) .setOutput([1]); const working = gpu2.createKernel(function(input, lookup) { const idx = input[this.thread.x]; return lookup[idx]; }) .setOutput([1]); assert.equal(broken([2], [7, 13, 19, 23])[0], 19); assert.equal(working([2], [7, 13, 19, 23])[0], 19); gpu1.destroy(); gpu2.destroy(); } test('Issue #300 nested array index - auto', () => { nestedArrayIndex(); }); test('Issue #300 nested array index - gpu', () => { nestedArrayIndex('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Issue #300 nested array index - webgl', () => { nestedArrayIndex('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #300 nested array index - webgl2', () => { nestedArrayIndex('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #300 nested array index - headlessgl', () => { nestedArrayIndex('headlessgl'); }); test('Issue #300 nested array index - cpu', () => { nestedArrayIndex('cpu'); }); ================================================ FILE: test/issues/31-nested-var-declare-test.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, FunctionBuilder, WebGLFunctionNode, WebGL2FunctionNode, CPUFunctionNode } = require('../../src'); describe('issue #31 redeclare'); // nested redeclare function nestedVarRedeclareFunction() { let result = 0; // outer loop limit is effectively skipped in CPU for(let i=0; i<10; ++i) { // inner loop limit should be higher, to avoid infinite loops for(i=0; i<20; ++i) { result += 1; } } return result; } function nestedVarRedeclareTest(mode) { const gpu = new GPU({ mode }); const f = gpu.createKernel(nestedVarRedeclareFunction, { output: [1], }); assert.throws(() => { f(); }); gpu.destroy(); } test('Issue #31 - nestedVarRedeclare auto', () => { nestedVarRedeclareTest(null); }); test('Issue #31 - nestedVarRedeclare gpu', () => { nestedVarRedeclareTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Issue #31 - nestedVarRedeclare webgl', () => { nestedVarRedeclareTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #31 - nestedVarRedeclare webgl2', () => { nestedVarRedeclareTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #31 - nestedVarRedeclare headlessgl', () => { nestedVarRedeclareTest('headlessgl'); }); test('Issue #31 - nestedVarRedeclare cpu', () => { nestedVarRedeclareTest('cpu'); }); test('Issue #31 - nestedVarRedeclare : AST handling webgl', () => { const builder = new FunctionBuilder({ functionNodes: [new WebGLFunctionNode(nestedVarRedeclareFunction.toString(), { output: [1] })], output: [1] }); assert.throws(() => { builder.getStringFromFunctionNames(['nestedVarRedeclareFunction']); }); }); test('Issue #31 - nestedVarRedeclare : AST handling webgl2', () => { const builder = new FunctionBuilder({ functionNodes: [new WebGL2FunctionNode(nestedVarRedeclareFunction.toString(), { output: [1] })], output: [1] }); assert.throws(() => { builder.getStringFromFunctionNames(['nestedVarRedeclareFunction']); }); }); test('Issue #31 - nestedVarRedeclare : AST handling cpu', () => { const builder = new FunctionBuilder({ functionNodes: [new CPUFunctionNode(nestedVarRedeclareFunction.toString(), { output: [1] })], output: [1] }); assert.throws(() => { builder.getStringFromFunctionNames(['nestedVarRedeclareFunction']); }); }); describe('issue #31 nested declare'); // nested declare function nestedVarDeclareFunction() { let result = 0.0; // outer loop limit is effectively skipped in CPU for(let i=0; i<10; ++i) { // inner loop limit should be higher, to avoid infinite loops for(let i=0; i<20; ++i) { result += 1; } } return result; } function nestedVarDeclareTest(mode ) { const gpu = new GPU({ mode }); const f = gpu.createKernel(nestedVarDeclareFunction, { output : [1] }); assert.equal(f(), 200, 'basic return function test'); gpu.destroy(); } test('Issue #31 - nestedVarDeclare auto', () => { nestedVarDeclareTest(null); }); test('Issue #31 - nestedVarDeclare gpu', () => { nestedVarDeclareTest('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Issue #31 - nestedVarDeclare webgl', () => { nestedVarDeclareTest('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #31 - nestedVarDeclare webgl2', () => { nestedVarDeclareTest('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #31 - nestedVarDeclare headlessgl', () => { nestedVarDeclareTest('headlessgl'); }); test('Issue #31 - nestedVarDeclare cpu', () => { nestedVarDeclareTest('cpu'); }); test('Issue #31 - nestedVarDeclare : AST handling webgl', () => { const builder = new FunctionBuilder({ functionNodes: [new WebGLFunctionNode(nestedVarDeclareFunction.toString(), { output: [1] })] }); assert.equal( builder.getStringFromFunctionNames(['nestedVarDeclareFunction']), 'float nestedVarDeclareFunction() {' + '\nfloat user_result=0.0;' + '\nfor (int user_i=0;(user_i<10);++user_i){' + '\nfor (int user_i=0;(user_i<20);++user_i){' //<-- Note: don't do this in real life! + '\nuser_result+=1.0;}' + '\n}' + '\n' + '\nreturn user_result;' + '\n}' ); }); test('Issue #31 - nestedVarDeclare : AST handling webgl2', () => { const builder = new FunctionBuilder({ functionNodes: [new WebGL2FunctionNode(nestedVarDeclareFunction.toString(), { output: [1] })] }); assert.equal( builder.getStringFromFunctionNames(['nestedVarDeclareFunction']), 'float nestedVarDeclareFunction() {' + '\nfloat user_result=0.0;' + '\nfor (int user_i=0;(user_i<10);++user_i){' + '\nfor (int user_i=0;(user_i<20);++user_i){' //<-- Note: don't do this in real life! + '\nuser_result+=1.0;}' + '\n}' + '\n' + '\nreturn user_result;' + '\n}' ); }); test('Issue #31 - nestedVarDeclare : AST handling cpu', () => { const builder = new FunctionBuilder({ functionNodes: [new CPUFunctionNode(nestedVarDeclareFunction.toString(), { output: [1] })] }); assert.equal( builder.getStringFromFunctionNames(['nestedVarDeclareFunction']), 'function nestedVarDeclareFunction() {' + '\nlet user_result=0;' + '\nfor (let user_i=0;(user_i<10);++user_i){' + '\nfor (let user_i=0;(user_i<20);++user_i){' + '\nuser_result+=1;}' + '\n}' + '\n' + '\nreturn user_result;' + '\n}' ); }); ================================================ FILE: test/issues/313-variable-lookup.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #313'); function variableLookup(mode) { function mult2(scale) { return 2*scale; } const gpu = new GPU({ mode, functions: [mult2] }); const render1 = gpu.createKernel(function(input) { return (mult2(input) + mult2(input*2) + mult2(input*1)) // RIGHT }) .setOutput([1]); const render2 = gpu.createKernel(function(input) { return (mult2(input) + mult2(input*2) + mult2(input)); // WRONG }) .setOutput([1]); assert.equal(render1(1)[0], 8, 'render1 equals 8'); assert.equal(render2(1)[0], 8, 'render2 equals 8'); gpu.destroy(); } test('Issue #313 Mismatch argument lookup - auto', () => { variableLookup(); }); test('Issue #313 Mismatch argument lookup - gpu', () => { variableLookup('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Issue #313 Mismatch argument lookup - webgl', () => { variableLookup('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #313 Mismatch argument lookup - webgl2', () => { variableLookup('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #313 Mismatch argument lookup - headlessgl', () => { variableLookup('headlessgl'); }); test('Issue #313 Mismatch argument lookup - cpu', () => { variableLookup('cpu'); }); ================================================ FILE: test/issues/314-large-input-array-addressing.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU, WebGLKernel, HeadlessGLKernel } = require('../../src'); describe('issue #314'); // max size of ok addressing was 8388608, 8388609 is shifted by 1 so index seems to be 8388610 // after this fix max addressing is 2^31 which is the max a int32 can handle // run out of heap before being able to create a butter that big! // wanted to use uints but caused more problems than it solved const DATA_MAX = (GPU.isHeadlessGLSupported ? HeadlessGLKernel : WebGLKernel).features.maxTextureSize*8; const divisor = 100; const data = new Uint16Array(DATA_MAX); let v = 0; for (let i = 0; i < DATA_MAX/divisor; i++) { for (let j = 0; j < divisor; j++) { data[i*divisor + j] = v++; } } function buildLargeArrayAddressKernel(mode) { const gpu = new GPU({ mode }); const largeArrayAddressKernel = gpu.createKernel(function(data) { return data[this.thread.x]; }, { precision: 'unsigned', }) .setOutput([DATA_MAX]); const result = largeArrayAddressKernel(data); let same = true; let i = 0; for (; i < DATA_MAX; i++) { if (result[i] !== data[i]) { same = false; break; } } assert.ok(same, "not all elements are the same, failed on index:" + i); gpu.destroy(); } test('Issue #314 Large array addressing - auto', () => { buildLargeArrayAddressKernel(null); }); test('Issue #314 Large array addressing - gpu', () => { buildLargeArrayAddressKernel('gpu'); }); (GPU.isWebGLSupported ? test : skip)('Issue #314 Large array addressing - webgl', () => { buildLargeArrayAddressKernel('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #314 Large array addressing - webgl2', () => { buildLargeArrayAddressKernel('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #314 Large array addressing - headlessgl', () => { buildLargeArrayAddressKernel('headlessgl'); }); ================================================ FILE: test/issues/335-missing-z-index-issue.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #335'); function missingZIndexIssue(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.z][this.thread.y][this.thread.x]; }) .setOutput([1, 1, undefined]); kernel([[[1]]]); gpu.destroy(); } test('Issue #335 Missing z index issue auto', () => { assert.throws(() => { missingZIndexIssue('auto'); }); }); test('Issue #335 Missing z index issue gpu', () => { assert.throws(() => { missingZIndexIssue('gpu'); }); }); test('Issue #335 Missing z index issue webgl', () => { assert.throws(() => { missingZIndexIssue('webgl'); }); }); test('Issue #335 Missing z index issue webgl2', () => { assert.throws(() => { missingZIndexIssue('webgl2'); }); }); test('Issue #335 Missing z index issue cpu', () => { assert.throws(() => { missingZIndexIssue('cpu'); }); }); ================================================ FILE: test/issues/346-uint8array-converted.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #346'); const DATA_MAX = 1024; const uint8data = new Uint8Array(DATA_MAX); const uint16data = new Uint16Array(DATA_MAX); for (let i = 0; i < DATA_MAX; i++) { uint8data[i] = Math.random() * 255; uint16data[i] = Math.random() * 255 * 255; } function buildUintArrayInputKernel(mode, data) { const gpu = new GPU({ mode }); const largeArrayAddressKernel = gpu.createKernel(function(data) { return data[this.thread.x]; }, { precision: 'unsigned' }) .setOutput([DATA_MAX]); const result = largeArrayAddressKernel(data); let same = true; let i = 0; for (; i < DATA_MAX; i++) { if (result[i] !== data[i]) { same = false; break; } } assert.ok(same, "not all elements are the same, failed on index:" + i); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('Issue #346 uint8 input array - webgl', () => { buildUintArrayInputKernel('webgl', uint8data); }); (GPU.isWebGL2Supported ? test : skip)('Issue #346 uint8 input array - webgl2', () => { buildUintArrayInputKernel('webgl2', uint8data); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #346 uint8 input array - headlessgl', () => { buildUintArrayInputKernel('headlessgl', uint8data); }); (GPU.isWebGLSupported ? test : skip)('Issue #346 uint16 input array - webgl', () => { buildUintArrayInputKernel('webgl', uint16data); }); (GPU.isWebGL2Supported ? test : skip)('Issue #346 uint16 input array - webgl2', () => { buildUintArrayInputKernel('webgl2', uint16data); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #346 uint16 input array - headlessgl', () => { buildUintArrayInputKernel('headlessgl', uint16data); }); ================================================ FILE: test/issues/349-division-by-factors-of-3.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #349 divide by 3'); function testDivideByThree(mode) { const gpu = new GPU({mode}); const k = gpu.createKernel(function (v1, v2) { return v1 / v2; }, { output: [1], precision: 'single' }); assert.equal(k(6, 3)[0], 2); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Issue #349 - divide by three auto', () => { testDivideByThree(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Issue #349 - divide by three gpu', () => { testDivideByThree('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Issue #349 - divide by three webgl', () => { testDivideByThree('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #349 - divide by three webgl2', () => { testDivideByThree('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #349 - divide by three headlessgl', () => { testDivideByThree('headlessgl'); }); test('Issue #349 - divide by three cpu', () => { testDivideByThree('cpu'); }); describe('issue #349 divide by random numbers'); function someRandomWholeNumberDivisions(mode) { const DATA_MAX = 1024 * 1024; const dividendData = new Float32Array(DATA_MAX); const divisorData = new Float32Array(DATA_MAX); const expectedResults = new Float32Array(DATA_MAX); const maxWholeNumberRepresentation = Math.sqrt(16777217); for (let i = 0; i < DATA_MAX; i++) { divisorData[i] = parseInt(Math.random() * maxWholeNumberRepresentation + 1, 10); expectedResults[i] = parseInt(Math.random() * maxWholeNumberRepresentation + 1, 10); dividendData[i] = divisorData[i] * expectedResults[i]; } const gpu = new GPU({mode}); const k = gpu.createKernel(function (v1, v2) { return v1[this.thread.x] / v2[this.thread.x]; }, { output: [DATA_MAX], precision: 'single' }); const result = k(dividendData, divisorData); let same = true; let i = 0; for (; i < DATA_MAX; i++) { if (result[i] !== expectedResults[i]) { same = false; break; } } assert.ok(same, same ? "" : "not all elements are the same, failed on index:" + i + " " + dividendData[i] + "/" + divisorData[i]); gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Issue #349 - some random whole number divisions auto', () => { someRandomWholeNumberDivisions(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Issue #349 - some random whole number divisions gpu', () => { someRandomWholeNumberDivisions('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Issue #349 - some random whole number divisions webgl', () => { someRandomWholeNumberDivisions('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #349 - some random whole number divisions webgl2', () => { someRandomWholeNumberDivisions('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #349 - some random whole number divisions headlessgl', () => { someRandomWholeNumberDivisions('headlessgl'); }); test('Issue #349 - some random whole number divisions cpu', () => { someRandomWholeNumberDivisions('cpu'); }); describe('issue #349 disable integer division bug'); function testDisableFixIntegerDivisionBug(mode) { const gpu = new GPU({mode}); const idFix = gpu.createKernel(function(v1, v2) { return v1 / v2; }, { precision: 'single', output: [1] }); const idDixOff = gpu.createKernel(function(v1, v2) { return v1 / v2; }, { output: [1], precision: 'single', fixIntegerDivisionAccuracy: false }); if (!gpu.Kernel.features.isIntegerDivisionAccurate) { assert.ok( ( idFix(6, 3)[0] === 2 && idFix(6030401, 3991)[0] === 1511 ) && ( idDixOff(6, 3)[0] !== 2 || idDixOff(6030401, 3991)[0] !== 1511 ), "when bug is present should show bug!"); } else { assert.ok(idFix(6, 3)[0] === 2 && idDixOff(6, 3)[0] === 2, "when bug isn't present should not show bug!"); } gpu.destroy(); } (GPU.isSinglePrecisionSupported ? test : skip)('Issue #349 - test disable fix integer division bug auto', () => { testDisableFixIntegerDivisionBug(); }); (GPU.isSinglePrecisionSupported ? test : skip)('Issue #349 - test disable fix integer division bug gpu', () => { testDisableFixIntegerDivisionBug('gpu'); }); (GPU.isSinglePrecisionSupported && GPU.isWebGLSupported ? test : skip)('Issue #349 - test disable fix integer division bug webgl', () => { testDisableFixIntegerDivisionBug('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #349 - test disable fix integer division bug webgl2', () => { testDisableFixIntegerDivisionBug('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #349 - test disable fix integer division bug headlessgl', () => { testDisableFixIntegerDivisionBug('headlessgl'); }); test('Issue #349 - test disable fix integer division bug cpu', () => { testDisableFixIntegerDivisionBug('cpu'); }); ================================================ FILE: test/issues/357-modulus-issue.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #357'); // complimentary tests in features/arithmetic-operators.js & features/assignment-operators.js function testModKernel(mode) { const gpu = new GPU({mode}); const nValues = 100; const myFunc3 = gpu.createKernel(function(x) { return x[this.thread.x % 3]; }).setOutput([nValues]); const input = [1, 2, 3]; myFunc3(input); const expected = new Float32Array(nValues); for (let i = 0; i < nValues; i++) { expected[i] = input[i % 3]; } assert.deepEqual(myFunc3([1, 2, 3]), expected); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('Issue #357 - modulus issue webgl', () => { testModKernel('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #357 - modulus issue webgl2', () => { testModKernel('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #357 - modulus issue headlessgl', () => { testModKernel('headlessgl'); }); ================================================ FILE: test/issues/359-addfunction-params-wrong.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #359'); function testAddFunctionKernel(mode) { const gpu = new GPU({mode}); function clcC(xx) { return Math.abs(xx); } function intermediate(c1) { return clcC(c1); } gpu.addFunction(clcC); gpu.addFunction(intermediate); const nestFunctionsKernel = gpu.createKernel(function() { return intermediate(-1); }, { output: [1] }); assert.equal(nestFunctionsKernel()[0], 1); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('Issue #359 - addFunction calls addFunction issue webgl', () => { testAddFunctionKernel('webgl') }); (GPU.isWebGL2Supported ? test : skip)('Issue #359 - addFunction calls addFunction issue webgl2', () => { testAddFunctionKernel('webgl2') }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #359 - addFunction calls addFunction issue headlessgl', () => { testAddFunctionKernel('headlessgl') }); ================================================ FILE: test/issues/378-only-first-iteration.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #378'); function testOnlyFirstIterationSafari(mode) { const gpu = new GPU({ mode: mode }); const conflictingName = 0.4; const kernel = gpu.createKernel(function(iter) { let sum = 0; for(let i=2; i { testOnlyFirstIterationSafari('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #378 - only first iteration safari webgl2', () => { testOnlyFirstIterationSafari('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #378 - only first iteration safari headlessgl', () => { testOnlyFirstIterationSafari('headlessgl'); }); ================================================ FILE: test/issues/382-bad-constant.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #382'); function testModKernel(mode) { const gpu = new GPU({ mode: mode }); const conflictingName = 0.4; const kernel = gpu.createKernel(function(a, conflictingName) { return a[this.thread.x] + this.constants.conflictingName + conflictingName; }) .setOutput([1]) .setConstants({ conflictingName: conflictingName }); const result = kernel([1], 0.6); assert.equal(result[0], 2); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('Issue #382 - bad constant webgl', () => { testModKernel('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('Issue #382 - bad constant webgl2', () => { testModKernel('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #382 - bad constant headlessgl', () => { testModKernel('headlessgl'); }); ================================================ FILE: test/issues/390-thread-assignment.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { WebGLFunctionNode, WebGL2FunctionNode, CPUFunctionNode } = require('../../src'); describe('issue #390'); test('Issue #390 - thread assignment webgl', function(assert) { const node = new WebGLFunctionNode(function assignThreadToVar() { const x = this.thread.x; const y = this.thread.y; const sum = x + y; return sum; }.toString(), { output: [1], returnType: 'Number' }); assert.equal(node.toString(), 'float assignThreadToVar() {' + '\nfloat user_x=float(threadId.x);' + '\nfloat user_y=float(threadId.y);' + '\nfloat user_sum=(user_x+user_y);' + '\nreturn user_sum;' + '\n}'); const { x, y, sum } = node.contexts[1]; assert.equal(x.name, 'x'); assert.equal(x.valueType, 'Number'); assert.equal(y.name, 'y'); assert.equal(y.valueType, 'Number'); assert.equal(sum.name, 'sum'); assert.equal(sum.valueType, 'Number'); }); test('Issue #390 - thread assignment webgl2', function(assert) { const node = new WebGL2FunctionNode(function assignThreadToVar() { const x = this.thread.x; const y = this.thread.y; const sum = x + y; return sum; }.toString(), { output: [1], returnType: 'Number' }); assert.equal(node.toString(), 'float assignThreadToVar() {' + '\nfloat user_x=float(threadId.x);' + '\nfloat user_y=float(threadId.y);' + '\nfloat user_sum=(user_x+user_y);' + '\nreturn user_sum;' + '\n}'); const { x, y, sum } = node.contexts[1]; assert.equal(x.name, 'x'); assert.equal(x.valueType, 'Number'); assert.equal(y.name, 'y'); assert.equal(y.valueType, 'Number'); assert.equal(sum.name, 'sum'); assert.equal(sum.valueType, 'Number'); }); test('Issue #390 - thread assignment cpu', function(assert) { const node = new CPUFunctionNode(function assignThreadToVar() { const x = this.thread.x; const y = this.thread.y; const sum = x + y; return sum; }.toString(), { output: [1] }); assert.equal(node.toString(), 'function assignThreadToVar() {' + '\nconst user_x=_this.thread.x;' + '\nconst user_y=_this.thread.y;' + '\nconst user_sum=(user_x+user_y);' + '\nreturn user_sum;' + '\n}'); const { x, y, z, sum } = node.contexts[1]; assert.equal(x.name, 'x'); assert.equal(x.valueType, 'Integer'); assert.equal(y.name, 'y'); assert.equal(y.valueType, 'Integer'); assert.equal(sum.name, 'sum'); assert.equal(sum.valueType, 'Number'); }); test('Issue #390 (related) - output assignment webgl', function(assert) { const node = new WebGLFunctionNode(function assignThreadToVar() { const x = this.output.x; const y = this.output.y; const z = this.output.z; const sum = x + y + z; return sum; }.toString(), { output: [1,2,3] }); assert.equal(node.toString(), 'float assignThreadToVar() {' + '\nfloat user_x=1.0;' + '\nfloat user_y=2.0;' + '\nfloat user_z=3.0;' + '\nfloat user_sum=((user_x+user_y)+user_z);' + '\nreturn user_sum;' + '\n}'); const { x, y, z, sum } = node.contexts[1]; assert.equal(x.name, 'x'); assert.equal(x.valueType, 'Number'); assert.equal(y.name, 'y'); assert.equal(y.valueType, 'Number'); assert.equal(z.name, 'z'); assert.equal(z.valueType, 'Number'); assert.equal(sum.name, 'sum'); assert.equal(sum.valueType, 'Number'); }); test('Issue #390 (related) - output assignment webgl2', function(assert) { const node = new WebGL2FunctionNode(function assignThreadToVar() { const x = this.output.x; const y = this.output.y; const z = this.output.z; const sum = x + y + z; return sum; }.toString(), { output: [1,2,3] }); assert.equal(node.toString(), 'float assignThreadToVar() {' + '\nfloat user_x=1.0;' + '\nfloat user_y=2.0;' + '\nfloat user_z=3.0;' + '\nfloat user_sum=((user_x+user_y)+user_z);' + '\nreturn user_sum;' + '\n}'); const context = node.contexts[1]; const { x, y, z, sum } = context; assert.equal(x.name, 'x'); assert.equal(x.valueType, 'Number'); assert.equal(y.name, 'y'); assert.equal(y.valueType, 'Number'); assert.equal(z.name, 'z'); assert.equal(z.valueType, 'Number'); assert.equal(sum.name, 'sum'); assert.equal(sum.valueType, 'Number'); }); test('Issue #390 (related) - output assignment cpu', function(assert) { const node = new CPUFunctionNode(`function assignThreadToVar() { const x = this.output.x; const y = this.output.y; const z = this.output.z; const sum = x + y + z; return sum; }`, { output: [1,2,3] }); assert.equal(node.toString(), 'function assignThreadToVar() {' + '\nconst user_x=outputX;' + '\nconst user_y=outputY;' + '\nconst user_z=outputZ;' + '\nconst user_sum=((user_x+user_y)+user_z);' + '\nreturn user_sum;' + '\n}'); const context = node.contexts[1]; const { x, y, z, sum } = context; assert.equal(context['@contextType'], 'const/let'); assert.equal(x.name, 'x'); assert.equal(x.valueType, 'Number'); assert.equal(y.name, 'y'); assert.equal(y.valueType, 'Number'); assert.equal(z.name, 'z'); assert.equal(z.valueType, 'Number'); assert.equal(sum.name, 'sum'); assert.equal(sum.valueType, 'Number'); }); ================================================ FILE: test/issues/396-combine-kernels-example.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #396 - combine kernels example'); function combineKernelsExample(mode) { const gpu = new GPU({ mode }); const add = gpu.createKernel(function(a, b) { return a[this.thread.x] + b[this.thread.x]; }).setOutput([5]); const multiply = gpu.createKernel(function(a, b) { return a[this.thread.x] * b[this.thread.x]; }).setOutput([5]); const superKernel = gpu.combineKernels(add, multiply, function(a, b, c) { return multiply(add(a, b), c); }); const result = superKernel([1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]); assert.deepEqual(Array.from(result), [2, 8, 18, 32, 50 ]); gpu.destroy(); } test('auto', () => { combineKernelsExample(); }); test('gpu', () => { combineKernelsExample('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { combineKernelsExample('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { combineKernelsExample('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { combineKernelsExample('headlessgl'); }); test('cpu', () => { combineKernelsExample('cpu'); }); ================================================ FILE: test/issues/399-double-definition.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #399'); function doubleDefinitionUnsignedPrecision(mode) { const gpu = new GPU({ mode }); const toTexture = gpu.createKernel(function(value) { return value[this.thread.x]; }, { precision: 'unsigned', output: [2], pipeline: true, hardcodeConstants: true, immutable: true }); // basically it doesn't die, but builds all the way through to webGL assert.equal(toTexture([0, 1]).constructor.name, 'GLTextureUnsigned'); gpu.destroy(); } (GPU.isWebGLSupported ? test : skip)('Issue #399 - double definition unsigned precision webgl', () => { doubleDefinitionUnsignedPrecision('webgl') }); (GPU.isWebGL2Supported ? test : skip)('Issue #399 - double definition unsigned precision webgl2', () => { doubleDefinitionUnsignedPrecision('webgl2') }); (GPU.isHeadlessGLSupported ? test : skip)('Issue #399 - double definition unsigned precision headlessgl', () => { doubleDefinitionUnsignedPrecision('headlessgl') }); function doubleDefinitionSinglePrecision(mode) { const gpu = new GPU({ mode }); const toTexture = gpu.createKernel(function(value) { return value[this.thread.x]; }, { precision: 'single', output: [2], pipeline: true, hardcodeConstants: true, immutable: true }); // basically it doesn't die, but builds all the way through to webGL assert.equal(toTexture([0, 1]).constructor.name, 'GLTextureFloat'); gpu.destroy(); } (GPU.isWebGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('Issue #399 - double definition single precision webgl', () => { doubleDefinitionSinglePrecision('webgl') }); (GPU.isWebGL2Supported && GPU.isSinglePrecisionSupported ? test : skip)('Issue #399 - double definition single precision webgl2', () => { doubleDefinitionSinglePrecision('webgl2') }); (GPU.isHeadlessGLSupported && GPU.isSinglePrecisionSupported ? test : skip)('Issue #399 - double definition single precision headlessgl', () => { doubleDefinitionSinglePrecision('headlessgl') }); ================================================ FILE: test/issues/401-cpu-canvas-check.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU, CPUKernel } = require('../../src'); describe('issue #401'); test('Issue #401 - cpu no canvas graphical', function(assert) { assert.throws(function() { CPUKernel.prototype.build.apply({ setupConstants: function() {}, setupArguments: function() {}, validateSettings: function() {}, getKernelString: function() {}, translateSource: function() {}, buildSignature: function() {}, graphical: true, output: [1], canvas: null }, []); }, new Error('no canvas available for using graphical output'), 'throws when canvas is not available and using graphical output'); }); test('Issue #401 - cpu no canvas', function(assert) { CPUKernel.prototype.build.apply({ setupConstants: function() {}, setupArguments: function() {}, validateSettings: function() {}, getKernelString: function() {}, translateSource: function() {}, buildSignature: function() {}, graphical: false, output: [1], canvas: null }, []); assert.equal(true, true, 'ok when canvas is not available and not using graphical output'); }); ================================================ FILE: test/issues/410-if-statement.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #410 - if statement when unsigned on NVidia'); function ifStatement(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(a) { const paramDenom = a[this.thread.x][1] - a[this.thread.x][0]; if(paramDenom === 0) { return 100; } return 200; }) .setPrecision('unsigned') .setOutput([2]); const result = kernel( [ [0, 0], [0, 2] ] ); assert.deepEqual(Array.from(result), [100,200]); gpu.destroy(); } test('auto', () => { ifStatement(); }); test('gpu', () => { ifStatement('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { ifStatement('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { ifStatement('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { ifStatement('headlessgl'); }); test('cpu', () => { ifStatement('cpu'); }); ================================================ FILE: test/issues/422-warnings.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #422 - warnings'); function warnings(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(a, b) { return a[this.thread.x] + b[this.thread.x]; }).setOutput([10]); assert.deepEqual(Array.from(kernel([0,1,2,3,4,5,6,7,8,9], [0,1,2,3,4,5,6,7,8,9])), [0,2,4,6,8,10,12,14,16,18]); gpu.destroy(); } test('auto', () => { warnings(); }); test('gpu', () => { warnings('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { warnings('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { warnings('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { warnings('headlessgl'); }); test('cpu', () => { warnings('cpu'); }); ================================================ FILE: test/issues/470-modulus-wrong.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #470 - modulus wrong'); function testModulusWrong(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(mod) { return this.thread.x % mod; }, { output: [10], argumentTypes: { mod: 'Integer', }, }); const result = kernel(6); assert.equal(kernel.argumentTypes[0], 'Integer'); assert.equal(result[0], 0 % 6); assert.equal(result[1], 1 % 6); assert.equal(result[2], 2 % 6); assert.equal(result[3], 3 % 6); assert.equal(result[4], 4 % 6); assert.equal(result[5], 5 % 6); assert.equal(result[6], 6 % 6); assert.equal(result[7], 7 % 6); assert.equal(result[8], 8 % 6); assert.equal(result[9], 9 % 6); } test('auto', () => { testModulusWrong(); }); test('gpu', () => { testModulusWrong('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testModulusWrong('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testModulusWrong('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testModulusWrong('headlessgl'); }); test('cpu', () => { testModulusWrong('cpu'); }); ================================================ FILE: test/issues/471-canvas-issue.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #471 - canvas issue'); function testCanvasIssue(mode) { const gpu = new GPU({mode}); const render = gpu .createKernel(function () { this.color(0, 0, 0, 1); }) .setOutput([200, 200]) .setGraphical(true); render(); assert.equal(render.canvas.constructor.name, 'HTMLCanvasElement'); gpu.destroy(); } (GPU.isCanvasSupported ? test : skip)('auto', () => { testCanvasIssue(); }); (GPU.isCanvasSupported ? test : skip)('gpu', () => { testCanvasIssue('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testCanvasIssue('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testCanvasIssue('webgl2'); }); (GPU.isCanvasSupported ? test : skip)('cpu', () => { testCanvasIssue('cpu'); }); ================================================ FILE: test/issues/472-compilation-issue.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #472 - compilation issue'); function testCompilationIssue(mode) { const gpu = new GPU({ mode }); const kernelFunction = function(data, wobble) { let x = this.thread.x, y = this.thread.y; x = Math.floor(x + wobble * Math.sin(y / 10)); y = Math.floor(y + wobble * Math.cos(x / 10)); const n = 4 * (x + this.constants.w * (this.constants.h - y)); this.color(data[n] / 256, data[n + 1] / 256, data[n + 2] / 256, 1); }; const render = gpu.createKernel(kernelFunction, { constants: { w: 4, h: 4 }, output: [2, 2], graphical: true, }); render(new Uint8ClampedArray([ 230,233,240,255, 231,234,241,255, 232,235,242,255, 233,236,243,255 ]), 14 * Math.sin(Date.now() / 400)); assert.equal(render.getPixels().length, 2 * 2 * 4); gpu.destroy(); } test('auto', () => { testCompilationIssue(); }); test('gpu', () => { testCompilationIssue('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testCompilationIssue('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testCompilationIssue('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testCompilationIssue('headlessgl'); }); (GPU.isCanvasSupported ? test : skip)('cpu', () => { testCompilationIssue('cpu'); }); ================================================ FILE: test/issues/473-4-pixels.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #473 - only 4 pixels are shown'); function testOnly4PixelsAreShownRGBStaticOutput(mode) { const gpu = new GPU({ mode }); const render = gpu.createKernel( function() { this.color(1, 1, 1); }, { output: [20, 20], graphical: true, } ); render(); const pixels = render.getPixels(); assert.equal(pixels.length, 20 * 20 * 4); assert.equal(pixels.filter(v => v === 255).length, 20 * 20 * 4); gpu.destroy(); } test('RGB static output auto', () => { testOnly4PixelsAreShownRGBStaticOutput(); }); test('RGB static output gpu', () => { testOnly4PixelsAreShownRGBStaticOutput('gpu'); }); (GPU.isWebGLSupported ? test : skip)('RGB static output webgl', () => { testOnly4PixelsAreShownRGBStaticOutput('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('RGB static output webgl2', () => { testOnly4PixelsAreShownRGBStaticOutput('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('RGB static output headlessgl', () => { testOnly4PixelsAreShownRGBStaticOutput('headlessgl'); }); (GPU.isCanvasSupported ? test : skip)('RGB static output cpu', () => { testOnly4PixelsAreShownRGBStaticOutput('cpu'); }); function testOnly4PixelsAreShownRGBAStaticOutput(mode) { const gpu = new GPU({ mode }); const render = gpu.createKernel( function() { this.color(1, 1, 1, 1); }, { output: [20, 20], graphical: true, } ); render(); const pixels = render.getPixels(); assert.equal(pixels.length, 20 * 20 * 4); assert.equal(pixels.filter(v => v === 255).length, 20 * 20 * 4); gpu.destroy(); } test('RGBA static output auto', () => { testOnly4PixelsAreShownRGBAStaticOutput(); }); test('RGBA static output gpu', () => { testOnly4PixelsAreShownRGBAStaticOutput('gpu'); }); (GPU.isWebGLSupported ? test : skip)('RGBA static output webgl', () => { testOnly4PixelsAreShownRGBAStaticOutput('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('RGBA static output webgl2', () => { testOnly4PixelsAreShownRGBAStaticOutput('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('RGBA static output headlessgl', () => { testOnly4PixelsAreShownRGBAStaticOutput('headlessgl'); }); (GPU.isCanvasSupported ? test : skip)('RGBA static output cpu', () => { testOnly4PixelsAreShownRGBAStaticOutput('cpu'); }); function testOnly4PixelsAreShownRGBDynamicOutput(mode) { const gpu = new GPU({ mode }); const render = gpu.createKernel( function() { this.color(1, 1, 1); }, { output: [20, 20], graphical: true, dynamicOutput: true, } ); render(); const pixels = render.getPixels(); assert.equal(pixels.length, 20 * 20 * 4); assert.equal(pixels.filter(v => v === 255).length, 20 * 20 * 4); render.setOutput([10, 10]); render(); const pixels2 = render.getPixels(); assert.equal(pixels2.length, 10 * 10 * 4); assert.equal(pixels2.filter(v => v === 255).length, 10 * 10 * 4); gpu.destroy(); } test('rgb dynamic output auto', () => { testOnly4PixelsAreShownRGBDynamicOutput(); }); test('rgb dynamic output gpu', () => { testOnly4PixelsAreShownRGBDynamicOutput('gpu'); }); (GPU.isWebGLSupported ? test : skip)('rgb dynamic output webgl', () => { testOnly4PixelsAreShownRGBDynamicOutput('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('rgb dynamic output webgl2', () => { testOnly4PixelsAreShownRGBDynamicOutput('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('rgb dynamic output headlessgl', () => { testOnly4PixelsAreShownRGBDynamicOutput('headlessgl'); }); (GPU.isCanvasSupported ? test : skip)('rgb dynamic output cpu', () => { testOnly4PixelsAreShownRGBDynamicOutput('cpu'); }); function testOnly4PixelsAreShownRGBADynamicOutput(mode) { const gpu = new GPU({ mode }); const render = gpu.createKernel( function() { this.color(1, 1, 1, 1); }, { output: [20, 20], graphical: true, dynamicOutput: true, } ); render(); const pixels = render.getPixels(); assert.equal(pixels.length, 20 * 20 * 4); assert.equal(pixels.filter(v => v === 255).length, 20 * 20 * 4); render.setOutput([10, 10]); render(); const pixels2 = render.getPixels(); assert.equal(pixels2.length, 10 * 10 * 4); assert.equal(pixels2.filter(v => v === 255).length, 10 * 10 * 4); gpu.destroy(); } test('rgba dynamic output auto', () => { testOnly4PixelsAreShownRGBADynamicOutput(); }); test('rgba dynamic output gpu', () => { testOnly4PixelsAreShownRGBADynamicOutput('gpu'); }); (GPU.isWebGLSupported ? test : skip)('rgba dynamic output webgl', () => { testOnly4PixelsAreShownRGBADynamicOutput('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('rgba dynamic output webgl2', () => { testOnly4PixelsAreShownRGBADynamicOutput('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('rgba dynamic output headlessgl', () => { testOnly4PixelsAreShownRGBADynamicOutput('headlessgl'); }); (GPU.isCanvasSupported ? test : skip)('rgba dynamic output cpu', () => { testOnly4PixelsAreShownRGBADynamicOutput('cpu'); }); ================================================ FILE: test/issues/487-dynamic-arguments.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU } = require('../../src'); describe('issue #487 - pipeline dynamic arguments'); function testPipelineDynamicArguments(mode) { const gpu = new GPU({mode: mode}); const kernel = gpu.createKernel(function (w) { return this.thread.x + this.thread.y * w; }) .setPipeline(true) .setDynamicOutput(true); const sumRow = gpu.createKernel(function (texture, w) { let sum = 0; for (let i = 0; i < w; i++) sum = sum + texture[this.thread.x][i]; return sum; }) .setDynamicArguments(true) .setDynamicOutput(true); function doAThing(w, h) { kernel.setOutput([w, h]); let intermediate = kernel(w); const array = intermediate.toArray(); assert.equal(array.length, h); assert.equal(array[0].length, w); sumRow.setOutput([h]); const result = sumRow(intermediate, w); assert.equal(result.length, h); assert.equal(result[0].length, undefined); } doAThing(10, 5); doAThing(3, 2); gpu.destroy(); } test('(GPU only) auto', () => { testPipelineDynamicArguments(); }); test('(GPU only) gpu', () => { testPipelineDynamicArguments('gpu'); }); (GPU.isWebGLSupported ? test : skip)('(GPU only) webgl', () => { testPipelineDynamicArguments('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('(GPU only) webgl2', () => { testPipelineDynamicArguments('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('(GPU only) headlessgl', () => { testPipelineDynamicArguments('headlessgl'); }); ================================================ FILE: test/issues/493-strange-literal.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #493 - strange literal'); function testStrangeLiteral(mode) { const gpu = new GPU({ mode }); function kernelFunction(array) { const xFactor = (1 - 0) * this.constants.x + this.thread.x * this.constants.y; const yFactor = (1 - .5) * this.constants.x + this.thread.x * this.constants.y; const value = array[this.thread.x]; return [ value[0] / xFactor, value[1] / yFactor, ]; } const kernel1 = gpu.createKernel(kernelFunction) .setArgumentTypes({ array: 'Array1D(2)' }) .setConstants({ x: 1, y: 1}) .setOutput([1]); assert.deepEqual(kernel1([[1,2]]), [new Float32Array([1,4])]); const kernel2 = gpu.createKernel(kernelFunction) .setStrictIntegers(true) .setArgumentTypes({ array: 'Array1D(2)' }) .setConstants({ x: 1, y: 1}) .setOutput([1]); assert.deepEqual(kernel2([[1,2]]), [new Float32Array([1,4])]); gpu.destroy(); } test('auto', () => { testStrangeLiteral(); }); test('gpu', () => { testStrangeLiteral('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testStrangeLiteral('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testStrangeLiteral('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testStrangeLiteral('headlessgl'); }); test('cpu', () => { testStrangeLiteral('cpu'); }); ================================================ FILE: test/issues/500-sticky-arrays.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #500 - strange literal'); function testStickyArrays(mode) { const gpu = new GPU({ mode }); function processImage(image) { return image[0]; } gpu.addFunction(processImage); const kernel = gpu.createKernel(function(image1, image2, image3) { return [processImage(image1), processImage(image2), processImage(image3)]; }, { output: [1] }); assert.deepEqual(kernel([1], [2], [3]), [new Float32Array([1,2,3])]); } test('auto', () => { testStickyArrays(); }); test('gpu', () => { testStickyArrays('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testStickyArrays('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testStickyArrays('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testStickyArrays('headlessgl'); }); test('cpu', () => { testStickyArrays('cpu'); }); ================================================ FILE: test/issues/519-sanitize-names.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #519 - sanitize names'); function testSanitizeNames(mode) { const gpu = new GPU({ mode }); const kernel1 = gpu.createKernel(function (value__$, value__, value$, _) { return value__$ + value__ + value$ + _ + 1; }, { output: [1] }); assert.equal(kernel1(1, 2, 3, 4)[0], 11); gpu.destroy(); } test('auto', () => { testSanitizeNames(); }); test('gpu', () => { testSanitizeNames('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testSanitizeNames('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testSanitizeNames('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testSanitizeNames('headlessgl'); }); test('cpu', () => { testSanitizeNames('cpu'); }); ================================================ FILE: test/issues/553-permanent-flip.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #553 - permanent flip'); function testFixPermanentFlip(precision, mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(a1, a2, a3, a4) { return a2[this.thread.x]; }, { precision, output: [4] }); const arr = [1, 2, 3, 4]; for (let i = 0; i < 4; i++) { assert.deepEqual(kernel( 999, arr, new Image(2, 2), 999, ), new Float32Array(arr)); } gpu.destroy(); } // unsigned (typeof Image === 'undefined' ? skip : test)('auto unsigned', () => { testFixPermanentFlip('unsigned'); }); (typeof Image === 'undefined' ? skip : test)('gpu unsigned', () => { testFixPermanentFlip('unsigned', 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl unsigned', () => { testFixPermanentFlip('unsigned', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2 unsigned', () => { testFixPermanentFlip('unsigned', 'webgl2'); }); (typeof Image === 'undefined' ? skip : test)('cpu unsigned', () => { testFixPermanentFlip('unsigned', 'cpu'); }); // single (typeof Image === 'undefined' ? skip : test)('auto single', () => { testFixPermanentFlip('single'); }); (typeof Image === 'undefined' ? skip : test)('gpu single', () => { testFixPermanentFlip('single', 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl single', () => { testFixPermanentFlip('single', 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2 single', () => { testFixPermanentFlip('single', 'webgl2'); }); (typeof Image === 'undefined' ? skip : test)('cpu single', () => { testFixPermanentFlip('single', 'cpu'); }); ================================================ FILE: test/issues/556-minify-for-loop.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU, WebGLFunctionNode } = require('../../src'); describe('issue #556 - minify for loop'); const source = 'function w(t,e){for(var r=0,i=0;i 4, returnType: 'Number' }); assert.equal(node.toString(), `float w(sampler2D user_t,ivec2 user_tSize,ivec3 user_tDim, sampler2D user_e,ivec2 user_eSize,ivec3 user_eDim) { float user_r=0.0;int user_i=0; for (int safeI=0;safeI { testWebGLFunctionNode(); }); function testKernel(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(source, { output: [1, 1], constants: { size: 1 }, }); const result = kernel([[1]], [[1]]); assert.deepEqual(result, [new Float32Array([1])]); } test('kernel auto', () => { testKernel(); }); test('kernel gpu', () => { testKernel('gpu'); }); (GPU.isWebGLSupported ? test : skip)('kernel webgl', () => { testKernel('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('kernel webgl2', () => { testKernel('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('kernel headlessgl', () => { testKernel('headlessgl'); }); test('kernel cpu', () => { testKernel('cpu'); }); ================================================ FILE: test/issues/560-minification-madness.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #560 - minification madness'); function testMinificationMadness(mode, canvas) { const gpu = new GPU({ mode, canvas }); const kernel = gpu.createKernel(function (t, e, i, n, r) { for ( var o = this.constants.maxIter, a = this.constants.canvasWidth, s = this.constants.canvasHeight, l = i + (n - i) * (this.thread.y / s), c = t + (e - t) * (this.thread.x / a), p = 0, u = 0, h = 0, d = 0; p * p + u * u < 4 && h < o ;) d = p * p - u * u + c, u = 2 * p * u + l, p = d, h++; h === o ? this.color(0, 0, 0, 1) : this.color(r[3 * h] / 255, r[3 * h + 1] / 255, r[3 * h + 2] / 255, 1); }, { output: [1, 1], constants: { maxIter: 1, canvasWidth: 1, canvasHeight: 1, }, graphical: true, }); kernel(1,2,3,4,[5]); assert.ok(kernel.getPixels()); if (kernel.context && kernel.context.getError) assert.ok(kernel.context.getError() === 0); gpu.destroy(); } test('auto', () => { testMinificationMadness(); }); test('gpu', () => { testMinificationMadness('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testMinificationMadness('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testMinificationMadness('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testMinificationMadness('headlessgl'); }); test('cpu', () => { const mockData = []; const result = true; mockData.data = { set: () => {}, slice: () => result }; const mockPutImageData = () => {}; const mockContext = { createImageData: () => mockData, putImageData: mockPutImageData, }; const mockCanvas = { getContext: () => mockContext }; testMinificationMadness('cpu', typeof HTMLCanvasElement === 'undefined' ? mockCanvas : null); }); ================================================ FILE: test/issues/564-boolean.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #564 - boolean handled'); function testBooleanHandled(fft, mode) { const gpu = new GPU({ mode }); gpu.addNativeFunction('fft', fft, { returnType: 'Array(4)' }); const kernel = gpu.createKernel( function(){ let s = true; return fft(s); },{ output:[1], } ); assert.deepEqual(Array.from(kernel()[0]), [1,1,1,1]); gpu.destroy(); } const fft = `vec4 fft (bool horizontal){ return vec4(1,1,horizontal?1:0,1); }`; test('auto', () => { testBooleanHandled(fft); }); test('gpu', () => { testBooleanHandled(fft, 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testBooleanHandled(fft, 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testBooleanHandled(fft, 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testBooleanHandled(fft, 'headlessgl'); }); test('cpu', () => { testBooleanHandled(`function fft(horizontal){ return [1,1,horizontal?1:0,1]; }`, 'cpu'); }); ================================================ FILE: test/issues/567-wrong-modulus.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #567 - wrong modulus'); function testWrongModulus(mode) { const gpu = new GPU({ mode }); const kernel1 = gpu.createKernel(function () { return 91 % 7; }, { output: [1] }); assert.equal(kernel1()[0], 91 % 7); const kernel2 = gpu.createKernel(function (value1, value2) { return value1 % value2; }, { output: [1], }); assert.equal(kernel2(91, 7)[0], 91 % 7); const kernel3 = gpu.createKernel(function (value1, value2) { return value1 % value2; }, { output: [1], }); assert.equal(kernel3(91, 7)[0], 91 % 7); const kernel4 = gpu.createKernel(function () { return this.constants.value1 % this.constants.value2; }, { output: [1], constants: { value1: 91, value2: 7, } }); assert.equal(kernel4()[0].toFixed(2), 91 % 7); const kernel5 = gpu.createKernel(function () { return 91 % this.constants.value; }, { output: [1], constants: { value: 7 }, strictIntegers: true }); assert.equal(kernel5()[0], 91 % 7); gpu.destroy(); } test('auto', () => { testWrongModulus(); }); test('gpu', () => { testWrongModulus('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testWrongModulus('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testWrongModulus('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testWrongModulus('headlessgl'); }); test('cpu', () => { testWrongModulus('cpu'); }); ================================================ FILE: test/issues/585-inaccurate-lookups.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #585 - inaccurate lookups'); function testResize(mode) { const gpu = new GPU({ mode }); const kernel = gpu.createKernel(function(value) { return value[this.thread.x]; }, { output: [4], }); const result = kernel([0,1,2,3]); assert.equal(Math.round(result[0]), 0); assert.equal(Math.round(result[1]), 1); assert.equal(Math.round(result[2]), 2); assert.equal(Math.round(result[3]), 3); gpu.destroy(); } test('auto', () => { testResize(); }); test('gpu', () => { testResize('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testResize('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testResize('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testResize('headlessgl'); }); test('cpu', () => { testResize('cpu'); }); ================================================ FILE: test/issues/586-unable-to-resize.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #586 - unable to resize'); function testResize(convert, mode) { const gpu = new GPU({ mode }); const createTexture1 = gpu.createKernel(function() { return 1; }, { output: [2, 2], pipeline: false}); const createTexture2 = gpu.createKernel(function() { return 1; }, { output: [4, 4], pipeline: true}); var t1 = createTexture1(); var t2 = createTexture2(); assert.deepEqual(convert(t2), [ new Float32Array([1,1,1,1]), new Float32Array([1,1,1,1]), new Float32Array([1,1,1,1]), new Float32Array([1,1,1,1]), ]); gpu.destroy(); } test('auto', () => { testResize(t => t.toArray()); }); test('gpu', () => { testResize(t => t.toArray(), 'gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testResize(t => t.toArray(), 'webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testResize(t => t.toArray(), 'webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testResize(t => t.toArray(), 'headlessgl'); }); test('cpu', () => { testResize(a => a, 'cpu'); }); ================================================ FILE: test/issues/608-rewritten-arrays.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #608 - rewritten arrays'); function testRewrittenArrays(mode) { const gpu = new GPU({ mode }); const kernel1 = gpu.createKernel(function (a, b) { return a[this.thread.y][this.thread.x]; }, { constants: { c: [21, 23] }, output: [2, 2] }); const kernel2 = gpu.createKernel(function (a, b) { return b[this.thread.y][this.thread.x]; }, { constants: { c: [21, 23] }, output: [2, 2] }); const kernel3 = gpu.createKernel(function (a, b) { return this.constants.c[this.thread.x]; }, { constants: { c: [21, 23] }, output: [2, 2] }); const a = [ [2, 3], [5, 7] ]; const b = [ [11, 13], [17, 19] ]; const cExpected = [ [21, 23], [21, 23] ]; // testing twice to ensure constants are reset assert.deepEqual(kernel1(a, b).map(v => Array.from(v)), a); assert.deepEqual(kernel2(a, b).map(v => Array.from(v)), b); assert.deepEqual(kernel3(a, b).map(v => Array.from(v)), cExpected); assert.deepEqual(kernel1(a, b).map(v => Array.from(v)), a); assert.deepEqual(kernel2(a, b).map(v => Array.from(v)), b); assert.deepEqual(kernel3(a, b).map(v => Array.from(v)), cExpected); gpu.destroy(); } test('auto', () => { testRewrittenArrays(); }); test('gpu', () => { testRewrittenArrays('gpu'); }); (GPU.isWebGLSupported ? test : skip)('webgl', () => { testRewrittenArrays('webgl'); }); (GPU.isWebGL2Supported ? test : skip)('webgl2', () => { testRewrittenArrays('webgl2'); }); (GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { testRewrittenArrays('headlessgl'); }); test('cpu', () => { testRewrittenArrays('cpu'); }); ================================================ FILE: test/issues/91-create-kernel-map-array.js ================================================ const { assert, skip, test, module: describe } = require('qunit'); const { GPU, HeadlessGLKernel, WebGLKernel, WebGL2Kernel, CPUKernel } = require('../../src'); describe('issue #91'); function getResult(mode) { const A = [ [1, 2], [3, 4], [5, 6] ]; const B = [ [6, 5, 4], [3, 2, 1] ]; const gpu = new GPU({ mode }); function multiply(b, a, y, x) { let sum = 0; for (let i = 0; i < 2; i++) { sum += b[y][i] * a[i][x]; } return sum; } const kernels = gpu.createKernelMap({ multiplyResult: multiply }, function (a, b) { return multiply(b, a, this.thread.y, this.thread.x); }) .setOutput([2, 2]); const result = kernels(A, B).result; assert.deepEqual(Array.from(result[0]), [21,32]); assert.deepEqual(Array.from(result[1]), [9,14]); gpu.destroy(); return kernels; } (GPU.isWebGL2Supported || (GPU.isHeadlessGLSupported && HeadlessGLKernel.features.kernelMap) ? test : skip)("Issue #91 - type detection auto", () => { getResult(); }); (GPU.isWebGL2Supported || (GPU.isHeadlessGLSupported && HeadlessGLKernel.features.kernelMap) ? test : skip)("Issue #91 - type detection gpu", () => { getResult('gpu'); }); (GPU.isWebGLSupported ? test : skip)("Issue #91 - type detection webgl", () => { const kernel = getResult('webgl'); assert.equal(kernel.kernel.constructor, WebGLKernel, 'kernel type is wrong'); }); (GPU.isWebGL2Supported ? test : skip)("Issue #91 - type detection webgl2", () => { const kernel = getResult('webgl2'); assert.equal(kernel.kernel.constructor, WebGL2Kernel, 'kernel type is wrong'); }); (GPU.isHeadlessGLSupported ? test : skip)("Issue #91 - type detection headlessgl", () => { const kernel = getResult('headlessgl'); assert.equal(kernel.kernel.constructor, HeadlessGLKernel, 'kernel type is wrong'); }); test("Issue #91 - type detection cpu", () => { const kernel = getResult('cpu'); assert.equal(kernel.kernel.constructor, CPUKernel, 'kernel type is wrong'); }); ================================================ FILE: test/issues/96-param-names.js ================================================ const { assert, skip, test, module: describe, only } = require('qunit'); const { GPU } = require('../../src'); describe('issue #96'); function getResult(mode) { const A = [ [1, 1, 1], [1, 1, 1] ]; const B = [ [1, 1], [1, 1], [1, 1] ]; const gpu = new GPU({ mode }); function multiply(m, n, y, x) { let sum = 0; for (let i = 0; i < 2; i++) { sum += m[y][i] * n[i][x]; } return sum; } const kernels = gpu.createKernelMap({ multiplyResult: multiply }, function (a, b) { return multiply(b, a, this.thread.y, this.thread.x); }) .setOutput([B.length, A.length]); const result = kernels(A, B).result; assert.deepEqual(Array.from(result[0]), [2,2,2]); assert.deepEqual(Array.from(result[1]), [2,2,2]); assert.deepEqual(result.length, 2); gpu.destroy(); return result; } (GPU.isKernelMapSupported ? test : skip)("Issue #96 - param names auto", () => { getResult(); }); (GPU.isKernelMapSupported ? test : skip)("Issue #96 - param names gpu", () => { getResult('gpu'); }); (GPU.isWebGLSupported ? test : skip)("Issue #96 - param names webgl", () => { getResult('webgl'); }); (GPU.isWebGL2Supported ? test : skip)("Issue #96 - param names webgl2", () => { getResult('webgl2'); }); (GPU.isHeadlessGLSupported && GPU.isKernelMapSupported ? test : skip)("Issue #96 - param names headlessgl", () => { getResult('headlessgl'); }); test("Issue #96 - param names cpu", () => { getResult('cpu'); }); ================================================ FILE: test/test-utils.js ================================================ const testUtils = { /** * A visual debug utility * @param {GPU} gpu * @param rgba * @param width * @param height * @return {Object[]} */ splitRGBAToCanvases: (gpu, rgba, width, height) => { const visualKernelR = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(pixel.r / 255, 0, 0, 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelR(rgba); const visualKernelG = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(0, pixel.g / 255, 0, 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelG(rgba); const visualKernelB = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(0, 0, pixel.b / 255, 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelB(rgba); const visualKernelA = gpu.createKernel(function(v) { const pixel = v[this.thread.y][this.thread.x]; this.color(255, 255, 255, pixel.a / 255); }, { output: [width, height], graphical: true, argumentTypes: { v: 'Array2D(4)' } }); visualKernelA(rgba); return [ visualKernelR.getPixels(), visualKernelG.getPixels(), visualKernelB.getPixels(), visualKernelA.getPixels(), ]; }, }; module.exports = testUtils;