@xprite/lighter 0.0.0-stage → 0.1.0

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,597 @@
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 FACET_AREA_BASE = 180;
51
+ const FACET_AREA_SCALE = 1.1;
52
+ const FACET_REFERENCE_SIDE = 64;
53
+ const FACET_MAX_SPRITE_SCALE = 2;
54
+ const FACET_MIN_REGION_AREA = 8;
55
+ const FACET_TILT_LIMIT = 0.35;
56
+ const FACET_MIN_SUPPORT = 2;
57
+ const FACET_SUPPORT_BASE = 1.5;
58
+ const FACET_SUPPORT_RANGE = 0.75;
59
+ const FACET_DOT_LIMIT = 0.7;
60
+ const FACET_DOT_RANGE = 0.1;
61
+ const FACET_DIRECTION_COUNT = 4;
62
+ const DIRECTION_EPSILON = 0.001;
63
+ const SPECKLE_MAX_PIXELS = 2;
64
+ export const NORMAL_MAP_LIMITS = Object.freeze({
65
+ shapeStrength: 200,
66
+ normalStrength: 300,
67
+ smoothing: 6,
68
+ facets: 100,
69
+ paintedLightAngle: FULL_TURN_DEGREES - 1,
70
+ paintedLightInfluence: PERCENT,
71
+ });
72
+ const PRESET_DEFAULTS = {
73
+ [NormalMapPreset.Architecture]: { shapeStrength: 100, smoothing: 1, facets: 20 },
74
+ [NormalMapPreset.Character]: { shapeStrength: 65, smoothing: 2, facets: 15 },
75
+ [NormalMapPreset.Object]: { shapeStrength: 100, smoothing: 3, facets: 35 },
76
+ [NormalMapPreset.Terrain]: { shapeStrength: 110, smoothing: 3, facets: 50 },
77
+ };
78
+ export function defaultNormalMapOptions(preset = NormalMapPreset.Object) {
79
+ return {
80
+ preset,
81
+ ...PRESET_DEFAULTS[preset],
82
+ normalStrength: PERCENT,
83
+ mergeOutlines: true,
84
+ invertY: false,
85
+ paintedLightAngle: DEFAULT_PAINTED_LIGHT_ANGLE,
86
+ paintedLightInfluence: 60,
87
+ };
88
+ }
89
+ export function normalizeNormalMapOptions(input) {
90
+ const preset = Object.values(NormalMapPreset).includes(input.preset)
91
+ ? input.preset
92
+ : NormalMapPreset.Object;
93
+ const result = defaultNormalMapOptions(preset);
94
+ for (const key of Object.keys(NORMAL_MAP_LIMITS)) {
95
+ const value = input[key];
96
+ if (typeof value === "number" && Number.isFinite(value))
97
+ result[key] = Math.round(Math.max(0, Math.min(NORMAL_MAP_LIMITS[key], value)));
98
+ }
99
+ for (const key of ["mergeOutlines", "invertY"])
100
+ if (typeof input[key] === "boolean")
101
+ result[key] = input[key];
102
+ return result;
103
+ }
104
+ /** Cache source segmentation, silhouette distance and geometry between parameter edits. */
105
+ export function createNormalMapGenerator(albedo, shading) {
106
+ const { w, h, N, a, fg, lum, labels, lo, hi, adjacent, queue, clusters, foregroundArea } = segmentLightingMapSource(albedo, LightingMapRegionMode.Perceptual);
107
+ const spriteScale = Math.min(FACET_MAX_SPRITE_SCALE, Math.sqrt(foregroundArea) / FACET_REFERENCE_SIDE);
108
+ const distance = new Float32Array(N);
109
+ distance.fill(N);
110
+ let head = 0, tail = 0;
111
+ for (let i = 0; i < N; i++)
112
+ if (fg[i] &&
113
+ (i % w === 0 || i % w === w - 1 || i < w || i >= N - w || adjacent(i).some((n) => !fg[n]))) {
114
+ distance[i] = 1;
115
+ queue[tail++] = i;
116
+ }
117
+ while (head < tail) {
118
+ const p = queue[head++];
119
+ for (const n of adjacent(p))
120
+ if (fg[n] && distance[n] > distance[p] + 1) {
121
+ distance[n] = distance[p] + 1;
122
+ queue[tail++] = n;
123
+ }
124
+ }
125
+ const range = hi - lo, normalized = (i) => range > LUMINANCE_EPSILON ? (lum[i] - lo) / range : CONSTANT_LUMINANCE;
126
+ const thin = new Uint8Array(N);
127
+ for (const cluster of clusters) {
128
+ if (cluster.value > lo + range * OUTLINE_DARKNESS)
129
+ continue;
130
+ let interior = 0;
131
+ for (const p of cluster.pixels)
132
+ if (adjacent(p).length === 4 && adjacent(p).every((n) => labels[n] === labels[p]))
133
+ interior++;
134
+ if (interior / cluster.pixels.length < OUTLINE_INTERIOR_RATIO)
135
+ for (const p of cluster.pixels)
136
+ thin[p] = 1;
137
+ }
138
+ let cachedFieldKey = "";
139
+ let cachedField = null;
140
+ let cachedKey = "";
141
+ let cachedDirections = null;
142
+ let shadingSource;
143
+ let lightSignal;
144
+ let paintedEstimate;
145
+ const estimatePainted = () => {
146
+ if (paintedEstimate === undefined)
147
+ paintedEstimate = estimatePaintedLight({ width: w, height: h, data: a }, shadingSource);
148
+ return paintedEstimate;
149
+ };
150
+ const setShading = (source) => {
151
+ if (source) {
152
+ assertPixelBuffer(source);
153
+ if (source.width !== w || source.height !== h)
154
+ throw new RangeError("Shading source must match the sprite dimensions");
155
+ }
156
+ shadingSource = source ? { ...source, data: source.data.slice() } : undefined;
157
+ lightSignal = undefined;
158
+ paintedEstimate = undefined;
159
+ cachedKey = "";
160
+ };
161
+ if (shading)
162
+ setShading(shading);
163
+ return {
164
+ setShading,
165
+ suggestPaintedLightAngle() {
166
+ return estimatePainted()?.angle ?? null;
167
+ },
168
+ generate(input = {}) {
169
+ const options = normalizeNormalMapOptions(input);
170
+ const experimental = input.experimental ?? {};
171
+ let influence = options.paintedLightInfluence / PERCENT;
172
+ let angleDeg = options.paintedLightAngle;
173
+ if (influence > 0 && input.paintedLightAngle === undefined) {
174
+ const estimate = estimatePainted();
175
+ if (estimate) {
176
+ angleDeg = estimate.angle;
177
+ influence *= Math.min(1, Math.max(0, (estimate.fit - ESTIMATE_FADE_LOW) / (ESTIMATE_FADE_HIGH - ESTIMATE_FADE_LOW)));
178
+ }
179
+ else
180
+ influence = 0;
181
+ }
182
+ const key = JSON.stringify([
183
+ options.preset,
184
+ options.shapeStrength,
185
+ options.smoothing,
186
+ options.facets,
187
+ options.mergeOutlines,
188
+ influence,
189
+ influence ? angleDeg : 0,
190
+ ]);
191
+ let directions = cachedDirections;
192
+ if (!directions || cachedKey !== key) {
193
+ const preset = options.preset;
194
+ const profile = HEIGHT_PROFILES[preset];
195
+ const scale = options.shapeStrength / PERCENT;
196
+ const fieldKey = JSON.stringify([preset, options.smoothing, influence, experimental]);
197
+ let field = cachedField;
198
+ if (!field || cachedFieldKey !== fieldKey) {
199
+ const distField = experimental.chamferDistance
200
+ ? chamferDistance(fg, w, h)
201
+ : distance;
202
+ const groove = experimental.edgeGroove ?? 0;
203
+ const edgeDist = groove > 0 ? colorEdgeDistance(a, fg, w, h) : null;
204
+ // silhouette ramp exponent scales from the small-sprite sqrt profile to a
205
+ // linear ramp once the sprite is large enough for facets to stay accurate
206
+ const pow = experimental.bevelPow ??
207
+ Math.min(BEVEL_POW_LINEAR, Math.max(BEVEL_POW_SQRT, BEVEL_POW_SQRT + (spriteScale - BEVEL_POW_PIVOT) * 0.5));
208
+ const mid = experimental.midLum ? (lo + hi) / 2 : null;
209
+ const lumTerm = experimental.oklab ? new Float32Array(N) : null;
210
+ if (lumTerm)
211
+ for (let i = 0; i < N; i++)
212
+ lumTerm[i] = fg[i]
213
+ ? oklabLightness(a[i * 4], a[i * 4 + 1], a[i * 4 + 2])
214
+ : 0;
215
+ let nextField = new Float32Array(N);
216
+ for (let i = 0; i < N; i++)
217
+ if (fg[i]) {
218
+ const convex = Math.pow(Math.min(distField[i], profile.cap) / profile.cap, pow) *
219
+ profile.silhouette * Math.sqrt(profile.cap);
220
+ const lumPart = lumTerm
221
+ ? lumTerm[i] * profile.luminance * (1 - influence)
222
+ : mid !== null
223
+ ? (lum[i] - mid) * profile.luminance * (1 - influence)
224
+ : normalized(i) * profile.luminance * (1 - influence);
225
+ const dip = edgeDist ? groove * Math.min(1, edgeDist[i] / 2) : 0;
226
+ nextField[i] = convex + lumPart + dip;
227
+ }
228
+ for (let pass = 0; pass < options.smoothing; pass++) {
229
+ let blurred;
230
+ if (experimental.maskedBlur) {
231
+ blurred = separableMaskedBlur(nextField, fg, w, h);
232
+ }
233
+ else {
234
+ blurred = new Float32Array(N);
235
+ for (let i = 0; i < N; i++)
236
+ if (fg[i]) {
237
+ let sum = nextField[i] * CENTER_SMOOTHING_WEIGHT, count = CENTER_SMOOTHING_WEIGHT;
238
+ for (const n of adjacent(i))
239
+ if (fg[n]) {
240
+ sum += nextField[n];
241
+ count++;
242
+ }
243
+ blurred[i] = sum / count;
244
+ }
245
+ }
246
+ nextField = blurred;
247
+ }
248
+ cachedFieldKey = fieldKey;
249
+ field = cachedField = nextField;
250
+ }
251
+ const dirs = new Float32Array(N * 3);
252
+ const unit = (v) => {
253
+ const len = Math.hypot(...v) || 1;
254
+ return v.map((n) => n / len);
255
+ };
256
+ const quantize = (v) => {
257
+ v = unit(v);
258
+ const tilt = Math.hypot(v[0], v[1]);
259
+ if (tilt < FRONT_FACING_LIMIT)
260
+ return [0, 0, 1];
261
+ const angle = Math.round(Math.atan2(v[1], v[0]) / AZIMUTH_STEP) * AZIMUTH_STEP;
262
+ const elevation = preset === NormalMapPreset.Architecture
263
+ ? Math.min(TILT_LEVEL_MAX, ARCHITECTURE_TILT * scale)
264
+ : tilt < TILT_LOW
265
+ ? TILT_LEVEL_LOW
266
+ : tilt < TILT_MEDIUM
267
+ ? TILT_LEVEL_MEDIUM
268
+ : tilt < TILT_HIGH
269
+ ? TILT_LEVEL_HIGH
270
+ : TILT_LEVEL_MAX;
271
+ return [
272
+ Math.cos(angle) * elevation,
273
+ Math.sin(angle) * elevation,
274
+ Math.sqrt(1 - elevation * elevation),
275
+ ];
276
+ };
277
+ const heightField = field;
278
+ if (influence)
279
+ lightSignal ??= paintedLightSignal(w, h, fg, foregroundArea, lum, shadingSource);
280
+ const angle = angleDeg * RADIANS_PER_DEGREE;
281
+ const lightX = Math.cos(angle) * influence * PAINTED_LIGHT_TILT_GAIN;
282
+ const lightY = Math.sin(angle) * influence * PAINTED_LIGHT_TILT_GAIN;
283
+ const normalAt = (pixel) => {
284
+ const x = pixel % w;
285
+ const y = (pixel / w) | 0;
286
+ const center = heightField[pixel];
287
+ const at = (neighbor) => (fg[neighbor] ? heightField[neighbor] : center);
288
+ const dx = (x < w - 1 ? at(pixel + 1) : center) - (x ? at(pixel - 1) : center);
289
+ const dy = (y < h - 1 ? at(pixel + w) : center) - (y ? at(pixel - w) : center);
290
+ if (!influence)
291
+ return unit([-dx * scale, dy * scale, 1]);
292
+ const tilt = lightSignal[pixel];
293
+ return unit([-dx * scale + lightX * tilt, dy * scale + lightY * tilt, 1]);
294
+ };
295
+ for (let i = 0; i < N; i++)
296
+ if (fg[i])
297
+ dirs.set(normalAt(i), i * 3);
298
+ const facetStrength = options.facets / PERCENT;
299
+ // Size eligibility by the occupied footprint, then size each candidate by its own region.
300
+ const minFacetArea = Math.max(FACET_MIN_REGION_AREA, Math.round((FACET_AREA_BASE - options.facets * FACET_AREA_SCALE) * spriteScale));
301
+ const facetSupportFactor = FACET_SUPPORT_BASE - facetStrength * FACET_SUPPORT_RANGE;
302
+ const facetDotLimit = FACET_DOT_LIMIT + facetStrength * FACET_DOT_RANGE;
303
+ for (const cluster of clusters) {
304
+ let sum = [0, 0, 0];
305
+ for (const p of cluster.pixels) {
306
+ if (preset === NormalMapPreset.Architecture &&
307
+ Math.hypot(dirs[p * 3], dirs[p * 3 + 1]) < ARCHITECTURE_FLAT_LIMIT)
308
+ continue;
309
+ for (let c = 0; c < 3; c++)
310
+ sum[c] += dirs[p * 3 + c];
311
+ }
312
+ if (sum[2] === 0)
313
+ sum = [0, 0, 1];
314
+ const average = unit(sum), groups = new Map();
315
+ const split = options.facets > 0 && cluster.pixels.length >= minFacetArea;
316
+ if (split) {
317
+ for (const p of cluster.pixels) {
318
+ const dx = dirs[p * 3], dy = dirs[p * 3 + 1], tilt = Math.hypot(dx, dy);
319
+ const key = tilt > FACET_TILT_LIMIT
320
+ ? (Math.round(Math.atan2(dy, dx) / FACET_DIRECTION_STEP) +
321
+ FACET_DIRECTION_COUNT) %
322
+ FACET_DIRECTION_COUNT
323
+ : FRONT_FACET_KEY;
324
+ if (!groups.has(key))
325
+ groups.set(key, []);
326
+ groups.get(key).push(p);
327
+ }
328
+ }
329
+ const minSupport = Math.max(FACET_MIN_SUPPORT, Math.ceil(Math.sqrt(cluster.pixels.length) * facetSupportFactor));
330
+ const supported = [...groups.values()].filter((group) => group.length >= minSupport);
331
+ let allow = false;
332
+ if (supported.length >= 2) {
333
+ const means = supported.map((g) => {
334
+ const s = [0, 0, 0];
335
+ for (const p of g)
336
+ for (let c = 0; c < 3; c++)
337
+ s[c] += dirs[p * 3 + c];
338
+ return unit(s);
339
+ });
340
+ for (let i = 0; i < means.length; i++)
341
+ for (let j = 0; j < i; j++)
342
+ if (means[i].reduce((s, v, c) => s + v * means[j][c], 0) < facetDotLimit)
343
+ allow = true;
344
+ }
345
+ const base = quantize(average);
346
+ for (const p of cluster.pixels)
347
+ dirs.set(base, p * 3);
348
+ if (allow)
349
+ for (const g of supported) {
350
+ const sum = [0, 0, 0];
351
+ for (const p of g) {
352
+ const v = normalAt(p);
353
+ for (let c = 0; c < 3; c++)
354
+ sum[c] += v[c];
355
+ }
356
+ const v = quantize(sum);
357
+ for (const p of g)
358
+ dirs.set(v, p * 3);
359
+ }
360
+ }
361
+ if (options.mergeOutlines) {
362
+ const assigned = new Uint8Array(N);
363
+ head = 0;
364
+ tail = 0;
365
+ for (let i = 0; i < N; i++)
366
+ if (fg[i] && !thin[i]) {
367
+ assigned[i] = 1;
368
+ queue[tail++] = i;
369
+ }
370
+ while (head < tail) {
371
+ const p = queue[head++];
372
+ for (const n of adjacent(p))
373
+ if (fg[n] && !assigned[n]) {
374
+ assigned[n] = 1;
375
+ dirs.set(dirs.subarray(p * 3, p * 3 + 3), n * 3);
376
+ queue[tail++] = n;
377
+ }
378
+ }
379
+ }
380
+ const seen = new Uint8Array(N);
381
+ for (let i = 0; i < N; i++)
382
+ if (fg[i] && !seen[i]) {
383
+ const group = [];
384
+ head = 0;
385
+ tail = 1;
386
+ queue[0] = i;
387
+ seen[i] = 1;
388
+ while (head < tail) {
389
+ const p = queue[head++];
390
+ group.push(p);
391
+ for (const n of adjacent(p))
392
+ if (labels[n] === labels[i] &&
393
+ !seen[n] &&
394
+ Math.abs(dirs[n * 3] - dirs[i * 3]) < DIRECTION_EPSILON &&
395
+ Math.abs(dirs[n * 3 + 1] - dirs[i * 3 + 1]) < DIRECTION_EPSILON) {
396
+ seen[n] = 1;
397
+ queue[tail++] = n;
398
+ }
399
+ }
400
+ if (group.length <= SPECKLE_MAX_PIXELS) {
401
+ const neighbors = group
402
+ .flatMap(adjacent)
403
+ .filter((n) => labels[n] === labels[i] && !group.includes(n));
404
+ if (neighbors.length) {
405
+ const n = neighbors[0];
406
+ for (const p of group)
407
+ dirs.set(dirs.subarray(n * 3, n * 3 + 3), p * 3);
408
+ }
409
+ }
410
+ }
411
+ cachedKey = key;
412
+ directions = cachedDirections = dirs;
413
+ }
414
+ const output = new Uint8ClampedArray(N * 4);
415
+ const gain = options.normalStrength / PERCENT;
416
+ const ySign = options.invertY ? -1 : 1;
417
+ for (let i = 0; i < N; i++) {
418
+ const vector = i * 3, at = i * 4;
419
+ const x = fg[i] ? directions[vector] * gain : 0;
420
+ const y = fg[i] ? directions[vector + 1] * gain : 0;
421
+ const z = fg[i] ? directions[vector + 2] : 1;
422
+ const length = Math.sqrt(x * x + y * y + z * z) || 1;
423
+ output[at] = Math.round((x / length + 1) * NORMAL_CHANNEL_SCALE);
424
+ output[at + 1] = Math.round(((y / length) * ySign + 1) * NORMAL_CHANNEL_SCALE);
425
+ output[at + 2] = Math.round((z / length + 1) * NORMAL_CHANNEL_SCALE);
426
+ output[at + 3] = a[at + 3];
427
+ }
428
+ return { width: w, height: h, data: output };
429
+ },
430
+ };
431
+ }
432
+ export function generateNormalMap(albedo, input = {}) {
433
+ return createNormalMapGenerator(albedo).generate(input);
434
+ }
435
+ function colorEdgeDistance(a, fg, w, h) {
436
+ const seeds = new Uint8Array(w * h);
437
+ for (let y = 0; y < h; y++)
438
+ for (let x = 0; x < w; x++) {
439
+ const i = y * w + x;
440
+ if (!fg[i])
441
+ continue;
442
+ const o = i * 4;
443
+ if (x < w - 1 && fg[i + 1]) {
444
+ const j = o + 4;
445
+ if (a[o] !== a[j] || a[o + 1] !== a[j + 1] || a[o + 2] !== a[j + 2]) {
446
+ seeds[i] = 1;
447
+ seeds[i + 1] = 1;
448
+ }
449
+ }
450
+ if (y < h - 1 && fg[i + w]) {
451
+ const j = o + w * 4;
452
+ if (a[o] !== a[j] || a[o + 1] !== a[j + 1] || a[o + 2] !== a[j + 2]) {
453
+ seeds[i] = 1;
454
+ seeds[i + w] = 1;
455
+ }
456
+ }
457
+ }
458
+ const INF = 1e9, d = new Float32Array(w * h);
459
+ for (let i = 0; i < w * h; i++)
460
+ d[i] = seeds[i] ? 0 : INF;
461
+ for (let y = 0; y < h; y++)
462
+ for (let x = 0; x < w; x++) {
463
+ const i = y * w + x;
464
+ let v = d[i];
465
+ if (v === 0)
466
+ continue;
467
+ if (x > 0)
468
+ v = Math.min(v, d[i - 1] + 3);
469
+ if (y > 0) {
470
+ v = Math.min(v, d[i - w] + 3);
471
+ if (x > 0)
472
+ v = Math.min(v, d[i - w - 1] + 4);
473
+ if (x < w - 1)
474
+ v = Math.min(v, d[i - w + 1] + 4);
475
+ }
476
+ d[i] = v;
477
+ }
478
+ for (let y = h - 1; y >= 0; y--)
479
+ for (let x = w - 1; x >= 0; x--) {
480
+ const i = y * w + x;
481
+ let v = d[i];
482
+ if (v === 0)
483
+ continue;
484
+ if (x < w - 1)
485
+ v = Math.min(v, d[i + 1] + 3);
486
+ if (y < h - 1) {
487
+ v = Math.min(v, d[i + w] + 3);
488
+ if (x < w - 1)
489
+ v = Math.min(v, d[i + w + 1] + 4);
490
+ if (x > 0)
491
+ v = Math.min(v, d[i + w - 1] + 4);
492
+ }
493
+ d[i] = v;
494
+ }
495
+ for (let i = 0; i < w * h; i++)
496
+ if (d[i] < INF)
497
+ d[i] /= 3;
498
+ return d;
499
+ }
500
+ function chamferDistance(fg, w, h) {
501
+ const INF = 1e9;
502
+ const d = new Float32Array(w * h);
503
+ for (let i = 0; i < w * h; i++)
504
+ d[i] = fg[i] ? INF : 0;
505
+ const C1 = 3, C2 = 4;
506
+ for (let y = 0; y < h; y++)
507
+ for (let x = 0; x < w; x++) {
508
+ const i = y * w + x;
509
+ let v = d[i];
510
+ if (v === 0)
511
+ continue;
512
+ if (x > 0)
513
+ v = Math.min(v, d[i - 1] + C1);
514
+ if (y > 0) {
515
+ v = Math.min(v, d[i - w] + C1);
516
+ if (x > 0)
517
+ v = Math.min(v, d[i - w - 1] + C2);
518
+ if (x < w - 1)
519
+ v = Math.min(v, d[i - w + 1] + C2);
520
+ }
521
+ d[i] = v;
522
+ }
523
+ for (let y = h - 1; y >= 0; y--)
524
+ for (let x = w - 1; x >= 0; x--) {
525
+ const i = y * w + x;
526
+ let v = d[i];
527
+ if (v === 0)
528
+ continue;
529
+ if (x < w - 1)
530
+ v = Math.min(v, d[i + 1] + C1);
531
+ if (y < h - 1) {
532
+ v = Math.min(v, d[i + w] + C1);
533
+ if (x < w - 1)
534
+ v = Math.min(v, d[i + w + 1] + C2);
535
+ if (x > 0)
536
+ v = Math.min(v, d[i + w - 1] + C2);
537
+ }
538
+ d[i] = v;
539
+ }
540
+ for (let i = 0; i < w * h; i++)
541
+ if (d[i] < INF)
542
+ d[i] /= 3;
543
+ return d;
544
+ }
545
+ function separableMaskedBlur(field, mask, w, h) {
546
+ const masked = new Float32Array(w * h);
547
+ for (let i = 0; i < w * h; i++)
548
+ masked[i] = field[i] * mask[i];
549
+ const m = Float32Array.from(mask);
550
+ const blur1d = (src, wgt, alongX) => {
551
+ const out = new Float32Array(w * h);
552
+ const outW = new Float32Array(w * h);
553
+ const limit = alongX ? w : h;
554
+ const stride = alongX ? 1 : w;
555
+ const radius = 1;
556
+ for (let line = 0; line < (alongX ? h : w); line++) {
557
+ const base = alongX ? line * w : line;
558
+ for (let i = 0; i < limit; i++) {
559
+ const i0 = Math.max(0, i - radius);
560
+ const i1 = Math.min(limit, i + radius + 1);
561
+ let s = 0, sw = 0;
562
+ for (let k = i0; k < i1; k++) {
563
+ s += src[base + k * stride];
564
+ sw += wgt[base + k * stride];
565
+ }
566
+ out[base + i * stride] = s;
567
+ outW[base + i * stride] = sw;
568
+ }
569
+ }
570
+ return { out, outW };
571
+ };
572
+ const r1 = blur1d(masked, m, true);
573
+ const num = new Float32Array(w * h);
574
+ const den = new Float32Array(w * h);
575
+ for (let x = 0; x < w; x++)
576
+ for (let y = 0; y < h; y++) {
577
+ const i = y * w + x;
578
+ num[i] = r1.out[i];
579
+ den[i] = r1.outW[i];
580
+ }
581
+ const r2 = blur1d(num, den, false);
582
+ const out = new Float32Array(w * h);
583
+ for (let i = 0; i < w * h; i++)
584
+ out[i] = r2.outW[i] > 1e-6 ? r2.out[i] / r2.outW[i] : field[i];
585
+ return out;
586
+ }
587
+ function oklabLightness(r, g, b) {
588
+ const lin = (c) => {
589
+ const x = c / 255;
590
+ return x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
591
+ };
592
+ const lr = lin(r), lg = lin(g), lb = lin(b);
593
+ const l = Math.cbrt(0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb);
594
+ const m = Math.cbrt(0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb);
595
+ const s = Math.cbrt(0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb);
596
+ return 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;
597
+ }
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@xprite/lighter",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Generate normal maps, light masks, and relighted renders from pixel art.",
5
+ "license": "MIT",
6
+ "author": "rhinoc",
7
+ "packageManager": "pnpm@11.1.3",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/rhinoc/xprite-lighter.git"
11
+ },
12
+ "homepage": "https://github.com/rhinoc/xprite-lighter#readme",
13
+ "keywords": [
14
+ "pixel-art",
15
+ "normal-map",
16
+ "relighting",
17
+ "light-mask",
18
+ "sprite",
19
+ "image-processing"
20
+ ],
21
+ "type": "module",
22
+ "sideEffects": false,
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ }
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "LICENSE",
32
+ "README.md"
33
+ ],
34
+ "scripts": {
35
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
36
+ "typecheck": "tsc -p tsconfig.json",
37
+ "test": "vitest run",
38
+ "prepublishOnly": "pnpm run build",
39
+ "bench": "node bench/run.mjs && python3 bench/run-relit.py --out bench/run",
40
+ "demo": "python3 -m http.server 8734",
41
+ "bench:all": "for m in object character terrain architecture spritelab spritefusion naive; do node bench/run.mjs bench bench/run-$m $m && python3 bench/run-relit.py --out bench/run-$m; done"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "^26.6.6",
45
+ "pngjs": "^7.0.0",
46
+ "typescript": "^6.0.3",
47
+ "vitest": "^5.0.2"
48
+ }
49
+ }