Skip to content

packages/core/src/features/textures/lib/chemical-recipes.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   defineTexture,
3   type TextureContext,
4   type TextureRecipe,
5 } from "@pibbl/core";
6 import type { InkMessage } from "./definitions.js";
7 import { paletteLut, texturePalettes, validateSeed } from "./palette.js";
8 import {
9   ChemicalField,
10   schnakenbergModel,
11   barkleyModel,
12   brusselatorModel,
13   type ChemicalConfig,
14 } from "./chemical-field.js";
15 
16 /** Shared simulation timing, diffusion and initialization controls. See {@link SchnakenbergOptions}. */
17 interface ChemicalOptions {
18   /** Unsigned 32-bit initialization seed; default 42. See {@link schnakenberg}. */
19   readonly seed?: number;
20   /** Activator diffusion per grid cell, finite 0–32. See {@link schnakenberg}. */
21   readonly diffusionU?: number;
22   /** Inhibitor diffusion per grid cell, finite 0–32. See {@link schnakenberg}. */
23   readonly diffusionV?: number;
24   /** Initial seeded disturbance amplitude, finite 0–1; default 0.1. See {@link schnakenberg}. */
25   readonly initialNoise?: number;
26   /** Initialization steps, integer 0–12000; default 4096. See {@link schnakenberg}. */
27   readonly warmupSteps?: number;
28   /** Multiplier of 480 numerical steps/second, finite 0–4; default 1. Zero idles. See {@link schnakenberg}. */
29   readonly speed?: number;
30   /** Initially suspend stepping; default false. See {@link InkMessage}. */
31   readonly paused?: boolean;
32 }
33 /** Schnakenberg production rates, diffusion and initialization. See {@link schnakenberg}. */
34 export interface SchnakenbergOptions extends ChemicalOptions {
35   /** Activator source, finite 0.01–2; default 0.1. See {@link schnakenberg}. */
36   readonly a?: number;
37   /** Inhibitor source, finite 0.01–2; default 0.9. See {@link schnakenberg}. */
38   readonly b?: number;
39 }
40 /** Excitability, recovery, diffusion and initialization. See {@link barkley}. */
41 export interface BarkleyOptions extends ChemicalOptions {
42   /** Excitability scale, finite 0.3–1.2; default 0.75. See {@link barkley}. */
43   readonly a?: number;
44   /** Excitation threshold offset, finite 0–0.2; default 0.02. See {@link barkley}. */
45   readonly b?: number;
46   /** Fast/slow time separation, finite 0.005–0.1; default 0.02. See {@link barkley}. */
47   readonly epsilon?: number;
48 }
49 /** Brusselator feed rates, diffusion and initialization. See {@link brusselator}. */
50 export interface BrusselatorOptions extends ChemicalOptions {
51   /** Activator feed, finite 0.1–3; default 1. See {@link brusselator}. */
52   readonly a?: number;
53   /** Conversion rate, finite 0.1–5; default 1.8. See {@link brusselator}. */
54   readonly b?: number;
55 }
56 /** Immutable Schnakenberg starting configurations. See {@link SchnakenbergOptions}. */
57 export const schnakenbergPresets = Object.freeze({
58   /** Separated activator spots. See {@link schnakenberg}. */
59   spots: Object.freeze({ a: 0.1, b: 0.9, diffusionU: 1, diffusionV: 20 }),
60   /** Connected activator bands. See {@link schnakenberg}. */
61   labyrinths: Object.freeze({
62     a: 0.01,
63     b: 1.7,
64     diffusionU: 1,
65     diffusionV: 20,
66     warmupSteps: 10000,
67   }),
68 });
69 /** Immutable Barkley starting configurations. See {@link BarkleyOptions}. */
70 export const barkleyPresets = Object.freeze({
71   /** Broken excitation fronts form rotating spirals. See {@link barkley}. */
72   spirals: Object.freeze({
73     a: 0.75,
74     b: 0.02,
75     epsilon: 0.02,
76     diffusionU: 1,
77     diffusionV: 0,
78   }),
79   /** Broader propagating excitation fronts. See {@link barkley}. */
80   waves: Object.freeze({
81     a: 0.9,
82     b: 0.01,
83     epsilon: 0.04,
84     diffusionU: 1,
85     diffusionV: 0,
86   }),
87 });
88 /** Immutable Brusselator starting configurations. See {@link BrusselatorOptions}. */
89 export const brusselatorPresets = Object.freeze({
90   /** Differential diffusion supports stationary spots. See {@link brusselator}. */
91   spots: Object.freeze({
92     a: 1,
93     b: 1.9,
94     diffusionU: 0.2,
95     diffusionV: 2,
96     warmupSteps: 10000,
97   }),
98   /** Equal diffusion above the oscillation threshold. See {@link brusselator}. */
99   oscillations: Object.freeze({ a: 1, b: 3, diffusionU: 0.3, diffusionV: 0.3 }),
100 });
101 function bounded(
102   name: string,
103   value: number,
104   min: number,
105   max: number,
106   integer = false,
107 ) {
108   if (
109     !Number.isFinite(value) ||
110     value < min ||
111     value > max ||
112     (integer && !Number.isInteger(value))
113   )
114     throw new RangeError(
115       `${name} must be ${integer ? "an integer " : ""}within ${min}..${max}.`,
116     );
117   return value;
118 }
119 function common(
120   options: ChemicalOptions,
121 ): Omit<ChemicalConfig, "a" | "b" | "epsilon" | "diffusionU" | "diffusionV"> {
122   if (options.paused !== undefined && typeof options.paused !== "boolean")
123     throw new TypeError("Chemical paused must be boolean.");
124   return {
125     seed: validateSeed(options.seed),
126     initialNoise: bounded(
127       "Chemical initialNoise",
128       options.initialNoise ?? 0.1,
129       0,
130       1,
131     ),
132     warmupSteps: bounded(
133       "Chemical warmupSteps",
134       options.warmupSteps ?? 4096,
135       0,
136       12000,
137       true,
138     ),
139     speed: bounded("Chemical speed", options.speed ?? 1, 0, 4),
140     paused: options.paused ?? false,
141   };
142 }
143 function diffusion(
144   options: ChemicalOptions,
145   defaults: { diffusionU: number; diffusionV: number },
146 ) {
147   return {
148     diffusionU: bounded(
149       "Chemical diffusionU",
150       options.diffusionU ?? defaults.diffusionU,
151       0,
152       32,
153     ),
154     diffusionV: bounded(
155       "Chemical diffusionV",
156       options.diffusionV ?? defaults.diffusionV,
157       0,
158       32,
159     ),
160   };
161 }
162 function schnakenbergConfig(options: SchnakenbergOptions): ChemicalConfig {
163   return {
164     ...common(options),
165     ...diffusion(options, schnakenbergPresets.spots),
166     a: bounded("Schnakenberg a", options.a ?? 0.1, 0.01, 2),
167     b: bounded("Schnakenberg b", options.b ?? 0.9, 0.01, 2),
168     epsilon: 0.02,
169   };
170 }
171 function barkleyConfig(options: BarkleyOptions): ChemicalConfig {
172   return {
173     ...common(options),
174     ...diffusion(options, barkleyPresets.spirals),
175     a: bounded("Barkley a", options.a ?? 0.75, 0.3, 1.2),
176     b: bounded("Barkley b", options.b ?? 0.02, 0, 0.2),
177     epsilon: bounded("Barkley epsilon", options.epsilon ?? 0.02, 0.005, 0.1),
178   };
179 }
180 function brusselatorConfig(options: BrusselatorOptions): ChemicalConfig {
181   return {
182     ...common(options),
183     ...diffusion(options, brusselatorPresets.spots),
184     a: bounded("Brusselator a", options.a ?? 1, 0.1, 3),
185     b: bounded("Brusselator b", options.b ?? 1.8, 0.1, 5),
186     epsilon: 0.02,
187   };
188 }
189 interface State {
190   config: ChemicalConfig;
191   field: ChemicalField;
192   paused: boolean;
193   elapsed: number;
194   fresh: boolean;
195   image: ImageData | undefined;
196   lut: Uint8ClampedArray | undefined;
197   paletteKey: string;
198 }
199 function chemicalRecipe(model: typeof schnakenbergModel) {
200   const makeField = (context: TextureContext, config: ChemicalConfig) => {
201     if (context.canvas.width < 3 || context.canvas.height < 3)
202       throw new RangeError(
203         "Chemical textures require at least 3×3 raster samples.",
204       );
205     return new ChemicalField({
206       width: context.canvas.width - 1,
207       height: context.canvas.height - 1,
208       config,
209       model,
210     });
211   };
212   const active = (state: State) => !state.paused && state.config.speed > 0;
213   const reset = (state: State, context: TextureContext) => {
214     const next = makeField(context, state.config);
215     state.field.dispose();
216     state.field = next;
217     state.elapsed = 0;
218     state.fresh = true;
219     context.invalidate();
220     if (active(state)) context.requestFrame();
221   };
222   return defineTexture<ChemicalConfig, State, InkMessage>({
223     defaultPlacement: { mode: "repeat" },
224     create(context, config) {
225       const state: State = {
226         config,
227         field: makeField(context, config),
228         paused: config.paused,
229         elapsed: 0,
230         fresh: true,
231         image: new ImageData(context.canvas.width, context.canvas.height),
232         lut: undefined,
233         paletteKey: "",
234       };
235       if (active(state)) context.requestFrame();
236       return state;
237     },
238     update(state, config, context) {
239       if (JSON.stringify(config) === JSON.stringify(state.config)) return;
240       const { speed: _speed, paused: _paused, ...previous } = state.config;
241       const { speed, paused, ...next } = config;
242       const changed = JSON.stringify(previous) !== JSON.stringify(next);
243       if (paused !== state.config.paused) state.paused = paused;
244       state.config = config;
245       state.elapsed = 0;
246       state.fresh = true;
247       if (changed) reset(state, context);
248       if (!state.paused && speed > 0) context.requestFrame();
249     },
250     receive(state, message, context) {
251       if (message.type === "pause") {
252         if (typeof message.paused !== "boolean")
253           throw new TypeError("Chemical pause requires a boolean.");
254         state.paused = message.paused;
255         state.elapsed = 0;
256         state.fresh = true;
257         if (active(state)) context.requestFrame();
258       } else if (message.type === "reset") reset(state, context);
259       else if (message.type === "paint" || message.type === "stir") {
260         const radius = bounded(
261           "Chemical brush radius",
262           message.radius ?? (message.type === "paint" ? 6 : 16),
263           0.01,
264           128,
265         );
266         if (!Number.isFinite(message.u) || !Number.isFinite(message.v))
267           throw new RangeError("Chemical brush coordinates must be finite.");
268         if (message.type === "paint") {
269           const strength = bounded(
270             "Chemical brush strength",
271             message.strength ?? 0.8,
272             0,
273             1,
274           );
275           if (message.u < 0 || message.u > 1 || message.v < 0 || message.v > 1)
276             return;
277           if (strength === 0) return;
278           state.field.paint({ ...message, radius, strength });
279         } else {
280           const du = bounded("Chemical stir du", message.du, -1, 1),
281             dv = bounded("Chemical stir dv", message.dv, -1, 1);
282           if (message.u < 0 || message.u > 1 || message.v < 0 || message.v > 1)
283             return;
284           state.field.stir({ ...message, radius, du, dv });
285         }
286         context.invalidate();
287       } else throw new TypeError("Unknown chemical texture message.");
288     },
289     advance(state, frame, context) {
290       if (!active(state)) return;
291       if (!state.fresh) {
292         state.elapsed += Math.min(50, frame.delta) * state.config.speed * 0.48;
293         const count = Math.min(96, Math.floor(state.elapsed));
294         state.elapsed -= count;
295         if (count > 0) {
296           state.field.advance(count);
297           context.invalidate();
298         }
299       }
300       state.fresh = false;
301       context.requestFrame();
302     },
303     rasterize(state, context) {
304       const key = (context.palette ?? texturePalettes.lagoon).join();
305       if (key !== state.paletteKey) {
306         state.lut = paletteLut(context.palette ?? texturePalettes.lagoon);
307         state.paletteKey = key;
308       }
309       const { width, height } = context.canvas,
310         data = state.image!.data,
311         lut = state.lut!;
312       for (let y = 0; y < height; y++)
313         for (let x = 0; x < width; x++) {
314           const index =
315             (y % state.field.height) * state.field.width +
316             (x % state.field.width);
317           const color =
318               Math.round(
319                 Math.max(0, Math.min(1, state.field.intensity(index))) * 255,
320               ) * 4,
321             i = (y * width + x) * 4;
322           data[i] = lut[color]!;
323           data[i + 1] = lut[color + 1]!;
324           data[i + 2] = lut[color + 2]!;
325           data[i + 3] = 255;
326         }
327       context.canvas.getContext("2d")!.putImageData(state.image!, 0, 0);
328     },
329     dispose(state) {
330       state.field.dispose();
331       state.image = undefined;
332       state.lut = undefined;
333     },
334   });
335 }
336 const schnakenbergRecipe = /* @__PURE__ */ chemicalRecipe(schnakenbergModel);
337 const barkleyRecipe = /* @__PURE__ */ chemicalRecipe(barkleyModel);
338 const brusselatorRecipe = /* @__PURE__ */ chemicalRecipe(brusselatorModel);
339 /**
340  * Creates a periodic Schnakenberg activator/inhibitor texture with paint, stir, pause and reset.
341  * @param options - Reaction rates, diffusion and initialization. See {@link SchnakenbergOptions}.
342  * @returns A mountable simulation recipe. See {@link TextureRecipe}, {@link InkMessage}.
343  * @see {@link schnakenbergPresets}
344  */
345 export function schnakenberg(
346   options: SchnakenbergOptions = {},
347 ): TextureRecipe<InkMessage> {
348   return schnakenbergRecipe(schnakenbergConfig(options));
349 }
350 /**
351  * Creates a periodic Barkley excitable texture initialized with a broken excitation front.
352  * @param options - Excitability, recovery, diffusion and initialization. See {@link BarkleyOptions}.
353  * @returns A mountable simulation recipe. See {@link TextureRecipe}, {@link InkMessage}.
354  * @see {@link barkleyPresets}
355  */
356 export function barkley(
357   options: BarkleyOptions = {},
358 ): TextureRecipe<InkMessage> {
359   return barkleyRecipe(barkleyConfig(options));
360 }
361 /**
362  * Creates a periodic Brusselator texture with paint, stir, pause and reset.
363  * @param options - Feed rates, diffusion and initialization. See {@link BrusselatorOptions}.
364  * @returns A mountable simulation recipe. See {@link TextureRecipe}, {@link InkMessage}.
365  * @see {@link brusselatorPresets}
366  */
367 export function brusselator(
368   options: BrusselatorOptions = {},
369 ): TextureRecipe<InkMessage> {
370   return brusselatorRecipe(brusselatorConfig(options));
371 }
372 

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