Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
GpuParticles.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#include "./GpuParticles.hpp"
5#include "../../core/Log.hpp"
8#include "../RenderOrigin.hpp"
10
11#include <algorithm>
12#include <cmath>
13#include <cstring>
14
15namespace esengine {
16
17namespace {
18
19constexpr u32 kInstanceBytes = PARTICLE_INSTANCE_STRIDE;
20// Position + age, velocity + lifetime, then start size, end size, rotation, angular velocity.
21constexpr u32 kStateBytes = 48;
22
23constexpr u32 kMaxFields = 8;
24constexpr u32 kLutSize = particle::kColorLutSize;
25static_assert(kLutSize == 32, "the kernel's LUT arrays are sized for 32 entries");
26
27enum Flags : u32 {
28 kReset = 1u << 0,
29 kLocal = 1u << 1,
30 kNoise = 1u << 2,
31 kSizeLut = 1u << 3,
32 kColorLut = 1u << 4,
33 kSpeedLut = 1u << 5,
34 kFloor = 1u << 6,
35 kDepth = 1u << 7,
36 kSdf = 1u << 8,
37 kEmitBirth = 1u << 9,
38 kEmitDeath = 1u << 10,
39 kEmitHit = 1u << 11,
40 kFed = 1u << 12,
41 kTrail = 1u << 13,
42};
43
44// An event a kernel appends and another reads: where and which kind, how fast, and the surface it hit with the slot that hit it.
45constexpr u32 kEventBytes = 48;
46constexpr u32 kEventHeaderBytes = 16;
47// The most events one emitter keeps of a frame. Past it they are dropped: a child would have nowhere to put so many anyway.
48constexpr u32 kMaxEvents = 4096;
49constexpr u32 kMaxColliders = 64;
50static_assert(sizeof(particle::SdfColliderInstance) == 64, "the kernel's Collider is 64 bytes");
51constexpr u32 kDepthGridMin = 64;
52constexpr u32 kDepthGridMax = 640;
53
54// Mirrors the kernel's `Params`: vec4s only, so the layout is the same in both languages with no padding to get wrong.
55struct ParamsBlock {
56 u32 p0[4]; // capacity, firstIndex, spawnCount, smoothCount
57 u32 p1[4]; // seed, flags, shape, octaves
58 f32 p2[4]; // dt, noiseTime, lifetimeMin, lifetimeMax
59 f32 p3[4]; // speedMin, speedMax, startSizeMin, startSizeMax
60 f32 p4[4]; // endSizeMin, endSizeMax, rotationMin, rotationMax
61 f32 p5[4]; // angularVelocityMin, angularVelocityMax, gravity.x, gravity.y
62 f32 p6[4]; // gravity.z, damping, noiseStrength, noiseFrequency
63 f32 p7[4]; // noiseScroll.x, noiseScroll.y, shapeRadius, shapeHalfAngle
64 f32 p8[4]; // shapeSize.xyz, sizeEasing
65 f32 p9[4]; // aimMin, aimMax (radians), colorEasing, floorY
66 f32 p10[4]; // bounce, friction, lifetimeLoss, spriteFPS
67 u32 p11[4]; // spriteColumns, spriteRows, spriteLoop, fieldCount
68 f32 startColor[4];
69 f32 endColor[4];
70 f32 origin[4]; // emitter position
71 f32 scale[4]; // emitter scale
72 f32 rot0[4], rot1[4], rot2[4]; // emitter rotation, one column each
73 f32 local[4]; // cos, sin of the emitter's turn about Z; scale.x, scale.y
74 f32 shift[4]; // the render origin, taken from each particle's world position as it is written for drawing
75 f32 fields[kMaxFields * 3][4];
76 f32 colorLut[kLutSize][4];
77 f32 sizeLut[kLutSize / 4][4];
78 f32 speedLut[kLutSize / 4][4];
79 u32 p12[4]; // frame, eventCapacity, subBurst, colliderCount
80 f32 p13[4]; // eventChance, inheritVelocity, thickness, depthValid
81 u32 p14[4]; // trailPoints, collisionMask, depthGridW, depthGridH
82 f32 p15[4];
83 f32 camera[4]; // the eye (w 1) or the way to the viewer (w 0), as the draw's vertex stage has it
84 f32 depthClip[4][4], depthWorld[4][4]; // the view the depth was left by, and its inverse
85 f32 depthOrigin[4]; // the render origin it was seen from
86};
87static_assert(sizeof(ParamsBlock) == 107 * 16, "the kernel's Params is 107 vec4s");
88constexpr u32 kJobStride = 2048; // a uniform binding starts on a multiple of 256
89static_assert(sizeof(ParamsBlock) <= kJobStride && kJobStride % 256 == 0);
90constexpr u32 kMaxJobs = 64;
91
92// In pieces: MSVC refuses one string literal past 16 KB, and takes adjacent ones to 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 };
96struct Params {
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>,
100 p11: vec4<u32>,
101 startColor: vec4<f32>, endColor: vec4<f32>,
102 origin: vec4<f32>, scale: vec4<f32>,
103 rot0: vec4<f32>, rot1: vec4<f32>, rot2: vec4<f32>,
104 local: vec4<f32>,
105 shift: 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>,
111 camera: vec4<f32>,
112 depthClip: mat4x4<f32>, depthWorld: mat4x4<f32>,
113 depthOrigin: vec4<f32>,
114};
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>;
128
129var<private> rng: u32;
130var<private> hitPoint: vec3<f32>;
131var<private> hitNormal: vec3<f32>;
132
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;
137}
138fn rand() -> f32 {
139 rng = pcg(rng);
140 return f32(rng) * 2.3283064365386963e-10;
141}
142fn rr(a: f32, b: f32) -> f32 {
143 if (a >= b) { return a; }
144 return a + (b - a) * rand();
145}
146
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));
153}
154fn planarAim() -> vec3<f32> {
155 let a = rr(P.p9.x, P.p9.y);
156 return vec3<f32>(cos(a), sin(a), 0.0);
157}
158
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;
163 h = h ^ (h >> 16u);
164 return f32(h) * (1.0 / 4294967295.0);
165}
166fn grad2(x: i32, y: i32) -> vec2<f32> {
167 let a = hash2(x, y) * 6.283185307179586;
168 return vec2<f32>(cos(a), sin(a));
169}
170fn fade(t: f32) -> f32 { return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); }
171fn perlin2(p: vec2<f32>) -> f32 {
172 let pi = floor(p);
173 let pf = p - pi;
174 let x0 = i32(pi.x);
175 let y0 = i32(pi.y);
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));
180 let ux = fade(pf.x);
181 let uy = fade(pf.y);
182 return mix(mix(n00, n10, ux), mix(n01, n11, ux), uy);
183}
184fn fbm2(p: vec2<f32>, octaves: u32) -> f32 {
185 var sum = 0.0;
186 var amp = 1.0;
187 var freq = 1.0;
188 var norm = 0.0;
189 let n = clamp(octaves, 1u, 8u);
190 for (var i = 0u; i < n; i = i + 1u) {
191 sum = sum + amp * perlin2(p * freq);
192 norm = norm + amp;
193 freq = freq * 2.0;
194 amp = amp * 0.5;
195 }
196 if (norm > 0.0) { return sum / norm; }
197 return 0.0;
198}
199fn curl(p: vec2<f32>, octaves: u32) -> vec2<f32> {
200 let e = 0.1;
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));
204}
205
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; }
210 return t;
211}
212
213fn lutF(which: u32, t: f32) -> f32 {
214 let f = clamp(t, 0.0, 1.0) * 31.0;
215 let i = u32(f);
216 let j = min(i + 1u, 31u);
217 var a: f32;
218 var b: f32;
219 if (which == 0u) {
220 a = P.sizeLut[i >> 2u][i & 3u];
221 b = P.sizeLut[j >> 2u][j & 3u];
222 } else {
223 a = P.speedLut[i >> 2u][i & 3u];
224 b = P.speedLut[j >> 2u][j & 3u];
225 }
226 return mix(a, b, f - f32(i));
227}
228fn lutC(t: f32) -> vec4<f32> {
229 let f = clamp(t, 0.0, 1.0) * 31.0;
230 let i = u32(f);
231 let j = min(i + 1u, 31u);
232 return mix(P.colorLut[i], P.colorLut[j], f - f32(i));
233}
234
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);
242 var factor = 1.0;
243 if (c.x > 0.0) {
244 if (distSq > c.x * c.x) { return vel; }
245 if (c.y > 0.5) { factor = 1.0 - sqrt(distSq) / c.x; }
246 }
247 let strength = b.w;
248 var v = vel;
249 let kind = u32(a.w + 0.5);
250 if (kind == 0u) {
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);
257 if (d > 1e-4) {
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); }
264 }
265 } else {
266 v = v * (1.0 - min(strength * factor * dt, 1.0));
267 }
268 return v;
269}
270
271fn hide(i: u32) {
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);
277 }
278 }
279}
280
281)WGSL" R"WGSL(
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);
286 if (k < P.p12.y) {
287 events.rec[k] = EventRec(vec4<f32>(at, kind), vec4<f32>(vel, 0.0), vec4<f32>(normal, f32(slot)));
288 }
289}
290
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)];
297}
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;
301}
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);
304}
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.
322 var normal = -ray;
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);
336 if (size > 1e-8) {
337 normal = n / size;
338 if (dot(normal, ray) > 0.0) { normal = -normal; }
339 }
340 }
341 if (dot(vel, normal) >= 0.0) { return false; }
342 hitNormal = normal;
343 hitPoint = surface + P.depthOrigin.xyz + normal * (0.001 * P.p13.z);
344 return true;
345}
346
347// --- the distance functions (ParticleSystem sdfDistance) ---
348fn turnBack(q: vec4<f32>, v: vec3<f32>) -> vec3<f32> {
349 let u = -q.xyz;
350 return v + 2.0 * cross(u, cross(u, v) + q.w * v);
351}
352fn sdfOne(k: u32, point: vec3<f32>) -> f32 {
353 let c = colliders[k];
354 let q = turnBack(c.rot, point - c.at.xyz);
355 var d: f32;
356 if (c.at.w > 1.5) {
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);
362 } else {
363 d = length(q) - c.ext.x;
364 }
365 if (c.ext.w > 0.5) { return -d; }
366 return d;
367}
368fn sdfHit(point: vec3<f32>, vel: vec3<f32>) -> bool {
369 var least = 0.0;
370 var found = P.p12.w;
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; }
375 }
376 if (found == P.p12.w) { return false; }
377 let e = max(0.01, -least * 0.1);
378 let g = vec3<f32>(
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; }
386 hitNormal = normal;
387 hitPoint = point - normal * least;
388 return true;
389}
390
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);
400 let d = b - a;
401 let x = dot(d, right);
402 let y = dot(d, up);
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);
404}
405fn stepTrail(i: u32, head: vec3<f32>, born: bool, color: vec4<f32>, extra: vec4<f32>) {
406 let points = P.p14.x;
407 let n = points - 1u;
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);
412 count = 1u;
413 } else {
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));
419 }
420 }
421 var prev = head;
422 for (var j = 0u; j < n; j = j + 1u) {
423 if (j >= count) {
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);
425 continue;
426 }
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);
430 prev = next;
431 }
432}
433
434)WGSL" R"WGSL(
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);
441
442 var pos = vec3<f32>(0.0);
443 var dir = vec3<f32>(0.0, 1.0, 0.0);
444 let shape = P.p1.z;
445 if (shape == 1u) {
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);
454 var z = 0.0;
455 if (P.p8.z > 0.0) { z = rr(-h.z, h.z); }
456 pos = vec3<f32>(x, y, z);
457 dir = planarAim();
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; }
464 dir = coneDir(cap2);
465 pos = coneDir(cap2) * (P.p7.z * pow(rr(0.0, 1.0), 1.0 / 3.0));
466 } else {
467 dir = planarAim();
468 }
469 let speed = rr(P.p3.x, P.p3.y);
470 let R = mat3x3<f32>(P.rot0.xyz, P.rot1.xyz, P.rot2.xyz);
471 var wpos: vec3<f32>;
472 var wdir: vec3<f32>;
473 if (!world) {
474 wpos = origin + pos * P.scale.xyz;
475 wdir = dir;
476 } else {
477 wpos = origin + R * (pos * P.scale.xyz);
478 wdir = R * dir;
479 }
480 return State(vec4<f32>(wpos, 0.0), vec4<f32>(wdir * speed + inherit, max(life, 1e-4)), vec4<f32>(startSize, endSize, rot, angVel));
481}
482
483@compute @workgroup_size(64)
484fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
485 let cap = P.p0.x;
486 let i = gid.x;
487 if (i >= cap) { return; }
488 let flags = P.p1.y;
489 if ((flags & 1u) != 0u) {
490 states[i] = State(vec4<f32>(0.0), vec4<f32>(0.0), vec4<f32>(0.0));
491 hide(i);
492 return;
493 }
494 let local = (flags & 2u) != 0u;
495 let R = mat3x3<f32>(P.rot0.xyz, P.rot1.xyz, P.rot2.xyz);
496 let dt = P.p2.x;
497
498 var st = states[i];
499 var stepDt = dt;
500 var born = false;
501 rng = pcg(P.p1.x ^ (i * 2654435761u) ^ (P.p12.x * 40503u));
502
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;
506 if (rel < P.p0.z) {
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);
511 born = true;
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));
522 var at = e.at.xyz;
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);
526 born = true;
527 }
528 }
529 if (!born && st.pa.w >= st.vl.w) {
530 hide(i);
531 return;
532 }
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);
538 }
539
540 let life = st.vl.w;
541 var age = st.pa.w + stepDt;
542 if (age >= life) {
543 st.pa.w = life;
544 states[i] = st;
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);
550 }
551 hide(i);
552 return;
553 }
554 var pos = st.pa.xyz;
555 var vel = st.vl.xyz;
556 let t = age / life;
557
558 vel = vel + vec3<f32>(P.p5.z, P.p5.w, P.p6.x) * stepDt;
559 if (!local) {
560 for (var k = 0u; k < P.p11.w; k = k + 1u) { vel = applyField(k, pos, vel, stepDt); }
561 }
562 if (P.p6.y > 0.0) { vel = vel * max(0.0, 1.0 - P.p6.y * stepDt); }
563 var speedMul = 1.0;
564 if ((flags & 32u) != 0u) { speedMul = lutF(1u, t); }
565 pos = pos + vel * speedMul * stepDt;
566
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;
570 }
571
572 if ((flags & (64u | 128u | 256u)) != 0u) {
573 var point = pos;
574 var velW = vel;
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);
580 collided = true;
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);
585 }
586 if (collided) {
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);
590 let incoming = velW;
591 velW = (velW - hitNormal * approach) * (1.0 - fr) - hitNormal * approach * bounce;
592 point = hitPoint;
593 if (local) {
594 pos = transpose(R) * (point - P.origin.xyz);
595 vel = transpose(R) * velW;
596 } else {
597 pos = point;
598 vel = velW;
599 }
600 if ((flags & 2048u) != 0u) { emitEvent(2.0, point, incoming, hitNormal, i); }
601 age = age + clamp(P.p10.z, 0.0, 1.0) * life;
602 if (age >= life) {
603 st.pa.w = life;
604 states[i] = st;
605 if ((flags & 1024u) != 0u) { emitEvent(0.0, point, velW, vec3<f32>(0.0), i); }
606 hide(i);
607 return;
608 }
609 }
610 }
611
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));
614 states[i] = st;
615
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); }
620
621 var u0 = 0.0;
622 var v0 = 0.0;
623 var us = 1.0;
624 var vs = 1.0;
625 let cols = max(P.p11.x, 1u);
626 let rows = max(P.p11.y, 1u);
627 let total = f32(cols * rows);
628 if (total > 1.0) {
629 us = 1.0 / f32(cols);
630 vs = 1.0 / f32(rows);
631 if (P.p10.w > 0.0) {
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;
638 }
639 }
640
641 var worldPos = pos;
642 var worldSize = vec2<f32>(size);
643 if (local) {
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);
647 }
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);
652}
653)WGSL";
654
655// Before an emitter's kernel: its events are this frame's. After: the ring has moved on by what its parent lit.
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;
663
664@compute @workgroup_size(1)
665fn begin() {
666 atomicStore(&events.count, 0u);
667 events.capacity = C.p.x;
668}
669@compute @workgroup_size(1)
670fn finish() {
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);
673}
674)WGSL";
675
676// The scene's depth left where next frame's kernel can read it: no texture survives a graph, and a buffer is what the kernel already has.
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>;
682
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);
690}
691)WGSL";
692
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; }
695
696// A finite, non-negative range: a bad value reaching a kernel is a hung or poisoned buffer, and nothing reads it back.
697f32 finite(f32 v, f32 fallback = 0.0f) { return std::isfinite(v) ? v : fallback; }
698
699} // namespace
700
701struct GpuParticles::Job {
702 Entity entity;
714
716 release();
718
719bool GpuParticles::available() const {
720 return !failed_ && device_.supportsCompute();
722
723void GpuParticles::freeSlot(Slot& slot) {
724 if (slot.state != BufferHandle::Invalid) device_.deleteBuffer(slot.state);
725 if (slot.instances != BufferHandle::Invalid) device_.deleteBuffer(slot.instances);
726 if (slot.events != BufferHandle::Invalid) device_.deleteBuffer(slot.events);
727 if (slot.trail != BufferHandle::Invalid) device_.deleteBuffer(slot.trail);
728 if (slot.segments != BufferHandle::Invalid) device_.deleteBuffer(slot.segments);
729 if (slot.readback != ReadbackHandle::Invalid) device_.discardReadback(slot.readback);
730 slot = {};
731}
732
734 for (auto& [id, slot] : slots_) freeSlot(slot);
735 slots_.clear();
736 jobs_.clear();
737 if (params_ != BufferHandle::Invalid) device_.deleteBuffer(params_);
738 params_ = BufferHandle::Invalid;
739 paramsCapacity_ = 0;
740 if (kernel_ != ComputeHandle::Invalid) device_.deleteCompute(kernel_);
741 kernel_ = ComputeHandle::Invalid;
742 for (ComputeHandle* k : {&beginEvents_, &finishEvents_, &depthCopy_}) {
743 if (*k != ComputeHandle::Invalid) device_.deleteCompute(*k);
745 }
746 for (BufferHandle* b : {&control_, &emptyRead_, &emptyEvents_, &emptyTrail_, &emptySegments_, &colliders_, &depthGrid_, &depthParams_}) {
747 if (*b != BufferHandle::Invalid) device_.deleteBuffer(*b);
749 }
750 controlCapacity_ = 0;
751 collidersCapacity_ = 0;
752 depthW_ = depthH_ = 0;
753 depthValid_ = false;
754 failed_ = false;
755}
756
758 ++frame_;
759 jobs_.clear();
760 lastDispatches_ = 0;
761 drawn_ = 0;
762 depthCopied_ = false;
763 wantsDepth_ = wantsDepthNext_;
764 wantsDepthNext_ = false;
765 pollReadbacks();
766 // Given back after a few seconds unseen: an emitter off screen keeps its particles for a moment, not for ever.
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);
771 } else {
772 ++it;
773 }
774 }
775}
776
777bool GpuParticles::ensureKernel() {
778 if (kernel_ != ComputeHandle::Invalid) return true;
779 if (failed_ || !device_.supportsCompute()) return false;
780 std::string log;
781 kernel_ = device_.createCompute(GfxComputeSource{GfxShaderLanguage::WGSL, kKernel, "main"}, &log);
782 if (kernel_ == ComputeHandle::Invalid) {
783 ES_LOG_ERROR("GpuParticles: the kernel did not compile: {}", log);
784 failed_ = true;
785 return false;
786 }
787 return true;
788}
789
790bool GpuParticles::ensureEventKernels() {
791 if (beginEvents_ != ComputeHandle::Invalid && finishEvents_ != ComputeHandle::Invalid) return true;
792 std::string log;
793 beginEvents_ = device_.createCompute(GfxComputeSource{GfxShaderLanguage::WGSL, kEventControl, "begin"}, &log);
794 finishEvents_ = device_.createCompute(GfxComputeSource{GfxShaderLanguage::WGSL, kEventControl, "finish"}, &log);
795 if (beginEvents_ == ComputeHandle::Invalid || finishEvents_ == ComputeHandle::Invalid) {
796 ES_LOG_ERROR("GpuParticles: the event kernels did not compile: {}", log);
797 return false;
798 }
799 return true;
800}
801
802void GpuParticles::ensureEmpties() {
803 // A kernel's layout is fixed, so what an emitter does not use is still bound; written-to bindings may not share a buffer.
804 const auto make = [this](BufferHandle& b, u32 size) {
805 if (b == BufferHandle::Invalid) b = device_.createBuffer({GfxBufferUsage::Storage, size, false}, GfxContent::transient(), nullptr);
806 };
807 make(emptyRead_, 128);
808 make(emptyEvents_, 128);
809 make(emptyTrail_, 64);
810 make(emptySegments_, 64);
811}
812
813void GpuParticles::pollReadbacks() {
814 for (auto& [id, slot] : slots_) {
815 if (slot.readback == ReadbackHandle::Invalid) continue;
816 const GfxReadbackStatus status = device_.pollReadback(slot.readback);
817 if (status == GfxReadbackStatus::Pending) continue;
818 const ReadbackHandle handle = slot.readback;
819 slot.readback = ReadbackHandle::Invalid;
820 if (status != GfxReadbackStatus::Ready) continue;
821 std::vector<u8> bytes(slot.readbackBytes);
822 if (!device_.takeReadback(handle, bytes.data(), bytes.size()) || !slot.system) continue;
823 u32 total = 0;
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;
827 out.reserve(kept);
828 u32 hits = 0;
829 for (u32 k = 0; k < kept; ++k) {
830 f32 r[12];
831 std::memcpy(r, bytes.data() + kEventHeaderBytes + k * kEventBytes, sizeof(r));
832 if (r[3] < 1.5f) continue;
833 ++hits;
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});
836 }
837 // Past what was kept, the kinds are not known; every event of an emitter that only reports hits is one.
838 slot.system->addGpuCollisions(Entity::fromRaw(id), total > kept ? hits + (total - kept) : hits, out.data(), static_cast<u32>(out.size()));
839 }
840}
841
842GpuParticles::Slot* GpuParticles::ensureSlot(Entity entity, u32 capacity) {
843 Slot& slot = slots_[entity.raw];
844 slot.lastUsed = frame_;
845 if (slot.state != BufferHandle::Invalid && slot.capacity == capacity) return &slot;
846 freeSlot(slot);
847 // Zeroed by the device: age 0 of lifetime 0 is a dead particle, and a zero instance has no size to draw.
848 slot.state = device_.createBuffer({GfxBufferUsage::Storage, capacity * kStateBytes, false}, GfxContent::transient(), nullptr);
849 slot.instances = device_.createBuffer({GfxBufferUsage::Storage, capacity * kInstanceBytes, false}, GfxContent::transient(), nullptr);
850 if (slot.state == BufferHandle::Invalid || slot.instances == BufferHandle::Invalid) {
851 ES_LOG_ERROR("GpuParticles: could not allocate {} particles", capacity);
852 freeSlot(slot);
853 slots_.erase(entity.raw);
854 return nullptr;
855 }
856 slot.capacity = capacity;
857 slot.lastUsed = frame_;
858 return &slot;
859}
860
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,
863 BufferHandle& instances, BufferHandle& segments, u32& segmentCount) {
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);
871
872 const bool collides = emitter.collisionEnabled;
873 const i32 mode = emitter.collisionMode;
874 const bool depthMode = collides && mode == static_cast<i32>(ecs::ParticleCollisionMode::Depth);
875 const bool sdfMode = collides && mode == static_cast<i32>(ecs::ParticleCollisionMode::Sdf);
876 if (depthMode) wantsDepthNext_ = true;
877
878 // What an emitter fires: its child's trigger, and what the game asks to hear.
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;
882 const bool emitsBirth = hasChild && trigger == static_cast<i32>(ecs::SubEmitterTrigger::Birth);
883 const bool emitsDeath = hasChild && trigger == static_cast<i32>(ecs::SubEmitterTrigger::Death);
884 const bool emitsHit = (hasChild && trigger == static_cast<i32>(ecs::SubEmitterTrigger::Collision)) || report > 0;
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;
889 if (slot->events == BufferHandle::Invalid || slot->eventBytes != bytes) {
890 if (slot->events != BufferHandle::Invalid) device_.deleteBuffer(slot->events);
891 slot->events = device_.createBuffer({GfxBufferUsage::Storage, bytes, false}, GfxContent::transient(), nullptr);
892 slot->eventBytes = bytes;
893 if (slot->events == BufferHandle::Invalid) return false;
894 }
895 }
896
897 const bool trailOn = emitter.trailEnabled && emitter.trailWidth > 0.0f;
898 const u32 points = static_cast<u32>(std::clamp(emitter.trailPoints, 2, particle::kMaxTrailPoints));
899 if (trailOn) {
900 if (slot->trail == BufferHandle::Invalid || slot->trailPoints != points) {
901 if (slot->trail != BufferHandle::Invalid) device_.deleteBuffer(slot->trail);
902 if (slot->segments != BufferHandle::Invalid) device_.deleteBuffer(slot->segments);
903 slot->trail = device_.createBuffer({GfxBufferUsage::Storage, step.capacity * points * 16u, false}, GfxContent::transient(), nullptr);
904 slot->segments = device_.createBuffer({GfxBufferUsage::Storage, step.capacity * (points - 1u) * kInstanceBytes, false}, GfxContent::transient(), nullptr);
905 slot->trailPoints = points;
906 if (slot->trail == BufferHandle::Invalid || slot->segments == BufferHandle::Invalid) {
907 ES_LOG_ERROR("GpuParticles: could not allocate trails for {} particles", step.capacity);
908 return false;
909 }
910 }
911 segments = slot->segments;
912 segmentCount = step.drawCount * (points - 1u);
913 }
914
915 // A second camera's collect asks for the same step until the first has run it.
916 for (const Job& queued : jobs_) {
917 if (queued.entity == entity) return true;
918 }
919 const bool local = emitter.simulationSpace == static_cast<i32>(ecs::SimulationSpace::Local);
920 // Nothing to advance and nowhere it could have moved to: the buffer already says what is true.
921 if (step.dt <= 0.0f && step.spawnCount == 0 && !step.reset && !local) return true;
922 if (jobs_.size() >= kMaxJobs) return true;
923
924 Job job{entity, {}, slot, &system, step};
925 ParamsBlock& b = job.block;
926 std::memset(&b, 0, sizeof(b));
927
928 u32 flags = 0;
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;
933 if (collides && mode == static_cast<i32>(ecs::ParticleCollisionMode::Floor)) flags |= kFloor;
934 // A scene query is the CPU's to ask; here, what the emitter says to do when one is not to be had.
935 if (collides && (mode == static_cast<i32>(ecs::ParticleCollisionMode::Physics2D) || mode == static_cast<i32>(ecs::ParticleCollisionMode::Physics3D))
936 && emitter.collisionFallback == static_cast<i32>(ecs::ParticleCollisionFallback::Floor)) flags |= kFloor;
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;
944
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;
951
952 // A scene's own draw of randomness, fixed per emitter: the same emitter replays the same particles.
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));
964 set4(b.p9, finite(emitter.angleSpreadMin * math::DEG_TO_RAD), finite(emitter.angleSpreadMax * math::DEG_TO_RAD),
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);
973
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);
985 const glm::dvec3 origin = renderOrigin();
986 set4(b.shift, static_cast<f32>(origin.x), static_cast<f32>(origin.y), static_cast<f32>(origin.z), 0.0f);
987
988 for (u32 k = 0; k < fieldCount; ++k) {
989 const particle::ForceFieldInstance& f = fields[k];
990 set4(b.fields[k * 3], f.position.x, f.position.y, f.position.z, static_cast<f32>(f.type));
991 set4(b.fields[k * 3 + 1], f.direction.x, f.direction.y, f.direction.z, f.strength);
992 set4(b.fields[k * 3 + 2], f.radius, f.falloff ? 1.0f : 0.0f, 0.0f, 0.0f);
993 }
994 if (colorLut) {
995 for (u32 k = 0; k < kLutSize; ++k) set4(b.colorLut[k], (*colorLut)[k].r, (*colorLut)[k].g, (*colorLut)[k].b, (*colorLut)[k].a);
996 }
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];
1000 }
1001
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);
1004 // A report must hear every hit; a chance belongs to a child.
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);
1010 job.subEmitter = emitter.subEmitter;
1011 job.inheritVelocity = std::clamp(finite(emitter.subEmitterInheritVelocity), 0.0f, 1.0f);
1012 job.eventCapacity = eventCapacity;
1013 job.reportEvents = report;
1014
1015 jobs_.push_back(job);
1016 return true;
1017}
1018
1019void GpuParticles::declareDepthCopy(rg::RenderGraph& graph, rg::ResourceId scene, u32 sceneW, u32 sceneH, const glm::mat4& clip) {
1020 if (!wantsDepth_ || depthCopied_ || scene == rg::kNoResource || !device_.supportsCompute()) return;
1021 depthCopied_ = true;
1022 rg::TargetDesc token;
1023 token.width = 1;
1024 token.height = 1;
1026 token.storage = true;
1027 token.linearFilter = false;
1028 rg::PassDesc pass;
1029 pass.name = "gpu_particle_depth";
1030 pass.compute = true;
1031 pass.keep = true;
1032 pass.dependencies = {scene};
1033 pass.write = graph.createTarget(token);
1034 const glm::dvec3 origin = renderOrigin();
1035 pass.execute = [this, &graph, scene, sceneW, sceneH, clip, origin](const rg::PassContext&) {
1036 const TextureHandle depth = graph.depthTextureOf(scene);
1037 if (depth == TextureHandle::Invalid) { depthValid_ = false; return; }
1038 if (depthCopy_ == ComputeHandle::Invalid) {
1039 std::string log;
1040 depthCopy_ = device_.createCompute(GfxComputeSource{GfxShaderLanguage::WGSL, kDepthCopy, "main"}, &log);
1041 if (depthCopy_ == ComputeHandle::Invalid) {
1042 ES_LOG_ERROR("GpuParticles: the depth copy did not compile: {}", log);
1043 return;
1044 }
1045 }
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)));
1048 if (w != depthW_ || h != depthH_ || depthGrid_ == BufferHandle::Invalid) {
1049 if (depthGrid_ != BufferHandle::Invalid) device_.deleteBuffer(depthGrid_);
1050 depthGrid_ = device_.createBuffer({GfxBufferUsage::Storage, w * h * 4u, false}, GfxContent::transient(), nullptr);
1051 if (depthGrid_ == BufferHandle::Invalid) { depthW_ = depthH_ = 0; depthValid_ = false; return; }
1052 depthW_ = w;
1053 depthH_ = h;
1054 }
1055 if (depthParams_ == BufferHandle::Invalid) {
1056 depthParams_ = device_.createBuffer({GfxBufferUsage::Uniform, 16, true}, GfxContent::transient(), nullptr);
1057 if (depthParams_ == BufferHandle::Invalid) return;
1058 }
1059 const u32 size[4] = {w, h, 0, 0};
1060 device_.updateBuffer(depthParams_, 0, size, sizeof(size));
1061 const GfxComputeBinding bindings[3] = {
1062 GfxComputeBinding::uniform(0, depthParams_),
1063 GfxComputeBinding::depth(1, depth),
1064 GfxComputeBinding::storage(2, depthGrid_),
1065 };
1066 if (device_.dispatchCompute(depthCopy_, bindings, 3, (w + 7) / 8, (h + 7) / 8)) {
1067 depthValid_ = true;
1068 depthClip_ = clip;
1069 depthWorld_ = glm::inverse(clip);
1070 depthOrigin_ = glm::vec3(origin);
1071 }
1072 };
1073 graph.addPass(std::move(pass));
1074}
1075
1077 depthGridMax_ = std::clamp(texels, kDepthGridMin, kDepthGridMax);
1081 if (jobs_.empty()) return rg::kNoResource;
1082 // The pass is tied to the scene by what it writes, the way the other compute passes are: a single texel nobody samples.
1083 rg::TargetDesc token;
1084 token.width = 1;
1085 token.height = 1;
1087 token.storage = true;
1088 token.linearFilter = false;
1089 const rg::ResourceId done = graph.createTarget(token);
1090 rg::PassDesc pass;
1091 pass.name = "gpu_particles";
1092 pass.compute = true;
1093 pass.write = done;
1094 pass.execute = [this](const rg::PassContext&) { run(); };
1095 graph.addPass(std::move(pass));
1096 return done;
1097}
1098
1099void GpuParticles::run() {
1100 if (jobs_.empty() || kernel_ == ComputeHandle::Invalid) return;
1101 const u32 needed = static_cast<u32>(jobs_.size()) * kJobStride;
1102 if (params_ == BufferHandle::Invalid || paramsCapacity_ < needed) {
1103 if (params_ != BufferHandle::Invalid) device_.deleteBuffer(params_);
1104 paramsCapacity_ = std::max(needed, kJobStride * 8u);
1105 params_ = device_.createBuffer({GfxBufferUsage::Uniform, paramsCapacity_, true}, GfxContent::transient(), nullptr);
1106 if (params_ == BufferHandle::Invalid) {
1107 paramsCapacity_ = 0;
1108 return;
1109 }
1110 }
1111 ensureEmpties();
1112
1113 // A parent runs before what its events feed, however the scene happens to list them.
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);
1120 break;
1121 }
1122 }
1123 }
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;
1127 };
1128 order_.clear();
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;
1133 placed_[index] = 1;
1134 if (depth < kMaxJobs) {
1135 if (Job* parent = parentOf(job)) self(self, *parent, depth + 1);
1136 }
1137 order_.push_back(&job);
1138 };
1139 for (Job& job : jobs_) place(place, job, 0);
1140
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)) {
1144 if (colliders_ != BufferHandle::Invalid) device_.deleteBuffer(colliders_);
1145 collidersCapacity_ = kMaxColliders * sizeof(particle::SdfColliderInstance);
1146 colliders_ = device_.createBuffer({GfxBufferUsage::Storage, collidersCapacity_, true}, GfxContent::transient(), nullptr);
1147 }
1148 if (colliderBytes > 0 && colliders_ != BufferHandle::Invalid) device_.updateBuffer(colliders_, 0, colliders.data(), colliderBytes);
1149
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;
1154 if (depthValid_) {
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);
1160 }
1161 std::memcpy(staging_.data() + i * kJobStride, &job.block, sizeof(ParamsBlock));
1162 }
1163 device_.updateBuffer(params_, 0, staging_.data(), needed);
1164
1165 bool anyEvents = false;
1166 for (const Job& job : jobs_) anyEvents = anyEvents || job.slot->events != BufferHandle::Invalid;
1167 if (anyEvents) {
1168 if (!ensureEventKernels()) anyEvents = false;
1169 const u32 controlBytes = static_cast<u32>(jobs_.size()) * 256u;
1170 if (anyEvents && (control_ == BufferHandle::Invalid || controlCapacity_ < controlBytes)) {
1171 if (control_ != BufferHandle::Invalid) device_.deleteBuffer(control_);
1172 controlCapacity_ = std::max(controlBytes, 256u * 8u);
1173 control_ = device_.createBuffer({GfxBufferUsage::Uniform, controlCapacity_, true}, GfxContent::transient(), nullptr);
1174 if (control_ == BufferHandle::Invalid) { controlCapacity_ = 0; anyEvents = false; }
1175 }
1176 if (anyEvents) {
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));
1181 }
1182 device_.updateBuffer(control_, 0, control_staging_.data(), controlBytes);
1183 }
1184 }
1185
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);
1190 const BufferHandle ownEvents = job.slot->events != BufferHandle::Invalid ? job.slot->events : emptyEvents_;
1191 const bool fed = (job.block.p1[1] & kFed) != 0u;
1192 const BufferHandle inEvents = fed && parent && parent->slot->events != BufferHandle::Invalid ? parent->slot->events : emptyRead_;
1193 const bool controlled = anyEvents && job.slot->events != BufferHandle::Invalid;
1194 if (controlled) {
1195 const GfxComputeBinding control[2] = {
1196 GfxComputeBinding::uniform(0, control_, i * 256u, 16u),
1197 GfxComputeBinding::storage(1, ownEvents),
1198 };
1199 device_.dispatchCompute(beginEvents_, control, 2, 1);
1200 }
1201 const GfxComputeBinding bindings[9] = {
1202 GfxComputeBinding::uniform(0, params_, i * kJobStride, sizeof(ParamsBlock)),
1203 GfxComputeBinding::storage(1, job.slot->state),
1204 GfxComputeBinding::storage(2, job.slot->instances),
1205 GfxComputeBinding::storage(3, ownEvents),
1206 GfxComputeBinding::storageRead(4, inEvents),
1207 GfxComputeBinding::storageRead(5, depthValid_ && depthGrid_ != BufferHandle::Invalid ? depthGrid_ : emptyRead_),
1208 GfxComputeBinding::storageRead(6, colliders_ != BufferHandle::Invalid ? colliders_ : emptyRead_),
1209 GfxComputeBinding::storage(7, job.slot->trail != BufferHandle::Invalid ? job.slot->trail : emptyTrail_),
1210 GfxComputeBinding::storage(8, job.slot->segments != BufferHandle::Invalid ? job.slot->segments : emptySegments_),
1211 };
1212 if (device_.dispatchCompute(kernel_, bindings, 9, (job.slot->capacity + 63) / 64)) {
1213 ++lastDispatches_;
1214 job.system->commitGpuStep(job.entity, job.step);
1215 }
1216 if (controlled && fed) {
1217 const GfxComputeBinding control[3] = {
1218 GfxComputeBinding::uniform(0, control_, i * 256u, 16u),
1219 GfxComputeBinding::storage(1, ownEvents),
1220 GfxComputeBinding::storageRead(2, inEvents),
1221 };
1222 device_.dispatchCompute(finishEvents_, control, 3, 1);
1223 }
1224 if (job.reportEvents > 0 && controlled && job.slot->readback == ReadbackHandle::Invalid) {
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);
1227 }
1228 }
1229 jobs_.clear();
1230}
1231
1232} // namespace esengine
1233
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.
Definition Log.hpp:296
The point the frame is drawn relative to: a world far from zero loses precision in single floats,...
Unified Transform component with local and world-space data.
static constexpr GfxContent transient()
Abstract graphics device interface.
Definition GfxDevice.hpp:75
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.
Definition Math.hpp:76
constexpr int kColorLutSize
constexpr int kMaxTrailPoints
constexpr ResourceId kNoResource
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
@ Storage
Read and written by compute shaders (var<storage, read_write>), and readable back....
Definition GfxEnums.hpp:77
ComputeHandle
A compute program (GfxDevice::createCompute); only a device that supportsCompute() issues one.
Definition GfxEnums.hpp:39
GfxReadbackStatus
State of an in-flight readback. GL completes at request time (first poll reports Ready); WebGPU resol...
Definition GfxEnums.hpp:47
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
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
Definition GfxEnums.hpp:122
ReadbackHandle
An in-flight framebuffer readback (GfxDevice::requestReadback).
Definition GfxEnums.hpp:43
float f32
32-bit floating point
Definition Types.hpp:59
static constexpr Entity fromRaw(u32 v)
Reconstructs an Entity from a raw packed value.
Definition Types.hpp:162
static GfxComputeBinding depth(u32 binding, TextureHandle texture)
Definition GfxEnums.hpp:718
static GfxComputeBinding uniform(u32 binding, BufferHandle buffer, u32 offset=0, u32 size=0)
Definition GfxEnums.hpp:701
static GfxComputeBinding storageRead(u32 binding, BufferHandle buffer, u32 offset=0, u32 size=0)
Definition GfxEnums.hpp:704
static GfxComputeBinding storage(u32 binding, BufferHandle buffer, u32 offset=0, u32 size=0)
Definition GfxEnums.hpp:707
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...
One full-screen pass.
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.