p5.js icon indicating copy to clipboard operation
p5.js copied to clipboard

Support transformation matrices in p5.strands

Open davepagurek opened this issue 5 months ago • 11 comments

Increasing access

If you want to use WebGL/WebGPU instancing to draw many particles, then you end up having to position the particles in a p5.strands shader rather than using the usual translate/rotate/scale functions. This gets complex pretty quickly, making it hard to take advantage of the performance opportunities of shaders. It would be great to make it as close as we can to the ease of use of regular p5 positioning.

Most appropriate sub-area of p5.js?

  • [ ] Accessibility
  • [ ] Color
  • [ ] Core/Environment/Rendering
  • [ ] Data
  • [ ] DOM
  • [ ] Events
  • [ ] Image
  • [ ] IO
  • [x] Math
  • [ ] Typography
  • [ ] Utilities
  • [x] WebGL
  • [ ] Build process
  • [ ] Unit testing
  • [ ] Internationalization
  • [ ] Friendly errors
  • [ ] Other (specify if possible)

Feature enhancement details

Here are some examples of what it looks like right now:

  • https://openprocessing.org/@davepagurek/2845379
  • https://editor.p5js.org/davepagurek/sketches/Y4gEVBKaL
  • https://openprocessing.org/@davepagurek/2838235

Notably, that last one uses rotations, and is really complicated!

So we can't make this look exactly like regular p5 transformations because we're working at a different level: normally we're moving space around ourselves and then drawing something there; in a shader, we're looking at an individual vertex at a time and updating its position/normal.

However, I think we can do something fairly close, taking inspiration from the web DOMMatrix API. Here's a comparison of using transforms in p5 to applying a DOMMatrix to a point:

p5/shape

DOMMatrix/point

DOMMatrixReadOnly/point

translate(25, 25)
rotate(-PI * 0.2)
translate(-25, -25)
scale(2)
model(something)
const t = new DOMMatrix()
t.translateSelf(25, 25)
t.rotateSelf(36) // DOMMatrix uses degrees by default
t.translateSelf(-25, -25)
t.scaleSelf(2)
const transformed = t.transformPoint(somePoint)
const t = new DOMMatrix()
  .translate(25, 25)
  .rotate(36) // DOMMatrix uses degrees by default
  .translate(-25, -25)
  .scale(2)
const transformed = t.transformPoint(somePoint)

A matrix should ideally have these methods from DOMMatrix:

  • translate
  • rotate (and rotateAxisAngle)
  • scale
  • skewX and skewY
  • inverse
  • multiply
  • transformPoint

Additionally, I think we also need transformNormal. In 3D, to make lighting work, we also need to update the orientation of the surface. This involves taking the transpose of the upper-left 3x3 submatrix of the 4x4 matrix of a 3D affine transform and then applying that to the normal vector.

Note: to mutate or not to mutate?

I don't think we'd want to have the *Self suffixes like in DOMMatrix. I feel like we should use the un-suffixed names, but decide whether they mutate in place, or return a modified version.

Here's a little pro/con list of mutation:

For mutationAgainst mutation
  • p5.Vector methods mutate
  • Method chainining is not something we see much of in p5 code, and doing t = t.multiply(something) each line to avoid chaining is a little more verbose
  • p5.strands vectors don't do any mutation in place -- they mirror GLSL vectors, where they are data like numbers in js, and global functions (not methods!) like cross(v1, v2) or normalize(v) return new vectors -- so we would be consistent within strands
  • avoids a common bug where you accidentally mutate an object that you intend to reuse in another calculation

I personally lean towards not mutating in p5.strands for consistency within strands. To make it less confusing with p5.Vector, I propose not making methods on matrices in strands, similar to vectors in strands, and making global methods called translate(...), scale(...), etc. We can reuse the same methods that in regular p5 mutate the current coordinate space, and the idea would be that because there is no global coordinate space you can mutate in strands, you use those methods slightly differently in the strands context, and then there's also no confusion in p5 about whether they'll mutate the objects, since p5.Vector static methods also don't mutate.

In the future, matrices outside of strands might get methods that do mutate.

Note: matrices or transforms?

While in GLSL/WGSL these are matrices, they are used almost exclusively for transforms. I think we still want to support mat3(...), mat4(...) etc constructors for GLSL compatibility, but as aliases for transform2D(...) and transform3D(...) respectively. (Multiplying a 3D transform, which is a mat4, against a vec3, via transformPoint would under the hood add a 1 to its end to make it an affine point. We can maybe let the * operator do "raw" multiplication.)

