packages/core/src/features/textures/lib/patterns.ts
This is the source snapshot used to build these API details. View this revision on GitHub.
1 import {
2 defineTexture,
3 type TextureContext,
4 type TextureRecipe,
5 } from "@pibbl/core";
6 import { paletteLut, texturePalettes, validateSeed } from "./palette.js";
7
8 /** Shared periodic motion controls for geometric and fiber recipes. @see {@link stripes} */
9 export interface PatternMotionOptions {
10 /** Initial phase in cycles; any finite value wraps. See {@link PatternMotionOptions}. */
11 readonly phase?: number;
12 /** Nonnegative cycles per second, up to 20; zero idles. See {@link PatternMotionOptions}. */
13 readonly speed?: number;
14 }
15 /** Controls for periodic stripes; rotate the repeat lattice through paint placement. @see {@link stripes} */
16 export interface StripesOptions extends PatternMotionOptions {
17 /** Integer stripe periods across the tile, 1–64; default 8. See {@link StripesOptions}. */
18 readonly bands?: number;
19 /** Foreground fraction of each period, 0–1; default 0.5. See {@link StripesOptions}. */
20 readonly dutyCycle?: number;
21 /** Horizontal wave amplitude in tile fractions, 0–1; default 0. See {@link StripesOptions}. */
22 readonly wave?: number;
23 /** Integer wave periods down the tile, 1–16; default 1. See {@link StripesOptions}. */
24 readonly waveCycles?: number;
25 }
26 /** Controls for a two-color checkerboard. @see {@link checkers} */
27 export interface CheckersOptions extends PatternMotionOptions {
28 /** Even integer columns, 2–64; default 8. See {@link CheckersOptions}. */
29 readonly columns?: number;
30 /** Even integer rows, 2–64; default 8. See {@link CheckersOptions}. */
31 readonly rows?: number;
32 }
33 /** Controls for seeded seamless wood grain with optional knots. @see {@link woodGrain} */
34 export interface WoodGrainOptions extends PatternMotionOptions {
35 /** Unsigned 32-bit variation seed; default 42. See {@link WoodGrainOptions}. */
36 readonly seed?: number;
37 /** Integer grain periods across the tile, 4–128; default 32. See {@link WoodGrainOptions}. */
38 readonly grain?: number;
39 /** Irregular grain bending, 0–1; default 0.5. See {@link WoodGrainOptions}. */
40 readonly distortion?: number;
41 /** Fine fiber and pore variation, 0–1; default 0.4. See {@link WoodGrainOptions}. */
42 readonly roughness?: number;
43 /** Integer knot count, 0–12; default 0 for clear grain. See {@link WoodGrainOptions}. */
44 readonly knots?: number;
45 /** Knot radius in tile fractions, 0.02–0.18; default 0.09. See {@link WoodGrainOptions}. */
46 readonly knotSize?: number;
47 }
48 const tau = Math.PI * 2;
49 function wrap(value: number) {
50 return ((value % 1) + 1) % 1;
51 }
52 function bounded(
53 name: string,
54 value: number,
55 min: number,
56 max: number,
57 integer = false,
58 ) {
59 if (
60 !Number.isFinite(value) ||
61 value < min ||
62 value > max ||
63 (integer && !Number.isInteger(value))
64 )
65 throw new RangeError(
66 `${name} must be ${integer ? "an integer " : ""}in [${min}, ${max}].`,
67 );
68 return value;
69 }
70 function motion(options: PatternMotionOptions) {
71 const phase = options.phase ?? 0;
72 if (!Number.isFinite(phase))
73 throw new RangeError("Texture phase must be finite.");
74 return {
75 phase: wrap(phase),
76 speed: bounded("Texture speed", options.speed ?? 0, 0, 20),
77 };
78 }
79 type Motion = ReturnType<typeof motion>;
80 interface PatternState<Config> {
81 config: Config;
82 phase: number;
83 fresh: boolean;
84 fieldDirty: boolean;
85 field: Float32Array;
86 image: ImageData | undefined;
87 paletteKey?: string;
88 lut?: Uint8ClampedArray;
89 }
90 // Shared lifecycle only. Each public factory has its own configuration and one
91 // fixed return contract. Sampling and recoloring reuse bounded buffers.
92 function pattern<Options, Config extends Motion>(
93 validate: (options: Options) => Config,
94 sample: (config: Config, u: number, v: number, phase: number) => number,
95 ) {
96 const definition = defineTexture<Config, PatternState<Config>>({
97 create(context, config) {
98 const { width, height } = context.canvas;
99 if (config.speed > 0) context.requestFrame();
100 return {
101 config,
102 phase: config.phase,
103 fresh: true,
104 fieldDirty: true,
105 field: new Float32Array(width * height),
106 image: new ImageData(width, height),
107 };
108 },
109 update(state, config, context) {
110 if (JSON.stringify(config) === JSON.stringify(state.config)) return;
111 if (config.phase !== state.config.phase) state.phase = config.phase;
112 if (config.speed !== state.config.speed) state.fresh = true;
113 state.config = config;
114 state.fieldDirty = true;
115 context.invalidate();
116 if (config.speed > 0) context.requestFrame();
117 },
118 advance(state, frame, context) {
119 if (state.config.speed === 0) return;
120 if (!state.fresh && frame.delta > 0) {
121 state.phase = wrap(
122 state.phase + (frame.delta * state.config.speed) / 1000,
123 );
124 state.fieldDirty = true;
125 context.invalidate();
126 }
127 state.fresh = false;
128 context.requestFrame();
129 },
130 rasterize(state, context: TextureContext) {
131 const { width, height } = context.canvas;
132 if (state.fieldDirty) {
133 for (let y = 0; y < height; y++)
134 for (let x = 0; x < width; x++)
135 state.field[y * width + x] = sample(
136 state.config,
137 x === width - 1 ? 0 : x / (width - 1),
138 y === height - 1 ? 0 : y / (height - 1),
139 state.phase,
140 );
141 state.fieldDirty = false;
142 }
143 const palette = context.palette ?? texturePalettes.porcelain;
144 const key = palette.join();
145 if (key !== state.paletteKey) {
146 state.lut = paletteLut(palette);
147 state.paletteKey = key;
148 }
149 const image = state.image!;
150 const data = image.data,
151 lut = state.lut!;
152 for (let i = 0; i < state.field.length; i++) {
153 const index =
154 Math.round(Math.max(0, Math.min(1, state.field[i])) * 255) * 4;
155 data[i * 4] = lut[index];
156 data[i * 4 + 1] = lut[index + 1];
157 data[i * 4 + 2] = lut[index + 2];
158 data[i * 4 + 3] = 255;
159 }
160 context.canvas.getContext("2d")!.putImageData(image, 0, 0);
161 },
162 dispose(state) {
163 state.field = new Float32Array(0);
164 state.image = undefined;
165 state.lut = undefined;
166 },
167 });
168 return (options: Options): TextureRecipe => definition(validate(options));
169 }
170 const stripeRecipe = /* @__PURE__ */ pattern(
171 (options: StripesOptions) => ({
172 ...motion(options),
173 bands: bounded("Stripe bands", options.bands ?? 8, 1, 64, true),
174 dutyCycle: bounded("Stripe dutyCycle", options.dutyCycle ?? 0.5, 0, 1),
175 wave: bounded("Stripe wave", options.wave ?? 0, 0, 1),
176 waveCycles: bounded(
177 "Stripe waveCycles",
178 options.waveCycles ?? 1,
179 1,
180 16,
181 true,
182 ),
183 }),
184 (c, u, v, phase) =>
185 wrap(
186 (u + c.wave * Math.sin(tau * (v * c.waveCycles + phase))) * c.bands +
187 phase,
188 ) < c.dutyCycle
189 ? 1
190 : 0,
191 );
192
193 /**
194 * Creates seamless straight or wavy stripes using the palette endpoints.
195 * @param options - Stripe geometry and periodic motion. See {@link StripesOptions}.
196 * @returns A mountable texture recipe with no message commands. See {@link TextureRecipe}.
197 * @see {@link StripesOptions}
198 */
199 export function stripes(options: StripesOptions = {}): TextureRecipe {
200 return stripeRecipe(options);
201 }
202 const checkerRecipe = /* @__PURE__ */ pattern(
203 (options: CheckersOptions) => {
204 const columns = bounded(
205 "Checker columns",
206 options.columns ?? 8,
207 2,
208 64,
209 true,
210 );
211 const rows = bounded("Checker rows", options.rows ?? 8, 2, 64, true);
212 if (columns % 2 || rows % 2)
213 throw new RangeError(
214 "Checker rows and columns must be even for seamless alternation.",
215 );
216 return { ...motion(options), columns, rows };
217 },
218 (c, u, v, phase) =>
219 (Math.floor(wrap(u + phase) * c.columns) + Math.floor(v * c.rows)) % 2,
220 );
221 /**
222 * Creates a seamless checkerboard using the palette endpoints.
223 * @param options - Even row/column counts and periodic motion. See {@link CheckersOptions}.
224 * @returns A mountable texture recipe with no message commands. See {@link TextureRecipe}.
225 * @see {@link CheckersOptions}
226 */
227 export function checkers(options: CheckersOptions = {}): TextureRecipe {
228 return checkerRecipe(options);
229 }
230 function hash(index: number, seed: number) {
231 let value = Math.imul(index ^ seed, 0x45d9f3b);
232 value = Math.imul(value ^ (value >>> 16), 0x45d9f3b);
233 return ((value ^ (value >>> 16)) >>> 0) / 0xffffffff;
234 }
235 // Seeded lattice noise wraps both axes. Several scales bend the growth lines
236 // independently, avoiding the uniform sine-wave paths of the original study.
237 function noise(
238 u: number,
239 v: number,
240 columns: number,
241 rows: number,
242 seed: number,
243 ) {
244 const x = wrap(u) * columns,
245 y = wrap(v) * rows;
246 const ix = Math.floor(x),
247 iy = Math.floor(y);
248 const fx = x - ix,
249 fy = y - iy;
250 const sx = fx * fx * fx * (fx * (fx * 6 - 15) + 10);
251 const sy = fy * fy * fy * (fy * (fy * 6 - 15) + 10);
252 const a = hash(iy * columns + ix, seed);
253 const b = hash(iy * columns + ((ix + 1) % columns), seed);
254 const c = hash(((iy + 1) % rows) * columns + ix, seed);
255 const d = hash(((iy + 1) % rows) * columns + ((ix + 1) % columns), seed);
256 return ((a + (b - a) * sx) * (1 - sy) + (c + (d - c) * sx) * sy) * 2 - 1;
257 }
258 const woodRecipe = /* @__PURE__ */ pattern(
259 (options: WoodGrainOptions) => {
260 const seed = validateSeed(options.seed);
261 const knots = bounded("Wood knots", options.knots ?? 0, 0, 12, true);
262 return {
263 ...motion(options),
264 seed,
265 grain: bounded("Wood grain", options.grain ?? 32, 4, 128, true),
266 distortion: bounded("Wood distortion", options.distortion ?? 0.5, 0, 1),
267 roughness: bounded("Wood roughness", options.roughness ?? 0.4, 0, 1),
268 knotSize: bounded("Wood knotSize", options.knotSize ?? 0.09, 0.02, 0.18),
269 knots: Array.from({ length: knots }, (_, i) => ({
270 u: hash(i * 7 + 11, seed),
271 v: hash(i * 7 + 21, seed),
272 aspect: 1 + 0.9 * hash(i * 7 + 31, seed),
273 })),
274 };
275 },
276 (c, u, v, phase) => {
277 v = wrap(v + phase);
278 const broad = noise(u, v, 4, 4, c.seed);
279 const medium = noise(u, v, 8, 8, c.seed ^ 0x517cc1b7);
280 const fine = noise(u, v, 16, 16, c.seed ^ 0x68bc21eb);
281 let coordinate =
282 u + c.distortion * (0.12 * broad + 0.045 * medium + 0.015 * fine);
283 // Shortest periodic offsets let a knot crossing a tile boundary continue
284 // in its neighboring copy. Compact support vanishes before antipodal points.
285 for (const knot of c.knots) {
286 const dx = wrap(u - knot.u + 0.5) - 0.5;
287 const dy = wrap(v - knot.v + 0.5) - 0.5;
288 const radius = Math.hypot(dx, dy / knot.aspect) / (c.knotSize * 0.7);
289 if (radius >= 2) continue;
290 // Inverse stream coordinate around an elliptical obstacle: subtracting
291 // this displacement makes equal-growth contours bow away from the core.
292 // At radius 1 the center streamline follows the knot boundary; the
293 // compact taper restores undisturbed grain at radius 2.
294 const outside = Math.max(1, radius);
295 const influence = Math.pow((4 - outside * outside) / 3, 2);
296 coordinate -= (dx / (outside * outside)) * influence;
297 }
298 const growth =
299 0.5 +
300 0.5 * Math.cos(tau * (coordinate * c.grain + c.roughness * fine * 0.2));
301 const fiber = Math.pow(
302 0.5 + 0.5 * Math.cos(tau * coordinate * c.grain * 3),
303 12,
304 );
305 let value =
306 0.72 -
307 0.32 * Math.pow(growth, 7) +
308 0.055 * broad -
309 c.roughness * (0.09 * fiber + 0.035 * fine);
310 for (const knot of c.knots) {
311 const dx = wrap(u - knot.u + 0.5) - 0.5;
312 const dy = wrap(v - knot.v + 0.5) - 0.5;
313 const radius = Math.hypot(dx, dy / knot.aspect) / (c.knotSize * 0.7);
314 if (radius >= 1) continue;
315 const edge = Math.min(1, Math.max(0, (radius - 0.85) / 0.15));
316 const blend = 1 - edge * edge * (3 - 2 * edge);
317 const ring = Math.pow(0.5 + 0.5 * Math.cos(tau * radius * 3), 5);
318 const knotValue =
319 0.55 - 0.23 * ring - 0.28 * Math.pow(Math.max(0, 1 - radius * 3), 2);
320 value += (knotValue - value) * blend;
321 }
322 return value;
323 },
324 );
325 /**
326 * Creates seamless seeded wood with irregular grain, fine fibers, and optional knots.
327 * @param options - Grain frequency, distortion, roughness, knots, seed, and motion. See {@link WoodGrainOptions}.
328 * @returns A mountable texture recipe with no message commands. See {@link TextureRecipe}.
329 * @see {@link WoodGrainOptions}
330 */
331 export function woodGrain(options: WoodGrainOptions = {}): TextureRecipe {
332 return woodRecipe(options);
333 }
334
335 /** Shared thread geometry and shading for seamless woven fabrics. @see {@link plainWeave} */
336 export interface FabricOptions extends PatternMotionOptions {
337 /** Unsigned 32-bit fiber variation seed; default 42. See {@link FabricOptions}. */
338 readonly seed?: number;
339 /** Thread count on each axis, a multiple of 8 in 8–128; default 16. See {@link FabricOptions}. */
340 readonly threads?: number;
341 /** Thread width as a fraction of cell spacing, 0.2–1; default 0.8. See {@link FabricOptions}. */
342 readonly threadWidth?: number;
343 /** Rounded thread lighting strength, 0–1; default 0.65. See {@link FabricOptions}. */
344 readonly relief?: number;
345 /** Seeded directional fibers and soft, uneven yarn edges, 0–1; default 0.2. See {@link FabricOptions}. */
346 readonly fuzz?: number;
347 }
348 function fabricConfig(options: FabricOptions) {
349 const threads = bounded(
350 "Fabric threads",
351 options.threads ?? 16,
352 8,
353 128,
354 true,
355 );
356 if (threads % 8 !== 0)
357 throw new RangeError("Fabric threads must be a multiple of 8.");
358 return {
359 ...motion(options),
360 seed: validateSeed(options.seed),
361 threads,
362 threadWidth: bounded(
363 "Fabric threadWidth",
364 options.threadWidth ?? 0.8,
365 0.2,
366 1,
367 ),
368 relief: bounded("Fabric relief", options.relief ?? 0.65, 0, 1),
369 fuzz: bounded("Fabric fuzz", options.fuzz ?? 0.2, 0, 1),
370 };
371 }
372 type FabricConfig = ReturnType<typeof fabricConfig>;
373 function fabricSample(
374 c: FabricConfig,
375 u: number,
376 v: number,
377 warpOnTop: boolean,
378 ) {
379 const x = u * c.threads,
380 y = v * c.threads;
381 const warpFiber = noise(u, v, c.threads * 8, 16, c.seed);
382 const weftFiber = noise(u, v, 16, c.threads * 8, c.seed ^ 0x68bc21eb);
383 // Spun yarn has uneven edges and a soft fiber envelope. Coverage, rather
384 // than a binary inside/outside test, keeps enlarged yarn from looking cut out.
385 const warpRadius = c.threadWidth * (1 + c.fuzz * 0.14 * warpFiber);
386 const weftRadius = c.threadWidth * (1 + c.fuzz * 0.14 * weftFiber);
387 const acrossWarp = (Math.abs((x % 1) - 0.5) * 2) / warpRadius;
388 const acrossWeft = (Math.abs((y % 1) - 0.5) * 2) / weftRadius;
389 const softness = 0.1 + c.fuzz * 0.45;
390 const coverage = (across: number) => {
391 const t = Math.max(
392 0,
393 Math.min(1, (across - (1 - softness)) / (2 * softness)),
394 );
395 return 1 - t * t * (3 - 2 * t);
396 };
397 const warp = coverage(acrossWarp),
398 weft = coverage(acrossWeft);
399 const warpCrown = Math.sqrt(Math.max(0, 1 - acrossWarp * acrossWarp));
400 const weftCrown = Math.sqrt(Math.max(0, 1 - acrossWeft * acrossWeft));
401 const warpValue =
402 0.62 + c.relief * (0.14 * warpCrown - 0.07) + c.fuzz * 0.15 * warpFiber;
403 const weftValue =
404 0.43 + c.relief * (0.14 * weftCrown - 0.07) + c.fuzz * 0.15 * weftFiber;
405 const gap = 0.18;
406 // The drawdown determines occlusion at crossings. A yarn stays continuous
407 // along a float; no per-cell bevel or repeated shadow chops it into blocks.
408 return warpOnTop
409 ? warpValue * warp + (weftValue * weft + gap * (1 - weft)) * (1 - warp)
410 : weftValue * weft + (warpValue * warp + gap * (1 - warp)) * (1 - weft);
411 }
412 const plainWeaveRecipe = /* @__PURE__ */ pattern(
413 fabricConfig,
414 (c, u, v, phase) => {
415 v = wrap(v + phase);
416 const x = Math.floor(u * c.threads),
417 y = Math.floor(v * c.threads);
418 return fabricSample(c, u, v, (x + y) % 2 === 0);
419 },
420 );
421 const twillRecipe = /* @__PURE__ */ pattern(fabricConfig, (c, u, v, phase) => {
422 v = wrap(v + phase);
423 const x = Math.floor(u * c.threads),
424 y = Math.floor(v * c.threads);
425 return fabricSample(c, u, v, (((x - y) % 4) + 4) % 4 < 2);
426 });
427 const herringboneHarnesses = [0, 1, 2, 3, 1, 0, 3, 2] as const;
428 const herringboneRecipe = /* @__PURE__ */ pattern(
429 fabricConfig,
430 (c, u, v, phase) => {
431 v = wrap(v + phase);
432 const x = Math.floor(u * c.threads) % 8,
433 y = Math.floor(v * c.threads);
434 // CottonWorks Weaving 101, p. 23: harness sequence 1,2,3,4,2,1,4,3.
435 // The offset at each reversal breaks the diagonal instead of duplicating
436 // the turning end, which would produce a pointed/chevron-like twill.
437 const harness = herringboneHarnesses[x];
438 return fabricSample(c, u, v, (harness + y) % 4 >= 2);
439 },
440 );
441 /**
442 * Creates an alternating over-under plain weave with rounded threads and seeded fibers.
443 * @param options - Thread geometry, shading, seed, and motion. See {@link FabricOptions}.
444 * @returns A mountable recipe with no message commands. See {@link TextureRecipe}.
445 * @see {@link FabricOptions}
446 */
447 export function plainWeave(options: FabricOptions = {}): TextureRecipe {
448 return plainWeaveRecipe(options);
449 }
450 /**
451 * Creates a two-over, two-under diagonal twill fabric.
452 * @param options - Thread geometry, shading, seed, and motion. See {@link FabricOptions}.
453 * @returns A mountable recipe with no message commands. See {@link TextureRecipe}.
454 * @see {@link FabricOptions}
455 */
456 export function twill(options: FabricOptions = {}): TextureRecipe {
457 return twillRecipe(options);
458 }
459 /**
460 * Creates a reversing twill fabric with repeating herringbone chevrons.
461 * @param options - Thread geometry, shading, seed, and motion. See {@link FabricOptions}.
462 * @returns A mountable recipe with no message commands. See {@link TextureRecipe}.
463 * @see {@link FabricOptions}
464 */
465 export function herringbone(options: FabricOptions = {}): TextureRecipe {
466 return herringboneRecipe(options);
467 }
468
469 /** Seeded seamless noise layers and their tonal response. @see {@link softNoise} */
470 export interface NoiseOptions extends PatternMotionOptions {
471 /** Unsigned 32-bit noise seed; default 42. See {@link NoiseOptions}. */
472 readonly seed?: number;
473 /** Integer base lattice periods per axis, 1–16; default 4. See {@link NoiseOptions}. */
474 readonly frequency?: number;
475 /** Number of doubled-frequency layers, integer 1–6; default 4. See {@link NoiseOptions}. */
476 readonly octaves?: number;
477 /** Relative amplitude of each successive layer, 0–1; default 0.5. See {@link NoiseOptions}. */
478 readonly persistence?: number;
479 /** Tonal contrast about the midpoint, 0–4; default 1. See {@link NoiseOptions}. */
480 readonly contrast?: number;
481 }
482 function noiseConfig(options: NoiseOptions) {
483 return {
484 ...motion(options),
485 seed: validateSeed(options.seed),
486 frequency: bounded("Noise frequency", options.frequency ?? 4, 1, 16, true),
487 octaves: bounded("Noise octaves", options.octaves ?? 4, 1, 6, true),
488 persistence: bounded("Noise persistence", options.persistence ?? 0.5, 0, 1),
489 contrast: bounded("Noise contrast", options.contrast ?? 1, 0, 4),
490 };
491 }
492 function layeredNoise(
493 c: ReturnType<typeof noiseConfig>,
494 u: number,
495 v: number,
496 ridge: boolean,
497 ) {
498 let sum = 0,
499 weight = 0,
500 amplitude = 1,
501 frequency = c.frequency;
502 for (let i = 0; i < c.octaves; i++) {
503 const sample = noise(
504 u,
505 v,
506 frequency,
507 frequency,
508 c.seed ^ Math.imul(i, 0x517cc1b7),
509 );
510 sum += (ridge ? 1 - Math.abs(sample) : 0.5 + sample * 0.5) * amplitude;
511 weight += amplitude;
512 amplitude *= c.persistence;
513 frequency *= 2;
514 }
515 return 0.5 + (sum / weight - 0.5) * c.contrast;
516 }
517 const softNoiseRecipe = /* @__PURE__ */ pattern(noiseConfig, (c, u, v, phase) =>
518 layeredNoise(c, u, wrap(v + phase), false),
519 );
520 const ridgedNoiseRecipe = /* @__PURE__ */ pattern(
521 noiseConfig,
522 (c, u, v, phase) => layeredNoise(c, u, wrap(v + phase), true),
523 );
524 /**
525 * Creates smooth seamless multiscale lattice noise for clouds, pigment, and material variation.
526 * @param options - Seed, lattice frequencies, amplitudes, contrast, and motion. See {@link NoiseOptions}.
527 * @returns A mountable recipe with no message commands. See {@link TextureRecipe}.
528 * @see {@link NoiseOptions}
529 */
530 export function softNoise(options: NoiseOptions = {}): TextureRecipe {
531 return softNoiseRecipe(options);
532 }
533 /**
534 * Creates seamless multiscale ridges by folding each noise layer around its midpoint.
535 * @param options - Seed, lattice frequencies, amplitudes, contrast, and motion. See {@link NoiseOptions}.
536 * @returns A mountable recipe with no message commands. See {@link TextureRecipe}.
537 * @see {@link NoiseOptions}
538 */
539 export function ridgedNoise(options: NoiseOptions = {}): TextureRecipe {
540 return ridgedNoiseRecipe(options);
541 }
542
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.