Skip to content

packages/core/src/lib/transitions/embers-physics.ts

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import type { PibblEmbersOptions } from './embers.js';
2 import { finite } from "./capture.js";
3 import type { lazyTransitionKernel } from "./wasm/kernel.js";
4 /**
5  * Collision information produced by an ember's physical interaction.
6  *
7  * @see {@link PibblEmbersPhysicsOptions}
8  */
9 export interface PibblEmberCollision {
10   /** Fraction of the swept segment at impact, from zero to one. */
11   readonly fraction: number;
12   /** Outward surface normal in the receiving primitive's local coordinates. */
13   readonly normal: readonly [number, number];
14 }
15 /**
16  * Collision and physical motion options for transition embers.
17  *
18  * @see {@link PibblEmberCollision}
19  * @see {@link PibblEmbersOptions}
20  */
21 export interface PibblEmbersPhysicsOptions {
22   /** Local units/second². Default [0, -60]. */
23   readonly gravity?: readonly [number, number];
24   /** Target air velocity in local units/second. Default [0, -45]. */
25   readonly wind?: readonly [number, number];
26   /** Velocity damping per second. Default 4. */
27   readonly drag?: number;
28   /** Bounce coefficient, zero to one. Default 0.5. */
29   readonly restitution?: number;
30   /** Packed committed solids in receiver-local coordinates (e.g. physicsObstacles2D).
31    * Revision must change whenever data changes. Up to 8192 packed numbers.
32    * Sweeps run as one WASM batch; mutually exclusive with collide.
33    */
34   readonly obstacles?: Readonly<{
35     /**
36      * Reads the current committed values required by this integration. See
37      * {@link PibblEmbersPhysicsOptions}.
38      * @returns The current obstacle revision and packed geometry arrays.
39      */
40     read(): Readonly<{
41       /**
42        * Revision used to detect changes to the underlying state or geometry. See
43        * {@link PibblEmbersPhysicsOptions}.
44        */
45       revision: number;
46       /** Packed box obstacle data consumed by the simulation. See {@link PibblEmbersPhysicsOptions}. */
47       boxes: Float64Array;
48       /**
49        * Packed ellipse obstacle data consumed by the simulation. See
50        * {@link PibblEmbersPhysicsOptions}.
51        */
52       ellipses: Float64Array;
53       /**
54        * Packed polygon obstacle data consumed by the simulation. See
55        * {@link PibblEmbersPhysicsOptions}.
56        */
57       polygons: Float64Array;
58     }>;
59   }>;
60   /**
61    * Synchronous point sweep, called in Advance. Return the closest hit, if any.
62    * @param from - Previous particle position.
63    * @param to - Proposed particle position.
64    * @returns Collision information, or undefined when motion is unobstructed. See
65    * {@link PibblEmberCollision} .
66    */
67   readonly collide?: (
68     from: readonly [number, number],
69     to: readonly [number, number],
70   ) => PibblEmberCollision | undefined;
71 }
72 export function resolveEmbersPhysics(options: PibblEmbersPhysicsOptions) {
73   const vector = (value: readonly [number, number], name: string) =>
74     Object.freeze([
75       finite(value[0], `${name}.x`),
76       finite(value[1], `${name}.y`),
77     ] as const);
78   const restitution = finite(
79     options.restitution ?? 0.5,
80     "physics.restitution",
81     0,
82   );
83   if (restitution > 1)
84     throw new RangeError("physics.restitution must be between zero and one.");
85   if (options.collide !== undefined && typeof options.collide !== "function")
86     throw new TypeError("physics.collide must be a synchronous function.");
87   if (
88     options.obstacles &&
89     (typeof options.obstacles.read !== "function" || options.collide)
90   )
91     throw new TypeError(
92       "physics.obstacles requires read() and cannot be combined with collide.",
93     );
94   return Object.freeze({
95     obstacles: options.obstacles,
96     gravity: vector(options.gravity ?? [0, -60], "physics.gravity"),
97     wind: vector(options.wind ?? [0, -45], "physics.wind"),
98     drag: finite(options.drag ?? 4, "physics.drag", 0),
99     restitution,
100     collide: options.collide,
101   });
102 }
103 type Kernel = ReturnType<ReturnType<typeof lazyTransitionKernel>>;
104 export function emberSimulation(
105   kernel: Kernel,
106   options: ReturnType<typeof resolveEmbersPhysics>,
107   region: Readonly<{ x: number; y: number; width: number; height: number }>,
108   linger: number,
109   burnWidth: number,
110 ) {
111   let previous = 0,
112     remainder = 0,
113     needsReset = true,
114     disposed = false;
115   const step = 1000 / 60;
116   let obstacleRevision: number | undefined;
117   let boxLength = 0,
118     ellipseLength = 0,
119     polygonLength = 0;
120   return {
121     reset() {
122       previous = 0;
123       remainder = 0;
124       needsReset = true;
125     },
126     get disposed() {
127       return disposed;
128     },
129     dispose() {
130       disposed = true;
131       kernel.dispose();
132     },
133     advance(elapsed: number, progressAt: (time: number) => number) {
134       if (disposed || elapsed <= previous) return;
135       const { exports, values } = kernel();
136       if (needsReset) {
137         exports.resetPhysics!();
138         needsReset = false;
139       }
140       remainder += Math.min(elapsed - previous, step * 4);
141       previous = elapsed;
142       if (remainder + 1e-8 >= step && options.obstacles) {
143         const batch = options.obstacles.read();
144         if (batch.revision !== obstacleRevision) {
145           const { boxes, ellipses, polygons } = batch;
146           if (
147             !Number.isFinite(batch.revision) ||
148             boxes.length % 10 ||
149             ellipses.length % 10 ||
150             boxes.length + ellipses.length + polygons.length > 8192
151           )
152             throw new RangeError(
153               "Invalid ember obstacle batch or capacity exceeded (8192 numbers).",
154             );
155           validateFiniteObstacles(boxes);
156           validateFiniteObstacles(ellipses);
157           validateFiniteObstacles(polygons);
158           validateObstacleExtents(boxes);
159           validateObstacleExtents(ellipses);
160           for (let at = 0; at < polygons.length;) {
161             const count = polygons[at]!;
162             if (
163               !Number.isInteger(count) ||
164               count < 3 ||
165               at + 6 + count * 2 > polygons.length
166             )
167               throw new RangeError("Invalid ember obstacle polygon.");
168             at += 6 + count * 2;
169           }
170           values.set(boxes, 22400);
171           values.set(ellipses, 22400 + boxes.length);
172           values.set(polygons, 22400 + boxes.length + ellipses.length);
173           boxLength = boxes.length;
174           ellipseLength = ellipses.length;
175           polygonLength = polygons.length;
176           obstacleRevision = batch.revision;
177         }
178       }
179       while (remainder + 1e-8 >= step) {
180         const time = elapsed - remainder + step;
181         remainder = Math.max(0, remainder - step);
182         const q = progressAt(time);
183         exports.births!(time, linger);
184         for (let i = 0; i < 1200; i++)
185           values[11166 + i] = progressAt(values[12366 + i]!);
186         exports.sample!(
187           q,
188           1,
189           time,
190           linger,
191           0,
192           burnWidth,
193           region.x,
194           region.y,
195           region.width,
196           region.height,
197           Math.min(512, Math.max(1, Math.ceil(region.width / 2))),
198         );
199         exports.stepPhysics!(
200           time,
201           step / 1000,
202           ...options.gravity,
203           ...options.wind,
204           options.drag,
205           linger,
206         );
207         if (options.obstacles)
208           exports.collideObstacles!(
209             boxLength,
210             ellipseLength,
211             polygonLength,
212             options.restitution,
213           );
214         if (options.collide)
215           for (let i = 0; i < 1200; i++) {
216             const s = 14000 + i * 7;
217             if (values[s + 4]! < 0) continue;
218             const from = [values[s + 5]!, values[s + 6]!] as const,
219               to = [values[s]!, values[s + 1]!] as const;
220             if (from[0] === to[0] && from[1] === to[1]) continue;
221             const hit = options.collide(from, to);
222             if (!hit) continue;
223             const fraction = finite(hit.fraction, "collision.fraction", 0);
224             const nx = finite(hit.normal?.[0], "collision.normal.x"),
225               ny = finite(hit.normal?.[1], "collision.normal.y"),
226               length = Math.hypot(nx, ny);
227             if (fraction > 1 || length < 1e-8)
228               throw new RangeError(
229                 "Ember collision requires a fraction in [0, 1] and a nonzero normal.",
230               );
231             exports.collidePhysics!(
232               i,
233               fraction,
234               nx / length,
235               ny / length,
236               options.restitution,
237             );
238           }
239       }
240     },
241     present() {
242       if (!needsReset && !disposed) kernel().exports.presentPhysics!();
243       else {
244         const { values } = kernel();
245         for (let i = 0; i < 1200; i++) values[1566 + i * 8 + 5] = -1;
246       }
247     },
248   };
249 }
250 
251 function validateFiniteObstacles(packed: ArrayLike<number>): void {
252   for (let i = 0; i < packed.length; i++)
253     if (!Number.isFinite(packed[i]))
254       throw new RangeError("Ember obstacles must be finite.");
255 }
256 
257 function validateObstacleExtents(packed: ArrayLike<number>): void {
258   for (let i = 0; i < packed.length; i += 10)
259               if (packed[i + 2]! <= 0 || packed[i + 3]! <= 0)
260                 throw new RangeError(
261                   "Ember obstacle extents must be positive.",
262                 );
263 }
264 

Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.