21constexpr u32 kStateBytes = 48;
23constexpr u32 kMaxFields = 8;
25static_assert(kLutSize == 32,
"the kernel's LUT arrays are sized for 32 entries");
38 kEmitDeath = 1u << 10,
45constexpr u32 kEventBytes = 48;
46constexpr u32 kEventHeaderBytes = 16;
48constexpr u32 kMaxEvents = 4096;
49constexpr u32 kMaxColliders = 64;
51constexpr u32 kDepthGridMin = 64;
52constexpr u32 kDepthGridMax = 640;
72 f32 rot0[4], rot1[4], rot2[4];
75 f32 fields[kMaxFields * 3][4];
76 f32 colorLut[kLutSize][4];
77 f32 sizeLut[kLutSize / 4][4];
78 f32 speedLut[kLutSize / 4][4];
84 f32 depthClip[4][4], depthWorld[4][4];
87static_assert(
sizeof(ParamsBlock) == 107 * 16,
"the kernel's Params is 107 vec4s");
88constexpr u32 kJobStride = 2048;
89static_assert(
sizeof(ParamsBlock) <= kJobStride && kJobStride % 256 == 0);
90constexpr u32 kMaxJobs = 64;
93const char*
const kKernel = R
"WGSL(
94struct State { pa: vec4<f32>, vl: vec4<f32>, ms: vec4<f32> };
95struct Inst { px: f32, py: f32, pz: f32, sx: f32, sy: f32, rot: f32, color: u32, u0: f32, v0: f32, us: f32, vs: f32, age: f32, random: f32, intensity: f32, life: f32 };
97 p0: vec4<u32>, p1: vec4<u32>,
98 p2: vec4<f32>, p3: vec4<f32>, p4: vec4<f32>, p5: vec4<f32>, p6: vec4<f32>, p7: vec4<f32>,
99 p8: vec4<f32>, p9: vec4<f32>, p10: vec4<f32>,
101 startColor: vec4<f32>, endColor: vec4<f32>,
102 origin: vec4<f32>, scale: vec4<f32>,
103 rot0: vec4<f32>, rot1: vec4<f32>, rot2: vec4<f32>,
106 fields: array<vec4<f32>, 24>,
107 colorLut: array<vec4<f32>, 32>,
108 sizeLut: array<vec4<f32>, 8>,
109 speedLut: array<vec4<f32>, 8>,
110 p12: vec4<u32>, p13: vec4<f32>, p14: vec4<u32>, p15: vec4<f32>,
112 depthClip: mat4x4<f32>, depthWorld: mat4x4<f32>,
113 depthOrigin: vec4<f32>,
115struct EventRec { at: vec4<f32>, vel: vec4<f32>, normal: vec4<f32> };
116struct Events { count: atomic<u32>, head: u32, capacity: u32, pad: u32, rec: array<EventRec> };
117struct EventsIn { count: u32, head: u32, capacity: u32, pad: u32, rec: array<EventRec> };
118struct Collider { at: vec4<f32>, rot: vec4<f32>, ext: vec4<f32>, mask: vec4<u32> };
119@group(0) @binding(0) var<uniform> P: Params;
120@group(0) @binding(1) var<storage, read_write> states: array<State>;
121@group(0) @binding(2) var<storage, read_write> insts: array<Inst>;
122@group(0) @binding(3) var<storage, read_write> events: Events;
123@group(0) @binding(4) var<storage, read> parentEvents: EventsIn;
124@group(0) @binding(5) var<storage, read> depthGrid: array<f32>;
125@group(0) @binding(6) var<storage, read> colliders: array<Collider>;
126@group(0) @binding(7) var<storage, read_write> trail: array<vec4<f32>>;
127@group(0) @binding(8) var<storage, read_write> segments: array<Inst>;
129var<private> rng: u32;
130var<private> hitPoint: vec3<f32>;
131var<private> hitNormal: vec3<f32>;
133fn pcg(v: u32) -> u32 {
134 let s = v * 747796405u + 2891336453u;
135 let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u;
136 return (w >> 22u) ^ w;
140 return f32(rng) * 2.3283064365386963e-10;
142fn rr(a: f32, b: f32) -> f32 {
143 if (a >= b) { return a; }
144 return a + (b - a) * rand();
147// --- the shapes: where a particle is born and which way it leaves (ParticleShapes.hpp) ---
148fn coneDir(halfAngle: f32) -> vec3<f32> {
149 let cosT = rr(cos(halfAngle), 1.0);
150 let sinT = sqrt(max(0.0, 1.0 - cosT * cosT));
151 let phi = rr(0.0, 6.283185307179586);
152 return vec3<f32>(sinT * cos(phi), cosT, sinT * sin(phi));
154fn planarAim() -> vec3<f32> {
155 let a = rr(P.p9.x, P.p9.y);
156 return vec3<f32>(cos(a), sin(a), 0.0);
159// --- curl noise (ParticleNoise.hpp): the same field the CPU sim advects along ---
160fn hash2(x: i32, y: i32) -> f32 {
161 var h = u32(x) * 374761393u + u32(y) * 668265263u;
162 h = (h ^ (h >> 13u)) * 1274126177u;
164 return f32(h) * (1.0 / 4294967295.0);
166fn grad2(x: i32, y: i32) -> vec2<f32> {
167 let a = hash2(x, y) * 6.283185307179586;
168 return vec2<f32>(cos(a), sin(a));
170fn fade(t: f32) -> f32 { return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); }
171fn perlin2(p: vec2<f32>) -> f32 {
176 let n00 = dot(grad2(x0, y0), pf - vec2<f32>(0.0, 0.0));
177 let n10 = dot(grad2(x0 + 1, y0), pf - vec2<f32>(1.0, 0.0));
178 let n01 = dot(grad2(x0, y0 + 1), pf - vec2<f32>(0.0, 1.0));
179 let n11 = dot(grad2(x0 + 1, y0 + 1), pf - vec2<f32>(1.0, 1.0));
182 return mix(mix(n00, n10, ux), mix(n01, n11, ux), uy);
184fn fbm2(p: vec2<f32>, octaves: u32) -> f32 {
189 let n = clamp(octaves, 1u, 8u);
190 for (var i = 0u; i < n; i = i + 1u) {
191 sum = sum + amp * perlin2(p * freq);
196 if (norm > 0.0) { return sum / norm; }
199fn curl(p: vec2<f32>, octaves: u32) -> vec2<f32> {
201 let dpdx = fbm2(p + vec2<f32>(e, 0.0), octaves) - fbm2(p - vec2<f32>(e, 0.0), octaves);
202 let dpdy = fbm2(p + vec2<f32>(0.0, e), octaves) - fbm2(p - vec2<f32>(0.0, e), octaves);
203 return vec2<f32>(dpdy, -dpdx) * (0.25 / (2.0 * e));
206fn ease(kind: f32, t: f32) -> f32 {
207 if (kind > 2.5) { return select(-1.0 + (4.0 - 2.0 * t) * t, 2.0 * t * t, t < 0.5); }
208 if (kind > 1.5) { return t * (2.0 - t); }
209 if (kind > 0.5) { return t * t; }
213fn lutF(which: u32, t: f32) -> f32 {
214 let f = clamp(t, 0.0, 1.0) * 31.0;
216 let j = min(i + 1u, 31u);
220 a = P.sizeLut[i >> 2u][i & 3u];
221 b = P.sizeLut[j >> 2u][j & 3u];
223 a = P.speedLut[i >> 2u][i & 3u];
224 b = P.speedLut[j >> 2u][j & 3u];
226 return mix(a, b, f - f32(i));
228fn lutC(t: f32) -> vec4<f32> {
229 let f = clamp(t, 0.0, 1.0) * 31.0;
231 let j = min(i + 1u, 31u);
232 return mix(P.colorLut[i], P.colorLut[j], f - f32(i));
235// A scene force field folded into a world-space particle's velocity (ParticleSystem.cpp applyForceField).
236fn applyField(k: u32, pos: vec3<f32>, vel: vec3<f32>, dt: f32) -> vec3<f32> {
237 let a = P.fields[k * 3u];
238 let b = P.fields[k * 3u + 1u];
239 let c = P.fields[k * 3u + 2u];
240 let toField = a.xyz - pos;
241 let distSq = dot(toField, toField);
244 if (distSq > c.x * c.x) { return vel; }
245 if (c.y > 0.5) { factor = 1.0 - sqrt(distSq) / c.x; }
249 let kind = u32(a.w + 0.5);
251 v = v + b.xyz * (strength * factor * dt);
252 } else if (kind == 1u) {
253 let d = sqrt(distSq);
254 if (d > 1e-4) { v = v + (toField / d) * (strength * factor * dt); }
255 } else if (kind == 2u) {
256 let d = sqrt(distSq);
258 let radial = -toField / d;
259 var axis = vec3<f32>(0.0, 0.0, 1.0);
260 if (length(b.xyz) > 1e-6) { axis = normalize(b.xyz); }
261 let perp = cross(axis, radial);
262 let pl = length(perp);
263 if (pl > 1e-6) { v = v + (perp / pl) * (strength * factor * dt); }
266 v = v * (1.0 - min(strength * factor * dt, 1.0));
272 insts[i] = Inst(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0u, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0);
273 if ((P.p1.y & 8192u) != 0u) {
274 let n = P.p14.x - 1u;
275 for (var j = 0u; j < n; j = j + 1u) {
276 segments[i * n + j] = Inst(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0u, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0);
282// --- events: what another emitter's kernel, or the game a frame or two later, is told ---
283fn emitEvent(kind: f32, at: vec3<f32>, vel: vec3<f32>, normal: vec3<f32>, slot: u32) {
284 if (P.p13.x < 1.0 && rand() >= P.p13.x) { return; }
285 let k = atomicAdd(&events.count, 1u);
287 events.rec[k] = EventRec(vec4<f32>(at, kind), vec4<f32>(vel, 0.0), vec4<f32>(normal, f32(slot)));
291// --- the depth the last frame left: reprojected with the camera that saw it, so a turning camera does not smear it ---
292fn depthAt(tx: i32, ty: i32) -> f32 {
293 let w = i32(P.p14.z);
294 let h = i32(P.p14.w);
295 if (tx < 0 || ty < 0 || tx >= w || ty >= h) { return 1.0; }
296 return depthGrid[u32(ty * w + tx)];
298fn unproject(uv: vec2<f32>, depth: f32) -> vec3<f32> {
299 let world = P.depthWorld * vec4<f32>(uv * 2.0 - 1.0, depth, 1.0);
300 return world.xyz / world.w;
302fn texelSurface(tx: i32, ty: i32, depth: f32) -> vec3<f32> {
303 return unproject((vec2<f32>(f32(tx), f32(ty)) + 0.5) / vec2<f32>(f32(P.p14.z), f32(P.p14.w)), depth);
305fn depthHit(point: vec3<f32>, vel: vec3<f32>, dt: f32) -> bool {
306 let rel = point - P.depthOrigin.xyz;
307 let clip = P.depthClip * vec4<f32>(rel, 1.0);
308 if (clip.w <= 0.0) { return false; }
309 let ndc = clip.xyz / clip.w;
310 if (abs(ndc.x) >= 1.0 || abs(ndc.y) >= 1.0 || ndc.z < 0.0 || ndc.z > 1.0) { return false; }
311 let uv = (ndc.xy + 1.0) * 0.5;
312 let tx = i32(uv.x * f32(P.p14.z));
313 let ty = i32(uv.y * f32(P.p14.w));
314 let depth = depthAt(tx, ty);
315 if (depth >= 1.0) { return false; }
316 let ray = normalize(unproject(uv, 1.0) - unproject(uv, 0.0));
317 let surface = texelSurface(tx, ty, depth);
318 let behind = dot(rel - surface, ray);
319 // A particle may cross more than the thickness in a step, and still have hit what it crossed.
320 if (behind < 0.0 || behind > max(P.p13.z, length(vel) * dt)) { return false; }
321 // The surface's slope from the texels beside it, each way from whichever is nearer: an edge belongs to what stands in front.
323 let l = depthAt(tx - 1, ty);
324 let r = depthAt(tx + 1, ty);
325 let u = depthAt(tx, ty - 1);
326 let d = depthAt(tx, ty + 1);
327 let useR = abs(r - depth) <= abs(l - depth);
328 let useD = abs(d - depth) <= abs(u - depth);
329 let hx = select(l, r, useR);
330 let hy = select(u, d, useD);
331 if (hx < 1.0 && hy < 1.0) {
332 let across = texelSurface(select(tx - 1, tx + 1, useR), ty, hx) - surface;
333 let along = texelSurface(tx, select(ty - 1, ty + 1, useD), hy) - surface;
334 let n = cross(across, along);
335 let size = length(n);
338 if (dot(normal, ray) > 0.0) { normal = -normal; }
341 if (dot(vel, normal) >= 0.0) { return false; }
343 hitPoint = surface + P.depthOrigin.xyz + normal * (0.001 * P.p13.z);
347// --- the distance functions (ParticleSystem sdfDistance) ---
348fn turnBack(q: vec4<f32>, v: vec3<f32>) -> vec3<f32> {
350 return v + 2.0 * cross(u, cross(u, v) + q.w * v);
352fn sdfOne(k: u32, point: vec3<f32>) -> f32 {
353 let c = colliders[k];
354 let q = turnBack(c.rot, point - c.at.xyz);
357 let along = clamp(q.y, -c.ext.y, c.ext.y);
358 d = length(vec3<f32>(q.x, q.y - along, q.z)) - c.ext.x;
359 } else if (c.at.w > 0.5) {
360 let over = abs(q) - c.ext.xyz;
361 d = length(max(over, vec3<f32>(0.0))) + min(max(over.x, max(over.y, over.z)), 0.0);
363 d = length(q) - c.ext.x;
365 if (c.ext.w > 0.5) { return -d; }
368fn sdfHit(point: vec3<f32>, vel: vec3<f32>) -> bool {
371 for (var k = 0u; k < P.p12.w; k = k + 1u) {
372 if ((colliders[k].mask.x & P.p14.y) == 0u) { continue; }
373 let d = sdfOne(k, point);
374 if (d < least) { least = d; found = k; }
376 if (found == P.p12.w) { return false; }
377 let e = max(0.01, -least * 0.1);
379 sdfOne(found, point + vec3<f32>(e, 0.0, 0.0)) - sdfOne(found, point - vec3<f32>(e, 0.0, 0.0)),
380 sdfOne(found, point + vec3<f32>(0.0, e, 0.0)) - sdfOne(found, point - vec3<f32>(0.0, e, 0.0)),
381 sdfOne(found, point + vec3<f32>(0.0, 0.0, e)) - sdfOne(found, point - vec3<f32>(0.0, 0.0, e)));
382 let size = length(g);
383 if (size < 1e-6) { return false; }
384 let normal = g / size;
385 if (dot(vel, normal) >= 0.0) { return false; }
387 hitPoint = point - normal * least;
391// --- trails: each piece of the path as a quad the particle draw already knows, turned to lie along it as seen ---
392fn segmentBetween(a: vec3<f32>, b: vec3<f32>, width: f32, color: vec4<f32>, extra: vec4<f32>) -> Inst {
393 let mid = (a + b) * 0.5 - P.shift.xyz;
394 var fwd = P.camera.xyz;
395 if (P.camera.w > 0.5) { fwd = normalize(P.camera.xyz - mid); }
396 var refUp = vec3<f32>(0.0, 1.0, 0.0);
397 if (abs(fwd.y) > 0.999) { refUp = vec3<f32>(0.0, 0.0, 1.0); }
398 let right = normalize(cross(refUp, fwd));
399 let up = cross(fwd, right);
401 let x = dot(d, right);
403 return Inst(mid.x, mid.y, mid.z, sqrt(x * x + y * y), width, atan2(y, x), pack4x8unorm(color), 0.0, 0.0, 1.0, 1.0, extra.x, extra.y, extra.z, extra.w);
405fn stepTrail(i: u32, head: vec3<f32>, born: bool, color: vec4<f32>, extra: vec4<f32>) {
406 let points = P.p14.x;
408 let base = i * points;
409 var count = u32(trail[base].w);
410 if (born || count == 0u) {
411 trail[base] = vec4<f32>(head, 1.0);
414 let last = trail[base].xyz;
415 if (distance(head, last) >= P.p15.y) {
416 for (var k = n; k > 0u; k = k - 1u) { trail[base + k] = trail[base + k - 1u]; }
417 count = min(count + 1u, points);
418 trail[base] = vec4<f32>(head, f32(count));
422 for (var j = 0u; j < n; j = j + 1u) {
424 segments[i * n + j] = Inst(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0u, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0);
427 let next = trail[base + j].xyz;
428 let fadeOut = 1.0 - (f32(j) + 0.5) / f32(n);
429 segments[i * n + j] = segmentBetween(prev, next, P.p15.x * fadeOut, vec4<f32>(color.rgb, color.a * fadeOut), extra);
435fn bornState(origin: vec3<f32>, inherit: vec3<f32>, world: bool) -> State {
436 let life = rr(P.p2.z, P.p2.w);
437 let startSize = rr(P.p3.z, P.p3.w);
438 let endSize = rr(P.p4.x, P.p4.y);
439 let rot = rr(P.p4.z, P.p4.w);
440 let angVel = rr(P.p5.x, P.p5.y);
442 var pos = vec3<f32>(0.0);
443 var dir = vec3<f32>(0.0, 1.0, 0.0);
446 let angle = rr(0.0, 6.283185307179586);
447 let radius = rr(0.0, P.p7.z);
448 pos = vec3<f32>(cos(angle) * radius, sin(angle) * radius, 0.0);
449 if (radius > 0.001) { dir = pos / radius; } else { dir = planarAim(); }
450 } else if (shape == 2u) {
451 let h = P.p8.xyz * 0.5;
452 let x = rr(-h.x, h.x);
453 let y = rr(-h.y, h.y);
455 if (P.p8.z > 0.0) { z = rr(-h.z, h.z); }
456 pos = vec3<f32>(x, y, z);
458 } else if (shape == 3u) {
459 dir = coneDir(P.p7.w);
460 pos = coneDir(P.p7.w) * rr(0.0, P.p7.z);
461 } else if (shape == 4u || shape == 5u) {
462 var cap2 = 3.141592653589793;
463 if (shape == 5u) { cap2 = 1.5707963267948966; }
465 pos = coneDir(cap2) * (P.p7.z * pow(rr(0.0, 1.0), 1.0 / 3.0));
469 let speed = rr(P.p3.x, P.p3.y);
470 let R = mat3x3<f32>(P.rot0.xyz, P.rot1.xyz, P.rot2.xyz);
474 wpos = origin + pos * P.scale.xyz;
477 wpos = origin + R * (pos * P.scale.xyz);
480 return State(vec4<f32>(wpos, 0.0), vec4<f32>(wdir * speed + inherit, max(life, 1e-4)), vec4<f32>(startSize, endSize, rot, angVel));
483@compute @workgroup_size(64)
484fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
487 if (i >= cap) { return; }
489 if ((flags & 1u) != 0u) {
490 states[i] = State(vec4<f32>(0.0), vec4<f32>(0.0), vec4<f32>(0.0));
494 let local = (flags & 2u) != 0u;
495 let R = mat3x3<f32>(P.rot0.xyz, P.rot1.xyz, P.rot2.xyz);
501 rng = pcg(P.p1.x ^ (i * 2654435761u) ^ (P.p12.x * 40503u));
503 // Born this step? Slot i holds the particle whose absolute index lands on it.
504 let first = P.p0.y % cap;
505 let rel = (i + cap - first) % cap;
507 rng = pcg(P.p1.x ^ ((P.p0.y + rel) * 2654435761u));
508 var at = P.origin.xyz;
509 if (local) { at = vec3<f32>(0.0); }
510 st = bornState(at, vec3<f32>(0.0), !local);
512 // Rate-born particles are spread across the step they were born in, so a fast emitter draws a line, not a row of clumps.
513 if (rel < P.p0.w) { stepDt = dt * (1.0 - (f32(rel) + 0.5) / f32(P.p0.w)); }
514 } else if ((flags & 4096u) != 0u) {
515 // Or a parent's event lit it, each event its child's burst, from where the ring stopped last frame.
516 let burst = max(P.p12.z, 1u);
517 let lit = min(min(parentEvents.count, parentEvents.capacity) * burst, cap);
518 let fromHead = (i + cap - events.head % cap) % cap;
519 if (fromHead < lit) {
520 let e = parentEvents.rec[fromHead / burst];
521 rng = pcg(P.p1.x ^ ((events.head + fromHead) * 2654435761u) ^ (P.p12.x * 40503u));
523 var carried = e.vel.xyz * P.p13.y;
524 if (local) { at = transpose(R) * (at - P.origin.xyz); carried = transpose(R) * carried; }
525 st = bornState(at, carried, !local);
529 if (!born && st.pa.w >= st.vl.w) {
533 if (born && (flags & 512u) != 0u) {
534 var bornAt = st.pa.xyz;
535 var bornVel = st.vl.xyz;
536 if (local) { bornAt = P.origin.xyz + R * bornAt; bornVel = R * bornVel; }
537 emitEvent(1.0, bornAt, bornVel, vec3<f32>(0.0), i);
541 var age = st.pa.w + stepDt;
545 if ((flags & 1024u) != 0u) {
546 var deadAt = st.pa.xyz;
547 var deadVel = st.vl.xyz;
548 if (local) { deadAt = P.origin.xyz + R * deadAt; deadVel = R * deadVel; }
549 emitEvent(0.0, deadAt, deadVel, vec3<f32>(0.0), i);
558 vel = vel + vec3<f32>(P.p5.z, P.p5.w, P.p6.x) * stepDt;
560 for (var k = 0u; k < P.p11.w; k = k + 1u) { vel = applyField(k, pos, vel, stepDt); }
562 if (P.p6.y > 0.0) { vel = vel * max(0.0, 1.0 - P.p6.y * stepDt); }
564 if ((flags & 32u) != 0u) { speedMul = lutF(1u, t); }
565 pos = pos + vel * speedMul * stepDt;
567 if ((flags & 4u) != 0u) {
568 let flow = curl(pos.xy * P.p6.w + P.p7.xy, P.p1.w);
569 pos = pos + vec3<f32>(flow, 0.0) * P.p6.z * stepDt;
572 if ((flags & (64u | 128u | 256u)) != 0u) {
575 if (local) { point = P.origin.xyz + R * pos; velW = R * vel; }
576 var collided = false;
577 if ((flags & 64u) != 0u && point.y < P.p9.w && velW.y < 0.0) {
578 hitPoint = vec3<f32>(point.x, P.p9.w, point.z);
579 hitNormal = vec3<f32>(0.0, 1.0, 0.0);
581 } else if ((flags & 128u) != 0u && P.p13.w > 0.5) {
582 collided = depthHit(point, velW, stepDt);
583 } else if ((flags & 256u) != 0u) {
584 collided = sdfHit(point, velW);
587 let approach = dot(velW, hitNormal);
588 let fr = clamp(P.p10.y, 0.0, 1.0);
589 let bounce = clamp(P.p10.x, 0.0, 1.0);
591 velW = (velW - hitNormal * approach) * (1.0 - fr) - hitNormal * approach * bounce;
594 pos = transpose(R) * (point - P.origin.xyz);
595 vel = transpose(R) * velW;
600 if ((flags & 2048u) != 0u) { emitEvent(2.0, point, incoming, hitNormal, i); }
601 age = age + clamp(P.p10.z, 0.0, 1.0) * life;
605 if ((flags & 1024u) != 0u) { emitEvent(0.0, point, velW, vec3<f32>(0.0), i); }
612 let rotation = st.ms.z + st.ms.w * stepDt;
613 st = State(vec4<f32>(pos, age), vec4<f32>(vel, life), vec4<f32>(st.ms.x, st.ms.y, rotation, st.ms.w));
616 var size = mix(st.ms.x, st.ms.y, ease(P.p8.w, t));
617 if ((flags & 8u) != 0u) { size = st.ms.x * lutF(0u, t); }
618 var color = mix(P.startColor, P.endColor, ease(P.p9.z, t));
619 if ((flags & 16u) != 0u) { color = lutC(t); }
625 let cols = max(P.p11.x, 1u);
626 let rows = max(P.p11.y, 1u);
627 let total = f32(cols * rows);
629 us = 1.0 / f32(cols);
630 vs = 1.0 / f32(rows);
632 let raw = age * P.p10.w;
633 var frameF = min(raw, total - 1.0);
634 if (P.p11.z != 0u) { frameF = raw - total * floor(raw / total); }
635 let fi = u32(frameF);
636 u0 = f32(fi % cols) * us;
637 v0 = f32(fi / cols) * vs;
642 var worldSize = vec2<f32>(size);
644 let rel3 = pos * vec3<f32>(P.local.z, P.local.w, 1.0);
645 worldPos = P.origin.xyz + vec3<f32>(rel3.x * P.local.x - rel3.y * P.local.y, rel3.x * P.local.y + rel3.y * P.local.x, rel3.z);
646 worldSize = worldSize * vec2<f32>(P.local.z, P.local.w);
648 let extra = vec4<f32>(clamp(age / life, 0.0, 1.0), f32(pcg(i) >> 8u) / 16777216.0, P.p15.z, life);
649 if ((flags & 8192u) != 0u) { stepTrail(i, worldPos, born, color, extra); }
650 worldPos = worldPos - P.shift.xyz;
651 insts[i] = Inst(worldPos.x, worldPos.y, worldPos.z, worldSize.x, worldSize.y, rotation, pack4x8unorm(color), u0, v0, us, vs, extra.x, extra.y, extra.z, extra.w);
656const char*
const kEventControl = R
"WGSL(
657struct Control { p: vec4<u32> };
658struct Events { count: atomic<u32>, head: u32, capacity: u32, pad: u32 };
659struct EventsIn { count: u32, head: u32, capacity: u32, pad: u32 };
660@group(0) @binding(0) var<uniform> C: Control;
661@group(0) @binding(1) var<storage, read_write> events: Events;
662@group(0) @binding(2) var<storage, read> parentEvents: EventsIn;
664@compute @workgroup_size(1)
666 atomicStore(&events.count, 0u);
667 events.capacity = C.p.x;
669@compute @workgroup_size(1)
671 let lit = min(min(parentEvents.count, parentEvents.capacity) * max(C.p.y, 1u), C.p.z);
672 events.head = (events.head + lit) % max(C.p.z, 1u);
677const char*
const kDepthCopy = R
"WGSL(
678struct Grid { size: vec4<u32> };
679@group(0) @binding(0) var<uniform> G: Grid;
680@group(0) @binding(1) var depth: texture_depth_2d;
681@group(0) @binding(2) var<storage, read_write> grid: array<f32>;
683@compute @workgroup_size(8, 8)
684fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
685 if (gid.x >= G.size.x || gid.y >= G.size.y) { return; }
686 let dims = vec2<f32>(textureDimensions(depth));
687 let at = (vec2<f32>(gid.xy) + 0.5) / vec2<f32>(G.size.xy) * dims;
688 let texel = clamp(vec2<i32>(at), vec2<i32>(0), vec2<i32>(dims) - vec2<i32>(1));
689 grid[gid.y * G.size.x + gid.x] = textureLoad(depth, texel, 0);
693void set4(
f32 (&dst)[4],
f32 a,
f32 b,
f32 c,
f32 d) { dst[0] = a; dst[1] = b; dst[2] = c; dst[3] = d; }
694void set4(
u32 (&dst)[4],
u32 a,
u32 b,
u32 c,
u32 d) { dst[0] = a; dst[1] = b; dst[2] = c; dst[3] = d; }
697f32 finite(
f32 v,
f32 fallback = 0.0f) {
return std::isfinite(v) ? v : fallback; }
723void GpuParticles::freeSlot(Slot& slot) {
734 for (
auto& [
id, slot] : slots_) freeSlot(slot);
742 for (
ComputeHandle* k : {&beginEvents_, &finishEvents_, &depthCopy_}) {
746 for (
BufferHandle* b : {&control_, &emptyRead_, &emptyEvents_, &emptyTrail_, &emptySegments_, &colliders_, &depthGrid_, &depthParams_}) {
750 controlCapacity_ = 0;
751 collidersCapacity_ = 0;
752 depthW_ = depthH_ = 0;
762 depthCopied_ =
false;
763 wantsDepth_ = wantsDepthNext_;
764 wantsDepthNext_ =
false;
767 for (
auto it = slots_.begin(); it != slots_.end();) {
768 if (frame_ > it->second.lastUsed + 300) {
769 freeSlot(it->second);
770 it = slots_.erase(it);
777bool GpuParticles::ensureKernel() {
779 if (failed_ || !device_.supportsCompute())
return false;
783 ES_LOG_ERROR(
"GpuParticles: the kernel did not compile: {}", log);
790bool GpuParticles::ensureEventKernels() {
794 finishEvents_ = device_.createCompute(GfxComputeSource{
GfxShaderLanguage::WGSL, kEventControl,
"finish"}, &log);
796 ES_LOG_ERROR(
"GpuParticles: the event kernels did not compile: {}", log);
802void GpuParticles::ensureEmpties() {
807 make(emptyRead_, 128);
808 make(emptyEvents_, 128);
809 make(emptyTrail_, 64);
810 make(emptySegments_, 64);
813void GpuParticles::pollReadbacks() {
814 for (
auto& [
id, slot] : slots_) {
821 std::vector<u8> bytes(slot.readbackBytes);
822 if (!device_.takeReadback(handle, bytes.data(), bytes.size()) || !slot.system)
continue;
824 std::memcpy(&total, bytes.data(),
sizeof(
u32));
825 const u32 kept = std::min(total, (slot.readbackBytes - kEventHeaderBytes) / kEventBytes);
826 std::vector<particle::CollisionEvent> out;
829 for (
u32 k = 0; k < kept; ++k) {
831 std::memcpy(r, bytes.data() + kEventHeaderBytes + k * kEventBytes,
sizeof(r));
832 if (r[3] < 1.5f)
continue;
834 out.push_back({id,
static_cast<u32>(r[11]), 0xffffffffu, slot.collisionMode,
835 r[0], r[1], r[2], r[8], r[9], r[10], r[4], r[5], r[6], 1u});
838 slot.system->addGpuCollisions(
Entity::fromRaw(
id), total > kept ? hits + (total - kept) : hits, out.data(),
static_cast<u32>(out.size()));
842GpuParticles::Slot* GpuParticles::ensureSlot(Entity entity,
u32 capacity) {
843 Slot& slot = slots_[entity.raw];
844 slot.lastUsed = frame_;
851 ES_LOG_ERROR(
"GpuParticles: could not allocate {} particles", capacity);
853 slots_.erase(entity.raw);
856 slot.capacity = capacity;
857 slot.lastUsed = frame_;
861bool GpuParticles::submit(Entity entity,
const ecs::ParticleEmitter& emitter,
const ecs::Transform& transform,
862 particle::ParticleSystem& system,
const particle::GpuStep& step,
const glm::vec4& eye,
864 if (!ensureKernel() || step.capacity == 0)
return false;
865 Slot* slot = ensureSlot(entity, step.capacity);
866 if (!slot)
return false;
867 instances = slot->instances;
868 drawn_ += step.drawCount;
869 slot->system = &system;
870 slot->collisionMode =
static_cast<u32>(emitter.collisionMode);
872 const bool collides = emitter.collisionEnabled;
873 const i32 mode = emitter.collisionMode;
876 if (depthMode) wantsDepthNext_ =
true;
879 const bool hasChild = emitter.subEmitter != 0;
880 const i32 trigger = emitter.subEmitterTrigger;
881 const u32 report = collides && emitter.collisionEvents ?
static_cast<u32>(std::clamp(emitter.collisionEventBudget, 0, 1024)) : 0u;
885 const bool emits = emitsBirth || emitsDeath || emitsHit;
886 const u32 eventCapacity = emits ? kMaxEvents : 1u;
887 if (emits || step.fed) {
888 const u32 bytes = kEventHeaderBytes + eventCapacity * kEventBytes;
892 slot->eventBytes = bytes;
897 const bool trailOn = emitter.trailEnabled && emitter.trailWidth > 0.0f;
905 slot->trailPoints = points;
907 ES_LOG_ERROR(
"GpuParticles: could not allocate trails for {} particles", step.capacity);
911 segments = slot->segments;
912 segmentCount = step.drawCount * (points - 1u);
916 for (
const Job& queued : jobs_) {
917 if (queued.entity == entity)
return true;
921 if (step.dt <= 0.0f && step.spawnCount == 0 && !step.reset && !local)
return true;
922 if (jobs_.size() >= kMaxJobs)
return true;
924 Job job{entity, {}, slot, &system, step};
925 ParamsBlock& b = job.
block;
926 std::memset(&b, 0,
sizeof(b));
929 if (step.reset) flags |= kReset;
930 if (local) flags |= kLocal;
931 const bool noiseOn = emitter.noiseStrength > 0.0f && emitter.noiseFrequency > 0.0f;
932 if (noiseOn) flags |= kNoise;
937 if (depthMode) flags |= kDepth;
938 if (sdfMode) flags |= kSdf;
939 if (emitsBirth) flags |= kEmitBirth;
940 if (emitsDeath) flags |= kEmitDeath;
941 if (emitsHit) flags |= kEmitHit;
942 if (step.fed) flags |= kFed;
943 if (trailOn) flags |= kTrail;
945 const auto* colorLut = system.colorLut(entity);
946 const auto* sizeLut = system.sizeLut(entity);
947 const auto* speedLut = system.speedLut(entity);
948 if (colorLut) flags |= kColorLut;
949 if (sizeLut) flags |= kSizeLut;
950 if (speedLut) flags |= kSpeedLut;
953 const u32 seed = entity.raw * 2246822519u + 3266489917u;
954 set4(b.p0, step.capacity, step.firstIndex, step.spawnCount, step.smoothCount);
955 set4(b.p1, seed, flags,
static_cast<u32>(std::clamp(emitter.shape, 0, 5)),
static_cast<u32>(std::clamp(emitter.noiseOctaves, 1, 8)));
956 set4(b.p2, step.dt, step.noiseTime, finite(emitter.lifetimeMin), finite(emitter.lifetimeMax));
957 set4(b.p3, finite(emitter.speedMin), finite(emitter.speedMax), finite(emitter.startSizeMin), finite(emitter.startSizeMax));
958 set4(b.p4, finite(emitter.endSizeMin), finite(emitter.endSizeMax), finite(emitter.rotationMin), finite(emitter.rotationMax));
959 set4(b.p5, finite(emitter.angularVelocityMin), finite(emitter.angularVelocityMax), finite(emitter.gravity.x), finite(emitter.gravity.y));
960 set4(b.p6, finite(emitter.gravity.z), finite(emitter.damping), finite(emitter.noiseStrength), finite(emitter.noiseFrequency));
961 const f32 scroll = emitter.noiseScrollSpeed * step.noiseTime * emitter.noiseFrequency;
962 set4(b.p7, finite(scroll), finite(scroll), finite(emitter.shapeRadius), finite(emitter.shapeAngle * 0.5f *
math::DEG_TO_RAD));
963 set4(b.p8, finite(emitter.shapeSize.x), finite(emitter.shapeSize.y), finite(emitter.shapeSize.z),
static_cast<f32>(emitter.sizeEasing));
965 static_cast<f32>(emitter.colorEasing), finite(emitter.collisionFloor));
966 set4(b.p10, finite(emitter.collisionBounce), finite(emitter.collisionFriction), finite(emitter.collisionLifetimeLoss), finite(emitter.spriteFPS));
967 const std::vector<particle::ForceFieldInstance>& fields = system.forceFields();
968 const u32 fieldCount = local ? 0u :
static_cast<u32>(std::min<std::size_t>(fields.size(), kMaxFields));
969 set4(b.p11,
static_cast<u32>(std::max(emitter.spriteColumns, 1)),
static_cast<u32>(std::max(emitter.spriteRows, 1)),
970 emitter.spriteLoop ? 1u : 0u, fieldCount);
971 set4(b.startColor, emitter.startColor.r, emitter.startColor.g, emitter.startColor.b, emitter.startColor.a);
972 set4(b.endColor, emitter.endColor.r, emitter.endColor.g, emitter.endColor.b, emitter.endColor.a);
974 const glm::vec3 position = transform.worldPosition;
975 const glm::vec3 scale = transform.worldScale;
976 set4(b.origin, position.x, position.y, position.z, 0.0f);
977 set4(b.scale, scale.x, scale.y, scale.z, 0.0f);
978 const glm::mat3 rot = glm::mat3_cast(transform.worldRotation);
979 set4(b.rot0, rot[0].x, rot[0].y, rot[0].z, 0.0f);
980 set4(b.rot1, rot[1].x, rot[1].y, rot[1].z, 0.0f);
981 set4(b.rot2, rot[2].x, rot[2].y, rot[2].z, 0.0f);
982 f32 angle = 2.0f * std::atan2(transform.worldRotation.z, transform.worldRotation.w);
983 if (std::abs(angle) <= 0.001f) angle = 0.0f;
984 set4(b.local, std::cos(angle), std::sin(angle), scale.x, scale.y);
986 set4(b.shift,
static_cast<f32>(origin.x),
static_cast<f32>(origin.y),
static_cast<f32>(origin.z), 0.0f);
988 for (
u32 k = 0; k < fieldCount; ++k) {
992 set4(b.fields[k * 3 + 2], f.
radius, f.
falloff ? 1.0f : 0.0f, 0.0f, 0.0f);
995 for (
u32 k = 0; k < kLutSize; ++k) set4(b.colorLut[k], (*colorLut)[k].r, (*colorLut)[k].g, (*colorLut)[k].b, (*colorLut)[k].a);
997 for (
u32 k = 0; k < kLutSize; ++k) {
998 if (sizeLut) b.sizeLut[k >> 2][k & 3] = (*sizeLut)[k];
999 if (speedLut) b.speedLut[k >> 2][k & 3] = (*speedLut)[k];
1002 set4(b.p12,
static_cast<u32>(frame_), eventCapacity,
static_cast<u32>(std::max(emitter.burstCount, 1)),
1003 sdfMode ?
static_cast<u32>(std::min<std::size_t>(system.sdfColliders().size(), kMaxColliders)) : 0u);
1005 set4(b.p13, report > 0 || !hasChild ? 1.0f : std::clamp(finite(emitter.subEmitterChance, 1.0f), 0.0f, 1.0f), 0.0f,
1006 std::max(finite(emitter.collisionThickness), 0.0f), 0.0f);
1007 set4(b.p14, points, emitter.collisionMask & 0xffffu, depthW_, depthH_);
1008 set4(b.p15, finite(emitter.trailWidth), std::max(finite(emitter.trailMinDistance), 0.0f), std::max(finite(emitter.intensity), 0.0f), 0.0f);
1009 set4(b.camera, eye.x, eye.y, eye.z, eye.w);
1011 job.
inheritVelocity = std::clamp(finite(emitter.subEmitterInheritVelocity), 0.0f, 1.0f);
1015 jobs_.push_back(job);
1021 depthCopied_ =
true;
1029 pass.
name =
"gpu_particle_depth";
1042 ES_LOG_ERROR(
"GpuParticles: the depth copy did not compile: {}", log);
1046 const u32 w = std::max(std::min(sceneW, depthGridMax_), 1u);
1047 const u32 h = std::max(1u,
static_cast<u32>(
static_cast<u64>(sceneH) * w / std::max(sceneW, 1u)));
1059 const u32 size[4] = {w, h, 0, 0};
1060 device_.updateBuffer(depthParams_, 0, size,
sizeof(size));
1061 const GfxComputeBinding bindings[3] = {
1066 if (device_.dispatchCompute(depthCopy_, bindings, 3, (w + 7) / 8, (h + 7) / 8)) {
1069 depthWorld_ = glm::inverse(clip);
1070 depthOrigin_ = glm::vec3(origin);
1073 graph.
addPass(std::move(pass));
1077 depthGridMax_ = std::clamp(texels, kDepthGridMin, kDepthGridMax);
1091 pass.
name =
"gpu_particles";
1095 graph.
addPass(std::move(pass));
1099void GpuParticles::run() {
1101 const u32 needed =
static_cast<u32>(jobs_.size()) * kJobStride;
1104 paramsCapacity_ = std::max(needed, kJobStride * 8u);
1107 paramsCapacity_ = 0;
1114 const std::size_t jobCount = jobs_.size();
1115 parent_.assign(jobCount, -1);
1116 for (std::size_t child = 0; child < jobCount; ++child) {
1117 for (std::size_t candidate = 0; candidate < jobCount; ++candidate) {
1118 if (candidate != child && jobs_[candidate].subEmitter == jobs_[child].entity.raw) {
1119 parent_[child] =
static_cast<i32>(candidate);
1124 const auto parentOf = [
this](
const Job& child) ->
Job* {
1125 const i32 parent = parent_[
static_cast<std::size_t
>(&child - jobs_.data())];
1126 return parent >= 0 ? &jobs_[
static_cast<std::size_t
>(parent)] : nullptr;
1129 placed_.assign(jobCount, 0);
1130 const auto place = [&](
auto&& self,
Job& job,
u32 depth) ->
void {
1131 const std::size_t index =
static_cast<std::size_t
>(&job - jobs_.data());
1132 if (placed_[index])
return;
1134 if (depth < kMaxJobs) {
1135 if (
Job* parent = parentOf(job)) self(self, *parent, depth + 1);
1137 order_.push_back(&job);
1139 for (
Job& job : jobs_) place(place, job, 0);
1141 const std::vector<particle::SdfColliderInstance>& colliders = jobs_.front().system->sdfColliders();
1142 const u32 colliderBytes =
static_cast<u32>(std::min<std::size_t>(colliders.size(), kMaxColliders)) *
sizeof(particle::SdfColliderInstance);
1143 if (colliderBytes > 0 && (colliders_ ==
BufferHandle::Invalid || collidersCapacity_ < colliderBytes)) {
1145 collidersCapacity_ = kMaxColliders *
sizeof(particle::SdfColliderInstance);
1148 if (colliderBytes > 0 && colliders_ !=
BufferHandle::Invalid) device_.updateBuffer(colliders_, 0, colliders.data(), colliderBytes);
1150 staging_.assign(needed, 0);
1151 for (std::size_t i = 0; i < jobs_.size(); ++i) {
1152 Job& job = jobs_[i];
1153 if (
const Job* parent = parentOf(job)) job.
block.p13[1] = parent->inheritVelocity;
1155 job.block.p13[3] = 1.0f;
1156 set4(job.block.p14, job.block.p14[0], job.block.p14[1], depthW_, depthH_);
1157 std::memcpy(job.block.depthClip, &depthClip_[0][0],
sizeof(job.block.depthClip));
1158 std::memcpy(job.block.depthWorld, &depthWorld_[0][0],
sizeof(job.block.depthWorld));
1159 set4(job.block.depthOrigin, depthOrigin_.x, depthOrigin_.y, depthOrigin_.z, 0.0f);
1161 std::memcpy(staging_.data() + i * kJobStride, &job.block,
sizeof(ParamsBlock));
1163 device_.updateBuffer(params_, 0, staging_.data(), needed);
1165 bool anyEvents =
false;
1168 if (!ensureEventKernels()) anyEvents =
false;
1169 const u32 controlBytes =
static_cast<u32>(jobs_.size()) * 256u;
1172 controlCapacity_ = std::max(controlBytes, 256u * 8u);
1177 control_staging_.assign(controlBytes, 0);
1178 for (std::size_t i = 0; i < jobs_.size(); ++i) {
1179 const u32 words[4] = {jobs_[i].eventCapacity, jobs_[i].block.p12[2], jobs_[i].slot->capacity, 0u};
1180 std::memcpy(control_staging_.data() + i * 256u, words,
sizeof(words));
1182 device_.updateBuffer(control_, 0, control_staging_.data(), controlBytes);
1186 for (
Job* jobPtr : order_) {
1187 const Job& job = *jobPtr;
1188 const u32 i =
static_cast<u32>(jobPtr - jobs_.data());
1189 const Job* parent = parentOf(job);
1191 const bool fed = (job.block.p1[1] & kFed) != 0u;
1195 const GfxComputeBinding control[2] = {
1199 device_.dispatchCompute(beginEvents_, control, 2, 1);
1201 const GfxComputeBinding bindings[9] = {
1212 if (device_.dispatchCompute(kernel_, bindings, 9, (job.slot->capacity + 63) / 64)) {
1214 job.system->commitGpuStep(job.entity, job.step);
1216 if (controlled && fed) {
1217 const GfxComputeBinding control[3] = {
1222 device_.dispatchCompute(finishEvents_, control, 3, 1);
1225 job.slot->readbackBytes = kEventHeaderBytes + std::min(job.reportEvents, job.eventCapacity) * kEventBytes;
1226 job.slot->readback = device_.requestBufferReadback(job.slot->events, 0, job.slot->readbackBytes);
Abstract graphics device interface.
Particles simulated by a compute kernel, drawn from the buffer the kernel wrote (WebGPU).
Logging utilities for ESEngine.
#define ES_LOG_ERROR(...)
Logs an error message.
The point the frame is drawn relative to: a world far from zero loses precision in single floats,...
static constexpr GfxContent transient()
Abstract graphics device interface.
void deleteCompute(ComputeHandle program)
Deletes a compute program.
BufferHandle createBuffer(const BufferDesc &desc, GfxContent content, const void *initialData)
Creates a buffer with fixed capacity and optional initial contents.
virtual void discardReadback(ReadbackHandle handle)=0
Abandons a readback (any state); its resources are released.
ComputeHandle createCompute(const GfxComputeSource &source, std::string *outLog=nullptr)
Compiles a compute program.
void deleteBuffer(BufferHandle buffer)
Deletes a buffer.
virtual bool supportsCompute() const
Whether this device runs compute shaders.
void beginFrame()
A new frame: the previous frame's jobs are gone, and a slot nobody asked for in a while is given back...
bool submit(Entity entity, const ecs::ParticleEmitter &emitter, const ecs::Transform &transform, particle::ParticleSystem &system, const particle::GpuStep &step, const glm::vec4 &eye, BufferHandle &instances, BufferHandle &segments, u32 &segmentCount)
Queues the step an emitter needs and says where its particles are. The step is committed to the emitt...
void setDepthGridMax(u32 texels)
rg::ResourceId declare(rg::RenderGraph &graph)
Adds the compute pass for what was submitted. The resource it writes must be named by the pass that d...
void declareDepthCopy(rg::RenderGraph &graph, rg::ResourceId scene, u32 sceneW, u32 sceneH, const glm::mat4 &clip)
Copies the scene's depth for next frame's kernel, once a frame. clip is the view that drew it,...
GpuParticles(GfxDevice &device)
bool available() const
Whether the device can run the kernel at all.
void addPass(PassDesc pass)
ResourceId createTarget(const TargetDesc &desc)
TextureHandle depthTextureOf(ResourceId id) const
constexpr float DEG_TO_RAD
Degrees to radians conversion factor.
constexpr int kColorLutSize
constexpr int kMaxTrailPoints
constexpr ResourceId kNoResource
std::int32_t i32
Signed 32-bit integer.
std::uint64_t u64
Unsigned 64-bit integer.
@ Storage
Read and written by compute shaders (var<storage, read_write>), and readable back....
ComputeHandle
A compute program (GfxDevice::createCompute); only a device that supportsCompute() issues one.
GfxReadbackStatus
State of an in-flight readback. GL completes at request time (first poll reports Ready); WebGPU resol...
std::uint32_t u32
Unsigned 32-bit integer.
glm::dvec3 & renderOrigin()
The origin, in world units. A double, as the world positions it is taken from are far from zero.
static constexpr u32 PARTICLE_INSTANCE_STRIDE
ReadbackHandle
An in-flight framebuffer readback (GfxDevice::requestReadback).
float f32
32-bit floating point
static constexpr Entity fromRaw(u32 v)
Reconstructs an Entity from a raw packed value.
static GfxComputeBinding depth(u32 binding, TextureHandle texture)
static GfxComputeBinding uniform(u32 binding, BufferHandle buffer, u32 offset=0, u32 size=0)
static GfxComputeBinding storageRead(u32 binding, BufferHandle buffer, u32 offset=0, u32 size=0)
static GfxComputeBinding storage(u32 binding, BufferHandle buffer, u32 offset=0, u32 size=0)
f32 inheritVelocity
What of a parent's speed that child keeps.
particle::ParticleSystem * system
u32 subEmitter
The child its events feed.
u32 reportEvents
How many of its events the game asks to hear about.
What one frame asks of a GPU-simulated emitter: how long to advance, how many to spawn and where in t...
std::function< void(const PassContext &)> execute
bool compute
A compute pass: no render pass is opened and no unit is bound — execute dispatches,...
std::vector< ResourceId > dependencies
Resources the pass uses but the graph must not bind.
bool keep
Wanted by a later frame rather than by this picture: not culled for nothing having read it yet.
Shape of a target the graph allocates.
bool storage
Written by a compute shader (a pass with compute set), then sampled like any target.