Left click to zoom in, right click to zoom out.
+
+
+
diff --git a/examples/mandelbulb.html b/examples/mandelbulb.html
new file mode 100644
index 00000000..5b93c642
--- /dev/null
+++ b/examples/mandelbulb.html
@@ -0,0 +1,587 @@
+
+
+
+
+
+
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.
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/examples/random.html b/examples/random.html
new file mode 100644
index 00000000..0ef1b50c
--- /dev/null
+++ b/examples/random.html
@@ -0,0 +1,66 @@
+
+
+
+ This handles all the raw state, converted state, etc. Of a single function.
- *
- * @prop functionName - {String} Name of the function
- * @prop jsFunction - {Function} The JS Function the node represents
- * @prop jsFunctionString - {String} jsFunction.toString()
- * @prop paramNames - {String[]} Parameter names of the function
- * @prop paramTypes - {String[]} Shader land parameters type assumption
- * @prop isRootKernel - {Boolean} Special indicator, for kernel function
- * @prop webglFunctionString - {String} webgl converted function string
- * @prop openglFunctionString - {String} opengl converted function string
- * @prop calledFunctions - {String[]} List of all the functions called
- * @prop initVariables - {String[]} List of variables initialized in the function
- * @prop readVariables - {String[]} List of variables read operations occur
- * @prop writeVariables - {String[]} List of variables write operations occur
- *
*/
-module.exports = class CPUFunctionNode extends BaseFunctionNode {
- generate(options) {
- this.functionString = this.jsFunctionString;
- }
-
- /**
- * @memberOf CPUFunctionNode#
- * @function
- * @name getFunctionPrototypeString
- *
- * @desc Returns the converted webgl shader function equivalent of the JS function
- *
- * @returns {String} webgl function string, result is cached under this.getFunctionPrototypeString
- *
- */
- getFunctionPrototypeString(options) {
- return this.functionString;
- }
+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
};
\ No newline at end of file
diff --git a/src/backend/cpu/kernel-string.js b/src/backend/cpu/kernel-string.js
index 4b1d1cb1..d619b477 100644
--- a/src/backend/cpu/kernel-string.js
+++ b/src/backend/cpu/kernel-string.js
@@ -1,58 +1,185 @@
-'use strict';
-
-const utils = require('../../core/utils');
-const kernelRunShortcut = require('../kernel-run-shortcut');
-
-module.exports = function(cpuKernel, name) {
- return `() => {
- ${ kernelRunShortcut.toString() };
- const utils = {
- allPropertiesOf: function ${ utils.allPropertiesOf.toString() },
- clone: function ${ utils.clone.toString() },
- /*splitArray: function ${ utils.splitArray.toString() },
- getArgumentType: function ${ utils.getArgumentType.toString() },
- getDimensions: function ${ utils.getDimensions.toString() },
- dimToTexSize: function ${ utils.dimToTexSize.toString() },
- copyFlatten: function ${ utils.copyFlatten.toString() },
- flatten: function ${ utils.flatten.toString() },
- systemEndianness: '${ utils.systemEndianness() }',
- initWebGl: function ${ utils.initWebGl.toString() },
- isArray: function ${ utils.isArray.toString() }*/
- };
- class ${ name || 'Kernel' } {
- constructor() {
- this.argumentsLength = 0;
- this._canvas = null;
- this._webGl = null;
- this.built = false;
- this.program = null;
- this.paramNames = ${ JSON.stringify(cpuKernel.paramNames) };
- this.paramTypes = ${ JSON.stringify(cpuKernel.paramTypes) };
- this.texSize = ${ JSON.stringify(cpuKernel.texSize) };
- this.dimensions = ${ JSON.stringify(cpuKernel.dimensions) };
- this._kernelString = \`${ cpuKernel._kernelString }\`;
- this.run = function() {
- this.run = null;
- this.build();
- return this.run.apply(this, arguments);
- }.bind(this);
- this.thread = {
- x: 0,
- y: 0,
- z: 0
- };
- this.runDimensions = {
- x: null,
- y: null,
- z: null
- };
+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');
}
- setCanvas(canvas) { this._canvas = canvas; return this; }
- setWebGl(webGl) { this._webGl = webGl; return this; }
- ${ cpuKernel.build.toString() }
- run () { ${ cpuKernel.kernelString } }
- getKernelString() { return this._kernelString; }
- };
- return kernelRunShortcut(new Kernel());
- };`;
+ });
+ 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
};
\ No newline at end of file
diff --git a/src/backend/cpu/kernel.js b/src/backend/cpu/kernel.js
index f0fe7be9..13279e5c 100644
--- a/src/backend/cpu/kernel.js
+++ b/src/backend/cpu/kernel.js
@@ -1,337 +1,673 @@
-'use strict';
-
-const KernelBase = require('../kernel-base');
-const utils = require('../../core/utils');
-const kernelString = require('./kernel-string');
-
-module.exports = class CPUKernel extends KernelBase {
-
- /**
- * @constructor CPUKernel
- *
- * @desc Kernel Implementation for CPU.
- *
- * Instantiates properties to the CPU Kernel.
- *
- * @extends KernelBase
- *
- * @prop {Object} thread - The thread dimensions, x, y and z
- * @prop {Object} runDimensions - The canvas dimensions
- * @prop {Object} functionBuilder - Function Builder instance bound to this Kernel
- * @prop {Function} run - Method to run the kernel
- *
- */
- constructor(fnString, settings) {
- super(fnString, settings);
- this._fnBody = utils.getFunctionBodyFromString(fnString);
- this.functionBuilder = settings.functionBuilder;
- this._fn = null;
- this.run = null;
- this._canvasCtx = null;
- this._imageData = null;
- this._colorData = null;
- this._kernelString = null;
- this.thread = {
- x: 0,
- y: 0,
- z: 0
- };
- this.runDimensions = {
- x: null,
- y: null,
- z: null
- };
-
- this.run = function() {
- this.run = null;
- this.build();
- return this.run.apply(this, arguments);
- }.bind(this);
- }
-
- /**
- * @memberOf CPUKernel#
- * @function
- * @name validateOptions
- *
- * @desc Validate options related to CPU Kernel, such as
- * dimensions size, and auto dimension support.
- *
- */
- validateOptions() {
- if (!this.dimensions || this.dimensions.length === 0) {
- if (arguments.length !== 1) {
- throw 'Auto dimensions only supported for kernels with only one input';
- }
-
- const argType = utils.getArgumentType(arguments[0]);
- if (argType === 'Array') {
- this.dimensions = utils.getDimensions(argType);
- } else if (argType === 'Texture') {
- this.dimensions = arguments[0].dimensions;
- } else {
- throw 'Auto dimensions not supported for input type: ' + argType;
- }
- }
- }
-
- /**
- * @memberOf CPUKernel#
- * @function
- * @name build
- *
- * @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() {
-
- //
- // NOTE: these are optional safety checks
- // does not actually do anything
- //
- const kernelArgs = [];
- for (let i = 0; i < arguments.length; i++) {
- const argType = utils.getArgumentType(arguments[i]);
- if (argType === 'Array' || argType === 'Number') {
- kernelArgs[i] = arguments[i];
- } else if (argType === 'Texture') {
- kernelArgs[i] = arguments[i].toArray();
- } else {
- throw 'Input type not supported (CPU): ' + arguments[i];
- }
- }
-
- const threadDim = this.threadDim || (this.threadDim = utils.clone(this.dimensions));
-
- while (threadDim.length < 3) {
- threadDim.push(1);
- }
-
- if (this.graphical) {
- const canvas = this.getCanvas();
- this.runDimensions.x = canvas.width = threadDim[0];
- this.runDimensions.y = canvas.height = threadDim[1];
- this._canvasCtx = canvas.getContext('2d');
- this._imageData = this._canvasCtx.createImageData(threadDim[0], threadDim[1]);
- this._colorData = new Uint8ClampedArray(threadDim[0] * threadDim[1] * 4);
- }
-
- const kernelString = this.getKernelString();
-
- if (this.debug) {
- console.log('Options:');
- console.dir(this);
- console.log('Function output:');
- console.log(kernelString);
- }
-
- this.kernelString = kernelString;
- this.run = new Function([], kernelString).bind(this)();
- }
-
- 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.runDimensions.x;
- const height = this.runDimensions.y;
-
- 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;
- }
-
- /**
- * @memberOf CPUKernel#
- * @function
- * @name getKernelString
- *
- * @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;
-
- const paramNames = this.paramNames;
- const builder = this.functionBuilder;
-
- // Thread dim fix (to make compilable)
- const threadDim = this.threadDim || (this.threadDim = utils.clone(this.dimensions));
- while (threadDim.length < 3) {
- threadDim.push(1);
- }
-
- if (this.subKernels !== null) {
- this.subKernelOutputTextures = [];
- this.subKernelOutputVariableNames = [];
- for (let i = 0; i < this.subKernels.length; i++) {
- const subKernel = this.subKernels[i];
- builder.addSubKernel(subKernel);
- this.subKernelOutputVariableNames.push(subKernel.name + 'Result');
- }
-
- } else if (this.subKernelProperties !== null) {
- this.subKernelOutputVariableNames = [];
- let i = 0;
- for (let p in this.subKernelProperties) {
- if (!this.subKernelProperties.hasOwnProperty(p)) continue;
- const subKernel = this.subKernelProperties[p];
- builder.addSubKernel(subKernel);
- this.subKernelOutputVariableNames.push(subKernel.name + 'Result');
- i++;
- }
- }
-
- return this._kernelString = `
- ${ this.constants ? Object.keys(this.constants).map((key) => { return `var ${ key } = ${ this.constants[key] }`; }).join(';\n') + ';\n' : '' }
- ${ this.subKernelOutputVariableNames === null
- ? ''
- : this.subKernelOutputVariableNames.map((name) => ` var ${ name } = null;\n`).join('')
- }
- ${ builder.getPrototypeString() }
- var fn = function fn(${ this.paramNames.join(', ') }) { ${ this._fnBody } }.bind(this);
- return function (${ this.paramNames.join(', ') }) {
- var ret = new Array(${ threadDim[2] });
- ${ this.subKernelOutputVariableNames === null
- ? ''
- : this.subKernelOutputVariableNames.map((name) => ` ${ name } = new Array(${ threadDim[2] });\n`).join('')
- }
- for (this.thread.z = 0; this.thread.z < ${ threadDim[2] }; this.thread.z++) {
- ret[this.thread.z] = new Array(${ threadDim[1] });
- ${ this.subKernelOutputVariableNames === null
- ? ''
- : this.subKernelOutputVariableNames.map((name) => ` ${ name }[this.thread.z] = new Array(${ threadDim[1] });\n`).join('')
- }
- for (this.thread.y = 0; this.thread.y < ${ threadDim[1] }; this.thread.y++) {
- ret[this.thread.z][this.thread.y] = new Array(${ threadDim[0] });
- ${ this.subKernelOutputVariableNames === null
- ? ''
- : this.subKernelOutputVariableNames.map((name) => ` ${ name }[this.thread.z][this.thread.y] = new Array(${ threadDim[0] });\n`).join('')
- }
- for (this.thread.x = 0; this.thread.x < ${ threadDim[0] }; this.thread.x++) {
- ret[this.thread.z][this.thread.y][this.thread.x] = fn(${ this.paramNames.join(', ') });
- }
+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) {
- this._imageData.data.set(this._colorData);
- this._canvasCtx.putImageData(this._imageData, 0, 0);
- return;
+ if (this.output.length !== 2) {
+ throw new Error('Output must have 2 dimensions on graphical mode');
+ }
}
-
- if (this.dimensions.length === 1) {
- ret = ret[0][0];
- ${ this.subKernelOutputVariableNames === null
- ? ''
- : this.subKernelOutputVariableNames.map((name) => ` ${ name } = ${ name }[0][0];\n`).join('')
- }
-
- } else if (this.dimensions.length === 2) {
- ret = ret[0];
- ${ this.subKernelOutputVariableNames === null
- ? ''
- : this.subKernelOutputVariableNames.map((name) => ` ${ name } = ${ name }[0];\n`).join('')
+
+ 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 }`);
}
-
- ${ this.subKernelOutputVariableNames === null
- ? 'return ret;\n'
- : this.subKernels !== null
- ? `var result = [
- ${ this.subKernelOutputVariableNames.map((name) => `${ name }`).join(',\n') }
- ];
- result.result = ret;
- return result;\n`
- : `return {
- result: ret,
- ${ Object.keys(this.subKernelProperties).map((name, i) => `${ name }: ${ this.subKernelOutputVariableNames[i] }`).join(',\n') }
- };`
+ }
+
+ _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 }
}
- }.bind(this);`;
- }
-
- /**
- * @memberOf CPUKernel#
- * @function
- * @name toString
- *
- * @desc Returns the *pre-compiled* Kernel as a JS Object String, that can be reused.
- *
- */
- toString() {
- return kernelString(this);
- }
-
- /**
- * @memberOf CPUKernel#
- * @function
- * @name precompileKernelObj
- *
- * @desc Precompile the kernel into a single object,
- * that can be used for building the execution kernel subsequently.
- *
- * @param {Array} argTypes - Array of argument types
- *
- * Return:
- * Compiled kernel {Object}
- *
- */
- precompileKernelObj(argTypes) {
-
- const threadDim = this.threadDim || (this.threadDim = utils.clone(this.dimensions));
-
-
- return {
- threadDim: threadDim
- };
- }
-
- /**
- * @memberOf CPUKernel
- * @function
- * @name compileKernel
- * @static
- *
- * @desc Takes a previously precompiled kernel object,
- * and complete compilation into a full kernel
- *
- * @returns {Function} Compiled kernel
- *
- */
- static compileKernel(precompileObj) {
-
- // Extract values from precompiled obj
- const threadDim = precompileObj.threadDim;
-
- // Normalize certain values : For actual build
- while (threadDim.length < 3) {
- threadDim.push(1);
- }
-
- }
+ }
+ }`;
+ }
+
+ _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
};
\ No newline at end of file
diff --git a/src/backend/cpu/runner.js b/src/backend/cpu/runner.js
deleted file mode 100644
index 48052f0d..00000000
--- a/src/backend/cpu/runner.js
+++ /dev/null
@@ -1,40 +0,0 @@
-'use strict';
-
-const utils = require('../../core/utils');
-const RunnerBase = require('../runner-base');
-const CPUKernel = require('./kernel');
-const CPUFunctionBuilder = require('./function-builder');
-
-module.exports = class CPURunner extends RunnerBase {
-
- /**
- * @constructor CPURunner
- *
- * @desc Instantiates a Runner instance for the kernel.
- *
- * @extends RunnerBase
- *
- * @param {Object} settings - Settings to instantiate properties in RunnerBase, with given values
- *
- */
-
- constructor(settings) {
- super(new CPUFunctionBuilder(), settings);
- this.Kernel = CPUKernel;
- this.kernel = null;
- }
-
- /**
- * @memberOf CPURunner#
- * @function
- * @name getMode()
- *
- * Return the current mode in which gpu.js is executing.
- *
- * @returns {String} The current mode; "cpu".
- *
- */
- getMode() {
- return 'cpu';
- }
-};
\ No newline at end of file
diff --git a/src/backend/function-builder-base.js b/src/backend/function-builder-base.js
deleted file mode 100644
index dd427200..00000000
--- a/src/backend/function-builder-base.js
+++ /dev/null
@@ -1,126 +0,0 @@
-'use strict';
-
-module.exports = class FunctionBuilderBase {
-
- /**
- * @constructor FunctionBuilderBase
- *
- * @desc This handles all the raw state, converted state, etc. of a single function.
- * [INTERNAL] A collection of functionNodes.
- *
- * @prop {Object} nodeMap - Object map, where nodeMap[function] = new FunctionNode;
- * @prop {Object} gpu - The current gpu instance bound to this builder
- * @prop {Object} rootKernel - The root kernel object, contains the paramNames, dimensions etc.
- *
- */
- constructor(gpu) {
- this.nodeMap = {};
- this.gpu = gpu;
- this.rootKernel = null;
- }
-
- /**
- * @memberOf FunctionBuilderBase#
- * @function
- * @name addFunction
- *
- * @desc Instantiates a FunctionNode, and add it to the nodeMap
- *
- * @param {GPU} gpu - The GPU instance
- * @param {String} functionName - Function name to assume, if its null, it attempts to extract from the function
- * @param {Function} jsFunction - JS Function to do conversion
- * @param {String[]|Object} paramTypes - Parameter type array, assumes all parameters are 'float' if null
- * @param {String} returnType - The return type, assumes 'float' if null
- *
- */
- addFunction(functionName, jsFunction, paramTypes, returnType) {
- throw new Error('addFunction not supported on base');
- }
-
- /**
- * @memberOf FunctionBuilderBase#
- * @function
- * @name addFunctionNode
- *
- * @desc Add the funciton node directly
- *
- * @param {functionNode} inNode - functionNode to add
- *
- */
- addFunctionNode(inNode) {
- this.nodeMap[inNode.functionName] = inNode;
- if (inNode.isRootKernel) {
- this.rootKernel = inNode;
- }
- }
-
- /**
- * @memberOf FunctionBuilderBase#
- * @function
- * @name traceFunctionCalls
- *
- * @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, parent) {
- functionName = functionName || 'kernel';
- retList = retList || [];
-
- const fNode = this.nodeMap[functionName];
- if (fNode) {
- // Check if function already exists
- if (retList.indexOf(functionName) >= 0) {
- // Does nothing if already traced
- } else {
- retList.push(functionName);
- if (parent) {
- fNode.parent = parent;
- fNode.constants = parent.constants;
- }
- fNode.getFunctionString(); //ensure JS trace is done
- for (let i = 0; i < fNode.calledFunctions.length; ++i) {
- this.traceFunctionCalls(fNode.calledFunctions[i], retList, fNode);
- }
- }
- }
-
- return retList;
- }
-
-
-
-
- //---------------------------------------------------------
- //
- // Polyfill stuff
- //
- //---------------------------------------------------------
-
- // Round function used in polyfill
- static round(a) {
- return round(a);
- }
-
- /**
- * @memberOf FunctionBuilderBase#
- * @function
- * @name polyfillStandardFunctions
- *
- * @desc Polyfill in the missing Math functions (round)
- *
- */
- polyfillStandardFunctions() {
- this.addFunction('round', round);
- }
-};
-
-function round(a) {
- return Math.floor(a + 0.5);
-}
\ No newline at end of file
diff --git a/src/backend/function-builder.js b/src/backend/function-builder.js
new file mode 100644
index 00000000..1633f0e8
--- /dev/null
+++ b/src/backend/function-builder.js
@@ -0,0 +1,627 @@
+/**
+ * @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
+};
\ No newline at end of file
diff --git a/src/backend/function-node-base.js b/src/backend/function-node-base.js
deleted file mode 100644
index 815b0952..00000000
--- a/src/backend/function-node-base.js
+++ /dev/null
@@ -1,316 +0,0 @@
-'use strict';
-
-const utils = require('../core/utils');
-const acorn = require('acorn');
-
-module.exports = class BaseFunctionNode {
-
- /**
- * @constructor FunctionNodeBase
- *
- * @desc Represents a single function, inside JS, webGL, or openGL.
- *
- * This handles all the raw state, converted state, etc. Of a single function.
- *
- * @prop {String} functionName - Name of the function
- * @prop {Function} jsFunction - The JS Function the node represents
- * @prop {String} jsFunctionString - jsFunction.toString()
- * @prop {String[]} paramNames - Parameter names of the function
- * @prop {String[]} paramTypes - Shader land parameters type assumption
- * @prop {Boolean} isRootKernel - Special indicator, for kernel function
- * @prop {String} webglFunctionString - webgl converted function string
- * @prop {String} openglFunctionString - opengl converted function string
- * @prop {String[]} calledFunctions - List of all the functions called
- * @prop {String[]} initVariables - List of variables initialized in the function
- * @prop {String[]} readVariables - List of variables read operations occur
- * @prop {String[]} writeVariables - List of variables write operations occur
- *
- * @param {GPU} gpu - The GPU instance
- * @param {String} functionName - Function name to assume, if its null, it attempts to extract from the function
- * @param {Function|String} jsFunction - JS Function to do conversion
- * @param {String[]|Object} paramTypes - Parameter type array, assumes all parameters are 'float' if null
- * @param {String} returnType - The return type, assumes 'float' if null
- *
- */
- constructor(functionName, jsFunction, options, paramTypes, returnType) {
- //
- // Internal vars setup
- //
- this.calledFunctions = [];
- this.calledFunctionsArguments = {};
- this.initVariables = [];
- this.readVariables = [];
- this.writeVariables = [];
- this.addFunction = null;
- this.isRootKernel = false;
- this.isSubKernel = false;
- this.parent = null;
- this.debug = null;
- this.prototypeOnly = null;
- this.constants = null;
-
- if (options) {
- if (options.hasOwnProperty('debug')) {
- this.debug = options.debug;
- }
- if (options.hasOwnProperty('prototypeOnly')) {
- this.prototypeOnly = options.prototypeOnly;
- }
- if (options.hasOwnProperty('constants')) {
- this.constants = options.constants;
- }
- if (options.hasOwnProperty('loopMaxIterations')) {
- this.loopMaxIterations = options.loopMaxIterations;
- }
- }
-
- //
- // Missing jsFunction object exception
- //
- if (!jsFunction) {
- throw 'jsFunction, parameter is missing';
- }
-
- //
- // Setup jsFunction and its string property + validate them
- //
- this.jsFunctionString = jsFunction.toString();
- if (!utils.isFunctionString(this.jsFunctionString)) {
- console.error('jsFunction, to string conversion check failed: not a function?', this.jsFunctionString);
- throw 'jsFunction, to string conversion check failed: not a function?';
- }
-
- if (!utils.isFunction(jsFunction)) {
- //throw 'jsFunction, is not a valid JS Function';
- this.jsFunction = null;
- } else {
- this.jsFunction = jsFunction;
- }
-
- //
- // Setup the function name property
- //
- this.functionName = functionName ||
- (jsFunction && jsFunction.name) ||
- utils.getFunctionNameFromString(this.jsFunctionString);
-
- if (!(this.functionName)) {
- throw 'jsFunction, missing name argument or value';
- }
-
- //
- // Extract parameter name, and its argument types
- //
- this.paramNames = utils.getParamNamesFromString(this.jsFunctionString);
- if (paramTypes) {
- if (Array.isArray(paramTypes)) {
- if (paramTypes.length !== this.paramNames.length) {
- throw 'Invalid argument type array length, against function length -> (' +
- paramTypes.length + ',' +
- this.paramNames.length +
- ')';
- }
- this.paramTypes = paramTypes;
- } else if (typeof paramTypes === 'object') {
- const paramVariableNames = Object.keys(paramTypes);
- if (paramTypes.hasOwnProperty('returns')) {
- this.returnType = paramTypes.returns;
- paramVariableNames.splice(paramVariableNames.indexOf('returns'), 1);
- }
- if (paramVariableNames.length > 0 && paramVariableNames.length !== this.paramNames.length) {
- throw 'Invalid argument type array length, against function length -> (' +
- paramVariableNames.length + ',' +
- this.paramNames.length +
- ')';
- } else {
- this.paramTypes = this.paramNames.map((key) => {
- if (paramTypes.hasOwnProperty(key)) {
- return paramTypes[key];
- } else {
- return 'float';
- }
- });
- }
- }
- } else {
- this.paramTypes = [];
- //TODO: Remove when we have proper type detection
- // for (let a = 0; a < this.paramNames.length; ++a) {
- // this.paramTypes.push();
- // }
- }
-
- //
- // Return type handling
- //
- if (!this.returnType) {
- this.returnType = returnType || 'float';
- }
- }
-
- setAddFunction(fn) {
- this.addFunction = fn;
- return this;
- }
- /**
- *
- * Core Functions
- *
- */
-
- /**
- * @memberOf FunctionNodeBase#
- * @function
- * @name getJSFunction
- *
- * @desc Gets and return the stored JS Function.
- * Note: that this internally eval the function, if only the string was provided on construction
- *
- * @returns {Function} The function object
- *
- */
- getJsFunction() {
- if (this.jsFunction) {
- return this.jsFunction;
- }
-
- if (this.jsFunctionString) {
- this.jsFunction = eval(this.jsFunctionString);
- return this.jsFunction;
- }
-
- throw 'Missing jsFunction, and jsFunctionString parameter';
- }
-
- /**
- * @typedef {Object} ASTObject
- */
-
- /**
- * @typedef {Object} JISONParser
- */
-
- /**
- * @memberOf FunctionNodeBase#
- * @function
- * @name getJsAST
- *
- * @desc Parses the class function JS, and returns its Abstract Syntax Tree object.
- *
- * This is used internally to convert to shader code
- *
- * @param {JISONParser} inParser - Parser to use, assumes in scope 'parser' if null
- *
- * @returns {ASTObject} The function AST Object, note that result is cached under this.jsFunctionAST;
- *
- */
- getJsAST(inParser) {
- if (this.jsFunctionAST) {
- return this.jsFunctionAST;
- }
-
- inParser = inParser || acorn;
- if (inParser === null) {
- throw 'Missing JS to AST parser';
- }
-
- const ast = inParser.parse('var ' + this.functionName + ' = ' + this.jsFunctionString + ';');
- if (ast === null) {
- throw 'Failed to parse JS code';
- }
-
- // take out the function object, outside the var declarations
- const funcAST = ast.body[0].declarations[0].init;
- this.jsFunctionAST = funcAST;
-
- return funcAST;
- }
-
-
- /**
- * @memberOf FunctionNodeBase#
- * @function
- * @name getFunctionString
- *
- * @desc Returns the converted webgl shader function equivalent of the JS function
- *
- * @returns {String} webgl function string, result is cached under this.webGlFunctionString
- *
- */
- getFunctionString() {
- this.generate();
- return this.functionString;
- }
-
- /**
- * @memberOf FunctionNodeBase#
- * @function
- * @name setFunctionString
- *
- * @desc Set the functionString value, overwriting it
- *
- * @param {String} functionString - Shader code string, representing the function
- *
- */
- setFunctionString(functionString) {
- this.functionString = functionString;
- }
-
- /**
- * @memberOf FunctionNodeBase#
- * @function
- * @name getParamType
- *
- * @desc Return the type of parameter sent to subKernel/Kernel.
- *
- * @param {String} paramName - Name of the parameter
- *
- * @returns {String} Type of the parameter
- *
- */
- getParamType(paramName) {
- const paramIndex = this.paramNames.indexOf(paramName);
- if (paramIndex === -1) return null;
- if (!this.parent) return null;
- if (this.paramTypes[paramIndex]) return this.paramTypes[paramIndex];
- const calledFunctionArguments = this.parent.calledFunctionsArguments[this.functionName];
- for (let i = 0; i < calledFunctionArguments.length; i++) {
- const calledFunctionArgument = calledFunctionArguments[i];
- if (calledFunctionArgument[paramIndex] !== null) {
- return this.paramTypes[paramIndex] = calledFunctionArgument[paramIndex].type;
- }
- }
- return null;
- }
-
- /**
- * @memberOf FunctionNodeBase#
- * @function
- * @name getUserParamName
- *
- * @desc Return the name of the *user parameter*(subKernel parameter) corresponding
- * to the parameter supplied to the kernel
- *
- * @param {String} paramName - Name of the parameter
- *
- * @returns {String} Name of the parameter
- *
- */
- getUserParamName(paramName) {
- const paramIndex = this.paramNames.indexOf(paramName);
- if (paramIndex === -1) return null;
- if (!this.parent) return null;
- const calledFunctionArguments = this.parent.calledFunctionsArguments[this.functionName];
- for (let i = 0; i < calledFunctionArguments.length; i++) {
- const calledFunctionArgument = calledFunctionArguments[i];
- if (calledFunctionArgument[paramIndex] !== null) {
- return calledFunctionArgument[paramIndex].name;
- }
- }
- return null;
- }
-
- generate(options) {
- throw new Error('generate not defined on BaseFunctionNode');
- }
-};
\ No newline at end of file
diff --git a/src/backend/function-node.js b/src/backend/function-node.js
new file mode 100644
index 00000000..3946b1a3
--- /dev/null
+++ b/src/backend/function-node.js
@@ -0,0 +1,1498 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/function-tracer.js b/src/backend/function-tracer.js
new file mode 100644
index 00000000..f9779867
--- /dev/null
+++ b/src/backend/function-tracer.js
@@ -0,0 +1,311 @@
+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,
+};
\ No newline at end of file
diff --git a/src/backend/gl/kernel-string.js b/src/backend/gl/kernel-string.js
new file mode 100644
index 00000000..75ca4064
--- /dev/null
+++ b/src/backend/gl/kernel-string.js
@@ -0,0 +1,366 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/kernel.js b/src/backend/gl/kernel.js
new file mode 100644
index 00000000..e2e55478
--- /dev/null
+++ b/src/backend/gl/kernel.js
@@ -0,0 +1,1059 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/array-2-float-2d.js b/src/backend/gl/texture/array-2-float-2d.js
new file mode 100644
index 00000000..a0e7defd
--- /dev/null
+++ b/src/backend/gl/texture/array-2-float-2d.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/array-2-float-3d.js b/src/backend/gl/texture/array-2-float-3d.js
new file mode 100644
index 00000000..28f5b092
--- /dev/null
+++ b/src/backend/gl/texture/array-2-float-3d.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/array-2-float.js b/src/backend/gl/texture/array-2-float.js
new file mode 100644
index 00000000..fab1a2ae
--- /dev/null
+++ b/src/backend/gl/texture/array-2-float.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/array-3-float-2d.js b/src/backend/gl/texture/array-3-float-2d.js
new file mode 100644
index 00000000..4f615879
--- /dev/null
+++ b/src/backend/gl/texture/array-3-float-2d.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/array-3-float-3d.js b/src/backend/gl/texture/array-3-float-3d.js
new file mode 100644
index 00000000..ea53aee0
--- /dev/null
+++ b/src/backend/gl/texture/array-3-float-3d.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/array-3-float.js b/src/backend/gl/texture/array-3-float.js
new file mode 100644
index 00000000..5f99396b
--- /dev/null
+++ b/src/backend/gl/texture/array-3-float.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/array-4-float-2d.js b/src/backend/gl/texture/array-4-float-2d.js
new file mode 100644
index 00000000..a370eaa2
--- /dev/null
+++ b/src/backend/gl/texture/array-4-float-2d.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/array-4-float-3d.js b/src/backend/gl/texture/array-4-float-3d.js
new file mode 100644
index 00000000..21e09249
--- /dev/null
+++ b/src/backend/gl/texture/array-4-float-3d.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/array-4-float.js b/src/backend/gl/texture/array-4-float.js
new file mode 100644
index 00000000..80553d15
--- /dev/null
+++ b/src/backend/gl/texture/array-4-float.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/float-2d.js b/src/backend/gl/texture/float-2d.js
new file mode 100644
index 00000000..1fb927e9
--- /dev/null
+++ b/src/backend/gl/texture/float-2d.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/float-3d.js b/src/backend/gl/texture/float-3d.js
new file mode 100644
index 00000000..9a8a536f
--- /dev/null
+++ b/src/backend/gl/texture/float-3d.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/float.js b/src/backend/gl/texture/float.js
new file mode 100644
index 00000000..21d3748f
--- /dev/null
+++ b/src/backend/gl/texture/float.js
@@ -0,0 +1,38 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/graphical.js b/src/backend/gl/texture/graphical.js
new file mode 100644
index 00000000..18360021
--- /dev/null
+++ b/src/backend/gl/texture/graphical.js
@@ -0,0 +1,15 @@
+const { GLTextureUnsigned } = require('./unsigned');
+
+class GLTextureGraphical extends GLTextureUnsigned {
+ constructor(settings) {
+ super(settings);
+ this.type = 'ArrayTexture(4)';
+ }
+ toArray() {
+ return this.renderValues();
+ }
+}
+
+module.exports = {
+ GLTextureGraphical
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/index.js b/src/backend/gl/texture/index.js
new file mode 100644
index 00000000..d5cac523
--- /dev/null
+++ b/src/backend/gl/texture/index.js
@@ -0,0 +1,125 @@
+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 };
\ No newline at end of file
diff --git a/src/backend/gl/texture/memory-optimized-2d.js b/src/backend/gl/texture/memory-optimized-2d.js
new file mode 100644
index 00000000..20234ee3
--- /dev/null
+++ b/src/backend/gl/texture/memory-optimized-2d.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/memory-optimized-3d.js b/src/backend/gl/texture/memory-optimized-3d.js
new file mode 100644
index 00000000..f65e5f9f
--- /dev/null
+++ b/src/backend/gl/texture/memory-optimized-3d.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/memory-optimized.js b/src/backend/gl/texture/memory-optimized.js
new file mode 100644
index 00000000..03474f58
--- /dev/null
+++ b/src/backend/gl/texture/memory-optimized.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/unsigned-2d.js b/src/backend/gl/texture/unsigned-2d.js
new file mode 100644
index 00000000..3adba8b1
--- /dev/null
+++ b/src/backend/gl/texture/unsigned-2d.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/unsigned-3d.js b/src/backend/gl/texture/unsigned-3d.js
new file mode 100644
index 00000000..ccedf143
--- /dev/null
+++ b/src/backend/gl/texture/unsigned-3d.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/gl/texture/unsigned.js b/src/backend/gl/texture/unsigned.js
new file mode 100644
index 00000000..0a357206
--- /dev/null
+++ b/src/backend/gl/texture/unsigned.js
@@ -0,0 +1,37 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/headless-gl/kernel.js b/src/backend/headless-gl/kernel.js
new file mode 100644
index 00000000..f91b1352
--- /dev/null
+++ b/src/backend/headless-gl/kernel.js
@@ -0,0 +1,145 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/kernel-base.js b/src/backend/kernel-base.js
deleted file mode 100644
index 88ffd0ef..00000000
--- a/src/backend/kernel-base.js
+++ /dev/null
@@ -1,328 +0,0 @@
-'use strict';
-
-const utils = require('../core/utils');
-
-module.exports = class BaseKernel {
-
- /**
- * @constructor BaseKernel
- *
- * @desc Implements the base class for Kernels, and is used as a
- * parent class for all Kernel implementations.
- *
- * This contains the basic methods needed by all Kernel implementations,
- * like setDimensions, addSubKernel, etc.
- *
- * @prop {Array} paramNames - Name of the parameters of the kernel function
- * @prop {String} fnString - Kernel function as a String
- * @prop {Array} dimensions - Dimensions of the kernel function, this.thread.x, etc.
- * @prop {Boolean} debug - Toggle debug mode
- * @prop {String} graphical - Toggle graphical mode
- * @prop {number} loopMaxIterations - Maximum number of loop iterations
- * @prop {Object} constants - Global constants
- * @prop {Array} subKernels - Sub kernels bound to this kernel instance
- * @prop {Object} subKernelProperties - Sub kernels bound to this kernel instance as key/value pairs
- * @prop {Array} subKernelOutputVariableNames - Names of the variables outputted by the subkerls
- *
- */
- constructor(fnString, settings) {
- this.paramNames = utils.getParamNamesFromString(fnString);
- this.fnString = fnString;
- this.dimensions = [];
- this.debug = false;
- this.graphical = false;
- this.loopMaxIterations = 0;
- this.constants = null;
- this.wraparound = null;
- this.hardcodeConstants = null;
- this.outputToTexture = null;
- this.texSize = null;
- this._canvas = null;
- this._webGl = null;
- this.threadDim = null;
- this.floatTextures = null;
- this.floatOutput = null;
- this.floatOutputForce = null;
- this.addFunction = null;
- this.copyData = true;
- this.subKernels = null;
- this.subKernelProperties = null;
- this.subKernelNames = null;
- this.subKernelOutputVariableNames = null;
-
- for (let p in settings) {
- if (!settings.hasOwnProperty(p) || !this.hasOwnProperty(p)) continue;
- this[p] = settings[p];
- }
- if (settings.hasOwnProperty('canvas')) {
- this._canvas = settings.canvas;
- }
-
- if (!this._canvas) this._canvas = utils.initCanvas();
- }
-
- build() {
- throw new Error('"build" not defined on Base');
- }
-
- setAddFunction(cb) {
- this.addFunction = cb;
- return this;
- }
-
- /**
- * @memberOf BaseKernel#
- * @function
- * @name setDimensions
- *
- * @desc Set dimensions of the kernel function
- *
- * @param {Array} dimensions - The dimensions array set the dimensions to
- *
- */
- setDimensions(dimensions) {
- this.dimensions = dimensions;
- return this;
- }
-
- /**
- * @memberOf BaseKernel#
- * @function
- * @name setDebug
- *
- * @desc Toggle debug mode
- *
- * @param {Boolean} flag - true to enable debug
- *
- */
- setDebug(flag) {
- this.debug = flag;
- return this;
- }
-
- /**
- * @memberOf BaseKernel#
- * @function
- * @name setGraphical
- *
- * @desc Toggle graphical output mode
- *
- * @param {Boolean} flag - true to enable graphical output
- *
- */
- setGraphical(flag) {
- this.graphical = flag;
- return this;
- }
-
- /**
- * @memberOf BaseKernel#
- * @function
- * @name setLoopMaxIterations
- *
- * @desc Set the maximum number of loop iterations
- *
- * @param {number} max - iterations count
- *
- */
- setLoopMaxIterations(max) {
- this.loopMaxIterations = max;
- return this;
- }
-
- /**
- * @memberOf BaseKernel#
- * @function
- * @name setConstants
- * @desc Set Constants
- */
- setConstants(constants) {
- this.constants = constants;
- return this;
- }
-
- setWraparound(flag) {
- console.warn('Wraparound mode is not supported and undocumented.');
- this.wraparound = flag;
- return this;
- }
-
- setHardcodeConstants(flag) {
- this.hardcodeConstants = flag;
- return this;
- }
-
- setOutputToTexture(flag) {
- this.outputToTexture = flag;
- return this;
- }
-
- /**
- * @memberOf BaseKernel#
- * @function
- * @name setFloatTextures
- *
- * @desc Toggle texture output mode
- *
- * @param {Boolean} flag - true to enable floatTextures
- *
- */
- setFloatTextures(flag) {
- this.floatTextures = flag;
- return this;
- }
-
- /**
- * @memberOf BaseKernel#
- * @function
- * @name setFloatOutput
- *
- * @desc Toggle output mode
- *
- * @param {Boolean} flag - true to enable float
- *
- */
- setFloatOutput(flag) {
- this.floatOutput = flag;
- return this;
- }
-
- setFloatOutputForce(flag) {
- this.floatOutputForce = flag;
- return this;
- }
-
- /**
- * @memberOf BaseKernel#
- * @function
- * @name setCanvas
- *
- * @desc Bind the canvas to kernel
- *
- * @param {Canvas} canvas - Canvas to bind
- *
- */
- setCanvas(canvas) {
- this._canvas = canvas;
- return this;
- }
-
- /**
- * @memberOf BaseKernel#
- * @function
- * @name setCanvas
- *
- * @desc Bind the webGL instance to kernel
- *
- * @param {Canvas} webGL - webGL instance to bind
- *
- */
- setWebGl(webGl) {
- this._webGl = webGl;
- return this;
- }
-
- setCopyData(copyData) {
- this.copyData = copyData;
- return this;
- }
-
- /**
- * @memberOf BaseKernel#
- * @function
- * @name getCanvas()
- *
- * @desc Returns the current canvas instance bound to the kernel
- *
- */
- getCanvas() {
- return this._canvas;
- }
-
- /**
- * @memberOf BaseKernel#
- * @function
- * @name getWebGl()
- *
- * @desc Returns the current webGl instance bound to the kernel
- *
- */
- getWebGl() {
- return this._webGl;
- }
-
- validateOptions() {
- throw new Error('validateOptions not defined');
- }
-
- exec() {
- return this.execute.apply(this, arguments);
- }
-
- execute() {
- //
- // Prepare the required objects
- //
- const args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));
-
- //
- // Setup and return the promise, and execute the function, in synchronous mode
- //
- return utils.newPromise((accept, reject) => {
- try {
- accept(this.run.apply(this, args));
- } catch (e) {
- //
- // Error : throw rejection
- //
- reject(e);
- }
- });
- }
-
- /**
- * @memberOf BaseKernel#
- * @function
- * @name addSubKernel
- *
- * @desc Add a sub kernel to the root kernel instance.
- * This is what `createKernelMap` uses.
- *
- * @param {String} fnString - function (as a String) of the subKernel to add
- *
- */
- addSubKernel(fnString) {
- if (this.subKernels === null) {
- this.subKernels = [];
- this.subKernelNames = [];
- }
- this.subKernels.push(fnString);
- this.subKernelNames.push(utils.getFunctionNameFromString(fnString));
- return this;
- }
-
- /**
- * @memberOf BaseKernel#
- * @function
- * @name addSubKernelProperty
- *
- * @desc Add a sub kernel to the root kernel instance, indexed by a property name
- * This is what `createKernelMap` uses.
- *
- * @param {String} property - property key for the subKernel
- * @param {String} fnString - function (as a String) of the subKernel to add
- *
- */
- addSubKernelProperty(property, fnString) {
- if (this.subKernelProperties === null) {
- this.subKernelProperties = {};
- this.subKernelNames = [];
- }
- if (this.subKernelProperties.hasOwnProperty(property)) {
- throw new Error(`cannot add sub kernel ${ property }, already defined`);
- }
- this.subKernelProperties[property] = fnString;
- this.subKernelNames.push(utils.getFunctionNameFromString(fnString));
- return this;
- }
-};
\ No newline at end of file
diff --git a/src/backend/kernel-run-shortcut.js b/src/backend/kernel-run-shortcut.js
deleted file mode 100644
index a8c6ac79..00000000
--- a/src/backend/kernel-run-shortcut.js
+++ /dev/null
@@ -1,34 +0,0 @@
-'use strict';
-
-const utils = require('../core/utils');
-
-module.exports = function kernelRunShortcut(kernel) {
- const shortcut = function() {
- return kernel.run.apply(kernel, arguments);
- };
-
- utils.allPropertiesOf(kernel).forEach((key) => {
- if (key[0] === '_' && key[1] === '_') return;
- if (typeof kernel[key] === 'function') {
- if (key.substring(0, 3) === 'set') {
- shortcut[key] = function() {
- kernel[key].apply(kernel, arguments);
- return shortcut;
- };
- } else {
- shortcut[key] = kernel[key].bind(kernel);
- }
- } else {
- shortcut.__defineGetter__(key, () => {
- return kernel[key];
- });
- shortcut.__defineSetter__(key, (value) => {
- kernel[key] = value;
- });
- }
- });
-
- shortcut.kernel = kernel;
-
- return shortcut;
-};
\ No newline at end of file
diff --git a/src/backend/kernel-value.js b/src/backend/kernel-value.js
new file mode 100644
index 00000000..1fdfc369
--- /dev/null
+++ b/src/backend/kernel-value.js
@@ -0,0 +1,70 @@
+/**
+ * @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
+};
\ No newline at end of file
diff --git a/src/backend/kernel.js b/src/backend/kernel.js
new file mode 100644
index 00000000..dd68ca10
--- /dev/null
+++ b/src/backend/kernel.js
@@ -0,0 +1,949 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/runner-base.js b/src/backend/runner-base.js
deleted file mode 100644
index 06d04990..00000000
--- a/src/backend/runner-base.js
+++ /dev/null
@@ -1,121 +0,0 @@
-'use strict';
-
-const utils = require('../core/utils');
-const kernelRunShortcut = require('./kernel-run-shortcut');
-
-module.exports = class BaseRunner {
-
- /**
- * @constructor BaseRunner
- *
- * @desc Represents the 'private/protected' namespace of the GPU class
- *
- * I know @private makes more sense, but since the documentation engine state is undetirmined.
- * (See https://github.com/gpujs/gpu.js/issues/19 regarding documentation engine issue)
- * File isolation is currently the best way to go.
- *
- * *base.js* internal functions namespace
- * *gpu.js* PUBLIC function namespace
- *
- * @prop {Object} settings - Settings object used to set Dimensions, etc.
- * @prop {String} kernel - Current kernel instance
- * @prop {Object} canvas - Canvas instance attached to the kernel
- * @prop {Object} webGl - WebGl instance attached to the kernel
- * @prop {Function} fn - Kernel function to run
- * @prop {Object} functionBuilder - FunctionBuilder instance
- * @prop {String} fnString - Kernel function (as a String)
- * @prop {String} endianness - endian information like Little-endian, Big-endian.
- *
- */
-
- constructor(functionBuilder, settings) {
- settings = settings || {};
- this.kernel = settings.kernel;
- this.canvas = settings.canvas;
- this.webGl = settings.webGl;
- this.fn = null;
- this.functionBuilder = functionBuilder;
- this.fnString = null;
- this.endianness = utils.systemEndianness();
- this.functionBuilder.polyfillStandardFunctions();
- }
-
- /**
- * @memberOf BaseRunner#
- * @function
- * @name textureToArray
- *
- * @desc Converts the provided Texture instance to a JavaScript Array
- *
- * @param {Object} texture - Texture Object
- *
- */
- textureToArray(texture) {
- const copy = this.createKernel(function(x) {
- return x[this.thread.z][this.thread.y][this.thread.x];
- });
-
- return copy(texture);
- }
-
- /**
- * @memberOf BaseRunner#
- * @function
- *
- * @name deleteTexture
- *
- * @desc Deletes the provided Texture instance
- *
- * @param {Object} texture - Texture Object
- */
- deleteTexture(texture) {
- this.webGl.deleteTexture(texture.texture);
- }
-
- /**
- * @memberOf BaseRunner#
- * @function
- * @name buildPromiseKernel
- *
- * @desc Get and returns the ASYNCHRONOUS executor, of a class and kernel
- * This returns a Promise object from an argument set.
- *
- * Note that there is no current implementation.
- *
- */
- buildPromiseKernel() {
- throw new Error('not yet implemented');
- }
-
- getMode() {
- throw new Error('"mode" not implemented on BaseRunner');
- }
-
- /**
- * @memberOf BaseRunner#
- * @function
- *
- * @name buildKernel
- *
- * @desc Get and returns the Synchronous executor, of a class and kernel
- * Which returns the result directly after passing the arguments.
- *
- */
- buildKernel(fn, settings) {
- settings = Object.assign({}, settings || {});
- const fnString = fn.toString();
- if (!settings.functionBuilder) {
- settings.functionBuilder = this.functionBuilder;
- }
-
- if (!settings.canvas) {
- settings.canvas = this.canvas;
- }
-
- if (!settings.webGl) {
- settings.webGl = this.webgl;
- }
-
- return kernelRunShortcut(new this.Kernel(fnString, settings));
- }
-};
\ No newline at end of file
diff --git a/src/backend/web-gl/fragment-shader.js b/src/backend/web-gl/fragment-shader.js
new file mode 100644
index 00000000..166e80e5
--- /dev/null
+++ b/src/backend/web-gl/fragment-shader.js
@@ -0,0 +1,496 @@
+// 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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/function-builder.js b/src/backend/web-gl/function-builder.js
deleted file mode 100644
index c8f49943..00000000
--- a/src/backend/web-gl/function-builder.js
+++ /dev/null
@@ -1,161 +0,0 @@
-'use strict';
-
-const FunctionBuilderBase = require('../function-builder-base');
-const WebGLFunctionNode = require('./function-node');
-const utils = require('../../core/utils');
-
-/**
- * @class WebGLFunctionBuilder
- *
- * @extends FunctionBuilderBase
- *
- * @desc Builds webGl functions (shaders) from JavaScript function Strings
- *
- */
-module.exports = class WebGLFunctionBuilder extends FunctionBuilderBase {
- addFunction(functionName, jsFunction, paramTypes, returnType) {
- this.addFunctionNode(
- new WebGLFunctionNode(functionName, jsFunction, paramTypes, returnType)
- .setAddFunction(this.addFunction.bind(this))
- );
- }
-
- /**
- * @memberOf WebGLFunctionBuilder#
- * @function
- * @name getStringFromFunctionNames
- *
- * @desc Get the webGl string from function names
- *
- * @param {String[]} functionList - List of function to build the webgl string.
- *
- * @returns {String} The full webgl 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.nodeMap[functionList[i]];
- if (node) {
- ret.push(this.nodeMap[functionList[i]].getFunctionString());
- }
- }
- return ret.join('\n');
- }
-
- /**
- * @memberOf WebGLFunctionBuilder#
- * @function
- * @name getPrototypeStringFromFunctionNames
- *
- * @desc Return webgl String of all functions converted to webgl shader form
- *
- * @param {String[]} functionList - List of function names to build the webgl string.
- * @param {Object} opt - Settings object passed to functionNode. See functionNode for more details.
- *
- * @returns {String} Prototype String of all functions converted to webgl shader form
- *
- */
- getPrototypeStringFromFunctionNames(functionList, opt) {
- const ret = [];
- for (let i = 0; i < functionList.length; ++i) {
- const node = this.nodeMap[functionList[i]];
- if (node) {
- ret.push(node.getFunctionPrototypeString(opt));
- }
- }
- return ret.join('\n');
- }
-
- /**
- * @memberOf WebGLFunctionBuilder#
- * @function
- * @name getString
- *
- * Get webGl string for a particular function name
- *
- * @param {String} functionName - Function name to trace from. If null, it returns the WHOLE builder stack
- *
- * @returns {String} The full webgl string, of all the various functions. Trace optimized if functionName given
- *
- */
- getString(functionName, opt) {
- if (opt === undefined) {
- opt = {};
- }
-
- if (functionName) {
- return this.getStringFromFunctionNames(this.traceFunctionCalls(functionName, [], opt).reverse(), opt);
- }
- return this.getStringFromFunctionNames(Object.keys(this.nodeMap), opt);
- }
-
- /**
- * @memberOf WebGLFunctionBuilder#
- * @name getPrototypeString
- * @function
- *
- * @desc Return the webgl string for a function converted to glsl (webgl shaders)
- *
- * @param {String} functionName - Function name to trace from. If null, it returns the WHOLE builder stack
- *
- * @returns {String} The full webgl string, of all the various functions. Trace optimized if functionName given
- *
- */
- getPrototypeString(functionName) {
- this.rootKernel.generate();
- if (functionName) {
- return this.getPrototypeStringFromFunctionNames(this.traceFunctionCalls(functionName, []).reverse());
- }
- return this.getPrototypeStringFromFunctionNames(Object.keys(this.nodeMap));
- }
-
- /**
- * @memberOf WebGLFunctionBuilder#
- * @function
- * @name addKernel
- *
- * @desc Add a new kernel to this instance
- *
- * @param {String} fnString - Kernel function as a String
- * @param {Object} options - Settings object to set constants, debug mode, etc.
- * @param {Array} paramNames - Parameters of the kernel
- * @param {Array} paramTypes - Types of the parameters
- *
- *
- * @returns {Object} The inserted kernel as a Kernel Node
- *
- */
- addKernel(fnString, options, paramNames, paramTypes) {
- const kernelNode = new WebGLFunctionNode('kernel', fnString, options, paramTypes);
- kernelNode.setAddFunction(this.addFunction.bind(this));
- kernelNode.paramNames = paramNames;
- kernelNode.paramTypes = paramTypes;
- kernelNode.isRootKernel = true;
- this.addFunctionNode(kernelNode);
- return kernelNode;
- }
-
- /**
- * @memberOf WebGLFunctionBuilder#
- * @function
- * @name addSubKernel
- *
- * @desc Add a new sub-kernel to the current kernel instance
- *
- * @param {Function} jsFunction - Sub-kernel function (JavaScript)
- * @param {Object} options - Settings object to set constants, debug mode, etc.
- * @param {Array} paramNames - Parameters of the sub-kernel
- * @param {Array} returnType - Return type of the subKernel
- *
- * @returns {Object} The inserted sub-kernel as a Kernel Node
- *
- */
- addSubKernel(jsFunction, options, paramTypes, returnType) {
- const kernelNode = new WebGLFunctionNode(null, jsFunction, options, paramTypes, returnType);
- kernelNode.setAddFunction(this.addFunction.bind(this));
- kernelNode.isSubKernel = true;
- this.addFunctionNode(kernelNode);
- return kernelNode;
- }
-};
\ No newline at end of file
diff --git a/src/backend/web-gl/function-node.js b/src/backend/web-gl/function-node.js
index dedc3949..0a0e844f 100644
--- a/src/backend/web-gl/function-node.js
+++ b/src/backend/web-gl/function-node.js
@@ -1,1194 +1,1606 @@
-'use strict';
-
-const FunctionNodeBase = require('../function-node-base');
-const utils = require('../../core/utils');
-// Closure capture for the ast function, prevent collision with existing AST functions
-// The prefixes to use
-const jsMathPrefix = 'Math.';
-const localPrefix = 'this.';
-const constantsPrefix = 'this.constants.';
-
-const DECODE32_ENCODE32 = /decode32\(\s+encode32\(/g;
-const ENCODE32_DECODE32 = /encode32\(\s+decode32\(/g;
-
-/**
- * @class WebGLFunctionNode
- *
- * @desc [INTERNAL] Takes in a function node, and does all the AST voodoo required to generate its respective webGL code.
- *
- * @extends FunctionNodeBase
- *
- * @param {functionNode} inNode - The function node object
- *
- * @returns the converted webGL function string
- *
- */
-module.exports = class WebGLFunctionNode extends FunctionNodeBase {
- generate() {
- if (this.debug) {
- console.log(this);
- }
- if (this.prototypeOnly) {
- return WebGLFunctionNode.astFunctionPrototype(this.getJsAST(), [], this).join('').trim();
- } else {
- this.functionStringArray = this.astGeneric(this.getJsAST(), [], this);
- }
- this.functionString = webGlRegexOptimize(
- this.functionStringArray.join('').trim()
- );
- return this.functionString;
- }
-
- isIdentifierConstant(paramName) {
- if (!this.constants) return false;
- return this.constants.hasOwnProperty(paramName);
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astGeneric
- *
- * @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
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {String} the prased openclgl string array
- */
- astGeneric(ast, retArr, funcParam) {
- if (ast === null) {
- throw astErrorOutput('NULL ast', ast, funcParam);
- } else {
- if (Array.isArray(ast)) {
- for (let i = 0; i < ast.length; i++) {
- this.astGeneric(ast[i], retArr, funcParam);
- }
- return retArr;
- }
-
- switch (ast.type) {
- case 'FunctionDeclaration':
- return this.astFunctionDeclaration(ast, retArr, funcParam);
- case 'FunctionExpression':
- return this.astFunctionExpression(ast, retArr, funcParam);
- case 'ReturnStatement':
- return this.astReturnStatement(ast, retArr, funcParam);
- case 'Literal':
- return this.astLiteral(ast, retArr, funcParam);
- case 'BinaryExpression':
- return this.astBinaryExpression(ast, retArr, funcParam);
- case 'Identifier':
- return this.astIdentifierExpression(ast, retArr, funcParam);
- case 'AssignmentExpression':
- return this.astAssignmentExpression(ast, retArr, funcParam);
- case 'ExpressionStatement':
- return this.astExpressionStatement(ast, retArr, funcParam);
- case 'EmptyStatement':
- return this.astEmptyStatement(ast, retArr, funcParam);
- case 'BlockStatement':
- return this.astBlockStatement(ast, retArr, funcParam);
- case 'IfStatement':
- return this.astIfStatement(ast, retArr, funcParam);
- case 'BreakStatement':
- return this.astBreakStatement(ast, retArr, funcParam);
- case 'ContinueStatement':
- return this.astContinueStatement(ast, retArr, funcParam);
- case 'ForStatement':
- return this.astForStatement(ast, retArr, funcParam);
- case 'WhileStatement':
- return this.astWhileStatement(ast, retArr, funcParam);
- case 'VariableDeclaration':
- return this.astVariableDeclaration(ast, retArr, funcParam);
- case 'VariableDeclarator':
- return this.astVariableDeclarator(ast, retArr, funcParam);
- case 'ThisExpression':
- return this.astThisExpression(ast, retArr, funcParam);
- case 'SequenceExpression':
- return this.astSequenceExpression(ast, retArr, funcParam);
- case 'UnaryExpression':
- return this.astUnaryExpression(ast, retArr, funcParam);
- case 'UpdateExpression':
- return this.astUpdateExpression(ast, retArr, funcParam);
- case 'LogicalExpression':
- return this.astLogicalExpression(ast, retArr, funcParam);
- case 'MemberExpression':
- return this.astMemberExpression(ast, retArr, funcParam);
- case 'CallExpression':
- return this.astCallExpression(ast, retArr, funcParam);
- case 'ArrayExpression':
- return this.astArrayExpression(ast, retArr, funcParam);
- }
-
- throw astErrorOutput('Unknown ast type : ' + ast.type, ast, funcParam);
- }
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astFunctionDeclaration
- *
- * @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
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astFunctionDeclaration(ast, retArr, funcParam) {
- if (this.addFunction) {
- this.addFunction(null, utils.getAstString(this.jsFunctionString, ast));
- }
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astFunctionPrototype
- * @static
- *
- * @desc Parses the abstract syntax tree for to its *named function prototype*
- *
- * @param {Object} ast - the AST object to parse
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- static astFunctionPrototype(ast, retArr, funcParam) {
- // Setup function return type and name
- if (funcParam.isRootKernel || funcParam.isSubKernel) {
- return retArr;
- }
-
- retArr.push(funcParam.returnType);
- retArr.push(' ');
- retArr.push(funcParam.functionName);
- retArr.push('(');
-
- // Arguments handling
- for (let i = 0; i < funcParam.paramNames.length; ++i) {
- if (i > 0) {
- retArr.push(', ');
- }
-
- retArr.push(funcParam.paramTypes[i]);
- retArr.push(' ');
- retArr.push('user_');
- retArr.push(funcParam.paramNames[i]);
- }
-
- retArr.push(');\n');
-
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astFunctionExpression
- *
- * @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
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astFunctionExpression(ast, retArr, funcParam) {
-
- // Setup function return type and name
- if (funcParam.isRootKernel) {
- retArr.push('void');
- funcParam.kernalAst = ast;
- } else {
- retArr.push(funcParam.returnType);
- }
- retArr.push(' ');
- retArr.push(funcParam.functionName);
- retArr.push('(');
-
- if (!funcParam.isRootKernel) {
- // Arguments handling
- for (let i = 0; i < funcParam.paramNames.length; ++i) {
- const paramName = funcParam.paramNames[i];
-
- if (i > 0) {
- retArr.push(', ');
- }
- const type = funcParam.getParamType(paramName);
- switch (type) {
- case 'Texture':
- case 'Array':
- retArr.push('sampler2D');
- break;
- default:
- retArr.push('float');
- }
-
- retArr.push(' ');
- retArr.push('user_');
- retArr.push(paramName);
- }
- }
-
- // 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, funcParam);
- retArr.push('\n');
- }
-
- // Function closing
- retArr.push('}\n');
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astReturnStatement
- *
- * @desc Parses the abstract syntax tree for to *return* statement
- *
- * @param {Object} ast - the AST object to parse
- * @param {Array} retArr - return array string
- * @param {Object} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astReturnStatement(ast, retArr, funcParam) {
- if (funcParam.isRootKernel) {
- retArr.push('kernelResult = ');
- this.astGeneric(ast.argument, retArr, funcParam);
- retArr.push(';');
- retArr.push('return;');
- } else if (funcParam.isSubKernel) {
- retArr.push(`${ funcParam.functionName }Result = `);
- this.astGeneric(ast.argument, retArr, funcParam);
- retArr.push(';');
- retArr.push(`return ${ funcParam.functionName }Result;`);
- } else {
- retArr.push('return ');
- this.astGeneric(ast.argument, retArr, funcParam);
- retArr.push(';');
- }
-
- //throw astErrorOutput(
- // 'Non main function return, is not supported : '+funcParam.currentFunctionNamespace,
- // ast, funcParam
- //);
-
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astLiteral
- *
- * @desc Parses the abstract syntax tree for *literal value*
- *
- * @param {Object} ast - the AST object to parse
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astLiteral(ast, retArr, funcParam) {
-
- // Reject non numeric literals
- if (isNaN(ast.value)) {
- throw astErrorOutput(
- 'Non-numeric literal not supported : ' + ast.value,
- ast, funcParam
- );
- }
-
- // Push the literal value as a float/int
- retArr.push(ast.value);
-
- // If it was an int, node made a float
- if (Number.isInteger(ast.value)) {
- retArr.push('.0');
- }
-
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astBinaryExpression
- *
- * @desc Parses the abstract syntax tree for *binary* expression
- *
- * @param {Object} ast - the AST object to parse
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astBinaryExpression(ast, retArr, funcParam) {
- retArr.push('(');
-
- if (ast.operator === '%') {
- retArr.push('mod(');
- this.astGeneric(ast.left, retArr, funcParam);
- retArr.push(',');
- this.astGeneric(ast.right, retArr, funcParam);
- retArr.push(')');
- } else if (ast.operator === '===') {
- this.astGeneric(ast.left, retArr, funcParam);
- retArr.push('==');
- this.astGeneric(ast.right, retArr, funcParam);
- } else if (ast.operator === '!==') {
- this.astGeneric(ast.left, retArr, funcParam);
- retArr.push('!=');
- this.astGeneric(ast.right, retArr, funcParam);
- } else {
- this.astGeneric(ast.left, retArr, funcParam);
- retArr.push(ast.operator);
- this.astGeneric(ast.right, retArr, funcParam);
- }
-
- retArr.push(')');
-
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astIdentifierExpression
- *
- * @desc Parses the abstract syntax tree for *identifier* expression
- *
- * @param {Object} idtNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astIdentifierExpression(idtNode, retArr, funcParam) {
- if (idtNode.type !== 'Identifier') {
- throw astErrorOutput(
- 'IdentifierExpression - not an Identifier',
- ast, funcParam
- );
- }
-
- switch (idtNode.name) {
- case 'gpu_threadX':
- retArr.push('threadId.x');
- break;
- case 'gpu_threadY':
- retArr.push('threadId.y');
- break;
- case 'gpu_threadZ':
- retArr.push('threadId.z');
- break;
- case 'gpu_dimensionsX':
- retArr.push('uOutputDim.x');
- break;
- case 'gpu_dimensionsY':
- retArr.push('uOutputDim.y');
- break;
- case 'gpu_dimensionsZ':
- retArr.push('uOutputDim.z');
- break;
- default:
- if (this.constants && this.constants.hasOwnProperty(idtNode.name)) {
- retArr.push('constants_' + idtNode.name);
- } else {
- const userParamName = funcParam.getUserParamName(idtNode.name);
- if (userParamName !== null) {
- retArr.push('user_' + userParamName);
- } else {
- retArr.push('user_' + idtNode.name);
- }
- }
- }
-
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astForStatement
- *
- * @desc Parses the abstract syntax tree forfor *for-loop* expression
- *
- * @param {Object} forNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {String} the prased openclgl string
- */
- astForStatement(forNode, retArr, funcParam) {
- if (forNode.type !== 'ForStatement') {
- throw astErrorOutput(
- 'Invalid for statment',
- ast, funcParam
- );
- }
-
- if (forNode.test && forNode.test.type === 'BinaryExpression') {
- if (forNode.test.right.type === 'Identifier' &&
- forNode.test.operator === '<' &&
- this.isIdentifierConstant(forNode.test.right.name) === false) {
-
- if (this.opt.loopMaxIterations === undefined) {
- console.warn('Warning: loopMaxIterations is not set! Using default of 100 which may result in unintended behavior.');
- console.warn('Set loopMaxIterations or use a for loop of fixed length to silence this message.');
- }
-
- retArr.push('for (float ');
- this.astGeneric(forNode.init, retArr, funcParam);
- retArr.push(';');
- this.astGeneric(forNode.test.left, retArr, funcParam);
- retArr.push(forNode.test.operator);
- retArr.push('LOOP_MAX');
- retArr.push(';');
- this.astGeneric(forNode.update, retArr, funcParam);
- retArr.push(')');
-
- retArr.push('{\n');
- retArr.push('if (');
- this.astGeneric(forNode.test.left, retArr, funcParam);
- retArr.push(forNode.test.operator);
- this.astGeneric(forNode.test.right, retArr, funcParam);
- retArr.push(') {\n');
- if (forNode.body.type === 'BlockStatement') {
- for (let i = 0; i < forNode.body.body.length; i++) {
- this.astGeneric(forNode.body.body[i], retArr, funcParam);
- }
- } else {
- this.astGeneric(forNode.body, retArr, funcParam);
- }
- retArr.push('} else {\n');
- retArr.push('break;\n');
- retArr.push('}\n');
- retArr.push('}\n');
-
- return retArr;
- } else {
- const declarations = JSON.parse(JSON.stringify(forNode.init.declarations));
- const updateArgument = forNode.update.argument;
- if (!Array.isArray(declarations) || declarations.length < 1) {
- console.log(this.jsFunctionString);
- throw new Error('Error: Incompatible for loop declaration');
- }
-
- if (declarations.length > 1) {
- let initArgument = null;
- for (let i = 0; i < declarations.length; i++) {
- const declaration = declarations[i];
- if (declaration.id.name === updateArgument.name) {
- initArgument = declaration;
- declarations.splice(i, 1);
- } else {
- retArr.push('float ');
- this.astGeneric(declaration, retArr, funcParam);
- retArr.push(';');
- }
- }
-
- retArr.push('for (float ');
- this.astGeneric(initArgument, retArr, funcParam);
- retArr.push(';');
- } else {
- retArr.push('for (');
- this.astGeneric(forNode.init, retArr, funcParam);
- }
-
- this.astGeneric(forNode.test, retArr, funcParam);
- retArr.push(';');
- this.astGeneric(forNode.update, retArr, funcParam);
- retArr.push(')');
- this.astGeneric(forNode.body, retArr, funcParam);
- return retArr;
- }
- }
-
- throw astErrorOutput(
- 'Invalid for statement',
- ast, funcParam
- );
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astWhileStatement
- *
- * @desc Parses the abstract syntax tree for *while* loop
- *
- *
- * @param {Object} whileNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {String} the parsed openclgl string
- */
- astWhileStatement(whileNode, retArr, funcParam) {
- if (whileNode.type !== 'WhileStatement') {
- throw astErrorOutput(
- 'Invalid while statment',
- ast, funcParam
- );
- }
-
- retArr.push('for (float i = 0.0; i < LOOP_MAX; i++) {');
- retArr.push('if (');
- this.astGeneric(whileNode.test, retArr, funcParam);
- retArr.push(') {\n');
- this.astGeneric(whileNode.body, retArr, funcParam);
- retArr.push('} else {\n');
- retArr.push('break;\n');
- retArr.push('}\n');
- retArr.push('}\n');
-
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astAssignmentExpression
- *
- * @desc Parses the abstract syntax tree for *Assignment* Expression
- *
- * @param {Object} assNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astAssignmentExpression(assNode, retArr, funcParam) {
- if (assNode.operator === '%=') {
- this.astGeneric(assNode.left, retArr, funcParam);
- retArr.push('=');
- retArr.push('mod(');
- this.astGeneric(assNode.left, retArr, funcParam);
- retArr.push(',');
- this.astGeneric(assNode.right, retArr, funcParam);
- retArr.push(')');
- } else {
- this.astGeneric(assNode.left, retArr, funcParam);
- retArr.push(assNode.operator);
- this.astGeneric(assNode.right, retArr, funcParam);
- return retArr;
- }
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astEmptyStatement
- *
- * @desc Parses the abstract syntax tree for an *Empty* Statement
- *
- * @param {Object} eNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astEmptyStatement(eNode, retArr, funcParam) {
- //retArr.push(';\n');
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astBlockStatement
- *
- * @desc Parses the abstract syntax tree for *Block* statement
- *
- * @param {Object} bnode - the AST object to parse
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astBlockStatement(bNode, retArr, funcParam) {
- retArr.push('{\n');
- for (let i = 0; i < bNode.body.length; i++) {
- this.astGeneric(bNode.body[i], retArr, funcParam);
- }
- retArr.push('}\n');
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astExpressionStatement
- *
- * @desc Parses the abstract syntax tree for *generic expression* statement
- *
- * @param {Object} esNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astExpressionStatement(esNode, retArr, funcParam) {
- this.astGeneric(esNode.expression, retArr, funcParam);
- retArr.push(';\n');
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astVariableDeclaration
- *
- * @desc Parses the abstract syntax tree for *Variable Declaration*
- *
- * @param {Object} vardecNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astVariableDeclaration(vardecNode, retArr, funcParam) {
- retArr.push('float ');
- for (let i = 0; i < vardecNode.declarations.length; i++) {
- if (i > 0) {
- retArr.push(',');
- }
- this.astGeneric(vardecNode.declarations[i], retArr, funcParam);
- }
- retArr.push(';');
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astVariableDeclarator
- *
- * @desc Parses the abstract syntax tree for *Variable Declarator*
- *
- * @param {Object} ivardecNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astVariableDeclarator(ivardecNode, retArr, funcParam) {
- this.astGeneric(ivardecNode.id, retArr, funcParam);
- if (ivardecNode.init !== null) {
- retArr.push('=');
- this.astGeneric(ivardecNode.init, retArr, funcParam);
- }
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astIfStatement
- *
- * @desc Parses the abstract syntax tree for *If* Statement
- *
- * @param {Object} ifNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astIfStatement(ifNode, retArr, funcParam) {
- retArr.push('if (');
- this.astGeneric(ifNode.test, retArr, funcParam);
- retArr.push(')');
- if (ifNode.consequent.type === 'BlockStatement') {
- this.astGeneric(ifNode.consequent, retArr, funcParam);
- } else {
- retArr.push(' {\n');
- this.astGeneric(ifNode.consequent, retArr, funcParam);
- retArr.push('\n}\n');
- }
-
- if (ifNode.alternate) {
- retArr.push('else ');
- if (ifNode.alternate.type === 'BlockStatement') {
- this.astGeneric(ifNode.alternate, retArr, funcParam);
- } else {
- retArr.push(' {\n');
- this.astGeneric(ifNode.alternate, retArr, funcParam);
- retArr.push('\n}\n');
- }
- }
- return retArr;
-
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astBreakStatement
- *
- * @desc Parses the abstract syntax tree for *Break* Statement
- *
- * @param {Object} brNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astBreakStatement(brNode, retArr, funcParam) {
- retArr.push('break;\n');
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astContinueStatement
- *
- * @desc Parses the abstract syntax tree for *Continue* Statement
- *
- * @param {Object} crNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astContinueStatement(crNode, retArr, funcParam) {
- retArr.push('continue;\n');
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astLogicalExpression
- *
- * @desc Parses the abstract syntax tree for *Logical* Expression
- *
- * @param {Object} logNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astLogicalExpression(logNode, retArr, funcParam) {
- retArr.push('(');
- this.astGeneric(logNode.left, retArr, funcParam);
- retArr.push(logNode.operator);
- this.astGeneric(logNode.right, retArr, funcParam);
- retArr.push(')');
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astUpdateExpression
- *
- * @desc Parses the abstract syntax tree for *Update* Expression
- *
- * @param {Object} uNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astUpdateExpression(uNode, retArr, funcParam) {
- if (uNode.prefix) {
- retArr.push(uNode.operator);
- this.astGeneric(uNode.argument, retArr, funcParam);
- } else {
- this.astGeneric(uNode.argument, retArr, funcParam);
- retArr.push(uNode.operator);
- }
-
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astUnaryExpression
- *
- * @desc Parses the abstract syntax tree for *Unary* Expression
- *
- * @param {Object} uNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astUnaryExpression(uNode, retArr, funcParam) {
- if (uNode.prefix) {
- retArr.push(uNode.operator);
- this.astGeneric(uNode.argument, retArr, funcParam);
- } else {
- this.astGeneric(uNode.argument, retArr, funcParam);
- retArr.push(uNode.operator);
- }
-
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astThisExpression
- *
- * @desc Parses the abstract syntax tree for *This* expression
- *
- * @param {Object} tNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astThisExpression(tNode, retArr, funcParam) {
- retArr.push('this');
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astMemberExpression
- *
- * @desc Parses the abstract syntax tree for *Member* Expression
- *
- * @param {Object} mNode - An ast Node
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astMemberExpression(mNode, retArr, funcParam) {
- if (mNode.computed) {
- if (mNode.object.type === 'Identifier') {
- // Working logger
- const reqName = mNode.object.name;
- const funcName = funcParam.functionName || 'kernel';
- let assumeNotTexture = false;
-
- // Possibly an array request - handle it as such
- if (funcParam.paramNames) {
- const idx = funcParam.paramNames.indexOf(reqName);
- if (idx >= 0 && funcParam.paramTypes[idx] === 'float') {
- assumeNotTexture = true;
- }
- }
-
- if (assumeNotTexture) {
- // Get from array
- this.astGeneric(mNode.object, retArr, funcParam);
- retArr.push('[int(');
- this.astGeneric(mNode.property, retArr, funcParam);
- retArr.push(')]');
- } else {
- // Get from texture
- // This normally refers to the global read only input vars
- retArr.push('get(');
- this.astGeneric(mNode.object, retArr, funcParam);
- retArr.push(', vec2(');
- this.astGeneric(mNode.object, retArr, funcParam);
- retArr.push('Size[0],');
- this.astGeneric(mNode.object, retArr, funcParam);
- retArr.push('Size[1]), vec3(');
- this.astGeneric(mNode.object, retArr, funcParam);
- retArr.push('Dim[0],');
- this.astGeneric(mNode.object, retArr, funcParam);
- retArr.push('Dim[1],');
- this.astGeneric(mNode.object, retArr, funcParam);
- retArr.push('Dim[2]');
- retArr.push('), ');
- this.astGeneric(mNode.property, retArr, funcParam);
- retArr.push(')');
- }
- } else {
- this.astGeneric(mNode.object, retArr, funcParam);
- const last = retArr.pop();
- retArr.push(',');
- this.astGeneric(mNode.property, retArr, funcParam);
- retArr.push(last);
- }
- } else {
-
- // Unroll the member expression
- let unrolled = this.astMemberExpressionUnroll(mNode);
- let unrolled_lc = unrolled.toLowerCase();
-
- // Its a constant, remove this.constants.
- if (unrolled.indexOf(constantsPrefix) === 0) {
- unrolled = 'constants_' + unrolled.slice(constantsPrefix.length);
- }
-
- if (unrolled_lc === 'this.thread.x') {
- retArr.push('threadId.x');
- } else if (unrolled_lc === 'this.thread.y') {
- retArr.push('threadId.y');
- } else if (unrolled_lc === 'this.thread.z') {
- retArr.push('threadId.z');
- } else if (unrolled_lc === 'this.dimensions.x') {
- retArr.push('uOutputDim.x');
- } else if (unrolled_lc === 'this.dimensions.y') {
- retArr.push('uOutputDim.y');
- } else if (unrolled_lc === 'this.dimensions.z') {
- retArr.push('uOutputDim.z');
- } else {
- retArr.push(unrolled);
- }
- }
- return retArr;
- }
-
- astSequenceExpression(sNode, retArr, funcParam) {
- for (let i = 0; i < sNode.expressions.length; i++) {
- if (i > 0) {
- retArr.push(',');
- }
- this.astGeneric(sNode.expressions, retArr, funcParam);
- }
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astMemberExpressionUnroll
- * @desc Parses the abstract syntax tree for binary expression.
- *
- * Utility function for astCallExpression.
- *
- * @param {Object} ast - the AST object to parse
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {String} the function namespace call, unrolled
- */
- astMemberExpressionUnroll(ast, funcParam) {
- if (ast.type === 'Identifier') {
- return ast.name;
- } else if (ast.type === 'ThisExpression') {
- return 'this';
- }
-
- if (ast.type === 'MemberExpression') {
- if (ast.object && ast.property) {
- return (
- this.astMemberExpressionUnroll(ast.object, funcParam) +
- '.' +
- this.astMemberExpressionUnroll(ast.property, funcParam)
- );
- }
- }
-
- // Failure, unknown expression
- throw astErrorOutput(
- 'Unknown CallExpression_unroll',
- ast, funcParam
- );
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astCallExpression
- *
- * @desc Parses the abstract syntax tree for *call* expression
- *
- * @param {Object} ast - the AST object to parse
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astCallExpression(ast, retArr, funcParam) {
- if (ast.callee) {
- // Get the full function call, unrolled
- let funcName = this.astMemberExpressionUnroll(ast.callee);
-
- // Its a math operator, remove the prefix
- if (funcName.indexOf(jsMathPrefix) === 0) {
- funcName = funcName.slice(jsMathPrefix.length);
- }
-
- // Its a local function, remove this
- if (funcName.indexOf(localPrefix) === 0) {
- funcName = funcName.slice(localPrefix.length);
- }
-
- // Register the function into the called registry
- if (funcParam.calledFunctions.indexOf(funcName) < 0) {
- funcParam.calledFunctions.push(funcName);
- }
- if (!funcParam.hasOwnProperty('funcName')) {
- funcParam.calledFunctionsArguments[funcName] = [];
- }
-
- const functionArguments = [];
- funcParam.calledFunctionsArguments[funcName].push(functionArguments);
-
- // Call the function
- retArr.push(funcName);
-
- // Open arguments space
- retArr.push('(');
-
- // Add the vars
- for (let i = 0; i < ast.arguments.length; ++i) {
- const argument = ast.arguments[i];
- if (i > 0) {
- retArr.push(', ');
- }
- this.astGeneric(argument, retArr, funcParam);
- if (argument.type === 'Identifier') {
- const paramIndex = funcParam.paramNames.indexOf(argument.name);
- if (paramIndex === -1) {
- functionArguments.push(null);
- } else {
- functionArguments.push({
- name: argument.name,
- type: funcParam.paramTypes[paramIndex]
- });
- }
- } else {
- functionArguments.push(null);
- }
- }
-
- // Close arguments space
- retArr.push(')');
-
- return retArr;
- }
-
- // Failure, unknown expression
- throw astErrorOutput(
- 'Unknown CallExpression',
- ast, funcParam
- );
-
- return retArr;
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name astArrayExpression
- *
- * @desc Parses the abstract syntax tree for *Array* Expression
- *
- * @param {Object} ast - the AST object to parse
- * @param {Array} retArr - return array string
- * @param {Function} funcParam - FunctionNode, that tracks compilation state
- *
- * @returns {Array} the append retArr
- */
- astArrayExpression(arrNode, retArr, funcParam) {
- const arrLen = arrNode.elements.length;
-
- retArr.push('float[' + arrLen + '](');
- for (let i = 0; i < arrLen; ++i) {
- if (i > 0) {
- retArr.push(', ');
- }
- const subNode = arrNode.elements[i];
- this.astGeneric(subNode, retArr, funcParam)
- }
- retArr.push(')');
-
- return retArr;
-
- // // Failure, unknown expression
- // throw astErrorOutput(
- // 'Unknown ArrayExpression',
- // arrNode, funcParam
- //);
- }
-
- /**
- * @memberOf WebGLFunctionNode#
- * @function
- * @name getFunctionPrototypeString
- *
- * @desc Returns the converted webgl shader function equivalent of the JS function
- *
- * @returns {String} webgl function string, result is cached under this.getFunctionPrototypeString
- *
- */
- getFunctionPrototypeString() {
- if (this.webGlFunctionPrototypeString) {
- return this.webGlFunctionPrototypeString;
- }
- return this.webGlFunctionPrototypeString = this.generate();
- }
-
- build() {
- return this.getFunctionPrototypeString().length > 0;
- }
-};
-
-function isIdentifierKernelParam(paramName, ast, funcParam) {
- return funcParam.paramNames.indexOf(paramName) !== -1;
-}
-
-function ensureIndentifierType(paramName, expectedType, ast, funcParam) {
- const start = ast.loc.start;
-
- if (!isIdentifierKernelParam(paramName, funcParam) && expectedType !== 'float') {
- throw 'Error unexpected identifier ' + paramName + ' on line ' + start.line;
- } else {
- const actualType = funcParam.paramTypes[funcParam.paramNames.indexOf(paramName)];
- if (actualType !== expectedType) {
- throw 'Error unexpected identifier ' + paramName + ' on line ' + start.line;
- }
- }
-}
+const { utils } = require('../../utils');
+const { FunctionNode } = require('../function-node');
/**
- * @ignore
- * @function
- * @name webgl_regex_optimize
- *
- * @desc [INTERNAL] Takes the near final webgl function string, and do regex search and replacments.
- * For voodoo optimize out the following:
- *
- * - decode32(encode32(
- * - encode32(decode32(
- *
- * @param {String} inStr - The webGl function String
- *
+ * @desc [INTERNAL] Takes in a function node, and does all the AST voodoo required to toString its respective WebGL code
*/
-function webGlRegexOptimize(inStr) {
- return inStr
- .replace(DECODE32_ENCODE32, '((')
- .replace(ENCODE32_DECODE32, '((');
+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('');
+ }
}
-/**
- * @function
- * @name astErrorOutput
- * @ignore
- * @desc To throw the AST error, with its location.
- *
- * @todo add location support fpr the AST error
- *
- * @param {Object} error - the error message output
- * @param {Object} ast - the AST object where the error is
- * @param {Object} funcParam - FunctionNode, that tracks compilation state
- */
-function astErrorOutput(error, ast, funcParam) {
- console.error(error, ast, funcParam);
- return error;
-}
\ No newline at end of file
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-string.js b/src/backend/web-gl/kernel-string.js
deleted file mode 100644
index 720e5cbd..00000000
--- a/src/backend/web-gl/kernel-string.js
+++ /dev/null
@@ -1,57 +0,0 @@
-'use strict';
-
-const utils = require('../../core/utils');
-const kernelRunShortcut = require('../kernel-run-shortcut');
-
-module.exports = function(gpuKernel, name) {
- return `() => {
- ${ kernelRunShortcut.toString() };
- const utils = {
- allPropertiesOf: function ${ utils.allPropertiesOf.toString() },
- clone: function ${ utils.clone.toString() },
- splitArray: function ${ utils.splitArray.toString() },
- getArgumentType: function ${ utils.getArgumentType.toString() },
- getDimensions: function ${ utils.getDimensions.toString() },
- dimToTexSize: function ${ utils.dimToTexSize.toString() },
- copyFlatten: function ${ utils.copyFlatten.toString() },
- flatten: function ${ utils.flatten.toString() },
- systemEndianness: '${ utils.systemEndianness() }',
- initWebGl: function ${ utils.initWebGl.toString() },
- isArray: function ${ utils.isArray.toString() }
- };
- class ${ name || 'Kernel' } {
- constructor() {
- this.argumentsLength = 0;
- this._canvas = null;
- this._webGl = null;
- this.built = false;
- this.program = null;
- this.paramNames = ${ JSON.stringify(gpuKernel.paramNames) };
- this.paramTypes = ${ JSON.stringify(gpuKernel.paramTypes) };
- this.texSize = ${ JSON.stringify(gpuKernel.texSize) };
- this.dimensions = ${ JSON.stringify(gpuKernel.dimensions) };
- this.compiledFragShaderString = \`${ gpuKernel.compiledFragShaderString }\`;
- this.compiledVertShaderString = \`${ gpuKernel.compiledVertShaderString }\`;
- this.programUniformLocationCache = {};
- this.textureCache = {};
- this.subKernelOutputTextures = null;
- }
- ${ gpuKernel._getFragShaderString.toString() }
- ${ gpuKernel._getVertShaderString.toString() }
- validateOptions() {}
- setupParams() {}
- setCanvas(canvas) { this._canvas = canvas; return this; }
- setWebGl(webGl) { this._webGl = webGl; return this; }
- ${ gpuKernel.getUniformLocation.toString() }
- ${ gpuKernel.setupParams.toString() }
- ${ gpuKernel.build.toString() }
- ${ gpuKernel.run.toString() }
- ${ gpuKernel._addArgument.toString() }
- ${ gpuKernel.getArgumentTexture.toString() }
- ${ gpuKernel.getTextureCache.toString() }
- ${ gpuKernel.getOutputTexture.toString() }
- ${ gpuKernel.renderOutput.toString() }
- };
- return kernelRunShortcut(new Kernel());
- };`;
-};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value-maps.js b/src/backend/web-gl/kernel-value-maps.js
new file mode 100644
index 00000000..843164a7
--- /dev/null
+++ b/src/backend/web-gl/kernel-value-maps.js
@@ -0,0 +1,202 @@
+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,
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/array.js b/src/backend/web-gl/kernel-value/array.js
new file mode 100644
index 00000000..b6e77f2f
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/array.js
@@ -0,0 +1,90 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/array2.js b/src/backend/web-gl/kernel-value/array2.js
new file mode 100644
index 00000000..ea4f1467
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/array2.js
@@ -0,0 +1,29 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/array3.js b/src/backend/web-gl/kernel-value/array3.js
new file mode 100644
index 00000000..47ad55f8
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/array3.js
@@ -0,0 +1,29 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/array4.js b/src/backend/web-gl/kernel-value/array4.js
new file mode 100644
index 00000000..a5556476
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/array4.js
@@ -0,0 +1,29 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/boolean.js b/src/backend/web-gl/kernel-value/boolean.js
new file mode 100644
index 00000000..895663d0
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/boolean.js
@@ -0,0 +1,28 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/dynamic-html-image.js b/src/backend/web-gl/kernel-value/dynamic-html-image.js
new file mode 100644
index 00000000..926ead66
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/dynamic-html-image.js
@@ -0,0 +1,26 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/dynamic-html-video.js b/src/backend/web-gl/kernel-value/dynamic-html-video.js
new file mode 100644
index 00000000..a10a00f6
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/dynamic-html-video.js
@@ -0,0 +1,7 @@
+const { WebGLKernelValueDynamicHTMLImage } = require('./dynamic-html-image');
+
+class WebGLKernelValueDynamicHTMLVideo extends WebGLKernelValueDynamicHTMLImage {}
+
+module.exports = {
+ WebGLKernelValueDynamicHTMLVideo
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/dynamic-memory-optimized-number-texture.js b/src/backend/web-gl/kernel-value/dynamic-memory-optimized-number-texture.js
new file mode 100644
index 00000000..0db73297
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/dynamic-memory-optimized-number-texture.js
@@ -0,0 +1,25 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/dynamic-number-texture.js b/src/backend/web-gl/kernel-value/dynamic-number-texture.js
new file mode 100644
index 00000000..edf5980d
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/dynamic-number-texture.js
@@ -0,0 +1,25 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/dynamic-single-array.js b/src/backend/web-gl/kernel-value/dynamic-single-array.js
new file mode 100644
index 00000000..165fa10a
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/dynamic-single-array.js
@@ -0,0 +1,27 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/dynamic-single-array1d-i.js b/src/backend/web-gl/kernel-value/dynamic-single-array1d-i.js
new file mode 100644
index 00000000..0c9489ce
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/dynamic-single-array1d-i.js
@@ -0,0 +1,23 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/dynamic-single-array2d-i.js b/src/backend/web-gl/kernel-value/dynamic-single-array2d-i.js
new file mode 100644
index 00000000..b164f3c1
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/dynamic-single-array2d-i.js
@@ -0,0 +1,23 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/dynamic-single-array3d-i.js b/src/backend/web-gl/kernel-value/dynamic-single-array3d-i.js
new file mode 100644
index 00000000..b1d52a5d
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/dynamic-single-array3d-i.js
@@ -0,0 +1,23 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/dynamic-single-input.js b/src/backend/web-gl/kernel-value/dynamic-single-input.js
new file mode 100644
index 00000000..4c17285d
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/dynamic-single-input.js
@@ -0,0 +1,28 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/dynamic-unsigned-array.js b/src/backend/web-gl/kernel-value/dynamic-unsigned-array.js
new file mode 100644
index 00000000..fb2dd7dd
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/dynamic-unsigned-array.js
@@ -0,0 +1,29 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/dynamic-unsigned-input.js b/src/backend/web-gl/kernel-value/dynamic-unsigned-input.js
new file mode 100644
index 00000000..de16334b
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/dynamic-unsigned-input.js
@@ -0,0 +1,30 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/float.js b/src/backend/web-gl/kernel-value/float.js
new file mode 100644
index 00000000..3668bfb6
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/float.js
@@ -0,0 +1,30 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/html-image.js b/src/backend/web-gl/kernel-value/html-image.js
new file mode 100644
index 00000000..e0f169c2
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/html-image.js
@@ -0,0 +1,42 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/html-video.js b/src/backend/web-gl/kernel-value/html-video.js
new file mode 100644
index 00000000..56165481
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/html-video.js
@@ -0,0 +1,7 @@
+const { WebGLKernelValueHTMLImage } = require('./html-image');
+
+class WebGLKernelValueHTMLVideo extends WebGLKernelValueHTMLImage {}
+
+module.exports = {
+ WebGLKernelValueHTMLVideo
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/index.js b/src/backend/web-gl/kernel-value/index.js
new file mode 100644
index 00000000..671bade1
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/index.js
@@ -0,0 +1,66 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/integer.js b/src/backend/web-gl/kernel-value/integer.js
new file mode 100644
index 00000000..c7dad4ac
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/integer.js
@@ -0,0 +1,27 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/memory-optimized-number-texture.js b/src/backend/web-gl/kernel-value/memory-optimized-number-texture.js
new file mode 100644
index 00000000..11193441
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/memory-optimized-number-texture.js
@@ -0,0 +1,72 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/number-texture.js b/src/backend/web-gl/kernel-value/number-texture.js
new file mode 100644
index 00000000..97c43e7d
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/number-texture.js
@@ -0,0 +1,73 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/single-array.js b/src/backend/web-gl/kernel-value/single-array.js
new file mode 100644
index 00000000..1684f283
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/single-array.js
@@ -0,0 +1,47 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/single-array1d-i.js b/src/backend/web-gl/kernel-value/single-array1d-i.js
new file mode 100644
index 00000000..0f7e4221
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/single-array1d-i.js
@@ -0,0 +1,52 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/single-array2d-i.js b/src/backend/web-gl/kernel-value/single-array2d-i.js
new file mode 100644
index 00000000..38bbf1ad
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/single-array2d-i.js
@@ -0,0 +1,52 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/single-array3d-i.js b/src/backend/web-gl/kernel-value/single-array3d-i.js
new file mode 100644
index 00000000..8992f1bd
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/single-array3d-i.js
@@ -0,0 +1,52 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/single-input.js b/src/backend/web-gl/kernel-value/single-input.js
new file mode 100644
index 00000000..a9c3dbaa
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/single-input.js
@@ -0,0 +1,48 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/unsigned-array.js b/src/backend/web-gl/kernel-value/unsigned-array.js
new file mode 100644
index 00000000..8e52ae9f
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/unsigned-array.js
@@ -0,0 +1,50 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel-value/unsigned-input.js b/src/backend/web-gl/kernel-value/unsigned-input.js
new file mode 100644
index 00000000..4370ac77
--- /dev/null
+++ b/src/backend/web-gl/kernel-value/unsigned-input.js
@@ -0,0 +1,51 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl/kernel.js b/src/backend/web-gl/kernel.js
index 76f04834..ffea4705 100644
--- a/src/backend/web-gl/kernel.js
+++ b/src/backend/web-gl/kernel.js
@@ -1,1192 +1,1607 @@
-'use strict';
-
-const fs = require('fs');
-const KernelBase = require('../kernel-base');
-const utils = require('../../core/utils');
-const Texture = require('../../core/texture');
-const fragShaderString = require('./shader-frag');
-const vertShaderString = require('./shader-vert');
-const kernelString = require('./kernel-string');
+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 = {};
-module.exports = class WebGLKernel extends KernelBase {
-
- /**
- * @constructor WebGLKernel
- *
- * @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.
- *
- * @extends KernelBase
- *
- * @prop {Object} textureCache - webGl Texture cache
- * @prop {Object} threadDim - The thread dimensions, x, y and z
- * @prop {Object} programUniformLocationCache - Location of program variables in memory
- * @prop {Object} framebuffer - Webgl frameBuffer
- * @prop {Object} buffer - WebGL buffer
- * @prop {Object} program - The webGl Program
- * @prop {Object} functionBuilder - Function Builder instance bound to this Kernel
- * @prop {Boolean} outputToTexture - Set output type to Texture, instead of float
- * @prop {String} endianness - Endian information like Little-endian, Big-endian.
- * @prop {Array} paramTypes - Types of parameters sent to the Kernel
- * @prop {number} argumentsLength - Number of parameters sent to the Kernel
- * @prop {String} compiledFragShaderString - Compiled fragment shader string
- * @prop {String} compiledVertShaderString - Compiled Vertical shader string
- */
- constructor(fnString, settings) {
- super(fnString, settings);
- this.textureCache = {};
- this.threadDim = {};
- this.programUniformLocationCache = {};
- this.framebuffer = null;
-
- this.buffer = null;
- this.program = null;
- this.functionBuilder = settings.functionBuilder;
- this.outputToTexture = settings.outputToTexture;
- this.endianness = utils.systemEndianness();
- this.subKernelOutputTextures = null;
- this.subKernelOutputVariableNames = null;
- this.paramTypes = null;
- this.argumentsLength = 0;
- this.ext = null;
- this.compiledFragShaderString = null;
- this.compiledVertShaderString = null;
- this.extDrawBuffersMap = null;
- this.outputTexture = null;
- this.maxTexSize = null;
- if (!this._webGl) this._webGl = utils.initWebGl(this.getCanvas());
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name validateOptions
- *
- * @desc Validate options related to Kernel, such as
- * floatOutputs and Textures, texSize, dimensions,
- * graphical output.
- *
- */
- validateOptions() {
- const isReadPixel = utils.isFloatReadPixelsSupported();
- if (this.floatTextures === true && !utils.OES_texture_float) {
- throw 'Float textures are not supported on this browser';
- } else if (this.floatOutput === true && this.floatOutputForce !== true && !isReadPixel) {
- throw 'Float texture outputs are not supported on this browser';
- } else if (this.floatTextures === null && !isReadPixel && !this.graphical) {
- //NOTE: handle
- this.floatTextures = true;
- this.floatOutput = false;
- }
-
- if (!this.dimensions || this.dimensions.length === 0) {
- if (arguments.length !== 1) {
- throw 'Auto dimensions only supported for kernels with only one input';
- }
-
- const argType = utils.getArgumentType(arguments[0]);
- if (argType === 'Array') {
- this.dimensions = utils.getDimensions(argType);
- } else if (argType === 'Texture') {
- this.dimensions = arguments[0].dimensions;
- } else {
- throw 'Auto dimensions not supported for input type: ' + argType;
- }
- }
-
- this.texSize = utils.dimToTexSize({
- floatTextures: this.floatTextures,
- floatOutput: this.floatOutput
- }, this.dimensions, true);
-
- if (this.graphical) {
- if (this.dimensions.length !== 2) {
- throw 'Output must have 2 dimensions on graphical mode';
- }
-
- if (this.floatOutput) {
- throw 'Cannot use graphical mode and float output at the same time';
- }
-
- this.texSize = utils.clone(this.dimensions);
- } else if (this.floatOutput === undefined && utils.OES_texture_float) {
- this.floatOutput = true;
- }
- }
-
- updateMaxTexSize() {
- const texSize = this.texSize;
- const canvas = this._canvas;
- 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];
- }
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name build
- *
- * @desc Builds the Kernel, by compiling Fragment and Vertical Shaders,
- * and instantiates the program.
- *
- */
-
- build() {
- this.validateOptions();
- this.setupParams(arguments);
- this.updateMaxTexSize();
- const texSize = this.texSize;
- const gl = this._webGl;
- const canvas = this._canvas;
- gl.enable(gl.SCISSOR_TEST);
- gl.viewport(0, 0, this.maxTexSize[0], this.maxTexSize[1]);
- canvas.width = this.maxTexSize[0];
- canvas.height = this.maxTexSize[1];
- const threadDim = this.threadDim = utils.clone(this.dimensions);
- while (threadDim.length < 3) {
- threadDim.push(1);
- }
-
- if (this.functionBuilder) this._addKernels();
-
- const compiledVertShaderString = this._getVertShaderString(arguments);
- const vertShader = gl.createShader(gl.VERTEX_SHADER);
- gl.shaderSource(vertShader, compiledVertShaderString);
- gl.compileShader(vertShader);
-
- const compiledFragShaderString = this._getFragShaderString(arguments);
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER);
- gl.shaderSource(fragShader, compiledFragShaderString);
- gl.compileShader(fragShader);
-
- if (!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) {
- console.log(compiledVertShaderString);
- console.error('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(vertShader));
- throw 'Error compiling vertex shader';
- }
- if (!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) {
- console.log(compiledFragShaderString);
- console.error('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(fragShader));
- throw 'Error compiling fragment shader';
- }
-
- if (this.debug) {
- console.log('Options:');
- console.dir(this);
- console.log('GLSL Shader Output:');
- console.log(compiledFragShaderString);
- }
-
- 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];
-
- 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, gl.FALSE, 0, 0);
- const aTexCoordLoc = gl.getAttribLocation(this.program, 'aTexCoord');
- gl.enableVertexAttribArray(aTexCoordLoc);
- gl.vertexAttribPointer(aTexCoordLoc, 2, gl.FLOAT, gl.FALSE, 0, texCoordOffset);
-
- this.setupOutputTexture();
-
- if (this.subKernelOutputTextures !== null) {
- const extDrawBuffersMap = this.extDrawBuffersMap = [gl.COLOR_ATTACHMENT0];
- for (let i = 0; i < this.subKernelOutputTextures.length; i++) {
- const subKernelOutputTexture = this.subKernelOutputTextures[i];
- extDrawBuffersMap.push(gl.COLOR_ATTACHMENT0 + i + 1);
- gl.activeTexture(gl.TEXTURE0 + arguments.length + i);
- gl.bindTexture(gl.TEXTURE_2D, subKernelOutputTexture);
- 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.floatOutput) {
- 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);
- }
- }
- }
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name run
- *
- * @desc Run the kernel program, and send the output to renderOutput
- *
- * This method calls a helper method *renderOutput* to return the result.
- *
- * @returns {Object} Result The final output of the program, as float, and as Textures for reuse.
- *
- *
- */
- run() {
- if (this.program === null) {
- this.build.apply(this, arguments);
- }
- const paramNames = this.paramNames;
- const paramTypes = this.paramTypes;
- const texSize = this.texSize;
- const gl = this._webGl;
-
- gl.useProgram(this.program);
- gl.scissor(0, 0, texSize[0], texSize[1]);
-
- if (!this.hardcodeConstants) {
- const uOutputDimLoc = this.getUniformLocation('uOutputDim');
- gl.uniform3fv(uOutputDimLoc, this.threadDim);
- const uTexSizeLoc = this.getUniformLocation('uTexSize');
- gl.uniform2fv(uTexSizeLoc, texSize);
- }
-
- const ratioLoc = this.getUniformLocation('ratio');
- gl.uniform2f(ratioLoc, texSize[0] / this.maxTexSize[0], texSize[1] / this.maxTexSize[1]);
-
- this.argumentsLength = 0;
- for (let texIndex = 0; texIndex < paramNames.length; texIndex++) {
- this._addArgument(arguments[texIndex], paramTypes[texIndex], paramNames[texIndex]);
- }
-
- if (this.graphical) {
- gl.bindRenderbuffer(gl.RENDERBUFFER, null);
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
- return;
- }
-
- gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
- //the call to this._addArgument may rewrite the outputTexture, keep this here
- const outputTexture = this.outputTexture;
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, outputTexture, 0);
-
- if (this.subKernelOutputTextures !== null) {
- for (let i = 0; i < this.subKernelOutputTextures.length; i++) {
- const subKernelOutputTexture = this.subKernelOutputTextures[i];
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i + 1, gl.TEXTURE_2D, subKernelOutputTexture, 0);
- }
- this.ext.drawBuffersWEBGL(this.extDrawBuffersMap);
- }
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
-
- if (this.subKernelOutputTextures !== null) {
- if (this.subKernels !== null) {
- const output = [];
- output.result = this.renderOutput(outputTexture);
- for (let i = 0; i < this.subKernels.length; i++) {
- output.push(new Texture(this.subKernelOutputTextures[i], texSize, this.dimensions, this._webGl));
- }
- return output;
- } else if (this.subKernelProperties !== null) {
- const output = {
- result: this.renderOutput(outputTexture)
- };
- let i = 0;
- for (let p in this.subKernelProperties) {
- if (!this.subKernelProperties.hasOwnProperty(p)) continue;
- output[p] = new Texture(this.subKernelOutputTextures[i], texSize, this.dimensions, this._webGl);
- i++;
- }
- return output;
- }
- }
-
- return this.renderOutput(outputTexture);
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name renderOutput
- *
- *
- * @desc Helper function to return webGl function's output.
- * Since the program runs on GPU, we need to get the
- * output of the program back to CPU and then return them.
- *
- * *Note*: This should not be called directly.
- *
- * @param {Object} outputTexture - Output Texture returned by webGl program
- *
- * @returns {Object|Array} result
- *
- *
- */
- renderOutput(outputTexture) {
- const texSize = this.texSize;
- const gl = this._webGl;
- const threadDim = this.threadDim;
- const dimensions = this.dimensions;
- if (this.outputToTexture) {
- return new Texture(outputTexture, texSize, dimensions, this._webGl);
- } else {
- let result;
- if (this.floatOutput) {
- result = new Float32Array(texSize[0] * texSize[1] * 4);
- gl.readPixels(0, 0, texSize[0], texSize[1], gl.RGBA, gl.FLOAT, result);
- } else {
- const bytes = new Uint8Array(texSize[0] * texSize[1] * 4);
- gl.readPixels(0, 0, texSize[0], texSize[1], gl.RGBA, gl.UNSIGNED_BYTE, bytes);
- result = new Float32Array(bytes.buffer);
- }
-
- result = result.subarray(0, threadDim[0] * threadDim[1] * threadDim[2]);
-
- if (dimensions.length === 1) {
- return result;
- } else if (dimensions.length === 2) {
- return utils.splitArray(result, dimensions[0]);
- } else if (dimensions.length === 3) {
- const cube = utils.splitArray(result, dimensions[0] * dimensions[1]);
- return cube.map(function(x) {
- return utils.splitArray(x, dimensions[0]);
- });
- }
- }
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name getOutputTexture
- *
- * @desc This uses *getTextureCache* to get the Texture Cache of the Output
- *
- * @returns {Object} Ouptut Texture Cache
- *
- */
- getOutputTexture() {
- return this.getTextureCache('OUTPUT');
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name detachOutputTexture
- *
- * @desc Detaches output texture
- *
- *
- */
- detachOutputTexture() {
- this.detachTextureCache('OUTPUT');
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name setupOutputTexture
- *
- * @desc Detaches a texture from cache if exists, and sets up output texture
- */
- setupOutputTexture() {
- const gl = this._webGl;
- const texSize = this.texSize;
- this.detachOutputTexture();
- this.outputTexture = this.getOutputTexture();
- gl.activeTexture(gl.TEXTURE0 + this.paramNames.length);
- gl.bindTexture(gl.TEXTURE_2D, this.outputTexture);
- 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.floatOutput) {
- 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);
- }
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name getArgumentTexture
- *
- * @desc This uses *getTextureCache** to get the Texture Cache of the argument supplied
- *
- * @param {String} name - Name of the argument
- *
- * Texture cache for the supplied argument
- *
- */
- getArgumentTexture(name) {
- return this.getTextureCache(`ARGUMENT_${ name }`);
- }
-
- /**
- * @memberOf WebGLKernel#
- * @name getSubKernelTexture
- * @function
- *
- * @desc This uses *getTextureCache* to get the Texture Cache of the sub-kernel
- *
- * @param {String} name - Name of the subKernel
- *
- * @returns {Object} Texture cache for the subKernel
- *
- */
- getSubKernelTexture(name) {
- return this.getTextureCache(`SUB_KERNEL_${ name }`);
- }
-
- /**
- * @memberOf WebGLKernel#
- * @name getTextureCache
- * @function
- *
- * @desc Returns the Texture Cache of the supplied parameter (can be kernel, sub-kernel or argument)
- *
- * @param {String} name - Name of the subkernel, argument, or kernel.
- *
- * @returns {Object} Texture cache
- *
- */
- getTextureCache(name) {
- if (this.outputToTexture) {
- // Don't retain a handle on the output texture, we might need to render on the same texture later
- return this._webGl.createTexture();
- }
- if (this.textureCache.hasOwnProperty(name)) {
- return this.textureCache[name];
- }
- return this.textureCache[name] = this._webGl.createTexture();
- }
-
- /**
- * @memberOf WebGLKernel#
- * @name detachTextureCache
- * @function
- * @desc removes a texture from the kernel's cache
- * @param {String} name - Name of texture
- */
- detachTextureCache(name) {
- delete this.textureCache[name];
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name setupParams
- *
- * @desc Setup the parameter types for the parameters
- * supplied to the Kernel function
- *
- * @param {Array} args - The actual parameters sent to the Kernel
- *
- */
- setupParams(args) {
- const paramTypes = this.paramTypes = [];
- for (let i = 0; i < args.length; i++) {
- const param = args[i];
- const paramType = utils.getArgumentType(param);
- paramTypes.push(paramType);
- }
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name getUniformLocation
- *
- * @desc Return WebGlUniformLocation for various variables
- * related to webGl program, such as user-defiend variables,
- * as well as, dimension sizes, etc.
- *
- */
- getUniformLocation(name) {
- let location = this.programUniformLocationCache[name];
- if (!location) {
- location = this._webGl.getUniformLocation(this.program, name);
- this.programUniformLocationCache[name] = location;
- }
- return location;
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _getFragShaderArtifactMap
- *
- * @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(),
- CONSTANTS: this._getConstantsString(),
- DECODE32_ENDIANNESS: this._getDecode32EndiannessString(),
- ENCODE32_ENDIANNESS: this._getEncode32EndiannessString(),
- GET_WRAPAROUND: this._getGetWraparoundString(),
- GET_TEXTURE_CHANNEL: this._getGetTextureChannelString(),
- GET_TEXTURE_INDEX: this._getGetTextureIndexString(),
- GET_RESULT: this._getGetResultString(),
- MAIN_PARAMS: this._getMainParamsString(args),
- MAIN_CONSTANTS: this._getMainConstantsString(),
- KERNEL: this._getKernelString(),
- MAIN_RESULT: this._getMainResultString()
- };
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _addArgument
- *
- * @desc Adds kernel parameters to the Argument Texture,
- * binding it to the webGl instance, etc.
- *
- * @param {Array|Texture|Number} value - The actual argument supplied to the kernel
- * @param {String} type - Type of the argument
- * @param {String} name - Name of the argument
- *
- */
- _addArgument(value, type, name) {
- const gl = this._webGl;
- const argumentTexture = this.getArgumentTexture(name);
- if (value instanceof Texture) {
- type = 'Texture';
- }
- switch (type) {
- case 'Array':
- {
- const dim = utils.getDimensions(value, true);
- const size = utils.dimToTexSize({
- floatTextures: this.floatTextures,
- floatOutput: this.floatOutput
- }, dim);
- gl.activeTexture(gl.TEXTURE0 + this.argumentsLength);
- gl.bindTexture(gl.TEXTURE_2D, argumentTexture);
- 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);
-
- let length = size[0] * size[1];
- if (this.floatTextures) {
- length *= 4;
- }
-
- const valuesFlat = new Float32Array(length);
- utils.flattenTo(value, valuesFlat);
-
- let buffer;
- if (this.floatTextures) {
- buffer = new Float32Array(valuesFlat);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size[0], size[1], 0, gl.RGBA, gl.FLOAT, buffer);
- } else {
- buffer = new Uint8Array((new Float32Array(valuesFlat)).buffer);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size[0], size[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
- }
-
- const loc = this.getUniformLocation('user_' + name);
- const locSize = this.getUniformLocation('user_' + name + 'Size');
- const dimLoc = this.getUniformLocation('user_' + name + 'Dim');
-
- if (!this.hardcodeConstants) {
- gl.uniform3fv(dimLoc, dim);
- gl.uniform2fv(locSize, size);
- }
- gl.uniform1i(loc, this.argumentsLength);
- break;
- }
- case 'Number':
- {
- const loc = this.getUniformLocation('user_' + name);
- gl.uniform1f(loc, value);
- break;
- }
- case 'Texture':
- {
- const inputTexture = value;
- const dim = utils.getDimensions(inputTexture.dimensions, true);
- const size = inputTexture.size;
-
- if (inputTexture.texture === this.outputTexture) {
- this.setupOutputTexture();
- }
-
- gl.activeTexture(gl.TEXTURE0 + this.argumentsLength);
- gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture);
-
- const loc = this.getUniformLocation('user_' + name);
- const locSize = this.getUniformLocation('user_' + name + 'Size');
- const dimLoc = this.getUniformLocation('user_' + name + 'Dim');
-
- gl.uniform3fv(dimLoc, dim);
- gl.uniform2fv(locSize, size);
- gl.uniform1i(loc, this.argumentsLength);
- break;
- }
- default:
- throw 'Input type not supported (WebGL): ' + value;
- }
- this.argumentsLength++;
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _getHeaderString
- *
- * @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 || this.subKernelProperties !== null ?
- //webgl2 '#version 300 es\n' :
- '#extension GL_EXT_draw_buffers : require\n' :
- ''
- );
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _getLoopMaxString
- *
- * @desc Get the maximum loop size String.
- *
- * @returns {String} result
- *
- */
- _getLoopMaxString() {
- return (
- this.loopMaxIterations ?
- ` ${ parseInt(this.loopMaxIterations) }.0;\n` :
- ' 100.0;\n'
- );
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _getConstantsString
- *
- * @desc Generate transpiled glsl Strings for constant parameters sent to a kernel
- *
- * They can be defined by *hardcodeConstants*
- *
- * @returns {String} result
- *
- */
- _getConstantsString() {
- const result = [];
- const threadDim = this.threadDim;
- const texSize = this.texSize;
- if (this.hardcodeConstants) {
- result.push(
- `highp vec3 uOutputDim = vec3(${ threadDim[0] },${ threadDim[1] }, ${ threadDim[2] })`,
- `highp vec2 uTexSize = vec2(${ texSize[0] }, ${ texSize[1] })`
- );
- } else {
- result.push(
- 'uniform highp vec3 uOutputDim',
- 'uniform highp vec2 uTexSize'
- );
- }
-
- return this._linesToString(result);
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _getTextureCoordinate
- *
- * @desc Get texture coordinate string for the program
- *
- * @returns {String} result
- *
- */
- _getTextureCoordinate() {
- const names = this.subKernelOutputVariableNames;
- if (names === null || names.length < 1) {
- return 'varying highp vec2 vTexCoord;\n';
- } else {
- return 'out highp vec2 vTexCoord;\n';
- }
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _getDecode32EndiannessString
- *
- * @desc Get Decode32 endianness string for little-endian and big-endian
- *
- * @returns {String} result
- *
- */
- _getDecode32EndiannessString() {
- return (
- this.endianness === 'LE' ?
- '' :
- ' rgba.rgba = rgba.abgr;\n'
- );
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _getEncode32EndiannessString
- *
- * @desc Get Encode32 endianness string for little-endian and big-endian
- *
- * @returns {String} result
- *
- */
- _getEncode32EndiannessString() {
- return (
- this.endianness === 'LE' ?
- '' :
- ' rgba.rgba = rgba.abgr;\n'
- );
- }
-
- /**
- * @function
- * @memberOf WebGLKernel#
- * @name _getGetWraparoundString
- *
- * @returns {String} wraparound string
- */
- _getGetWraparoundString() {
- return (
- this.wraparound ?
- ' xyz = mod(xyz, texDim);\n' :
- ''
- );
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _getGetTextureChannelString
- *
- */
- _getGetTextureChannelString() {
- if (!this.floatTextures) return '';
-
- return this._linesToString([
- ' int channel = int(integerMod(index, 4.0))',
- ' index = float(int(index) / 4)'
- ]);
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _getGetTextureIndexString
- *
- * @desc Get generic texture index string, if floatTextures flag is true.
- *
- * @example
- * ' index = float(int(index)/4);\n'
- *
- */
- _getGetTextureIndexString() {
- return (
- this.floatTextures ?
- ' index = float(int(index)/4);\n' :
- ''
- );
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _getGetResultString
- *
- */
- _getGetResultString() {
- if (!this.floatTextures) return ' return decode32(texel);\n';
- return this._linesToString([
- ' if (channel == 0) return texel.r',
- ' if (channel == 1) return texel.g',
- ' if (channel == 2) return texel.b',
- ' if (channel == 3) return texel.a'
- ]);
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _getMainParamsString
- *
- * @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
- *
- */
- _getMainParamsString(args) {
- const result = [];
- const paramTypes = this.paramTypes;
- const paramNames = this.paramNames;
- for (let i = 0; i < paramNames.length; i++) {
- const param = args[i];
- const paramName = paramNames[i];
- const paramType = paramTypes[i];
- if (this.hardcodeConstants) {
- if (paramType === 'Array' || paramType === 'Texture') {
- const paramDim = utils.getDimensions(param, true);
- const paramSize = utils.dimToTexSize({
- floatTextures: this.floatTextures,
- floatOutput: this.floatOutput
- }, paramDim);
-
- result.push(
- `uniform highp sampler2D user_${ paramName }`,
- `highp vec2 user_${ paramName }Size = vec2(${ paramSize[0] }.0, ${ paramSize[1] }.0)`,
- `highp vec3 user_${ paramName }Dim = vec3(${ paramDim[0] }.0, ${ paramDim[1]}.0, ${ paramDim[2] }.0)`
- );
- } else if (paramType === 'Number' && Number.isInteger(param)) {
- result.push(`highp float user_${ paramName } = ${ param }.0`);
- } else if (paramType === 'Number') {
- result.push(`highp float user_${ paramName } = ${ param }`);
- }
- } else {
- if (paramType === 'Array' || paramType === 'Texture') {
- result.push(
- `uniform highp sampler2D user_${ paramName }`,
- `uniform highp vec2 user_${ paramName }Size`,
- `uniform highp vec3 user_${ paramName }Dim`
- );
- } else if (paramType === 'Number') {
- result.push(`uniform highp float user_${ paramName }`);
- }
- }
- }
- return this._linesToString(result);
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _getMainConstantsString
- *
- */
- _getMainConstantsString() {
- const result = [];
- if (this.constants) {
- for (let name in this.constants) {
- if (!this.constants.hasOwnProperty(name)) continue;
- let value = parseFloat(this.constants[name]);
-
- if (Number.isInteger(value)) {
- result.push('const float constants_' + name + ' = ' + parseInt(value) + '.0');
- } else {
- result.push('const float constants_' + name + ' = ' + parseFloat(value));
- }
- }
- }
- return this._linesToString(result);
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _getKernelString
- *
- * @desc Get Kernel program string (in *glsl*) for a kernel.
- *
- * @returns {String} result
- *
- */
- _getKernelString() {
- const result = [];
- const names = this.subKernelOutputVariableNames;
- if (names !== null) {
- result.push('highp float kernelResult = 0.0');
- for (let i = 0; i < names.length; i++) {
- result.push(
- `highp float ${ names[i] } = 0.0`
- );
- }
-
- /* this is v2 prep
- result.push('highp float kernelResult = 0.0');
- result.push('layout(location = 0) out highp float fradData0 = 0.0');
- for (let i = 0; i < names.length; i++) {
- result.push(
- `highp float ${ names[i] } = 0.0`,
- `layout(location = ${ i + 1 }) out highp float fragData${ i + 1 } = 0.0`
+
+
+/**
+ * @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}`
);
- }*/
- } else {
- result.push('highp float kernelResult = 0.0');
- }
-
- return this._linesToString(result) + this.functionBuilder.getPrototypeString('kernel');
- }
-
- /**
- *
- * @memberOf WebGLKernel#
- * @function
- * @name _getMainResultString
- *
- * @desc Get main result string with checks for floatOutput, graphical, subKernelsOutputs, etc.
- *
- * @returns {String} result
- *
- */
- _getMainResultString() {
- const names = this.subKernelOutputVariableNames;
- const result = [];
- if (this.floatOutput) {
- result.push(' index *= 4.0');
- }
-
- if (this.graphical) {
- result.push(
- ' threadId = indexTo3D(index, uOutputDim)',
- ' kernel()',
- ' gl_FragColor = actualColor'
- );
- } else if (this.floatOutput) {
- result.push(
- ' threadId = indexTo3D(index, uOutputDim)',
- ' kernel()',
- ' gl_FragColor.r = kernelResult',
- ' index += 1.0',
- ' threadId = indexTo3D(index, uOutputDim)',
- ' kernel()',
- ' gl_FragColor.g = kernelResult',
- ' index += 1.0',
- ' threadId = indexTo3D(index, uOutputDim)',
- ' kernel()',
- ' gl_FragColor.b = kernelResult',
- ' index += 1.0',
- ' threadId = indexTo3D(index, uOutputDim)',
- ' kernel()',
- ' gl_FragColor.a = kernelResult'
- );
- } else if (names !== null) {
- result.push(' threadId = indexTo3D(index, uOutputDim)');
- result.push(' kernel()');
- result.push(' gl_FragData[0] = encode32(kernelResult)');
- for (let i = 0; i < names.length; i++) {
- result.push(` gl_FragData[${ i + 1 }] = encode32(${ names[i] })`);
- }
- /* this is v2 prep
- * result.push(' kernel()');
- result.push(' fragData0 = encode32(kernelResult)');
- for (let i = 0; i < names.length; i++) {
- result.push(` fragData${ i + 1 } = encode32(${ names[i] })`);
- }*/
- } else {
- result.push(
- ' threadId = indexTo3D(index, uOutputDim)',
- ' kernel()',
- ' gl_FragColor = encode32(kernelResult)'
- );
- }
-
- return this._linesToString(result);
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _linesToString
- *
- * @param {Array} lines - An Array of strings
- *
- * @returns {String} Single combined String, seperated by *\n*
- *
- */
- _linesToString(lines) {
- if (lines.length > 0) {
- return lines.join(';\n') + ';\n';
- } else {
- return '\n';
- }
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _replaceArtifacts
- *
- * @param {String} src - Shader string
- * @param {Array} map - Variables/Constants associated with shader
- *
- */
- _replaceArtifacts(src, map) {
- return src.replace(/[ ]*__([A-Z]+[0-9]*([_]?[A-Z])*)__;\n/g, (match, artifact) => {
- if (map.hasOwnProperty(artifact)) {
- return map[artifact];
- }
- throw `unhandled artifact ${ artifact }`;
- });
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _addKernels
- *
- * @desc Adds all the sub-kernels supplied with this Kernel instance.
- *
- */
- _addKernels() {
- const builder = this.functionBuilder;
- const gl = this._webGl;
- builder.addKernel(this.fnString, {
- prototypeOnly: false,
- constants: this.constants,
- debug: this.debug,
- loopMaxIterations: this.loopMaxIterations
- }, this.paramNames, this.paramTypes);
-
- if (this.subKernels !== null) {
- const ext = this.ext = gl.getExtension('WEBGL_draw_buffers');
- if (!ext) throw new Error('could not instantiate draw buffers extension');
- this.subKernelOutputTextures = [];
- this.subKernelOutputVariableNames = [];
- for (let i = 0; i < this.subKernels.length; i++) {
- const subKernel = this.subKernels[i];
- builder.addSubKernel(subKernel, {
- prototypeOnly: false,
- constants: this.constants,
- debug: this.debug,
- loopMaxIterations: this.loopMaxIterations
- });
- this.subKernelOutputTextures.push(this.getSubKernelTexture(i));
- this.subKernelOutputVariableNames.push(subKernel.name + 'Result');
- }
-
- } else if (this.subKernelProperties !== null) {
- const ext = this.ext = gl.getExtension('WEBGL_draw_buffers');
- if (!ext) throw new Error('could not instantiate draw buffers extension');
- this.subKernelOutputTextures = [];
- this.subKernelOutputVariableNames = [];
- let i = 0;
- for (let p in this.subKernelProperties) {
- if (!this.subKernelProperties.hasOwnProperty(p)) continue;
- const subKernel = this.subKernelProperties[p];
- builder.addSubKernel(subKernel, {
- prototypeOnly: false,
- constants: this.constants,
- debug: this.debug,
- loopMaxIterations: this.loopMaxIterations
- });
- this.subKernelOutputTextures.push(this.getSubKernelTexture(p));
- this.subKernelOutputVariableNames.push(subKernel.name + 'Result');
- i++;
- }
- }
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _getFragShaderString
- *
- * @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
- *
- */
- _getFragShaderString(args) {
- if (this.compiledFragShaderString !== null) {
- return this.compiledFragShaderString;
- }
- return this.compiledFragShaderString = this._replaceArtifacts(fragShaderString, this._getFragShaderArtifactMap(args));
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name _getVertShaderString
- *
- * @desc Get the vertical shader String
- *
- * @param {Array} args - The actual parameters sent to the Kernel
- *
- * @returns {String} Vertical Shader string
- *
- */
- _getVertShaderString(args) {
- if (this.compiledVertShaderString !== null) {
- return this.compiledVertShaderString;
- }
- //TODO: webgl2 compile like frag shader
- return this.compiledVertShaderString = vertShaderString;
- }
-
- /**
- * @memberOf WebGLKernel#
- * @function
- * @name toString
- *
- * @desc Returns the *pre-compiled* Kernel as a JS Object String, that can be reused.
- *
- */
- toString() {
- return kernelString(this);
- }
+ }
+ }
+ 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
};
\ No newline at end of file
diff --git a/src/backend/web-gl/runner.js b/src/backend/web-gl/runner.js
deleted file mode 100644
index 6e9a54d4..00000000
--- a/src/backend/web-gl/runner.js
+++ /dev/null
@@ -1,40 +0,0 @@
-'use strict';
-
-const RunnerBase = require('../runner-base');
-const WebGLKernel = require('./kernel');
-const utils = require('../../core/utils');
-const WebGLFunctionBuilder = require('./function-builder');
-
-
-module.exports = class WebGLRunner extends RunnerBase {
-
- /**
- * @constructor WebGLRunner
- *
- * @extends RunnerBase
-
- * @desc Instantiates a Runner instance for the kernel.
- *
- * @param {Object} settings - Settings to instantiate properties in RunnerBase, with given values
- *
- */
- constructor(settings) {
- super(new WebGLFunctionBuilder(), settings);
- this.Kernel = WebGLKernel;
- this.kernel = null;
- }
-
- /**
- * @memberOf WebGLRunner#
- * @function
- * @name getMode
- *
- * @desc Return the current mode in which gpu.js is executing.
- *
- * @returns {String} The current mode; "cpu".
- *
- */
- getMode() {
- return 'gpu';
- }
-};
\ No newline at end of file
diff --git a/src/backend/web-gl/shader-frag.js b/src/backend/web-gl/shader-frag.js
deleted file mode 100644
index 544bdd7f..00000000
--- a/src/backend/web-gl/shader-frag.js
+++ /dev/null
@@ -1,132 +0,0 @@
-module.exports = `__HEADER__;
-precision highp float;
-precision highp int;
-precision highp sampler2D;
-
-const float LOOP_MAX = __LOOP_MAX__;
-#define EPSILON 0.0000001;
-
-__CONSTANTS__;
-
-varying highp vec2 vTexCoord;
-
-vec4 round(vec4 x) {
- return floor(x + 0.5);
-}
-
-highp float round(highp float x) {
- return floor(x + 0.5);
-}
-
-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);
-}
-
-highp float integerMod(highp float x, highp float y) {
- highp float res = floor(mod(x, y));
- return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);
-}
-
-highp int integerMod(highp int x, highp int y) {
- return int(integerMod(float(x), float(y)));
-}
-
-// 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
-highp float decode32(highp vec4 rgba) {
- __DECODE32_ENDIANNESS__;
- rgba *= 255.0;
- vec2 gte128;
- gte128.x = rgba.b >= 128.0 ? 1.0 : 0.0;
- gte128.y = rgba.a >= 128.0 ? 1.0 : 0.0;
- float exponent = 2.0 * rgba.a - 127.0 + dot(gte128, MAGIC_VEC);
- float res = exp2(round(exponent));
- rgba.b = rgba.b - 128.0 * gte128.x;
- res = dot(rgba, SCALE_FACTOR) * exp2(round(exponent-23.0)) + res;
- res *= gte128.y * -2.0 + 1.0;
- return res;
-}
-
-highp vec4 encode32(highp float f) {
- highp float F = abs(f);
- highp float sign = f < 0.0 ? 1.0 : 0.0;
- highp float exponent = floor(log2(F));
- highp float mantissa = (exp2(-exponent) * F);
- // exponent += floor(log2(mantissa));
- vec4 rgba = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;
- rgba.rg = integerMod(rgba.rg, 256.0);
- rgba.b = integerMod(rgba.b, 128.0);
- rgba.a = exponent*0.5 + 63.5;
- rgba.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;
- rgba = floor(rgba);
- rgba *= 0.003921569; // 1/255
- __ENCODE32_ENDIANNESS__;
- return rgba;
-}
-// Dragons end here
-
-highp float index;
-highp vec3 threadId;
-
-highp vec3 indexTo3D(highp float idx, highp vec3 texDim) {
- highp float z = floor(idx / (texDim.x * texDim.y));
- idx -= z * texDim.x * texDim.y;
- highp float y = floor(idx / texDim.x);
- highp float x = integerMod(idx, texDim.x);
- return vec3(x, y, z);
-}
-
-highp float get(highp sampler2D tex, highp vec2 texSize, highp vec3 texDim, highp float z, highp float y, highp float x) {
- highp vec3 xyz = vec3(x, y, z);
- xyz = floor(xyz + 0.5);
- __GET_WRAPAROUND__;
- highp float index = round(xyz.x + texDim.x * (xyz.y + texDim.y * xyz.z));
- __GET_TEXTURE_CHANNEL__;
- highp float w = round(texSize.x);
- vec2 st = vec2(integerMod(index, w), float(int(index) / int(w))) + 0.5;
- __GET_TEXTURE_INDEX__;
- highp vec4 texel = texture2D(tex, st / texSize);
- __GET_RESULT__;
-}
-
-highp float get(highp sampler2D tex, highp vec2 texSize, highp vec3 texDim, highp float y, highp float x) {
- return get(tex, texSize, texDim, 0.0, y, x);
-}
-
-highp float get(highp sampler2D tex, highp vec2 texSize, highp vec3 texDim, highp float x) {
- return get(tex, texSize, texDim, 0.0, 0.0, x);
-}
-
-highp 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);
-}
-
-__MAIN_PARAMS__;
-__MAIN_CONSTANTS__;
-__KERNEL__;
-
-void main(void) {
- index = floor(vTexCoord.s * float(uTexSize.x)) + floor(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;
- __MAIN_RESULT__;
-}`;
\ No newline at end of file
diff --git a/src/backend/web-gl/shader-vert.js b/src/backend/web-gl/shader-vert.js
deleted file mode 100644
index 5e3df566..00000000
--- a/src/backend/web-gl/shader-vert.js
+++ /dev/null
@@ -1,14 +0,0 @@
-module.exports = `precision highp float;
-precision highp int;
-precision highp sampler2D;
-
-attribute highp vec2 aPos;
-attribute highp vec2 aTexCoord;
-
-varying highp vec2 vTexCoord;
-uniform vec2 ratio;
-
-void main(void) {
- gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);
- vTexCoord = aTexCoord;
-}`;
\ No newline at end of file
diff --git a/src/backend/web-gl/validator-kernel.js b/src/backend/web-gl/validator-kernel.js
deleted file mode 100644
index f5b15632..00000000
--- a/src/backend/web-gl/validator-kernel.js
+++ /dev/null
@@ -1,26 +0,0 @@
-'use strict';
-
-const WebGLKernel = require('./kernel');
-const utils = require('../../core/utils');
-
-/**
- * @class WebGLValidatorKernel
- *
- * @desc Helper class for WebGLKernel to validate texture size and dimensions.
- *
- */
-module.exports = class WebGLValidatorKernel extends WebGLKernel {
-
- /**
- * @memberOf WebGLValidatorKernel#
- * @function
- * @name validateOptions
- *
- */
- validateOptions() {
- this.texSize = utils.dimToTexSize({
- floatTextures: this.floatTextures,
- floatOutput: this.floatOutput
- }, this.dimensions, true);
- }
-};
\ No newline at end of file
diff --git a/src/backend/web-gl/vertex-shader.js b/src/backend/web-gl/vertex-shader.js
new file mode 100644
index 00000000..88647d73
--- /dev/null
+++ b/src/backend/web-gl/vertex-shader.js
@@ -0,0 +1,19 @@
+// 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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/fragment-shader.js b/src/backend/web-gl2/fragment-shader.js
new file mode 100644
index 00000000..b45a8706
--- /dev/null
+++ b/src/backend/web-gl2/fragment-shader.js
@@ -0,0 +1,452 @@
+// 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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/function-node.js b/src/backend/web-gl2/function-node.js
new file mode 100644
index 00000000..69b96e14
--- /dev/null
+++ b/src/backend/web-gl2/function-node.js
@@ -0,0 +1,47 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value-maps.js b/src/backend/web-gl2/kernel-value-maps.js
new file mode 100644
index 00000000..728f592c
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value-maps.js
@@ -0,0 +1,205 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/array2.js b/src/backend/web-gl2/kernel-value/array2.js
new file mode 100644
index 00000000..dc4ffab6
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/array2.js
@@ -0,0 +1,7 @@
+const { WebGLKernelValueArray2 } = require('../../web-gl/kernel-value/array2');
+
+class WebGL2KernelValueArray2 extends WebGLKernelValueArray2 {}
+
+module.exports = {
+ WebGL2KernelValueArray2
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/array3.js b/src/backend/web-gl2/kernel-value/array3.js
new file mode 100644
index 00000000..6cf3e26a
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/array3.js
@@ -0,0 +1,7 @@
+const { WebGLKernelValueArray3 } = require('../../web-gl/kernel-value/array3');
+
+class WebGL2KernelValueArray3 extends WebGLKernelValueArray3 {}
+
+module.exports = {
+ WebGL2KernelValueArray3
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/array4.js b/src/backend/web-gl2/kernel-value/array4.js
new file mode 100644
index 00000000..839613ca
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/array4.js
@@ -0,0 +1,7 @@
+const { WebGLKernelValueArray4 } = require('../../web-gl/kernel-value/array4');
+
+class WebGL2KernelValueArray4 extends WebGLKernelValueArray4 {}
+
+module.exports = {
+ WebGL2KernelValueArray4
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/boolean.js b/src/backend/web-gl2/kernel-value/boolean.js
new file mode 100644
index 00000000..c91a61a9
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/boolean.js
@@ -0,0 +1,7 @@
+const { WebGLKernelValueBoolean } = require('../../web-gl/kernel-value/boolean');
+
+class WebGL2KernelValueBoolean extends WebGLKernelValueBoolean {}
+
+module.exports = {
+ WebGL2KernelValueBoolean
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/dynamic-html-image-array.js b/src/backend/web-gl2/kernel-value/dynamic-html-image-array.js
new file mode 100644
index 00000000..2ee88b4f
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/dynamic-html-image-array.js
@@ -0,0 +1,27 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/dynamic-html-image.js b/src/backend/web-gl2/kernel-value/dynamic-html-image.js
new file mode 100644
index 00000000..f1ba34eb
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/dynamic-html-image.js
@@ -0,0 +1,17 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/dynamic-html-video.js b/src/backend/web-gl2/kernel-value/dynamic-html-video.js
new file mode 100644
index 00000000..00f723d1
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/dynamic-html-video.js
@@ -0,0 +1,8 @@
+const { utils } = require('../../../utils');
+const { WebGL2KernelValueDynamicHTMLImage } = require('./dynamic-html-image');
+
+class WebGL2KernelValueDynamicHTMLVideo extends WebGL2KernelValueDynamicHTMLImage {}
+
+module.exports = {
+ WebGL2KernelValueDynamicHTMLVideo
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/dynamic-memory-optimized-number-texture.js b/src/backend/web-gl2/kernel-value/dynamic-memory-optimized-number-texture.js
new file mode 100644
index 00000000..5e3cff4b
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/dynamic-memory-optimized-number-texture.js
@@ -0,0 +1,16 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/dynamic-number-texture.js b/src/backend/web-gl2/kernel-value/dynamic-number-texture.js
new file mode 100644
index 00000000..e3820a56
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/dynamic-number-texture.js
@@ -0,0 +1,17 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/dynamic-single-array.js b/src/backend/web-gl2/kernel-value/dynamic-single-array.js
new file mode 100644
index 00000000..7278317d
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/dynamic-single-array.js
@@ -0,0 +1,28 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/dynamic-single-array1d-i.js b/src/backend/web-gl2/kernel-value/dynamic-single-array1d-i.js
new file mode 100644
index 00000000..45203f92
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/dynamic-single-array1d-i.js
@@ -0,0 +1,24 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/dynamic-single-array2d-i.js b/src/backend/web-gl2/kernel-value/dynamic-single-array2d-i.js
new file mode 100644
index 00000000..d80f712d
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/dynamic-single-array2d-i.js
@@ -0,0 +1,24 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/dynamic-single-array3d-i.js b/src/backend/web-gl2/kernel-value/dynamic-single-array3d-i.js
new file mode 100644
index 00000000..15f79ba4
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/dynamic-single-array3d-i.js
@@ -0,0 +1,24 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/dynamic-single-input.js b/src/backend/web-gl2/kernel-value/dynamic-single-input.js
new file mode 100644
index 00000000..21fa5b31
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/dynamic-single-input.js
@@ -0,0 +1,29 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/dynamic-unsigned-array.js b/src/backend/web-gl2/kernel-value/dynamic-unsigned-array.js
new file mode 100644
index 00000000..514682c5
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/dynamic-unsigned-array.js
@@ -0,0 +1,17 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/dynamic-unsigned-input.js b/src/backend/web-gl2/kernel-value/dynamic-unsigned-input.js
new file mode 100644
index 00000000..9c79330a
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/dynamic-unsigned-input.js
@@ -0,0 +1,17 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/float.js b/src/backend/web-gl2/kernel-value/float.js
new file mode 100644
index 00000000..b3fc5a78
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/float.js
@@ -0,0 +1,8 @@
+const { utils } = require('../../../utils');
+const { WebGLKernelValueFloat } = require('../../web-gl/kernel-value/float');
+
+class WebGL2KernelValueFloat extends WebGLKernelValueFloat {}
+
+module.exports = {
+ WebGL2KernelValueFloat
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/html-image-array.js b/src/backend/web-gl2/kernel-value/html-image-array.js
new file mode 100644
index 00000000..b7707a57
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/html-image-array.js
@@ -0,0 +1,73 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/html-image.js b/src/backend/web-gl2/kernel-value/html-image.js
new file mode 100644
index 00000000..637182a0
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/html-image.js
@@ -0,0 +1,17 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/html-video.js b/src/backend/web-gl2/kernel-value/html-video.js
new file mode 100644
index 00000000..85fb3953
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/html-video.js
@@ -0,0 +1,8 @@
+const { utils } = require('../../../utils');
+const { WebGL2KernelValueHTMLImage } = require('./html-image');
+
+class WebGL2KernelValueHTMLVideo extends WebGL2KernelValueHTMLImage {}
+
+module.exports = {
+ WebGL2KernelValueHTMLVideo
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/integer.js b/src/backend/web-gl2/kernel-value/integer.js
new file mode 100644
index 00000000..8b0467c8
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/integer.js
@@ -0,0 +1,20 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/memory-optimized-number-texture.js b/src/backend/web-gl2/kernel-value/memory-optimized-number-texture.js
new file mode 100644
index 00000000..7fd85798
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/memory-optimized-number-texture.js
@@ -0,0 +1,18 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/number-texture.js b/src/backend/web-gl2/kernel-value/number-texture.js
new file mode 100644
index 00000000..440f1e4e
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/number-texture.js
@@ -0,0 +1,18 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/single-array.js b/src/backend/web-gl2/kernel-value/single-array.js
new file mode 100644
index 00000000..c149f06f
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/single-array.js
@@ -0,0 +1,31 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/single-array1d-i.js b/src/backend/web-gl2/kernel-value/single-array1d-i.js
new file mode 100644
index 00000000..41de1187
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/single-array1d-i.js
@@ -0,0 +1,22 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/single-array2d-i.js b/src/backend/web-gl2/kernel-value/single-array2d-i.js
new file mode 100644
index 00000000..f7723860
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/single-array2d-i.js
@@ -0,0 +1,22 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/single-array3d-i.js b/src/backend/web-gl2/kernel-value/single-array3d-i.js
new file mode 100644
index 00000000..904f4bfd
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/single-array3d-i.js
@@ -0,0 +1,22 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/single-input.js b/src/backend/web-gl2/kernel-value/single-input.js
new file mode 100644
index 00000000..261168e2
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/single-input.js
@@ -0,0 +1,27 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/unsigned-array.js b/src/backend/web-gl2/kernel-value/unsigned-array.js
new file mode 100644
index 00000000..bac1e6f1
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/unsigned-array.js
@@ -0,0 +1,17 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel-value/unsigned-input.js b/src/backend/web-gl2/kernel-value/unsigned-input.js
new file mode 100644
index 00000000..ed933347
--- /dev/null
+++ b/src/backend/web-gl2/kernel-value/unsigned-input.js
@@ -0,0 +1,17 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/kernel.js b/src/backend/web-gl2/kernel.js
new file mode 100644
index 00000000..52adbd60
--- /dev/null
+++ b/src/backend/web-gl2/kernel.js
@@ -0,0 +1,641 @@
+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
+};
\ No newline at end of file
diff --git a/src/backend/web-gl2/vertex-shader.js b/src/backend/web-gl2/vertex-shader.js
new file mode 100644
index 00000000..e44dc986
--- /dev/null
+++ b/src/backend/web-gl2/vertex-shader.js
@@ -0,0 +1,20 @@
+// 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
+};
\ No newline at end of file
diff --git a/src/wrapper/header.js b/src/browser-header.txt
similarity index 100%
rename from src/wrapper/header.js
rename to src/browser-header.txt
diff --git a/src/browser.js b/src/browser.js
new file mode 100644
index 00000000..740a38dc
--- /dev/null
+++ b/src/browser.js
@@ -0,0 +1,25 @@
+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;
\ No newline at end of file
diff --git a/src/core/alias.js b/src/core/alias.js
deleted file mode 100644
index 39a60afb..00000000
--- a/src/core/alias.js
+++ /dev/null
@@ -1,7 +0,0 @@
-'use strict';
-
-const utils = require('./utils');
-module.exports = function alias(name, fn) {
- const fnString = fn.toString();
- return new Function(`return function ${ name } (${ utils.getParamNamesFromString(fnString).join(', ') }) {${ utils.getFunctionBodyFromString(fnString) }}`)();
-};
\ No newline at end of file
diff --git a/src/core/gpu-core.js b/src/core/gpu-core.js
deleted file mode 100644
index 5748793a..00000000
--- a/src/core/gpu-core.js
+++ /dev/null
@@ -1,90 +0,0 @@
-'use strict';
-
-const UtilsCore = require("./utils-core");
-
-/**
- * This is a minimalistic version of GPU.js used
- * to run precompiled GPU.JS code.
- *
- * This intentionally excludes the JS AST compiller : which is 400kb alone/
- *
- * @class GPUCore
- */
-module.exports = class GPUCore {
-
- /**
- * @name validateKernelObj
- * @function
- * @static
- * @memberOf GPUCore
- *
- * @description Validates the KernelObj to comply with the defined format
- * Note that this does only a limited sanity check, and does not
- * gurantee a full working validation.
- *
- * For the kernel object format see :
- *
- * @param {Object|String} kernelObj - KernelObj used to validate
- *
- * @returns {Object} The validated kernel object, converted from JSON if needed
- *
- */
- static validateKernelObj(kernelObj) {
-
- // NULL validation
- if (kernelObj == null) {
- throw "KernelObj being validated is NULL";
- }
-
- // String JSON conversion
- if (typeof kernelObj === "string") {
- try {
- kernelObj = JSON.parse(kernelObj);
- } catch (e) {
- console.error(e);
- throw "Failed to convert KernelObj from JSON string";
- }
-
- // NULL validation
- if (kernelObj == null) {
- throw "Invalid (NULL) KernelObj JSON string representation";
- }
- }
-
- // Check for kernel obj flag
- if (kernelObj.isKernelObj != true) {
- throw "Failed missing isKernelObj flag check";
- }
-
- // Return the validated kernelObj
- return kernelObj;
- }
-
- /**
- * @name loadKernelObj
- * @function
- * @static
- * @memberOf GPUCore
- *
- * @description Loads the precompilled kernel object. For GPUCore this is the ONLY way to create the kernel.
- * To generate the kernelObj use
- *
- * Note that this function calls internally, and throws an exception if it fails.
- *
- * @see GPUCore.validateKernelObj
- * @see Kernel.exportKernelObj
- *
- * @param {Object} kernelObj - The precompilled kernel object
- * @param {Object} inOpt - [Optional] the option overrides to use
- *
- * @returns {Function} The kernel function
- *
- */
- static loadKernelObj(kernelObj, inOpt) {
-
- // Validates the kernelObj, throws an exception if it fails
- kernelObj = validateKernelObj(kernelObj);
-
-
- }
-}
\ No newline at end of file
diff --git a/src/core/gpu.js b/src/core/gpu.js
deleted file mode 100644
index 6fda7a6e..00000000
--- a/src/core/gpu.js
+++ /dev/null
@@ -1,327 +0,0 @@
-'use strict';
-
-const utils = require('./utils');
-const WebGLRunner = require('../backend/web-gl/runner');
-const CPURunner = require('../backend/cpu/runner');
-const WebGLValidatorKernel = require('../backend/web-gl/validator-kernel');
-const GPUCore = require("./gpu-core");
-
-/**
- * Initialises the GPU.js library class which manages the webGlContext for the created functions.
- * @class
- * @extends GPUCore
- */
-class GPU extends GPUCore {
- /**
- * Creates an instance of GPU.
- * @param {any} settings - Settings to set mode, andother properties. See #GPUCore
- * @memberOf GPU#
- */
- constructor(settings) {
- super(settings);
-
- settings = settings || {};
- this._canvas = settings.canvas || null;
- this._webGl = settings.webGl || null;
- let mode = settings.mode || 'webgl';
- if (!utils.isWebGlSupported()) {
- console.warn('Warning: gpu not supported, falling back to cpu support');
- mode = 'cpu';
- }
-
- this.kernels = [];
-
- const runnerSettings = {
- canvas: this._canvas,
- webGl: this._webGl
- };
-
- if (mode) {
- switch (mode.toLowerCase()) {
- case 'cpu':
- this._runner = new CPURunner(runnerSettings);
- break;
- case 'gpu':
- case 'webgl':
- this._runner = new WebGLRunner(runnerSettings);
- break;
- case 'webgl-validator':
- this._runner = new WebGLRunner(runnerSettings);
- this._runner.Kernel = WebGLValidatorKernel;
- break;
- default:
- throw new Error(`"${mode}" mode is not defined`);
- }
- }
- }
- /**
- *
- * This creates a callable function object to call the kernel function with the argument parameter set
- *
- * @name createKernel
- * @function
- * @memberOf GPU##
- *
- * @param {Function} inputFunction - The calling to perform the conversion
- * @param {Object} settings - The parameter configuration object
- * @property {String} settings.dimensions - Thread dimension array (Defeaults to [1024])
- * @property {String} settings.mode - CPU / GPU configuration mode (Defaults to null)
- *
- * The following modes are supported
- * *null* / *'auto'* : Attempts to build GPU mode, else fallbacks
- * *'gpu'* : Attempts to build GPU mode, else fallbacks
- * *'cpu'* : Forces JS fallback mode only
- *
- *
- * @returns {Function} callable function to run
- *
- */
- createKernel(fn, settings) {
- //
- // basic parameters safety checks
- //
- if (typeof fn === 'undefined') {
- throw 'Missing fn parameter';
- }
- if (!utils.isFunction(fn)) {
- throw 'fn parameter not a function';
- }
-
- const kernel = this._runner.buildKernel(fn, settings || {});
-
- //if canvas didn't come from this, propagate from kernel
- if (!this._canvas) {
- this._canvas = kernel.getCanvas();
- }
- if (!this._runner.canvas) {
- this._runner.canvas = kernel.getCanvas();
- }
-
- this.kernels.push(kernel);
-
- return kernel;
- }
-
- /**
- *
- * 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*
- *
- * @name createKernelMap
- * @function
- * @memberOf GPU#
- *
- * @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;
- if (typeof arguments[arguments.length - 2] === 'function') {
- fn = arguments[arguments.length - 2];
- settings = arguments[arguments.length - 1];
- } else {
- fn = arguments[arguments.length - 1];
- }
-
- if (!utils.isWebGlDrawBuffersSupported()) {
- this._runner = new CPURunner(settings);
- }
-
- const kernel = this.createKernel(fn, settings);
- if (Array.isArray(arguments[0])) {
- const functions = arguments[0];
- for (let i = 0; i < functions.length; i++) {
- kernel.addSubKernel(functions[i]);
- }
- } else {
- const functions = arguments[0];
- for (let p in functions) {
- if (!functions.hasOwnProperty(p)) continue;
- kernel.addSubKernelProperty(p, functions[p]);
- }
- }
-
- return kernel;
- }
-
- /**
- *
- * 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.
- *
- * @name combineKernels
- * @function
- * @memberOf GPU#
- *
- * @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 lastKernel = arguments[arguments.length - 2];
- const combinedKernel = arguments[arguments.length - 1];
- if (this.getMode() === 'cpu') return combinedKernel;
-
- const canvas = arguments[0].getCanvas();
- let webGl = arguments[0].getWebGl();
-
- for (let i = 0; i < arguments.length - 1; i++) {
- arguments[i]
- .setCanvas(canvas)
- .setWebGl(webGl)
- .setOutputToTexture(true);
- }
-
- return function() {
- combinedKernel.apply(null, arguments);
- const texSize = lastKernel.texSize;
- const gl = lastKernel.getWebGl();
- const threadDim = lastKernel.threadDim;
- let result;
- if (lastKernel.floatOutput) {
- result = new Float32Array(texSize[0] * texSize[1] * 4);
- gl.readPixels(0, 0, texSize[0], texSize[1], gl.RGBA, gl.FLOAT, result);
- } else {
- const bytes = new Uint8Array(texSize[0] * texSize[1] * 4);
- gl.readPixels(0, 0, texSize[0], texSize[1], gl.RGBA, gl.UNSIGNED_BYTE, bytes);
- result = new Float32Array(bytes.buffer);
- }
-
- result = result.subarray(0, threadDim[0] * threadDim[1] * threadDim[2]);
-
- if (lastKernel.dimensions.length === 1) {
- return result;
- } else if (lastKernel.dimensions.length === 2) {
- return utils.splitArray(result, lastKernel.dimensions[0]);
- } else if (lastKernel.dimensions.length === 3) {
- const cube = utils.splitArray(result, lastKernel.dimensions[0] * lastKernel.dimensions[1]);
- return cube.map(function(x) {
- return utils.splitArray(x, lastKernel.dimensions[0]);
- });
- }
- };
- }
-
-
- /**
- *
- * Adds additional functions, that the kernel may call.
- *
- * @name addFunction
- * @function
- * @memberOf GPU#
- *
- * @param {Function|String} fn - JS Function to do conversion
- * @param {String[]|Object} paramTypes - Parameter type array, assumes all parameters are 'float' if null
- * @param {String} returnType - The return type, assumes 'float' if null
- *
- * @returns {GPU} returns itself
- *
- */
- addFunction(fn, paramTypes, returnType) {
- this._runner.functionBuilder.addFunction(null, fn, paramTypes, returnType);
- return this;
- }
-
- /**
- *
- * Return the current mode in which gpu.js is executing.
- * @name getMode
- * @function
- * @memberOf GPU#
- *
- * @returns {String} The current mode, "cpu", "webgl", etc.
- *
- */
- getMode() {
- return this._runner.getMode();
- }
-
- /**
- *
- * Return TRUE, if browser supports WebGl AND Canvas
- *
- * @name get isWebGlSupported
- * @function
- * @memberOf GPU#
- *
- * Note: This function can also be called directly `GPU.isWebGlSupported()`
- *
- * @returns {Boolean} TRUE if browser supports webGl
- *
- */
- isWebGlSupported() {
- return utils.isWebGlSupported();
- }
-
- /**
- *
- * Return the canvas object bound to this gpu instance.
- *
- * @name getCanvas
- * @function
- * @memberOf GPU#
- *
- * @returns {Object} Canvas object if present
- *
- */
- getCanvas() {
- return this._canvas;
- }
-
- /**
- *
- * Return the webGl object bound to this gpu instance.
- *
- * @name getWebGl
- * @function
- * @memberOf GPU#
- *
- * @returns {Object} WebGl object if present
- *
- */
- getWebGl() {
- return this._webGl;
- }
-};
-
-// This ensure static methods are "inherited"
-// See: https://stackoverflow.com/questions/5441508/how-to-inherit-static-methods-from-base-class-in-javascript
-Object.assign(GPU, GPUCore);
-
-module.exports = GPU;
\ No newline at end of file
diff --git a/src/core/texture.js b/src/core/texture.js
deleted file mode 100644
index 6749da3b..00000000
--- a/src/core/texture.js
+++ /dev/null
@@ -1,55 +0,0 @@
-'use strict';
-
-let gpu = null;
-
-module.exports = class Texture {
-
- /**
- * @desc WebGl Texture implementation in JS
- * @constructor Texture
- * @param {Object} texture
- * @param {Array} size
- * @param {Array} dimensions
- * @param {Object} webGl
- */
- constructor(texture, size, dimensions, webGl) {
- this.texture = texture;
- this.size = size;
- this.dimensions = dimensions;
- this.webGl = webGl;
- this.kernel = null;
- }
-
- /**
- * @name toArray
- * @function
- * @memberOf Texture#
- *
- * @desc Converts the Texture into a JavaScript Array.
- *
- * @param {Object} The `gpu` Object
- *
- */
- toArray(gpu) {
- if (!gpu) throw new Error('You need to pass the GPU object for toArray to work.');
- if (this.kernel) return this.kernel(this);
-
- this.kernel = gpu.createKernel(function(x) {
- return x[this.thread.z][this.thread.y][this.thread.x];
- }).setDimensions(this.dimensions);
-
- return this.kernel(this);
- }
-
- /**
- * @name delete
- * @desc Deletes the Texture.
- * @function
- * @memberOf Texture#
- *
- *
- */
- delete() {
- return this.webGl.deleteTexture(this.texture);
- }
-};
\ No newline at end of file
diff --git a/src/core/utils-core.js b/src/core/utils-core.js
deleted file mode 100644
index 8f0d7907..00000000
--- a/src/core/utils-core.js
+++ /dev/null
@@ -1,223 +0,0 @@
-'use strict';
-
-/**
- *
- * @desc Reduced subset of Utils, used exclusively in gpu-core.js
- * Various utility functions / snippets of code that GPU.JS uses internally.\
- * This covers various snippets of code that is not entirely gpu.js specific (ie. may find uses elsewhere)
- *
- * Note that all methods in this class is 'static' by nature `UtilsCore.functionName()`
- *
- * @class UtilsCore
- *
- */
-
-class UtilsCore {
-
- /**
- * @typedef {Object} webGlContext
- */
-
- /**
- * @typedef {Object} CanvasDOMObject
- */
-
- //-----------------------------------------------------------------------------
- //
- // Canvas validation and support
- //
- //-----------------------------------------------------------------------------
-
- /**
- * @name isCanvas
- * @static
- * @function
- * @memberOf UtilsCore
- *
- *
- * @desc Return TRUE, on a valid DOM canvas object
- *
- * Note: This does just a VERY simply sanity check. And may give false positives.
- *
- * @param {CanvasDOMObject} canvasObj - Object to validate
- *
- * @returns {Boolean} TRUE if the object is a DOM canvas
- *
- */
- static isCanvas(canvasObj) {
- return (
- canvasObj !== null &&
- canvasObj.nodeName &&
- canvasObj.getContext &&
- canvasObj.nodeName.toUpperCase() === 'CANVAS'
- );
- }
-
- /**
- * @name isCanvasSupported
- * @function
- * @static
- * @memberOf UtilsCore
- *
- * @desc Return TRUE, if browser supports canvas
- *
- * @returns {Boolean} TRUE if browser supports canvas
- *
- */
- static isCanvasSupported() {
- return _isCanvasSupported;
- }
-
- /**
- * @name initCanvas
- * @function
- * @static
- * @memberOf UtilsCore
- *
- * @desc Initiate and returns a canvas, for usage in init_webgl.
- * Returns only if canvas is supported by browser.
- *
- * @returns {CanvasDOMObject} CanvasDOMObject if supported by browser, else null
- *
- */
- static initCanvas() {
- // Fail fast if browser previously detected no support
- if (!_isCanvasSupported) {
- return null;
- }
-
- // Create a new canvas DOM
- const canvas = document.createElement('canvas');
-
- // Default width and height, to fix webgl issue in safari
- canvas.width = 2;
- canvas.height = 2;
-
- // Returns the canvas
- return canvas;
- }
-
- //-----------------------------------------------------------------------------
- //
- // Webgl validation and support
- //
- //-----------------------------------------------------------------------------
-
-
- /**
- *
- * @name isWebGl
- * @function
- * @static
- * @memberOf UtilsCore
- *
- * @desc Return TRUE, on a valid webGlContext object
- *
- * Note: This does just a VERY simply sanity check. And may give false positives.
- *
- * @param {webGlContext} webGlObj - Object to validate
- *
- * @returns {Boolean} TRUE if the object is a webGlContext object
- *
- */
- static isWebGl(webGlObj) {
- return webGlObj && typeof webGlObj.getExtension === 'function';
- }
-
- /**
- * @name isWebGlSupported
- * @function
- * @static
- * @memberOf UtilsCore
- *
- * @desc Return TRUE, if browser supports webgl
- *
- * @returns {Boolean} TRUE if browser supports webgl
- *
- */
- static isWebGlSupported() {
- return _isWebGlSupported;
- }
-
- static isWebGlDrawBuffersSupported() {
- return _isWebGlDrawBuffersSupported;
- }
-
- // Default webgl options to use
- static initWebGlDefaultOptions() {
- return {
- alpha: false,
- depth: false,
- antialias: false
- };
- }
-
- /**
- * @name initWebGl
- * @function
- * @static
- * @memberOf UtilsCore
- *
- * @desc Initiate and returns a webGl, from a canvas object
- * Returns only if webGl is supported by browser.
- *
- * @param {CanvasDOMObject} canvasObj - Object to validate
- *
- * @returns {CanvasDOMObject} CanvasDOMObject if supported by browser, else null
- *
- */
- static initWebGl(canvasObj) {
-
- // First time setup, does the browser support check memorizer
- if (typeof _isCanvasSupported !== 'undefined' || canvasObj === null) {
- if (!_isCanvasSupported) {
- return null;
- }
- }
-
- // Fail fast for invalid canvas object
- if (!UtilsCore.isCanvas(canvasObj)) {
- throw new Error('Invalid canvas object - ' + canvasObj);
- }
-
- // Create a new canvas DOM
- const webGl = (
- canvasObj.getContext('experimental-webgl', UtilsCore.initWebGlDefaultOptions()) ||
- canvasObj.getContext('webgl', UtilsCore.initWebGlDefaultOptions())
- );
-
- if (webGl) {
- // Get the extension that is needed
- webGl.OES_texture_float = webGl.getExtension('OES_texture_float');
- webGl.OES_texture_float_linear = webGl.getExtension('OES_texture_float_linear');
- webGl.OES_element_index_uint = webGl.getExtension('OES_element_index_uint');
- }
-
- // Returns the canvas
- return webGl;
- }
-
-}
-
-//-----------------------------------------------------------------------------
-//
-// Canvas & Webgl validation and support constants
-//
-//-----------------------------------------------------------------------------
-
-const _isCanvasSupported = typeof document !== 'undefined' ? UtilsCore.isCanvas(document.createElement('canvas')) : false;
-const _testingWebGl = UtilsCore.initWebGl(UtilsCore.initCanvas());
-const _isWebGlSupported = UtilsCore.isWebGl(_testingWebGl);
-const _isWebGlDrawBuffersSupported = _isWebGlSupported && Boolean(_testingWebGl.getExtension('WEBGL_draw_buffers'));
-
-if (_isWebGlSupported) {
- UtilsCore.OES_texture_float = _testingWebGl.OES_texture_float;
- UtilsCore.OES_texture_float_linear = _testingWebGl.OES_texture_float_linear;
- UtilsCore.OES_element_index_uint = _testingWebGl.OES_element_index_uint;
-} else {
- UtilsCore.OES_texture_float = false;
- UtilsCore.OES_texture_float_linear = false;
- UtilsCore.OES_element_index_uint = false;
-}
-
-module.exports = UtilsCore;
\ No newline at end of file
diff --git a/src/core/utils.js b/src/core/utils.js
deleted file mode 100644
index 102dc51d..00000000
--- a/src/core/utils.js
+++ /dev/null
@@ -1,516 +0,0 @@
-'use strict';
-
-/**
- *
- * @classdesc Various utility functions / snippets of code that GPU.JS uses internally.\
- * This covers various snippets of code that is not entirely gpu.js specific (ie. may find uses elsewhere)
- *
- * Note that all methods in this class are *static* by nature `Utils.functionName()`
- *
- * @class Utils
- * @extends UtilsCore
- *
- */
-
-const UtilsCore = require("./utils-core");
-const Texture = require('./texture');
-// FUNCTION_NAME regex
-const FUNCTION_NAME = /function ([^(]*)/;
-
-// STRIP COMMENTS regex
-const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
-
-// ARGUMENT NAMES regex
-const ARGUMENT_NAMES = /([^\s,]+)/g;
-
-const _systemEndianness = (() => {
- 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');
-})();
-
-let _isFloatReadPixelsSupported = null;
-
-class Utils extends UtilsCore {
-
- //-----------------------------------------------------------------------------
- //
- // System values support (currently only endianness)
- //
- //-----------------------------------------------------------------------------
-
- /**
- * @memberOf Utils
- * @name systemEndianness
- * @function
- * @static
- *
- * Gets the system endianness, and cache it
- *
- * @returns {String} 'LE' or 'BE' depending on system architecture
- *
- * Credit: https://gist.github.com/TooTallNate/4750953
- */
- static systemEndianness() {
- return _systemEndianness;
- }
-
- //-----------------------------------------------------------------------------
- //
- // Function and function string validations
- //
- //-----------------------------------------------------------------------------
-
- /**
- * @memberOf Utils
- * @name isFunction
- * @function
- * @static
- *
- * Return 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
- *
- */
- static isFunction(funcObj) {
- return typeof(funcObj) === 'function';
- }
-
- /**
- * @memberOf Utils
- * @name isFunctionString
- * @function
- * @static
- *
- * Return TRUE, on a valid JS function string
- *
- * Note: This does just a VERY simply sanity check. And may give false positives.
- *
- * @param {String} funcStr - String of JS function to validate
- *
- * @returns {Boolean} TRUE if the string passes basic validation
- *
- */
- static isFunctionString(funcStr) {
- if (funcStr !== null) {
- return (funcStr.toString()
- .slice(0, 'function'.length)
- .toLowerCase() === 'function');
- }
- return false;
- }
-
- /**
- * @memberOf Utils
- * @name getFunctionName_fromString
- * @function
- * @static
- *
- * 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)
- *
- */
- static getFunctionNameFromString(funcStr) {
- return FUNCTION_NAME.exec(funcStr)[1];
- }
-
- static getFunctionBodyFromString(funcStr) {
- return funcStr.substring(funcStr.indexOf('{') + 1, funcStr.lastIndexOf('}'));
- }
-
- /**
- * @memberOf Utils
- * @name getParamNames_fromString
- * @function
- * @static
- *
- * Return list of parameter names extracted from the JS function string
- *
- * @param {String} funcStr - String of JS function to validate
- *
- * @returns {String[]} Array representing all the parameter names
- *
- */
- static getParamNamesFromString(func) {
- const fnStr = func.toString().replace(STRIP_COMMENTS, '');
- let result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
- if (result === null)
- result = [];
- return result;
- }
-
- //-----------------------------------------------------------------------------
- //
- // Object / function cloning and manipulation
- //
- //-----------------------------------------------------------------------------
-
- /**
- * @memberOf Utils
- * @name clone
- * @function
- * @static
- *
- * Returns a clone
- *
- * @param {Object} obj - Object to clone
- *
- * @returns {Object} Cloned object
- *
- */
- static 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;
- }
-
- /**
- * @memberOf Utils
- * @name newPromise
- * @function
- * @static
- *
- * Returns a `new Promise` object based on the underlying implmentation
- *
- * @param {Function} executor - Promise builder function
- *
- * @returns {Promise} Promise object
- *
- */
- static newPromise(executor) {
- const simple = Promise || small_promise;
- if (simple === null) {
- throw TypeError('Browser is missing Promise implementation. Consider adding small_promise.js polyfill');
- }
- return (new simple(executor));
- }
-
- /**
- * @memberOf Utils
- * @name functionBinder
- * @function
- * @static
- *
- * Limited implementation of Function.bind, with fallback
- *
- * @param {Function} inFunc - to setup bind on
- * @param {Object} thisObj - The this parameter to assume inside the binded function
- *
- * @returns {Function} The binded function
- *
- */
- static functionBinder(inFunc, thisObj) {
- if (inFunc.bind) {
- return inFunc.bind(thisObj);
- }
-
- return function() {
- const args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));
- return inFunc.apply(thisObj, args);
- }
- }
-
- /**
- * @memberOf Utils
- * @name isArray
- * @function
- * @static
- *
- * * Checks if is an array or Array-like object
- *
- * @param {Object} arg - The argument object to check if is array
- *
- * @returns {Boolean} true if is array or Array-like object
- *
- */
- static isArray(array) {
- if (isNaN(array.length)) {
- return false;
- }
-
- return true;
- }
-
- /**
- * @memberOf Utils
- * @name getArgumentType
- * @function
- * @static
- *
- * Evaluate the argument type, to apply respective logic for it
- *
- * @param {Object} arg - The argument object to evaluate type
- *
- * @returns {String} Argument type Array/Number/Texture/Unknown
- *
- */
- static getArgumentType(arg) {
- if (Utils.isArray(arg)) {
- return 'Array';
- } else if (typeof arg === 'number') {
- return 'Number';
- } else if (arg instanceof Texture) {
- return 'Texture';
- } else {
- return 'Unknown';
- }
- }
- /**
- * @typedef {Object} gpuJSObject
- */
-
- /**
- * @memberOf Utils
- * @name isFloatReadPixelsSupported
- * @function
- * @static
- *
- * Checks if the browser supports readPixels with float type
- *
- * @param {gpuJSObject} gpu - the gpu object
- *
- * @returns {Boolean} true if browser supports
- *
- */
- static isFloatReadPixelsSupported() {
- if (_isFloatReadPixelsSupported !== null) {
- return _isFloatReadPixelsSupported
- }
-
- const GPU = require('../index');
- const x = new GPU({
- mode: 'webgl-validator'
- }).createKernel(function() {
- return 1;
- }, {
- dimensions: [2],
- floatTextures: true,
- floatOutput: true,
- floatOutputForce: true
- })();
-
- _isFloatReadPixelsSupported = x[0] === 1;
-
- return _isFloatReadPixelsSupported;
- }
-
-
- static dimToTexSize(opt, dimensions, output) {
- let numTexels = dimensions[0];
- for (let i = 1; i < dimensions.length; i++) {
- numTexels *= dimensions[i];
- }
-
- if (opt.floatTextures && (!output || opt.floatOutput)) {
- numTexels = Math.ceil(numTexels / 4);
- }
-
- const w = Math.ceil(Math.sqrt(numTexels));
- return [w, w];
- }
-
- /**
- * @memberOf Utils
- * @name getDimensions
- * @function
- * @static
- *
- * Return the dimension of an array.
- *
- * @param {Array} x - The array
- * @param {number} pad - To include padding in the dimension calculation [Optional]
- *
- *
- *
- */
-
- static 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.dimensions;
- } else {
- throw 'Unknown dimensions of ' + x;
- }
-
- if (pad) {
- ret = Utils.clone(ret);
- while (ret.length < 3) {
- ret.push(1);
- }
- }
-
- return ret;
- }
-
- /**
- * @memberOf Utils
- * @name pad
- * @function
- * @static
- *
- * Pad an array AND its elements with leading and ending zeros
- *
- * @param {Array} arr - the array to pad zeros to
- * @param {number} padding - amount of padding
- *
- * @returns {Array} Array with leading and ending zeros, and all the elements padded by zeros.
- *
- */
- static pad(arr, padding) {
- function zeros(n) {
- return Array.apply(null, new Array(n)).map(Number.prototype.valueOf, 0);
- }
-
- const len = arr.length + padding * 2;
-
- let ret = arr.map(function(x) {
- return [].concat(zeros(padding), x, zeros(padding));
- });
-
- for (let i = 0; i < padding; i++) {
- ret = [].concat([zeros(len)], ret, [zeros(len)]);
- }
-
- return ret;
- }
-
- /**
- * @memberOf Utils
- * @name flatten2dArrayTo
- * @function
- * @static
- *
- * Puts a nested 2d array into a one-dimensional target array
- * @param {Array|*} array
- * @param {Float32Array|Float64Array} target
- */
- static flatten2dArrayTo(array, target) {
- let offset = 0;
- for (let y = 0; y < array.length; y++) {
- target.set(array[y], offset);
- offset += array[y].length;
- }
- }
-
- /**
- * @memberOf Utils
- * @name flatten3dArrayTo
- * @function
- * @static
- *
- * Puts a nested 3d array into a one-dimensional target array
- * @param {Array|*} array
- * @param {Float32Array|Float64Array} target
- */
- static 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;
- }
- }
- }
-
- /**
- * @memberOf Utils
- * @name flatten3dArrayTo
- * @function
- * @static
- *
- * Puts a nested 1d, 2d, or 3d array into a one-dimensional target array
- * @param {Array|*} array
- * @param {Float32Array|Float64Array} target
- */
- static flattenTo(array, target) {
- if (Utils.isArray(array[0])) {
- if (Utils.isArray(array[0][0])) {
- Utils.flatten3dArrayTo(array, target);
- } else {
- Utils.flatten2dArrayTo(array, target);
- }
- } else {
- target.set(array);
- }
- }
-
- /**
- * @memberOf Utils
- * @name splitArray
- * @function
- * @static
- *
- * Splits an array into smaller arrays.
- * Number of elements in one small chunk is given by `part`
- *
- * @param {Array} array - The array to split into chunks
- * @param {Array} part - elements in one chunk
- *
-
- * @returns {Array} An array of smaller chunks
- *
- */
- static splitArray(array, part) {
- const result = [];
- for (let i = 0; i < array.length; i += part) {
- result.push(Array.prototype.slice.call(array, i, i + part));
- }
- return result;
- }
-
- static getAstString(source, ast) {
- let lines = Array.isArray(source) ? source : source.split(/\r?\n/g);
- const start = ast.loc.start;
- const end = ast.loc.end;
- const result = [];
- result.push(lines[start.line - 1].slice(start.column));
- for (let i = start.line; i < end.line - 1; i++) {
- result.push(lines[i]);
- }
- result.push(lines[end.line - 1].slice(0, end.column));
- return result.join('\n');
- }
-
- static allPropertiesOf(obj) {
- const props = [];
-
- do {
- props.push.apply(props, Object.getOwnPropertyNames(obj));
- } while (obj = Object.getPrototypeOf(obj));
-
- return props;
- }
-}
-
-// This ensure static methods are "inherited"
-// See: https://stackoverflow.com/questions/5441508/how-to-inherit-static-methods-from-base-class-in-javascript
-Object.assign(Utils, UtilsCore);
-
-module.exports = Utils;
\ No newline at end of file
diff --git a/src/gpu.js b/src/gpu.js
new file mode 100644
index 00000000..c9b1166b
--- /dev/null
+++ b/src/gpu.js
@@ -0,0 +1,605 @@
+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
+};
\ No newline at end of file
diff --git a/src/index-core.js b/src/index-core.js
deleted file mode 100644
index 853c4713..00000000
--- a/src/index-core.js
+++ /dev/null
@@ -1,12 +0,0 @@
-'use strict';
-
-const GPUCore = require("./core/gpu-core");
-if (typeof module !== 'undefined') {
- module.exports = GPUCore;
-}
-if (typeof window !== 'undefined') {
- window.GPUCore = GPUCore;
- if (window.GPU === null) {
- window.GPU = GPUCore;
- }
-}
\ No newline at end of file
diff --git a/src/index.d.ts b/src/index.d.ts
new file mode 100644
index 00000000..40d86bd0
--- /dev/null
+++ b/src/index.d.ts
@@ -0,0 +1,685 @@
+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