p5
Version:
[](https://www.npmjs.com/package/p5)
1,887 lines • 175 kB
JavaScript
"use strict";(function(){var e=Object.defineProperty,t=/* @__PURE__ */ ((t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r})({ADD:()=>Be,ALT:()=>`Alt`,ARROW:()=>c,AUTO:()=>Ee,AXES:()=>It,BACKSPACE:()=>De,BASELINE:()=>me,BEVEL:()=>we,BEZIER:()=>_t,BLEND:()=>Re,BLUR:()=>at,BOLD:()=>ct,BOLDITALIC:()=>lt,BOTTOM:()=>pe,BURN:()=>Ze,CENTER:()=>fe,CHAR:()=>ut,CHORD:()=>be,CLAMP:()=>Dt,CLOSE:()=>ve,CONTAIN:()=>zt,CONTROL:()=>Oe,CORNER:()=>se,CORNERS:()=>ce,COVER:()=>Bt,CROSS:()=>d,CURVE:()=>vt,DARKEST:()=>Ve,DEG_TO_RAD:()=>ae,DELETE:()=>ke,DIFFERENCE:()=>Ue,DILATE:()=>rt,DODGE:()=>Xe,DOWN_ARROW:()=>Ae,EMPTY_PATH:()=>7,ENTER:()=>je,ERODE:()=>it,ESCAPE:()=>Me,EXCLUDE:()=>Wt,EXCLUSION:()=>g,FALLBACK:()=>Rt,FILL:()=>bt,FLAT:()=>Ot,FLOAT:()=>x,FULL:()=>u,GRAY:()=>$e,GRID:()=>Ft,HALF_FLOAT:()=>Ht,HALF_PI:()=>ee,HAND:()=>f,HARD_LIGHT:()=>Je,IMAGE:()=>Ct,IMMEDIATE:()=>St,INCLUDE:()=>Ut,INVERT:()=>tt,ITALIC:()=>st,JOIN:()=>Gt,KEEP_CONNECTIONS:()=>y,LABEL:()=>Lt,LANDSCAPE:()=>jt,LEFT:()=>de,LEFT_ARROW:()=>Ne,LIGHTEST:()=>He,LINEAR:()=>ht,LINEAR_MIPMAP:()=>wt,LINES:()=>1,LINE_LOOP:()=>2,LINE_STRIP:()=>3,MIRROR:()=>v,MITER:()=>Te,MOVE:()=>p,MULTIPLY:()=>Ge,NEAREST:()=>Tt,NORMAL:()=>ot,OPAQUE:()=>et,OPEN:()=>ye,OPTION:()=>`Alt`,OVERLAY:()=>qe,P2D:()=>`p2d`,P2DP3:()=>i,PATH:()=>8,PI:()=>te,PIE:()=>`pie`,POINTS:()=>0,PORTRAIT:()=>Mt,POSTERIZE:()=>nt,PROJECT:()=>xe,QUADRATIC:()=>gt,QUADS:()=>he,QUAD_STRIP:()=>ge,QUARTER_PI:()=>ne,RADIUS:()=>le,RAD_TO_DEG:()=>oe,REMOVE:()=>ze,REPEAT:()=>Et,REPLACE:()=>Ke,RETURN:()=>Pe,RIGHT:()=>ue,RIGHT_ARROW:()=>Fe,ROUND:()=>Ce,SCREEN:()=>_,SEGMENTED:()=>At,SHIFT:()=>Ie,SIMPLE:()=>l,SMOOTH:()=>kt,SOFT_LIGHT:()=>Ye,SQUARE:()=>Se,STROKE:()=>yt,SUBTRACT:()=>We,TAB:()=>`Tab`,TAU:()=>re,TESS:()=>_e,TEXT:()=>m,TEXTURE:()=>xt,THRESHOLD:()=>Qe,TOP:()=>`top`,TRIANGLES:()=>4,TRIANGLE_FAN:()=>6,TRIANGLE_STRIP:()=>5,TWO_PI:()=>ie,UNSIGNED_BYTE:()=>b,UNSIGNED_INT:()=>Vt,UP_ARROW:()=>Le,VERSION:()=>r,WAIT:()=>h,WEBGL:()=>a,WEBGL2:()=>o,WEBGPU:()=>s,WORD:()=>dt,_CTX_MIDDLE:()=>mt,_DEFAULT_FILL:()=>Pt,_DEFAULT_LEADMULT:()=>pt,_DEFAULT_STROKE:()=>Nt,_DEFAULT_TEXT_FILL:()=>ft});let n=Math.PI,r=`2.4.0`,i=`p2d-p3`,a=`webgl`,o=`webgl2`,s=`webgpu`,c=`default`,l=`simple`,u=`full`,d=`crosshair`,f=`pointer`,p=`move`,m=`text`,h=`wait`,ee=n/2,te=n,ne=n/4,re=n*2,ie=n*2,ae=n/180,oe=180/n,se=`corner`,ce=`corners`,le=`radius`,ue=`right`,de=`left`,fe=`center`,pe=`bottom`,me=`alphabetic`,he=`quads`,ge=`quad_strip`,_e=`tess`,ve=`close`,ye=`open`,be=`chord`,xe=`square`,Se=`butt`,Ce=`round`,we=`bevel`,Te=`miter`,Ee=`auto`,De=`Backspace`,Oe=`Control`,ke=`Delete`,Ae=`ArrowDown`,je=`Enter`,Me=`Escape`,Ne=`ArrowLeft`,Pe=`Enter`,Fe=`ArrowRight`,Ie=`Shift`,Le=`ArrowUp`,Re=`source-over`,ze=`destination-out`,Be=`lighter`,Ve=`darken`,He=`lighten`,Ue=`difference`,We=`subtract`,g=`exclusion`,Ge=`multiply`,_=`screen`,Ke=`copy`,qe=`overlay`,Je=`hard-light`,Ye=`soft-light`,Xe=`color-dodge`,Ze=`color-burn`,Qe=`threshold`,$e=`gray`,et=`opaque`,tt=`invert`,nt=`posterize`,rt=`dilate`,it=`erode`,at=`blur`,ot=`normal`,st=`italic`,ct=`bold`,lt=`bold italic`,ut=`CHAR`,dt=`WORD`,ft=`#000000`,pt=1.25,mt=`middle`,ht=`linear`,gt=`quadratic`,_t=`bezier`,vt=`curve`,yt=`stroke`,bt=`fill`,xt=`texture`,St=`immediate`,Ct=`image`,wt=`linear_mipmap`,Tt=`nearest`,Et=`repeat`,Dt=`clamp`,v=`mirror`,y=`keep_connections`,Ot=y,kt=`smooth`,At=`segmented`,jt=`landscape`,Mt=`portrait`,Nt=`#000000`,Pt=`#FFFFFF`,Ft=`grid`,It=`axes`,Lt=`label`,Rt=`fallback`,zt=`contain`,Bt=`cover`,b=`unsigned-byte`,Vt=`unsigned-int`,x=`float`,Ht=`half-float`,Ut=Symbol(`include`),Wt=Symbol(`exclude`),Gt=Symbol(`join`);function Kt(e){let n={},r={},i=``,a=function(r,a){i+=e(`STROKE_CAP_${r}`,`${a}`,`u32`),n[t[r]]=a},o=function(n,a){i+=e(`STROKE_JOIN_${n}`,`${a}`,`u32`),r[t[n]]=a};return a(`ROUND`,0),a(`PROJECT`,1),a(`SQUARE`,2),o(`ROUND`,0),o(`MITER`,1),o(`BEVEL`,2),{STROKE_CAP_ENUM:n,STROKE_JOIN_ENUM:r,lineDefs:i}}let S={OPERATION:`operation`,LITERAL:`literal`,VARIABLE:`variable`,CONSTANT:`constant`,STRUCT:`struct`,PHI:`phi`,STATEMENT:`statement`,ASSIGNMENT:`assignment`},C=`_p5_instanceID`,qt=`_p5_param_`,w=Object.fromEntries(Object.entries(S).map(([e,t])=>[t,e])),Jt={[S.OPERATION]:[`opCode`,`dependsOn`,`dimension`,`baseType`],[S.LITERAL]:[`value`,`dimension`,`baseType`],[S.VARIABLE]:[`identifier`,`dimension`,`baseType`],[S.CONSTANT]:[`value`,`dimension`,`baseType`],[S.STRUCT]:[``],[S.PHI]:[`dependsOn`,`phiBlocks`,`dimension`,`baseType`],[S.STATEMENT]:[`statementType`],[S.ASSIGNMENT]:[`dependsOn`]},T={DISCARD:`discard`,BREAK:`break`,EARLY_RETURN:`early_return`,EXPRESSION:`expression`,EMPTY:`empty`},E={FLOAT:`float`,INT:`int`,BOOL:`bool`,MAT:`mat`,DEFER:`defer`,ASSIGN_ON_USE:`assign_on_use`,SAMPLER2D:`sampler2D`,SAMPLER:`sampler`},Yt={[E.FLOAT]:3,[E.INT]:2,[E.BOOL]:1,[E.MAT]:0,[E.DEFER]:-1,[E.ASSIGN_ON_USE]:-2,[E.SAMPLER2D]:-10,[E.SAMPLER]:-11},D={float1:{fnName:`float`,baseType:E.FLOAT,dimension:1,priority:3},float2:{fnName:`vec2`,baseType:E.FLOAT,dimension:2,priority:3},float3:{fnName:`vec3`,baseType:E.FLOAT,dimension:3,priority:3},float4:{fnName:`vec4`,baseType:E.FLOAT,dimension:4,priority:3},int1:{fnName:`int`,baseType:E.INT,dimension:1,priority:2},int2:{fnName:`ivec2`,baseType:E.INT,dimension:2,priority:2},int3:{fnName:`ivec3`,baseType:E.INT,dimension:3,priority:2},int4:{fnName:`ivec4`,baseType:E.INT,dimension:4,priority:2},bool1:{fnName:`bool`,baseType:E.BOOL,dimension:1,priority:1},bool2:{fnName:`bvec2`,baseType:E.BOOL,dimension:2,priority:1},bool3:{fnName:`bvec3`,baseType:E.BOOL,dimension:3,priority:1},bool4:{fnName:`bvec4`,baseType:E.BOOL,dimension:4,priority:1},mat2:{fnName:`mat2x2`,baseType:E.MAT,dimension:2,priority:0},mat3:{fnName:`mat3x3`,baseType:E.MAT,dimension:3,priority:0},mat4:{fnName:`mat4x4`,baseType:E.MAT,dimension:4,priority:0},defer:{fnName:null,baseType:E.DEFER,dimension:null,priority:-1},assign_on_use:{fnName:null,baseType:E.ASSIGN_ON_USE,dimension:null,priority:-2},sampler2D:{fnName:`sampler2D`,baseType:E.SAMPLER2D,dimension:1,priority:-10},sampler:{fnName:`sampler`,baseType:E.SAMPLER,dimension:1,priority:-11}};function Xt(e){return!!(e&&e.properties)}let O={FLOAT:{baseType:E.FLOAT,dimension:null,priority:3},INT:{baseType:E.INT,dimension:null,priority:2},BOOL:{baseType:E.BOOL,dimension:null,priority:1}};function Zt(e,t){return e.dimension===t.dimension&&e.baseType===t.baseType}Object.fromEntries(Object.values(D).filter(e=>e.fnName!==null).map(e=>[e.fnName,e]));let k={Binary:{ADD:0,SUBTRACT:1,MULTIPLY:2,DIVIDE:3,MODULO:4,EQUAL:5,NOT_EQUAL:6,GREATER_THAN:7,GREATER_EQUAL:8,LESS_THAN:9,LESS_EQUAL:10,LOGICAL_AND:11,LOGICAL_OR:12,MEMBER_ACCESS:13,ARRAY_ACCESS:14},Unary:{LOGICAL_NOT:100,NEGATE:101,PLUS:102,SWIZZLE:103,SNAPSHOT:104},Nary:{FUNCTION_CALL:200,CONSTRUCTOR:201,TERNARY:202,ARRAY_ASSIGNMENT:203},ControlFlow:{RETURN:300,JUMP:301,BRANCH_IF_FALSE:302,DISCARD:303,BREAK:304}},Qt=[{arity:`unary`,boolean:!0,name:`not`,symbol:`!`,opCode:k.Unary.LOGICAL_NOT},{arity:`unary`,name:`neg`,symbol:`-`,opCode:k.Unary.NEGATE},{arity:`unary`,name:`plus`,symbol:`+`,opCode:k.Unary.PLUS},{arity:`binary`,name:`add`,symbol:`+`,opCode:k.Binary.ADD},{arity:`binary`,name:`sub`,symbol:`-`,opCode:k.Binary.SUBTRACT},{arity:`binary`,name:`mult`,symbol:`*`,opCode:k.Binary.MULTIPLY},{arity:`binary`,name:`div`,symbol:`/`,opCode:k.Binary.DIVIDE},{arity:`binary`,name:`mod`,symbol:`%`,opCode:k.Binary.MODULO},{arity:`binary`,boolean:!0,name:`equalTo`,symbol:`==`,opCode:k.Binary.EQUAL},{arity:`binary`,boolean:!0,name:`notEqual`,symbol:`!=`,opCode:k.Binary.NOT_EQUAL},{arity:`binary`,boolean:!0,name:`greaterThan`,symbol:`>`,opCode:k.Binary.GREATER_THAN},{arity:`binary`,boolean:!0,name:`greaterEqual`,symbol:`>=`,opCode:k.Binary.GREATER_EQUAL},{arity:`binary`,boolean:!0,name:`lessThan`,symbol:`<`,opCode:k.Binary.LESS_THAN},{arity:`binary`,boolean:!0,name:`lessEqual`,symbol:`<=`,opCode:k.Binary.LESS_EQUAL},{arity:`binary`,boolean:!0,name:`and`,symbol:`&&`,opCode:k.Binary.LOGICAL_AND},{arity:`binary`,boolean:!0,name:`or`,symbol:`||`,opCode:k.Binary.LOGICAL_OR}];k.Binary.ADD,k.Binary.SUBTRACT,k.Binary.MULTIPLY,k.Binary.DIVIDE,k.Binary.MODULO,k.Binary.EQUAL,k.Binary.NOT_EQUAL,k.Binary.GREATER_THAN,k.Binary.GREATER_EQUAL,k.Binary.LESS_THAN,k.Binary.LESS_EQUAL,k.Binary.LOGICAL_AND,k.Binary.LOGICAL_OR;let A={},$t={},en={},tn={};for(let{symbol:e,opCode:t,name:n,arity:r,boolean:i}of Qt)A[t]=e,r===`unary`&&($t[e]=n),r===`binary`&&(en[e]=n),i&&(tn[t]=!0);let j={GLOBAL:`global`,FUNCTION:`function`,BRANCH:`branch`,IF_COND:`if_cond`,IF_BODY:`if_body`,ELSE_COND:`else_cond`,SCOPE_START:`scope_start`,SCOPE_END:`scope_end`,FOR:`for`,MERGE:`merge`,DEFAULT:`default`};Object.fromEntries(Object.entries(j).map(([e,t])=>[t,e]));let nn=`
// Group 0: Material Properties
struct MaterialUniforms {
uUseVertexColor: u32,
}
// Group 1: Model Transform
struct ModelUniforms {
// @p5 ifdef Vertex getWorldInputs
uModelMatrix: mat4x4<f32>,
uModelNormalMatrix: mat3x3<f32>,
// @p5 endif
// @p5 ifndef Vertex getWorldInputs
uModelViewMatrix: mat4x4<f32>,
uNormalMatrix: mat3x3<f32>,
// @p5 endif
uMaterialColor: vec4<f32>,
}
// Group 2: Camera and Projection
struct CameraUniforms {
uProjectionMatrix: mat4x4<f32>,
// @p5 ifdef Vertex getWorldInputs
uViewMatrix: mat4x4<f32>,
// @p5 endif
uCameraNormalMatrix: mat3x3<f32>,
}
`,rn=`
struct VertexInput {
@location(0) aPosition: vec3<f32>,
@location(1) aNormal: vec3<f32>,
@location(2) aTexCoord: vec2<f32>,
@location(3) aVertexColor: vec4<f32>,
};
struct VertexOutput {
@builtin(position) Position: vec4<f32>,
@location(0) vVertexNormal: vec3<f32>,
@location(1) vVertTexCoord: vec2<f32>,
@location(2) vColor: vec4<f32>,
};
${nn}
@group(0) @binding(0) var<uniform> material: MaterialUniforms;
@group(1) @binding(0) var<uniform> model: ModelUniforms;
@group(2) @binding(0) var<uniform> camera: CameraUniforms;
struct Vertex {
position: vec3<f32>,
normal: vec3<f32>,
texCoord: vec2<f32>,
color: vec4<f32>,
}
@vertex
fn main(input: VertexInput) -> VertexOutput {
HOOK_beforeVertex();
var output: VertexOutput;
let useVertexColor = (material.uUseVertexColor != 0 && input.aVertexColor.x >= 0.0);
var inputs = Vertex(
input.aPosition,
input.aNormal,
input.aTexCoord,
select(model.uMaterialColor, input.aVertexColor, useVertexColor)
);
// @p5 ifdef Vertex getObjectInputs
inputs = HOOK_getObjectInputs(inputs);
// @p5 endif
// @p5 ifdef Vertex getWorldInputs
inputs.position = (model.uModelMatrix * vec4<f32>(inputs.position, 1.0)).xyz;
inputs.normal = model.uModelNormalMatrix * inputs.normal;
inputs = HOOK_getWorldInputs(inputs);
// @p5 endif
// @p5 ifdef Vertex getWorldInputs
// Already multiplied by the model matrix, just apply view
inputs.position = (camera.uViewMatrix * vec4<f32>(inputs.position, 1.0)).xyz;
inputs.normal = camera.uCameraNormalMatrix * inputs.normal;
// @p5 endif
// @p5 ifndef Vertex getWorldInputs
// Apply both at once
inputs.position = (model.uModelViewMatrix * vec4<f32>(inputs.position, 1.0)).xyz;
inputs.normal = model.uNormalMatrix * inputs.normal;
// @p5 endif
// @p5 ifdef Vertex getCameraInputs
inputs = HOOK_getCameraInputs(inputs);
// @p5 endif
output.vVertTexCoord = inputs.texCoord;
output.vVertexNormal = normalize(inputs.normal);
output.vColor = inputs.color;
output.Position = camera.uProjectionMatrix * vec4<f32>(inputs.position, 1.0);
HOOK_afterVertex();
return output;
}
`,an=`
struct FragmentInput {
@location(0) vVertexNormal: vec3<f32>,
@location(1) vVertTexCoord: vec2<f32>,
@location(2) vColor: vec4<f32>,
};
${nn}
@group(0) @binding(0) var<uniform> material: MaterialUniforms;
@group(1) @binding(0) var<uniform> model: ModelUniforms;
@group(2) @binding(0) var<uniform> camera: CameraUniforms;
@fragment
fn main(input: FragmentInput) -> @location(0) vec4<f32> {
HOOK_beforeFragment();
var outColor = HOOK_getFinalColor(input.vColor, input.vVertTexCoord);
outColor = vec4<f32>(outColor.rgb * outColor.a, outColor.a);
HOOK_afterFragment();
return outColor;
}
`,on=`
// Group 0: Stroke Properties
struct StrokeUniforms {
uStrokeWeight: f32,
uUseLineColor: f32,
uSimpleLines: f32,
uStrokeCap: u32,
uStrokeJoin: u32,
}
// Group 1: Model Transform
struct ModelUniforms {
// @p5 ifdef StrokeVertex getWorldInputs
uModelMatrix: mat4x4<f32>,
uViewMatrix: mat4x4<f32>,
// @p5 endif
// @p5 ifndef StrokeVertex getWorldInputs
uModelViewMatrix: mat4x4<f32>,
// @p5 endif
uMaterialColor: vec4<f32>,
}
// Group 2: Camera and Projection
struct CameraUniforms {
uProjectionMatrix: mat4x4<f32>,
uViewport: vec4<f32>,
uPerspective: u32,
}
`,sn=`
struct StrokeVertexInput {
@location(0) aPosition: vec3<f32>,
@location(1) aSide: f32,
@location(2) aTangentIn: vec3<f32>,
@location(3) aTangentOut: vec3<f32>,
@location(4) aVertexColor: vec4<f32>,
};
struct StrokeVertexOutput {
@builtin(position) Position: vec4<f32>,
@location(0) vColor: vec4<f32>,
@location(1) vTangent: vec2<f32>,
@location(2) vCenter: vec2<f32>,
@location(3) vPosition: vec2<f32>,
@location(4) vMaxDist: f32,
@location(5) vCap: f32,
@location(6) vJoin: f32,
@location(7) vStrokeWeight: f32,
};
${on}
@group(0) @binding(0) var<uniform> stroke: StrokeUniforms;
@group(1) @binding(0) var<uniform> model: ModelUniforms;
@group(2) @binding(0) var<uniform> camera: CameraUniforms;
struct StrokeVertex {
position: vec3<f32>,
tangentIn: vec3<f32>,
tangentOut: vec3<f32>,
color: vec4<f32>,
weight: f32,
}
fn lineIntersection(aPoint: vec2f, aDir: vec2f, bPoint: vec2f, bDir: vec2f) -> vec2f {
// Rotate and translate so a starts at the origin and goes out to the right
var bMutPoint = bPoint;
bMutPoint -= aPoint;
var rotatedBFrom = vec2<f32>(
bMutPoint.x*aDir.x + bMutPoint.y*aDir.y,
bMutPoint.y*aDir.x - bMutPoint.x*aDir.y
);
var bTo = bMutPoint + bDir;
var rotatedBTo = vec2<f32>(
bTo.x*aDir.x + bTo.y*aDir.y,
bTo.y*aDir.x - bTo.x*aDir.y
);
var intersectionDistance =
rotatedBTo.x + (rotatedBFrom.x - rotatedBTo.x) * rotatedBTo.y /
(rotatedBTo.y - rotatedBFrom.y);
return aPoint + aDir * intersectionDistance;
}
@vertex
fn main(input: StrokeVertexInput) -> StrokeVertexOutput {
HOOK_beforeVertex();
var output: StrokeVertexOutput;
let simpleLines = (stroke.uSimpleLines != 0.);
if (!simpleLines) {
if (all(input.aTangentIn == vec3<f32>()) != all(input.aTangentOut == vec3<f32>())) {
output.vCap = 1.;
} else {
output.vCap = 0.;
}
let conditionA = any(input.aTangentIn != vec3<f32>());
let conditionB = any(input.aTangentOut != vec3<f32>());
let conditionC = any(input.aTangentIn != input.aTangentOut);
if (conditionA && conditionB && conditionC) {
output.vJoin = 1.;
} else {
output.vJoin = 0.;
}
}
var lineColor: vec4<f32>;
if (stroke.uUseLineColor != 0.) {
lineColor = input.aVertexColor;
} else {
lineColor = model.uMaterialColor;
}
var inputs = StrokeVertex(
input.aPosition.xyz,
input.aTangentIn,
input.aTangentOut,
lineColor,
stroke.uStrokeWeight
);
// @p5 ifdef StrokeVertex getObjectInputs
inputs = HOOK_getObjectInputs(inputs);
// @p5 endif
// @p5 ifdef StrokeVertex getWorldInputs
inputs.position = (model.uModelMatrix * vec4<f32>(inputs.position, 1.)).xyz;
inputs.tangentIn = (model.uModelMatrix * vec4<f32>(input.aTangentIn, 1.)).xyz;
inputs.tangentOut = (model.uModelMatrix * vec4<f32>(input.aTangentOut, 1.)).xyz;
inputs = HOOK_getWorldInputs(inputs);
// @p5 endif
// @p5 ifdef StrokeVertex getWorldInputs
// Already multiplied by the model matrix, just apply view
inputs.position = (model.uViewMatrix * vec4<f32>(inputs.position, 1.)).xyz;
inputs.tangentIn = (model.uViewMatrix * vec4<f32>(input.aTangentIn, 0.)).xyz;
inputs.tangentOut = (model.uViewMatrix * vec4<f32>(input.aTangentOut, 0.)).xyz;
// @p5 endif
// @p5 ifndef StrokeVertex getWorldInputs
// Apply both at once
inputs.position = (model.uModelViewMatrix * vec4<f32>(inputs.position, 1.)).xyz;
inputs.tangentIn = (model.uModelViewMatrix * vec4<f32>(input.aTangentIn, 0.)).xyz;
inputs.tangentOut = (model.uModelViewMatrix * vec4<f32>(input.aTangentOut, 0.)).xyz;
// @p5 endif
// @p5 ifdef StrokeVertex getCameraInputs
inputs = HOOK_getCameraInputs(inputs);
// @p5 endif
var posp = vec4<f32>(inputs.position, 1.);
var posqIn = vec4<f32>(inputs.position + inputs.tangentIn, 1.);
var posqOut = vec4<f32>(inputs.position + inputs.tangentOut, 1.);
output.vStrokeWeight = inputs.weight;
var facingCamera = pow(
// The word space tangent's z value is 0 if it's facing the camera
abs(normalize(posqIn-posp).z),
// Using pow() here to ramp 'facingCamera' up from 0 to 1 really quickly
// so most lines get scaled and don't get clipped
0.25
);
// Moving vertices slightly toward the camera
// to avoid depth-fighting with the fill triangles.
// A mix of scaling and offsetting is used based on distance
// Discussion here:
// https://github.com/processing/p5.js/issues/7200
// using a scale <1 moves the lines towards nearby camera
// in order to prevent popping effects due to half of
// the line disappearing behind the geometry faces.
var zDistance = -posp.z;
var distanceFactor = smoothstep(0., 800., zDistance);
// Discussed here:
// http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=252848
var scale = mix(1., 0.995, facingCamera);
var dynamicScale = mix(scale, 1.0, distanceFactor); // Closer = more scale, farther = less
posp = vec4<f32>(posp.xyz * dynamicScale, posp.w);
posqIn = vec4<f32>(posqIn.xyz * dynamicScale, posqIn.w);
posqOut= vec4<f32>(posqOut.xyz * dynamicScale, posqOut.w);
// Moving vertices slightly toward camera when far away
// https://github.com/processing/p5.js/issues/6956
var zOffset = mix(0., -1., facingCamera);
var dynamicZAdjustment = mix(0., zOffset, distanceFactor); // Closer = less zAdjustment, farther = more
posp.z -= dynamicZAdjustment;
posqIn.z -= dynamicZAdjustment;
posqOut.z -= dynamicZAdjustment;
var p = camera.uProjectionMatrix * posp;
var qIn = camera.uProjectionMatrix * posqIn;
var qOut = camera.uProjectionMatrix * posqOut;
var tangentIn = normalize((qIn.xy * p.w - p.xy * qIn.w) * camera.uViewport.zw);
var tangentOut = normalize((qOut.xy * p.w - p.xy * qOut.w) * camera.uViewport.zw);
var curPerspScale = vec2<f32>();
if (camera.uPerspective == 1) {
// Perspective ---
// convert from world to clip by multiplying with projection scaling factor
// to get the right thickness (see https://github.com/processing/processing/issues/5182)
// The y value of the projection matrix may be flipped if rendering to a Framebuffer.
// Multiplying again by its sign here negates the flip to get just the scale.
curPerspScale = (camera.uProjectionMatrix * vec4(1., sign(camera.uProjectionMatrix[1][1]), 0., 0.)).xy;
} else {
// No Perspective ---
// multiply by W (to cancel out division by W later in the pipeline) and
// convert from screen to clip (derived from clip to screen above)
curPerspScale = p.w / (0.5 * camera.uViewport.zw);
}
var offset = vec2<f32>();
if (output.vJoin == 1. && !simpleLines) {
output.vTangent = normalize(tangentIn + tangentOut);
var normalIn = vec2<f32>(-tangentIn.y, tangentIn.x);
var normalOut = vec2<f32>(-tangentOut.y, tangentOut.x);
var side = sign(input.aSide);
var sideEnum = abs(input.aSide);
// We generate vertices for joins on either side of the centerline, but
// the "elbow" side is the only one needing a join. By not setting the
// offset for the other side, all its vertices will end up in the same
// spot and not render, effectively discarding it.
if (sign(dot(tangentOut, vec2<f32>(-tangentIn.y, tangentIn.x))) != side) {
// Side enums:
// 1: the side going into the join
// 2: the middle of the join
// 3: the side going out of the join
if (sideEnum == 2.) {
// Calculate the position + tangent on either side of the join, and
// find where the lines intersect to find the elbow of the join
var c = (posp.xy / posp.w + vec2<f32>(1.)) * 0.5 * camera.uViewport.zw;
var intersection = lineIntersection(
c + (side * normalIn * inputs.weight / 2.),
tangentIn,
c + (side * normalOut * inputs.weight / 2.),
tangentOut
);
offset = intersection - c;
// When lines are thick and the angle of the join approaches 180, the
// elbow might be really far from the center. We'll apply a limit to
// the magnitude to avoid lines going across the whole screen when this
// happens.
var mag = length(offset);
var maxMag = 3. * inputs.weight;
if (mag > maxMag) {
offset *= maxMag / mag;
}
} else if (sideEnum == 1.) {
offset = side * normalIn * inputs.weight / 2.;
} else if (sideEnum == 3.) {
offset = side * normalOut * inputs.weight / 2.;
}
}
if (stroke.uStrokeJoin == 2) {
var avgNormal = vec2<f32>(-output.vTangent.y, output.vTangent.x);
output.vMaxDist = abs(dot(avgNormal, normalIn * inputs.weight / 2.));
} else {
output.vMaxDist = inputs.weight / 2.;
}
} else {
var tangent: vec2<f32>;
if (all(input.aTangentIn == vec3<f32>())) {
tangent = tangentOut;
} else {
tangent = tangentIn;
}
output.vTangent = tangent;
var normal = vec2<f32>(-tangent.y, tangent.x);
var normalOffset = sign(input.aSide);
// Caps will have side values of -2 or 2 on the edge of the cap that
// extends out from the line
var tangentOffset = abs(input.aSide) - 1.;
offset = (normal * normalOffset + tangent * tangentOffset) *
inputs.weight * 0.5;
output.vMaxDist = inputs.weight / 2.;
}
output.vCenter = p.xy;
output.vPosition = output.vCenter + offset;
output.vColor = inputs.color;
output.Position = vec4<f32>(
p.xy + offset.xy * curPerspScale,
p.zw
);
HOOK_afterVertex();
return output;
}`,cn=`
struct StrokeFragmentInput {
@location(0) vColor: vec4<f32>,
@location(1) vTangent: vec2<f32>,
@location(2) vCenter: vec2<f32>,
@location(3) vPosition: vec2<f32>,
@location(4) vMaxDist: f32,
@location(5) vCap: f32,
@location(6) vJoin: f32,
@location(7) vStrokeWeight: f32,
}
${on}
@group(0) @binding(0) var<uniform> stroke: StrokeUniforms;
@group(1) @binding(0) var<uniform> model: ModelUniforms;
@group(2) @binding(0) var<uniform> camera: CameraUniforms;
fn distSquared(a: vec2<f32>, b: vec2<f32>) -> f32 {
return dot(b - a, b - a);
}
struct Inputs {
color: vec4<f32>,
tangent: vec2<f32>,
center: vec2<f32>,
position: vec2<f32>,
strokeWeight: f32,
}
@fragment
fn main(input: StrokeFragmentInput) -> @location(0) vec4<f32> {
HOOK_beforeFragment();
var inputs: Inputs;
inputs.color = input.vColor;
inputs.tangent = input.vTangent;
inputs.center = input.vCenter;
inputs.position = input.vPosition;
inputs.strokeWeight = input.vStrokeWeight;
inputs = HOOK_getPixelInputs(inputs);
if (input.vCap > 0.) {
if (
stroke.uStrokeCap == STROKE_CAP_ROUND &&
HOOK_shouldDiscard(distSquared(inputs.position, inputs.center) > inputs.strokeWeight * inputs.strokeWeight * 0.25)
) {
discard;
} else if (
stroke.uStrokeCap == STROKE_CAP_SQUARE &&
HOOK_shouldDiscard(dot(inputs.position - inputs.center, inputs.tangent) > 0.)
) {
discard;
} else if (HOOK_shouldDiscard(false)) {
discard;
}
} else if (input.vJoin > 0.) {
if (
stroke.uStrokeJoin == STROKE_JOIN_ROUND &&
HOOK_shouldDiscard(distSquared(inputs.position, inputs.center) > inputs.strokeWeight * inputs.strokeWeight * 0.25)
) {
discard;
} else if (stroke.uStrokeJoin == STROKE_JOIN_BEVEL) {
let normal = vec2<f32>(-inputs.tangent.y, -inputs.tangent.x);
if (HOOK_shouldDiscard(abs(dot(inputs.position - inputs.center, normal)) > input.vMaxDist)) {
discard;
}
} else if (HOOK_shouldDiscard(false)) {
discard;
}
}
var col = HOOK_getFinalColor(inputs.color, vec2<f32>(0.0, 0.0));
col = vec4<f32>(col.rgb, 1.0) * col.a;
HOOK_afterFragment();
return vec4<f32>(col);
}
`,ln=`
// Group 0: Material Properties
struct MaterialUniforms {
uUseVertexColor: u32,
uHasSetAmbient: u32,
uAmbientColor: vec3<f32>,
uSpecularMatColor: vec4<f32>,
uAmbientMatColor: vec4<f32>,
uEmissiveMatColor: vec4<f32>,
uTint: vec4<f32>,
isTexture: u32,
uSpecular: u32,
uShininess: f32,
uMetallic: f32,
uHasNormalMap: u32,
uNormalScale: f32,
uNormalMapMode: u32,
uNormalTexelSize: vec2<f32>,
}
// Group 0: Lighting
struct LightingUniforms {
uDirectionalLightCount: i32,
uLightingDirection: array<vec3<f32>, 5>,
uDirectionalDiffuseColors: array<vec3<f32>, 5>,
uDirectionalSpecularColors: array<vec3<f32>, 5>,
uPointLightCount: i32,
uPointLightLocation: array<vec3<f32>, 5>,
uPointLightDiffuseColors: array<vec3<f32>, 5>,
uPointLightSpecularColors: array<vec3<f32>, 5>,
uSpotLightCount: i32,
uSpotLightAngle: vec4<f32>,
uSpotLightConc: vec4<f32>,
uSpotLightDiffuseColors: array<vec3<f32>, 4>,
uSpotLightSpecularColors: array<vec3<f32>, 4>,
uSpotLightLocation: array<vec3<f32>, 4>,
uSpotLightDirection: array<vec3<f32>, 4>,
uConstantAttenuation: f32,
uLinearAttenuation: f32,
uQuadraticAttenuation: f32,
uUseImageLight: u32,
uUseLighting: u32,
}
// Group 1: Model Transform
struct ModelUniforms {
// @p5 ifdef Vertex getWorldInputs
uModelMatrix: mat4x4<f32>,
uModelNormalMatrix: mat3x3<f32>,
// @p5 endif
// @p5 ifndef Vertex getWorldInputs
uModelViewMatrix: mat4x4<f32>,
uNormalMatrix: mat3x3<f32>,
// @p5 endif
uMaterialColor: vec4<f32>,
}
// Group 2: Camera and Projection
struct CameraUniforms {
uViewMatrix: mat4x4<f32>,
uProjectionMatrix: mat4x4<f32>,
uCameraNormalMatrix: mat3x3<f32>,
}
`,un=({useTextureMaps:e=!1}={})=>`
struct VertexInput {
@location(0) aPosition: vec3<f32>,
@location(1) aNormal: vec3<f32>,
@location(2) aTexCoord: vec2<f32>,
@location(3) aVertexColor: vec4<f32>,${e?`
@location(4) aTangent: vec4<f32>,`:``}
};
struct VertexOutput {
@builtin(position) Position: vec4<f32>,
@location(0) vNormal: vec3<f32>,
@location(1) vTexCoord: vec2<f32>,
@location(2) vViewPosition: vec3<f32>,
@location(4) vColor: vec4<f32>,${e?`
@location(5) vTangent: vec4<f32>,`:``}
};
${ln}
@group(0) @binding(0) var<uniform> material: MaterialUniforms;
@group(0) @binding(1) var<uniform> lighting: LightingUniforms;
@group(1) @binding(0) var<uniform> model: ModelUniforms;
@group(2) @binding(0) var<uniform> camera: CameraUniforms;
struct Vertex {
position: vec3<f32>,
normal: vec3<f32>,
texCoord: vec2<f32>,
color: vec4<f32>,
}
@vertex
fn main(input: VertexInput) -> VertexOutput {
HOOK_beforeVertex();
var output: VertexOutput;
let useVertexColor = (material.uUseVertexColor != 0 && input.aVertexColor.x >= 0.0);
var inputs = Vertex(
input.aPosition,
input.aNormal,
input.aTexCoord,
select(model.uMaterialColor, input.aVertexColor, useVertexColor)
);
${e?` var tangent = input.aTangent.xyz;
`:``}
// @p5 ifdef Vertex getObjectInputs
inputs = HOOK_getObjectInputs(inputs);
// @p5 endif
// @p5 ifdef Vertex getWorldInputs
inputs.position = (model.uModelMatrix * vec4<f32>(inputs.position, 1.0)).xyz;
inputs.normal = model.uModelNormalMatrix * inputs.normal;
${e?` tangent = model.uModelNormalMatrix * tangent;
`:``} inputs = HOOK_getWorldInputs(inputs);
// @p5 endif
// @p5 ifdef Vertex getWorldInputs
// Already multiplied by the model matrix, just apply view
inputs.position = (camera.uViewMatrix * vec4<f32>(inputs.position, 1.0)).xyz;
inputs.normal = camera.uCameraNormalMatrix * inputs.normal;
${e?` tangent = camera.uCameraNormalMatrix * tangent;
`:``}// @p5 endif
// @p5 ifndef Vertex getWorldInputs
// Apply both at once
inputs.position = (model.uModelViewMatrix * vec4<f32>(inputs.position, 1.0)).xyz;
inputs.normal = model.uNormalMatrix * inputs.normal;
${e?` tangent = model.uNormalMatrix * tangent;
`:``}// @p5 endif
// @p5 ifdef Vertex getCameraInputs
inputs = HOOK_getCameraInputs(inputs);
// @p5 endif
output.vViewPosition = inputs.position;
output.vTexCoord = inputs.texCoord;
output.vNormal = normalize(inputs.normal);
output.vColor = inputs.color;
${e?` output.vTangent = vec4<f32>(tangent, input.aTangent.w);
`:``}
output.Position = camera.uProjectionMatrix * vec4<f32>(inputs.position, 1.0);
HOOK_afterVertex();
return output;
}
`,dn=({useTextureMaps:e=!1}={})=>`
struct FragmentInput {
@location(0) vNormal: vec3<f32>,
@location(1) vTexCoord: vec2<f32>,
@location(2) vViewPosition: vec3<f32>,
@location(4) vColor: vec4<f32>,${e?`
@location(5) vTangent: vec4<f32>,`:``}
};
${ln}
@group(0) @binding(0) var<uniform> material: MaterialUniforms;
@group(0) @binding(1) var<uniform> lighting: LightingUniforms;
@group(0) @binding(2) var uSampler: texture_2d<f32>;
@group(0) @binding(3) var uSampler_sampler: sampler;
@group(0) @binding(4) var environmentMapDiffused: texture_2d<f32>;
@group(0) @binding(5) var environmentMapDiffused_sampler: sampler;
@group(0) @binding(6) var environmentMapSpecular: texture_2d<f32>;
@group(0) @binding(7) var environmentMapSpecular_sampler: sampler;
${e?`@group(0) @binding(8) var uNormalSampler: texture_2d<f32>;
@group(0) @binding(9) var uNormalSampler_sampler: sampler;
`:``}@group(1) @binding(0) var<uniform> model: ModelUniforms;
@group(2) @binding(0) var<uniform> camera: CameraUniforms;
struct ColorComponents {
baseColor: vec3<f32>,
opacity: f32,
ambientColor: vec3<f32>,
specularColor: vec3<f32>,
diffuse: vec3<f32>,
ambient: vec3<f32>,
specular: vec3<f32>,
emissive: vec3<f32>,
}
struct Inputs {
normal: vec3<f32>,
texCoord: vec2<f32>,
ambientLight: vec3<f32>,
ambientMaterial: vec3<f32>,
specularMaterial: vec3<f32>,
emissiveMaterial: vec3<f32>,
color: vec4<f32>,
shininess: f32,
metalness: f32,
}
struct LightResult {
diffuse: vec3<f32>,
specular: vec3<f32>,
}
struct LightIntensityResult {
diffuse: f32,
specular: f32,
}
const specularFactor = 2.0;
const diffuseFactor = 0.73;
const PI = 3.14159265359;
fn mapTextureToNormal(v: vec3<f32>) -> vec2<f32> {
// x = r sin(phi) cos(theta)
// y = r cos(phi)
// z = r sin(phi) sin(theta)
let phi = acos(v.y);
// if phi is 0, then there are no x, z components
var theta = 0.0;
// else
theta = acos(v.x / sin(phi));
let sinTheta = v.z / sin(phi);
if (sinTheta < 0.0) {
// Turn it into -theta, but in the 0-2PI range
theta = 2.0 * PI - theta;
}
theta = theta / (2.0 * PI);
let phiNorm = phi / PI;
let angles = vec2<f32>(fract(theta + 0.25), 1.0 - phiNorm);
return angles;
}
fn calculateImageDiffuse(vNormal: vec3<f32>, vViewPosition: vec3<f32>, metallic: f32) -> vec3<f32> {
// make 2 seperate builds
let worldCameraPosition = vec3<f32>(0.0, 0.0, 0.0); // hardcoded world camera position
let worldNormal = normalize(vNormal * camera.uCameraNormalMatrix);
let newTexCoord = mapTextureToNormal(worldNormal);
let texture = textureSample(environmentMapDiffused, environmentMapDiffused_sampler, newTexCoord);
// this is to make the darker sections more dark
// png and jpg usually flatten the brightness so it is to reverse that
return mix(smoothstep(vec3<f32>(0.0), vec3<f32>(1.0), texture.xyz), vec3<f32>(0.0), metallic);
}
fn calculateImageSpecular(vNormal: vec3<f32>, vViewPosition: vec3<f32>, shininess: f32, metallic: f32) -> vec3<f32> {
let worldCameraPosition = vec3<f32>(0.0, 0.0, 0.0);
let worldNormal = normalize(vNormal);
let lightDirection = normalize(vViewPosition - worldCameraPosition);
let R = reflect(lightDirection, worldNormal) * camera.uCameraNormalMatrix;
let newTexCoord = mapTextureToNormal(R);
// In p5js the range of shininess is >= 1,
// Therefore roughness range will be ([0,1]*8)*20 or [0, 160]
// The factor of 8 is because currently the getSpecularTexture
// only calculated 8 different levels of roughness
// The factor of 20 is just to spread up this range so that,
// [1, max] of shininess is converted to [0,160] of roughness
let roughness = 20.0 / shininess;
let outColor = textureSampleLevel(environmentMapSpecular, environmentMapSpecular_sampler, newTexCoord, roughness * 8.0 - 1.);
// this is to make the darker sections more dark
// png and jpg usually flatten the brightness so it is to reverse that
return mix(
pow(outColor.xyz, vec3<f32>(10.0)),
pow(outColor.xyz, vec3<f32>(1.2)),
metallic
);
}
fn phongSpecular(
lightDirection: vec3<f32>,
viewDirection: vec3<f32>,
surfaceNormal: vec3<f32>,
shininess: f32
) -> f32 {
let R = reflect(lightDirection, surfaceNormal);
return pow(max(0.0, dot(R, viewDirection)), shininess);
}
fn lambertDiffuse(lightDirection: vec3<f32>, surfaceNormal: vec3<f32>) -> f32 {
return max(0.0, dot(-lightDirection, surfaceNormal));
}
fn singleLight(
viewDirection: vec3<f32>,
normal: vec3<f32>,
lightVector: vec3<f32>,
shininess: f32,
metallic: f32
) -> LightIntensityResult {
let lightDir = normalize(lightVector);
let specularIntensity = mix(1.0, 0.4, metallic);
let diffuseIntensity = mix(1.0, 0.1, metallic);
let diffuse = lambertDiffuse(lightDir, normal) * diffuseIntensity;
let specular = select(
0.,
phongSpecular(lightDir, viewDirection, normal, shininess) * specularIntensity,
material.uSpecular == 1
);
return LightIntensityResult(diffuse, specular);
}
fn totalLight(
modelPosition: vec3<f32>,
normal: vec3<f32>,
shininess: f32,
metallic: f32
) -> LightResult {
var totalSpecular = vec3<f32>(0.0, 0.0, 0.0);
var totalDiffuse = vec3<f32>(0.0, 0.0, 0.0);
if (lighting.uUseLighting == 0) {
return LightResult(vec3<f32>(1.0, 1.0, 1.0), totalSpecular);
}
let viewDirection = normalize(-modelPosition);
for (var j = 0; j < 5; j++) {
if (j < lighting.uDirectionalLightCount) {
let lightVector = (camera.uViewMatrix * vec4<f32>(
lighting.uLightingDirection[j],
0.0
)).xyz;
let lightColor = lighting.uDirectionalDiffuseColors[j];
let specularColor = lighting.uDirectionalSpecularColors[j];
let result = singleLight(viewDirection, normal, lightVector, shininess, metallic);
totalDiffuse += result.diffuse * lightColor;
totalSpecular += result.specular * specularColor;
}
if (j < lighting.uPointLightCount) {
let lightPosition = (camera.uViewMatrix * vec4<f32>(
lighting.uPointLightLocation[j],
1.0
)).xyz;
let lightVector = modelPosition - lightPosition;
let lightDistance = length(lightVector);
let lightFalloff = 1.0 / (
lighting.uConstantAttenuation +
lightDistance * lighting.uLinearAttenuation +
lightDistance * lightDistance * lighting.uQuadraticAttenuation
);
let lightColor = lighting.uPointLightDiffuseColors[j] * lightFalloff;
let specularColor = lighting.uPointLightSpecularColors[j] * lightFalloff;
let result = singleLight(viewDirection, normal, lightVector, shininess, metallic);
totalDiffuse += result.diffuse * lightColor;
totalSpecular += result.specular * specularColor;
}
if (j < lighting.uSpotLightCount) {
let lightPosition = (camera.uViewMatrix * vec4<f32>(
lighting.uSpotLightLocation[j],
1.0
)).xyz;
let lightVector = modelPosition - lightPosition;
let lightDistance = length(lightVector);
var lightFalloff = 1.0 / (
lighting.uConstantAttenuation +
lightDistance * lighting.uLinearAttenuation +
lightDistance * lightDistance * lighting.uQuadraticAttenuation
);
let lightDirection = (camera.uViewMatrix * vec4<f32>(
lighting.uSpotLightDirection[j],
0.0
)).xyz;
let spotDot = dot(normalize(lightVector), normalize(lightDirection));
let spotFalloff = select(
0.0,
pow(spotDot, lighting.uSpotLightConc[j]),
spotDot < lighting.uSpotLightAngle[j]
);
lightFalloff *= spotFalloff;
let lightColor = lighting.uSpotLightDiffuseColors[j];
let specularColor = lighting.uSpotLightSpecularColors[j];
let result = singleLight(viewDirection, normal, lightVector, shininess, metallic);
totalDiffuse += result.diffuse * lightColor;
totalSpecular += result.specular * specularColor;
}
}
// Image light contribution
if (lighting.uUseImageLight != 0) {
totalDiffuse += calculateImageDiffuse(normal, modelPosition, metallic);
totalSpecular += calculateImageSpecular(normal, modelPosition, shininess, metallic);
}
return LightResult(
totalDiffuse * diffuseFactor,
totalSpecular * specularFactor
);
}
@fragment
fn main(input: FragmentInput) -> @location(0) vec4<f32> {
HOOK_beforeFragment();
let color = select(
input.vColor,
textureSample(uSampler, uSampler_sampler, input.vTexCoord) * (material.uTint/255.0),
material.isTexture == 1
); // TODO: check isTexture and apply tint
var N = normalize(input.vNormal);
${e?` if (material.uHasNormalMap == 1) {
// rebuild the tangent basis from the smooth per-vertex tangent (gram-schmidt
// keeps it perpendicular to the interpolated normal) and perturb by the map.
var T = normalize(input.vTangent.xyz);
T = normalize(T - N * dot(N, T));
let B = cross(N, T) * input.vTangent.w;
var mapN: vec3<f32>;
if (material.uNormalMapMode == 1u) {
// bump map: brightness is height, so the tangent-space normal comes from
// how fast that height changes between neighbouring texels. sampling both
// sides keeps the slope right at the edges of the map, where reaching past
// one side would otherwise clamp and read back the same texel.
let du = vec2<f32>(material.uNormalTexelSize.x, 0.0);
let dv = vec2<f32>(0.0, material.uNormalTexelSize.y);
let hl = textureSample(uNormalSampler, uNormalSampler_sampler, input.vTexCoord - du).r;
let hr = textureSample(uNormalSampler, uNormalSampler_sampler, input.vTexCoord + du).r;
let hd = textureSample(uNormalSampler, uNormalSampler_sampler, input.vTexCoord - dv).r;
let hu = textureSample(uNormalSampler, uNormalSampler_sampler, input.vTexCoord + dv).r;
// the surface leans away from the direction height increases in
mapN = normalize(vec3<f32>((hl - hr) * 0.5, (hd - hu) * 0.5, 1.0));
} else {
// normal map: rgb already holds the tangent-space normal
mapN = textureSample(uNormalSampler, uNormalSampler_sampler, input.vTexCoord).rgb * 2.0 - 1.0;
}
// scale the tangent-space slope so the strength can be tuned (-bm)
mapN = vec3<f32>(mapN.xy * material.uNormalScale, mapN.z);
N = normalize(mat3x3<f32>(T, B, N) * mapN);
}
`:``} var inputs = Inputs(
N,
input.vTexCoord,
material.uAmbientColor,
select(color.rgb, material.uAmbientMatColor.rgb, material.uHasSetAmbient == 1),
material.uSpecularMatColor.rgb,
material.uEmissiveMatColor.rgb,
color,
material.uShininess,
material.uMetallic
);
inputs = HOOK_getPixelInputs(inputs);
let light = totalLight(
input.vViewPosition,
inputs.normal,
inputs.shininess,
inputs.metalness
);
let baseColor = inputs.color;
let components = ColorComponents(
baseColor.rgb,
baseColor.a,
inputs.ambientMaterial,
inputs.specularMaterial,
light.diffuse,
inputs.ambientLight,
light.specular,
inputs.emissiveMaterial
);
var outColor = HOOK_getFinalColor(
HOOK_combineColors(components), input.vTexCoord
);
outColor = vec4<f32>(outColor.rgb * outColor.a, outColor.a);
HOOK_afterFragment();
return outColor;
}
`,M=`
// Group 0: Font Properties
struct FontUniforms {
uStrokeImageSize: vec2<i32>,
uCellsImageSize: vec2<i32>,
uGridImageSize: vec2<i32>,
uGridOffset: vec2<i32>,
uGridSize: vec2<i32>,
uGlyphRect: vec4<f32>,
uGlyphOffset: f32,
uMaterialColor: vec4<f32>,
}
// Group 1: Model Transform
struct ModelUniforms {
uModelViewMatrix: mat4x4<f32>,
}
// Group 2: Camera and Projection
struct CameraUniforms {
uProjectionMatrix: mat4x4<f32>,
}
`,fn=`
struct VertexInput {
@location(0) aPosition: vec3<f32>,
@location(1) aTexCoord: vec2<f32>,
};
struct VertexOutput {
@builtin(position) Position: vec4<f32>,
@location(0) vTexCoord: vec2<f32>,
};
${M}
@group(0) @binding(0) var<uniform> font: FontUniforms;
@group(1) @binding(0) var<uniform> model: ModelUniforms;
@group(2) @binding(0) var<uniform> camera: CameraUniforms;
@vertex
fn main(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
var positionVec4 = vec4<f32>(input.aPosition, 1.0);
// scale by the size of the glyph's rectangle
positionVec4.x = positionVec4.x * (font.uGlyphRect.z - font.uGlyphRect.x);
positionVec4.y = positionVec4.y * (font.uGlyphRect.w - font.uGlyphRect.y);
// Expand glyph bounding boxes by 1px on each side to give a bit of room
// for antialiasing
let newOrigin = (model.uModelViewMatrix * vec4<f32>(0.0, 0.0, 0.0, 1.0)).xyz;
let newDX = (model.uModelViewMatrix * vec4<f32>(1.0, 0.0, 0.0, 1.0)).xyz;
let newDY = (model.uModelViewMatrix * vec4<f32>(0.0, 1.0, 0.0, 1.0)).xyz;
let pixelScale = vec2<f32>(
1.0 / length(newOrigin - newDX),
1.0 / length(newOrigin - newDY)
);
let offset = pixelScale * normalize(input.aTexCoord - vec2<f32>(0.5, 0.5));
let textureOffset = offset * (1.0 / vec2<f32>(
font.uGlyphRect.z - font.uGlyphRect.x,
font.uGlyphRect.w - font.uGlyphRect.y
));
// move to the corner of the glyph
positionVec4.x = positionVec4.x + font.uGlyphRect.x;
positionVec4.y = positionVec4.y + font.uGlyphRect.y;
// move to the letter's line offset
positionVec4.x = positionVec4.x + font.uGlyphOffset;
positionVec4.x = positionVec4.x + offset.x;
positionVec4.y = positionVec4.y + offset.y;
output.Position = camera.uProjectionMatrix * model.uModelViewMatrix * positionVec4;
output.vTexCoord = input.aTexCoord + textureOffset;
return output;
}
`,pn=`
struct FragmentInput {
@location(0) vTexCoord: vec2<f32>,
};
${M}
@group(0) @binding(0) var<uniform> font: FontUniforms;
@group(0) @binding(1) var uSamplerStrokes: texture_2d<f32>;
@group(0) @binding(2) var uSamplerStrokes_sampler: sampler;
@group(0) @binding(3) var uSamplerRowStrokes: texture_2d<f32>;
@group(0) @binding(4) var uSamplerRowStrokes_sampler: sampler;
@group(0) @binding(5) var uSamplerRows: texture_2d<f32>;
@group(0) @binding(6) var uSamplerRows_sampler: sampler;
@group(0) @binding(7) var uSamplerColStrokes: texture_2d<f32>;
@group(0) @binding(8) var uSamplerColStrokes_sampler: sampler;
@group(0) @binding(9) var uSamplerCols: texture_2d<f32>;
@group(0) @binding(10) var uSamplerCols_sampler: sampler;
@group(1) @binding(0) var<uniform> model: ModelUniforms;
@group(2) @binding(0) var<uniform> camera: CameraUniforms;
// some helper functions
fn ROUND_f32(v: f32) -> i32 { return i32(floor(v + 0.5)); }
fn ROUND_vec2(v: vec2<f32>) -> vec2<i32> { return vec2<i32>(floor(v + 0.5)); }
fn saturate_f32(v: f32) -> f32 { return clamp(v, 0.0, 1.0); }
fn saturate_vec2(v: vec2<f32>) -> vec2<f32> { return clamp(v, vec2<f32>(0.0), vec2<f32>(1.0)); }
fn mul_f32_i32(v1: f32, v2: i32) -> i32 {
return i32(floor(v1 * f32(v2)));
}
fn mul_vec2_ivec2(v1: vec2<f32>, v2: vec2<i32>) -> vec2<i32> {
return vec2<i32>(floor(v1 * vec2<f32>(v2) + 0.5));
}
// unpack a 16-bit integer from a float vec2
fn getInt16(v: vec2<f32>) -> i32 {
let iv = ROUND_vec2(v * 255.0);
return iv.x * 128 + iv.y;
}
const minDistance: f32 = 1.0/8192.0;
const hardness: f32 = 1.05; // amount of antialias
// the maximum number of curves in a glyph
const N: i32 = 250;
// retrieves an indexed pixel from a texture
fn getTexel(texture: texture_2d<f32>, samp: sampler, pos: i32, size: vec2<i32>) -> vec4<f32> {
let width = size.x;
let x = pos % width;
let y = pos / width;
return textureLoad(texture, vec2<i32>(x, y), 0);
}
fn calculateCrossings(p0: vec2<f32>, p1: vec2<f32>, p2: vec2<f32>, vTexCoord: vec2<f32>, pixelScale: vec2<f32>) -> array<vec2<f32>, 2> {
// get the coefficients of the quadratic in t
var a = p0 - p1 * 2.0 + p2;
var b = p0 - p1;
a = vec2<f32>(
select(a.x, sign(a.x) * 1e-6, abs(a.x) < 1e-6),
select(a.y, sign(a.y) * 1e-6, abs(a.y) < 1e-6)
);
b = vec2<f32>(
select(b.x, sign(b.x) * 1e-6, abs(b.x) < 1e-6),
select(b.y, sign(b.y) * 1e-6, abs(b.y) < 1e-6)
);
let c = p0 - vTexCoord;
// found out which values of 't' it crosses the axes
let surd = sqrt(max(vec2<f32>(0.0), b * b - a * c));
let t1 = ((b - surd) / a).yx;
let t2 = ((b + surd) / a).yx;
// approximate straight lines to avoid rounding errors
var t1_fixed = t1;
var t2_fixed = t2;
if (abs(a.y) < 0.001) {
t1_fixed.x = c.y / (2.0 * b.y);
t2_fixed.x = c.y / (2.0 * b.y);
}
if (abs(a.x) < 0.001) {
t1_fixed.y = c.x / (2.0 * b.x);
t2_fixed.y = c.x / (2.0 * b.x);
}
// plug into quadratic formula to find the coordinates of the crossings
let C1 = ((a * t1_fixed - b * 2.0) * t1_fixed + c) * pixelScale;
let C2 = ((a * t2_fixed - b * 2.0) * t2_fixed + c) * pixelScale;
return array<vec2<f32>, 2>(C1, C2);
}
fn coverageX(p0: vec2<f32>, p1: vec2<f32>, p2: vec2<f32>, vTexCoord: vec2<f32>, pixelScale: vec2<f32>, coverage: ptr<function, vec2<f32>>, weight: ptr<function, vec2<f32>>) {
let crossings = calculateCrossings(p0, p1, p2, vTexCoord, pixelScale);
let C1 = crossings[0];
let C2 = crossings[1];
// determine on which side of the x-axis the points lie
let y0 = p0.y > vTexCoord.y;
let y1 = p1.y > vTexCoord.y;
let y2 = p2.y > vTexCoord.y;
// could we be under the curve (after t1)?
if ((y1 && !y2) || (!y1 && y0)) {
// add the coverage for t1
(*coverage).x = (*coverage).x + saturate_f32(C1.x + 0.5);
// calculate the anti-aliasing for t1
(*weight).x = min((*weight).x, abs(C1.x));
}
// are we outside the curve (after t2)?
if ((y1 && !y0) || (!y1 && y2)) {
// subtract the coverage for t2
(*coverage).x = (*coverage).x - saturate_f32(C2.x + 0.5);
// calculate the anti-aliasing for t2
(*weight).x = min((*weight).x, abs(C2.x));
}
}
// this is essentially the same as coverageX, but with the axes swapped
fn coverageY(p0: vec2<f32>, p1: vec2<f32>, p2: vec2<f32>, vTexCoord: vec2<f32>, pixelScale: vec2<f32>, coverage: ptr<function, vec2<f32>>, weight: ptr<function, vec2<f32>>) {
let crossings = calculateCrossings(p0, p1, p2, vTexCoord, pixelScale);
let C1 = crossings[0];
let C2 = crossings[1];
let x0 = p0.x > vTexCoord.x;
let x1 = p1.x > vTexCoord.x;
let x2 = p2.x > vTexCoord.x;
if ((x1 && !x2) || (!x1 && x0)) {
(*coverage).y = (*coverage).y - saturate_f32(C1.y + 0.5);
weight.y = min(weight.y, abs(C1.y));
}
if ((x1 && !x0) || (!x1 && x2)) {
(*coverage).y = (*coverage).y + saturate_f32(C2.y + 0.5);
(*weight).y = min((*weight).y, abs(C2.y));
}
}
@fragment
fn main(input: FragmentInput) -> @location(0) vec4<f32> {
// var pixelScale: vec2<f32>;
var coverage: vec2<f32> = vec2<f32>(0.0);
var weight: vec2<f32> = vec2<f32>(0.5);
let pixelScale = hardness / fwidth(input.vTexCoord);
// which grid cell is this pixel in?
let gridCoord = vec2<i32>(floor(input.vTexCoord * vec2<f32>(font.uGridSize)));
// intersect curves in this row
{
// the index into the row info bitmap
let rowIndex = gridCoord.y + font.uGridOffset.y;
// fetch the info texel
let rowInfo = getTexel(uSamplerRows, uSamplerRows_sampler, rowIndex, font.uGridImageSize);
// unpack the rowInfo
let rowStrokeIndex = getInt16(rowInfo.xy);
let rowStrokeCount = getInt16(rowInfo.zw);
for (var iRowStroke = 0; iRowStroke < N; iRowStroke = iRowStroke + 1) {
if (iRowStroke >= rowStrokeCount) {
break;
}
// each stroke is made up of 3 points: the start and control point
// and the start of the next curve.
// fetch the indices of this pair of strokes:
let strokeIndices = getTexel(uSamplerRowStrokes, uSamplerRowStrokes_sampler, rowStrokeIndex + iRowStroke, font.uCellsImageSize);
// unpack the stroke index
let strokePos = getInt16(strokeIndices.xy);
// fetch the two strokes
let stroke0 = getTexel(uSamplerStrokes, uSamplerStrokes_sampler, strokePos + 0, font.uStrokeImageSize);
let stroke1 = getTexel(uSamplerStrokes, uSamplerStrokes_sampler, strokePos + 1, font.uStrokeImageSize);
// calculate the coverage
coverageX(stroke0.xy, stroke0.zw, stroke1.xy, input.vTexCoord, pixelScale, &coverage, &weight);
}
}
// intersect curves in this column
{
let colIndex = gridCoord.x + font.uGridOffset.x;
let colInfo = getTexel(uSamplerCols, uSamplerCols_sampler, colIndex, font.uGridImageSize);
let colStrokeIndex = getInt16(colInfo.xy);
let colStrokeCount = getInt16(colInfo.zw);
for (var iColStroke = 0; iColStroke < N; iColStroke = iColStroke + 1) {
if (iColStroke >= colStrokeCount) {
break;
}
let strokeIndices = getTexel(uSamplerColStrokes, uSamplerColStrokes_sampler, colStrokeIndex + iColStroke, font.uCellsImageSize);
let strokePos = getInt16(strokeIndices.xy);
let stroke0 = getTexel(uSamplerStrokes, uSamplerStrokes_sampler, strokePos + 0, font.uStrokeImageSize);
let stroke1 = getTexel(uSamplerStrokes, uSamplerStrokes_sampler, strokePos + 1, font.uStrokeImageSize);
coverageY(stroke0.xy, stroke0.zw, stroke1.xy, input.vTexCoord, pixelScale, &coverage, &weight);
}
}
weight = saturate_vec2(vec2<f32>(1.0) - weight * 2.0);
let distance = max(weight.x + weight.y, minDistance); // manhattan approx.
let antialias = abs(dot(coverage, weight) / distance);
let cover = min(abs(coverage.x), abs(coverage.y));
var outColor = vec4<f32>(font.uMaterialColor.rgb, 1.0) * font.uMaterialColor.a;
outColor = outColor * saturate_f32(max(antialias, cover));
return outColor;
}
`,N=`
struct Uniforms {
uModelViewMatrix: mat4x4<f32>,
uProjectionMatrix: mat4x4<f32>,
};
`,mn=`
struct VertexInput {
@location(0) aPosition: vec3<f32>,
@location(1) aNormal: vec3<f32>,
@location(2) aTexCoord: vec2<f32>,
@location(3) aVertexColor: vec4<f32>,
};
struct VertexOutput {
@builtin(position) Position: vec4<f32>,
@location(0) vTexCoord: vec2<f32>,
};
${N}
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@vertex
fn main(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.vTexCoord = input.aTexCoord;
let positionVec4 = vec4<f32>(input.aPosition, 1.0);
output.Position = uniforms.uProjectionMatrix * uniforms.uModelViewMatrix * positionVec4;
return output;
}
`,hn=`
struct FragmentInput {
@location(0) vTexCoord: vec2<f32>,
};
${N}
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var uSampler: texture_2d<f32>;
@group(0) @binding(2) var uSampler_sampler: sampler;
@fragment
fn main(input: FragmentInput) -> @location(0) vec4<f32> {
return textureSample(uSampler, uSampler_sampler, input.vTexCoord);
}
`;var gn=`fn mod289Vec3(x: vec3<f32>) -> vec3<f32> {
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
fn mod289Vec4(x: vec4<f32>) -> vec4<f32> {
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
fn permute(x: vec4<f32>) -> vec4<f32> {
return mod289Vec4(((x*34.0)+10.0)*x);
}
fn taylorInvSqrt(r: vec4<f32>) -> vec4<f32> {
return vec4<f32>(1.79284291400159) - vec4<f32>(0.85373472095314) * r;
}
fn baseNoise(v: vec3<f32>) -> f32 {
let C = vec2<f32>(1.0/6.0, 1.0/3.0);
let D = vec4<f32>(0.0, 0.5, 1.0, 2.0);
// First corner
var i = floor(v + dot(v, C.yyy));
let x0 = v - i + dot(i, C.xxx);
// Other corners
let g = step(x0.yzx, x0.xyz);
let l = vec3<f32>(1.0) - g;
let i1 = min(g.xyz, l.zxy);
let i2 = max(g.xyz, l.zxy);
// x0 = x0 - 0.0 + 0.0 * C.xxx;
// x1 = x0 - i1 + 1.0 * C.xxx;
// x2 = x0 - i2 + 2.0 * C.xxx;
// x3 = x0 - 1.0 + 3.0 * C.xxx;
let x1 = x0 - i1 + C.xxx;
let x2 = x0 - i2 + C.yyy; // 2.0*C.x = 1/3 = C.y
let x3 = x0 - D.yyy; // -1.0+3.0*C.x = -0.5 = -D.y
// Permutations
i = mod289Vec3(i);
let p = permute( permute( permute(
i.z + vec4<f32>(0.0, i1.z, i2.z, 1.0 ))
+ i.y + vec4<f32>(0.0, i1.y, i2.y, 1.0 ))
+ i.x + vec4<f32>(0.0, i1.x, i2.x, 1.0 ));
// Gradients: 7x7 points over a square, mapped onto an octahedron.
// The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
let n_ = 0.142857142857; // 1.0/7.0
let ns = n_ * D.wyz - D.xzx;
let j = p - 49.0 * floor(p * ns.z * ns.z); // mod(p,7*7)
let x_ = floor(j * ns.z);
let y_ = floor(j - 7.0 * x_ ); // mod(j,N)
let x = x_ *ns.x + ns.yyyy;
let y = y_ *ns.x + ns.yyyy;
let h = vec4<f32>(1.0) - abs(x) - abs(y);
let b0 = vec4<f32>( x.xy, y.xy );
let b1 = vec4<f32>( x.zw, y.zw );
//vec4 s0 = vec4(lessThan(b0,0.0))*2.0 - 1.0;
//vec4 s1 = vec4(lessThan(b1,0.0))*2.0 - 1.0;
let s0 = floor(b0)*2.0 + vec4<f32>(1.0);
let s1 = floor(b1)*2.0 + vec4<f32>(1.0);
let sh = -step(h, vec4<f32>(0.0));
let a0 = b0.xzyw + s0.xzyw*sh.xxyy;
let a1 = b1.xzyw + s1.xzyw*sh.zzww;
let p0 = vec3<f32>(a0.xy, h.x);
let p1 = vec3<f32>(a0.zw, h.y);
let p2 = vec3<f32>(a1.xy, h.z);
let p3 = vec3<f32>(a1.zw, h.w);
//Normalise gradients
let norm = taylorInvSqrt(vec4<f32>(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));
let p0_norm = p0 * norm.x;
let p1_norm = p1 * norm.y;
let p2_norm = p2 * norm.z;
let p3_norm = p3 * norm.w;
// Mix final noise value
var m = max(vec4<f32>(0.5) - vec4<f32>(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), vec4<f32>(0.0));
m = m * m;
return 105.0 * dot( m*m, vec4<f32>( dot(p0_norm,x0), dot(p1_norm,x1),
dot(p2_norm,x2), dot(p3_norm,x3) ) );
}
fn noise(st: vec3<f32>, octaves: i32, ampFalloff: f32) -> f32 {
var result = 0.0;
var amplitude = 1.0;
var frequency = 1.0;
for (var i = 0; i < 8; i++) {
if (i >= octaves) { break; }
result += amplitude * baseNoise(st * frequency);
frequency *= 2.0;
amplitude *= ampFalloff;
}
return (result + 1.0) * 0.5;
}`,_n=`
var<private> _p5_randomCallIndex: i32 = 0;
fn _p5_hash(p: vec3<f32>) -> f32 {
var p3 = fract(p * vec3<f32>(0.1031, 0.1030, 0.0973));
p3 = p3 + dot(p3, p3.yxz + 33.33);
return fract((p3.x + p3.y) * p3.z);
}
fn random(seed: f32, pixelCoord: vec2<f32>) -> f32 {
let callIndex = f32(_p5_randomCallIndex);
_p5_randomCallIndex = _p5_randomCallIndex + 1;
let s = fract(seed * 0.7548776662);
return _p5_hash(vec3<f32>(
pixelCoord.x + s,
pixelCoord.y + callIndex * 0.5698402910,
s + callIndex * 0.6180339887
));
}
`,vn=`
var<private> _p5_randomCallIndex: i32 = 0;
fn _p5_hash(p: vec3<f32>) -> f32 {
var p3 = fract(p * vec3<f32>(0.1031, 0.1030, 0.0973));
p3 = p3 + dot(p3, p3.yxz + 33.33);
return fract((p3.x + p3.y) * p3.z);
}
fn random(seed: f32, vertexId: f32) -> f32 {
let callIndex = f32(_p5_randomCallIndex);
_p5_randomCallIndex = _p5_randomCallIndex + 1;
let s = fract(seed * 0.7548776662);
return _p5_hash(vec3<f32>(
vertexId + s,
vertexId * 0.5698402910 + callIndex * 0.6180339887,
s + callIndex * 0.7548776662
));
}
`,yn=`
var<private> _p5_randomCallIndex: i32 = 0;
fn _p5_hash(p: vec3<f32>) -> f32 {
var p3 = fract(p * vec3<f32>(0.1031, 0.1030, 0.0973));
p3 = p3 + dot(p3, p3.yxz + 33.33);
return fract((p3.x + p3.y) * p3.z);
}
fn random(seed: f32, invocationId: vec3<u32>) -> f32 {
let id = vec3<f32>(invocationId);
let callIndex = f32(_p5_randomCallIndex);
_p5_randomCallIndex = _p5_randomCallIndex + 1;
let s = fract(seed * 0.7548776662);
return _p5_hash(vec3<f32>(
id.x + s,
id.y + callIndex * 0.5698402910,
id.z + s + callIndex * 0.6180339887
));
}
`,bn=`fn _p5_inverse_mat2(m: mat2x2<f32>) -> mat2x2<f32> {
let det = m[0][0] * m[1][1] - m[1][0] * m[0][1];
let invDet = 1.0 / det;
return mat2x2<f32>(
m[1][1] * invDet, -m[0][1] * invDet,
-m[1][0] * invDet, m[0][0] * invDet
);
}
fn _p5_inverse_mat3(m: mat3x3<f32>) -> mat3x3<f32> {
let a00 = m[0][0]; let a01 = m[0][1]; let a02 = m[0][2];
let a10 = m[1][0]; let a11 = m[1][1]; let a12 = m[1][2];
let a20 = m[2][0]; let a21 = m[2][1]; let a22 = m[2][2];
let b01 = a22 * a11 - a12 * a21;
let b11 = -a22 * a10 + a12 * a20;
let b21 = a21 * a10 - a11 * a20;
let det = a00 * b01 + a01 * b11 + a02 * b21;
let invDet = 1.0 / det;
return mat3x3<f32>(
b01 * invDet,
(-a22 * a01 + a02 * a21) * invDet,
( a12 * a01 - a02 * a11) * invDet,
b11 * invDet,
( a22 * a00 - a02 * a20) * invDet,
(-a12 * a00 + a02 * a10) * invDet,
b21 * invDet,
(-a21 * a00 + a01 * a20) * invDet,
( a11 * a00 - a01 * a10) * invDet
);
}
fn _p5_inverse_mat4(m: mat4x4<f32>) -> mat4x4<f32> {
let a00 = m[0][0]; let a01 = m[0][1]; let a02 = m[0][2]; let a03 = m[0][3];
let a10 = m[1][0]; let a11 = m[1][1]; let a12 = m[1][2]; let a13 = m[1][3];
let a20 = m[2][0]; let a21 = m[2][1]; let a22 = m[2][2]; let a23 = m[2][3];
let a30 = m[3][0]; let a31 = m[3][1]; let a32 = m[3][2]; let a33 = m[3][3];
let b00 = a00 * a11 - a01 * a10;
let b01 = a00 * a12 - a02 * a10;
let b02 = a00 * a13 - a03 * a10;
let b03 = a01 * a12 - a02 * a11;
let b04 = a01 * a13 - a03 * a11;
let b05 = a02 * a13 - a03 * a12;
let b06 = a20 * a31 - a21 * a30;
let b07 = a20 * a32 - a22 * a30;
let b08 = a20 * a33 - a23 * a30;
let b09 = a21 * a32 - a22 * a31;
let b10 = a21 * a33 - a23 * a31;
let b11 = a22 * a33 - a23 * a32;
let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
let invDet = 1.0 / det;
return mat4x4<f32>(
(a11 * b11 - a12 * b10 + a13 * b09) * invDet,
(a02 * b10 - a01 * b11 - a03 * b09) * invDet,
(a31 * b05 - a32 * b04 + a33 * b03) * invDet,
(a22 * b04 - a21 * b05 - a23 * b03) * invDet,
(a12 * b08 - a10 * b11 - a13 * b07) * invDet,
(a00 * b11 - a02 * b08 + a03 * b07) * invDet,
(a32 * b02 - a30 * b05 - a33 * b01) * invDet,
(a20 * b05 - a22 * b02 + a23 * b01) * invDet,
(a10 * b10 - a11 * b08 + a13 * b06) * invDet,
(a01 * b08 - a00 * b10 - a03 * b06) * invDet,
(a30 * b04 - a31 * b02 + a33 * b00) * invDet,
(a21 * b02 - a20 * b04 - a23 * b00) * invDet,
(a11 * b07 - a10 * b09 - a12 * b06) * invDet,
(a00 * b09 - a01 * b07 + a02 * b06) * invDet,
(a31 * b01 - a30 * b03 - a32 * b00) * invDet,
(a20 * b03 - a21 * b01 + a22 * b00) * invDet
);
}
`;function P(e){let t=`[p5.strands internal error]: ${e}`;throw Error(t)}function F(e,t){let n=`[p5.strands ${e}]: ${t}`;throw Error(n)}function I(e,t,n){F(`dimension mismatch`,`Cannot assign a value of dimension ${t} to \`${n}\`, which expects dimension ${e}.`)}function L(e,t){return Sn(e,t)}function R(e={}){let t={nodeType:e.nodeType??null,baseType:e.baseType??null,dimension:e.dimension??null,opCode:e.opCode??null,value:e.value??null,identifier:e.identifier??null,statementType:e.statementType??null,swizzle:e.swizzle??null,dependsOn:Array.isArray(e.dependsOn)?e.dependsOn:[],usedBy:Array.isArray(e.usedBy)?e.usedBy:[],phiBlocks:Array.isArray(e.phiBlocks)?e.phiBlocks:[]};return Cn(t),t}function z(e,t){return{id:t,nodeType:e.nodeTypes[t],opCode:e.opCodes[t],value:e.values[t],identifier:e.identifiers[t],dependsOn:e.dependsOn[t],usedBy:e.usedBy[t],phiBlocks:e.phiBlocks[t],dimension:e.dimensions[t],baseType:e.baseTypes[t],statementType:e.statementTypes[t],swizzle:e.swizzles[t]}}function xn(e,t){return{baseType:e.baseTypes[t],dimension:e.dimensions[t],priority:Yt[e.baseTypes[t]]}}function Sn(e,t){let n=e.nextID++;e.nodeTypes[n]=t.nodeType,e.opCodes[n]=t.opCode,e.values[n]=t.value,e.identifiers[n]=t.identifier,e.dependsOn[n]=t.dependsOn.slice(),e.usedBy[n]=t.usedBy,e.phiBlocks[n]=t.phiBlocks.slice(),e.baseTypes[n]=t.baseType,e.dimensions[n]=t.dimension,e.statementTypes[n]=t.statementType,e.swizzles[n]=t.swizzle;for(let r of t.dependsOn)Array.isArray(e.usedBy[r])||(e.usedBy[r]=[]),e.usedBy[r].push(n);return n}function Cn(e){let t=e.nodeType,n=Jt[t];n.length===2&&P(`Required fields for node type '${w[t]}' not defined. Please add them to the utils.js file in p5.strands!`);let r=[];for(let t of n)e[t]===null&&r.push(t);if(e.dependsOn?.some(e=>e===void 0))throw Error(`Undefined dependency!`);r.length>0&&P(`Missing fields ${r.join(`, `)} for a node type '${w[t]}'.`)}function B(e,t,n){n===void 0&&P("undefined nodeID in `recordInBasicBlock()`"),t===void 0&&P("undefined blockID in `recordInBasicBlock()"),e.blockInstructions[t]=e.blockInstructions[t]||[],e.blockInstructions[t].push(n)}var V=class{constructor(e,t,n){this.id=e,this.strandsContext=n,this.dimension=t,this.structProperties=null,this._schema=null,this.isStrandsNode=!0;let r=this.strandsContext.dag,i=z(r,this.id);i&&i.identifier&&(this._originalIdentifier=i.identifier),i&&(this._originalBaseType=i.baseType,this._originalDimension=i.dimension)}withStructProperties(e){return this.structProperties=e,this}copy(){return H(this.id,this.dimension,this.strandsContext)}typeInfo(){return{baseType:this._originalBaseType||E.FLOAT,dimension:this.dimension}}bridge(e){let{dag:t,cfg:n}=this.strandsContext,r=z(t,this.id)?.baseType??E.FLOAT,i;if(i=e?.isStrandsNode?e.id:G(this.strandsContext,{baseType:r,dimension:this.dimension},e).id,this._originalIdentifier){let r=e?.isStrandsNode?e.dimension:Array.isArray(e)?e.length:1;r!==this._originalDimension&&r!==1&&I(this._originalDimension,r,this._originalIdentifier);let{id:a}=W(this.strandsContext,{baseType:this._originalBaseType,dimension:this._originalDimension},this._originalIdentifier),o=L(t,R({nodeType:S.ASSIGNMENT,dependsOn:[a,i],phiBlocks:[]}));B(n,n.currentBlock,o);let s=L(t,R({nodeType:S.VARIABLE,baseType:this._originalBaseType,dimension:this._originalDimension,identifier:this._originalIdentifier}));this.id=s}else this.id=i;return this}bridgeSwizzle(e,t){let{dag:n,cfg:r}=this.strandsContext,i=z(n,this.id)?.baseType??E.FLOAT,a;if(a=t?.isStrandsNode?t.id:G(this.strandsContext,{baseType:i,dimension:this.dimension},t).id,this._originalIdentifier){let i=t?.isStrandsNode?t.dimension:Array.isArray(t)?t.length:1;i!==e.length&&i!==1&&I(e.length,i,`${this._originalIdentifier}.${e}`);let{id:o}=W(this.strandsContext,{baseType:this._originalBaseType,dimension:this._originalDimension},this._originalIdentifier),s=L(n,R({nodeType:S.OPERATION,opCode:k.Unary.SWIZZLE,baseType:this._originalBaseType,dimension:e.length,swizzle:e,dependsOn:[o]})),c=L(n,R({nodeType:S.ASSIGNMENT,dependsOn:[s,a],phiBlocks:[]}));B(r,r.currentBlock,c);let l=L(n,R({nodeType:S.VARIABLE,baseType:this._originalBaseType,dimension:this._originalDimension,identifier:this._originalIdentifier}));this.id=l}else this.id=a;return this}getValue(){if(this._originalIdentifier){let{id:e,dimension:t}=W(this.strandsContext,{baseType:this._originalBaseType,dimension:this._originalDimension},this._originalIdentifier);return H(e,t,this.strandsContext)}return this}get(e){if(z(this.strandsContext.dag,this.id).baseType===`storage`&&this._schema)return jn(this.strandsContext,this,e,this._schema);let{id:t,dimension:n}=An(this.strandsContext,this,e,`read`);return H(t,n,this.strandsContext)}set(e,t){if(z(this.strandsContext.dag,this.id).baseType!==`storage`)throw Error(`set() can only be used on storage buffers`);if(!this._originalIdentifier)throw Error(`set() can only be used on storage buffers with an identifier`);if(typeof t==`object`&&t&&!t.isStrandsNode&&this._schema){let n=jn(this.strandsContext,this,e,this._schema);for(let[e,r]of Object.entries(t))n[e]=r;return this}return Mn(this.strandsContext,this,e,t),this}};function H(e,t,n,r){return new Proxy(new V(e,t,n),kn(e,t,n,r))}let wn={acos:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],acosh:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],asin:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],asinh:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],atan:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0},{params:[O.FLOAT,O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],atanh:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],cos:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],cosh:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],degrees:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],radians:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],sin:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],sinh:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],tan:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],tanh:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],abs:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0},{params:[O.FLOAT],returnType:O.INT,isp5Function:!0}],ceil:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],clamp:[{params:[O.FLOAT,O.FLOAT,O.FLOAT],returnType:O.FLOAT,isp5Function:!1},{params:[O.FLOAT,D.float1,D.float1],returnType:O.FLOAT,isp5Function:!1},{params:[O.INT,O.INT,O.INT],returnType:O.INT,isp5Function:!1},{params:[O.INT,D.int1,D.int1],returnType:O.INT,isp5Function:!1}],dFdx:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],dFdy:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],exp:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],exp2:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],floor:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],fma:[{params:[O.FLOAT,O.FLOAT,O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],fract:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],fwidth:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],inversesqrt:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],log:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],log2:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],max:[{params:[O.FLOAT,O.FLOAT],returnType:O.FLOAT,isp5Function:!0},{params:[O.FLOAT,D.float1],returnType:O.FLOAT,isp5Function:!0},{params:[O.INT,O.INT],returnType:O.INT,isp5Function:!0},{params:[O.INT,D.int1],returnType:O.INT,isp5Function:!0}],min:[{params:[O.FLOAT,O.FLOAT],returnType:O.FLOAT,isp5Function:!0},{params:[O.FLOAT,D.float1],returnType:O.FLOAT,isp5Function:!0},{params:[O.INT,O.INT],returnType:O.INT,isp5Function:!0},{params:[O.INT,D.int1],returnType:O.INT,isp5Function:!0}],mix:[{params:[O.FLOAT,O.FLOAT,O.FLOAT],returnType:O.FLOAT,isp5Function:!1},{params:[O.FLOAT,O.FLOAT,D.float1],returnType:O.FLOAT,isp5Function:!1},{params:[O.FLOAT,O.FLOAT,O.BOOL],returnType:O.FLOAT,isp5Function:!1}],mod:[{params:[O.FLOAT,O.FLOAT],returnType:O.FLOAT,isp5Function:!0},{params:[O.FLOAT,D.float1],returnType:O.FLOAT,isp5Function:!0}],pow:[{params:[O.FLOAT,O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],round:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],roundEven:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],sign:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!1},{params:[O.INT],returnType:O.INT,isp5Function:!1}],smoothstep:[{params:[O.FLOAT,O.FLOAT,O.FLOAT],returnType:O.FLOAT,isp5Function:!1},{params:[D.float1,D.float1,O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],sqrt:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],step:[{params:[O.FLOAT,O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],trunc:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],cross:[{params:[D.float3,D.float3],returnType:D.float3,isp5Function:!0}],distance:[{params:[O.FLOAT,O.FLOAT],returnType:D.float1,isp5Function:!0}],dot:[{params:[O.FLOAT,O.FLOAT],returnType:D.float1,isp5Function:!0}],equal:[{params:[O.FLOAT,O.FLOAT],returnType:O.BOOL,isp5Function:!1},{params:[O.INT,O.INT],returnType:O.BOOL,isp5Function:!1},{params:[O.BOOL,O.BOOL],returnType:O.BOOL,isp5Function:!1}],faceforward:[{params:[O.FLOAT,O.FLOAT,O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],length:[{params:[O.FLOAT],returnType:D.float1,isp5Function:!1}],normalize:[{params:[O.FLOAT],returnType:O.FLOAT,isp5Function:!0}],notEqual:[{params:[O.FLOAT,O.FLOAT],returnType:O.BOOL,isp5Function:!1},{params:[O.INT,O.INT],returnType:O.BOOL,isp5Function:!1},{params:[O.BOOL,O.BOOL],returnType:O.BOOL,isp5Function:!1}],reflect:[{params:[O.FLOAT,O.FLOAT],returnType:O.FLOAT,isp5Function:!1}],refract:[{params:[O.FLOAT,O.FLOAT,D.float1],returnType:O.FLOAT,isp5Function:!1}],inverse:[{params:[D.mat2],returnType:D.mat2,isp5Function:!1},{params:[D.mat3],returnType:D.mat3,isp5Function:!1},{params:[D.mat4],returnType:D.mat4,isp5Function:!1}],transpose:[{params:[D.mat2],returnType:D.mat2,isp5Function:!1},{params:[D.mat3],returnType:D.mat3,isp5Function:!1},{params:[D.mat4],returnType:D.mat4,isp5Function:!1}]};function U(e,t,n){let{cfg:r,dag:i}=e,{dimension:a,baseType:o}=t;a!==1&&P(`Created a scalar literal node with dimension > 1.`);let s=L(i,R({nodeType:S.LITERAL,dimension:a,baseType:o,value:n}));return B(r,r.currentBlock,s),{id:s,dimension:a}}function W(e,t,n){let{cfg:r,dag:i}=e,{dimension:a,baseType:o}=t,s=L(i,R({nodeType:S.VARIABLE,dimension:a,baseType:o,identifier:n}));return B(r,r.currentBlock,s),{id:s,dimension:a}}function Tn(e,t,n){let r=Array.isArray(n)?n:[n],i=[],{dimension:a,baseType:o}=t,s=e.dag,c=0,l=null;for(let t of r.flat(1/0))if(t&&t.isStrandsNode){let e=z(s,t.id);if(l=t.id,o=e.baseType,e.opCode===k.Nary.CONSTRUCTOR)for(let t of e.dependsOn)i.push(t);else i.push(t.id);c+=e.dimension;continue}else if(typeof t==`number`){let{id:n,dimension:r}=U(e,{dimension:1,baseType:o},t);i.push(n),c+=r;continue}else if(typeof t==`boolean`){let{id:n,dimension:r}=U(e,{dimension:1,baseType:E.BOOL},t);i.push(n),c+=r,o!==E.BOOL&&(o=E.BOOL);continue}else F(`type error`,`You've tried to construct a scalar or vector type with a non-numeric value: ${t}`);a===null?a=c:a>c&&c===1?c=a:c!==1&&c!==a&&F(`type error`,`You've tried to construct a ${o+a} with ${c} components`);let u={dimension:a,baseType:o,priority:Yt[o]};return{originalNodeID:l,mappedDependencies:i,inferredTypeInfo:u}}function En(e,t,n){let r=R({nodeType:S.OPERATION,opCode:k.Nary.CONSTRUCTOR,dimension:t.dimension,baseType:t.baseType,dependsOn:n});return L(e.dag,r)}function G(e,t,n){let r=e.cfg;n=(Array.isArray(n)?n:[n]).flat(1/0).map(t=>t.isStrandsNode&&t.typeInfo().baseType===E.INT&&t.typeInfo().dimension===1?Dn(e,t):t);let{mappedDependencies:i,inferredTypeInfo:a}=Tn(e,t,n),o={baseType:a.baseType===E.BOOL?E.BOOL:t.baseType,dimension:a.dimension},s=En(e,o,i);return t.baseType!==E.DEFER&&B(r,r.currentBlock,s),{id:s,dimension:o.dimension,components:i}}function Dn(e,t){let{id:n,dimension:r}=On(e,e.backend.getTypeName(`float`,t.typeInfo().dimension),[t],{overloads:[{params:[t.typeInfo()],returnType:{...t.typeInfo(),baseType:E.FLOAT}}]});return H(n,r,e)}function On(e,t,n,{overloads:r}={}){let{cfg:i,dag:a}=e,o=r||wn[t],s=n.map(t=>Tn(e,D.defer,t)),c=o.filter(e=>e.params.length===s.length);if(c.length===0){let e=/* @__PURE__ */ new Set,n=[];o.forEach(t=>e.add(t.params.length)),e.forEach(e=>n.push(`${e}`));let r=n.join(`, or `);F(`parameter validation error`,`Function '${t}' has ${o.length} variants which expect ${r} arguments, but ${s.length} arguments were provided.`)}let l=e=>e.dimension===null,u=null,d=0,f=null,p=null;for(let e of c){let t=!0,n=0;for(let r=0;r<s.length;r++){let i=s[r].inferredTypeInfo,a=e.params[r],o=a.dimension;l(a)?((p===null||p===1)&&(p=i.dimension),p!==i.dimension&&!(i.dimension===1&&p>=1)&&(t=!1),o=p):i.dimension>o&&(t=!1),i.baseType===a.baseType?n+=2:a.priority>i.priority&&(n+=1)}t&&(!u||n>d)&&(u=e,d=n,f={...e.returnType},l(f)&&(f.dimension=p))}u===null&&F(`parameter validation`,`No matching overload for ${t} was found!`);let m=[];for(let t=0;t<u.params.length;t++){let n=s[t],r={...u.params[t]};if(l(r)&&(r.dimension=p),n.originalNodeID&&Zt(n.inferredTypeInfo,r))m.push(n.originalNodeID);else{let t=En(e,r,n.mappedDependencies);B(i,i.currentBlock,t),m.push(t)}}let h=L(a,R({nodeType:S.OPERATION,opCode:k.Nary.FUNCTION_CALL,identifier:t,dependsOn:m,baseType:f.baseType,dimension:f.dimension}));return B(i,i.currentBlock,h),{id:h,dimension:f.dimension}}function K(e,t,n){let{dag:r,cfg:i}=e,a=r.baseTypes[t.id],o=L(r,R({nodeType:S.OPERATION,baseType:a,dimension:n.length,opCode:k.Unary.SWIZZLE,dependsOn:[t.id],swizzle:n}));return B(i,i.currentBlock,o),{id:o,dimension:n.length}}function kn(e,t,n,r){let i=[[`x`,`y`,`z`,`w`],[`r`,`g`,`b`,`a`],[`s`,`t`,`p`,`q`]].map(e=>e.slice(0,t));return{get(e,t,r){if(t in e)return Reflect.get(...arguments);for(let r of i)if([...t.toString()].every(e=>r.includes(e))){let a=K(n,e,[...t].map(e=>{let t=r.indexOf(e);return i[0][t]}).join(``));return H(a.id,a.dimension,n)}},set(e,t,a,o){for(let o of i){let i=[...t];if(!(i.every(e=>o.includes(e))&&new Set(i).size===i.length&&e.dimension>=i.length))continue;let s=e.dimension,c=Array(s);for(let t=0;t<s;t++){let{id:r,dimension:i}=K(n,e,`xyzw`[t]);c[t]=H(r,i,n)}let l=[];if(a?.isStrandsNode){if(a.dimension===1)l=Array(i.length).fill(a);else if(a.dimension===i.length)for(let e=0;e<i.length;e++){let{id:t,dimension:r}=K(n,a,`xyzw`[e]);l.push(H(t,r,n))}else I(i.length,a.dimension,`${e._originalIdentifier||`value`}.${t}`)}else if(Array.isArray(a)){let e=a.flat(1/0);e.length===1?l=Array(i.length).fill(e[0]):e.length===i.length?l=e:F(`type error`,`Swizzle assignment: RHS length ${e.length} does not match ${i.length}.`)}else typeof a==`number`?l=Array(i.length).fill(a):F(`type error`,`Unsupported RHS for swizzle assignment: ${a}`);for(let e=0;e<i.length;e++){let t=o.indexOf(i[e]);c[t]=l[e]}let{id:u}=G(n,{baseType:z(n.dag,e.id)?.baseType??E.FLOAT,dimension:s},c);return e.id=u,typeof r==`function`&&r(u),!0}return Reflect.set(...arguments)}}}function An(e,t,n,r){let{dag:i,cfg:a}=e,o;if(n instanceof V)o=n;else{let{id:t,dimension:r}=G(e,{baseType:E.INT,dimension:1},n);o=H(t,r,e)}let s=L(i,R({nodeType:S.OPERATION,opCode:k.Binary.ARRAY_ACCESS,dependsOn:[t.id,o.id],dimension:1,baseType:E.FLOAT,accessMode:r}));return B(a,a.currentBlock,s),{id:s,dimension:1}}function jn(e,t,n,r){let{dag:i,cfg:a}=e,o;if(n instanceof V)o=n;else{let{id:t,dimension:r}=G(e,{baseType:E.INT,dimension:1},n);o=H(t,r,e)}let s={};for(let n of r.fields)Object.defineProperty(s,n.name,{get(){let r=R({nodeType:S.OPERATION,opCode:k.Binary.ARRAY_ACCESS,dependsOn:[t.id,o.id],dimension:n.dim,baseType:E.FLOAT,identifier:n.name}),s=L(i,r);return B(a,a.currentBlock,s),H(s,n.dim,e,e=>{let r=R({nodeType:S.OPERATION,opCode:k.Binary.ARRAY_ACCESS,dependsOn:[t.id,o.id],dimension:n.dim,baseType:E.FLOAT,identifier:n.name}),s=L(i,r),c=R({nodeType:S.ASSIGNMENT,dependsOn:[s,e],phiBlocks:[]}),l=L(i,c);B(a,a.currentBlock,l)})},set(r){let s=R({nodeType:S.OPERATION,opCode:k.Binary.ARRAY_ACCESS,dependsOn:[t.id,o.id],dimension:n.dim,baseType:E.FLOAT,identifier:n.name}),c=L(i,s),l;if(r?.isStrandsNode)l=r.id;else{let{id:t}=G(e,{baseType:E.FLOAT,dimension:n.dim},r);l=t}let u=R({nodeType:S.ASSIGNMENT,dependsOn:[c,l],phiBlocks:[]}),d=L(i,u);B(a,a.currentBlock,d)},configurable:!0});return s}function Mn(e,t,n,r){let{dag:i,cfg:a}=e,o;if(n instanceof V)o=n;else{let{id:t,dimension:r}=G(e,{baseType:E.INT,dimension:1},n);o=H(t,r,e)}let s;if(r instanceof V)s=r.typeInfo().baseType===E.FLOAT?r:Dn(e,r);else{let{id:t,dimension:n}=G(e,{baseType:E.FLOAT,dimension:1},r);s=H(t,n,e)}let c=L(i,R({nodeType:S.OPERATION,opCode:k.Binary.ARRAY_ACCESS,dependsOn:[t.id,o.id],dimension:1,baseType:E.FLOAT})),l=L(i,R({nodeType:S.ASSIGNMENT,dependsOn:[c,s.id],phiBlocks:[]}));return B(a,a.currentBlock,l),{id:l}}function Nn(e,t){return e.nodeTypes[t]!==S.OPERATION||e.baseTypes[t]===E.SAMPLER2D?!1:e.opCodes[t]===k.Unary.SNAPSHOT||(e.usedBy[t]||[]).length>1}let Pn={float1:`f32`,float2:`vec2<f32>`,float3:`vec3<f32>`,float4:`vec4<f32>`,int1:`i32`,int2:`vec2<i32>`,int3:`vec3<i32>`,int4:`vec4<i32>`,bool1:`bool`,bool2:`vec2<bool>`,bool3:`vec3<bool>`,bool4:`vec4<bool>`,mat2:`mat2x2<f32>`,mat3:`mat3x3<f32>`,mat4:`mat4x4<f32>`},q={[j.DEFAULT]:(e,t,n)=>{let{dag:r,cfg:i}=t,a=i.blockInstructions[e]||[];for(let e of a){let t=r.nodeTypes[e];if(Nn(r,e)){let t=J.generateDeclaration(n,r,e);n.write(t)}t===S.STATEMENT&&J.generateStatement(n,r,e),t===S.ASSIGNMENT&&(J.generateAssignment(n,r,e),n.visitedNodes.add(e))}},[j.BRANCH](e,t,n){let{dag:r,cfg:i}=t,a=i.blockInstructions[e]||[];for(let e of a)if(z(r,e).nodeType===S.PHI){let t=`T${n.nextTempID++}`;n.tempNames[e]=t;let i=xn(r,e),a=J.getTypeName(i.baseType,i.dimension),o;if(i.dimension===1)o=this.defaultScalarValue(i.baseType);else if(i.baseType===E.MAT)o=`${a}()`;else{let e=this.defaultScalarValue(i.baseType);o=`${a}(${Array(i.dimension).fill(e).join(`, `)})`}n.write(`var ${t}: ${a} = ${o};`)}this[j.DEFAULT](e,t,n)},defaultScalarValue(e){return e===E.FLOAT?`0.0`:e===E.BOOL?`false`:`0`},[j.IF_COND](e,t,n){let{dag:r,cfg:i}=t,a=i.blockConditions[e],o=J.generateExpression(n,r,a);n.write(`if (${o})`),this[j.DEFAULT](e,t,n)},[j.ELSE_COND](e,t,n){n.write(`else`),this[j.DEFAULT](e,t,n)},[j.IF_BODY](e,t,n){this[j.DEFAULT](e,t,n),this.assignPhiNodeValues(e,t,n)},[j.SCOPE_START](e,t,n){n.write(`{`),n.indent++},[j.SCOPE_END](e,t,n){n.indent--,n.write(`}`)},[j.MERGE](e,t,n){this[j.DEFAULT](e,t,n)},[j.FUNCTION](e,t,n){this[j.DEFAULT](e,t,n)},[j.FOR](e,t,n){let{dag:r,cfg:i}=t,a=i.blockInstructions[e]||[];n.write(`for (`);let o=n.suppressSemicolon;for(let e=0;e<a.length;e++){let t=a[e],i=z(r,t);if(n.suppressSemicolon=e===a.length-1,Nn(r,t)){let e=J.generateDeclaration(n,r,t);n.write(e)}i.nodeType===S.STATEMENT&&J.generateStatement(n,r,t),i.nodeType===S.ASSIGNMENT&&(J.generateAssignment(n,r,t),n.visitedNodes.add(t))}n.suppressSemicolon=o,n.write(`)`)},assignPhiNodeValues(e,t,n){let{dag:r,cfg:i}=t,a=i.outgoingEdges[e]||[];for(let t of a){let a=i.blockInstructions[t]||[];for(let t of a){let i=z(r,t);if(i.nodeType===S.PHI){let a=i.phiBlocks?.indexOf(e);if(a!==-1&&a<i.dependsOn.length){let e=i.dependsOn[a],o=n.tempNames[t];if(o&&e!==null){let t=J.generateExpression(n,r,e);n.write(`${o} = ${t};`)}}}}}}},J={hookEntry(e){let t=`(${e.parameters.map(e=>`${e.type.properties?`_p5_strands_raw_${e.name}`:`${qt}${e.name}`}: ${e.type.typeName}`).join(`, `)}) {`,n=e.parameters.filter(e=>e.type.properties).map(e=>` var ${qt}${e.name} = _p5_strands_raw_${e.name};`).join(`
`);return n?t+`
`+n:t},addTextureBindingsToDeclarations(e){if(!e.renderer||!e.baseShader)return;let t=e.renderer.getNextBindingIndex({vert:e.baseShader._vertSrc,frag:e.baseShader._fragSrc,compute:e.baseShader._computeSrc});for(let{name:n,typeInfo:r}of e.uniforms)if(r.baseType===`sampler2D`){let r=`@group(0) @binding(${t}) var ${n}: texture_2d<f32>;`,i=`@group(0) @binding(${t+1}) var ${n}_sampler: sampler;`;e.vertexDeclarations.add(r),e.vertexDeclarations.add(i),e.fragmentDeclarations.add(r),e.fragmentDeclarations.add(i),t+=2}},addStorageBufferBindingsToDeclarations(e){if(!e.renderer||!e.baseShader)return;let t=e.baseShader.shaderType===`compute`,n=e.renderer.getNextBindingIndex({vert:e.baseShader._vertSrc,frag:e.baseShader._fragSrc,compute:e.baseShader._computeSrc});for(let{name:r,typeInfo:i}of e.uniforms)if(i.baseType===`storage`){if(i.isStorageList)this._addStorageListBindings(e,r,i,n,t),n+=1;else{let a=t?`read_write`:`read`,o;if(i.schema){let e=`${r}Element`;o=`struct ${e} ${i.schema.structBody}\n@group(0) @binding(${n}) var<storage, ${a}> ${r}: array<${e}>;`}else o=`@group(0) @binding(${n}) var<storage, ${a}> ${r}: array<f32>;`;t?e.computeDeclarations.add(o):(e.vertexDeclarations.add(o),e.fragmentDeclarations.add(o)),n+=1}}},_addStorageListBindings(e,t,n,r,i){let{schema:a,maxCapacity:o}=n,s=a?`${t}Element`:`f32`,c=a?`struct ${s} ${a.structBody}\n`:``;if(i){let n=`${t}_buf`,i=`${c}struct ${n} { data: array<${s}, ${o}>, length: atomic<i32> }\n@group(0) @binding(${r}) var<storage, read_write> ${t}: ${n};`,l=`fn _p5_push_${t}(${a?`element: ${s}`:`value: f32`}) {\n let _idx = atomicAdd(&${t}.length, 1);\n atomicMin(&${t}.length, ${o});\n if (_idx < ${o}) { ${a?`${t}.data[_idx] = element;`:`${t}.data[_idx] = value;`} }\n}`,u=`fn _p5_pop_${t}() -> ${a?s:`f32`} {\n let _idx = atomicSub(&${t}.length, 1);\n atomicMax(&${t}.length, 0);\n return ${t}.data[_idx - 1];\n}`,d=`fn _p5_length_${t}() -> i32 {\n return atomicLoad(&${t}.length);\n}`;e.computeDeclarations.add(i),e.computeDeclarations.add(l),e.computeDeclarations.add(u),e.computeDeclarations.add(d)}else{let n=`${c}@group(0) @binding(${r}) var<storage, read> ${t}: array<${s}>;`;e.vertexDeclarations.add(n),e.fragmentDeclarations.add(n)}},_storageListDataAccess(e,t){if(e.shaderContext!==`compute`)return t;let n=e.strandsContext?.uniforms;return n&&n.find(e=>e.name===t)?.typeInfo?.isStorageList?`${t}.data`:t},getTypeName(e,t){return Pn[e+t]||e},getNoiseShaderSnippet(){return gn},getRandomFragmentShaderSnippet(){return _n},getRandomVertexShaderSnippet(){return vn},getRandomComputeShaderSnippet(){return yn},generateHookUniformKey(e,t){return t.baseType===`sampler2D`?`${e}: sampler2D`:t.baseType===`storage`?null:`${e}: ${this.getTypeName(t.baseType,t.dimension)}`},generateVaryingVariable(e,t){return`${e}: ${this.getTypeName(t.baseType,t.dimension)}`},generateLocalDeclaration(e,t){return`var<private> ${e}: ${this.getTypeName(t.baseType,t.dimension)};`},generateStatement(e,t,n){let r=z(t,n),i=e.suppressSemicolon?``:`;`;if(r.statementType===T.DISCARD)e.write(`discard${i}`);else if(r.statementType===T.BREAK)e.write(`break${i}`);else if(r.statementType===T.EXPRESSION){let n=r.dependsOn[0],a=this.generateExpression(e,t,n);e.write(`${a}${i}`)}else if(r.statementType===T.EMPTY)e.write(i);else if(r.statementType===T.EARLY_RETURN){if(r.dependsOn&&r.dependsOn.length>0){let n=r.dependsOn[0],a=this.generateExpression(e,t,n);e.write(`return ${a}${i}`)}else e.write(`return${i}`)}},generateAssignment(e,t,n){let r=z(t,n),i=r.dependsOn[0],a=r.dependsOn[1],o=z(t,i),s=e.suppressSemicolon?``:`;`;if(o.opCode===k.Binary.ARRAY_ACCESS){let[n,r]=o.dependsOn,i=this.generateExpression(e,t,n),c=this.generateExpression(e,t,r),l=this.generateExpression(e,t,a),u=o.identifier?`.${o.identifier}`:``,d=this._storageListDataAccess(e,i);e.write(`${d}[i32(${c})]${u} = ${l}${s}`)}else if(o.opCode===k.Unary.SWIZZLE){let n=o.dependsOn[0],r=z(t,n),i=this.generateExpression(e,t,n),c=o.swizzle,l=r.dimension,u=this.generateExpression(e,t,a),d=[];for(let e=0;e<l;e++)d[e]={target:`self`,index:e};let f=e=>`xyzw`.includes(e)?`xyzw`.indexOf(e):`rgba`.includes(e)?`rgba`.indexOf(e):-1;for(let e=0;e<c.length;e++){let t=f(c[e]);t>=0&&t<l&&(d[t]={target:`rhs`,index:e})}let p=this.getTypeName(r.baseType,l),m=d.map(({target:e,index:t})=>`${e===`self`?i:u}.${`xyzw`[t]}`);e.write(`${i} = ${p}(${m.join(`, `)})${s}`)}else{let n=this.generateExpression(e,t,i),r=this.generateExpression(e,t,a);n&&r&&n!==r&&e.write(`${n} = ${r}${s}`)}},generateDeclaration(e,t,n){let r=this.generateExpression(e,t,n),i=`T${e.nextTempID++}`;e.tempNames[n]=i;let a=xn(t,n);return`var ${i}: ${this.getTypeName(a.baseType,a.dimension)} = ${r};`},generateReturnStatement(e,t,n,r){if(!r){t.write(`return;`);return}let i=e.dag,a=z(i,n);if(Xt(r)&&a.identifier){let e=r;for(let n=0;n<e.properties.length;n++){let r=e.properties[n],o=this.generateExpression(t,i,a.dependsOn[n]);r.name!==o&&t.write(`${a.identifier}.${r.name} = ${o};`)}}t.write(`return ${this.generateExpression(t,i,n)};`)},generateExpression(e,t,n){let r=z(t,n);if(e.tempNames?.[n])return e.tempNames[n];switch(r.nodeType){case S.LITERAL:return r.baseType===E.FLOAT?r.value.toFixed(4):r.value;case S.VARIABLE:{if(e.shaderContext&&e.strandsContext?.sharedVariables?.has(r.identifier)){let t=e.strandsContext.sharedVariables.get(r.identifier);e.shaderContext===`vertex`?t.usedInVertex=!0:e.shaderContext===`fragment`&&(t.usedInFragment=!0)}if(r.identifier===this.instanceIdReference()&&e.shaderContext===`fragment`)return e.strandsContext._instanceIDUsedInFragment=!0,C;let t=e.strandsContext?.uniforms?.find(e=>e.name===r.identifier);return t&&t.typeInfo.baseType!==`sampler2D`&&t.typeInfo.baseType!==`storage`?`hooks.${r.identifier}`:r.identifier}case S.OPERATION:{let n=r.usedBy.length>0;if(r.opCode===k.Nary.CONSTRUCTOR)return r.baseType===E.SAMPLER2D?this.generateExpression(e,t,r.dependsOn[0]):`${this.getTypeName(r.baseType,r.dimension)}(${r.dependsOn.map(n=>this.generateExpression(e,t,n)).join(`, `)})`;if(r.opCode===k.Nary.TERNARY){let[n,i,a]=r.dependsOn,o=this.generateExpression(e,t,n),s=this.generateExpression(e,t,i);return`select(${this.generateExpression(e,t,a)}, ${s}, ${o})`}if(r.opCode===k.Nary.FUNCTION_CALL){if(r.identifier===`mod`&&r.dependsOn.length===2){let[n,i]=r.dependsOn,a=this.generateExpression(e,t,n),o=this.generateExpression(e,t,i);return r.usedBy.length>0?`(${a} % ${o})`:`${a} % ${o}`}if(r.identifier===`inverse`){let{vertexDeclarations:n,fragmentDeclarations:i,computeDeclarations:a}=e.strandsContext,o={vertex:n,fragment:i,compute:a},s=o[e.shaderContext];for(let e of s?[s]:Object.values(o))e.add(bn);let c=this.generateExpression(e,t,r.dependsOn[0]);return`_p5_inverse_mat${r.dimension}(${c})`}if(r.identifier===`atan`&&r.dependsOn.length===2)return`atan2(${r.dependsOn.map(n=>this.generateExpression(e,t,n)).join(`, `)})`;let n=r.dependsOn.map(n=>this.generateExpression(e,t,n));if(r.identifier===`random`){let t=e.shaderContext;t===`fragment`?n.push(`_p5FragPos.xy`):t===`vertex`?n.push(`f32(_p5VertexId)`):t===`compute`&&n.push(`_p5GlobalId`)}return`${r.identifier}(${n.join(`, `)})`}if(r.opCode===k.Binary.MEMBER_ACCESS){let[n,i]=r.dependsOn;return`${this.generateExpression(e,t,n)}.${this.generateExpression(e,t,i)}`}if(r.opCode===k.Unary.SNAPSHOT)return this.generateExpression(e,t,r.dependsOn[0]);if(r.opCode===k.Unary.SWIZZLE){let n=r.dependsOn[0];return`${this.generateExpression(e,t,n)}.${r.swizzle}`}if(r.opCode===k.Binary.ARRAY_ACCESS){let[n,i]=r.dependsOn,a=this.generateExpression(e,t,n),o=this.generateExpression(e,t,i),s=r.identifier?`.${r.identifier}`:``;return`${this._storageListDataAccess(e,a)}[i32(${o})]${s}`}if(r.dependsOn.length===2){let[i,a]=r.dependsOn,o=this.generateExpression(e,t,i),s=this.generateExpression(e,t,a);if(r.opCode===k.Binary.MODULO)return`(${o} % ${s})`;let c=A[r.opCode];return n?`(${o} ${c} ${s})`:`${o} ${c} ${s}`}if(r.opCode===k.Unary.LOGICAL_NOT||r.opCode===k.Unary.NEGATE||r.opCode===k.Unary.PLUS){let[n]=r.dependsOn,i=this.generateExpression(e,t,n);return`${A[r.opCode]}${i}`}return P(`Operation with opCode ${r.opCode} is not supported in expressions`)}case S.PHI:if(r.identifier)return r.identifier;if(e.tempNames?.[n])return e.tempNames[n];{let n=r.dependsOn.filter(e=>e!==null);if(n.length>0)return this.generateExpression(e,t,n[0]);throw Error(`No valid inputs for node`)}case S.ASSIGNMENT:return P(`ASSIGNMENT nodes should not be used as expressions`);default:return P(`${w[r.nodeType]} code generation not implemented yet`)}},generateBlock(e,t,n){let r=t.cfg.blockTypes[e];(q[r]||q[j.DEFAULT]).call(q,e,t,n)},createGetTextureCall(e,t){let n=t[0],r=t[1],{dag:i}=e,a=z(i,n.id).identifier+`_sampler`,o=W(e,{baseType:E.SAMPLER,dimension:1},a),s=H(o.id,o.dimension,e),c=U(e,{dimension:1,baseType:E.FLOAT},0),{id:l,dimension:u}=On(e,`textureSampleLevel`,[n,s,r,H(c.id,c.dimension,e)],{overloads:[{params:[D.sampler2D,D.sampler,D.float2,D.float1],returnType:D.float4}]});return{id:l,dimension:u}},instanceIdReference(){return`instanceID`},generateInstanceIDVarying(){return{name:C,declaration:`${C}: i32`,source:`i32(instanceID)`,interpolation:`flat`}}},Y=`
struct Uniforms {
uModelViewMatrix: mat4x4<f32>,
uProjectionMatrix: mat4x4<f32>,
uNormalMatrix: mat3x3<f32>,
roughness: f32,
};
`,Fn=`
const PI = 3.14159265359;
fn nTOE(v: vec3<f32>) -> vec2<f32> {
// x = r sin(phi) cos(theta)
// y = r cos(phi)
// z = r sin(phi) sin(theta)
let phi = acos(v.y);
// if phi is 0, then there are no x, z components
var theta = 0.0;
// else
theta = acos(v.x / sin(phi));
let sinTheta = v.z / sin(phi);
if (sinTheta < 0.0) {
// Turn it into -theta, but in the 0-2PI range
theta = 2.0 * PI - theta;
}
theta = theta / (2.0 * PI);
let phiNorm = phi / PI;
return vec2<f32>(phiNorm, theta);
}
fn random(p: vec2<f32>) -> f32 {
let p3 = fract(vec3<f32>(p.x, p.y, p.x) * 0.1031);
let dotP3 = dot(p3, p3.yzx + 33.33);
return fract((p3.x + p3.y) * p3.z);
}
`,In=`
struct VertexInput {
@location(0) aPosition: vec3<f32>,
@location(1) aNormal: vec3<f32>,
@location(2) aTexCoord: vec2<f32>,
}
struct VertexOutput {
@builtin(position) Position: vec4<f32>,
@location(0) localPos: vec3<f32>,
@location(1) vWorldNormal: vec3<f32>,
@location(2) vWorldPosition: vec3<f32>,
@location(3) vTexCoord: vec2<f32>,
}
${Y}
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@vertex
fn main(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
// Multiply the position by the matrix
let viewModelPosition = uniforms.uModelViewMatrix * vec4<f32>(input.aPosition, 1.0);
output.Position = uniforms.uProjectionMatrix * viewModelPosition;
// Orient the normals and pass to the fragment shader
output.vWorldNormal = uniforms.uNormalMatrix * input.aNormal;
// Send the view position to the fragment shader
output.vWorldPosition = viewModelPosition.xyz;
output.localPos = output.vWorldPosition;
output.vTexCoord = input.aTexCoord;
return output;
}
`,Ln=`
struct FragmentInput {
@location(0) localPos: vec3<f32>,
@location(3) vTexCoord: vec2<f32>,
}
${Y}
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var environmentMap: texture_2d<f32>;
@group(0) @binding(2) var environmentMap_sampler: sampler;
${Fn}
@fragment
fn main(input: FragmentInput) -> @location(0) vec4<f32> {
// The sample direction equals the hemisphere's orientation
let phi = input.vTexCoord.x * 2.0 * PI;
let theta = input.vTexCoord.y * PI;
let x = sin(theta) * cos(phi);
let y = sin(theta) * sin(phi);
let z = cos(theta);
let normal = vec3<f32>(x, y, z);
// Discretely sampling the hemisphere given the integral's
// spherical coordinates translates to the following fragment code:
var irradiance = vec3<f32>(0.0);
let up = vec3<f32>(0.0, 1.0, 0.0);
let right = normalize(cross(up, normal));
let upNorm = normalize(cross(normal, right));
// We specify a fixed sampleDelta delta value to traverse
// the hemisphere; decreasing or increasing the sample delta
// will increase or decrease the accuracy respectively.
let sampleDelta = 0.100;
var nrSamples = 0.0;
let randomOffset = random(input.vTexCoord) * sampleDelta;
for (var rawPhi = 0.0; rawPhi < 2.0 * PI; rawPhi += sampleDelta) {
let phiSample = rawPhi + randomOffset;
for (var rawTheta = 0.0; rawTheta < 0.5 * PI; rawTheta += sampleDelta) {
let thetaSample = rawTheta + randomOffset;
// spherical to cartesian (in tangent space) // tangent space to world // add each sample result to irradiance
let xSample = sin(thetaSample) * cos(phiSample);
let ySample = sin(thetaSample) * sin(phiSample);
let zSample = cos(thetaSample);
let tangentSample = vec3<f32>(xSample, ySample, zSample);
let sampleVec = tangentSample.x * right + tangentSample.y * upNorm + tangentSample.z * normal;
let envSample = textureSample(environmentMap, environmentMap_sampler, nTOE(sampleVec));
irradiance += envSample.xyz * cos(thetaSample) * sin(thetaSample);
nrSamples += 1.0;
}
}
// divide by the total number of samples taken, giving us the average sampled irradiance.
irradiance = PI * irradiance * (1.0 / nrSamples);
return vec4<f32>(irradiance, 1.0);
}
`,Rn=`
struct FragmentInput {
@location(0) localPos: vec3<f32>,
@location(3) vTexCoord: vec2<f32>,
}
${Y}
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var environmentMap: texture_2d<f32>;
@group(0) @binding(2) var environmentMap_sampler: sampler;
${Fn}
fn VanDerCorput(nIn: i32, base: i32) -> f32 {
// Use the bit manipulation version for WebGPU (equivalent to WEBGL2 version)
var n = u32(nIn);
n = (n << 16u) | (n >> 16u);
n = ((n & 0x55555555u) << 1u) | ((n & 0xAAAAAAAAu) >> 1u);
n = ((n & 0x33333333u) << 2u) | ((n & 0xCCCCCCCCu) >> 2u);
n = ((n & 0x0F0F0F0Fu) << 4u) | ((n & 0xF0F0F0F0u) >> 4u);
n = ((n & 0x00FF00FFu) << 8u) | ((n & 0xFF00FF00u) >> 8u);
return f32(n) * 2.3283064365386963e-10; // / 0x100000000
}
fn HammersleyNoBitOps(i: i32, N: i32) -> vec2<f32> {
return vec2<f32>(f32(i) / f32(N), VanDerCorput(i, 2));
}
fn ImportanceSampleGGX(Xi: vec2<f32>, N: vec3<f32>, roughness: f32) -> vec3<f32> {
let a = roughness * roughness;
let phi = 2.0 * PI * Xi.x;
let cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a * a - 1.0) * Xi.y));
let sinTheta = sqrt(1.0 - cosTheta * cosTheta);
// from spherical coordinates to cartesian coordinates
var H: vec3<f32>;
H.x = cos(phi) * sinTheta;
H.y = sin(phi) * sinTheta;
H.z = cosTheta;
// from tangent-space vector to world-space sample vector
let up = select(vec3<f32>(0.0, 0.0, 1.0), vec3<f32>(1.0, 0.0, 0.0), abs(N.z) < 0.999);
let tangent = normalize(cross(up, N));
let bitangent = cross(N, tangent);
let sampleVec = tangent * H.x + bitangent * H.y + N * H.z;
return normalize(sampleVec);
}
@fragment
fn main(input: FragmentInput) -> @location(0) vec4<f32> {
let SAMPLE_COUNT = 400i; // 4096
let lowRoughnessLimit = i32(pow(2.0, (uniforms.roughness + 0.1) * 20.0));
var totalWeight = 0.0;
var prefilteredColor = vec3<f32>(0.0);
let phi = input.vTexCoord.x * 2.0 * PI;
let theta = input.vTexCoord.y * PI;
let x = sin(theta) * cos(phi);
let y = sin(theta) * sin(phi);
let z = cos(theta);
let N = vec3<f32>(x, y, z);
let V = N;
for (var i = 0i; i < SAMPLE_COUNT; i++) {
// break at smaller sample numbers for low roughness levels
if (i == lowRoughnessLimit) {
break;
}
let Xi = HammersleyNoBitOps(i, SAMPLE_COUNT);
let H = ImportanceSampleGGX(Xi, N, uniforms.roughness);
let L = normalize(2.0 * dot(V, H) * H - V);
let NdotL = max(dot(N, L), 0.0);
// Always sample the texture to maintain uniform control flow
let envSample = textureSample(environmentMap, environmentMap_sampler, nTOE(L));
// Only add to accumulators if NdotL > 0
if (NdotL > 0.0) {
prefilteredColor += envSample.xyz * NdotL;
totalWeight += NdotL;
}
}
prefilteredColor = prefilteredColor / totalWeight;
return vec4<f32>(prefilteredColor, 1.0);
}
`;var X=class e{static bucket=[];static patterns=/* @__PURE__ */ new Map([[`zero`,e=>parseFloat(e)===0],[`one`,e=>parseFloat(e)===1],[`*`,()=>!0]]);static addTranslations(t,n){let r=/\$\{(.+?)\}/gm;for(let[i,a]of Object.entries(n)){let n=/* @__PURE__ */ new Map;if(typeof a==`string`){let t=a.split(r),i=[],o=[];for(let e=0;e<t.length;e++)e%2==0?i.push(t[e]):o.push(t[e]);n.set(e.patterns.get(`*`),{strings:i,placeholders:o})}else for(let[t,i]of Object.entries(a)){let a=t.split(`_`)[1],o=/\[(.+?)\]/.exec(a)?.[1],s=/\((.+?)\)/.exec(a)?.[1],c=i.split(r),l=[],u=[];for(let e=0;e<c.length;e++)e%2==0?l.push(c[e]):u.push(c[e]);n.set(e.patterns.get(o)||(s?e=>e.toString()===s:()=>!0),{strings:l,placeholders:u})}e.bucket.push({lang:Intl.getCanonicalLocales(Array.isArray(t)?t:[t]),label:i,pattern:new zn(n)})}}static tl(t,...n){return new e(Array.from(t),n)}strings;values;constructor(e,t){this.strings=e,this.values=t}toString(t){t&&=Intl.getCanonicalLocales(Array.isArray(t)?t:[t]);let n=e.bucket.find(e=>e.pattern.isMatch(this.strings));if(!n){let n=``;for(let r=0;r<this.strings.length;r++)n+=this.strings[r],this.values[r]&&(n+=this.values[r]instanceof e?this.values[r].toString(t):this.values[r]);return n}let r;r=t?t.reduce((t,r)=>(t||=e.bucket.find(e=>e.label===n.label&&e.lang.includes(r)),t),null):e.bucket.find(e=>e.label===n.label&&e.lang.filter(e=>n.lang.includes(e)).length>0),r||=n;let{strings:i,placeholders:a}=r.pattern.match(this.values[0]),{placeholders:o}=n.pattern.match(this.values[0]),s=this.values.reduce((e,t,n)=>(o[n]&&(e[o[n]]=t),e),{}),c=``;for(let t=0;t<i.length;t++){c+=i[t];let n=s[a[t]];n!==void 0&&(c+=n instanceof e?n.toString(r.lang):n)}return c}setValues(){}},zn=class{patterns;constructor(e){this.patterns=e}match(e){for(let[t,n]of this.patterns.entries())if(t(e))return n}isMatch(e){for(let{strings:t}of this.patterns.values())if(e.join(`---`)===t.join(`---`))return!0;return!1}};X.addTranslations([`en`,`en-US`,`en-GB`],{tkkbbojj0n:`Sorry, Could not set the attributes, you need to call setAttributes() before calling the other drawing methods in setup()`,wji0jlntb6:"Error during parsing: ${error.message}","6eru983h1s":`Sorry, the file type is invalid. Only OBJ and STL files are supported.`,wuo7dk4fkf:"It looks like you've called ${functionName} outside of a shader's modify() function.",ecbfo4yfrl:`It looks like you've called getTexture outside of a shader's modify() function.`,btvs56mkpo:"It looks like you've called noise() with ${args.length} arguments. It only supports 1D to 3D input.",pzoz7wj542:"It looks like you've called random() with ${args.length} arguments. In strands, random() supports 0, 1, or 2 numeric arguments.",lgfuy6eb2r:"It looks like you've called ${typeInfo.fnName} outside of a shader's modify() function.","4lplbdw1xp":`file`,dl8q3ezp00:`JSON file`,"99dup7cw27":`text file`,vzls8t7bw4:"It looks like there was a problem loading your ${errorFileType}. Try checking if the file path (${path}) is correct, hosting the file online, or running a local server.\n\n+ More info: ${infoURL}","5cz1brq3ke":`There was some trouble loading your GIF. Make sure that your GIF is using 87a or 89a encoding.`,"1kv37lrbjy":`🌸 p5.js says: `,ordinal1:`first`,ordinal2:`second`,ordinal3:`third`,ordinal4:`fourth`,ordinal5:`fifth`,ordinal6:`sixth`,ordinal7:`seventh`,ordinal8:`eighth`,ordinal9:`ninth`,ordinal10:`tenth`,typeString:`string`,typeBoolean:`boolean`,typeNumber:`number`,typeFunction:`function`,"54cbftewi2":"${message} (https://p5js.org/reference/${referenceSection}.${funcName})",rnwntgqpx8:"${message} (https://p5js.org/reference/${referenceSection}/${funcName})",jya7nlorb5:`The preload() function has been removed in p5.js 2.0. Please load assets in setup() using async / await keywords or callbacks instead. See https://github.com/processing/p5.js-compatibility for more information about 2.0 and compatibility, or https://dev.to/limzykenneth/asynchronous-p5js-20-458f for more information about promises and async/await.`,qj9oojqr1i:"It seems that you may have accidentally written ${prop} instead of ${fxns[lowercase]}. Please correct it if it's not intentional.","0t1z3tmmr8":'${locationObj\n ? FES.log`[${locationObj.file}, line ${locationObj.line}]`\n : \'\'} It seems that you may have accidentally written "${errSym}" instead of "${matchedSymbols[0].name}". Please correct it to ${matchedSymbols[0].name} if you wish to use the ${matchedSymbols[0].type} from p5.js.',ita6bv1dd3:"[${locationObj.file}, line ${locationObj.line}]","2xeoxf2b68":"${locationObj\n ? FES.log`[${locationObj.file}, line ${locationObj.line}]`\n : ''} It seems that you may have accidentally written \"${errSym}\".\\nYou may have meant one of the following: \\n${suggestions}",mfljpzrw6p:"Did you just try to use p5.js's ${symbolName} ${symbol.type}? If so, you may want to move it into your sketch's setup() function.\\n\\nFor more details, see: ${FAQ_URL}",aorhrzsojk:"Syntax Error - Found a symbol that JavaScript doesn't recognize or didn't expect at its place.\\n\\n+ More info: ${url}",xrwjb1a7yc:"Syntax Error - Symbol present at a place that wasn't expected.\\nUsually this is due to a typo. Check the line number in the error for anything missing/extra.\\n\\n+ More info: ${url}",redeclare:'Syntax Error - "${errSym}" is being redeclared. JavaScript doesn\'t allow declaring a variable more than once. Check the line number in error for redeclaration of the variable.\\n\\n+ More info: ${url}',"6tfheg3s15":"Syntax Error - A const variable is declared but not initialized. In JavaScript, an initializer for a const is required. A value must be specified in the same statement in which the variable is declared. Check the line number in the error and assign the const variable a value.\\n\\n+ More info: ${url}",ywpv6fodj4:"Syntax Error - return lies outside of a function. Make sure you’re not missing any brackets, so that return lies inside a function.\\n\\n+ More info: ${url}",a694k1m6nn:"at the ${ordinals[position]} parameter","00gwqo2yxt":", but received ${actualType}",jfjwdczlfk:"Expected ${expectedTypeStr} ${positionStr}${actualTypeStr}","1roh3zggwt":"Did you mean to put \\`await\\` before a loading function? An unexpected Promise was found. ",ltzhpuu4r8:"${message}${buildTypeMismatchMessage(actualType, expectedTypesStr, position)} in ${func + '()'}.",referenceLink:"For more information, see ${documentationLink}.",paramTooFew:{"${minArgs}_[one]":"Expected at least ${minArgs} argument, but received fewer in ${func}(). ${referenceLink}","${minArgs}_[*]":"Expected at least ${minArgs} arguments, but received fewer in ${func}(). ${referenceLink}"},paramTooMany:{"${minArgs}_[one]":"Expected at most ${maxArgs} argument, but received more in ${func}(). ${referenceLink}","${minArgs}_[*]":"Expected at most ${maxArgs} arguments, but received more in ${func}(). ${referenceLink}"},paramType:"Expected ${typeName} at the ${position} parameter in ${funcName}.",hr7vkbw7rp:"┌[${location}] \\n\\t Error at line ${frame.lineNumber} in ${frame.functionName}()\\n",zcob0p6ap3:"└[${location}] \\n\\t Called from line ${frame.lineNumber} in ${frame.functionName}()\\n",e1bltb2f3i:"The media that tried to play (with '${this.src}') wasn't allowed to by this browser, most likely due to the browser's autoplay policy.\\n\\n+ More info: https://developer.mozilla.org/docs/Web/Media/Autoplay_guide",fxcmxx850s:"${experimentalMessages[subjectArea]} For more info, see https://p5js.org/contribute/${subjectArea}/",ukmn4qp8ql:`To create a WEBGPU canvas, remember to add the WebGPU add-on to your project.`,gp2s5qktp8:"We weren't able to find a renderer called ${selectedRenderer}.",rf4evsxua3:`The GIF is over the maximum allowed dimension. Try to shrink the image or set p5.MAX_GIF_PIXELS to a higher value.`,"5szmoepgx4":`To create a WEBGPU canvas, add the WebGPU add-on to your project.`,xswmwyt2ek:`Falling back to WebGL renderer.`,fxy3ssriqw:"${e.message} Falling back to WebGL renderer."});let Z=navigator.language,Q=Gn(`localStorage`),Bn=Q?window.localStorage.getItem(`${Z}-${r}`):null,Vn=new Promise(async e=>{if(Bn)X.addTranslations(Z,JSON.parse(Bn)),e();else try{let e=await fetch(`./${Z}.json`);if(!e.ok)throw Error(`Cannot reach local file`);let t=await e.json();X.addTranslations(Z,t),Q&&window.localStorage.setItem(`${Z}-${r}`,JSON.stringify(t))}catch{try{let e=await fetch(`https://cdn.jsdelivr.net/npm/p5@${r}/translations/${Z}/extracted.json`);if(!e.ok)throw Error(`Cannot reach CDN file`);let t=await e.json();X.addTranslations(Z,t),Q&&window.localStorage.setItem(`${Z}-${r}`,JSON.stringify(t))}catch{}}finally{e()}});var Hn=class e{static languageCode=navigator.languages;static translationPromise=Vn;static disableFriendlyErrors=!1;static#e(t,n,...r){if(e.disableFriendlyErrors)return;let i=[],a=X.tl(n,...r.map(t=>{if(t instanceof Un){let n=`%c${t.message.toString(e.languageCode)}%c`;return i.push(t.styleString,``),n}return t?.message&&t?.styleStrings?(i.push(...t.styleStrings),t.message):t})),o=a.toString(e.languageCode),s=n=>{let{prefix:r}=Object.assign({prefix:X.tl`🌸 p5.js says: `},n),a=``;n?.reference&&(a+=Wn(o,n.reference)),r instanceof X?console[t](r.toString(e.languageCode)+o+a,...i):r===!1?console[t](o+a,...i):console[t](r+o+a,...i)};return s.message=o,s.styleStrings=i,s.toString=function(e){return a.toString(e)},s}static log(t,...n){return e.#e(`log`,t,...n)}static debug(t,...n){return e.#e(`debug`,t,...n)}static error(t,...n){return e.#e(`error`,t,...n)}static info(t,...n){return e.#e(`info`,t,...n)}static warn(t,...n){return e.#e(`warn`,t,...n)}static TL=X;static premade={ordinals:[X.tl`first`,X.tl`second`,X.tl`third`,X.tl`fourth`,X.tl`fifth`,X.tl`sixth`,X.tl`seventh`,X.tl`eighth`,X.tl`ninth`,X.tl`tenth`],types:{string:X.tl`string`,boolean:X.tl`boolean`,number:X.tl`number`,function:X.tl`function`}}},Un=class{message;styleString;constructor(e,t){this.message=e,this.styleString=t}toString(e){return this.message.toString(e)}};function Wn(e,t){let n=``;if(t==null||t.substring(0,4)===`load`)n=e;else{let e=t.split(`.`),r=e.length>1?`${e[0]}.${e[1]}`:`p5`,i=e.length===1?t:e.slice(2).join(`/`);n=i.startsWith(`p5.`)?` (https://p5js.org/reference/${r}.${i})`:` (https://p5js.org/reference/${r}/${i})`}return n}function Gn(e){let t;try{t=window[e];let n=`__storage_test__`;return t.setItem(n,n),t.removeItem(n),!0}catch(e){return e instanceof DOMException&&e.name===`QuotaExceededError`&&t&&t.length!==0}}let Kn={webgpu:`WEBGPU mode is experimental, so its functions and constants may change in future versions. You can get involved by giving feedback to help direct its development!`,"p5.strands":`p5.strands shaders are experimental, so functions for building shaders and the hooks available within them may change in future versions. You can get involved by giving feedback to help direct its development!`,"p5.strands.transforms":`p5.strands transforms are experimental, so transform2D(), transform3D(), the matrix constructors, and the functions that build on them may change in future versions. You can get involved by giving feedback to help direct their development!`,"p5.svg":`SVG features are experimental, so SVG export, import, and shape recording functions may change in future versions. You can get involved by giving feedback to help direct its development!`},qn={"p5.strands.transforms":{doc:`p5.strands`,section:`transforms-and-matrices`}};function Jn(e){let{doc:t=e,section:n}=qn[e]||{};return`https://p5js.org/contribute/${t}/${n?`#${n}`:``}`}let Yn={};function Xn(e,t,n){let r=t||Yn;if(!e.disableFriendlyErrors&&!r.warnedExperimental?.[n]){r.warnedExperimental=r.warnedExperimental||{},r.warnedExperimental[n]=!0;let e=Kn[n],t=Jn(n);Hn.log`${e} For more info, see ${t}`()}}let $={PENDING:0,UNPROMOTED:1,PROMOTED:2};function Zn(e,t){let{lineDefs:n}=Kt((e,t,n)=>`const ${e}: ${n} = ${t};\n`),{Renderer3D:r,Shader:i,Texture:a,MipmapTexture:o,Image:c,Camera:l,RGBA:u}=e,d={f32:Float32Array,u32:Uint32Array,i32:Int32Array};class f{constructor(e,t,n,r=null,i=Float32Array,a=null){this._isStorageBuffer=!0,this.buffer=e,this.size=t,this.length=a,this._renderer=n,this._schema=r,this._arrayType=r===null?i:Float32Array,this._checkedArrayType=void 0}update(e){let t=this._renderer.device;if(this._schema!==null){if(!Array.isArray(e)||e.length===0||typeof e[0]!=`object`||Array.isArray(e[0]))throw Error(`update() expects an array of objects matching the original struct format`);let n=this._renderer._inferStructSchema(e[0]);if(n.structBody!==this._schema.structBody)throw Error(`update() data structure doesn't match the original.\n Expected: ${this._schema.structBody}\n Got: ${n.structBody}`);let r=this._renderer._packStructArray(e,this._schema);if(r.byteLength>this.size)throw Error(`update() data (${r.byteLength} bytes) exceeds buffer size (${this.size} bytes)`);t.queue.writeBuffer(this.buffer,0,r)}else{let n=this._arrayType,r;if(e instanceof n)r=e;else if(Array.isArray(e))r=new n(e);else throw Error(`update() expects a ${n.name} or array of numbers for this buffer`);if(r.byteLength>this.size)throw Error(`update() data (${r.byteLength} bytes) exceeds buffer size (${this.size} bytes)`);t.queue.writeBuffer(this.buffer,0,r)}}async read(){let e=this._renderer.device;this._renderer.flushDraw();let t=e.createBuffer({size:this.size,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),n=e.createCommandEncoder();n.copyBufferToBuffer(this.buffer,0,t,0,this.size),e.queue.submit([n.finish()]),await t.mapAsync(GPUMapMode.READ,0,this.size);let r=t.getMappedRange(0,this.size),i=this._arrayType,a=new i(r.byteLength/i.BYTES_PER_ELEMENT);return a.set(new i(r)),t.unmap(),t.destroy(),this._schema===null?a:this._renderer._unpackStructArray(a,this._schema)}set(e,t){let n=this._renderer.device;if(this._schema!==null){if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`set() expects a plain object matching the original struct format for this buffer`);let{stride:r}=this._schema,i=e*r;if(i+r>this.size)throw Error(`set() index ${e} is out of bounds for this buffer (buffer holds ${Math.floor(this.size/r)} elements)`);let a=this._renderer._packStructArray([t],this._schema);n.queue.writeBuffer(this.buffer,i,a.buffer,0,r)}else{if(typeof t!=`number`)throw Error(`set() expects a number for this float buffer`);let r=e*4;if(r+4>this.size)throw Error(`set() index ${e} is out of bounds for this buffer (buffer holds ${Math.floor(this.size/4)} floats)`);n.queue.writeBuffer(this.buffer,r,new Float32Array([t]))}}}e.StorageBuffer=f;class p{constructor(e,t,n,r,i=null,a=0){this._isStorageList=!0,this.buffer=e,this._lengthOffset=t,this.maxCapacity=n,this._renderer=r,this._schema=i,this._stride=i?i.stride:4,this._cpuLength=a}clear(){this._cpuLength=0;let e=this._renderer.device.createCommandEncoder();e.clearBuffer(this.buffer,this._lengthOffset,4),this._renderer._pendingCommandEncoders.push(e.finish()),this._renderer._hasPendingDraws=!0}push(e){if(this._cpuLength>=this.maxCapacity)throw Error(`StorageList is full (maxCapacity: ${this.maxCapacity})`);let t=this._renderer.device,n;if(this._schema)n=this._renderer._packStructArray([e],this._schema);else{if(typeof e!=`number`)throw Error(`Float StorageList.push() expects a number`);n=new Float32Array([e])}t.queue.writeBuffer(this.buffer,this._cpuLength*this._stride,n),this._cpuLength++,t.queue.writeBuffer(this.buffer,this._lengthOffset,new Int32Array([this._cpuLength]))}update(e){if(this._schema){if(!Array.isArray(e)||e.length===0||typeof e[0]!=`object`)throw Error(`update() expects an array of objects matching the list schema`);if(e.length>this.maxCapacity)throw Error(`update() data length ${e.length} exceeds maxCapacity ${this.maxCapacity}`);let t=this._renderer._packStructArray(e,this._schema);this._renderer.device.queue.writeBuffer(this.buffer,0,t)}else{let t=e instanceof Float32Array?e:new Float32Array(e);if(t.length>this.maxCapacity)throw Error(`update() data length ${t.length} exceeds maxCapacity ${this.maxCapacity}`);this._renderer.device.queue.writeBuffer(this.buffer,0,t)}this._cpuLength=e.length,this._renderer.device.queue.writeBuffer(this.buffer,this._lengthOffset,new Int32Array([this._cpuLength]))}async read(){let e=this._renderer.device;this._renderer.flushDraw();let t=this.buffer.size,n=e.createBuffer({size:t,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),r=e.createCommandEncoder();r.copyBufferToBuffer(this.buffer,0,n,0,t),e.queue.submit([r.finish()]),await n.mapAsync(GPUMapMode.READ);let i=n.getMappedRange(),a=Math.min(new DataView(i).getInt32(this._lengthOffset,!0),this.maxCapacity),o,s=this._schema?this._schema.stride:4;if(this._schema){let e=a*s,t=new Float32Array(e/4);e>0&&t.set(new Float32Array(i,0,e/4)),o=this._renderer._unpackStructArray(t,this._schema)}else{let e=new Float32Array(a);a>0&&e.set(new Float32Array(i,0,a)),o=e}return n.unmap(),n.destroy(),o}}e.StorageList=p;class m extends r{constructor(t,n,r,i,a){super(t,n,r,i,a),this.rendererType=s,this._pInst.rendererType=this.rendererType,Xn(e,t,`webgpu`),this.activeRenderPass=null,this.activeRenderPassEncoder=null,this.activeShaderOptions=null,this.activeShader=null,this.samplers=/* @__PURE__ */ new Map,this.uniformBufferAlignment=256,this.activeUniformBuffers=[],this.currentUniformBuffer=void 0,this.uniformBufferPool=[],this.resettingUniformBuffers=[],this.dynamicEntryOffsets=/* @__PURE__ */ new Uint32Array(64),this.currentCanvasColorTexture=null,this.currentCanvasColorTextureView=null,this.pixelReadBuffer=null,this.pixelReadBufferSize=0,this.strandsBackend=J,this._shadersWithPools=[],this._geometriesWithPools=[],this._hasPendingDraws=!1,this._pendingCommandEncoders=[],this._postSubmitCallbacks=[],this._retiredBuffers=[],this._storageBuffers=/* @__PURE__ */ new Set,this._tempBuffers=[],this._pixelReadCanvas=null,this._pixelReadCtx=null,this.mainFramebuffer=null,this._frameState=$.PENDING,this.finalCamera=new l(this),this.finalCamera._computeCameraDefaultSettings(),this.finalCamera._setDefaultCamera(),this.depthFormat=`depth24plus-stencil8`,this.depthTexture=null,this.depthTextureView=null}async setupContext(){this._setAttributeDefaults(this._pInst),await this._initContext()}_setAttributeDefaults(e){let t={forceFallbackAdapter:!1,powerPreference:`high-performance`};e._webgpuAttributes=e._webgpuAttributes===null?t:Object.assign(t,e._webgpuAttributes)}async _initContext(){if(!navigator.gpu)throw Error(`WebGPU is not supported by this browser.`);if(this.adapter=await navigator.gpu.requestAdapter(this._webgpuAttributes),!this.adapter)throw Error(`No compatible GPU could be found for WebGPU on this device.`);if(this.device=await this.adapter.requestDevice({requiredFeatures:[`depth32float-stencil8`]}).catch(()=>null),!this.device)throw Error(`WebGPU is available, but a WebGPU device could not be created on this system.`);if(this.drawingContext=this.canvas.getContext(`webgpu`),!this.drawingContext)throw Error(`WebGPU is available, but the drawing context could not be created for this canvas.`);this.queue=this.device.queue,this.presentationFormat=navigator.gpu.getPreferredCanvasFormat(),this.drawingContext.configure({device:this.device,format:this.presentationFormat,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:`premultiplied`}),this.mainFramebuffer=this.createFramebuffer({_useCanvasFormat:!0}),this._updateSize(),this._update(),this.flushDraw()}async _setAttributes(t,n){if(this._pInst._webgpuAttributes===void 0){console.log(`You are trying to use setAttributes on a p5.Graphics object that does not use a WebGPU renderer.`);return}let r=!0;n===void 0?t instanceof Object&&this._pInst._webgpuAttributes!==t&&(this._pInst._webgpuAttributes=t,r=!1):(this._pInst._webgpuAttributes===null&&(this._pInst._webgpuAttributes={}),this._pInst._webgpuAttributes[t]!==n&&(this._pInst._webgpuAttributes[t]=n,r=!1)),this.isP3D&&!r&&(!this._pInst._setupDone&&this.geometryBufferCache.numCached()>0?e.FES.log`Sorry, Could not set the attributes, you need to call setAttributes() before calling the other drawing methods in setup()`():(await this._resetContext(null,null,m),this.states.curCamera&&(this.states.curCamera._renderer=this._renderer)))}_updateSize(){if(this.device&&this.depthFormat){if(this.depthTexture&&this.depthTexture.destroy){this.flushDraw();let e=this.depthTexture;this._postSubmitCallbacks.push(()=>e.destroy()),this.depthTextureView=null}this.depthTexture=this.device.createTexture({size:{width:Math.ceil(this.width*this._pixelDensity),height:Math.ceil(this.height*this._pixelDensity),depthOrArrayLayers:1},format:this.depthFormat,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),this.depthTextureView=this.depthTexture.createView(),this.clear()}}_getCanvasColorTextureView(){let e=this.drawingContext.getCurrentTexture();return this.currentCanvasColorTexture!==e&&(this.currentCanvasColorTexture=e,this.currentCanvasColorTextureView=e.createView()),this.currentCanvasColorTextureView}_beginActiveRenderPass(){if(this.activeRenderPass)return;let e=this.activeFramebuffer(),t={view:e?e.aaColorTexture?e.aaColorTextureView:e.colorTextureView:this._getCanvasColorTextureView(),loadOp:`load`,storeOp:`store`,resolveTarget:e&&e.aaColorTexture?e.colorTextureView:void 0},n=e?e.aaDepthTexture?e.aaDepthTextureView:e.depthTextureView:this.depthTextureView,r={colorAttachments:[t],depthStencilAttachment:n?{view:n,depthLoadOp:`load`,depthStoreOp:`store`,depthClearValue:1,stencilLoadOp:`load`,stencilStoreOp:`store`,depthReadOnly:!1,stencilReadOnly:!1}:void 0},i=this.device.createCommandEncoder(),a=i.beginRenderPass(r);this.activeRenderPassEncoder=i,this.activeRenderPass=a}_finishActiveRenderPass(){if(!this.activeRenderPass)return;let e=this.activeRenderPassEncoder;this.activeRenderPass.end(),this._pendingCommandEncoders.push(e.finish()),this.activeRenderPassEncoder=null,this.activeRenderPass=null,this.activeShader=null,this.activeShaderOptions=null}clear(...e){if(!this.device||!this.drawingContext)return;let t=e[0]||0,n=e[1]||0,r=e[2]||0,i=e[3]||0;this._frameState!==$.PROMOTED&&!this.activeFramebuffer()&&(this._pInst.frameCount>0?this._frameState=$.UNPROMOTED:this._promoteToFramebufferWithoutCopy()),this._finishActiveRenderPass();let a=this.device.createCommandEncoder(),o=this.activeFramebuffer(),s={view:o?o.aaColorTexture?o.aaColorTextureView:o.colorTextureView:this._getCanvasColorTextureView(),clearValue:{r:t*i,g:n*i,b:r*i,a:i},loadOp:`clear`,storeOp:`store`,resolveTarget:o&&o.aaColorTexture?o.colorTextureView:void 0},c=o?o.aaDepthTexture?o.aaDepthTextureView:o.depthTextureView:this.depthTextureView,l=c?{view:c,depthClearValue:1,depthLoadOp:`clear`,depthStoreOp:`store`,stencilLoadOp:`load`,stencilStoreOp:`store`}:void 0,u={colorAttachments:[s],...l?{depthStencilAttachment:l}:{}};a.beginRenderPass(u).end(),this._pendingCommandEncoders.push(a.finish()),this._hasPendingDraws=!0}clearDepth(e=1){if(!this.device||!this.depthTextureView)return;this._finishActiveRenderPass();let t=this.device.createCommandEncoder(),n=this.activeFramebuffer(),r=n?n.aaDepthTexture?n.aaDepthTextureView:n.depthTextureView:this.depthTextureView;if(!r)return;let i={colorAttachments:[],depthStencilAttachment:{view:r,depthClearValue:e,depthLoadOp:`clear`,depthStoreOp:`store`,stencilLoadOp:`load`,stencilStoreOp:`store`}};t.beginRenderPass(i).end(),this._pendingCommandEncoders.push(t.finish()),this._hasPendingDraws=!0}_prepareBuffer(e,t,n){let r=n.attributes[e.attr];if(!r)return;let{src:i,dst:a,size:o,map:s}=e,c=this.device,l=this._getOrMakeCachedBuffers(t),u=t[i];if(!u||u.length===0){if(e.default)u=t[i]=e.default(t),u.isDefault=!0;else return}if(!l[a]||t.dirtyFlags[i]!==!1){let e=s?s(u):u,n=this._normalizeBufferData(e,Float32Array),r=this._getVertexBufferFromPool(t,a,n.byteLength),o=new n.constructor(n);r.dataCopy=o,c.queue.writeBuffer(r.buffer,0,o),l[a]=r.buffer,t.dirtyFlags[i]=!1}n.enableAttrib(r,o)}_disableRemainingAttributes(e){}_enableAttrib(e){let t=e.location;this.registerEnabled.has(t)||this.registerEnabled.add(t)}_ensureGeometryBuffers(e,t,n){if(!t)return;let r=this.device.createBuffer({size:Math.ceil(t.length*n.BYTES_PER_ELEMENT/4)*4,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST,mappedAtCreation:!0});new n(r.getMappedRange()).set(t),r.unmap(),e.indexBuffer=r,e.indexBufferType=n===Uint32Array?`uint32`:`uint16`}_freeBuffers(e){let t=e=>{e&&e.destroy&&e.destroy()};t(e.indexBuffer);let n=n=>{for(let r of n)t(e[r.dst]),e[r.dst]=null};n(this.buffers.stroke),n(this.buffers.fill),n(this.buffers.user)}_getValidSampleCount(e){return e<=1?1:4}_shaderOptions({mode:e,compute:t,workgroupSize:n}){if(t)return{compute:!0,workgroupSize:n};let r=this.activeFramebuffer(),i=r?this._getWebGPUColorFormat(r):this.presentationFormat,a=r&&r.antialias?r.antialiasSamples:1,o=this._getValidSampleCount(a),s=r?r.useDepth?this._getWebGPUDepthFormat(r):void 0:this.depthFormat,c=this.drawTarget(),l=this._clipping,u=c._isClipApplied;return{topology:e===5?`triangle-strip`:`triangle-list`,blendMode:this.states.curBlendMode,sampleCount:o,format:i,depthFormat:s,clipping:l,clipApplied:u}}_shaderOptionsDifferent(e){if(!this.activeShaderOptions)return!0;for(let t in this.activeShaderOptions)if(this.activeShaderOptions[t]!==e[t])return!0;return!1}_initShader(e){let t=this.device;e.shaderType===`compute`?(e.computeModule=t.createShaderModule({code:e.computeSrc()}),e._computePipelineCache=null,e._workgroupSize=null,e.getPipeline=({workgroupSize:n})=>(e._computePipelineCache||(e._computePipelineCache=t.createComputePipeline({layout:e._pipelineLayout,compute:{module:e.computeModule,entryPoint:`main`}}),e._workgroupSize=n),e._computePipelineCache)):(e.vertModule=t.createShaderModule({code:e.vertSrc()}),e.fragModule=t.createShaderModule({code:e.fragSrc()}),e._pipelineCache=/* @__PURE__ */ new Map,e.getPipeline=({topology:n,blendMode:r,sampleCount:i,format:a,depthFormat:o,clipping:s,clipApplied:c})=>{let l=`${n}_${r}_${i}_${a}_${o}_${s}_${c}`;if(!e._pipelineCache.has(l)){let u=t.createRenderPipeline({layout:e._pipelineLayout,vertex:{module:e.vertModule,entryPoint:`main`,buffers:this._getVertexLayout(e)},fragment:{module:e.fragModule,entryPoint:`main`,targets:[{format:a,blend:this._getBlendState(r)}]},primitive:{topology:n},multisample:{count:i},...o?{depthStencil:{format:o,depthWriteEnabled:!s,depthCompare:`less-equal`,stencilFront:{compare:s?`always`:c?`not-equal`:`always`,failOp:`keep`,depthFailOp:`keep`,passOp:s?`replace`:`keep`},stencilBack:{compare:s?`always`:c?`not-equal`:`always`,failOp:`keep`,depthFailOp:`keep`,passOp:s?`replace`:`keep`},stencilReadMask:255,stencilWriteMask:s?255:0}}:{}});e._pipelineCache.set(l,u)}return e._pipelineCache.get(l)})}_finalizeShader(e){e._uniformBufferGroups=[],e.buffersDirty=/* @__PURE__ */ new Set;for(let t of e._uniformGroups){let n=Object.values(t.uniforms),r=Math.max(0,...n.map(e=>e.offsetEnd)),i=Math.ceil(r/16)*16;e._uniformBufferGroups.push({group:t.group,binding:t.binding,cacheKey:t.group*1e3+t.binding,varName:t.varName,structType:t.structType,uniforms:n,size:i,bufferPool:[],nextBufferPool:[],dynamic:n.some(e=>e.name.startsWith(`uModel`)),buffersInUse:/* @__PURE__ */ new Set,currentBuffer:null})}this._shadersWithPools.push(e);let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let t of e._uniformBufferGroups){let n=r.get(t.group)||[];n.push({bufferGroup:t,binding:t.binding,visibility:e.shaderType===`compute`?GPUShaderStage.COMPUTE:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:`uniform`,hasDynamicOffset:t.dynamic}}),r.set(t.group,n)}for(let[e,t]of r.entries())t.sort((e,t)=>e.binding-t.binding),n.set(e,t);for(let t of e.samplers){let e=t.group,r=n.get(e)||[];if(![`sampler`,`texture_2d<f32>`].includes(t.type))throw Error(`Unsupported texture type: ${t.type}`);r.push({binding:t.binding,visibility:t.visibility,sampler:t.type===`sampler`?{type:`filtering`}:void 0,texture:t.type===`texture_2d<f32>`?{sampleType:`float`,viewDimension:`2d`}:void 0,uniform:t}),r.sort((e,t)=>e.binding-t.binding),n.set(e,r)}for(let t of e._storageBuffers||[]){let e=t.group,r=n.get(e)||[];r.push({binding:t.binding,visibility:t.visibility,buffer:{type:t.accessMode===`read`?`read-only-storage`:`storage`},storage:t}),r.sort((e,t)=>e.binding-t.binding),n.set(e,r)}let i=[];for(let[e,r]of n){let n=this.device.createBindGroupLayout({entries:r});t.set(e,n),i.push([e,r])}e._groupEntries=i,e._bindGroupLayouts=[...t.values()],e._cachedBindGroup={},e._lastDynamicBuffer={},e._pipelineLayout=this.device.createPipelineLayout({bindGroupLayouts:e._bindGroupLayouts}),e._compiled=!0}_getBlendState(e){switch(e){case Re:return{color:{operation:`add`,srcFactor:`one`,dstFactor:`one-minus-src-alpha`},alpha:{operation:`add`,srcFactor:`one`,dstFactor:`one-minus-src-alpha`}};case Be:return{color:{operation:`add`,srcFactor:`one`,dstFactor:`one`},alpha:{operation:`add`,srcFactor:`one`,dstFactor:`one`}};case ze:return{color:{operation:`add`,srcFactor:`zero`,dstFactor:`one-minus-src-alpha`},alpha:{operation:`add`,srcFactor:`zero`,dstFactor:`one-minus-src-alpha`}};case Ge:return{color:{operation:`add`,srcFactor:`dst-color`,dstFactor:`one-minus-src-alpha`},alpha:{operation:`add`,srcFactor:`dst-alpha`,dstFactor:`one-minus-src-alpha`}};case _:return{color:{operation:`add`,srcFactor:`one`,dstFactor:`one-minus-src-color`},alpha:{operation:`add`,srcFactor:`one`,dstFactor:`one-minus-src-alpha`}};case g:return{color:{operation:`add`,srcFactor:`one-minus-dst-color`,dstFactor:`one-minus-src-color`},alpha:{operation:`add`,srcFactor:`one`,dstFactor:`one`}};case Ke:return{color:{operation:`add`,srcFactor:`one`,dstFactor:`zero`},alpha:{operation:`add`,srcFactor:`one`,dstFactor:`zero`}};case We:return{color:{operation:`reverse-subtract`,srcFactor:`one`,dstFactor:`one`},alpha:{operation:`add`,srcFactor:`one`,dstFactor:`one-minus-src-alpha`}};case Ve:return{color:{operation:`min`,srcFactor:`one`,dstFactor:`one`},alpha:{operation:`min`,srcFactor:`one`,dstFactor:`one`}};case He:return{color:{operation:`max`,srcFactor:`one`,dstFactor:`one`},alpha:{operation:`max`,srcFactor:`one`,dstFactor:`one`}};default:console.warn(`Unsupported blend mode: ${e}`);return}}_applyColorBlend(){}_getVertexLayout(e){let t=[];for(let n in e.attributes){let r=e.attributes[n];if(!r||r.location===-1)continue;let i=this.buffers[e.shaderType].find(e=>e.attr===n)||this.buffers.user.find(e=>e.attr===n);if(!i)continue;let{size:a}=i,o=this._getFormatFromSize(a);t.push({arrayStride:a*4,stepMode:`vertex`,attributes:[{shaderLocation:r.location,offset:0,format:o}]})}return t}_getVertexBuffers(e){if(!e._vertexBuffers){let t=[];for(let n in e.attributes){let r=e.attributes[n];if(!r||r.location===-1)continue;let i=this.buffers[e.shaderType].find(e=>e.attr===n)||this.buffers.user.find(e=>e.attr===n);i&&t.push(i)}e._vertexBuffers=t}return e._vertexBuffers}_getFormatFromSize(e){switch(e){case 1:return`float32`;case 2:return`float32x2`;case 3:return`float32x3`;case 4:return`float32x4`;default:throw Error(`Unsupported attribute size: ${e}`)}}_useShader(e,t){}_updateViewport(){this._origViewport={width:this.width,height:this.height},this._viewport=[0,0,this.width,this.height]}_createPixelsArray(){this.pixels=new Uint8Array(this.width*this.pixelDensity()*this.height*this.pixelDensity()*4)}supportsTriangleFan(){return!1}supportsVideoUpload(){return this._supportsVideoUpload!==!1}textureNeedsRecreating(e){if(e.isFramebufferTexture)return!1;let t=e.textureHandle.gpuTexture,n=e._getTextureDataFromSource();return!n||!n.width||!n.height?!1:n.width!==t.width||n.height!==t.height}viewport(){}zClipRange(){return[0,1]}defaultNearScale(){return .01}defaultFarScale(){return 100}_resetBuffersBeforeDraw(){this._finishActiveRenderPass(),this._pInst.frameCount>0&&(this._frameState=$.PENDING);let e=this.activeFramebuffer(),t=this.device.createCommandEncoder(),n=e?e.aaDepthTexture?e.aaDepthTextureView:e.depthTextureView:this.depthTextureView;if(n){let e={colorAttachments:[],depthStencilAttachment:{view:n,depthClearValue:1,depthLoadOp:`clear`,depthStoreOp:`store`,stencilLoadOp:`load`,stencilStoreOp:`store`}};t.beginRenderPass(e).end(),this._pendingCommandEncoders.push(t.finish()),this._hasPendingDraws=!0}}_promoteToFramebuffer(){if(this._frameState===$.PROMOTED||this.activeFramebuffer())return;this.flushDraw(),this._frameState=$.PROMOTED;let e=this.drawingContext.getCurrentTexture();(this.mainFramebuffer.width!==this.width||this.mainFramebuffer.height!==this.height)&&this.mainFramebuffer.resize(this.width,this.height);let t=this.device.createCommandEncoder();t.copyTextureToTexture({texture:e,origin:{x:0,y:0,z:0},mipLevel:0},{texture:this.mainFramebuffer.colorTexture,origin:{x:0,y:0,z:0},mipLevel:0},{width:Math.ceil(this.width*this._pixelDensity),height:Math.ceil(this.height*this._pixelDensity),depthOrArrayLayers:1}),t.copyTextureToTexture({texture:this.depthTexture,origin:{x:0,y:0,z:0},mipLevel:0},{texture:this.mainFramebuffer.depthTexture,origin:{x:0,y:0,z:0},mipLevel:0},{width:Math.ceil(this.width*this._pixelDensity),height:Math.ceil(this.height*this._pixelDensity),depthOrArrayLayers:1}),this._pendingCommandEncoders.push(t.finish()),this._hasPendingDraws=!0;let n=this.states.uModelMatrix.copy();this.states.uModelMatrix.set(this.states.uModelMatrix.copy()),this.states.uModelMatrix.reset(),this.mainFramebuffer.defaultCamera.set(this.states.curCamera),this.mainFramebuffer.begin(),this.states.uModelMatrix.set(n)}_promoteToFramebufferWithoutCopy(){if(this._frameState===$.PROMOTED)return;(this.mainFramebuffer.width!==this.width||this.mainFramebuffer.height!==this.height)&&this.mainFramebuffer.resize(this.width,this.height),this._frameState=$.PROMOTED,this.flushDraw();let e=this.states.uModelMatrix.copy();this.states.uModelMatrix.set(this.states.uModelMatrix.copy()),this.states.uModelMatrix.reset(),this.mainFramebuffer.defaultCamera.set(this.states.curCamera),this.mainFramebuffer.begin(),this.states.uModelMatrix.set(e)}_initializeGeometryBufferPools(e){e._vertexBufferPools||(e._vertexBufferPools={},e._vertexBuffersInUse={},e._vertexBuffersToReturn={},this._geometriesWithPools.push(e))}_getVertexBufferFromPool(e,t,n){this._initializeGeometryBufferPools(e),e._vertexBufferPools[t]||(e._vertexBufferPools[t]=[]),e._vertexBuffersInUse[t]||(e._vertexBuffersInUse[t]=[]),e._vertexBuffersToReturn[t]||(e._vertexBuffersToReturn[t]=[]);let r=e._vertexBufferPools[t];if(r.length>0){let i=r.pop();if(i.buffer.size>=n)return e._vertexBuffersInUse[t].push(i),i;this._retiredBuffers.push(i.buffer)}let i={buffer:this.device.createBuffer({size:n,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),size:n,dataCopy:null};return e._vertexBuffersInUse[t].push(i),i}_returnVertexBuffersToPool(){for(let e of this._geometriesWithPools)if(e._vertexBuffersToReturn){for(let[t,n]of Object.entries(e._vertexBuffersToReturn))if(n.length>0){let r=e._vertexBufferPools[t]||[];for(;n.length>0;){let e=n.pop();e.dataCopy=null,r.push(e)}e._vertexBufferPools[t]=r}}}onReset(e){this._markGeometryBuffersForReturn(e)}_markGeometryBuffersForReturn(e){if(e._vertexBuffersInUse&&e._vertexBuffersToReturn){for(let[t,n]of Object.entries(e._vertexBuffersInUse))if(n.length>0){let r=e._vertexBuffersToReturn[t]||[];for(;n.length>0;){let e=n.pop();r.push(e)}e._vertexBuffersToReturn[t]=r}}}_getUniformBufferFromPool(e){if(e.bufferPool.length>0){let t=e.bufferPool.pop();return e.buffersInUse.add(t),t}let t=this.device.createBuffer({size:e.size,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),n=new Float32Array(e.size/4),r={buffer:t,data:n,dataView:new DataView(n.buffer)};return e.buffersInUse.add(r),r}_getDynamicUniformBufferFromPool(e){let t;if(this.currentUniformBuffer&&this.currentUniformBuffer.offset+e.size<this.currentUniformBuffer.size)t=this.currentUniformBuffer;else if(this.uniformBufferPool.length>0)t=this.uniformBufferPool.pop(),this.activeUniformBuffers.push(t);else{let e=10240;t={dynamic:!0,lastOffset:0,offset:0,size:e,buffer:this.device.createBuffer({size:e,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,mappedAtCreation:!0}),uniformBuffer:this.device.createBuffer({size:e,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})},t.data=new Float32Array(t.buffer.getMappedRange()),t.dataView=new DataView(t.data.buffer),this.activeUniformBuffers.push(t)}return this.currentUniformBuffer=t,t}_returnUniformBuffersToPool(){for(let e of this._shadersWithPools)this._returnShaderBuffersToPool(e)}_returnShaderBuffersToPool(e){if(e._uniformBufferGroups)for(let t of e._uniformBufferGroups){for(;t.nextBufferPool.length>0;)t.bufferPool.push(t.nextBufferPool.pop());for(let e of t.buffersInUse.keys())e!==t.currentBuffer&&t.nextBufferPool.push(e);t.buffersInUse.clear(),t.currentBuffer&&t.buffersInUse.add(t.currentBuffer)}}flushDraw(){if(this._finishActiveRenderPass(),this._hasPendingDraws){let e=this._pendingCommandEncoders;if(this._pendingCommandEncoders=[],this._hasPendingDraws=!1,this.activeUniformBuffers.length>0){let t=this.device.createCommandEncoder();for(let e of this.activeUniformBuffers)e.buffer.unmap(),t.copyBufferToBuffer(e.buffer,e.uniformBuffer);e.unshift(t.finish())}this.queue.submit(e);let t=this._tempBuffers;this._tempBuffers=[],t.length>0&&this._postSubmitCallbacks.push(()=>{for(let e of t)e.destroy()});for(let e of this.activeUniformBuffers)e.offset=0,e.lastOffset=0,e.buffer.mapAsync(GPUMapMode.WRITE).then(()=>(e.data=new Float32Array(e.buffer.getMappedRange()),e.dataView=new DataView(e.data.buffer),this.uniformBufferPool.push(e),e));if(this.activeUniformBuffers=[],this.currentUniformBuffer=void 0,this._postSubmitCallbacks.length>0){let e=this._postSubmitCallbacks;this._postSubmitCallbacks=[],this.device.queue.onSubmittedWorkDone().then(()=>{for(let t of e)t()})}this.currentCanvasColorTexture=null,this.currentCanvasColorTextureView=null}}_ensurePixelReadCanvas(e,t){return this._pixelReadCanvas||(this._pixelReadCanvas=document.createElement(`canvas`),this._pixelReadCtx=this._pixelReadCanvas.getContext(`2d`)),(this._pixelReadCanvas.width!==e||this._pixelReadCanvas.height!==t)&&(this._pixelReadCanvas.width=e,this._pixelReadCanvas.height=t),{canvas:this._pixelReadCanvas,ctx:this._pixelReadCtx}}resize(e,t){super.resize(e,t),this._hasPendingDraws=!0,this.flushDraw()}async finishDraw(){this.flushDraw();let e=[];if(this._frameState===$.PROMOTED){for(;this.activeFramebuffers.length>0;){let t=this.activeFramebuffers.pop();e.unshift({fbo:t,diff:{...this.states}})}this.flushDraw(),this._pInst.push(),this.states.setValue(`enableLighting`,!1),this.states.setValue(`activeImageLight`,null),this._pInst.setCamera(this.finalCamera),this._pInst.shader(this._getBlitShader()),this._pInst.resetMatrix(),this._pInst.imageMode(this._pInst.CENTER),this._pInst.image(this.mainFramebuffer,0,0),this._pInst.pop(),this.flushDraw()}this._returnUniformBuffersToPool();for(let e of this._geometriesWithPools)this._markGeometryBuffersForReturn(e);this.resettingUniformBuffers=[],this._returnVertexBuffersToPool();let t=this._retiredBuffers;if(this._postSubmitCallbacks.push(()=>{for(let e of t)e&&e.destroy&&e.destroy()}),this._retiredBuffers=[],this._frameState===$.PROMOTED)for(let{fbo:t,diff:n}of e){(t!==this.mainFramebuffer||this._frameState!==$.PROMOTED)&&t.begin();for(let e in n)this.states.setValue(e,n[e])}}_drawBuffers(e,{mode:t=4,count:n=1}){let r=this.geometryBufferCache.getCached(e);if(!r)return;this._frameState===$.PENDING&&!this.activeFramebuffer()&&this._promoteToFramebufferWithoutCopy();let i=this._curShader,a=this._instanceList;if(a){this._drawBuffersIndirect(e,r,i,t,a);return}this._beginActiveRenderPass();let o=this.activeRenderPass;this.setupShaderBindGroups(i,o,{mode:t,buffers:r});for(let e of i._vertexBuffers||this._getVertexBuffers(i)){let t=i.attributes[e.attr].location,n=r[e.dst];o.setVertexBuffer(t,n,0)}if(i.shaderType===`fill`){if(r.indexBuffer){let t=r.indexFormat||`uint16`;o.setIndexBuffer(r.indexBuffer,t),o.drawIndexed(e.faces.length*3,n,0,0,0)}else o.draw(e.vertices.length,n,0,0)}else if(i.shaderType===`text`){if(!r.indexBuffer)throw Error(`Text geometry must have an index buffer`);let t=r.indexFormat||`uint16`;o.setIndexBuffer(r.indexBuffer,t),o.drawIndexed(e.faces.length*3,n,0,0,0)}r.lineVerticesBuffer&&i.shaderType===`stroke`&&o.draw(e.lineVertices.length/3,n,0,0),this._hasPendingDraws=!0}_drawBuffersIndirect(e,t,n,r,i){this._finishActiveRenderPass();let a=!!t.indexBuffer&&n.shaderType!==`stroke`,o=this.device.createBuffer({size:20,usage:GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_DST,mappedAtCreation:!0}),s=new Uint32Array(o.getMappedRange());s[0]=n.shaderType===`stroke`?e.lineVertices?e.lineVertices.length/3:0:a?e.faces.length*3:e.vertices.length,o.unmap(),this._tempBuffers.push(o);let c=this.device.createCommandEncoder();c.copyBufferToBuffer(i.buffer,i._lengthOffset,o,4,4),this._pendingCommandEncoders.push(c.finish()),this._beginActiveRenderPass();let l=this.activeRenderPass;this.setupShaderBindGroups(n,l,{mode:r,buffers:t});for(let e of n._vertexBuffers||this._getVertexBuffers(n)){let r=n.attributes[e.attr].location,i=t[e.dst];l.setVertexBuffer(r,i,0)}n.shaderType===`fill`?a?(l.setIndexBuffer(t.indexBuffer,t.indexFormat||`uint16`),l.drawIndexedIndirect(o,0)):l.drawIndirect(o,0):n.shaderType===`stroke`?t.lineVerticesBuffer&&l.drawIndirect(o,0):n.shaderType===`text`&&t.indexBuffer&&(l.setIndexBuffer(t.indexBuffer,t.indexFormat||`uint16`),l.drawIndexedIndirect(o,0)),this._hasPendingDraws=!0}setupShaderBindGroups(e,t,n){let r=this._shaderOptions(n);(r.compute||this.activeShader!==e||this._shaderOptionsDifferent(r))&&t.setPipeline(e.getPipeline(r)),r.compute||(this.activeShader=e,this.activeShaderOptions=r,this.drawTarget()._isClipApplied&&!this._clipping?t.setStencilReference(0):this._clipping&&t.setStencilReference(1));for(let t of e._uniformBufferGroups)if(t.dynamic){let n=this._getDynamicUniformBufferFromPool(t);e._lastDynamicBuffer[t.cacheKey]!==n&&(e._cachedBindGroup[t.group]=void 0,e._lastDynamicBuffer[t.cacheKey]=n),this._packUniformGroup(e,t.uniforms,n),n.lastOffset=n.offset,n.offset+=Math.ceil(t.size/this.uniformBufferAlignment)*this.uniformBufferAlignment,t.currentDynamicBuffer=n,t.lastOffset=n.lastOffset}else{let n;!this._hasGroupDataChanged(e,t)&&t.currentBuffer?(n=t.currentBuffer,t.buffersInUse.add(n)):(n=this._getUniformBufferFromPool(t),this._packUniformGroup(e,t.uniforms,n),this.device.queue.writeBuffer(n.buffer,0,n.data.buffer,n.data.byteOffset,n.data.byteLength),e.buffersDirty.delete(t.group*1e3+t.binding),e._cachedBindGroup[t.group]=void 0,t.currentBuffer=n)}for(let t of e.samplers){let n=t.group*1e3+t.binding;e.buffersDirty.has(n)&&(e._cachedBindGroup[t.group]=void 0,e.buffersDirty.delete(n))}for(let t of e._storageBuffers||[]){let n=t.group*1e3+t.binding;e.buffersDirty.has(n)&&(e._cachedBindGroup[t.group]=void 0,e.buffersDirty.delete(n))}for(let n of e._groupEntries){let r=n[0],i=n[1],a=0,o=[],s=e._cachedBindGroup[r];for(let t of i){let n=t.bufferGroup,r=n?.currentBuffer||n?.currentDynamicBuffer;if(r)n.dynamic&&(this.dynamicEntryOffsets[a++]=n.lastOffset),s||o.push({binding:t.binding,resource:n.dynamic?{buffer:r.uniformBuffer,offset:0,size:Math.ceil(n.size/this.uniformBufferAlignment)*this.uniformBufferAlignment}:{buffer:r.buffer}});else if(t.storage&&!s){let n=e.uniforms[t.storage.name];if(!n||!n._cachedData||!n._cachedData._isStorageBuffer&&!n._cachedData._isStorageList)throw Error(`Storage buffer "${t.storage.name}" not set. Use shader.setUniform("${t.storage.name}", storageBuffer)`);this._checkStorageElementType(t.storage,n._cachedData),o.push({binding:t.binding,resource:{buffer:n._cachedData.buffer}})}else s||o.push({binding:t.binding,resource:t.uniform.type===`sampler`?(t.uniform.textureSource.texture||this._getEmptyTexture()).getSampler():(t.uniform.texture||this._getEmptyTexture()).textureHandle.view})}let c=e._bindGroupLayouts[r];s||=this.device.createBindGroup({layout:c,entries:o}),e._cachedBindGroup[r]=s,a===0?t.setBindGroup(r,s):t.setBindGroup(r,s,this.dynamicEntryOffsets,0,a)}return t}_packField(e,t,n,r,i){if(t===void 0)return;t?.isVector?t=t.values.length===t.dimensions?t.values:t.values.slice(0,t.dimensions):t?.isColor&&(t=t._getRGBA([1,1,1,1]));let a=i+e.offset;if(e.baseType===`u32`){if(e.size===4)r.setUint32(a,t,!0);else for(let e=0;e<t.length;e++)r.setUint32(a+e*4,t[e],!0)}else if(e.baseType===`i32`){if(e.size===4)r.setInt32(a,t,!0);else for(let e=0;e<t.length;e++)r.setInt32(a+e*4,t[e],!0)}else if(e.packInPlace){let e=a/4;n[e+0]=t[0],n[e+1]=t[1],n[e+2]=t[2],n[e+4]=t[3],n[e+5]=t[4],n[e+6]=t[5],n[e+8]=t[6],n[e+9]=t[7],n[e+10]=t[8]}else e.size===4?n.set([t],a/4):n.set(t,a/4)}_packUniformGroup(e,t,n){let r=n.data,i=n.dataView,a=n.offset||0;for(let n of t){let t=e.uniforms[n.name];t&&!t.isSampler&&this._packField(t,t._mappedData,r,i,a)}}_hasGroupDataChanged(e,t){return!t.currentBuffer||e.buffersDirty.has(t.group*1e3+t.binding)}_parseStruct(e,t){let n=e.match(RegExp(`struct\\s+${t}\\s*\\{([^\\}]+)\\}`));if(!n)throw Error(`Can't find a struct definition for ${t}`);let r=n[1],i={},a,o=0,s=0,c=/(?:@location\((\d+)\)\s+)?(\w+):\s*([^\n]+?),?\n/g,l=e=>{if([`f32`,`i32`,`u32`,`bool`].includes(e))return{align:4,size:4,items:1,baseType:e};if(/^vec[2-4](<f32>|f)$/.test(e)){let t=parseInt(e.match(/^vec([2-4])/)[1]),n=4*t;return{align:t===2?8:16,size:n,items:t,baseType:`f32`}}if(/^vec[2-4]<(i32|u32)>$/.test(e)){let t=parseInt(e.match(/^vec([2-4])/)[1]),n=e.match(/^vec[2-4]<(i32|u32)>$/)[1],r=4*t;return{align:t===2?8:16,size:r,items:t,baseType:n}}if(/^mat[2-4](?:x[2-4])?(<f32>|f)$/.test(e)){if(e[4]===`x`&&e[3]!==e[5])throw Error(`Non-square matrices not implemented yet`);let t=parseInt(e[3]),n=t===2?8:16;return{align:n,size:Math.ceil(t*4/n)*n*t,pack:t===3?e=>[...e.slice(0,3),...e.slice(3,6),...e.slice(6,9)]:void 0,packInPlace:t===3,items:t*t,baseType:`f32`}}if(/^array<.+>$/.test(e)){let[,t,n]=e.match(/^array<(.+),\s*(\d+)>/),r=parseInt(n),{align:i,size:a,items:o,pack:s=e=>[...e],baseType:c}=l(t),u=Math.ceil(a/i)*i;return{align:i,size:u*r,items:o*r,pack:e=>{let t=[];for(let n=0;n<e.length;n+=o){let r=s(e.slice(n,o));t.push(...r);for(let e=0;e<u/4-r.length;e++)t.push(0)}return t},baseType:c}}throw Error(`Unknown type in WGSL struct: ${e}`)};for(;(a=c.exec(r))!==null;){let[,e,t,n]=a,{size:r,align:c,pack:u,packInPlace:d,baseType:f}=l(n);s=Math.ceil(s/c)*c;let p=s+r;i[t]={name:t,location:e?parseInt(e):void 0,index:o,type:n,size:r,offset:s,offsetEnd:p,pack:u,packInPlace:d,baseType:f},o++,s=p}return i}_mapUniformData(e,t){return e.pack?e.pack(t):t}_getShaderAttributes(e){let t=/fn main\(.+:\s*([^\s)]+)/.exec(e._vertSrc);if(!t)throw Error("Can't find `fn main` in vertex shader source");let n=t[1];return this._parseStruct(e.vertSrc(),n)}getUniformMetadata(e){let t=[],n=/@group\((\d+)\)\s+@binding\((\d+)\)\s+var<uniform>\s+(\w+)\s*:\s*(\w+);/g,r,i=e.shaderType===`compute`?e.computeSrc():e.vertSrc();for(;(r=n.exec(i))!==null;){let[,e,n,a,o]=r,s=parseInt(n),c=this._parseStruct(i,o);t.push({group:parseInt(e),binding:s,varName:a,structType:o,uniforms:c})}if(t.length===0&&e.shaderType!==`compute`)throw Error(`Expected at least one uniform struct bound to @group(0)`);let a={};for(let e of t)for(let[t,n]of Object.entries(e.uniforms))a[t]={...n,group:e.group,binding:e.binding,varName:e.varName};e._uniformGroups=t;let o={},s=/@group\((\d+)\)\s*@binding\((\d+)\)\s*var\s+(\w+)\s*:\s*(texture_2d<f32>|sampler);/g,c={},l=/@group\((\d+)\)\s*@binding\((\d+)\)\s*var<storage,\s*(read|read_write)>\s+(\w+)\s*:\s*(array<[\w<>, ]+>|atomic<\w+>|\w+)/g,u={};for(let e of t)u[e.group+`,`+e.binding]=!0;for(let[t,n]of[[e.vertSrc(),GPUShaderStage.VERTEX],[e.fragSrc(),GPUShaderStage.FRAGMENT],[e.computeSrc?e.computeSrc():null,GPUShaderStage.COMPUTE]]){if(!t)continue;let e;for(;(e=s.exec(t))!==null;){let[,t,r,i,a]=e,s=parseInt(t),c=parseInt(r);if(u[s+`,`+c])continue;let l=`${s},${c}`;o[l]={visibility:(o[l]?.visibility||0)|n,group:s,binding:c,name:i,type:a,isSampler:!0,noData:a===`sampler`}}for(let e of Object.values(o))if(e.type.startsWith(`texture`)){let t=e.name+`_sampler`,n=Object.values(o).find(e=>e.name===t);if(!n)throw Error(`Every shader texture needs an accompanying sampler. Could not find sampler ${t} for texture ${e.name}`);n.textureSource=e}for(;(e=l.exec(t))!==null;){let[,t,r,i,a,o]=e,s=o.match(/^array<(.+?)(?:,\s*\d+)?>$/)?.[1]??o,l=parseInt(t),u=parseInt(r),d=`${l},${u}`,f=c[d],p=f?.accessMode===`read_write`||i===`read_write`?`read_write`:i;c[d]={visibility:(f?.visibility||0)|n,group:l,binding:u,name:a,accessMode:p,isStorage:!0,type:`storage`,elementType:s,expectedArrayType:this._storageArrayTypeFor(s)}}}e._storageBuffers=Object.values(c),e._storageBuffersByName={};for(let t of e._storageBuffers)e._storageBuffersByName[t.name]=t;return[...Object.values(a).sort((e,t)=>e.index-t.index),...Object.values(o),...Object.values(c)]}getNextBindingIndex({vert:e,frag:t,compute:n},r=0){let i=/@group\((\d+)\)\s*@binding\((\d+)\)/g,a=-1,o=[];e&&o.push([e,GPUShaderStage.VERTEX]),t&&o.push([t,GPUShaderStage.FRAGMENT]),n&&o.push([n,GPUShaderStage.COMPUTE]);for(let[e]of o){let t;for(;(t=i.exec(e))!==null;){let[,e,n]=t;parseInt(e)===r&&(a=Math.max(a,parseInt(n)))}}return a+1}updateUniformValue(e,t,n){t.isSampler?t.texture=n instanceof a?n:this.getTexture(n):n?._isStorageBuffer?e._storageBuffersByName&&this._checkStorageElementType(e._storageBuffersByName[t.name],n):t._mappedData=this._mapUniformData(t,t._cachedData),e.buffersDirty.add(t.group*1e3+t.binding)}_updateTexture(e,t,n){this.textureNeedsRecreating(t)&&(t=this.getTexture(t.src),e.texture=t,n.buffersDirty.add(e.group*1e3+e.binding)),t.update()}bindTexture(e){}unbindTexture(e){}_unbindFramebufferTexture(e){}createTexture({width:e,height:t,format:n=`rgba8unorm`,usage:r}){let i=this.device.createTexture({size:[Math.max(1,e),Math.max(1,t)],format:n,usage:r||GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT});return{gpuTexture:i,view:i.createView()}}uploadTextureFromSource({gpuTexture:e},t){let n=t instanceof HTMLVideoElement;if(!(n&&t.readyState<2)){try{this.queue.copyExternalImageToTexture({source:t},{texture:e},[t.videoWidth||t.width,t.videoHeight||t.height])}catch(e){if(n&&e instanceof TypeError){this._supportsVideoUpload=!1;return}throw e}this._hasPendingDraws=!0,this.flushDraw()}}uploadTextureFromData({gpuTexture:e},t,n,r){this.queue.writeTexture({texture:e},t,{bytesPerRow:n*4,rowsPerImage:r},{width:n,height:r,depthOrArrayLayers:1}),this._hasPendingDraws=!0,this.flushDraw()}setTextureParams(e){}getSampler(e){let t=`${e.minFilter}_${e.magFilter}_${e.wrapS}_${e.wrapT}`;if(this.samplers.has(t))return this.samplers.get(t);let n={[Tt]:`nearest`,[ht]:`linear`,[Dt]:`clamp-to-edge`,[Et]:`repeat`,[v]:`mirror-repeat`},r=this.device.createSampler({magFilter:n[e.magFilter],minFilter:n[e.minFilter],addressModeU:n[e.wrapS],addressModeV:n[e.wrapT]});return this.samplers.set(t,r),r}bindTextureToShader(e,t,n,r){}deleteTexture({gpuTexture:e}){this._postSubmitCallbacks.push(()=>e.destroy())}_getLightShader(e=!1){let t=e?`_defaultLightShaderWithMaps`:`_defaultLightShader`;return this[t]||(this[t]=new i(this,un({useTextureMaps:e}),dn({useTextureMaps:e}),{vertex:{"void beforeVertex":`() {}`,"Vertex getObjectInputs":`(inputs: Vertex) { return inputs; }`,"Vertex getWorldInputs":`(inputs: Vertex) { return inputs; }`,"Vertex getCameraInputs":`(inputs: Vertex) { return inputs; }`,"void afterVertex":`() {}`},fragment:{"void beforeFragment":`() {}`,"Inputs getPixelInputs":`(inputs: Inputs) { return inputs; }`,"vec4f combineColors":`(components: ColorComponents) {
var rgb = vec3<f32>(0.0);
rgb += components.diffuse * components.baseColor;
rgb += components.ambient * components.ambientColor;
rgb += components.specular * components.specularColor;
rgb += components.emissive;
return vec4<f32>(rgb, components.opacity);
}`,"vec4f getFinalColor":`(color: vec4<f32>, texCoord: vec2<f32>) { return color; }`,"void afterFragment":`() {}`}})),this[t]}_getColorShader(){return this._defaultColorShader||=new i(this,rn,an,{vertex:{"void beforeVertex":`() {}`,"Vertex getObjectInputs":`(inputs: Vertex) { return inputs; }`,"Vertex getWorldInputs":`(inputs: Vertex) { return inputs; }`,"Vertex getCameraInputs":`(inputs: Vertex) { return inputs; }`,"void afterVertex":`() {}`},fragment:{"void beforeFragment":`() {}`,"vec4<f32> getFinalColor":`(color: vec4<f32>, texCoord: vec2<f32>) { return color; }`,"void afterFragment":`() {}`}}),this._defaultColorShader}_getLineShader(){return this._defaultLineShader||=new i(this,n+sn,n+cn,{vertex:{"void beforeVertex":`() {}`,"StrokeVertex getObjectInputs":`(inputs: StrokeVertex) { return inputs; }`,"StrokeVertex getWorldInputs":`(inputs: StrokeVertex) { return inputs; }`,"StrokeVertex getCameraInputs":`(inputs: StrokeVertex) { return inputs; }`,"void afterVertex":`() {}`},fragment:{"void beforeFragment":`() {}`,"Inputs getPixelInputs":`(inputs: Inputs) { return inputs; }`,"vec4<f32> getFinalColor":`(color: vec4<f32>, texCoord: vec2<f32>) { return color; }`,"bool shouldDiscard":`(outside: bool) { return outside; };`,"void afterFragment":`() {}`}}),this._defaultLineShader}_getFontShader(){return this._defaultFontShader||=new i(this,fn,pn),this._defaultFontShader}_getBlitShader(){return this._defaultBlitShader||=new i(this,mn,hn),this._defaultBlitShader}_adjustDimensions(e,t){return{adjustedWidth:e,adjustedHeight:t}}_applyClip(){let e=this.device.createCommandEncoder(),t=this.activeFramebuffer(),n=t?t.aaDepthTexture?t.aaDepthTextureView:t.depthTextureView:this.depthTextureView;if(!n)return;let r={colorAttachments:[],depthStencilAttachment:{view:n,stencilLoadOp:`clear`,stencilStoreOp:`store`,stencilClearValue:0,depthReadOnly:!0,stencilReadOnly:!1}};e.beginRenderPass(r).end(),this._pendingCommandEncoders.push(e.finish()),this._hasPendingDraws=!0}_unapplyClip(){}_clearClipBuffer(){this._finishActiveRenderPass();let e=this.device.createCommandEncoder(),t=this.activeFramebuffer(),n=t?t.aaDepthTexture?t.aaDepthTextureView:t.depthTextureView:this.depthTextureView;if(!n)return;let r={colorAttachments:[],depthStencilAttachment:{view:n,stencilLoadOp:`clear`,stencilStoreOp:`store`,stencilClearValue:1,depthReadOnly:!0,stencilReadOnly:!1}};e.beginRenderPass(r).end(),this._pendingCommandEncoders.push(e.finish()),this._hasPendingDraws=!0}_applyStencilTestIfClipping(){}uniformNameFromHookKey(e){return e.slice(0,e.indexOf(`:`))}populateHooks(e,t,n){if(!t.includes(`fn main`))return t;t=t.replace(/\/\/ @p5 (ifdef|ifndef) (\w+)\s+(\w+)\n((?:(?!\/\/ @p5)(?:.|\n))*)\/\/ @p5 endif/g,(t,n,r,i,a)=>{let o=n===`ifdef`;return(!!e.hooks.modified.vertex[`${r} ${i}`]||!!e.hooks.modified.fragment[`${r} ${i}`])===o?a:``});let[r,i,a]=t.split(/((?:@(?:vertex|fragment|compute)\s*(?:@workgroup_size\([^)]+\)\s*)?)?fn main[^{]+\{)/),o=(e,t)=>{let n=RegExp(`@builtin\\s*\\(\\s*${t}\\s*\\)\\s*(\\w+)\\s*:`).exec(e);return n?n[1]:null},s=(e,t,n,r)=>{let i=o(e,t);if(i)return{mainSrc:e,argName:i};let a=/\(\s*\S/.test(e);return{mainSrc:e.replace(/\)\s*(->|\{)/,`${a?`, `:``}@builtin(${t}) ${n}: ${r}) $1`),argName:n}},c=e=>{let t=/fn main\s*\(\s*(\w+)\s*:\s*(\w+)/.exec(e);return t?{inputName:t[1],structName:t[2]}:null},l=(e,t)=>{let n=RegExp(`struct\\s+${e}\\s*\\{([^}]*)\\}`,`s`).exec(r);if(!n)return null;let i=RegExp(`@builtin\\s*\\(\\s*${t}\\s*\\)\\s*(\\w+)\\s*:`,`s`).exec(n[1]);return i?i[1]:null},u=(e,t)=>{if(t.length===0)return e;let n=!/^\(\s*\)$/.test(e);return`${e.slice(0,-1)}${n?`, `:``}${t.join(`, `)})`},d=[],f=[];if(n===`vertex`){let e=s(i,`instance_index`,`instanceID`,`u32`);i=e.mainSrc;let t=s(i,`vertex_index`,`_p5VertexId`,`u32`);i=t.mainSrc,d=[`instanceID: u32`,`_p5VertexId: u32`],f=[e.argName,t.argName]}else if(n===`fragment`){let e=o(i,`position`);if(!e){let t=c(i);if(t){let n=l(t.structName,`position`);n&&(e=`${t.inputName}.${n}`)}}if(!e){let t=s(i,`position`,`_p5FragPos`,`vec4<f32>`);i=t.mainSrc,e=t.argName}d=[`_p5FragPos: vec4<f32>`],f=[e]}else if(n===`compute`){let e=s(i,`global_invocation_id`,`_p5GlobalId`,`vec3<u32>`);i=e.mainSrc,d=[`_p5GlobalId: vec3<u32>`],f=[e.argName]}let p=``;for(let t in e.hooks.uniforms)t.endsWith(`: sampler2D`)||(p+=` ${t},\n`);if(p){let t=this.getNextBindingIndex({vert:n===`vertex`?r+(e.hooks.vertex?.declarations??``)+e.hooks.declarations:e._vertSrc,frag:n===`fragment`?r+(e.hooks.fragment?.declarations??``)+e.hooks.declarations:e._fragSrc,compute:n===`compute`?r+(e.hooks.compute?.declarations??``)+e.hooks.declarations:e._computeSrc},0),i=`
// Hook Uniforms (from .modify())
struct HookUniforms {
${p}}
@group(0) @binding(${t}) var<uniform> hooks: HookUniforms;
`,a=r.replace(/(@group\(0\)\s+@binding)/,`${i}\n$1`);r=a===r?r+`
`+i:a}if(e.hooks.varyingVariables&&e.hooks.varyingVariables.length>0){let t=this._getNextAvailableLocation(r,n),i=``;for(let n of e.hooks.varyingVariables){let e=`@location(${t++}) ${n},`;i+=e+`
`}n===`vertex`?r=r.replace(/struct\s+VertexOutput\s+\{([^}]*)\}/,(e,t)=>`struct VertexOutput {${t}\n${i}}`):n===`fragment`&&(r=r.replace(/struct\s+FragmentInput\s+\{([^}]*)\}/,(e,t)=>`struct FragmentInput {${t}\n${i}}`))}if(e.hooks.varyingVariables&&e.hooks.varyingVariables.length>0){let t=``;for(let n of e.hooks.varyingVariables){let[e,r]=n.split(`:`).map(e=>e.trim());t+=`var<private> ${e}: ${r};\n`}if(r+=t,n===`vertex`){let t=``;for(let n of e.hooks.varyingVariables){let[e]=n.split(`:`).map(e=>e.trim());t+=` OUTPUT_VAR.${e} = ${e};\n`}let n=a.match(/return\s+(\w+)\s*;/);if(n){let e=n[1];t=t.replace(/OUTPUT_VAR/g,e),a=a.replace(/(return\s+\w+\s*;)/g,`${t} $1`)}}else if(n===`fragment`){let t=``;for(let n of e.hooks.varyingVariables){let[e]=n.split(`:`).map(e=>e.trim());t+=` ${e} = INPUT_VAR.${e};\n`}let n=c(i);if(n){let e=n.inputName;t=t.replace(/INPUT_VAR/g,e),a=t+a}}}if(e.hooks.instanceIDVarying){let{declaration:t,source:o,interpolation:s}=e.hooks.instanceIDVarying,l=this._getNextAvailableLocation(r,n),u=s?` @interpolate(${s})`:``,[d]=t.split(`:`).map(e=>e.trim()),f=`@location(${l})${u} ${t},`;if(n===`vertex`){r=r.replace(/struct\s+VertexOutput\s+\{([^}]*)\}/,(e,t)=>`struct VertexOutput {${t}\n${f}}`),r+=`var<private> ${t};\n`,a=`\n ${d} = ${o};\n`+a;let e=a.match(/return\s+(\w+)\s*;/);if(e){let t=e[1];a=a.replace(/(return\s+\w+\s*;)/g,`${t}.${d} = ${d};\n $1`)}}else if(n===`fragment`){r=r.replace(/struct\s+FragmentInput\s+\{([^}]*)\}/,(e,t)=>`struct FragmentInput {${t}\n${f}}`),r+=`var<private> ${t};\n`;let e=c(i);e&&(a=`\n ${d} = ${e.inputName}.${d};\n`+a)}}let m=``,h=``;e.hooks.declarations&&(m+=e.hooks.declarations+`
`),e.hooks[n]&&e.hooks[n].declarations&&(m+=e.hooks[n].declarations+`
`);for(let t in e.hooks.helpers){let[n,r]=t.split(` `),[,i,a]=/^(\([^)]*\))((?:.|\n)*)$/.exec(e.hooks.helpers[t]);m+=n===`void`?`fn ${r}${i}${a}\n`:`fn ${r}${i} -> ${n}${a}\n`}for(let t in e.hooks[n]){if(t===`declarations`)continue;let[r,i]=t.split(` `);h+=`const AUGMENTED_HOOK_${i} = ${e.hooks.modified[n][t]?`true`:`false`};\n`;let[,a,o]=/^(\([^)]*\))((?:.|\n)*)$/.exec(e.hooks[n][t]);a=u(a,d),m+=r===`void`?`fn HOOK_${i}${a}${o}\n`:`fn HOOK_${i}${a} -> ${r}${o}\n`}if(f.length>0){let e=e=>{let t=[],n=0,r;for(;(r=/HOOK_\w+\(/.exec(e.slice(n)))!==null;){let i=n+r.index+r[0].length-1,a=i+1,o=1,s=!1;for(;a<e.length&&o>0;){if(e[a]===`(`)o++;else if(e[a]===`)`){if(o--,o===0)break}else/\S/.test(e[a])&&(s=!0);a++}t.push({pos:a,hasParams:s}),n=i+1}t.sort((e,t)=>t.pos-e.pos);let i=e;for(let{pos:e,hasParams:n}of t){let t=(n?`, `:``)+f.join(`, `);i=i.slice(0,e)+t+i.slice(e)}return i};r=e(r),a=e(a)}return r+`
`+h+m+i+a}_getNextAvailableLocation(e,t){let n=-1,r=t===`vertex`?`VertexOutput`:`FragmentInput`,i=e.match(RegExp(`struct\\s+${r}\\s*\\{([^}]*)\\}`,`s`));if(i){let e=i[1].matchAll(/@location\((\d+)\)/g);for(let t of e){let e=parseInt(t[1]);e>n&&(n=e)}}return n+1}getShaderHookTypes(e,t){let n={f32:D.float1,"vec2<f32>":D.float2,"vec3<f32>":D.float3,"vec4<f32>":D.float4,vec2f:D.float2,vec3f:D.float3,vec4f:D.float4,i32:D.int1,"vec2<i32>":D.int2,"vec3<i32>":D.int3,"vec4<i32>":D.int4,bool:D.bool1,"vec2<bool>":D.bool2,"vec3<bool>":D.bool3,"vec4<bool>":D.bool4,"mat2x2<f32>":D.mat2,"mat3x3<f32>":D.mat3,"mat4x4<f32>":D.mat4,"texture_2d<f32>":D.sampler2D},r=e._vertSrc,i=e.hooks.vertex[t];if(i||(i=e.hooks.fragment[t],r=e._fragSrc),i||(i=e.hooks.compute[t],r=e._computeSrc),!i)throw Error(`Can't find hook ${t}!`);let a=t.split(/\s+/g),o=a.pop(),s=a.pop(),c=[...a],l=/\(([^)]*)\)/.exec(i);if(!l)throw Error(`Couldn't find function parameters in hook body:\n${i}`);let u=e=>{let t=RegExp(`struct\\s+${e}\\s*{([^}]*)}`).exec(r);if(!t)return;let i=[];for(let e of t[1].split(`,`)){let t=e.trim();if(!t)continue;let r=/(?:@location\([^)]*\)\s*)?(\w+)\s*:\s*([^,\s]+)/.exec(t);if(!r)continue;let a=r[1],o=r[2],s=n[o]||null,c=u(o);i.push({name:a,type:{typeName:o,qualifiers:[],properties:c,dataType:s}})}return i},d=l[1].split(`,`).map(e=>{let t=e.trim();if(!t)return null;let r=t.split(`:`).map(e=>e.trim());if(r.length!==2)return null;let i=r[0],a=r[1];a.includes(`texture_2d`)&&(a=`texture_2d<f32>`);let o=n[a]||null,s=u(a);return{name:i,type:{typeName:a,qualifiers:[],properties:s,dataType:o}}}).filter(Boolean),f=n[s]||null;return{name:o,returnType:{typeName:s,qualifiers:c,properties:u(s),dataType:f},parameters:d}}_ensurePixelReadBuffer(e){if(!this.pixelReadBuffer||this.pixelReadBufferSize<e){this.pixelReadBuffer&&(this.flushDraw(),this.pixelReadBuffer.destroy());let t=Math.max(e,this.pixelReadBufferSize*2);this.pixelReadBuffer=this.device.createBuffer({size:t,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this.pixelReadBufferSize=t}return this.pixelReadBuffer}_alignBytesPerRow(e){return Math.ceil(e/256)*256}defaultFramebufferAlpha(){return!0}defaultFramebufferAntialias(){return this._pInst._webgpuAttributes?.antialias!==!1}supportsFramebufferAntialias(){return!0}createFramebufferResources(e){}validateFramebufferFormats(e){[`unsigned-byte`,`float`,`half-float`].includes(e.format)||(console.warn(`Unknown Framebuffer format. Please use UNSIGNED_BYTE, FLOAT, or HALF_FLOAT. Defaulting to UNSIGNED_BYTE.`),e.format=b),e.useDepth&&![`unsigned-int`,`float`].includes(e.depthFormat)&&(console.warn(`Unknown Framebuffer depth format. Please use UNSIGNED_INT or FLOAT. Defaulting to FLOAT.`),e.depthFormat=x)}recreateFramebufferTextures(e){if(this.flushDraw(),e.colorTexture&&e.colorTexture.destroy){let t=e.colorTexture;this._postSubmitCallbacks.push(()=>t.destroy()),e.colorTextureView=null}if(e.aaColorTexture&&e.aaColorTexture.destroy){let t=e.aaColorTexture;this._postSubmitCallbacks.push(()=>t.destroy()),e.aaColorTextureView=null}if(e.depthTexture&&e.depthTexture.destroy){let t=e.depthTexture;this._postSubmitCallbacks.push(()=>t.destroy()),e.depthTextureView=null}if(e.aaDepthTexture&&e.aaDepthTexture.destroy){let t=e.aaDepthTexture;this._postSubmitCallbacks.push(()=>t.destroy()),e.aaDepthTextureView=null}let t={size:{width:e.width*e.density,height:e.height*e.density,depthOrArrayLayers:1},format:this._getWebGPUColorFormat(e)},n={...t,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|(e._useCanvasFormat?GPUTextureUsage.COPY_DST:0),sampleCount:1};if(e.colorTexture=this.device.createTexture(n),e.colorTextureView=e.colorTexture.createView(),e.antialias){let n={...t,usage:GPUTextureUsage.RENDER_ATTACHMENT,sampleCount:this._getValidSampleCount(e.antialiasSamples)};e.aaColorTexture=this.device.createTexture(n),e.aaColorTextureView=e.aaColorTexture.createView()}if(e.useDepth){let t={size:{width:e.width*e.density,height:e.height*e.density,depthOrArrayLayers:1},format:this._getWebGPUDepthFormat(e)},n={...t,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|(e._useCanvasFormat?GPUTextureUsage.COPY_DST:0),sampleCount:1};if(e.depthTexture=this.device.createTexture(n),e.depthTextureView=e.depthTexture.createView(),e.antialias){let n={...t,usage:GPUTextureUsage.RENDER_ATTACHMENT,sampleCount:this._getValidSampleCount(e.antialiasSamples)};e.aaDepthTexture=this.device.createTexture(n),e.aaDepthTextureView=e.aaDepthTexture.createView()}}this._clearFramebufferTextures(e)}_clearFramebufferTextures(e){this._finishActiveRenderPass();let t=this.device.createCommandEncoder(),n={view:e.aaColorTexture?e.aaColorTextureView:e.colorTextureView,loadOp:`clear`,storeOp:`store`,clearValue:{r:0,g:0,b:0,a:0},resolveTarget:e.aaColorTexture?e.colorTextureView:void 0},r=e.aaDepthTexture||e.depthTexture?{view:e.aaDepthTexture?e.aaDepthTextureView:e.depthTextureView,depthLoadOp:`clear`,depthStoreOp:`store`,depthClearValue:1,stencilLoadOp:`clear`,stencilStoreOp:`store`,depthReadOnly:!1,stencilReadOnly:!1}:void 0,i={colorAttachments:[n],depthStencilAttachment:r};t.beginRenderPass(i).end(),this._pendingCommandEncoders.push(t.finish()),this._hasPendingDraws=!0}_getFramebufferColorTextureView(e){return e.colorTexture?e.colorTextureView:null}createFramebufferTextureHandle(e){let t=e,n=this;return{get view(){return n._getFramebufferColorTextureView(t.framebuffer)},get gpuTexture(){return t.framebuffer.colorTexture}}}_jsValueToWgslType(e){if(typeof e==`number`)return`f32`;if(e?.isVector){if(e.dimensions===2)return`vec2f`;if(e.dimensions===3)return`vec3f`;if(e.dimensions===4)return`vec4f`;throw Error(`Unsupported vector dimension ${e.dimensions} for struct storage field`)}if(e?.isColor)return`vec4f`;if(Array.isArray(e)){if(e.length===2)return`vec2f`;if(e.length===3)return`vec3f`;if(e.length===4)return`vec4f`;throw Error(`Unsupported array length ${e.length} for struct storage field`)}throw Error(`Unsupported value type ${typeof e} for struct storage field`)}_inferStructSchema(t){let n=Object.entries(t);if(!e.disableFriendlyErrors)for(let[t,r]of n)typeof r==`object`&&r&&!Array.isArray(r)&&!r?.isVector&&!r?.isColor&&e._friendlyError(`The "${t}" property in your storage data contains a nested object. Make sure you only use properties with numbers, arrays of numbers, or p5.Vector.`,`createStorage`);let r=`{\n${n.map(([e,t])=>` ${e}: ${this._jsValueToWgslType(t)},`).join(`
`)}\n}`,i=this._parseStruct(`struct _Tmp ${r}`,`_Tmp`),a=0,o=1;return{fields:n.map(([e,t])=>{let n=i[e];a=Math.max(a,n.offsetEnd);let r=n.size<=4?4:n.size<=8?8:16;o=Math.max(o,r);let s=t?.isVector?`vector`:t?.isColor?`color`:void 0;return{name:e,baseType:n.baseType,size:n.size,offset:n.offset,packInPlace:n.packInPlace??!1,dim:n.size/4,kind:s}}),stride:Math.ceil(a/o)*o,structBody:r}}_packStructArray(e,t){let{fields:n,stride:r}=t,i=Math.max(e.length*r,16),a=Math.ceil(i/16)*16,o=new ArrayBuffer(a),s=new Float32Array(o),c=new DataView(o);for(let t=0;t<e.length;t++){let i=e[t],a=t*r;for(let e of n)this._packField(e,i[e.name],s,c,a)}return s}_unpackStructArray(e,t){let{fields:n,stride:r}=t,i=new DataView(e.buffer),a=Math.floor(e.byteLength/r),o=[];for(let t=0;t<a;t++){let a={},s=t*r;for(let t of n){let n=s+t.offset,r=t.size/4;if(t.baseType===`u32`)r===1?a[t.name]=i.getUint32(n,!0):a[t.name]=Array.from({length:r},(e,t)=>i.getUint32(n+t*4,!0));else if(t.baseType===`i32`)r===1?a[t.name]=i.getInt32(n,!0):a[t.name]=Array.from({length:r},(e,t)=>i.getInt32(n+t*4,!0));else{let i=n/4;if(r===1)a[t.name]=e[i];else{let n=Array.from(e.slice(i,i+r));if(t.kind===`vector`)a[t.name]=this._pInst.createVector(...n);else if(t.kind===`color`){let e=this.states.colorMaxes[this.states.colorMode];a[t.name]=this._pInst.color(n[0]*e[0],n[1]*e[1],n[2]*e[2],n[3]*e[3])}else a[t.name]=n}}}o.push(a)}return o}_storageArrayTypeFor(e){if(e)return d[e.replace(/^atomic<(\w+)>$/,`$1`)]}_checkStorageElementType(t,n){if(e.disableFriendlyErrors)return;let r=t?.expectedArrayType;r&&(n._isStorageList||n._checkedArrayType!==r&&(n._checkedArrayType=r,n._schema===null&&n._arrayType!==r&&e._friendlyError(`The storage buffer "${t.name}" is declared as array<${t.elementType}> in the shader, but it was created with a ${n._arrayType.name}. Create it with a ${r.name} instead so the values are read back correctly.`,`createStorage`)))}createStorage(t){let n=this.device;if(Array.isArray(t)&&t.length>0&&typeof t[0]==`object`&&!Array.isArray(t[0])){if(!e.disableFriendlyErrors&&t.length>1){let n=Object.keys(t[0]),r=!1;for(let i=1;i<t.length;i++){let a=t[i],o=Object.keys(a);if(!(n.length===o.length&&n.every((e,t)=>e===o[t]))){e._friendlyError(`Element ${i} has different fields than element 0. All elements should have the same properties.`,`createStorage`);break}for(let o of n){let n=this._jsValueToWgslType(t[0][o]),s=this._jsValueToWgslType(a[o]);if(n!==s){e._friendlyError(`The "${o}" property of element ${i} has type ${s} but element 0 has type ${n}. Proporties should have the same type across all elements.`,`createStorage`),r=!0;break}}if(r)break}}let r=this._inferStructSchema(t[0]),i=this._packStructArray(t,r),a=i.byteLength,o=n.createBuffer({size:a,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,mappedAtCreation:!0});new Float32Array(o.getMappedRange()).set(i),o.unmap();let s=new f(o,a,this,r,Float32Array,t.length);return this._storageBuffers.add(s),s}let r,i;if(typeof t==`number`)r=t*4,i=new Float32Array(t);else{if(ArrayBuffer.isView(t)&&!(t instanceof DataView))i=t;else if(Array.isArray(t))i=new Float32Array(t);else throw Error(`createStorage expects a number or array/TypedArray`);r=i.byteLength}let a=i.constructor;r=Math.ceil(r/16)*16;let o=n.createBuffer({size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,mappedAtCreation:i.length>0});i.length>0&&(new a(o.getMappedRange()).set(i),o.unmap());let s=new f(o,r,this,null,a,i.length);return this._storageBuffers.add(s),s}createStorageList(e,t){let n=this.device,r=null,i=0,a=null;Array.isArray(t)&&t.length>0&&typeof t[0]==`object`&&!Array.isArray(t[0])?(r=this._inferStructSchema(t[0]),a=this._packStructArray(t,r),i=t.length):t!==void 0&&typeof t==`object`&&!Array.isArray(t)&&(r=this._inferStructSchema(t));let o=e*(r?r.stride:4),s=Math.max(Math.ceil((o+4)/16)*16,16),c=n.createBuffer({size:s,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,mappedAtCreation:!0}),l=c.getMappedRange();a!==null&&new Float32Array(l).set(a),new Int32Array(l,o,1).set([i]),c.unmap();let u=new p(c,o,e,this,r,i);return this._storageBuffers.add(u),u}_getWebGPUColorFormat(e){return e.format===`float`?(e.channels,`rgba32float`):e.format===`half-float`?(e.channels,`rgba16float`):e._useCanvasFormat?this.presentationFormat:(e.channels,`rgba8unorm`)}_getWebGPUDepthFormat(e){return e._useCanvasFormat?this.depthFormat:e.useStencil?e.depthFormat===`float`?`depth32float-stencil8`:`depth24plus-stencil8`:e.depthFormat===`float`?`depth32float`:`depth24plus`}_deleteFramebufferTexture(e){this.flushDraw();let t=e.rawTexture();if(t.texture&&t.texture.destroy){let e=t.texture;this._postSubmitCallbacks.push(()=>e.destroy())}this.textures.delete(e)}deleteFramebufferTextures(e){this._deleteFramebufferTexture(e.color),e.depth&&this._deleteFramebufferTexture(e.depth)}deleteFramebufferResources(e){if(this.flushDraw(),e.colorTexture&&e.colorTexture.destroy){let t=e.colorTexture;this._postSubmitCallbacks.push(()=>t.destroy())}if(e.depthTexture&&e.depthTexture.destroy){let t=e.depthTexture;this._postSubmitCallbacks.push(()=>t.destroy())}if(e.aaDepthTexture&&e.aaDepthTexture.destroy){let t=e.aaDepthTexture;this._postSubmitCallbacks.push(()=>t.destroy())}}getFramebufferToBind(e){}updateFramebufferTexture(e,t){}bindFramebuffer(e){}framebufferYScale(){return 1}async readFramebufferPixels(e){this.flushDraw();let t=e.width*e.density,n=e.height*e.density,r=t*4,i=this._alignBytesPerRow(r),a=i*n,o=this.device.createBuffer({size:a,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),s=this.device.createCommandEncoder();s.copyTextureToBuffer({texture:e.colorTexture,origin:{x:0,y:0,z:0},mipLevel:0,aspect:`all`},{buffer:o,bytesPerRow:i,rowsPerImage:n},{width:t,height:n,depthOrArrayLayers:1}),this.device.queue.submit([s.finish()]),await o.mapAsync(GPUMapMode.READ,0,a);let c=o.getMappedRange(0,a),l;if(i===r)l=new Uint8Array(c.slice(0,t*n*4)),o.unmap();else{l=new Uint8Array(t*n*4);let e=new Uint8Array(c);for(let t=0;t<n;t++){let n=t*i,a=t*r;l.set(e.subarray(n,n+r),a)}o.unmap()}return this._ensurePixelsAreRGBA(e,l),l}async readFramebufferPixel(e,t,n){this.flushDraw();let r=this._alignBytesPerRow(4),i=r,a=this._ensurePixelReadBuffer(i),o=this.device.createCommandEncoder();o.copyTextureToBuffer({texture:e.colorTexture,origin:{x:t,y:n,z:0}},{buffer:a,bytesPerRow:r},{width:1,height:1,depthOrArrayLayers:1}),this.device.queue.submit([o.finish()]),await a.mapAsync(GPUMapMode.READ,0,i);let s=a.getMappedRange(0,i),c=new Uint8Array(s),l=[c[0],c[1],c[2],c[3]];return this._ensurePixelsAreRGBA(e,l),a.unmap(),l}async readFramebufferRegion(e,t,n,r,i){this.flushDraw();let a=r*e.density,o=i*e.density,s=a*4,l=this._alignBytesPerRow(s),u=l*o,d=this._ensurePixelReadBuffer(u),f=this.device.createCommandEncoder();f.copyTextureToBuffer({texture:e.colorTexture,mipLevel:0,origin:{x:t*e.density,y:n*e.density,z:0}},{buffer:d,bytesPerRow:l},{width:a,height:o,depthOrArrayLayers:1}),this.device.queue.submit([f.finish()]),await d.mapAsync(GPUMapMode.READ,0,u);let p=d.getMappedRange(0,u),m;if(l===s)m=new Uint8Array(p.slice(0,a*o*4));else{m=new Uint8Array(a*o*4);let e=new Uint8Array(p);for(let t=0;t<o;t++){let n=t*l,r=t*s;m.set(e.subarray(n,n+s),r)}}this._ensurePixelsAreRGBA(e,m);let h=new c(a,o);return h.imageData=h.canvas.getContext(`2d`).createImageData(a,o),h.imageData.data.set(m),h.pixels=h.imageData.data,h.updatePixels(),e.density!==1&&h.pixelDensity(e.density),d.unmap(),h}updateFramebufferPixels(e){let t=e.width*e.density,n=e.height*e.density,r=t*n*4;if(!e.pixels||e.pixels.length!==r)throw Error(`The pixels array has not been set correctly. Please call loadPixels() before updatePixels().`);this.device.queue.writeTexture({texture:e.colorTexture},e.pixels,{bytesPerRow:t*4,rowsPerImage:n},{width:t,height:n,depthOrArrayLayers:1})}_ensurePixelsAreRGBA(e,t){e._useCanvasFormat&&this.presentationFormat===`bgra8unorm`&&this._convertBGRtoRGB(t)}_convertBGRtoRGB(e){for(let t=0;t<e.length;t+=4){let n=e[t];e[t]=e[t+2],e[t+2]=n}}async loadPixels(){this._promoteToFramebuffer(),await this.mainFramebuffer.loadPixels(),this.pixels=this.mainFramebuffer.pixels.slice()}async get(e,t,n,r){return this._promoteToFramebuffer(),this.mainFramebuffer.get(e,t,n,r)}filter(...e){return this.activeFramebuffer()||this._promoteToFramebuffer(),super.filter(...e)}baseFilterShader(){return this._baseFilterShader||=new i(this,`
// Group 0: Filter Properties
struct FilterUniforms {
canvasSize: vec2<f32>,
texelSize: vec2<f32>,
}
// Group 1: Model Transform
struct ModelUniforms {
uModelViewMatrix: mat4x4<f32>,
}
// Group 2: Camera and Projection
struct CameraUniforms {
uProjectionMatrix: mat4x4<f32>,
}
@group(0) @binding(0) var<uniform> filterParams: FilterUniforms;
@group(0) @binding(1) var tex0: texture_2d<f32>;
@group(0) @binding(2) var tex0_sampler: sampler;
@group(1) @binding(0) var<uniform> model: ModelUniforms;
@group(2) @binding(0) var<uniform> camera: CameraUniforms;
struct VertexInput {
@location(0) aPosition: vec3<f32>,
@location(1) aTexCoord: vec2<f32>,
}
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@location(0) vTexCoord: vec2<f32>,
}
@vertex
fn main(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
// transferring texcoords for the frag shader
output.vTexCoord = input.aTexCoord;
// copy position with a fourth coordinate for projection (1.0 is normal)
let positionVec4 = vec4<f32>(input.aPosition, 1.0);
// project to 3D space
output.position = camera.uProjectionMatrix * model.uModelViewMatrix * positionVec4;
return output;
}
`,`
// Group 0: Filter Properties
struct FilterUniforms {
canvasSize: vec2<f32>,
texelSize: vec2<f32>,
}
// Group 1: Model Transform
struct ModelUniforms {
uModelViewMatrix: mat4x4<f32>,
}
// Group 2: Camera and Projection
struct CameraUniforms {
uProjectionMatrix: mat4x4<f32>,
}
@group(0) @binding(0) var<uniform> filterParams: FilterUniforms;
@group(0) @binding(1) var tex0: texture_2d<f32>;
@group(0) @binding(2) var tex0_sampler: sampler;
@group(1) @binding(0) var<uniform> model: ModelUniforms;
@group(2) @binding(0) var<uniform> camera: CameraUniforms;
struct FilterInputs {
texCoord: vec2<f32>,
canvasSize: vec2<f32>,
texelSize: vec2<f32>,
}
struct FragmentInput {
@location(0) vTexCoord: vec2<f32>,
}
struct FragmentOutput {
@location(0) color: vec4<f32>,
}
@fragment
fn main(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
var inputs: FilterInputs;
inputs.texCoord = input.vTexCoord;
inputs.canvasSize = filterParams.canvasSize;
inputs.texelSize = filterParams.texelSize;
var outColor = HOOK_getColor(inputs, tex0, tex0_sampler);
outColor = vec4<f32>(outColor.rgb * outColor.a, outColor.a);
output.color = outColor;
return output;
}
`,{vertex:{},fragment:{"vec4<f32> getColor":`(inputs: FilterInputs, canvasContent: texture_2d<f32>, canvasContent_sampler: sampler) -> vec4<f32> {
return textureSample(tex, tex_sampler, inputs.texCoord);
}`},hookAliases:{getColor:[`filterColor`]}}),this._baseFilterShader}baseComputeShader(){return this._baseComputeShader||=new i(this,`
struct ComputeUniforms {
uTotalCount: vec3<i32>,
uPhysicalCount: vec3<i32>,
}
@group(0) @binding(0) var<uniform> uniforms: ComputeUniforms;
@compute @workgroup_size(8, 8, 1)
fn main(
@builtin(global_invocation_id) globalId: vec3<u32>,
@builtin(local_invocation_id) localId: vec3<u32>,
@builtin(workgroup_id) workgroupId: vec3<u32>,
@builtin(local_invocation_index) localIndex: u32
) {
let totalIterations = u32(uniforms.uTotalCount.x) * u32(uniforms.uTotalCount.y) * u32(uniforms.uTotalCount.z);
let physicalId = globalId.x + globalId.y * (u32(uniforms.uPhysicalCount.x)) + globalId.z * (u32(uniforms.uPhysicalCount.x) * u32(uniforms.uPhysicalCount.y));
if (physicalId >= totalIterations) {
return;
}
var index = vec3<i32>(0);
index.x = i32(physicalId % u32(uniforms.uTotalCount.x));
let remainingY = physicalId / u32(uniforms.uTotalCount.x);
index.y = i32(remainingY % u32(uniforms.uTotalCount.y));
index.z = i32(remainingY / u32(uniforms.uTotalCount.y));
HOOK_iteration(index);
}
`,{compute:{"void iteration":`(index: vec3<i32>) {}`}}),this._baseComputeShader}_createImageLightShader(e){if(e===`diffused`)return this._pInst.createShader(In,Ln);if(e===`specular`)return this._pInst.createShader(In,Rn);throw Error(`Unknown imageLight shader type: ${e}`)}_createMipmapTexture(e){return new o(this,e,{})}_prepareMipmapData(e,t){let n={size:{width:e,height:e,depthOrArrayLayers:1},mipLevelCount:t,format:`rgba8unorm`,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT};return{gpuTexture:this.device.createTexture(n),size:e,mipLevels:t,format:`rgba8unorm`}}_accumulateMipLevel(e,t,n,r,i){this.flushDraw();let a=this.device.createCommandEncoder(),o=e.color.rawTexture().texture;a.copyTextureToTexture({texture:o,origin:{x:0,y:0,z:0}},{texture:t.gpuTexture,mipLevel:n,origin:{x:0,y:0,z:0}},{width:r,height:i,depthOrArrayLayers:1}),this.device.queue.submit([a.finish()])}_finalizeMipmapTexture(e){return new o(this,e,{})}createMipmapTextureHandle({gpuTexture:e,format:t,dataType:n,width:r,height:i}){return{texture:e,view:e.createView(),glFormat:t||`rgba8unorm`,glDataType:n||`uint8`}}compute(e,t,n=1,r=1){if(e.shaderType!==`compute`)throw Error(`compute() can only be called with a compute shader`);this._finishActiveRenderPass(),e._compiled||e.init(),e.setDefaultUniforms(),e.setUniform(`uTotalCount`,[t,n,r]);let i=t*n*r,a=524280,o=t,s=n,c=r;(t>a||n>a||r>a||i>1024&&n===1&&r===1)&&(o=Math.ceil(Math.sqrt(i)),s=Math.ceil(i/o),c=1);let l=Math.ceil(o/8),u=Math.ceil(s/8),d=Math.ceil(c/1);e.setUniform(`uPhysicalCount`,[l*8,u*8,d*1]);let f=this.device.createCommandEncoder(),p=f.beginComputePass();this.setupShaderBindGroups(e,p,{compute:!0,workgroupSize:[8,8,1]}),p.dispatchWorkgroups(l,u,d),p.end(),this._pendingCommandEncoders.push(f.finish()),this._hasPendingDraws=!0}}e.RendererWebGPU=m,e.renderers[s]=e.RendererWebGPU,t.setAttributes=async function(e,t){return this._renderer._setAttributes(e,t)}}typeof p5<`u`&&Zn(p5,p5.prototype);function Qn(e){e.registerAddon(Zn)}return Qn})();