Skip to content

packages/core/src/features/textures/lib/geometric-patterns.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 { defineTexture, type TextureRecipe } from "@pibbl/core";
2 import { paletteLut, texturePalettes, validateSeed } from "./palette.js";
3 import type { PatternMotionOptions } from "./patterns.js";
4 
5 /** Seamless circular dots with optional stagger and seeded displacement. @see {@link polkaDots} */
6 export interface PolkaDotsOptions extends PatternMotionOptions {
7   /** Integer columns, 1–64; default 12. See {@link PolkaDotsOptions}. */
8   readonly columns?: number;
9   /** Even integer rows, 2–64; default 12, preserving stagger across the seam. See {@link PolkaDotsOptions}. */
10   readonly rows?: number;
11   /** Radius in cell fractions, 0–0.5; default 0.3. See {@link PolkaDotsOptions}. */
12   readonly radius?: number;
13   /** Alternate-row horizontal offset in cell fractions, 0–1; default 0. See {@link PolkaDotsOptions}. */
14   readonly stagger?: number;
15   /** Seeded center displacement per axis in cell fractions, 0–0.5; default 0. See {@link PolkaDotsOptions}. */
16   readonly jitter?: number;
17   /** Unsigned 32-bit variation seed; default 42. See {@link PolkaDotsOptions}. */
18   readonly seed?: number;
19 }
20 /** A periodic tonal field expressed as varying dot sizes. @see {@link halftone} */
21 export interface HalftoneOptions extends PatternMotionOptions {
22   /** Integer columns, 1–64; default 24. See {@link HalftoneOptions}. */
23   readonly columns?: number;
24   /** Even integer rows, 2–64; default 24. See {@link HalftoneOptions}. */
25   readonly rows?: number;
26   /** Smallest dot radius in cell fractions, 0–0.5; default 0.05. See {@link HalftoneOptions}. */
27   readonly minRadius?: number;
28   /** Largest dot radius in cell fractions, minRadius–0.5; default 0.45. See {@link HalftoneOptions}. */
29   readonly maxRadius?: number;
30   /** Integer horizontal tonal periods, 0–16; default 1. See {@link HalftoneOptions}. */
31   readonly cyclesX?: number;
32   /** Integer vertical tonal periods, 0–16; default 1. See {@link HalftoneOptions}. */
33   readonly cyclesY?: number;
34   /** Tonal wave amplitude, 0–1; default 0.7. See {@link HalftoneOptions}. */
35   readonly contrast?: number;
36   /** Alternate-row offset in cell fractions, 0–1; default 0.5. See {@link HalftoneOptions}. */
37   readonly stagger?: number;
38 }
39 /** Seeded connecting quarter-circle tiles. @see {@link truchet} */
40 export interface TruchetOptions extends PatternMotionOptions {
41   /** Integer columns, 1–64; default 8. See {@link TruchetOptions}. */
42   readonly columns?: number;
43   /** Integer rows, 1–64; default 8. See {@link TruchetOptions}. */
44   readonly rows?: number;
45   /** Stroke width in cell fractions, 0–0.5; default 0.12. See {@link TruchetOptions}. */
46   readonly lineWidth?: number;
47   /** Fraction of tiles with the first orientation, 0–1; default 0.5. See {@link TruchetOptions}. */
48   readonly orientationBias?: number;
49   /** Unsigned 32-bit orientation seed; default 42. See {@link TruchetOptions}. */
50   readonly seed?: number;
51 }
52 /** One band in an ordered plaid repeat; colors are named keys. @see {@link PlaidOptions} */
53 export interface PlaidBand<Key extends string = string> {
54   /** Positive relative width; all widths on an axis are normalized together. See {@link PlaidBand}. */
55   readonly width: number;
56   /** A key from the plaid's colors dictionary. See {@link PlaidBand}. */
57   readonly color: Key;
58 }
59 /** A plaid's named colors, ordered bands, and crossing balance. @see {@link plaid} */
60 export interface PlaidOptions<
61   Colors extends Readonly<Record<string, string>> = Readonly<
62     Record<string, string>
63   >,
64 > extends PatternMotionOptions {
65   /** Dictionary of 1–16 opaque #RRGGBB colors. See {@link PlaidOptions}. */
66   readonly colors: Colors;
67   /** Ordered horizontal bands, 1–32, referencing existing color keys. See {@link PlaidOptions}. */
68   readonly horizontal: readonly PlaidBand<
69     NoInfer<Extract<keyof Colors, string>>
70   >[];
71   /** Ordered vertical bands, 1–32, referencing existing color keys. See {@link PlaidOptions}. */
72   readonly vertical: readonly PlaidBand<
73     NoInfer<Extract<keyof Colors, string>>
74   >[];
75   /** Horizontal contribution at crossings, 0–1; default 0.5. See {@link PlaidOptions}. */
76   readonly crossing?: number;
77 }
78 const tau = 2 * Math.PI;
79 const wrap = (n: number) => ((n % 1) + 1) % 1;
80 function bound(
81   name: string,
82   n: number,
83   min: number,
84   max: number,
85   integer = false,
86 ) {
87   if (
88     !Number.isFinite(n) ||
89     n < min ||
90     n > max ||
91     (integer && !Number.isInteger(n))
92   )
93     throw new RangeError(
94       `${name} must be ${integer ? "an integer" : "finite"} in ${min}–${max}.`,
95     );
96   return n;
97 }
98 function motion(o: PatternMotionOptions) {
99   return {
100     phase: wrap(
101       bound("phase", o.phase ?? 0, -Number.MAX_VALUE, Number.MAX_VALUE),
102     ),
103     speed: bound("speed", o.speed ?? 0, 0, 20),
104   };
105 }
106 function grid(
107   o: { columns?: number; rows?: number },
108   defaults: number,
109   even = false,
110 ) {
111   const columns = bound("columns", o.columns ?? defaults, 1, 64, true),
112     rows = bound("rows", o.rows ?? defaults, even ? 2 : 1, 64, true);
113   if (even && rows % 2)
114     throw new RangeError("rows must be even for seamless stagger.");
115   return { columns, rows };
116 }
117 function hash(
118   x: number,
119   y: number,
120   columns: number,
121   rows: number,
122   seed: number,
123 ) {
124   const ix = ((x % columns) + columns) % columns,
125     iy = ((y % rows) + rows) % rows;
126   let h = Math.imul((iy * columns + ix) ^ seed, 0x45d9f3b);
127   h = Math.imul(h ^ (h >>> 16), 0x45d9f3b);
128   return ((h ^ (h >>> 16)) >>> 0) / 0x100000000;
129 }
130 function coverage(distance: number, halfWidth: number, pixel: number) {
131   if (halfWidth === 0) return 0;
132   const t = Math.max(0, Math.min(1, (halfWidth - distance) / pixel + 0.5));
133   return t * t * (3 - 2 * t);
134 }
135 type Motion = { phase: number; speed: number };
136 type RGB = readonly [number, number, number];
137 interface State<C> {
138   config: C;
139   phase: number;
140   fresh: boolean;
141   dirty: boolean;
142   image: ImageData | undefined;
143   paletteKey: string;
144   lut: Uint8ClampedArray | undefined;
145 }
146 // Each factory owns a stable definition. Color samplers share only bounded raster
147 // storage and the existing Pibbl lifecycle; they never start a separate timer.
148 function geometry<O, C extends Motion>(
149   validate: (o: O) => C,
150   sample: (
151     c: C,
152     u: number,
153     v: number,
154     phase: number,
155     pixelX: number,
156     pixelY: number,
157   ) => number | RGB,
158   named = false,
159 ) {
160   const definition = defineTexture<C, State<C>>({
161     create(context, config) {
162       if (config.speed) context.requestFrame();
163       return {
164         config,
165         phase: config.phase,
166         fresh: true,
167         dirty: true,
168         image: new ImageData(context.canvas.width, context.canvas.height),
169         paletteKey: "",
170         lut: undefined,
171       };
172     },
173     update(state, config, context) {
174       if (JSON.stringify(config) === JSON.stringify(state.config)) return;
175       if (config.phase !== state.config.phase) state.phase = config.phase;
176       if (config.speed !== state.config.speed) state.fresh = true;
177       state.config = config;
178       state.dirty = true;
179       context.invalidate();
180       if (config.speed) context.requestFrame();
181     },
182     advance(state, frame, context) {
183       if (!state.config.speed) return;
184       if (!state.fresh && frame.delta > 0) {
185         state.phase = wrap(
186           state.phase + (frame.delta * state.config.speed) / 1000,
187         );
188         state.dirty = true;
189         context.invalidate();
190       }
191       state.fresh = false;
192       context.requestFrame();
193     },
194     rasterize(state, context) {
195       if (named && context.palette !== undefined)
196         throw new TypeError(
197           "plaid uses its named colors dictionary; omit useTexture palette.",
198         );
199       const palette = context.palette ?? texturePalettes.porcelain,
200         key = palette.join();
201       if (!named && key !== state.paletteKey) {
202         state.lut = paletteLut(palette);
203         state.paletteKey = key;
204         state.dirty = true;
205       }
206       if (!state.dirty) return;
207       const { width, height } = context.canvas,
208         data = state.image!.data;
209       for (let y = 0; y < height; y++)
210         for (let x = 0; x < width; x++) {
211           const result = sample(
212               state.config,
213               x === width - 1 ? 0 : x / (width - 1),
214               y === height - 1 ? 0 : y / (height - 1),
215               state.phase,
216               1 / (width - 1),
217               1 / (height - 1),
218             ),
219             index = (y * width + x) * 4;
220           if (typeof result === "number") {
221             const at = Math.round(Math.max(0, Math.min(1, result)) * 255) * 4;
222             data[index] = state.lut![at];
223             data[index + 1] = state.lut![at + 1];
224             data[index + 2] = state.lut![at + 2];
225           } else {
226             data[index] = result[0];
227             data[index + 1] = result[1];
228             data[index + 2] = result[2];
229           }
230           data[index + 3] = 255;
231         }
232       context.canvas.getContext("2d")!.putImageData(state.image!, 0, 0);
233       state.dirty = false;
234     },
235     dispose(state) {
236       state.image = undefined;
237       state.lut = undefined;
238     },
239   });
240   return (o: O): TextureRecipe => definition(validate(o));
241 }
242 function dots(
243   c: {
244     columns: number;
245     rows: number;
246     stagger: number;
247     jitter: number;
248     seed: number;
249   },
250   u: number,
251   v: number,
252   radius: (x: number, y: number) => number,
253   px: number,
254   py: number,
255 ) {
256   const x = u * c.columns,
257     y = v * c.rows,
258     pixel = Math.max(px * c.columns, py * c.rows);
259   let amount = 0;
260   // Neighboring periodic cells include dots displaced across cell/tile boundaries.
261   for (let j = Math.floor(y) - 1; j <= Math.floor(y) + 1; j++)
262     for (let i = Math.floor(x) - 2; i <= Math.floor(x) + 1; i++) {
263       const row = ((j % c.rows) + c.rows) % c.rows;
264       const cx =
265         i +
266         0.5 +
267         (row % 2) * c.stagger +
268         (hash(i, j, c.columns, c.rows, c.seed) - 0.5) * 2 * c.jitter;
269       const cy =
270         j +
271         0.5 +
272         (hash(i, j, c.columns, c.rows, c.seed ^ 0x19ae) - 0.5) * 2 * c.jitter;
273       amount = Math.max(
274         amount,
275         coverage(Math.hypot(x - cx, y - cy), radius(i, j), pixel),
276       );
277     }
278   return amount;
279 }
280 const dotRecipe = geometry(
281   (o: PolkaDotsOptions) => ({
282     ...motion(o),
283     ...grid(o, 12, true),
284     radius: bound("radius", o.radius ?? 0.3, 0, 0.5),
285     stagger: bound("stagger", o.stagger ?? 0, 0, 1),
286     jitter: bound("jitter", o.jitter ?? 0, 0, 0.5),
287     seed: validateSeed(o.seed ?? 42),
288   }),
289   (c, u, v, p, px, py) => dots(c, wrap(u + p), v, () => c.radius, px, py),
290 );
291 /**
292  * Creates a seamless dot lattice using palette endpoints.
293  * @param options - Dot geometry and motion.
294  * @returns A mountable texture recipe.
295  * @see {@link PolkaDotsOptions}
296  */
297 export function polkaDots(options: PolkaDotsOptions = {}): TextureRecipe {
298   return dotRecipe(options);
299 }
300 const halftoneRecipe = geometry(
301   (o: HalftoneOptions) => {
302     const minRadius = bound("minRadius", o.minRadius ?? 0.05, 0, 0.5),
303       maxRadius = bound("maxRadius", o.maxRadius ?? 0.45, minRadius, 0.5);
304     return {
305       ...motion(o),
306       ...grid(o, 24, true),
307       minRadius,
308       maxRadius,
309       cyclesX: bound("cyclesX", o.cyclesX ?? 1, 0, 16, true),
310       cyclesY: bound("cyclesY", o.cyclesY ?? 1, 0, 16, true),
311       contrast: bound("contrast", o.contrast ?? 0.7, 0, 1),
312       stagger: bound("stagger", o.stagger ?? 0.5, 0, 1),
313       jitter: 0,
314       seed: 42,
315     };
316   },
317   (c, u, v, p, px, py) =>
318     dots(
319       c,
320       u,
321       v,
322       (x, y) => {
323         const tone =
324           0.5 +
325           0.25 *
326             c.contrast *
327             (Math.sin(tau * (((x + 0.5) / c.columns) * c.cyclesX + p)) +
328               Math.sin(tau * (((y + 0.5) / c.rows) * c.cyclesY + p)));
329         return c.minRadius + (c.maxRadius - c.minRadius) * tone;
330       },
331       px,
332       py,
333     ),
334 );
335 /**
336  * Creates seamless varying-size dots from a periodic tonal field.
337  * @param options - Dot sizes, tonal periods, and motion.
338  * @returns A mountable texture recipe.
339  * @see {@link HalftoneOptions}
340  */
341 export function halftone(options: HalftoneOptions = {}): TextureRecipe {
342   return halftoneRecipe(options);
343 }
344 const truchetRecipe = geometry(
345   (o: TruchetOptions) => ({
346     ...motion(o),
347     ...grid(o, 8),
348     lineWidth: bound("lineWidth", o.lineWidth ?? 0.12, 0, 0.5),
349     orientationBias: bound("orientationBias", o.orientationBias ?? 0.5, 0, 1),
350     seed: validateSeed(o.seed ?? 42),
351   }),
352   (c, u, v, p, px, py) => {
353     const x = wrap(u + p) * c.columns,
354       y = wrap(v + p) * c.rows,
355       ix = Math.floor(x),
356       iy = Math.floor(y),
357       a = x - ix,
358       b = y - iy;
359     const first = hash(ix, iy, c.columns, c.rows, c.seed) < c.orientationBias;
360     const distance = first
361       ? Math.min(
362           Math.abs(Math.hypot(a, b) - 0.5),
363           Math.abs(Math.hypot(1 - a, 1 - b) - 0.5),
364         )
365       : Math.min(
366           Math.abs(Math.hypot(1 - a, b) - 0.5),
367           Math.abs(Math.hypot(a, 1 - b) - 0.5),
368         );
369     return coverage(
370       distance,
371       c.lineWidth / 2,
372       Math.max(px * c.columns, py * c.rows),
373     );
374   },
375 );
376 /**
377  * Creates seeded quarter-circle tiles that connect across every edge.
378  * @param options - Tile counts, stroke width, seed, and motion.
379  * @returns A mountable texture recipe.
380  * @see {@link TruchetOptions}
381  */
382 export function truchet(options: TruchetOptions = {}): TextureRecipe {
383   return truchetRecipe(options);
384 }
385 interface Band {
386   end: number;
387   color: RGB;
388 }
389 function bands(
390   input: readonly PlaidBand[],
391   colors: Readonly<Record<string, RGB>>,
392 ): Band[] {
393   if (!Array.isArray(input) || input.length < 1 || input.length > 32)
394     throw new RangeError("Plaid requires 1–32 bands per axis.");
395   const total = input.reduce(
396     (n, b) => n + bound("band width", b.width, Number.MIN_VALUE, 1e6),
397     0,
398   );
399   let end = 0;
400   return input.map((b) => {
401     if (!Object.hasOwn(colors, b.color))
402       throw new TypeError(`Unknown plaid color key: ${b.color}`);
403     end += b.width / total;
404     return { end, color: colors[b.color] };
405   });
406 }
407 // Integrate a box footprint across periodic band boundaries, giving crisp interiors
408 // and gradual coverage at edges at any raster resolution.
409 function bandColor(
410   bands: readonly Band[],
411   position: number,
412   footprint: number,
413 ): RGB {
414   const center = wrap(position),
415     lo = center - footprint / 2,
416     hi = center + footprint / 2,
417     result = [0, 0, 0];
418   for (let shift = -1; shift <= 1; shift++) {
419     let start = shift;
420     for (const band of bands) {
421       const end = shift + band.end,
422         weight =
423           Math.max(0, Math.min(hi, end) - Math.max(lo, start)) / footprint;
424       for (let k = 0; k < 3; k++) result[k] += band.color[k] * weight;
425       start = end;
426     }
427   }
428   return result as [number, number, number];
429 }
430 const plaidRecipe = geometry(
431   (
432     o: PatternMotionOptions & {
433       colors: Readonly<Record<string, string>>;
434       horizontal: readonly PlaidBand[];
435       vertical: readonly PlaidBand[];
436       crossing?: number;
437     },
438   ) => {
439     const entries = Object.entries(o.colors);
440     if (entries.length < 1 || entries.length > 16)
441       throw new RangeError("Plaid colors requires 1–16 named entries.");
442     const colors: Record<string, RGB> = Object.create(null);
443     for (const [key, value] of entries) {
444       if (!key || !/^#[\da-f]{6}$/i.test(value))
445         throw new TypeError("Plaid colors require named #RRGGBB entries.");
446       colors[key] = [
447         parseInt(value.slice(1, 3), 16),
448         parseInt(value.slice(3, 5), 16),
449         parseInt(value.slice(5, 7), 16),
450       ];
451     }
452     return {
453       ...motion(o),
454       horizontal: bands(o.horizontal, colors),
455       vertical: bands(o.vertical, colors),
456       crossing: bound("crossing", o.crossing ?? 0.5, 0, 1),
457     };
458   },
459   (c, u, v, p, px, py) => {
460     const horizontal = bandColor(c.horizontal, v + p, py),
461       vertical = bandColor(c.vertical, u + p, px);
462     return horizontal.map(
463       (n, i) => n * c.crossing + vertical[i] * (1 - c.crossing),
464     ) as [number, number, number];
465   },
466   true,
467 );
468 /**
469  * Creates plaid using checked color keys and ordered relative-width bands.
470  * @param options - Named colors, bands, crossing balance, and motion.
471  * @returns A mountable texture recipe.
472  * @see {@link PlaidOptions}
473  */
474 export function plaid<const Colors extends Readonly<Record<string, string>>>(
475   options: PlaidOptions<Colors>,
476 ): TextureRecipe {
477   return plaidRecipe(options);
478 }
479 const presetColors = Object.freeze({
480   background: "#f5e9d3",
481   primary: "#304c48",
482   accent: "#c56948",
483 });
484 function preset(sequence: readonly PlaidBand<keyof typeof presetColors>[]) {
485   const bands = Object.freeze(sequence.map((b) => Object.freeze({ ...b })));
486   return Object.freeze({
487     colors: presetColors,
488     horizontal: bands,
489     vertical: bands,
490     crossing: 0.5,
491   });
492 }
493 /** Named-color band configurations for gingham, tartan, and windowpane patterns. @see {@link plaid} */
494 export const plaidPresets = Object.freeze({
495   /** Equal-width alternating bands. See {@link plaidPresets}. */
496   gingham: preset([
497     { width: 1, color: "background" },
498     { width: 1, color: "primary" },
499   ]),
500   /** Symmetric bands with narrow accent lines. See {@link plaidPresets}. */
501   tartan: preset([
502     { width: 8, color: "primary" },
503     { width: 2, color: "background" },
504     { width: 1, color: "accent" },
505     { width: 2, color: "background" },
506   ]),
507   /** Narrow crossing lines on a broad background. See {@link plaidPresets}. */
508   windowpane: preset([
509     { width: 14, color: "background" },
510     { width: 1, color: "primary" },
511   ]),
512 });
513 

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