@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 rhinoc
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,179 @@
1
- # Temporary Holding Version
1
+ # @xprite/lighter
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@xprite/lighter)](https://www.npmjs.com/package/@xprite/lighter)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
5
+
6
+ Generate normal maps, light masks, and relighted renders from pixel art sprites. Runs in browsers
7
+ and Node, no runtime dependencies. Adapted from
8
+ [Pixel Art Lighter v3.5.22](https://www.moonfell-rpg.com/Pixel-Art-Lighter-v3.5.22.html) by Red
9
+ Hat Sprite (MIT), extended with Lab-aware clustering, sprite-scale-adaptive faceting, painted-light
10
+ estimation, and an invertY option. It is the normal-map engine of the
11
+ [Xprite](https://xprite.cc) pixel editor.
12
+
13
+ ## Compared with other tools
14
+
15
+ Same input, same light. "GT" on bench cases is the interpolated mesh normal;
16
+ "authored" on OGA sprites is the pack's own procedural normal (CC-BY Antifarea).
17
+ +auto runs `estimatePaintedLight`; +manual uses the labelled angle.
18
+
19
+ | | Input | GT / authored | Xprite +auto | Xprite +manual | Sprite Fusion | SpriteLab | Bump It | PAL upstream | Laigter |
20
+ | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
21
+ | mage-b-64 | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/mage-b-64-input.png" width="96" alt="i" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/mage-b-64-gt.png" width="96" alt="gt" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-xprite-auto-mage-b-64.png" width="96" alt="a" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-xprite-manual-mage-b-64.png" width="96" alt="m" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-spritefusion-mage-b-64.png" width="96" alt="sf" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-spritelab-mage-b-64.png" width="96" alt="sl" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-bumpit-mage-b-64.png" width="96" alt="b" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-pal-upstream-mage-b-64.png" width="96" alt="p" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-laigter-mage-b-64.png" width="96" alt="l" /> |
22
+ | watermill-a-64 | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/watermill-a-64-input.png" width="96" alt="i" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/watermill-a-64-gt.png" width="96" alt="gt" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-xprite-auto-watermill-a-64.png" width="96" alt="a" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-xprite-manual-watermill-a-64.png" width="96" alt="m" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-spritefusion-watermill-a-64.png" width="96" alt="sf" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-spritelab-watermill-a-64.png" width="96" alt="sl" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-bumpit-watermill-a-64.png" width="96" alt="b" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-pal-upstream-watermill-a-64.png" width="96" alt="p" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-laigter-watermill-a-64.png" width="96" alt="l" /> |
23
+ | rabbit | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/rabbit-input.png" width="96" alt="i" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/rabbit-authored.png" width="96" alt="gt" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/rabbit-auto.png" width="96" alt="a" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/rabbit-manual.png" width="96" alt="m" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-spritefusion-rabbit.png" width="96" alt="sf" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-spritelab-rabbit.png" width="96" alt="sl" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-bumpit-rabbit.png" width="96" alt="b" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-pal-upstream-rabbit.png" width="96" alt="p" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-laigter-rabbit.png" width="96" alt="l" /> |
24
+ | captain | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/captain-input.png" width="96" alt="i" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/captain-authored.png" width="96" alt="gt" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/captain-auto.png" width="96" alt="a" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/captain-manual.png" width="96" alt="m" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-spritefusion-captain.png" width="96" alt="sf" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-spritelab-captain.png" width="96" alt="sl" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-bumpit-captain.png" width="96" alt="b" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-pal-upstream-captain.png" width="96" alt="p" /> | <img src="https://raw.githubusercontent.com/rhinoc/xprite-lighter/main/docs/images/comp-laigter-captain.png" width="96" alt="l" /> |
25
+
26
+ OGA sprites ship authored normals made by Sprite DLight — procedural, not a
27
+ ground truth — so these rows are for visual comparison only, no scores.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ npm install @xprite/lighter
33
+ ```
34
+
35
+ ## Usage
36
+
37
+ ```ts
38
+ import {
39
+ createLightMaskGenerator,
40
+ createNormalMapGenerator,
41
+ defaultLightMaskOptions,
42
+ defaultNormalMapLightOptions,
43
+ defaultNormalMapOptions,
44
+ estimatePaintedLight,
45
+ generateNormalMap,
46
+ prepareNormalMapLighting,
47
+ removePaintedLight,
48
+ renderNormalMapLighting,
49
+ renderPreparedNormalMapLighting,
50
+ } from "@xprite/lighter";
51
+ ```
52
+
53
+ Images are `{ width, height, data: Uint8ClampedArray }`, straight-alpha RGBA.
54
+
55
+ ### Generate a normal map
56
+
57
+ ```ts
58
+ const normal = generateNormalMap(sprite, { preset: "object" });
59
+ // or with cached segmentation when the same source is edited interactively:
60
+ const generator = createNormalMapGenerator(sprite, shadingSource);
61
+ const hint = generator.suggestPaintedLightAngle();
62
+ const normal = generator.generate({ preset: "character", facets: 40 });
63
+ ```
64
+
65
+ Presets `architecture | character | object | terrain` change silhouette shape and facet density.
66
+ `generateNormalMap(input, options)`:
67
+
68
+ | Option | Description |
69
+ | --- | --- |
70
+ | `preset` | `architecture`, `character`, `object` (default), `terrain`. |
71
+ | `shapeStrength` | Overall height-field gain, 0–100. |
72
+ | `normalStrength` | Final normal tilt gain, 0–100. |
73
+ | `smoothing` | Box-blur passes on the height field, 0–6. |
74
+ | `facets` | Facet quantization density, 0–100. 0 = smooth normals. |
75
+ | `mergeOutlines` | Propagate normals into thin outline clusters. |
76
+ | `invertY` | Flip the green channel (DirectX convention). |
77
+ | `paintedLightAngle` | Direction the sprite was painted with, in degrees (0 = right, 90 = up). Omit it to auto-estimate with `estimatePaintedLight`; low-confidence estimates (fit 0.3–0.45) apply proportionally less influence, and when no estimate exists painted-light handling turns off. |
78
+ | `paintedLightInfluence` | 0–100, default 60; how much of the sprite's shading to treat as painted light instead of geometry. 0 disables it. |
79
+
80
+ `createNormalMapGenerator(albedo, shading?)` caches the segmentation and lets you call
81
+ `suggestPaintedLightAngle()` once, then `generate(options)` cheaply per slider change. The
82
+ painted-light estimate is computed once per source and reused by every `generate` call.
83
+
84
+ ### Generate a light mask
85
+
86
+ ```ts
87
+ const mask = createLightMaskGenerator(albedo).generate(defaultLightMaskOptions());
88
+ ```
89
+
90
+ A grayscale map of how much each cluster's interior should receive light. Used by
91
+ `prepareNormalMapLighting` to dim occluded regions.
92
+
93
+ ### Relight
94
+
95
+ ```ts
96
+ const prepared = prepareNormalMapLighting(albedo, normal, mask);
97
+ const lit = renderPreparedNormalMapLighting(prepared, {
98
+ ...defaultNormalMapLightOptions(width, height),
99
+ position: { x: width * 0.25, y: height * 0.1 },
100
+ height: 40,
101
+ brightness: 400,
102
+ ambient: 30,
103
+ });
104
+ ```
105
+
106
+ `prepareNormalMapLighting(albedo, normals, lightMask?)` precomputes linear colors, unit
107
+ normals and mask factors once; `renderPreparedNormalMapLighting(prepared, options)` re-renders
108
+ cheaply as the light moves.
109
+
110
+ `defaultNormalMapLightOptions(w, h)` returns `{ position, height, brightness, ambient, maskStrength, color, invertY }`.
111
+
112
+ ### Remove painted light
113
+
114
+ Most sprites already have a light painted in, so relighting them adds a second light on top.
115
+ Pass the estimated direction to divide it out first:
116
+
117
+ ```ts
118
+ const estimate = estimatePaintedLight(albedo);
119
+ const delight = estimate ? { angle: estimate.angle, influence: 100 } : undefined;
120
+ const lit = renderPreparedNormalMapLighting(prepared, { ...lightOptions, delight });
121
+ // or keep the flattened colors: removePaintedLight(prepared, delight)
122
+ ```
123
+
124
+ The painted light is modeled as ambient 0.15 + Lambert from 45° elevation, using the generated
125
+ normals. It works best on clean cel-shaded art; soft hand-painted lighting or ambient occlusion
126
+ can over-brighten.
127
+
128
+ ## How it works
129
+
130
+ 1. **Cluster.** Foreground pixels are grouped into 4-connected regions — exact RGB by default,
131
+ or Lab ΔE growth (`LightingMapRegionMode.Perceptual`) when antialiasing breaks exact colors.
132
+ 2. **Height field.** Silhouette distance (BFS from edges) plus normalized luminance; outline
133
+ clusters marked thin and propagated last. `paintedLightSignal` estimates how much of the
134
+ input's shading was painted, and `paintedLightAngle` tilts normals toward the estimated light.
135
+ 3. **Facet.** Cluster means are quantized into 8 azimuth buckets × 4 tilt levels; large clusters
136
+ split by direction support. Small sprites keep the concave √distance ramp; larger ones switch
137
+ to a linear ramp that preserves fold direction better.
138
+ 4. **Clean up.** ≤2 px same-direction fragments take their cluster's normal; `mergeOutlines`
139
+ propagates into the thin ring; `invertY` optionally flips green.
140
+
141
+ [`src/`](src) documents each stage. The editor side of this pipeline lives in
142
+ [xprite-normal-maps](https://github.com/rhinoc/xprite-normal-maps) under
143
+ `apps/editor/src/managers/normal-maps/` and `components/normal-maps/`.
144
+
145
+ ## Benchmark
146
+
147
+ `bench/` scores every method on the same 64 cases (8 KayKit CC0 models × 2 views × 4 sizes).
148
+ GT is the smooth interpolated mesh normal; relit targets are 5-band cel renders at 4 unseen
149
+ directions. Macro means below, at 30° boundary threshold.
150
+
151
+ | Method | AP ↑ | aligned recall ↑ | false edge ↓ | mean angle ° ↓ | relit MAE ↓ |
152
+ |---|---:|---:|---:|---:|---:|
153
+ | Xprite +auto hint | 0.520 | 14.67 | 1.19 | 37.99 | 29.81 |
154
+ | Xprite +auto hint +delight | 0.520 | 14.67 | 1.19 | 37.99 | **24.98** |
155
+ | Xprite +manual hint (160°) | **0.522** | **15.51** | 1.20 | 37.74 | 29.54 |
156
+ | Sprite Fusion | 0.317 | 3.65 | 2.76 | **37.57** | 30.37 |
157
+ | SpriteLab | 0.290 | 0.05 | 0.04 | 38.74 | 29.71 |
158
+ | Bump It | 0.311 | 0.08 | **0.01** | 41.38 | 29.68 |
159
+ | Pixel Art Lighter upstream | 0.287 | 4.75 | 4.42 | 40.03 | 29.95 |
160
+ | Laigter | 0.276 | 0.43 | 0.95 | 47.10 | 33.24 |
161
+
162
+ AP and aligned recall measure whether the *folds* land where the GT's facets
163
+ break — our quantized facets win these despite a higher smooth-GT angle error.
164
+ Relit MAE barely separates methods until the painted light is removed: every row
165
+ without `+delight` lights an already-lit input a second time.
166
+ See [`bench/README.md`](bench/README.md) for metric definitions, per-case CSVs,
167
+ and the light-mask variant results.
168
+
169
+ ## Demo & bench
170
+
171
+ - `pnpm run demo` serves a live browser demo (`demo/index.html`) comparing authored and generated
172
+ normals on an OpenGameArt monster sheet (CC-BY 3.0, Antifarea) and the mesh-GT corpus.
173
+ - `pnpm run bench` scores `generateNormalMap` against 64 mesh-GT cases (8 KayKit CC0 models ×
174
+ 2 views × 4 sizes) and the competitors above. Metrics: mean/median angular error, acc@11.25°,
175
+ boundary AP, aligned recall, false edge, relit cel MAE.
176
+
177
+ ## License
178
+
179
+ MIT. Third-party notices in [`LICENSES/`](LICENSES/).
package/dist/base.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ /** Pixel data shared by the generators. Kept free of editor types. */
2
+ export type Rgba = readonly [number, number, number, number];
3
+ export interface Point {
4
+ x: number;
5
+ y: number;
6
+ }
7
+ /** Straight-alpha RGBA pixels, row by row. */
8
+ export interface PixelBuffer {
9
+ width: number;
10
+ height: number;
11
+ data: Uint8ClampedArray;
12
+ }
13
+ export declare const UINT8_MAX = 255;
14
+ /** Keep accidental allocations bounded while allowing ordinary 4K imports. */
15
+ export declare const MAX_IMAGE_DIMENSION = 32768;
16
+ export declare const MAX_IMAGE_PIXELS = 64000000;
17
+ /** Constrains a number to an inclusive interval. */
18
+ export declare function clamp(value: number, minimum: number, maximum: number): number;
19
+ export declare function assertDimension(value: number, label: string): number;
20
+ export declare function assertPixelBuffer(image: PixelBuffer, label?: string): void;
21
+ //# sourceMappingURL=base.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../src/base.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,MAAM,MAAM,IAAI,GAAG,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAE7D,MAAM,WAAW,KAAK;IACpB,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;CACX;AAED,8CAA8C;AAC9C,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,iBAAiB,CAAC;CACzB;AAED,eAAO,MAAM,SAAS,MAAM,CAAC;AAC7B,8EAA8E;AAC9E,eAAO,MAAM,mBAAmB,QAAS,CAAC;AAC1C,eAAO,MAAM,gBAAgB,WAAa,CAAC;AAG3C,oDAAoD;AACpD,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAE7E;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAKpE;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,WAAW,EAAE,KAAK,SAAU,GAAG,IAAI,CAiB3E"}
package/dist/base.js ADDED
@@ -0,0 +1,34 @@
1
+ /** Pixel data shared by the generators. Kept free of editor types. */
2
+ export const UINT8_MAX = 255;
3
+ /** Keep accidental allocations bounded while allowing ordinary 4K imports. */
4
+ export const MAX_IMAGE_DIMENSION = 32_768;
5
+ export const MAX_IMAGE_PIXELS = 64_000_000;
6
+ const CHANNELS = 4;
7
+ /** Constrains a number to an inclusive interval. */
8
+ export function clamp(value, minimum, maximum) {
9
+ return Math.max(minimum, Math.min(maximum, value));
10
+ }
11
+ export function assertDimension(value, label) {
12
+ if (!Number.isSafeInteger(value) || value < 1 || value > MAX_IMAGE_DIMENSION) {
13
+ throw new RangeError(`${label} must be an integer from 1 to ${MAX_IMAGE_DIMENSION}`);
14
+ }
15
+ return value;
16
+ }
17
+ export function assertPixelBuffer(image, label = "image") {
18
+ if (!image || typeof image !== "object") {
19
+ throw new TypeError(`${label} must be a PixelBuffer`);
20
+ }
21
+ assertDimension(image.width, `${label}.width`);
22
+ assertDimension(image.height, `${label}.height`);
23
+ const pixels = image.width * image.height;
24
+ if (!Number.isSafeInteger(pixels) || pixels > MAX_IMAGE_PIXELS) {
25
+ throw new RangeError(`${label} is too large; at most ${MAX_IMAGE_PIXELS} pixels are supported`);
26
+ }
27
+ if (!(image.data instanceof Uint8ClampedArray)) {
28
+ throw new TypeError(`${label}.data must be a Uint8ClampedArray`);
29
+ }
30
+ const expectedLength = pixels * CHANNELS;
31
+ if (image.data.length !== expectedLength) {
32
+ throw new RangeError(`${label}.data must contain exactly ${expectedLength} bytes`);
33
+ }
34
+ }
@@ -0,0 +1,4 @@
1
+ export type Lab = readonly [number, number, number];
2
+ /** Convert sRGB bytes to CIELAB using a D65 white point. */
3
+ export declare function rgbToLab(r: number, g: number, b: number): Lab;
4
+ //# sourceMappingURL=color-lab.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"color-lab.d.ts","sourceRoot":"","sources":["../src/color-lab.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,GAAG,GAAG,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAWpD,4DAA4D;AAC5D,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,GAAG,CAQ7D"}
@@ -0,0 +1,17 @@
1
+ import { UINT8_MAX } from "./base.js";
2
+ const SRGB_LINEAR = Float64Array.from({ length: UINT8_MAX + 1 }, (_, value) => {
3
+ const channel = value / UINT8_MAX;
4
+ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
5
+ });
6
+ const D65 = [0.95047, 1, 1.08883];
7
+ const LAB_EPSILON = 216 / 24389;
8
+ const LAB_KAPPA = 24389 / 27;
9
+ const labPivot = (value) => value > LAB_EPSILON ? Math.cbrt(value) : (LAB_KAPPA * value + 16) / 116;
10
+ /** Convert sRGB bytes to CIELAB using a D65 white point. */
11
+ export function rgbToLab(r, g, b) {
12
+ const lr = SRGB_LINEAR[r], lg = SRGB_LINEAR[g], lb = SRGB_LINEAR[b];
13
+ const x = labPivot((lr * 0.4124564 + lg * 0.3575761 + lb * 0.1804375) / D65[0]);
14
+ const y = labPivot((lr * 0.2126729 + lg * 0.7151522 + lb * 0.072175) / D65[1]);
15
+ const z = labPivot((lr * 0.0193339 + lg * 0.119192 + lb * 0.9503041) / D65[2]);
16
+ return [116 * y - 16, 500 * (x - y), 200 * (y - z)];
17
+ }
@@ -0,0 +1,8 @@
1
+ export * from "./base.js";
2
+ export * from "./lighting-map-source.js";
3
+ export * from "./light-mask.js";
4
+ export * from "./normal-map.js";
5
+ export * from "./normal-map-lighting.js";
6
+ export { estimatePaintedLight, estimatePaintedLightAngle, type PaintedLightEstimate, } from "./normal-map-light-estimate.js";
7
+ export { paintedLightSignal } from "./normal-map-painted-light.js";
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,0BAA0B,CAAC;AACzC,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,OAAO,EACL,oBAAoB,EACpB,yBAAyB,EACzB,KAAK,oBAAoB,GAC1B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from "./base.js";
2
+ export * from "./lighting-map-source.js";
3
+ export * from "./light-mask.js";
4
+ export * from "./normal-map.js";
5
+ export * from "./normal-map-lighting.js";
6
+ export { estimatePaintedLight, estimatePaintedLightAngle, } from "./normal-map-light-estimate.js";
7
+ export { paintedLightSignal } from "./normal-map-painted-light.js";
@@ -0,0 +1,24 @@
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 { type PixelBuffer } from "./base.js";
7
+ export declare const DEFAULT_LIGHT_MASK_LAYER_NAME = "Light Mask";
8
+ export interface LightMaskOptions {
9
+ strength: number;
10
+ floor: number;
11
+ ceiling: number;
12
+ cavity: number;
13
+ }
14
+ export declare const LIGHT_MASK_LIMITS: Readonly<{
15
+ strength: 100;
16
+ floor: 255;
17
+ ceiling: 255;
18
+ cavity: 100;
19
+ }>;
20
+ export declare function defaultLightMaskOptions(): LightMaskOptions;
21
+ export declare function createLightMaskGenerator(albedo: PixelBuffer): {
22
+ generate(input?: Partial<LightMaskOptions>): PixelBuffer;
23
+ };
24
+ //# sourceMappingURL=light-mask.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"light-mask.d.ts","sourceRoot":"","sources":["../src/light-mask.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAa,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAOxD,eAAO,MAAM,6BAA6B,eAAe,CAAC;AAC1D,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;CAChB;AAMD,eAAO,MAAM,iBAAiB;;;;;EAK5B,CAAC;AAEH,wBAAgB,uBAAuB,IAAI,gBAAgB,CAE1D;AAED,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,WAAW;qBAyBxC,OAAO,CAAC,gBAAgB,CAAC,GAAQ,WAAW;EA0B/D"}
@@ -0,0 +1,75 @@
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 { UINT8_MAX } from "./base.js";
7
+ import { CONSTANT_LUMINANCE, LUMINANCE_EPSILON, segmentLightingMapSource, } from "./lighting-map-source.js";
8
+ export const DEFAULT_LIGHT_MASK_LAYER_NAME = "Light Mask";
9
+ const PERCENT = 100;
10
+ const SHADING_CURVE = 1.15;
11
+ const CAVITY_LUMINANCE_LIMIT = 0.35;
12
+ const CAVITY_NEIGHBOR_CONTRAST = 0.15;
13
+ const CAVITY_NEIGHBOR_MAJORITY = 0.5;
14
+ export const LIGHT_MASK_LIMITS = Object.freeze({
15
+ strength: PERCENT,
16
+ floor: UINT8_MAX,
17
+ ceiling: UINT8_MAX,
18
+ cavity: PERCENT,
19
+ });
20
+ export function defaultLightMaskOptions() {
21
+ return { strength: PERCENT, floor: 20, ceiling: UINT8_MAX, cavity: 35 };
22
+ }
23
+ export function createLightMaskGenerator(albedo) {
24
+ const { w, h, a, fg, lum, labels, lo, hi, adjacent, clusters } = segmentLightingMapSource(albedo);
25
+ const range = hi - lo;
26
+ const regions = clusters.map(({ pixels, value }) => {
27
+ const tone = range > LUMINANCE_EPSILON ? (value - lo) / range : CONSTANT_LUMINANCE;
28
+ let surrounded = 0;
29
+ if (tone < CAVITY_LUMINANCE_LIMIT) {
30
+ for (const pixel of pixels) {
31
+ let brighter = 0;
32
+ let neighbors = 0;
33
+ for (const neighbor of adjacent(pixel)) {
34
+ if (!fg[neighbor] || labels[neighbor] === labels[pixel])
35
+ continue;
36
+ neighbors++;
37
+ if (lum[neighbor] > value + range * CAVITY_NEIGHBOR_CONTRAST)
38
+ brighter++;
39
+ }
40
+ if (neighbors && brighter / neighbors > CAVITY_NEIGHBOR_MAJORITY)
41
+ surrounded++;
42
+ }
43
+ }
44
+ return {
45
+ pixels,
46
+ reception: tone ** SHADING_CURVE,
47
+ cavity: Math.min(1, surrounded / Math.sqrt(pixels.length)),
48
+ };
49
+ });
50
+ return {
51
+ generate(input = {}) {
52
+ const options = defaultLightMaskOptions();
53
+ for (const key of ["strength", "floor", "ceiling", "cavity"]) {
54
+ const value = input[key];
55
+ if (typeof value === "number" && Number.isFinite(value))
56
+ options[key] = Math.round(Math.max(0, Math.min(LIGHT_MASK_LIMITS[key], value)));
57
+ }
58
+ const strength = options.strength / PERCENT;
59
+ const floor = options.floor / UINT8_MAX;
60
+ const cavity = options.cavity / PERCENT;
61
+ const ceiling = options.ceiling / UINT8_MAX;
62
+ const data = new Uint8ClampedArray(a.length);
63
+ for (const region of regions) {
64
+ const reception = (floor + (1 - floor) * region.reception) * (1 - cavity * region.cavity);
65
+ const value = Math.round(UINT8_MAX * Math.min(ceiling, 1 - strength + strength * reception));
66
+ for (const pixel of region.pixels) {
67
+ const at = pixel * 4;
68
+ data[at] = data[at + 1] = data[at + 2] = value;
69
+ data[at + 3] = a[at + 3];
70
+ }
71
+ }
72
+ return { width: w, height: h, data };
73
+ },
74
+ };
75
+ }
@@ -0,0 +1,33 @@
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 { type PixelBuffer } from "./base.js";
7
+ export declare const CONSTANT_LUMINANCE = 0.75;
8
+ export declare const LUMINANCE_EPSILON = 0.00001;
9
+ export declare enum LightingMapRegionMode {
10
+ ExactRgb = "exact-rgb",
11
+ Perceptual = "perceptual"
12
+ }
13
+ export declare function lightingMapLuminance(data: Uint8ClampedArray, at: number): number;
14
+ /** Partition foreground pixels into four-connected regions. */
15
+ export declare function segmentLightingMapSource(albedo: PixelBuffer, mode?: LightingMapRegionMode): {
16
+ w: number;
17
+ h: number;
18
+ N: number;
19
+ a: Uint8ClampedArray<ArrayBuffer>;
20
+ fg: Uint8Array<ArrayBuffer>;
21
+ lum: Float32Array<ArrayBuffer>;
22
+ labels: Int32Array<ArrayBuffer>;
23
+ lo: number;
24
+ hi: number;
25
+ adjacent: (i: number) => number[];
26
+ queue: Int32Array<ArrayBuffer>;
27
+ clusters: {
28
+ pixels: number[];
29
+ value: number;
30
+ }[];
31
+ foregroundArea: number;
32
+ };
33
+ //# sourceMappingURL=lighting-map-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lighting-map-source.d.ts","sourceRoot":"","sources":["../src/lighting-map-source.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAgC,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAM3E,eAAO,MAAM,kBAAkB,OAAO,CAAC;AACvC,eAAO,MAAM,iBAAiB,UAAO,CAAC;AAWtC,oBAAY,qBAAqB;IAC/B,QAAQ,cAAc;IACtB,UAAU,eAAe;CAC1B;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,iBAAiB,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAKhF;AAuCD,+DAA+D;AAC/D,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,WAAW,EACnB,IAAI,wBAAiC;;;;;;;;;;kBAwBhB,MAAM;;;gBAWL,MAAM,EAAE;eAAS,MAAM;;;EA+B9C"}
@@ -0,0 +1,123 @@
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, UINT8_MAX } from "./base.js";
7
+ import { rgbToLab } from "./color-lab.js";
8
+ const RED_LUMINANCE = 0.2126;
9
+ const GREEN_LUMINANCE = 0.7152;
10
+ const BLUE_LUMINANCE = 0.0722;
11
+ export const CONSTANT_LUMINANCE = 0.75;
12
+ export const LUMINANCE_EPSILON = 1e-5;
13
+ const RGBA_CHANNELS = 4;
14
+ const ALPHA_CHANNEL = 3;
15
+ const UNASSIGNED = -1;
16
+ const REGION_DELTA_E = 10;
17
+ const EDGE_DELTA_E = 6;
18
+ const EDGE_ALPHA_STEP = 48;
19
+ const RED_SHIFT = 16;
20
+ const GREEN_SHIFT = 8;
21
+ const MAX_CACHED_LAB_COLORS = 4096;
22
+ export var LightingMapRegionMode;
23
+ (function (LightingMapRegionMode) {
24
+ LightingMapRegionMode["ExactRgb"] = "exact-rgb";
25
+ LightingMapRegionMode["Perceptual"] = "perceptual";
26
+ })(LightingMapRegionMode || (LightingMapRegionMode = {}));
27
+ export function lightingMapLuminance(data, at) {
28
+ return ((RED_LUMINANCE * data[at] + GREEN_LUMINANCE * data[at + 1] + BLUE_LUMINANCE * data[at + 2]) /
29
+ UINT8_MAX);
30
+ }
31
+ /** Grow across weak edges while keeping every accepted color close to the region seed. */
32
+ function perceptualRegionGrowth(data) {
33
+ // Keep scratch memory bounded even when a sprite has a large transparent margin.
34
+ const colors = new Map();
35
+ const rgb = (pixel) => {
36
+ const at = pixel * RGBA_CHANNELS;
37
+ return (data[at] << RED_SHIFT) | (data[at + 1] << GREEN_SHIFT) | data[at + 2];
38
+ };
39
+ const lab = (color) => {
40
+ const cached = colors.get(color);
41
+ if (cached)
42
+ return cached;
43
+ const value = rgbToLab(color >>> RED_SHIFT, (color >>> GREEN_SHIFT) & UINT8_MAX, color & UINT8_MAX);
44
+ if (colors.size === MAX_CACHED_LAB_COLORS)
45
+ colors.clear();
46
+ colors.set(color, value);
47
+ return value;
48
+ };
49
+ const distanceSquared = (first, second) => {
50
+ if (first === second)
51
+ return 0;
52
+ const a = lab(first);
53
+ const b = lab(second);
54
+ return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
55
+ };
56
+ const alpha = (pixel) => data[pixel * RGBA_CHANNELS + ALPHA_CHANNEL];
57
+ return (seed, pixel, neighbor) => {
58
+ if (Math.abs(alpha(pixel) - alpha(neighbor)) >= EDGE_ALPHA_STEP)
59
+ return false;
60
+ const neighborColor = rgb(neighbor);
61
+ return (distanceSquared(rgb(pixel), neighborColor) <= EDGE_DELTA_E ** 2 &&
62
+ distanceSquared(rgb(seed), neighborColor) <= REGION_DELTA_E ** 2);
63
+ };
64
+ }
65
+ /** Partition foreground pixels into four-connected regions. */
66
+ export function segmentLightingMapSource(albedo, mode = LightingMapRegionMode.ExactRgb) {
67
+ assertPixelBuffer(albedo);
68
+ const w = albedo.width, h = albedo.height, N = w * h, a = albedo.data.slice(), fg = new Uint8Array(N), lum = new Float32Array(N), labels = new Int32Array(N);
69
+ labels.fill(UNASSIGNED);
70
+ let foregroundArea = 0;
71
+ let lo = Infinity, hi = -Infinity;
72
+ for (let i = 0; i < N; i++) {
73
+ const k = i * 4;
74
+ fg[i] = a[k + 3] > 0 ? 1 : 0;
75
+ lum[i] = lightingMapLuminance(a, k);
76
+ if (fg[i]) {
77
+ foregroundArea++;
78
+ lo = Math.min(lo, lum[i]);
79
+ hi = Math.max(hi, lum[i]);
80
+ }
81
+ }
82
+ const adjacent = (i) => {
83
+ const x = i % w, y = (i / w) | 0, out = [];
84
+ if (x)
85
+ out.push(i - 1);
86
+ if (x < w - 1)
87
+ out.push(i + 1);
88
+ if (y)
89
+ out.push(i - w);
90
+ if (y < h - 1)
91
+ out.push(i + w);
92
+ return out;
93
+ };
94
+ const queue = new Int32Array(N), clusters = [];
95
+ const perceptual = mode === LightingMapRegionMode.Perceptual;
96
+ const canGrow = perceptual
97
+ ? perceptualRegionGrowth(a)
98
+ : (seed, _pixel, neighbor) => {
99
+ const from = seed * RGBA_CHANNELS;
100
+ const to = neighbor * RGBA_CHANNELS;
101
+ return a[from] === a[to] && a[from + 1] === a[to + 1] && a[from + 2] === a[to + 2];
102
+ };
103
+ for (let i = 0; i < N; i++)
104
+ if (fg[i] && labels[i] === UNASSIGNED) {
105
+ let head = 0, tail = 1;
106
+ queue[0] = i;
107
+ const id = clusters.length, pixels = [];
108
+ let luminanceSum = 0;
109
+ labels[i] = id;
110
+ while (head < tail) {
111
+ const p = queue[head++];
112
+ pixels.push(p);
113
+ luminanceSum += lum[p];
114
+ for (const n of adjacent(p))
115
+ if (fg[n] && labels[n] === UNASSIGNED && canGrow(i, p, n)) {
116
+ labels[n] = id;
117
+ queue[tail++] = n;
118
+ }
119
+ }
120
+ clusters.push({ pixels, value: perceptual ? luminanceSum / pixels.length : lum[i] });
121
+ }
122
+ return { w, h, N, a, fg, lum, labels, lo, hi, adjacent, queue, clusters, foregroundArea };
123
+ }
@@ -0,0 +1,10 @@
1
+ import { type PixelBuffer } from "./base.js";
2
+ /** Estimate an image-plane azimuth from contour shading. Null leaves the draft angle alone. */
3
+ export interface PaintedLightEstimate {
4
+ angle: number;
5
+ /** correlation fit in [0,1]; scale influence by this to fade weak signals */
6
+ fit: number;
7
+ }
8
+ export declare function estimatePaintedLightAngle(source: PixelBuffer, shading?: PixelBuffer): number | null;
9
+ export declare function estimatePaintedLight(source: PixelBuffer, shading?: PixelBuffer): PaintedLightEstimate | null;
10
+ //# sourceMappingURL=normal-map-light-estimate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normal-map-light-estimate.d.ts","sourceRoot":"","sources":["../src/normal-map-light-estimate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAuMxD,+FAA+F;AAC/F,MAAM,WAAW,oBAAoB;IACnC,KAAK,EAAE,MAAM,CAAC;IACd,6EAA6E;IAC7E,GAAG,EAAE,MAAM,CAAC;CACb;AAED,wBAAgB,yBAAyB,CACvC,MAAM,EAAE,WAAW,EACnB,OAAO,CAAC,EAAE,WAAW,GACpB,MAAM,GAAG,IAAI,CAGf;AAED,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,WAAW,EACnB,OAAO,CAAC,EAAE,WAAW,GACpB,oBAAoB,GAAG,IAAI,CAiG7B"}