This terminology keeps the door open for us to have more math-oriented matrices in p5, which have different assumptions (and performance tradeoffs) than ones intended for graphics. In the future we could have a non-strands transform with a similar API (a rename of the current p5.Matrix, keeping its transform/graphics methods?) alongside a non-strands p5.Matrix too.

davepagurek avatar Jun 22 '26 12:06 davepagurek

@davepagurek i would like to work on this please assign

vamshi567bh avatar Jun 22 '26 13:06 vamshi567bh

Hey @davepagurek! We have implemented the matrix transformation builtins for strands based on the discussion here. Here is what we did:

  • Added transform2D, transform3D, translate, rotate, scale, multiply, transformPoint, transformNormal as GLSL/WGSL function snippets
  • Registered all overloads in strands_builtins.js
  • Added matrix type aliases (Mat4x4 -> Mat4 etc.) and constructor aliases in strands_api.js
  • Added matrix multiplication support in ir_builders.js for matmat, matvec, vec*mat
  • GLSL implementations in matrixTransformGLSL.glsl
  • WGSL implementations in matrixTransformWGSL.js (with unique names per overload since WGSL doesnt support overloading)
  • Matrix snippets are injected into shader declarations from p5.strands.js

All 127 existing strands tests pass. The PR is at https://github.com/processing/p5.js/pull/8954,please review

vamshi567bh avatar Jun 22 '26 14:06 vamshi567bh

Hi @vamshi567bh, before we go and implement anything, we should wait for a bit more feedback on the API decisions I've suggested. (cc @lukeplowden @perminder-17 and @aashu2006 if you have thoughts!)

Generally, please wait until you have been assigned before opening a PR.

Also, for whichever API we do, I think we'll want to implement this by introducing support for matrix types in strands. While we could build a bunch of GLSL and WGSL functions to let it use, that's a lot to maintain in each renderer, so I wonder if we can instead write JavaScript helpers similar to how our strands color conversion methods are implemented that make use of the base matrix functionality so that more of the implementation is shared.

For another example of making helpers in JavaScript, I was recently working on a library to build SDF shaders for use in lighting. All of the SDF shape primitives are implemented just in JavaScript, but making use of the base strands functions.

davepagurek avatar Jun 23 '26 13:06 davepagurek

@davepagurek Sure I will keep the PR open or close it if you order and wait for more feedback on the API decisions. I'll also look into implementing this using JavaScript helpers as you suggested once we have a clear direction.

vamshi567bh avatar Jun 23 '26 15:06 vamshi567bh

I support the non-mutating approach cause it feels more consistent with how vectors already work in strands. one thing I would also be curious about is like how the transform composition feels in practice, since a lot of instancing code will likely be built from multiple translate/rotate/scale operations. It would be nice if combining transforms stays simple and natural as sketches get more complex.

aashu2006 avatar Jun 24 '26 12:06 aashu2006

A small thing that might make the API decision easier to review: define a few golden fixtures before choosing the final surface.

I would want fixtures that can be checked from both the JS helper side and the emitted GLSL/WGSL side:

  • transformPoint after translate -> rotate -> translate back -> scale;
  • transformNormal under non-uniform scale, so inverse-transpose behavior is explicit;
  • transform composition order, especially whether examples read the same way as normal p5 transform code;
  • immutability expectation: reusing a transform in two calculations should either preserve the original or intentionally mutate it, with a test proving whichever behavior is chosen;
  • raw matrix/vector multiplication kept separate from affine transformPoint semantics.

That would also help teach the feature. If the examples show the same point/normal going through JS helpers and shader output with matching results, then users can see why strands transforms differ from regular p5 coordinate-space transforms without having to infer it from implementation details.

HarperZ9 avatar Jun 28 '26 21:06 HarperZ9

Hi @davepagurek , thanks for your thoughtful feedback on transformations in Strands.

I've put together a short technical spec that outlines the proposed API design, along with a brief implementation plan.

I'd really appreciate any feedback from the community on the design. Does this approach make sense, or do you think we should consider a different direction? I'm very open to suggestions and discussion before moving forward.

Docs: https://docs.google.com/document/d/1Y4wBso5rc9DubRB2HK5hkQkdBccE2K6FN0kSvMkdrFY/edit?usp=sharing

CC: @lukeplowden @RandomGamingDev, @davepagurek @aashu2006 @ksen0

perminder-17 avatar Jul 09 '26 10:07 perminder-17

Thanks @perminder-17, this all sounds good to me!

davepagurek avatar Jul 13 '26 21:07 davepagurek

