accumulate

Add up a per-item value over every item of a list, in a real GPU loop over the live count.

accumulate(
  list: ListRef,
  body: (i: Expr) =,
> Expr, opts: {zero?: 'f32' | 'vec3f'; deps?: Expr[]; hint?: string} = {}): Expr

Import accumulate from shaders/std.

body(i) returns the value for item i. zero picks the sum's type: 'f32' (default) or 'vec3f' for a color. Anything the body reads that was computed outside the loop (a normal, a surface point) goes in deps, so it is emitted once before the loop instead of inside it. hint names the sum in the generated code.

Parameters

NameTypeNotes
listListRef
body(i: Expr) => Expr
opts{zero?: 'f32' | 'vec3f'; deps?: Expr[]; hint?: string}Optional. Default {}.

Example

const lights = listOf(params, 'lights')
const rgb = accumulate(lights, (i) => {
  const light = lights.at(i)
  const pos = light.position('position')
  const d = length(sub(uv, vec2(pos.member('x'), sub(1, pos.member('y')))))
  return mul(light.color('color').member('rgb'), div(light.number('intensity'), add(1, mul(d, d))))
}, {zero: 'vec3f', deps: [uv], hint: 'lightSum'})

See also

  • listOf — Read a list prop inside a hand-written builder: its live item count and each item's fields.

Used by

Irradiance