p5
Version:
[](https://www.npmjs.com/package/p5)
938 lines (937 loc) • 38.4 kB
JavaScript
import { BasePriority, BaseType, DataType, NodeType, OpCode, OpCodeToSymbol, booleanOpCode, typeEquals } from "./strands/ir_types.js";
import { dimensionMismatchError, internalError, userError } from "./strands/strands_FES.js";
import { createNodeData, extractNodeTypeInfo, getNodeDataFromID, getOrCreateNode, propagateTypeToAssignOnUse } from "./strands/ir_dag.js";
import { recordInBasicBlock } from "./strands/ir_cfg.js";
import { strandsBuiltinFunctions } from "./strands/strands_builtins.js";
//#region src/strands/strands_node.js
var StrandsNode = class {
constructor(id, dimension, strandsContext) {
this.id = id;
this.strandsContext = strandsContext;
this.dimension = dimension;
this.structProperties = null;
this._schema = null;
this.isStrandsNode = true;
const dag = this.strandsContext.dag;
const nodeData = getNodeDataFromID(dag, this.id);
if (nodeData && nodeData.identifier) this._originalIdentifier = nodeData.identifier;
if (nodeData) {
this._originalBaseType = nodeData.baseType;
this._originalDimension = nodeData.dimension;
}
}
withStructProperties(properties) {
this.structProperties = properties;
return this;
}
copy() {
return createStrandsNode(this.id, this.dimension, this.strandsContext);
}
typeInfo() {
return {
baseType: this._originalBaseType || BaseType.FLOAT,
dimension: this.dimension
};
}
bridge(value) {
const { dag, cfg } = this.strandsContext;
const baseType = getNodeDataFromID(dag, this.id)?.baseType ?? BaseType.FLOAT;
let newValueID;
if (value?.isStrandsNode) newValueID = value.id;
else newValueID = primitiveConstructorNode(this.strandsContext, {
baseType,
dimension: this.dimension
}, value).id;
if (this._originalIdentifier) {
const valueDim = value?.isStrandsNode ? value.dimension : Array.isArray(value) ? value.length : 1;
if (valueDim !== this._originalDimension && valueDim !== 1) dimensionMismatchError(this._originalDimension, valueDim, this._originalIdentifier);
const { id: targetVarID } = variableNode(this.strandsContext, {
baseType: this._originalBaseType,
dimension: this._originalDimension
}, this._originalIdentifier);
const assignmentNode = createNodeData({
nodeType: NodeType.ASSIGNMENT,
dependsOn: [targetVarID, newValueID],
phiBlocks: []
});
const assignmentID = getOrCreateNode(dag, assignmentNode);
recordInBasicBlock(cfg, cfg.currentBlock, assignmentID);
const variableNodeData = createNodeData({
nodeType: NodeType.VARIABLE,
baseType: this._originalBaseType,
dimension: this._originalDimension,
identifier: this._originalIdentifier
});
const variableID = getOrCreateNode(dag, variableNodeData);
this.id = variableID;
} else this.id = newValueID;
return this;
}
bridgeSwizzle(swizzlePattern, value) {
const { dag, cfg } = this.strandsContext;
const baseType = getNodeDataFromID(dag, this.id)?.baseType ?? BaseType.FLOAT;
let newValueID;
if (value?.isStrandsNode) newValueID = value.id;
else newValueID = primitiveConstructorNode(this.strandsContext, {
baseType,
dimension: this.dimension
}, value).id;
if (this._originalIdentifier) {
const valueDim = value?.isStrandsNode ? value.dimension : Array.isArray(value) ? value.length : 1;
if (valueDim !== swizzlePattern.length && valueDim !== 1) dimensionMismatchError(swizzlePattern.length, valueDim, `${this._originalIdentifier}.${swizzlePattern}`);
const { id: targetVarID } = variableNode(this.strandsContext, {
baseType: this._originalBaseType,
dimension: this._originalDimension
}, this._originalIdentifier);
const swizzleNode = createNodeData({
nodeType: NodeType.OPERATION,
opCode: OpCode.Unary.SWIZZLE,
baseType: this._originalBaseType,
dimension: swizzlePattern.length,
swizzle: swizzlePattern,
dependsOn: [targetVarID]
});
const swizzleID = getOrCreateNode(dag, swizzleNode);
const assignmentNode = createNodeData({
nodeType: NodeType.ASSIGNMENT,
dependsOn: [swizzleID, newValueID],
phiBlocks: []
});
const assignmentID = getOrCreateNode(dag, assignmentNode);
recordInBasicBlock(cfg, cfg.currentBlock, assignmentID);
const variableNodeData = createNodeData({
nodeType: NodeType.VARIABLE,
baseType: this._originalBaseType,
dimension: this._originalDimension,
identifier: this._originalIdentifier
});
const variableID = getOrCreateNode(dag, variableNodeData);
this.id = variableID;
} else this.id = newValueID;
return this;
}
getValue() {
if (this._originalIdentifier) {
const { id, dimension } = variableNode(this.strandsContext, {
baseType: this._originalBaseType,
dimension: this._originalDimension
}, this._originalIdentifier);
return createStrandsNode(id, dimension, this.strandsContext);
}
return this;
}
get(index) {
if (getNodeDataFromID(this.strandsContext.dag, this.id).baseType === "storage" && this._schema) return createStructArrayElementProxy(this.strandsContext, this, index, this._schema);
const { id, dimension } = arrayAccessNode(this.strandsContext, this, index, "read");
return createStrandsNode(id, dimension, this.strandsContext);
}
set(index, value) {
if (getNodeDataFromID(this.strandsContext.dag, this.id).baseType !== "storage") throw new Error("set() can only be used on storage buffers");
if (!this._originalIdentifier) throw new Error("set() can only be used on storage buffers with an identifier");
if (value !== null && typeof value === "object" && !value.isStrandsNode && this._schema) {
const proxy = createStructArrayElementProxy(this.strandsContext, this, index, this._schema);
for (const [fieldName, fieldValue] of Object.entries(value)) proxy[fieldName] = fieldValue;
return this;
}
arrayAssignmentNode(this.strandsContext, this, index, value);
return this;
}
};
function createStrandsNode(id, dimension, strandsContext, onRebind) {
return new Proxy(new StrandsNode(id, dimension, strandsContext), swizzleTrap(id, dimension, strandsContext, onRebind));
}
//#endregion
//#region src/strands/ir_builders.js
function scalarLiteralNode(strandsContext, typeInfo, value) {
const { cfg, dag } = strandsContext;
let { dimension, baseType } = typeInfo;
if (dimension !== 1) internalError("Created a scalar literal node with dimension > 1.");
const nodeData = createNodeData({
nodeType: NodeType.LITERAL,
dimension,
baseType,
value
});
const id = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, id);
return {
id,
dimension
};
}
function variableNode(strandsContext, typeInfo, identifier) {
const { cfg, dag } = strandsContext;
const { dimension, baseType } = typeInfo;
const nodeData = createNodeData({
nodeType: NodeType.VARIABLE,
dimension,
baseType,
identifier
});
const id = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, id);
return {
id,
dimension
};
}
function unaryOpNode(strandsContext, nodeOrValue, opCode) {
const { dag, cfg } = strandsContext;
let dependsOn;
let node;
if (nodeOrValue?.isStrandsNode) node = nodeOrValue;
else {
const { id, dimension } = primitiveConstructorNode(strandsContext, {
baseType: BaseType.FLOAT,
dimension: null
}, nodeOrValue);
node = createStrandsNode(id, dimension, strandsContext);
}
dependsOn = [node.id];
const typeInfo = {
baseType: dag.baseTypes[node.id],
dimension: node.dimension
};
if (booleanOpCode[opCode]) {
typeInfo.baseType = BaseType.BOOL;
typeInfo.dimension = 1;
}
const nodeData = createNodeData({
nodeType: NodeType.OPERATION,
opCode,
dependsOn,
baseType: typeInfo.baseType,
dimension: typeInfo.dimension
});
const id = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, id);
return {
id,
dimension: node.dimension
};
}
function snapshotNode(strandsContext, sourceID) {
const { dag, cfg } = strandsContext;
const { baseType, dimension } = extractNodeTypeInfo(dag, sourceID);
const nodeData = createNodeData({
nodeType: NodeType.OPERATION,
opCode: OpCode.Unary.SNAPSHOT,
dependsOn: [sourceID],
baseType,
dimension
});
const id = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, id);
return {
id,
dimension
};
}
function isMatrixArithmeticOp(opCode) {
return opCode === OpCode.Binary.ADD || opCode === OpCode.Binary.SUBTRACT || opCode === OpCode.Binary.MULTIPLY || opCode === OpCode.Binary.DIVIDE;
}
function resolveMatrixBinaryOpType(leftType, rightType, opCode) {
const leftIsMat = leftType.baseType === BaseType.MAT;
const rightIsMat = rightType.baseType === BaseType.MAT;
const matType = leftIsMat ? leftType : rightType;
const leftIsVector = !leftIsMat && leftType.dimension > 1;
const rightIsVector = !rightIsMat && rightType.dimension > 1;
if (opCode === OpCode.Binary.MULTIPLY) {
if (leftIsMat && rightIsMat) {
if (leftType.dimension !== rightType.dimension) userError("type error", `You can only multiply two matrices of the same size, but got mat${leftType.dimension} * mat${rightType.dimension}.`);
return {
baseType: BaseType.MAT,
dimension: matType.dimension
};
}
if (leftIsMat && rightIsVector || rightIsMat && leftIsVector) {
const vectorType = leftIsMat ? rightType : leftType;
if (vectorType.dimension !== matType.dimension) userError("type error", `A mat${matType.dimension} can only be multiplied with a vector of length ${matType.dimension}, but got a vector of length ${vectorType.dimension}.`);
return {
baseType: BaseType.FLOAT,
dimension: matType.dimension
};
}
return {
baseType: BaseType.MAT,
dimension: matType.dimension
};
}
if (leftIsMat && rightIsMat) {
if (leftType.dimension !== rightType.dimension) userError("type error", `You can only combine two matrices of the same size, but got mat${leftType.dimension} ${OpCodeToSymbol[opCode]} mat${rightType.dimension}.`);
return {
baseType: BaseType.MAT,
dimension: matType.dimension
};
}
if (leftIsMat && !rightIsVector || rightIsMat && !leftIsVector) return {
baseType: BaseType.MAT,
dimension: matType.dimension
};
userError("type error", `A matrix can't be combined with a vector using '${OpCodeToSymbol[opCode]}'. Use matrix multiplication (*) to transform a vector by a matrix.`);
}
function binaryOpNode(strandsContext, leftStrandsNode, rightArg, opCode) {
const { dag, cfg } = strandsContext;
let rightStrandsNode;
if (rightArg[0] instanceof StrandsNode && rightArg.length === 1) rightStrandsNode = rightArg[0];
else {
const { id, dimension } = primitiveConstructorNode(strandsContext, {
baseType: BaseType.FLOAT,
dimension: null
}, rightArg);
rightStrandsNode = createStrandsNode(id, dimension, strandsContext);
}
let finalLeftNodeID = leftStrandsNode.id;
let finalRightNodeID = rightStrandsNode.id;
let leftType = extractNodeTypeInfo(dag, leftStrandsNode.id);
let rightType = extractNodeTypeInfo(dag, rightStrandsNode.id);
if (leftType.baseType === BaseType.ASSIGN_ON_USE && rightType.baseType !== BaseType.ASSIGN_ON_USE) {
propagateTypeToAssignOnUse(dag, leftStrandsNode.id, rightType.baseType, rightType.dimension);
leftType = extractNodeTypeInfo(dag, leftStrandsNode.id);
} else if (rightType.baseType === BaseType.ASSIGN_ON_USE && leftType.baseType !== BaseType.ASSIGN_ON_USE) {
propagateTypeToAssignOnUse(dag, rightStrandsNode.id, leftType.baseType, leftType.dimension);
rightType = extractNodeTypeInfo(dag, rightStrandsNode.id);
}
if ((leftType.baseType === BaseType.MAT || rightType.baseType === BaseType.MAT) && isMatrixArithmeticOp(opCode)) {
const resultType = resolveMatrixBinaryOpType(leftType, rightType, opCode);
const nodeData = createNodeData({
nodeType: NodeType.OPERATION,
opCode,
dependsOn: [finalLeftNodeID, finalRightNodeID],
baseType: resultType.baseType,
dimension: resultType.dimension
});
const id = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, id);
return {
id,
dimension: nodeData.dimension
};
}
const preCastLeftType = { ...leftType };
const preCastRightType = { ...rightType };
const cast = {
node: null,
toType: leftType
};
if (leftType.baseType === rightType.baseType && leftType.baseType === BaseType.DEFER) {
cast.toType.baseType = BaseType.FLOAT;
if (leftType.dimension === rightType.dimension) cast.toType.dimension = leftType.dimension;
else if (leftType.dimension === 1 && rightType.dimension > 1) cast.toType.dimension = rightType.dimension;
else if (rightType.dimension === 1 && leftType.dimension > 1) cast.toType.dimension = leftType.dimension;
else userError("type error", `You have tried to perform a binary operation:\n${leftType.baseType + leftType.dimension} ${OpCodeToSymbol[opCode]} ${rightType.baseType + rightType.dimension}\nIt's only possible to operate on two nodes with the same dimension, or a scalar value and a vector.`);
const l = primitiveConstructorNode(strandsContext, cast.toType, leftStrandsNode);
const r = primitiveConstructorNode(strandsContext, cast.toType, rightStrandsNode);
finalLeftNodeID = l.id;
finalRightNodeID = r.id;
} else if (leftType.baseType !== rightType.baseType || leftType.dimension !== rightType.dimension) {
if (leftType.dimension === 1 && rightType.dimension > 1) {
cast.node = leftStrandsNode;
cast.toType = rightType;
} else if (rightType.dimension === 1 && leftType.dimension > 1) {
cast.node = rightStrandsNode;
cast.toType = leftType;
} else if (leftType.priority > rightType.priority) {
cast.node = rightStrandsNode;
cast.toType = leftType;
} else if (rightType.priority > leftType.priority) {
cast.node = leftStrandsNode;
cast.toType = rightType;
} else userError("type error", `A vector of length ${leftType.dimension} operated with a vector of length ${rightType.dimension} is not allowed.`);
const casted = primitiveConstructorNode(strandsContext, cast.toType, cast.node);
if (cast.node === leftStrandsNode) {
leftStrandsNode = createStrandsNode(casted.id, casted.dimension, strandsContext);
finalLeftNodeID = leftStrandsNode.id;
} else {
rightStrandsNode = createStrandsNode(casted.id, casted.dimension, strandsContext);
finalRightNodeID = rightStrandsNode.id;
}
}
const leftDim = dag.dimensions[finalLeftNodeID];
const rightDim = dag.dimensions[finalRightNodeID];
const leftBase = dag.baseTypes[finalLeftNodeID];
const rightBase = dag.baseTypes[finalRightNodeID];
const displayLeftBase = preCastLeftType.baseType === BaseType.DEFER ? leftBase : preCastLeftType.baseType;
const displayLeftDim = preCastLeftType.baseType === BaseType.DEFER ? leftDim : preCastLeftType.dimension;
const displayRightBase = preCastRightType.baseType === BaseType.DEFER ? rightBase : preCastRightType.baseType;
const displayRightDim = preCastRightType.baseType === BaseType.DEFER ? rightDim : preCastRightType.dimension;
const isOrdering = [
OpCode.Binary.LESS_THAN,
OpCode.Binary.LESS_EQUAL,
OpCode.Binary.GREATER_THAN,
OpCode.Binary.GREATER_EQUAL
].includes(opCode);
const isEquality = opCode === OpCode.Binary.EQUAL || opCode === OpCode.Binary.NOT_EQUAL;
const isLogical = opCode === OpCode.Binary.LOGICAL_AND || opCode === OpCode.Binary.LOGICAL_OR;
if (isOrdering) {
if (leftDim > 1 || rightDim > 1) userError("type error", `${OpCodeToSymbol[opCode]} is only defined for scalars. Got ${displayLeftBase}${displayLeftDim} ${OpCodeToSymbol[opCode]} ${displayRightBase}${displayRightDim}.`);
else if (leftBase === BaseType.BOOL || rightBase === BaseType.BOOL) userError("type error", `${OpCodeToSymbol[opCode]} is not defined for boolean values. Got ${displayLeftBase}${displayLeftDim} ${OpCodeToSymbol[opCode]} ${displayRightBase}${displayRightDim}.`);
} else if (isEquality) {
if ((leftDim > 1 || rightDim > 1) && (leftDim !== rightDim || leftBase !== rightBase)) userError("type error", `Equality comparisons between vectors require matching dimensions and base types. Got ${displayLeftBase}${displayLeftDim} ${OpCodeToSymbol[opCode]} ${displayRightBase}${displayRightDim}.`);
else if (leftBase === BaseType.BOOL !== (rightBase === BaseType.BOOL)) userError("type error", `Equality comparisons between boolean and numeric types are not allowed. Got ${displayLeftBase}${displayLeftDim} ${OpCodeToSymbol[opCode]} ${displayRightBase}${displayRightDim}.`);
} else if (isLogical) {
if (leftBase !== BaseType.BOOL || rightBase !== BaseType.BOOL || leftDim !== 1 || rightDim !== 1) userError("type error", `${OpCodeToSymbol[opCode]} requires two bool scalars. Got ${displayLeftBase}${displayLeftDim} ${OpCodeToSymbol[opCode]} ${displayRightBase}${displayRightDim}.`);
}
if (booleanOpCode[opCode]) {
cast.toType.baseType = BaseType.BOOL;
cast.toType.dimension = 1;
}
const nodeData = createNodeData({
nodeType: NodeType.OPERATION,
opCode,
dependsOn: [finalLeftNodeID, finalRightNodeID],
baseType: cast.toType.baseType,
dimension: cast.toType.dimension
});
const id = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, id);
return {
id,
dimension: nodeData.dimension
};
}
function memberAccessNode(strandsContext, parentNode, componentNode, memberTypeInfo) {
const { dag, cfg } = strandsContext;
const nodeData = createNodeData({
nodeType: NodeType.OPERATION,
opCode: OpCode.Binary.MEMBER_ACCESS,
dimension: memberTypeInfo.dimension,
baseType: memberTypeInfo.baseType,
dependsOn: [parentNode.id, componentNode.id]
});
const id = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, id);
return {
id,
dimension: memberTypeInfo.dimension
};
}
function structInstanceNode(strandsContext, structTypeInfo, identifier, dependsOn) {
const { cfg, dag } = strandsContext;
if (dependsOn.length === 0) for (const prop of structTypeInfo.properties) {
const typeInfo = prop.dataType;
const nodeData = createNodeData({
nodeType: NodeType.VARIABLE,
baseType: typeInfo.baseType,
dimension: typeInfo.dimension,
identifier: `${identifier}.${prop.name}`
});
const componentID = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, componentID);
dependsOn.push(componentID);
}
const nodeData = createNodeData({
nodeType: NodeType.VARIABLE,
dimension: structTypeInfo.properties.length,
baseType: structTypeInfo.typeName,
identifier,
dependsOn
});
const structID = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, structID);
return {
id: structID,
dimension: 0,
components: dependsOn
};
}
function mapPrimitiveDepsToIDs(strandsContext, typeInfo, dependsOn) {
const inputs = Array.isArray(dependsOn) ? dependsOn : [dependsOn];
const mappedDependencies = [];
let { dimension, baseType } = typeInfo;
const dag = strandsContext.dag;
let calculatedDimensions = 0;
let originalNodeID = null;
for (const dep of inputs.flat(Infinity)) if (dep && dep.isStrandsNode) {
const node = getNodeDataFromID(dag, dep.id);
originalNodeID = dep.id;
baseType = node.baseType;
if (node.opCode === OpCode.Nary.CONSTRUCTOR) for (const inner of node.dependsOn) mappedDependencies.push(inner);
else mappedDependencies.push(dep.id);
calculatedDimensions += node.dimension;
continue;
} else if (typeof dep === "number") {
const { id, dimension } = scalarLiteralNode(strandsContext, {
dimension: 1,
baseType
}, dep);
mappedDependencies.push(id);
calculatedDimensions += dimension;
continue;
} else if (typeof dep === "boolean") {
const { id, dimension } = scalarLiteralNode(strandsContext, {
dimension: 1,
baseType: BaseType.BOOL
}, dep);
mappedDependencies.push(id);
calculatedDimensions += dimension;
if (baseType !== BaseType.BOOL) baseType = BaseType.BOOL;
continue;
} else userError("type error", `You've tried to construct a scalar or vector type with a non-numeric value: ${dep}`);
if (dimension === null) dimension = calculatedDimensions;
else if (dimension > calculatedDimensions && calculatedDimensions === 1) calculatedDimensions = dimension;
else if (calculatedDimensions !== 1 && calculatedDimensions !== dimension) userError("type error", `You've tried to construct a ${baseType + dimension} with ${calculatedDimensions} components`);
const inferredTypeInfo = {
dimension,
baseType,
priority: BasePriority[baseType]
};
return {
originalNodeID,
mappedDependencies,
inferredTypeInfo
};
}
function constructTypeFromIDs(strandsContext, typeInfo, strandsNodesArray) {
const nodeData = createNodeData({
nodeType: NodeType.OPERATION,
opCode: OpCode.Nary.CONSTRUCTOR,
dimension: typeInfo.dimension,
baseType: typeInfo.baseType,
dependsOn: strandsNodesArray
});
return getOrCreateNode(strandsContext.dag, nodeData);
}
function matrixConstructorNode(strandsContext, dimension, values) {
const { cfg } = strandsContext;
const componentIDs = values.map((value) => {
if (value?.isStrandsNode) return value.id;
const { id } = scalarLiteralNode(strandsContext, {
dimension: 1,
baseType: BaseType.FLOAT
}, value);
return id;
});
const id = constructTypeFromIDs(strandsContext, {
baseType: BaseType.MAT,
dimension
}, componentIDs);
recordInBasicBlock(cfg, cfg.currentBlock, id);
return {
id,
dimension
};
}
function diagonalMatrixNode(strandsContext, dimension, value) {
const values = [];
for (let col = 0; col < dimension; col++) for (let row = 0; row < dimension; row++) values.push(row === col ? value : 0);
return matrixConstructorNode(strandsContext, dimension, values);
}
function identityMatrixNode(strandsContext, dimension) {
return diagonalMatrixNode(strandsContext, dimension, 1);
}
function matrixResizeNode(strandsContext, srcNode, srcDim, dstDim) {
const { dag, cfg } = strandsContext;
const sourceColumn = (colIndex) => {
const { id: indexID } = scalarLiteralNode(strandsContext, {
dimension: 1,
baseType: BaseType.INT
}, colIndex);
const nodeData = createNodeData({
nodeType: NodeType.OPERATION,
opCode: OpCode.Binary.ARRAY_ACCESS,
dependsOn: [srcNode.id, indexID],
dimension: srcDim,
baseType: BaseType.FLOAT
});
const id = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, id);
return createStrandsNode(id, srcDim, strandsContext);
};
const columns = [];
for (let col = 0; col < dstDim; col++) if (col < srcDim && dstDim < srcDim) {
const { id, dimension } = swizzleNode(strandsContext, sourceColumn(col), "xyzw".slice(0, dstDim));
columns.push(createStrandsNode(id, dimension, strandsContext));
} else if (col < srcDim) {
const pad = Array(dstDim - srcDim).fill(0);
const { id, dimension } = primitiveConstructorNode(strandsContext, {
baseType: BaseType.FLOAT,
dimension: dstDim
}, [sourceColumn(col), ...pad]);
columns.push(createStrandsNode(id, dimension, strandsContext));
} else {
const comps = Array.from({ length: dstDim }, (_, row) => row === col ? 1 : 0);
const { id, dimension } = primitiveConstructorNode(strandsContext, {
baseType: BaseType.FLOAT,
dimension: dstDim
}, comps);
columns.push(createStrandsNode(id, dimension, strandsContext));
}
return matrixConstructorNode(strandsContext, dstDim, columns);
}
function matrixNode(strandsContext, dimension, args) {
const dag = strandsContext.dag;
const componentCount = dimension * dimension;
const baseTypeOf = (a) => extractNodeTypeInfo(dag, a.id).baseType;
if (args.length === 0) return identityMatrixNode(strandsContext, dimension);
if (args.length === 1) {
const arg = args[0];
const isNode = !!arg?.isStrandsNode;
if (isNode && baseTypeOf(arg) === BaseType.MAT && arg.dimension === dimension) return {
id: arg.id,
dimension
};
if (isNode && baseTypeOf(arg) === BaseType.MAT) return matrixResizeNode(strandsContext, arg, arg.dimension, dimension);
if (typeof arg === "number" || isNode && arg.dimension === 1 && baseTypeOf(arg) !== BaseType.MAT) return diagonalMatrixNode(strandsContext, dimension, arg);
}
if (args.length === dimension && args.every((a) => a?.isStrandsNode && a.dimension === dimension && baseTypeOf(a) !== BaseType.MAT)) return matrixConstructorNode(strandsContext, dimension, args);
if (args.length === componentCount) return matrixConstructorNode(strandsContext, dimension, args);
userError("parameter validation", `A mat${dimension} constructor expects no arguments (identity), a single number (diagonal), a single mat${dimension}, ${dimension} column vectors, or ${componentCount} values — but got ${args.length} argument(s).`);
}
function primitiveConstructorNode(strandsContext, typeInfo, dependsOn) {
const cfg = strandsContext.cfg;
dependsOn = (Array.isArray(dependsOn) ? dependsOn : [dependsOn]).flat(Infinity).map((a) => {
if (a.isStrandsNode && a.typeInfo().baseType === BaseType.INT && a.typeInfo().dimension === 1) return castToFloat(strandsContext, a);
else return a;
});
const { mappedDependencies, inferredTypeInfo } = mapPrimitiveDepsToIDs(strandsContext, typeInfo, dependsOn);
const finalType = {
baseType: inferredTypeInfo.baseType === BaseType.BOOL ? BaseType.BOOL : typeInfo.baseType,
dimension: inferredTypeInfo.dimension
};
const id = constructTypeFromIDs(strandsContext, finalType, mappedDependencies);
if (typeInfo.baseType !== BaseType.DEFER) recordInBasicBlock(cfg, cfg.currentBlock, id);
return {
id,
dimension: finalType.dimension,
components: mappedDependencies
};
}
function castToFloat(strandsContext, dep) {
const { id, dimension } = functionCallNode(strandsContext, strandsContext.backend.getTypeName("float", dep.typeInfo().dimension), [dep], { overloads: [{
params: [dep.typeInfo()],
returnType: {
...dep.typeInfo(),
baseType: BaseType.FLOAT
}
}] });
return createStrandsNode(id, dimension, strandsContext);
}
function structConstructorNode(strandsContext, structTypeInfo, dependsOn) {
const { cfg, dag } = strandsContext;
const { properties } = structTypeInfo;
if (dependsOn.length !== properties.length) userError("type error", `You've tried to construct a ${structTypeInfo.typeName} struct with ${dependsOn.length} properties, but it expects ${properties.length} properties.\nThe properties it expects are:\n${properties.map((prop) => `${prop.name}: ${prop.dataType.baseType}${prop.dataType.dimension}`).join(", ")}`);
const nodeData = createNodeData({
nodeType: NodeType.OPERATION,
opCode: OpCode.Nary.CONSTRUCTOR,
dimension: properties.length,
baseType: structTypeInfo.typeName,
dependsOn
});
const id = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, id);
return {
id,
dimension: properties.length,
components: structTypeInfo.components
};
}
function functionCallNode(strandsContext, functionName, rawUserArgs, { overloads: rawOverloads } = {}) {
const { cfg, dag } = strandsContext;
const overloads = rawOverloads || strandsBuiltinFunctions[functionName];
const preprocessedArgs = rawUserArgs.map((rawUserArg) => mapPrimitiveDepsToIDs(strandsContext, DataType.defer, rawUserArg));
const matchingArgsCounts = overloads.filter((overload) => overload.params.length === preprocessedArgs.length);
if (matchingArgsCounts.length === 0) {
const argsLengthSet = /* @__PURE__ */ new Set();
const argsLengthArr = [];
overloads.forEach((overload) => argsLengthSet.add(overload.params.length));
argsLengthSet.forEach((len) => argsLengthArr.push(`${len}`));
const argsLengthStr = argsLengthArr.join(", or ");
userError("parameter validation error", `Function '${functionName}' has ${overloads.length} variants which expect ${argsLengthStr} arguments, but ${preprocessedArgs.length} arguments were provided.`);
}
const isGeneric = (T) => T.dimension === null;
let bestOverload = null;
let bestScore = 0;
let inferredReturnType = null;
let inferredDimension = null;
for (const overload of matchingArgsCounts) {
let isValid = true;
let similarity = 0;
for (let i = 0; i < preprocessedArgs.length; i++) {
const argType = preprocessedArgs[i].inferredTypeInfo;
const expectedType = overload.params[i];
let dimension = expectedType.dimension;
if (isGeneric(expectedType)) {
if (inferredDimension === null || inferredDimension === 1) inferredDimension = argType.dimension;
if (inferredDimension !== argType.dimension && !(argType.dimension === 1 && inferredDimension >= 1)) isValid = false;
dimension = inferredDimension;
} else if (argType.dimension > dimension) isValid = false;
if (argType.baseType === expectedType.baseType) similarity += 2;
else if (expectedType.priority > argType.priority) similarity += 1;
}
if (isValid && (!bestOverload || similarity > bestScore)) {
bestOverload = overload;
bestScore = similarity;
inferredReturnType = { ...overload.returnType };
if (isGeneric(inferredReturnType)) inferredReturnType.dimension = inferredDimension;
}
}
if (bestOverload === null) userError("parameter validation", `No matching overload for ${functionName} was found!`);
let dependsOn = [];
for (let i = 0; i < bestOverload.params.length; i++) {
const arg = preprocessedArgs[i];
const paramType = { ...bestOverload.params[i] };
if (isGeneric(paramType)) paramType.dimension = inferredDimension;
if (arg.originalNodeID && typeEquals(arg.inferredTypeInfo, paramType)) dependsOn.push(arg.originalNodeID);
else {
const castedArgID = constructTypeFromIDs(strandsContext, paramType, arg.mappedDependencies);
recordInBasicBlock(cfg, cfg.currentBlock, castedArgID);
dependsOn.push(castedArgID);
}
}
const nodeData = createNodeData({
nodeType: NodeType.OPERATION,
opCode: OpCode.Nary.FUNCTION_CALL,
identifier: functionName,
dependsOn,
baseType: inferredReturnType.baseType,
dimension: inferredReturnType.dimension
});
const id = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, id);
return {
id,
dimension: inferredReturnType.dimension
};
}
function statementNode(strandsContext, statementType) {
const { dag, cfg } = strandsContext;
const nodeData = createNodeData({
nodeType: NodeType.STATEMENT,
statementType
});
const id = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, id);
return id;
}
function swizzleNode(strandsContext, parentNode, swizzle) {
const { dag, cfg } = strandsContext;
const baseType = dag.baseTypes[parentNode.id];
const nodeData = createNodeData({
nodeType: NodeType.OPERATION,
baseType,
dimension: swizzle.length,
opCode: OpCode.Unary.SWIZZLE,
dependsOn: [parentNode.id],
swizzle
});
const id = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, id);
return {
id,
dimension: swizzle.length
};
}
function swizzleTrap(id, dimension, strandsContext, onRebind) {
const swizzleSets = [
[
"x",
"y",
"z",
"w"
],
[
"r",
"g",
"b",
"a"
],
[
"s",
"t",
"p",
"q"
]
].map((s) => s.slice(0, dimension));
return {
get(target, property, receiver) {
if (property in target) return Reflect.get(...arguments);
else for (const set of swizzleSets) if ([...property.toString()].every((char) => set.includes(char))) {
const node = swizzleNode(strandsContext, target, [...property].map((char) => {
const index = set.indexOf(char);
return swizzleSets[0][index];
}).join(""));
return createStrandsNode(node.id, node.dimension, strandsContext);
}
},
set(target, property, value, receiver) {
for (const swizzleSet of swizzleSets) {
const chars = [...property];
if (!(chars.every((c) => swizzleSet.includes(c)) && new Set(chars).size === chars.length && target.dimension >= chars.length)) continue;
const dim = target.dimension;
const lanes = new Array(dim);
for (let i = 0; i < dim; i++) {
const { id, dimension } = swizzleNode(strandsContext, target, "xyzw"[i]);
lanes[i] = createStrandsNode(id, dimension, strandsContext);
}
let scalars = [];
if (value?.isStrandsNode) {
if (value.dimension === 1) scalars = Array(chars.length).fill(value);
else if (value.dimension === chars.length) for (let k = 0; k < chars.length; k++) {
const { id, dimension } = swizzleNode(strandsContext, value, "xyzw"[k]);
scalars.push(createStrandsNode(id, dimension, strandsContext));
}
else dimensionMismatchError(chars.length, value.dimension, `${target._originalIdentifier || "value"}.${property}`);
} else if (Array.isArray(value)) {
const flat = value.flat(Infinity);
if (flat.length === 1) scalars = Array(chars.length).fill(flat[0]);
else if (flat.length === chars.length) scalars = flat;
else userError("type error", `Swizzle assignment: RHS length ${flat.length} does not match ${chars.length}.`);
} else if (typeof value === "number") scalars = Array(chars.length).fill(value);
else userError("type error", `Unsupported RHS for swizzle assignment: ${value}`);
for (let j = 0; j < chars.length; j++) {
const canonicalIndex = swizzleSet.indexOf(chars[j]);
lanes[canonicalIndex] = scalars[j];
}
const { id: newID } = primitiveConstructorNode(strandsContext, {
baseType: getNodeDataFromID(strandsContext.dag, target.id)?.baseType ?? BaseType.FLOAT,
dimension: dim
}, lanes);
target.id = newID;
if (typeof onRebind === "function") onRebind(newID);
return true;
}
return Reflect.set(...arguments);
}
};
}
function arrayAccessNode(strandsContext, bufferNode, indexNode, accessMode) {
const { dag, cfg } = strandsContext;
let index;
if (indexNode instanceof StrandsNode) index = indexNode;
else {
const { id, dimension } = primitiveConstructorNode(strandsContext, {
baseType: BaseType.INT,
dimension: 1
}, indexNode);
index = createStrandsNode(id, dimension, strandsContext);
}
const nodeData = createNodeData({
nodeType: NodeType.OPERATION,
opCode: OpCode.Binary.ARRAY_ACCESS,
dependsOn: [bufferNode.id, index.id],
dimension: 1,
baseType: BaseType.FLOAT,
accessMode
});
const id = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, id);
return {
id,
dimension: 1
};
}
function createStructArrayElementProxy(strandsContext, bufferNode, indexNode, schema) {
const { dag, cfg } = strandsContext;
let index;
if (indexNode instanceof StrandsNode) index = indexNode;
else {
const { id, dimension } = primitiveConstructorNode(strandsContext, {
baseType: BaseType.INT,
dimension: 1
}, indexNode);
index = createStrandsNode(id, dimension, strandsContext);
}
const proxy = {};
for (const field of schema.fields) Object.defineProperty(proxy, field.name, {
get() {
const nodeData = createNodeData({
nodeType: NodeType.OPERATION,
opCode: OpCode.Binary.ARRAY_ACCESS,
dependsOn: [bufferNode.id, index.id],
dimension: field.dim,
baseType: BaseType.FLOAT,
identifier: field.name
});
const id = getOrCreateNode(dag, nodeData);
recordInBasicBlock(cfg, cfg.currentBlock, id);
const onRebind = (newFieldID) => {
const accessData = createNodeData({
nodeType: NodeType.OPERATION,
opCode: OpCode.Binary.ARRAY_ACCESS,
dependsOn: [bufferNode.id, index.id],
dimension: field.dim,
baseType: BaseType.FLOAT,
identifier: field.name
});
const accessID = getOrCreateNode(dag, accessData);
const assignData = createNodeData({
nodeType: NodeType.ASSIGNMENT,
dependsOn: [accessID, newFieldID],
phiBlocks: []
});
const assignID = getOrCreateNode(dag, assignData);
recordInBasicBlock(cfg, cfg.currentBlock, assignID);
};
return createStrandsNode(id, field.dim, strandsContext, onRebind);
},
set(val) {
const accessData = createNodeData({
nodeType: NodeType.OPERATION,
opCode: OpCode.Binary.ARRAY_ACCESS,
dependsOn: [bufferNode.id, index.id],
dimension: field.dim,
baseType: BaseType.FLOAT,
identifier: field.name
});
const accessID = getOrCreateNode(dag, accessData);
let valueID;
if (val?.isStrandsNode) valueID = val.id;
else {
const { id } = primitiveConstructorNode(strandsContext, {
baseType: BaseType.FLOAT,
dimension: field.dim
}, val);
valueID = id;
}
const assignData = createNodeData({
nodeType: NodeType.ASSIGNMENT,
dependsOn: [accessID, valueID],
phiBlocks: []
});
const assignID = getOrCreateNode(dag, assignData);
recordInBasicBlock(cfg, cfg.currentBlock, assignID);
},
configurable: true
});
return proxy;
}
function arrayAssignmentNode(strandsContext, bufferNode, indexNode, valueNode) {
const { dag, cfg } = strandsContext;
let index;
if (indexNode instanceof StrandsNode) index = indexNode;
else {
const { id, dimension } = primitiveConstructorNode(strandsContext, {
baseType: BaseType.INT,
dimension: 1
}, indexNode);
index = createStrandsNode(id, dimension, strandsContext);
}
let value;
if (valueNode instanceof StrandsNode) value = valueNode.typeInfo().baseType !== BaseType.FLOAT ? castToFloat(strandsContext, valueNode) : valueNode;
else {
const { id, dimension } = primitiveConstructorNode(strandsContext, {
baseType: BaseType.FLOAT,
dimension: 1
}, valueNode);
value = createStrandsNode(id, dimension, strandsContext);
}
const arrayAccessData = createNodeData({
nodeType: NodeType.OPERATION,
opCode: OpCode.Binary.ARRAY_ACCESS,
dependsOn: [bufferNode.id, index.id],
dimension: 1,
baseType: BaseType.FLOAT
});
const arrayAccessID = getOrCreateNode(dag, arrayAccessData);
const assignmentData = createNodeData({
nodeType: NodeType.ASSIGNMENT,
dependsOn: [arrayAccessID, value.id],
phiBlocks: []
});
const assignmentID = getOrCreateNode(dag, assignmentData);
recordInBasicBlock(cfg, cfg.currentBlock, assignmentID);
return { id: assignmentID };
}
//#endregion
export { variableNode as C, unaryOpNode as S, createStrandsNode as T, statementNode as _, constructTypeFromIDs as a, swizzleNode as b, functionCallNode as c, matrixNode as d, matrixResizeNode as f, snapshotNode as g, scalarLiteralNode as h, castToFloat as i, identityMatrixNode as l, primitiveConstructorNode as m, arrayAssignmentNode as n, createStructArrayElementProxy as o, memberAccessNode as p, binaryOpNode as r, diagonalMatrixNode as s, arrayAccessNode as t, matrixConstructorNode as u, structConstructorNode as v, StrandsNode as w, swizzleTrap as x, structInstanceNode as y };