@xprite/lighter 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,657 @@
1
+ /**
2
+ * Adapted from Pixel Art Lighter v3.5.22 by Red Hat Sprite, MIT.
3
+ * Copyright (c) 2026 Red Hat Sprite. Full notice: LICENSES/pixel-art-lighter-MIT.txt.
4
+ * https://www.moonfell-rpg.com/Pixel-Art-Lighter-v3.5.22.html
5
+ */
6
+ import { assertPixelBuffer } from "./base.js";
7
+ import { CONSTANT_LUMINANCE, LightingMapRegionMode, LUMINANCE_EPSILON, segmentLightingMapSource, } from "./lighting-map-source.js";
8
+ import { estimatePaintedLight } from "./normal-map-light-estimate.js";
9
+ import { paintedLightSignal } from "./normal-map-painted-light.js";
10
+ export var NormalMapPreset;
11
+ (function (NormalMapPreset) {
12
+ NormalMapPreset["Architecture"] = "architecture";
13
+ NormalMapPreset["Character"] = "character";
14
+ NormalMapPreset["Object"] = "object";
15
+ NormalMapPreset["Terrain"] = "terrain";
16
+ })(NormalMapPreset || (NormalMapPreset = {}));
17
+ const PERCENT = 100;
18
+ const BEVEL_POW_SQRT = 0.5;
19
+ const BEVEL_POW_LINEAR = 1;
20
+ const BEVEL_POW_PIVOT = 0.5;
21
+ const DEFAULT_PAINTED_LIGHT_ANGLE = 135;
22
+ const FULL_TURN_DEGREES = 360;
23
+ const RADIANS_PER_DEGREE = Math.PI / 180;
24
+ const PAINTED_LIGHT_TILT_GAIN = 3;
25
+ const ESTIMATE_FADE_LOW = 0.2;
26
+ const ESTIMATE_FADE_HIGH = 0.45;
27
+ const CENTER_SMOOTHING_WEIGHT = 2;
28
+ const AZIMUTH_STEP = Math.PI / 4;
29
+ const FACET_DIRECTION_STEP = Math.PI / 2;
30
+ const FRONT_FACET_KEY = 9;
31
+ const HEIGHT_PROFILES = {
32
+ [NormalMapPreset.Architecture]: { silhouette: 0, cap: 16, luminance: 3.5 },
33
+ [NormalMapPreset.Character]: { silhouette: 0.65, cap: 8, luminance: 1.2 },
34
+ [NormalMapPreset.Object]: { silhouette: 0.65, cap: 16, luminance: 2.1 },
35
+ [NormalMapPreset.Terrain]: { silhouette: 0.12, cap: 16, luminance: 4 },
36
+ };
37
+ const NORMAL_CHANNEL_SCALE = 127.5;
38
+ const OUTLINE_DARKNESS = 0.24;
39
+ const OUTLINE_INTERIOR_RATIO = 0.15;
40
+ const FRONT_FACING_LIMIT = 0.12;
41
+ const TILT_LOW = 0.3;
42
+ const TILT_MEDIUM = 0.6;
43
+ const TILT_HIGH = 0.85;
44
+ const TILT_LEVEL_LOW = 0.24;
45
+ const TILT_LEVEL_MEDIUM = 0.48;
46
+ const TILT_LEVEL_HIGH = 0.72;
47
+ const TILT_LEVEL_MAX = 0.9;
48
+ const ARCHITECTURE_TILT = 0.6;
49
+ const ARCHITECTURE_FLAT_LIMIT = 0.06;
50
+ const ARCHITECTURE_EDGE_TILT = 0.35;
51
+ const ARCHITECTURE_EDGE_MIN_LENGTH = 12;
52
+ const FACET_AREA_BASE = 180;
53
+ const FACET_AREA_SCALE = 1.1;
54
+ const FACET_REFERENCE_SIDE = 64;
55
+ const FACET_MAX_SPRITE_SCALE = 2;
56
+ const FACET_MIN_REGION_AREA = 8;
57
+ const FACET_TILT_LIMIT = 0.35;
58
+ const FACET_MIN_SUPPORT = 2;
59
+ const FACET_SUPPORT_BASE = 1.5;
60
+ const FACET_SUPPORT_RANGE = 0.75;
61
+ const FACET_DOT_LIMIT = 0.7;
62
+ const FACET_DOT_RANGE = 0.1;
63
+ const FACET_DIRECTION_COUNT = 4;
64
+ const DIRECTION_EPSILON = 0.001;
65
+ const SPECKLE_MAX_PIXELS = 2;
66
+ export const NORMAL_MAP_LIMITS = Object.freeze({
67
+ shapeStrength: 200,
68
+ normalStrength: 300,
69
+ smoothing: 6,
70
+ facets: 100,
71
+ paintedLightAngle: FULL_TURN_DEGREES - 1,
72
+ paintedLightInfluence: PERCENT,
73
+ });
74
+ const PRESET_DEFAULTS = {
75
+ [NormalMapPreset.Architecture]: { shapeStrength: 100, smoothing: 1, facets: 20 },
76
+ [NormalMapPreset.Character]: { shapeStrength: 65, smoothing: 2, facets: 15 },
77
+ [NormalMapPreset.Object]: { shapeStrength: 100, smoothing: 3, facets: 35 },
78
+ [NormalMapPreset.Terrain]: { shapeStrength: 110, smoothing: 3, facets: 50 },
79
+ };
80
+ export function defaultNormalMapOptions(preset = NormalMapPreset.Object) {
81
+ return {
82
+ preset,
83
+ ...PRESET_DEFAULTS[preset],
84
+ normalStrength: PERCENT,
85
+ mergeOutlines: true,
86
+ invertY: false,
87
+ paintedLightAngle: DEFAULT_PAINTED_LIGHT_ANGLE,
88
+ paintedLightInfluence: 60,
89
+ };
90
+ }
91
+ export function normalizeNormalMapOptions(input) {
92
+ const preset = Object.values(NormalMapPreset).includes(input.preset)
93
+ ? input.preset
94
+ : NormalMapPreset.Object;
95
+ const result = defaultNormalMapOptions(preset);
96
+ for (const key of Object.keys(NORMAL_MAP_LIMITS)) {
97
+ const value = input[key];
98
+ if (typeof value === "number" && Number.isFinite(value))
99
+ result[key] = Math.round(Math.max(0, Math.min(NORMAL_MAP_LIMITS[key], value)));
100
+ }
101
+ for (const key of ["mergeOutlines", "invertY"])
102
+ if (typeof input[key] === "boolean")
103
+ result[key] = input[key];
104
+ return result;
105
+ }
106
+ /** Cache source segmentation, silhouette distance and geometry between parameter edits. */
107
+ export function createNormalMapGenerator(albedo, shading) {
108
+ const { w, h, N, a, fg, lum, labels, lo, hi, adjacent, queue, clusters, foregroundArea } = segmentLightingMapSource(albedo, LightingMapRegionMode.Perceptual);
109
+ const spriteScale = Math.min(FACET_MAX_SPRITE_SCALE, Math.sqrt(foregroundArea) / FACET_REFERENCE_SIDE);
110
+ const distance = new Float32Array(N);
111
+ distance.fill(N);
112
+ let head = 0, tail = 0;
113
+ for (let i = 0; i < N; i++)
114
+ if (fg[i] &&
115
+ (i % w === 0 || i % w === w - 1 || i < w || i >= N - w || adjacent(i).some((n) => !fg[n]))) {
116
+ distance[i] = 1;
117
+ queue[tail++] = i;
118
+ }
119
+ while (head < tail) {
120
+ const p = queue[head++];
121
+ for (const n of adjacent(p))
122
+ if (fg[n] && distance[n] > distance[p] + 1) {
123
+ distance[n] = distance[p] + 1;
124
+ queue[tail++] = n;
125
+ }
126
+ }
127
+ const range = hi - lo, normalized = (i) => range > LUMINANCE_EPSILON ? (lum[i] - lo) / range : CONSTANT_LUMINANCE;
128
+ const thin = new Uint8Array(N);
129
+ for (const cluster of clusters) {
130
+ if (cluster.value > lo + range * OUTLINE_DARKNESS)
131
+ continue;
132
+ let interior = 0;
133
+ for (const p of cluster.pixels)
134
+ if (adjacent(p).length === 4 && adjacent(p).every((n) => labels[n] === labels[p]))
135
+ interior++;
136
+ if (interior / cluster.pixels.length < OUTLINE_INTERIOR_RATIO)
137
+ for (const p of cluster.pixels)
138
+ thin[p] = 1;
139
+ }
140
+ let cachedFieldKey = "";
141
+ let cachedField = null;
142
+ let cachedKey = "";
143
+ let cachedDirections = null;
144
+ let shadingSource;
145
+ let lightSignal;
146
+ let paintedEstimate;
147
+ const estimatePainted = () => {
148
+ if (paintedEstimate === undefined)
149
+ paintedEstimate = estimatePaintedLight({ width: w, height: h, data: a }, shadingSource);
150
+ return paintedEstimate;
151
+ };
152
+ const setShading = (source) => {
153
+ if (source) {
154
+ assertPixelBuffer(source);
155
+ if (source.width !== w || source.height !== h)
156
+ throw new RangeError("Shading source must match the sprite dimensions");
157
+ }
158
+ shadingSource = source ? { ...source, data: source.data.slice() } : undefined;
159
+ lightSignal = undefined;
160
+ paintedEstimate = undefined;
161
+ cachedKey = "";
162
+ };
163
+ if (shading)
164
+ setShading(shading);
165
+ return {
166
+ setShading,
167
+ suggestPaintedLightAngle() {
168
+ return estimatePainted()?.angle ?? null;
169
+ },
170
+ generate(input = {}) {
171
+ const options = normalizeNormalMapOptions(input);
172
+ const experimental = input.experimental ?? {};
173
+ let influence = options.paintedLightInfluence / PERCENT;
174
+ let angleDeg = options.paintedLightAngle;
175
+ if (influence > 0 && input.paintedLightAngle === undefined) {
176
+ const estimate = estimatePainted();
177
+ if (estimate) {
178
+ angleDeg = estimate.angle;
179
+ influence *= Math.min(1, Math.max(0, (estimate.fit - ESTIMATE_FADE_LOW) / (ESTIMATE_FADE_HIGH - ESTIMATE_FADE_LOW)));
180
+ }
181
+ else
182
+ influence = 0;
183
+ }
184
+ const key = JSON.stringify([
185
+ options.preset,
186
+ options.shapeStrength,
187
+ options.smoothing,
188
+ options.facets,
189
+ options.mergeOutlines,
190
+ influence,
191
+ influence ? angleDeg : 0,
192
+ ]);
193
+ let directions = cachedDirections;
194
+ if (!directions || cachedKey !== key) {
195
+ const preset = options.preset;
196
+ const profile = HEIGHT_PROFILES[preset];
197
+ const scale = options.shapeStrength / PERCENT;
198
+ const fieldKey = JSON.stringify([preset, options.smoothing, influence, experimental]);
199
+ let field = cachedField;
200
+ if (!field || cachedFieldKey !== fieldKey) {
201
+ const distField = experimental.chamferDistance
202
+ ? chamferDistance(fg, w, h)
203
+ : distance;
204
+ const groove = experimental.edgeGroove ?? 0;
205
+ const edgeDist = groove > 0 ? colorEdgeDistance(a, fg, w, h) : null;
206
+ // silhouette ramp exponent scales from the small-sprite sqrt profile to a
207
+ // linear ramp once the sprite is large enough for facets to stay accurate
208
+ const pow = experimental.bevelPow ??
209
+ Math.min(BEVEL_POW_LINEAR, Math.max(BEVEL_POW_SQRT, BEVEL_POW_SQRT + (spriteScale - BEVEL_POW_PIVOT) * 0.5));
210
+ const mid = experimental.midLum ? (lo + hi) / 2 : null;
211
+ const lumTerm = experimental.oklab ? new Float32Array(N) : null;
212
+ if (lumTerm)
213
+ for (let i = 0; i < N; i++)
214
+ lumTerm[i] = fg[i]
215
+ ? oklabLightness(a[i * 4], a[i * 4 + 1], a[i * 4 + 2])
216
+ : 0;
217
+ let nextField = new Float32Array(N);
218
+ for (let i = 0; i < N; i++)
219
+ if (fg[i]) {
220
+ const convex = Math.pow(Math.min(distField[i], profile.cap) / profile.cap, pow) *
221
+ profile.silhouette * Math.sqrt(profile.cap);
222
+ const lumPart = lumTerm
223
+ ? lumTerm[i] * profile.luminance * (1 - influence)
224
+ : mid !== null
225
+ ? (lum[i] - mid) * profile.luminance * (1 - influence)
226
+ : normalized(i) * profile.luminance * (1 - influence);
227
+ const dip = edgeDist ? groove * Math.min(1, edgeDist[i] / 2) : 0;
228
+ nextField[i] = convex + lumPart + dip;
229
+ }
230
+ for (let pass = 0; pass < options.smoothing; pass++) {
231
+ let blurred;
232
+ if (experimental.maskedBlur) {
233
+ blurred = separableMaskedBlur(nextField, fg, w, h);
234
+ }
235
+ else {
236
+ blurred = new Float32Array(N);
237
+ for (let i = 0; i < N; i++)
238
+ if (fg[i]) {
239
+ let sum = nextField[i] * CENTER_SMOOTHING_WEIGHT, count = CENTER_SMOOTHING_WEIGHT;
240
+ for (const n of adjacent(i))
241
+ if (fg[n]) {
242
+ sum += nextField[n];
243
+ count++;
244
+ }
245
+ blurred[i] = sum / count;
246
+ }
247
+ }
248
+ nextField = blurred;
249
+ }
250
+ cachedFieldKey = fieldKey;
251
+ field = cachedField = nextField;
252
+ }
253
+ const dirs = new Float32Array(N * 3);
254
+ const unit = (v) => {
255
+ const len = Math.hypot(...v) || 1;
256
+ return v.map((n) => n / len);
257
+ };
258
+ const quantize = (v) => {
259
+ v = unit(v);
260
+ const tilt = Math.hypot(v[0], v[1]);
261
+ if (tilt < FRONT_FACING_LIMIT)
262
+ return [0, 0, 1];
263
+ const angle = Math.round(Math.atan2(v[1], v[0]) / AZIMUTH_STEP) * AZIMUTH_STEP;
264
+ const elevation = preset === NormalMapPreset.Architecture
265
+ ? Math.min(TILT_LEVEL_MAX, ARCHITECTURE_TILT * scale)
266
+ : tilt < TILT_LOW
267
+ ? TILT_LEVEL_LOW
268
+ : tilt < TILT_MEDIUM
269
+ ? TILT_LEVEL_MEDIUM
270
+ : tilt < TILT_HIGH
271
+ ? TILT_LEVEL_HIGH
272
+ : TILT_LEVEL_MAX;
273
+ return [
274
+ Math.cos(angle) * elevation,
275
+ Math.sin(angle) * elevation,
276
+ Math.sqrt(1 - elevation * elevation),
277
+ ];
278
+ };
279
+ const heightField = field;
280
+ if (influence)
281
+ lightSignal ??= paintedLightSignal(w, h, fg, foregroundArea, lum, shadingSource);
282
+ const angle = angleDeg * RADIANS_PER_DEGREE;
283
+ const lightX = Math.cos(angle) * influence * PAINTED_LIGHT_TILT_GAIN;
284
+ const lightY = Math.sin(angle) * influence * PAINTED_LIGHT_TILT_GAIN;
285
+ const normalAt = (pixel) => {
286
+ const x = pixel % w;
287
+ const y = (pixel / w) | 0;
288
+ const center = heightField[pixel];
289
+ const at = (neighbor) => (fg[neighbor] ? heightField[neighbor] : center);
290
+ const dx = (x < w - 1 ? at(pixel + 1) : center) - (x ? at(pixel - 1) : center);
291
+ const dy = (y < h - 1 ? at(pixel + w) : center) - (y ? at(pixel - w) : center);
292
+ if (!influence)
293
+ return unit([-dx * scale, dy * scale, 1]);
294
+ const tilt = lightSignal[pixel];
295
+ return unit([-dx * scale + lightX * tilt, dy * scale + lightY * tilt, 1]);
296
+ };
297
+ for (let i = 0; i < N; i++)
298
+ if (fg[i])
299
+ dirs.set(normalAt(i), i * 3);
300
+ const facetStrength = options.facets / PERCENT;
301
+ // Size eligibility by the occupied footprint, then size each candidate by its own region.
302
+ const minFacetArea = Math.max(FACET_MIN_REGION_AREA, Math.round((FACET_AREA_BASE - options.facets * FACET_AREA_SCALE) * spriteScale));
303
+ const facetSupportFactor = FACET_SUPPORT_BASE - facetStrength * FACET_SUPPORT_RANGE;
304
+ const facetDotLimit = FACET_DOT_LIMIT + facetStrength * FACET_DOT_RANGE;
305
+ for (const cluster of clusters) {
306
+ let sum = [0, 0, 0];
307
+ for (const p of cluster.pixels) {
308
+ if (preset === NormalMapPreset.Architecture &&
309
+ Math.hypot(dirs[p * 3], dirs[p * 3 + 1]) < ARCHITECTURE_FLAT_LIMIT)
310
+ continue;
311
+ for (let c = 0; c < 3; c++)
312
+ sum[c] += dirs[p * 3 + c];
313
+ }
314
+ if (sum[2] === 0)
315
+ sum = [0, 0, 1];
316
+ const average = unit(sum), groups = new Map();
317
+ const split = options.facets > 0 && cluster.pixels.length >= minFacetArea;
318
+ if (split) {
319
+ for (const p of cluster.pixels) {
320
+ const dx = dirs[p * 3], dy = dirs[p * 3 + 1], tilt = Math.hypot(dx, dy);
321
+ const key = tilt > FACET_TILT_LIMIT
322
+ ? (Math.round(Math.atan2(dy, dx) / FACET_DIRECTION_STEP) +
323
+ FACET_DIRECTION_COUNT) %
324
+ FACET_DIRECTION_COUNT
325
+ : FRONT_FACET_KEY;
326
+ if (!groups.has(key))
327
+ groups.set(key, []);
328
+ groups.get(key).push(p);
329
+ }
330
+ }
331
+ const minSupport = Math.max(FACET_MIN_SUPPORT, Math.ceil(Math.sqrt(cluster.pixels.length) * facetSupportFactor));
332
+ const supported = [...groups.values()].filter((group) => group.length >= minSupport);
333
+ let allow = false;
334
+ if (supported.length >= 2) {
335
+ const means = supported.map((g) => {
336
+ const s = [0, 0, 0];
337
+ for (const p of g)
338
+ for (let c = 0; c < 3; c++)
339
+ s[c] += dirs[p * 3 + c];
340
+ return unit(s);
341
+ });
342
+ for (let i = 0; i < means.length; i++)
343
+ for (let j = 0; j < i; j++)
344
+ if (means[i].reduce((s, v, c) => s + v * means[j][c], 0) < facetDotLimit)
345
+ allow = true;
346
+ }
347
+ const base = quantize(average);
348
+ for (const p of cluster.pixels)
349
+ dirs.set(base, p * 3);
350
+ if (allow)
351
+ for (const g of supported) {
352
+ const sum = [0, 0, 0];
353
+ for (const p of g) {
354
+ const v = normalAt(p);
355
+ for (let c = 0; c < 3; c++)
356
+ sum[c] += v[c];
357
+ }
358
+ const v = quantize(sum);
359
+ for (const p of g)
360
+ dirs.set(v, p * 3);
361
+ }
362
+ }
363
+ if (options.mergeOutlines) {
364
+ const assigned = new Uint8Array(N);
365
+ head = 0;
366
+ tail = 0;
367
+ for (let i = 0; i < N; i++)
368
+ if (fg[i] && !thin[i]) {
369
+ assigned[i] = 1;
370
+ queue[tail++] = i;
371
+ }
372
+ while (head < tail) {
373
+ const p = queue[head++];
374
+ for (const n of adjacent(p))
375
+ if (fg[n] && !assigned[n]) {
376
+ assigned[n] = 1;
377
+ dirs.set(dirs.subarray(p * 3, p * 3 + 3), n * 3);
378
+ queue[tail++] = n;
379
+ }
380
+ }
381
+ }
382
+ const seen = new Uint8Array(N);
383
+ for (let i = 0; i < N; i++)
384
+ if (fg[i] && !seen[i]) {
385
+ const group = [];
386
+ head = 0;
387
+ tail = 1;
388
+ queue[0] = i;
389
+ seen[i] = 1;
390
+ while (head < tail) {
391
+ const p = queue[head++];
392
+ group.push(p);
393
+ for (const n of adjacent(p))
394
+ if (labels[n] === labels[i] &&
395
+ !seen[n] &&
396
+ Math.abs(dirs[n * 3] - dirs[i * 3]) < DIRECTION_EPSILON &&
397
+ Math.abs(dirs[n * 3 + 1] - dirs[i * 3 + 1]) < DIRECTION_EPSILON) {
398
+ seen[n] = 1;
399
+ queue[tail++] = n;
400
+ }
401
+ }
402
+ if (group.length <= SPECKLE_MAX_PIXELS) {
403
+ const neighbors = group
404
+ .flatMap(adjacent)
405
+ .filter((n) => labels[n] === labels[i] && !group.includes(n));
406
+ if (neighbors.length) {
407
+ const n = neighbors[0];
408
+ for (const p of group)
409
+ dirs.set(dirs.subarray(n * 3, n * 3 + 3), p * 3);
410
+ }
411
+ }
412
+ }
413
+ if (preset === NormalMapPreset.Architecture && scale > 0)
414
+ alignStraightArchitectureEdges(dirs, fg, w, h, spriteScale, scale);
415
+ cachedKey = key;
416
+ directions = cachedDirections = dirs;
417
+ }
418
+ const output = new Uint8ClampedArray(N * 4);
419
+ const gain = options.normalStrength / PERCENT;
420
+ const ySign = options.invertY ? -1 : 1;
421
+ for (let i = 0; i < N; i++) {
422
+ const vector = i * 3, at = i * 4;
423
+ const x = fg[i] ? directions[vector] * gain : 0;
424
+ const y = fg[i] ? directions[vector + 1] * gain : 0;
425
+ const z = fg[i] ? directions[vector + 2] : 1;
426
+ const length = Math.sqrt(x * x + y * y + z * z) || 1;
427
+ output[at] = Math.round((x / length + 1) * NORMAL_CHANNEL_SCALE);
428
+ output[at + 1] = Math.round(((y / length) * ySign + 1) * NORMAL_CHANNEL_SCALE);
429
+ output[at + 2] = Math.round((z / length + 1) * NORMAL_CHANNEL_SCALE);
430
+ output[at + 3] = a[at + 3];
431
+ }
432
+ return { width: w, height: h, data: output };
433
+ },
434
+ };
435
+ }
436
+ export function generateNormalMap(albedo, input = {}) {
437
+ return createNormalMapGenerator(albedo).generate(input);
438
+ }
439
+ // A straight exterior edge is a stronger geometry cue than the colors of individual bricks.
440
+ function alignStraightArchitectureEdges(directions, foreground, width, height, spriteScale, strength) {
441
+ const depth = Math.max(1, Math.round(spriteScale * 2));
442
+ const minLength = Math.max(ARCHITECTURE_EDGE_MIN_LENGTH, depth * 4);
443
+ const distance = new Uint8Array(foreground.length).fill(depth);
444
+ const edgeX = new Int8Array(foreground.length);
445
+ const edgeY = new Int8Array(foreground.length);
446
+ for (const horizontal of [true, false]) {
447
+ const [lineCount, lineLength] = horizontal ? [height, width] : [width, height];
448
+ const [lineStride, pixelStride] = horizontal ? [width, 1] : [1, width];
449
+ for (const side of [-1, 1]) {
450
+ for (let line = 0; line < lineCount; line++) {
451
+ const start = line * lineStride;
452
+ const outside = line + side < 0 || line + side >= lineCount;
453
+ let runStart = 0;
454
+ for (let offset = 0; offset <= lineLength; offset++) {
455
+ const pixel = start + offset * pixelStride;
456
+ if (offset < lineLength &&
457
+ foreground[pixel] &&
458
+ (outside || !foreground[pixel + side * lineStride]))
459
+ continue;
460
+ if (offset - runStart >= minLength) {
461
+ for (let along = runStart; along < offset; along++) {
462
+ for (let step = 0; step < depth; step++) {
463
+ const inside = line - step * side;
464
+ const p = inside * lineStride + along * pixelStride;
465
+ if (inside < 0 || inside >= lineCount || !foreground[p])
466
+ break;
467
+ if (step > distance[p])
468
+ continue;
469
+ if (step < distance[p]) {
470
+ distance[p] = step;
471
+ edgeX[p] = edgeY[p] = 0;
472
+ }
473
+ if (horizontal)
474
+ edgeY[p] -= side;
475
+ else
476
+ edgeX[p] += side;
477
+ }
478
+ }
479
+ }
480
+ runStart = offset + 1;
481
+ }
482
+ }
483
+ }
484
+ }
485
+ for (let p = 0; p < foreground.length; p++) {
486
+ const length = Math.hypot(edgeX[p], edgeY[p]);
487
+ if (!length)
488
+ continue;
489
+ const tilt = ARCHITECTURE_EDGE_TILT * strength * (1 - distance[p] / depth);
490
+ directions[p * 3] = (edgeX[p] * tilt) / length;
491
+ directions[p * 3 + 1] = (edgeY[p] * tilt) / length;
492
+ directions[p * 3 + 2] = Math.sqrt(1 - tilt * tilt);
493
+ }
494
+ }
495
+ function colorEdgeDistance(a, fg, w, h) {
496
+ const seeds = new Uint8Array(w * h);
497
+ for (let y = 0; y < h; y++)
498
+ for (let x = 0; x < w; x++) {
499
+ const i = y * w + x;
500
+ if (!fg[i])
501
+ continue;
502
+ const o = i * 4;
503
+ if (x < w - 1 && fg[i + 1]) {
504
+ const j = o + 4;
505
+ if (a[o] !== a[j] || a[o + 1] !== a[j + 1] || a[o + 2] !== a[j + 2]) {
506
+ seeds[i] = 1;
507
+ seeds[i + 1] = 1;
508
+ }
509
+ }
510
+ if (y < h - 1 && fg[i + w]) {
511
+ const j = o + w * 4;
512
+ if (a[o] !== a[j] || a[o + 1] !== a[j + 1] || a[o + 2] !== a[j + 2]) {
513
+ seeds[i] = 1;
514
+ seeds[i + w] = 1;
515
+ }
516
+ }
517
+ }
518
+ const INF = 1e9, d = new Float32Array(w * h);
519
+ for (let i = 0; i < w * h; i++)
520
+ d[i] = seeds[i] ? 0 : INF;
521
+ for (let y = 0; y < h; y++)
522
+ for (let x = 0; x < w; x++) {
523
+ const i = y * w + x;
524
+ let v = d[i];
525
+ if (v === 0)
526
+ continue;
527
+ if (x > 0)
528
+ v = Math.min(v, d[i - 1] + 3);
529
+ if (y > 0) {
530
+ v = Math.min(v, d[i - w] + 3);
531
+ if (x > 0)
532
+ v = Math.min(v, d[i - w - 1] + 4);
533
+ if (x < w - 1)
534
+ v = Math.min(v, d[i - w + 1] + 4);
535
+ }
536
+ d[i] = v;
537
+ }
538
+ for (let y = h - 1; y >= 0; y--)
539
+ for (let x = w - 1; x >= 0; x--) {
540
+ const i = y * w + x;
541
+ let v = d[i];
542
+ if (v === 0)
543
+ continue;
544
+ if (x < w - 1)
545
+ v = Math.min(v, d[i + 1] + 3);
546
+ if (y < h - 1) {
547
+ v = Math.min(v, d[i + w] + 3);
548
+ if (x < w - 1)
549
+ v = Math.min(v, d[i + w + 1] + 4);
550
+ if (x > 0)
551
+ v = Math.min(v, d[i + w - 1] + 4);
552
+ }
553
+ d[i] = v;
554
+ }
555
+ for (let i = 0; i < w * h; i++)
556
+ if (d[i] < INF)
557
+ d[i] /= 3;
558
+ return d;
559
+ }
560
+ function chamferDistance(fg, w, h) {
561
+ const INF = 1e9;
562
+ const d = new Float32Array(w * h);
563
+ for (let i = 0; i < w * h; i++)
564
+ d[i] = fg[i] ? INF : 0;
565
+ const C1 = 3, C2 = 4;
566
+ for (let y = 0; y < h; y++)
567
+ for (let x = 0; x < w; x++) {
568
+ const i = y * w + x;
569
+ let v = d[i];
570
+ if (v === 0)
571
+ continue;
572
+ if (x > 0)
573
+ v = Math.min(v, d[i - 1] + C1);
574
+ if (y > 0) {
575
+ v = Math.min(v, d[i - w] + C1);
576
+ if (x > 0)
577
+ v = Math.min(v, d[i - w - 1] + C2);
578
+ if (x < w - 1)
579
+ v = Math.min(v, d[i - w + 1] + C2);
580
+ }
581
+ d[i] = v;
582
+ }
583
+ for (let y = h - 1; y >= 0; y--)
584
+ for (let x = w - 1; x >= 0; x--) {
585
+ const i = y * w + x;
586
+ let v = d[i];
587
+ if (v === 0)
588
+ continue;
589
+ if (x < w - 1)
590
+ v = Math.min(v, d[i + 1] + C1);
591
+ if (y < h - 1) {
592
+ v = Math.min(v, d[i + w] + C1);
593
+ if (x < w - 1)
594
+ v = Math.min(v, d[i + w + 1] + C2);
595
+ if (x > 0)
596
+ v = Math.min(v, d[i + w - 1] + C2);
597
+ }
598
+ d[i] = v;
599
+ }
600
+ for (let i = 0; i < w * h; i++)
601
+ if (d[i] < INF)
602
+ d[i] /= 3;
603
+ return d;
604
+ }
605
+ function separableMaskedBlur(field, mask, w, h) {
606
+ const masked = new Float32Array(w * h);
607
+ for (let i = 0; i < w * h; i++)
608
+ masked[i] = field[i] * mask[i];
609
+ const m = Float32Array.from(mask);
610
+ const blur1d = (src, wgt, alongX) => {
611
+ const out = new Float32Array(w * h);
612
+ const outW = new Float32Array(w * h);
613
+ const limit = alongX ? w : h;
614
+ const stride = alongX ? 1 : w;
615
+ const radius = 1;
616
+ for (let line = 0; line < (alongX ? h : w); line++) {
617
+ const base = alongX ? line * w : line;
618
+ for (let i = 0; i < limit; i++) {
619
+ const i0 = Math.max(0, i - radius);
620
+ const i1 = Math.min(limit, i + radius + 1);
621
+ let s = 0, sw = 0;
622
+ for (let k = i0; k < i1; k++) {
623
+ s += src[base + k * stride];
624
+ sw += wgt[base + k * stride];
625
+ }
626
+ out[base + i * stride] = s;
627
+ outW[base + i * stride] = sw;
628
+ }
629
+ }
630
+ return { out, outW };
631
+ };
632
+ const r1 = blur1d(masked, m, true);
633
+ const num = new Float32Array(w * h);
634
+ const den = new Float32Array(w * h);
635
+ for (let x = 0; x < w; x++)
636
+ for (let y = 0; y < h; y++) {
637
+ const i = y * w + x;
638
+ num[i] = r1.out[i];
639
+ den[i] = r1.outW[i];
640
+ }
641
+ const r2 = blur1d(num, den, false);
642
+ const out = new Float32Array(w * h);
643
+ for (let i = 0; i < w * h; i++)
644
+ out[i] = r2.outW[i] > 1e-6 ? r2.out[i] / r2.outW[i] : field[i];
645
+ return out;
646
+ }
647
+ function oklabLightness(r, g, b) {
648
+ const lin = (c) => {
649
+ const x = c / 255;
650
+ return x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
651
+ };
652
+ const lr = lin(r), lg = lin(g), lb = lin(b);
653
+ const l = Math.cbrt(0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb);
654
+ const m = Math.cbrt(0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb);
655
+ const s = Math.cbrt(0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb);
656
+ return 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;
657
+ }