Hi @davepagurek — following up on your invitation in #8978 to look into strands matrix support. Reading this issue, I wanted to scope my piece so it complements the transformation API design (and @perminder-17's work here) rather than overlapping with it. Before proposing anything I traced what exists on current main (8886f4c6e) and ran empirical checks in the preview sandbox on both backends. Findings first:

What already works (observed)

  • The DataType loop in strands_api.js (~line 747) auto-registers uniformMat2x2 / uniformMat3x3 / uniformMat4x4 from the mat entries in ir_types.js:69-71. These are currently undocumented and untested (zero references in docs/ or test/), but the plumbing works further than I expected:
  • WebGL: uniformMat3x3('uM', [...]) emits uniform mat3x3 uM; in the generated shader (valid — strands shaders are #version 300 es), and it compiles, links, and renders. Declaration end-to-end: ✅
  • WebGPU: the same call generates a correct uM: mat3x3<f32> member in the HookUniforms struct with a proper @group/@binding. Declaration in codegen: ✅

What breaks: * on a matrix operand (observed)

binaryOpNode (ir_builders.js) has no BaseType.MAT handling. For m * v with m: mat3, v: vec3, the mixed-type priority ladder (~lines 135-146) sees differing base types, equal dimensions, and priority: 0 on the mat types — so it casts the matrix down to a vec3. Generated GLSL from a real getWorldInputs hook:

_p5_param_inputs.position = (vec3(uM) * _p5_param_inputs.position);

The consequences differ by backend, from the same generated cast:

  • WebGL: silent corruption. vec3(uM) compiles (takes the first column), so a half-scale matrix turned every position into (0.5x, 0, 0) — all triangles degenerate, nothing renders, zero console output. A user gets a blank sketch with no error.
  • WebGPU: loud failure. WGSL has no vector-from-matrix constructor: Error while parsing WGSL: :107:32 error: no matching constructor for 'vec3<f32>(mat3x3<f32>)', followed by the ShaderModule/RenderPipeline/ CommandBuffer cascade.

(Also observed: mat * mat and mat * scalar happen to produce workable GLSL through the same ladder, but by accident of the cast rules, not by design. And setUniform doesn't unwrap a p5.Matrix — only flat arrays work — since there's no isMatrix duck-typing alongside isVector/ isColor.)

This is exactly why the Renderer3D.js:1929 sphere-mapping hack exists: the three uniformVec3 + three dot() calls are working around both halves (no documented matrix uniform, no working mat×vec).

Proposed scope (what I'd like to take on, if it fits)

The uniform plumbing half: make uniformMat2x2/3x3/4x4 first-class — unit + visual tests on both backends, documentation, and ideally setUniform accepting a p5.Matrix directly. This looks separable from the transform-API design questions in this issue, and would let the _getSphereMapping hack collapse once matrix ops land.

The operator half (m * v semantics) clearly belongs to this issue's design — you mention * possibly staying reserved for raw multiplication — so I don't want to touch its semantics. One question below on the interim.

Questions

  1. Does the split make sense — uniforms as a separate, smaller piece (happy to file a focused issue for it and keep this thread for the API design), with * semantics staying here?
  2. Interim behavior: until matrix-aware operator handling exists, would you want binaryOpNode to raise a friendly error on mat-typed operands in unsupported ops, instead of the silent vec3(mat) cast? (Similar shape to the dimension-mismatch check from #8823.) I'm happy to do that as part of the uniforms piece or leave it for the operator work — your call.
  3. @perminder-17 — does any of this overlap with what you have in progress? Glad to adjust scope around it.

Repro sketch (preview sandbox, either backend):

sh = p.baseMaterialShader().modify(() => {
  const uM = p.uniformMat3x3('uM', [0.5, 0, 0, 0, 0.5, 0, 0, 0, 0.5]);
  p.getWorldInputs((inputs) => {
    inputs.position = uM * inputs.position;
    return inputs;
  });
}, { p });

harshiltewari2004 avatar Jul 17 '26 07:07 harshiltewari2004

Thanks for the investigation @harshiltewari2004 , the split makes sense.

The uniforms half is a good separate piece. I think this already work:-

const uM = p.uniformMat3x3('uM', [0.5, 0, 0, 0, 0.5, 0, 0, 0, 0.5]);

So please go ahead with making it production-ready. tests, docs, etc plus anything else missing outside this issue's scope.

On overlap: I'm already working on the arithmetic side (m * v, m * m, m * scalar in binaryOpNode).

It would be nice to file an issue first where it can clearly mention the scope so we can assign you. Thanks for the help!

perminder-17 avatar Jul 18 '26 23:07 perminder-17

Filed the scoped issue as requested: #8992

harshiltewari2004 avatar Jul 19 '26 05:07 harshiltewari2004