Skip to content

packages/core/src/features/textures/lib/reaction-diffusion.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 {
2   grayScottConfig,
3   type ReactionDiffusionOptions,
4   type ReactionDiffusionPreset,
5 } from "./gray-scott.js";
6 import { defineRenderLayer, type PibblRenderLayerInput } from "@pibbl/core";
7 import { TextureRaster, type TextureRenderer } from "./presentation.js";
8 import { InkSimulation } from "./simulation.js";
9 import {
10   paletteLut,
11   texturePalettes,
12   validateResolution,
13   type TexturePalette,
14   type TextureResolution,
15 } from "./palette.js";
16 
17 /**
18  * Radius and strength of a reaction-diffusion brush stroke.
19  *
20  * @see {@link ReactionDiffusionProps}
21  */
22 export interface TextureBrush {
23   /** Radius in the coordinate system of this geometry or effect. See {@link TextureBrush}. */
24   readonly radius: number;
25   /** Magnitude of the displacement or brush effect. See {@link TextureBrush}. */
26   readonly strength: number;
27 }
28 /**
29  * Authored inputs for ReactionDiffusion, including the declared data and presentation options.
30  *
31  * @see {@link TextureRenderer}
32  * @see {@link TextureResolution}
33  * @see {@link TexturePalette}
34  * @see {@link TextureBrush}
35  * @see {@link ReactionDiffusion}
36  */
37 export interface ReactionDiffusionProps extends ReactionDiffusionOptions {
38   /**
39    * Renders the current data or resources using the supplied context. See {@link TextureRenderer}
40    * .
41    */
42   readonly render?: TextureRenderer;
43   /** Dimensions of the simulation or raster grid. See {@link TextureResolution}. */
44   readonly resolution?: TextureResolution;
45   /**
46    * Seed used for deterministic sampling or simulation initialization. See
47    * {@link ReactionDiffusionProps}.
48    */
49   readonly seed?: number;
50   /**
51    * Named pattern configuration used to initialize the simulation. See
52    * {@link ReactionDiffusionProps}.
53    */
54   readonly preset?: ReactionDiffusionPreset;
55   /** Ordered colors used to present texture intensity. See {@link TexturePalette}. */
56   readonly palette?: TexturePalette;
57   /**
58    * Whether simulation or playback advancement is suspended. See {@link ReactionDiffusionProps}.
59    */
60   readonly paused?: boolean;
61   /**
62    * Changing this revision requests a fresh simulation initialization. See
63    * {@link ReactionDiffusionProps}.
64    */
65   readonly resetRevision?: number;
66   /**
67    * Brush configuration for interactive reaction-diffusion input, or false to disable it. See
68    * {@link TextureBrush}.
69    */
70   readonly brush?: TextureBrush | false;
71 }
72 interface Options {
73   resolution: TextureResolution;
74   seed: number;
75   preset: ReactionDiffusionPreset;
76   feed: number;
77   kill: number;
78   warmupSteps: number;
79   palette: TexturePalette;
80   paused: boolean;
81   resetRevision: number;
82   brush: TextureBrush | false;
83 }
84 function options(props: ReactionDiffusionProps): Options {
85   const chemistry = grayScottConfig(props);
86   const brush = props.brush ?? { radius: 6, strength: 0.8 };
87   if (
88     brush &&
89     (!Number.isFinite(brush.radius) ||
90       brush.radius <= 0 ||
91       brush.radius > 128 ||
92       !Number.isFinite(brush.strength) ||
93       brush.strength < 0 ||
94       brush.strength > 1)
95   )
96     throw new RangeError(
97       "Brush radius must be in (0,128] and strength in [0,1].",
98     );
99   if (!Number.isSafeInteger(props.resetRevision ?? 0))
100     throw new RangeError("resetRevision must be a safe integer.");
101   return {
102     resolution: validateResolution(props.resolution),
103     ...chemistry,
104     palette: [...(props.palette ?? texturePalettes.lagoon)],
105     paused: props.paused ?? false,
106     resetRevision: props.resetRevision ?? 0,
107     brush: brush && { ...brush },
108   };
109 }
110 interface Stroke {
111   x: number;
112   y: number;
113   radius: number;
114   strength: number;
115 }
116 interface Resources {
117   render?: TextureRenderer;
118   config: Options;
119   simulation: InkSimulation;
120   raster: TextureRaster;
121   output: OffscreenCanvasRenderingContext2D;
122   lut: Uint8ClampedArray;
123   elapsed: number;
124   fresh: boolean;
125   dirty: boolean;
126   disposed: boolean;
127   target: object;
128   strokes: Stroke[];
129   pointer?: { id: number; x: number; y: number; release: () => void };
130   invalidate: () => void;
131 }
132 function reset(r: Resources, config: Options) {
133   const { width, height } = config.resolution;
134   const simulation = new InkSimulation({ width, height, ...config });
135   let raster: TextureRaster;
136   try {
137     raster = new TextureRaster(width, height);
138   } catch (error) {
139     simulation.dispose();
140     throw error;
141   }
142   r.simulation.dispose();
143   r.simulation = simulation;
144   r.raster.dispose();
145   r.raster = raster;
146   r.strokes.length = 0;
147   r.pointer?.release();
148   r.pointer = undefined;
149   r.elapsed = 0;
150   r.fresh = true;
151   r.dirty = true;
152 }
153 function input(
154   r: Resources,
155   event: Readonly<PibblRenderLayerInput<object>>,
156   width: number,
157   height: number,
158 ) {
159   if (r.disposed) return;
160   const original = event.originalEvent as PointerEvent;
161   if (event.type === "pointerup" || event.type === "pointercancel") {
162     if (r.pointer?.id === original.pointerId) {
163       r.pointer.release();
164       r.pointer = undefined;
165     }
166     return;
167   }
168   const brush = r.config.brush;
169   if (!brush || width <= 0 || height <= 0) return;
170   const x = (event.point.x / width) * r.simulation.width;
171   const y = (event.point.y / height) * r.simulation.height;
172   if (event.type === "pointerdown") {
173     if (r.pointer || original.button !== 0 || original.isPrimary === false)
174       return;
175     event.setPointerCapture(original.pointerId);
176     r.pointer = {
177       id: original.pointerId,
178       x,
179       y,
180       release: () => event.releasePointerCapture(original.pointerId),
181     };
182   } else if (
183     event.type !== "pointermove" ||
184     r.pointer?.id !== original.pointerId
185   )
186     return;
187   const previous = r.pointer!;
188   const distance = Math.hypot(x - previous.x, y - previous.y);
189   // Bound work for off-surface capture. Stamps outside the field are ignored, never clamped to its edge.
190   const count = Math.min(
191     4096,
192     Math.max(1, Math.ceil(distance / Math.max(0.5, brush.radius * 0.3))),
193   );
194   for (let i = 1; i <= count; i++) {
195     const px = previous.x + ((x - previous.x) * i) / count,
196       py = previous.y + ((y - previous.y) * i) / count;
197     if (
198       px >= 0 &&
199       py >= 0 &&
200       px < r.simulation.width &&
201       py < r.simulation.height &&
202       r.strokes.length < 8192
203     )
204       r.strokes.push({ x: px, y: py, ...brush });
205   }
206   previous.x = x;
207   previous.y = y;
208   r.invalidate();
209 }
210 
211 /**
212  * An independently sized, persistent Gray–Scott surface, advanced by Pibbl's scheduler.
213  *
214  * @param props - Authored component inputs, supplied through JSX or createElement. See the linked
215  * props and style types.
216  * @throws When called directly; Pibbl mounts this component through JSX or createElement.
217  *
218  * @see {@link ReactionDiffusionProps}
219  */
220 export const ReactionDiffusion = /* @__PURE__ */ defineRenderLayer<
221   ReactionDiffusionProps,
222   Resources
223 >({
224   create(context, props) {
225     const config = options(props),
226       lut = paletteLut(config.palette);
227     const output = context.canvas.getContext("2d");
228     if (!output) throw new Error("ReactionDiffusion requires Canvas 2D.");
229     const { width, height } = config.resolution;
230     const raster = new TextureRaster(width, height);
231     try {
232       return {
233         config,
234         lut,
235         raster,
236         output,
237         render: props.render,
238         simulation: new InkSimulation({ width, height, ...config }),
239         elapsed: 0,
240         fresh: true,
241         dirty: true,
242         disposed: false,
243         target: {},
244         strokes: [],
245         invalidate: context.invalidate,
246       };
247     } catch (error) {
248       raster.dispose();
249       throw error;
250     }
251   },
252   update(r, props) {
253     const next = options(props),
254       old = r.config;
255     if (next.palette.join() !== old.palette.join()) {
256       r.lut = paletteLut(next.palette);
257       r.dirty = true;
258     }
259     if (
260       next.seed !== old.seed ||
261       next.preset !== old.preset ||
262       next.feed !== old.feed ||
263       next.kill !== old.kill ||
264       next.warmupSteps !== old.warmupSteps ||
265       next.resetRevision !== old.resetRevision ||
266       next.resolution.width !== old.resolution.width ||
267       next.resolution.height !== old.resolution.height
268     )
269       reset(r, next);
270     if (next.paused !== old.paused) {
271       r.elapsed = 0;
272       r.fresh = true;
273     }
274     if (!next.brush) {
275       r.pointer?.release();
276       r.pointer = undefined;
277     }
278     r.config = next;
279     r.render = props.render;
280   },
281   render(r, frame, context) {
282     // The frame invalidator does not gate the committed input snapshot between brush samples.
283     r.invalidate = frame.invalidate;
284     for (const stroke of r.strokes)
285       r.simulation.paint(stroke.x, stroke.y, stroke.radius, stroke.strength);
286     if (r.strokes.length) r.dirty = true;
287     r.strokes.length = 0;
288     if (!r.config.paused && !r.fresh) {
289       r.elapsed += Math.max(0, Math.min(50, frame.delta));
290       const steps = Math.min(24, Math.floor(r.elapsed * 0.48 + 1e-9));
291       r.elapsed -= steps / 0.48;
292       if (steps) {
293         r.simulation.advance(steps);
294         r.dirty = true;
295       }
296     }
297     r.fresh = false;
298     if (r.dirty) {
299       r.raster.update(r.simulation.b, r.lut, 650 / 255);
300       r.dirty = false;
301     }
302     r.raster.draw(
303       r.output,
304       context.size.width,
305       context.size.height,
306       context.size.backingWidth,
307       context.size.backingHeight,
308       r.render,
309     );
310     if (!r.config.paused) frame.invalidate();
311   },
312   interaction: {
313     settle(r, _props, size) {
314       return {
315         targets: [
316           {
317             target: r.target,
318             cursor: r.config.brush ? "crosshair" : "default",
319           },
320         ],
321         hitTest: () => ({ kind: "target", target: r.target }),
322         onInput: (event) => input(r, event, size.width, size.height),
323       };
324     },
325   },
326   dispose(r) {
327     if (r.disposed) return;
328     r.disposed = true;
329     r.pointer?.release();
330     r.pointer = undefined;
331     r.strokes.length = 0;
332     r.invalidate = () => {};
333     r.simulation.dispose();
334     r.raster.dispose();
335     r.render = undefined;
336   },
337 });
338 

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