@margoengine/lighting2d 0.1.0 → 1.0.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.
package/README.md CHANGED
@@ -1,353 +1,353 @@
1
- # @margoengine/lighting2d
2
-
3
- 2D lights for pixel pictures: point, spot and directional lights, normal-mapped shading from a sprite layer's normals, and
4
- hard shadows from occluder edges. Each frame the lights add up in one target, which a pixel layer multiplies over what
5
- is below it. WebGPU only.
6
-
7
- ```ts
8
- import {EngineKernel} from 'margoengine/core';
9
- import {LayerCompositor} from 'margoengine/pixel';
10
- import {Lighting2D} from 'margoengine/lighting2d';
11
- const canvas = document.querySelector('canvas')!;
12
- const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [640, 360]});
13
- const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 4}});
14
- const picture = compositor.addLayer();
15
- const shade = compositor.addLayer({blend: 'multiply', z: 1});
16
- const lighting = Lighting2D.attach(engine, {target: shade.target, camera: shade.camera, ambient: '#202030'});
17
- const lamp = lighting.addLight({x: 40, y: 30, radius: 80, color: '#ffd9a0'});
18
- lighting.setOccluders([{shape: 'box', width: 16, height: 16, offset: [80, 45]}]);
19
- picture.write({width: 160, height: 90, data: new Uint8Array(160 * 90 * 4).fill(200)});
20
- engine.render({delta: 1 / 60});
21
- lamp.x += 1; // read each frame
22
- ```
23
-
24
- ## Lighting2D
25
-
26
- | Option | Default | What it does |
27
- | --- | --- | --- |
28
- | `target` | required | Where the light goes, a texture or a function such as a layer's `target` |
29
- | `normals` | flat | Surface directions the size of the target, such as a sprite layer's `normals.target` |
30
- | `camera` | `{x: 0, y: 0, zoom: 1}` | World units to pixels, such as a layer's `camera`; read each frame |
31
- | `ambient` | `#000000` | The light everything gets; read each frame |
32
- | `occluders` | none | What blocks light; see `setOccluders` |
33
- | `order` | `20` | Frame-graph order, after sprites and maps and before the compositor |
34
- | `name` | `lighting2d-1`, ... | Plugin name, unique per scene |
35
- | `layer` | `~0` (all) | Layer bitmask this pass illuminates; lights must share a bit to be drawn |
36
-
37
- `addLight(options)` returns a `Light2D`, `removeLight(light)` takes it away, and `lights` lists them.
38
-
39
- Lights add up in four half-float layers, 32 B per pixel of the target, so a sum of many lights reads the same on GPUs that
40
- round blends differently. `docs/limits.md` has the numbers.
41
-
42
- ## Light2D
43
-
44
- Every field is read each frame. Distances are world units, angles radians, and y runs down the screen.
45
-
46
- | Field | Default | What it does |
47
- | --- | --- | --- |
48
- | `kind` | `'point'` | `'point'`, `'spot'` or `'directional'` |
49
- | `x`, `y` | `0` | Position |
50
- | `color`, `intensity` | `#ffffff`, `1` | What it adds at full strength |
51
- | `radius`, `falloff` | `64`, `2` | Strength is `(1 - distance / radius) ^ falloff` |
52
- | `height` | `32` | How far in front of the picture it sits; a low light grazes flat surfaces, and 0 leaves them dark |
53
- | `angle` | `0` | Spot and directional: the way it shines, clockwise from +x |
54
- | `cone`, `softness` | `Math.PI / 4`, `0` | Spot: half the cone, and the outer part of it that fades, 0 to 1 |
55
- | `elevation` | `Math.PI / 4` | Directional: how far above the picture |
56
- | `shadows` | `true` | False lets it through occluders |
57
- | `layers` | `~0` (all) | Bitmask of layers this light illuminates |
58
- | `mask` | none | Geometric boundary (`rect`, `circle`, `polygon`) clipping the light |
59
-
60
- A surface gets the strength times the cosine between its normal and the way to the light. Normals follow the sprite
61
- layer's target: x right, y down the screen, z out of it. Where the normal target holds nothing (alpha 0) the surface is flat.
62
-
63
- ## Occluders
64
-
65
- `setOccluders(list)` replaces what blocks light. Each is `{shape: 'polygon', points}`, `{shape: 'polyline', points}`,
66
- `{shape: 'segment', from, to}`, `{shape: 'box', width, height, offset, rotation}` or `{shape: 'circle', radius, offset}`,
67
- in world units. The result of `tileMapColliders(map)` from `margoengine/physics2d` fits as it is, so a tile map's
68
- collision shapes cast shadows too.
69
-
70
- A pixel is in shadow when an occluder edge lies between its centre and the light, so the inside of a closed shape is dark
71
- to a light outside it. Shadow edges are hard: each pixel is lit or not, with no soft penumbra.
72
-
73
- ## Light masks and layers
74
-
75
- Lights can be filtered to specific layers or restricted to a geometric mask. Set `layers` on `Light2D` and `layer` on `Lighting2D` to select which lights affect which passes:
76
-
77
- ```ts
78
- import {EngineKernel} from 'margoengine/core';
79
- import {LayerCompositor} from 'margoengine/pixel';
80
- import {Lighting2D} from 'margoengine/lighting2d';
81
- const canvas = document.querySelector('canvas')!;
82
- const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [640, 360]});
83
- const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 4}});
84
- const picture = compositor.addLayer();
85
- const shade = compositor.addLayer({blend: 'multiply', z: 1});
86
- const lighting = Lighting2D.attach(engine, {target: shade.target, camera: shade.camera, layer: 0b01});
87
- const lamp = lighting.addLight({
88
- x: 40,
89
- y: 30,
90
- radius: 80,
91
- color: '#ffd9a0',
92
- layers: 0b01,
93
- mask: {kind: 'rect', minX: 10, minY: 10, maxX: 70, maxY: 60},
94
- });
95
- picture.write({width: 160, height: 90, data: new Uint8Array(160 * 90 * 4).fill(200)});
96
- engine.render({delta: 1 / 60});
97
- lamp.x += 1;
98
- ```
99
-
100
- `inLightMask(mask, x, y)` and `lightAffectsLayer(light, layerMask)` evaluate masks and layer masks in Node.
101
-
102
- ## Soft shadows
103
-
104
- `@margoengine/lighting2d/soft` provides soft penumbra shadows that soften with distance from the occluder. Near the occluder,
105
- shadow edges remain crisp; as distance increases, the penumbra widens proportionally to the light's emitter radius (`sourceRadius`).
106
- A directional light has no distance, so it softens by `angularRadius` instead, the source's angular radius in radians
107
- (0 to pi / 2, default `SUN_ANGULAR_RADIUS`, the Sun's 0.0046505); `sourceRadius` applies to point and spot lights only.
108
-
109
- ```ts
110
- import {EngineKernel} from 'margoengine/core';
111
- import {LayerCompositor} from 'margoengine/pixel';
112
- import {SoftLighting2D} from 'margoengine/lighting2d/soft';
113
- const canvas = document.querySelector('canvas')!;
114
- const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [640, 360]});
115
- const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 4}});
116
- const picture = compositor.addLayer();
117
- const shade = compositor.addLayer({blend: 'multiply', z: 1});
118
- const soft = SoftLighting2D.attach(engine, {target: shade.target, camera: shade.camera, ambient: '#202030', sourceRadius: 6});
119
- const lamp = soft.addLight({x: 40, y: 30, radius: 80, color: '#ffd9a0', sourceRadius: 8});
120
- soft.setOccluders([{shape: 'box', width: 16, height: 16, offset: [80, 45]}]);
121
- picture.write({width: 160, height: 90, data: new Uint8Array(160 * 90 * 4).fill(200)});
122
- engine.render({delta: 1 / 60});
123
- lamp.x += 1;
124
- ```
125
-
126
- CPU helper functions `softShadowFactor(light, edges, x, y, options)`, `softInShadow(light, edges, x, y, options)` and
127
- `softLightAt(light, x, y, edges, normal, options)` evaluate soft shadows in Node for testing.
128
-
129
- ## Light textures (cookies)
130
-
131
- `@margoengine/lighting2d/cookie` projects 2D textures (cookies / gobos) onto light footprints to shape lights with window patterns,
132
- slats, caustics or flashlights.
133
-
134
- ```ts
135
- import {EngineKernel} from 'margoengine/core';
136
- import {LayerCompositor} from 'margoengine/pixel';
137
- import {CookieLighting2D, createSpotCookie} from 'margoengine/lighting2d/cookie';
138
- const canvas = document.querySelector('canvas')!;
139
- const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [640, 360]});
140
- const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 4}});
141
- const picture = compositor.addLayer();
142
- const shade = compositor.addLayer({blend: 'multiply', z: 1});
143
- const cookies = CookieLighting2D.attach(engine, {target: shade.target, camera: shade.camera, ambient: '#202030'});
144
- const cookie = createSpotCookie(32, 0.4, 0.9);
145
- const flashlight = cookies.addLight({x: 40, y: 30, radius: 80, color: '#ffd9a0', cookie, cookieScale: [60, 60]});
146
- cookies.setOccluders([{shape: 'box', width: 16, height: 16, offset: [80, 45]}]);
147
- picture.write({width: 160, height: 90, data: new Uint8Array(160 * 90 * 4).fill(200)});
148
- engine.render({delta: 1 / 60});
149
- flashlight.x += 1;
150
- ```
151
-
152
- A `CookieLight2D` takes `cookie: CookieTexture2D`, `cookieScale: [width, height]`, `cookieOffset: [x, y]`, `cookieRotation: radians`,
153
- `cookieWrap: 'zero' | 'clamp' | 'repeat' | 'mirror'`, and `cookieMode: 'multiply' | 'alpha' | 'color'`. Presets `createSpotCookie`
154
- and `createWindowCookie` construct standard patterns. CPU helper `cookieLightAt(light, x, y, normal)` evaluates the shaped light in Node.
155
-
156
- ## 2D global illumination
157
-
158
- `@margoengine/lighting2d/gi` stores spatial radiance/transmittance intervals on world-space probe grids.
159
- Probe spacing doubles at each level from a one-world-unit base lattice centred at .5; angular samples multiply by
160
- `angularRatio`. Each child interval has its own visibility connector, composed before bilinear interpolation
161
- (Osborne/Sannikov appendix A). Opaque emitters terminate transmission. Cameras use the pixel layer's top-left origin.
162
-
163
- `cascades` defaults: `cascades: 4` (1..8), `baseRays: 4` (1..32), `baseDistance: 16` (>0), `intervalRatio: 4` (>1),
164
- `angularRatio: 4` (1..8), `bounces: 1` (0..4), `albedo: .5` (0..1), `intensity: 1` (>=0).
165
- The far reach is `baseDistance * intervalRatio ** (cascades - 1)`.
166
- Each requested bounce performs a separate two-sided diffuse surface gather, using only the preceding order;
167
- `bounces: 0` leaves reflecting surfaces black. Surface patches are at most `baseDistance` long and gather 32 angular
168
- samples with normalized cosine weights. This finite quadrature can miss small emitters; increase their resolved size
169
- or shorten `baseDistance` to improve spatial resolution. It is an approximation, with no performance or arbitrary-scene accuracy claim.
170
- Direct point, spot and directional lights retain their cones, heights/elevation, masks, layers and shadow setting.
171
- `layer` defaults to all bits, as does `scene.layer` in the CPU forms. Unorm targets clamp HDR output; use `rgba16float`
172
- when the result must exceed one. Every frame rebuilds the field without temporal history.
173
-
174
- ```ts
175
- import {EngineKernel} from 'margoengine/core';
176
- import {LayerCompositor} from 'margoengine/pixel';
177
- import {GILighting2D} from 'margoengine/lighting2d/gi';
178
- const canvas = document.querySelector('canvas')!;
179
- const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [640, 360]});
180
- const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 4}});
181
- const picture = compositor.addLayer();
182
- const shade = compositor.addLayer({blend: 'multiply', z: 1});
183
- const gi = GILighting2D.attach(engine, {
184
- target: shade.target,
185
- camera: shade.camera,
186
- ambient: '#101020',
187
- emitters: [{x: 40, y: 30, radius: 12, color: '#ffd9a0', intensity: 2}],
188
- occluders: [{shape: 'box', width: 16, height: 16, offset: [80, 45]}],
189
- cascades: {cascades: 2, baseRays: 4, baseDistance: 32, bounces: 1, albedo: 0.6},
190
- });
191
- picture.write({width: 160, height: 90, data: new Uint8Array(160 * 90 * 4).fill(200)});
192
- engine.render({delta: 1 / 60});
193
- gi.emitters[0] = {x: 41, y: 30, radius: 12, color: '#ffd9a0', intensity: 2};
194
- ```
195
-
196
- `RadianceCascade2D` and `evaluate2DGI(point, normal, scene, options)` evaluate 2D global illumination on the CPU for tests.
197
-
198
- ## 2.5D height and self-shadowing
199
-
200
- `@margoengine/lighting2d/height` casts perspective height shadows and self-shadows for top-down and isometric games.
201
- Sprites and structures have vertical height (z-axis extrusion) and elevation; light rays from point, spot and directional
202
- lights cast geometric shadows onto flat ground planes and lower receivers. Each GPU pass shades a flat +z-facing receiver
203
- at one elevation; arbitrary vertical-face normals are supported only by the CPU helper.
204
-
205
- ```ts
206
- import {EngineKernel} from 'margoengine/core';
207
- import {LayerCompositor} from 'margoengine/pixel';
208
- import {HeightLighting2D, createHeightOccluder} from 'margoengine/lighting2d/height';
209
- const canvas = document.querySelector('canvas')!;
210
- const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [640, 360]});
211
- const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 4}});
212
- const picture = compositor.addLayer();
213
- const shade = compositor.addLayer({blend: 'multiply', z: 1});
214
- const building = createHeightOccluder({shape: 'box', offset: [80, 45], width: 24, depth: 24, height: 16, selfShadow: true});
215
- const lighting = HeightLighting2D.attach(engine, {
216
- target: shade.target,
217
- camera: shade.camera,
218
- occluders: [building],
219
- elevation: 0,
220
- });
221
- const sun = lighting.addLight({kind: 'directional', angle: 0, elevation: Math.PI / 4, color: '#fff0d0'});
222
- picture.write({width: 160, height: 90, data: new Uint8Array(160 * 90 * 4).fill(200)});
223
- engine.render({delta: 1 / 60});
224
- sun.angle += 0.01;
225
- ```
226
-
227
- CPU helper functions `inHeightShadow(light, occluders, x, y, receiverElevation)`, `heightShadowFactor(light, occluders, x, y, receiverElevation)`
228
- and `heightLightAt(light, occluders, x, y, receiverElevation, normal)` evaluate height-based shading and self-shadowing in Node.
229
-
230
- ## Emissive sprites and bloom hookup
231
-
232
- `@margoengine/lighting2d/emissive` adds glowing emissive sprites that emit light into the scene with falloff, and isolates
233
- linear HDR emission and local threshold extraction in separate owned `rgba16float` textures. The pass clears and replaces
234
- its target every frame. `emissiveTexture` contains emission plus the local glow; `bloomTexture` contains the local threshold
235
- contribution alone. Neither texture aliases the caller's target. These textures are replaced on resize or restoration.
236
-
237
- ```ts
238
- import {EngineKernel} from 'margoengine/core';
239
- import {LayerCompositor} from 'margoengine/pixel';
240
- import {EmissiveLighting2D} from 'margoengine/lighting2d/emissive';
241
- const canvas = document.querySelector('canvas')!;
242
- const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [640, 360]});
243
- const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 4}});
244
- const picture = compositor.addLayer();
245
- const shade = compositor.addLayer({blend: 'multiply', z: 1});
246
- const emissive = EmissiveLighting2D.attach(engine, {
247
- target: shade.target,
248
- camera: shade.camera,
249
- bloom: true,
250
- bloomThreshold: 0.8,
251
- bloomIntensity: 1.0,
252
- });
253
- const orb = emissive.addSprite({x: 80, y: 45, radius: 8, glowRadius: 24, color: '#ffcc44', intensity: 2.0});
254
- picture.write({width: 160, height: 90, data: new Uint8Array(160 * 90 * 4).fill(200)});
255
- engine.render({delta: 1 / 60});
256
- orb.x += 1;
257
- ```
258
-
259
- `connectBloom(() => new Bloom(options))` owns an unattached image effect from `@margoengine/post/bloom`, dispatches
260
- its real `encodeImage` API on the isolated HDR emission, and presents the filtered HDR result to the target. Its factory is
261
- called again after device restoration; the pass disposes the old effect. An attached Bloom or a `setInput` mock is not a
262
- supported adapter. Set `bloom: false` to use only the external spatial blur, without the local glow contribution.
263
-
264
- ```ts
265
- import {EngineKernel} from 'margoengine/core';
266
- import {LayerCompositor} from 'margoengine/pixel';
267
- import {EmissiveLighting2D} from 'margoengine/lighting2d/emissive';
268
- import {Bloom} from 'margoengine/post/bloom';
269
- const engine = await EngineKernel.create(document.querySelector('canvas')!, {backend: 'webgpu', exactSize: [320, 180]});
270
- const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 2}});
271
- const shade = compositor.addLayer({blend: 'add'});
272
- const emission = EmissiveLighting2D.attach(engine, {target: shade.target, camera: shade.camera, bloom: false});
273
- emission.addSprite({x: 80, y: 45, radius: 3, glowRadius: 0, intensity: 3});
274
- emission.connectBloom(() => new Bloom({threshold: 0.8, strength: 0.8}));
275
- engine.render({delta: 0});
276
- ```
277
-
278
- `emissiveLightAt(sprite, x, y, layerMask, bloomIntensity, bloomThreshold)` evaluates direct emission and local glow in Node.
279
- The effective local threshold is the larger of the sprite threshold and global threshold (default 0.8 for each).
280
- The local glow is an analytic intensity term, not a spatial convolution; the optional Bloom adapter supplies spatial filtering.
281
-
282
- ## CPU forms
283
-
284
- `lightAt(light, x, y, normal)` is what a light adds at a world point, `occluderEdges(list)` the edges of a list, and
285
- `inShadow(light, edges, x, y)` the shadow test. They run in Node, for tools and tests.
286
-
287
- Trademark notice: names of other tools belong to their owners.
288
-
289
- ## Textures after a device restore
290
-
291
- `target`, `normals` and the SDF `source` and `emission` are textures you made on the engine's device. After the device is lost and restored, a
292
- plain texture is gone with it: the pass skips that frame's work, reports one `'state'` error through `engine.onError` (help `borrowed-lost`), and
293
- waits for a new texture. A function, such as a pixel layer's `target` getter, is read every frame and needs nothing. Hand in a new texture with
294
- `setTarget` and `setNormals` (every entry has them; `SDFScene2D` has `source` and `emission` setters), and `SDFScene2D.encode` returns false when it
295
- had nothing to draw.
296
-
297
- ```ts
298
- import {EngineKernel} from 'margoengine/core';
299
- import {Lighting2D} from 'margoengine/lighting2d';
300
- const canvas = document.querySelector('canvas')!;
301
- const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [64, 64]});
302
- const make = () => engine.gpu!.createTexture({size: [64, 64], format: 'rgba8unorm', usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING});
303
- const lighting = Lighting2D.attach(engine, {target: make()});
304
- engine.render({delta: 1 / 60});
305
- await engine.rebootDevice(); // the first texture is gone with the old device
306
- lighting.setTarget(make()); // the setter takes the engine's device as it is now
307
- engine.render({delta: 1 / 60});
308
- ```
309
-
310
- ## Lifetime and scene limits
311
-
312
- All entries are WebGPU-only and reject native WebGL2 with `code: 'unsupported'` and a help link. Each entry owns its GPU
313
- resources, rebuilds them after device restoration or target format changes, unregisters on disposal, and allows a new pass
314
- with the same name to attach. Submit a manually supplied command encoder before disposing its pass.
315
-
316
- The direct-light entries (root, soft, cookie and height) share rect, circle and polygon masks, including inversion and
317
- pass/light layer filtering. An omitted circle-mask centre is world `(0, 0)`. Mask points are uploaded every frame so mutable
318
- polygons take effect immediately. Polygon storage is bounded by the device's `maxStorageBufferBindingSize` (16 bytes per
319
- point). Height occluders cost 48 bytes each, emissive sprites 64 bytes each, bounded by the same limit; neither silently drops
320
- items beyond 64. Height uniforms cost at least 256 bytes per light, bounded by `maxBufferSize`. Excess storage throws before
321
- a draw. Soft sample counts must be integers in `[1, 64]`. Camera coordinates and zoom must be finite, with zoom above zero.
322
-
323
- Height and emissive targets contain the current frame only, including when all lights/sprites are removed. Compose separate
324
- lighting targets with pixel layers when combining passes. The regression suite includes native WebGL2 refusals, distinct
325
- height light uniforms, floating volumes, lights below the receiver, 65-item scenes, frame ordering, repeated frames, target
326
- format changes, name reuse, HDR extraction, the actual Bloom image adapter and device restoration. GI remains the exception
327
- to the physical-correctness claims above until its known defects are resolved.
328
-
329
- Height lights accumulate into an owned `rgba16float` image and present once to the target. This retains contributions smaller than one target byte (100 lights at intensity .001 sum to .1); the HDR image is rebuilt on resize or device restoration.
330
-
331
- Direct-light bind groups use the current mask buffer and normal target every frame. Contiguous uniform fields are packed together; validation still checks every numeric field before rendering.
332
-
333
- Validation errors identify the field and its allowed range, with a link to the
334
- pixel-lighting help page. Coordinates, angles and order must be finite; radius,
335
- dimensions, cone and falloff must also be positive. Intensity, height, glow radius,
336
- bloom controls and soft source radius allow zero. Softness is in `[0, 1]`, samples
337
- are integers in `[1, 64]`, and layer masks are integers in `[0, 4294967295]`.
338
- Cookie scale is positive, offsets and rotation are finite, and mode/wrap errors
339
- list the accepted names. Rect masks require ordered finite bounds, circles require
340
- a non-negative radius and optional two-coordinate centre, and polygons require at
341
- least three finite two-coordinate points. These checks apply before rendering and
342
- in CPU helpers; changing a mutable light to an invalid value reports that field.
343
-
344
- ```ts
345
- import {EmissiveSprite2D, checkEmissiveSprite} from 'margoengine/lighting2d/emissive';
346
- const sprite = new EmissiveSprite2D({radius: 8, glowRadius: 0});
347
- sprite.glowRadius = 24;
348
- checkEmissiveSprite(sprite); // A negative glowRadius reports "must be finite and non-negative".
349
- ```
350
-
351
- ## Rendering tiers
352
-
353
- GPU attachments refuse the small `@margoengine/webgl2-compat/preview` engine during setup with linked `MargoError` code `unsupported`. Use native WebGPU, the full WebGL2 compatibility layer, or awaited [automatic escalation](../webgl2-compat/README.md#automatic-escalation). The package-tier browser regression checks refusal and escalation; the package GPU suite checks drawing on both complete tiers.
1
+ # @margoengine/lighting2d
2
+
3
+ 2D lights for pixel pictures: point, spot and directional lights, normal-mapped shading from a sprite layer's normals, and
4
+ hard shadows from occluder edges. Each frame the lights add up in one target, which a pixel layer multiplies over what
5
+ is below it. WebGPU only.
6
+
7
+ ```ts
8
+ import {EngineKernel} from 'margoengine/core';
9
+ import {LayerCompositor} from 'margoengine/pixel';
10
+ import {Lighting2D} from 'margoengine/lighting2d';
11
+ const canvas = document.querySelector('canvas')!;
12
+ const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [640, 360]});
13
+ const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 4}});
14
+ const picture = compositor.addLayer();
15
+ const shade = compositor.addLayer({blend: 'multiply', z: 1});
16
+ const lighting = Lighting2D.attach(engine, {target: shade.target, camera: shade.camera, ambient: '#202030'});
17
+ const lamp = lighting.addLight({x: 40, y: 30, radius: 80, color: '#ffd9a0'});
18
+ lighting.setOccluders([{shape: 'box', width: 16, height: 16, offset: [80, 45]}]);
19
+ picture.write({width: 160, height: 90, data: new Uint8Array(160 * 90 * 4).fill(200)});
20
+ engine.render({delta: 1 / 60});
21
+ lamp.x += 1; // read each frame
22
+ ```
23
+
24
+ ## Lighting2D
25
+
26
+ | Option | Default | What it does |
27
+ | --- | --- | --- |
28
+ | `target` | required | Where the light goes, a texture or a function such as a layer's `target` |
29
+ | `normals` | flat | Surface directions the size of the target, such as a sprite layer's `normals.target` |
30
+ | `camera` | `{x: 0, y: 0, zoom: 1}` | World units to pixels, such as a layer's `camera`; read each frame |
31
+ | `ambient` | `#000000` | The light everything gets; read each frame |
32
+ | `occluders` | none | What blocks light; see `setOccluders` |
33
+ | `order` | `20` | Frame-graph order, after sprites and maps and before the compositor |
34
+ | `name` | `lighting2d-1`, ... | Plugin name, unique per scene |
35
+ | `layer` | `~0` (all) | Layer bitmask this pass illuminates; lights must share a bit to be drawn |
36
+
37
+ `addLight(options)` returns a `Light2D`, `removeLight(light)` takes it away, and `lights` lists them.
38
+
39
+ Lights add up in four half-float layers, 32 B per pixel of the target, so a sum of many lights reads the same on GPUs that
40
+ round blends differently. `docs/limits.md` has the numbers.
41
+
42
+ ## Light2D
43
+
44
+ Every field is read each frame. Distances are world units, angles radians, and y runs down the screen.
45
+
46
+ | Field | Default | What it does |
47
+ | --- | --- | --- |
48
+ | `kind` | `'point'` | `'point'`, `'spot'` or `'directional'` |
49
+ | `x`, `y` | `0` | Position |
50
+ | `color`, `intensity` | `#ffffff`, `1` | What it adds at full strength |
51
+ | `radius`, `falloff` | `64`, `2` | Strength is `(1 - distance / radius) ^ falloff` |
52
+ | `height` | `32` | How far in front of the picture it sits; a low light grazes flat surfaces, and 0 leaves them dark |
53
+ | `angle` | `0` | Spot and directional: the way it shines, clockwise from +x |
54
+ | `cone`, `softness` | `Math.PI / 4`, `0` | Spot: half the cone, and the outer part of it that fades, 0 to 1 |
55
+ | `elevation` | `Math.PI / 4` | Directional: how far above the picture |
56
+ | `shadows` | `true` | False lets it through occluders |
57
+ | `layers` | `~0` (all) | Bitmask of layers this light illuminates |
58
+ | `mask` | none | Geometric boundary (`rect`, `circle`, `polygon`) clipping the light |
59
+
60
+ A surface gets the strength times the cosine between its normal and the way to the light. Normals follow the sprite
61
+ layer's target: x right, y down the screen, z out of it. Where the normal target holds nothing (alpha 0) the surface is flat.
62
+
63
+ ## Occluders
64
+
65
+ `setOccluders(list)` replaces what blocks light. Each is `{shape: 'polygon', points}`, `{shape: 'polyline', points}`,
66
+ `{shape: 'segment', from, to}`, `{shape: 'box', width, height, offset, rotation}` or `{shape: 'circle', radius, offset}`,
67
+ in world units. The result of `tileMapColliders(map)` from `margoengine/physics2d` fits as it is, so a tile map's
68
+ collision shapes cast shadows too.
69
+
70
+ A pixel is in shadow when an occluder edge lies between its centre and the light, so the inside of a closed shape is dark
71
+ to a light outside it. Shadow edges are hard: each pixel is lit or not, with no soft penumbra.
72
+
73
+ ## Light masks and layers
74
+
75
+ Lights can be filtered to specific layers or restricted to a geometric mask. Set `layers` on `Light2D` and `layer` on `Lighting2D` to select which lights affect which passes:
76
+
77
+ ```ts
78
+ import {EngineKernel} from 'margoengine/core';
79
+ import {LayerCompositor} from 'margoengine/pixel';
80
+ import {Lighting2D} from 'margoengine/lighting2d';
81
+ const canvas = document.querySelector('canvas')!;
82
+ const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [640, 360]});
83
+ const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 4}});
84
+ const picture = compositor.addLayer();
85
+ const shade = compositor.addLayer({blend: 'multiply', z: 1});
86
+ const lighting = Lighting2D.attach(engine, {target: shade.target, camera: shade.camera, layer: 0b01});
87
+ const lamp = lighting.addLight({
88
+ x: 40,
89
+ y: 30,
90
+ radius: 80,
91
+ color: '#ffd9a0',
92
+ layers: 0b01,
93
+ mask: {kind: 'rect', minX: 10, minY: 10, maxX: 70, maxY: 60},
94
+ });
95
+ picture.write({width: 160, height: 90, data: new Uint8Array(160 * 90 * 4).fill(200)});
96
+ engine.render({delta: 1 / 60});
97
+ lamp.x += 1;
98
+ ```
99
+
100
+ `inLightMask(mask, x, y)` and `lightAffectsLayer(light, layerMask)` evaluate masks and layer masks in Node.
101
+
102
+ ## Soft shadows
103
+
104
+ `@margoengine/lighting2d/soft` provides soft penumbra shadows that soften with distance from the occluder. Near the occluder,
105
+ shadow edges remain crisp; as distance increases, the penumbra widens proportionally to the light's emitter radius (`sourceRadius`).
106
+ A directional light has no distance, so it softens by `angularRadius` instead, the source's angular radius in radians
107
+ (0 to pi / 2, default `SUN_ANGULAR_RADIUS`, the Sun's 0.0046505); `sourceRadius` applies to point and spot lights only.
108
+
109
+ ```ts
110
+ import {EngineKernel} from 'margoengine/core';
111
+ import {LayerCompositor} from 'margoengine/pixel';
112
+ import {SoftLighting2D} from 'margoengine/lighting2d/soft';
113
+ const canvas = document.querySelector('canvas')!;
114
+ const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [640, 360]});
115
+ const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 4}});
116
+ const picture = compositor.addLayer();
117
+ const shade = compositor.addLayer({blend: 'multiply', z: 1});
118
+ const soft = SoftLighting2D.attach(engine, {target: shade.target, camera: shade.camera, ambient: '#202030', sourceRadius: 6});
119
+ const lamp = soft.addLight({x: 40, y: 30, radius: 80, color: '#ffd9a0', sourceRadius: 8});
120
+ soft.setOccluders([{shape: 'box', width: 16, height: 16, offset: [80, 45]}]);
121
+ picture.write({width: 160, height: 90, data: new Uint8Array(160 * 90 * 4).fill(200)});
122
+ engine.render({delta: 1 / 60});
123
+ lamp.x += 1;
124
+ ```
125
+
126
+ CPU helper functions `softShadowFactor(light, edges, x, y, options)`, `softInShadow(light, edges, x, y, options)` and
127
+ `softLightAt(light, x, y, edges, normal, options)` evaluate soft shadows in Node for testing.
128
+
129
+ ## Light textures (cookies)
130
+
131
+ `@margoengine/lighting2d/cookie` projects 2D textures (cookies / gobos) onto light footprints to shape lights with window patterns,
132
+ slats, caustics or flashlights.
133
+
134
+ ```ts
135
+ import {EngineKernel} from 'margoengine/core';
136
+ import {LayerCompositor} from 'margoengine/pixel';
137
+ import {CookieLighting2D, createSpotCookie} from 'margoengine/lighting2d/cookie';
138
+ const canvas = document.querySelector('canvas')!;
139
+ const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [640, 360]});
140
+ const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 4}});
141
+ const picture = compositor.addLayer();
142
+ const shade = compositor.addLayer({blend: 'multiply', z: 1});
143
+ const cookies = CookieLighting2D.attach(engine, {target: shade.target, camera: shade.camera, ambient: '#202030'});
144
+ const cookie = createSpotCookie(32, 0.4, 0.9);
145
+ const flashlight = cookies.addLight({x: 40, y: 30, radius: 80, color: '#ffd9a0', cookie, cookieScale: [60, 60]});
146
+ cookies.setOccluders([{shape: 'box', width: 16, height: 16, offset: [80, 45]}]);
147
+ picture.write({width: 160, height: 90, data: new Uint8Array(160 * 90 * 4).fill(200)});
148
+ engine.render({delta: 1 / 60});
149
+ flashlight.x += 1;
150
+ ```
151
+
152
+ A `CookieLight2D` takes `cookie: CookieTexture2D`, `cookieScale: [width, height]`, `cookieOffset: [x, y]`, `cookieRotation: radians`,
153
+ `cookieWrap: 'zero' | 'clamp' | 'repeat' | 'mirror'`, and `cookieMode: 'multiply' | 'alpha' | 'color'`. Presets `createSpotCookie`
154
+ and `createWindowCookie` construct standard patterns. CPU helper `cookieLightAt(light, x, y, normal)` evaluates the shaped light in Node.
155
+
156
+ ## 2D global illumination
157
+
158
+ `@margoengine/lighting2d/gi` stores spatial radiance/transmittance intervals on world-space probe grids.
159
+ Probe spacing doubles at each level from a one-world-unit base lattice centred at .5; angular samples multiply by
160
+ `angularRatio`. Each child interval has its own visibility connector, composed before bilinear interpolation
161
+ (Osborne/Sannikov appendix A). Opaque emitters terminate transmission. Cameras use the pixel layer's top-left origin.
162
+
163
+ `cascades` defaults: `cascades: 4` (1..8), `baseRays: 4` (1..32), `baseDistance: 16` (>0), `intervalRatio: 4` (>1),
164
+ `angularRatio: 4` (1..8), `bounces: 1` (0..4), `albedo: .5` (0..1), `intensity: 1` (>=0).
165
+ The far reach is `baseDistance * intervalRatio ** (cascades - 1)`.
166
+ Each requested bounce performs a separate two-sided diffuse surface gather, using only the preceding order;
167
+ `bounces: 0` leaves reflecting surfaces black. Surface patches are at most `baseDistance` long and gather 32 angular
168
+ samples with normalized cosine weights. This finite quadrature can miss small emitters; increase their resolved size
169
+ or shorten `baseDistance` to improve spatial resolution. It is an approximation, with no performance or arbitrary-scene accuracy claim.
170
+ Direct point, spot and directional lights retain their cones, heights/elevation, masks, layers and shadow setting.
171
+ `layer` defaults to all bits, as does `scene.layer` in the CPU forms. Unorm targets clamp HDR output; use `rgba16float`
172
+ when the result must exceed one. Every frame rebuilds the field without temporal history.
173
+
174
+ ```ts
175
+ import {EngineKernel} from 'margoengine/core';
176
+ import {LayerCompositor} from 'margoengine/pixel';
177
+ import {GILighting2D} from 'margoengine/lighting2d/gi';
178
+ const canvas = document.querySelector('canvas')!;
179
+ const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [640, 360]});
180
+ const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 4}});
181
+ const picture = compositor.addLayer();
182
+ const shade = compositor.addLayer({blend: 'multiply', z: 1});
183
+ const gi = GILighting2D.attach(engine, {
184
+ target: shade.target,
185
+ camera: shade.camera,
186
+ ambient: '#101020',
187
+ emitters: [{x: 40, y: 30, radius: 12, color: '#ffd9a0', intensity: 2}],
188
+ occluders: [{shape: 'box', width: 16, height: 16, offset: [80, 45]}],
189
+ cascades: {cascades: 2, baseRays: 4, baseDistance: 32, bounces: 1, albedo: 0.6},
190
+ });
191
+ picture.write({width: 160, height: 90, data: new Uint8Array(160 * 90 * 4).fill(200)});
192
+ engine.render({delta: 1 / 60});
193
+ gi.emitters[0] = {x: 41, y: 30, radius: 12, color: '#ffd9a0', intensity: 2};
194
+ ```
195
+
196
+ `RadianceCascade2D` and `evaluate2DGI(point, normal, scene, options)` evaluate 2D global illumination on the CPU for tests.
197
+
198
+ ## 2.5D height and self-shadowing
199
+
200
+ `@margoengine/lighting2d/height` casts perspective height shadows and self-shadows for top-down and isometric games.
201
+ Sprites and structures have vertical height (z-axis extrusion) and elevation; light rays from point, spot and directional
202
+ lights cast geometric shadows onto flat ground planes and lower receivers. Each GPU pass shades a flat +z-facing receiver
203
+ at one elevation; arbitrary vertical-face normals are supported only by the CPU helper.
204
+
205
+ ```ts
206
+ import {EngineKernel} from 'margoengine/core';
207
+ import {LayerCompositor} from 'margoengine/pixel';
208
+ import {HeightLighting2D, createHeightOccluder} from 'margoengine/lighting2d/height';
209
+ const canvas = document.querySelector('canvas')!;
210
+ const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [640, 360]});
211
+ const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 4}});
212
+ const picture = compositor.addLayer();
213
+ const shade = compositor.addLayer({blend: 'multiply', z: 1});
214
+ const building = createHeightOccluder({shape: 'box', offset: [80, 45], width: 24, depth: 24, height: 16, selfShadow: true});
215
+ const lighting = HeightLighting2D.attach(engine, {
216
+ target: shade.target,
217
+ camera: shade.camera,
218
+ occluders: [building],
219
+ elevation: 0,
220
+ });
221
+ const sun = lighting.addLight({kind: 'directional', angle: 0, elevation: Math.PI / 4, color: '#fff0d0'});
222
+ picture.write({width: 160, height: 90, data: new Uint8Array(160 * 90 * 4).fill(200)});
223
+ engine.render({delta: 1 / 60});
224
+ sun.angle += 0.01;
225
+ ```
226
+
227
+ CPU helper functions `inHeightShadow(light, occluders, x, y, receiverElevation)`, `heightShadowFactor(light, occluders, x, y, receiverElevation)`
228
+ and `heightLightAt(light, occluders, x, y, receiverElevation, normal)` evaluate height-based shading and self-shadowing in Node.
229
+
230
+ ## Emissive sprites and bloom hookup
231
+
232
+ `@margoengine/lighting2d/emissive` adds glowing emissive sprites that emit light into the scene with falloff, and isolates
233
+ linear HDR emission and local threshold extraction in separate owned `rgba16float` textures. The pass clears and replaces
234
+ its target every frame. `emissiveTexture` contains emission plus the local glow; `bloomTexture` contains the local threshold
235
+ contribution alone. Neither texture aliases the caller's target. These textures are replaced on resize or restoration.
236
+
237
+ ```ts
238
+ import {EngineKernel} from 'margoengine/core';
239
+ import {LayerCompositor} from 'margoengine/pixel';
240
+ import {EmissiveLighting2D} from 'margoengine/lighting2d/emissive';
241
+ const canvas = document.querySelector('canvas')!;
242
+ const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [640, 360]});
243
+ const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 4}});
244
+ const picture = compositor.addLayer();
245
+ const shade = compositor.addLayer({blend: 'multiply', z: 1});
246
+ const emissive = EmissiveLighting2D.attach(engine, {
247
+ target: shade.target,
248
+ camera: shade.camera,
249
+ bloom: true,
250
+ bloomThreshold: 0.8,
251
+ bloomIntensity: 1.0,
252
+ });
253
+ const orb = emissive.addSprite({x: 80, y: 45, radius: 8, glowRadius: 24, color: '#ffcc44', intensity: 2.0});
254
+ picture.write({width: 160, height: 90, data: new Uint8Array(160 * 90 * 4).fill(200)});
255
+ engine.render({delta: 1 / 60});
256
+ orb.x += 1;
257
+ ```
258
+
259
+ `connectBloom(() => new Bloom(options))` owns an unattached image effect from `@margoengine/post/bloom`, dispatches
260
+ its real `encodeImage` API on the isolated HDR emission, and presents the filtered HDR result to the target. Its factory is
261
+ called again after device restoration; the pass disposes the old effect. An attached Bloom or a `setInput` mock is not a
262
+ supported adapter. Set `bloom: false` to use only the external spatial blur, without the local glow contribution.
263
+
264
+ ```ts
265
+ import {EngineKernel} from 'margoengine/core';
266
+ import {LayerCompositor} from 'margoengine/pixel';
267
+ import {EmissiveLighting2D} from 'margoengine/lighting2d/emissive';
268
+ import {Bloom} from 'margoengine/post/bloom';
269
+ const engine = await EngineKernel.create(document.querySelector('canvas')!, {backend: 'webgpu', exactSize: [320, 180]});
270
+ const compositor = LayerCompositor.attach(engine, {camera: {width: 160, height: 90, zoom: 2}});
271
+ const shade = compositor.addLayer({blend: 'add'});
272
+ const emission = EmissiveLighting2D.attach(engine, {target: shade.target, camera: shade.camera, bloom: false});
273
+ emission.addSprite({x: 80, y: 45, radius: 3, glowRadius: 0, intensity: 3});
274
+ emission.connectBloom(() => new Bloom({threshold: 0.8, strength: 0.8}));
275
+ engine.render({delta: 0});
276
+ ```
277
+
278
+ `emissiveLightAt(sprite, x, y, layerMask, bloomIntensity, bloomThreshold)` evaluates direct emission and local glow in Node.
279
+ The effective local threshold is the larger of the sprite threshold and global threshold (default 0.8 for each).
280
+ The local glow is an analytic intensity term, not a spatial convolution; the optional Bloom adapter supplies spatial filtering.
281
+
282
+ ## CPU forms
283
+
284
+ `lightAt(light, x, y, normal)` is what a light adds at a world point, `occluderEdges(list)` the edges of a list, and
285
+ `inShadow(light, edges, x, y)` the shadow test. They run in Node, for tools and tests.
286
+
287
+ Trademark notice: names of other tools belong to their owners.
288
+
289
+ ## Textures after a device restore
290
+
291
+ `target`, `normals` and the SDF `source` and `emission` are textures you made on the engine's device. After the device is lost and restored, a
292
+ plain texture is gone with it: the pass skips that frame's work, reports one `'state'` error through `engine.onError` (help `borrowed-lost`), and
293
+ waits for a new texture. A function, such as a pixel layer's `target` getter, is read every frame and needs nothing. Hand in a new texture with
294
+ `setTarget` and `setNormals` (every entry has them; `SDFScene2D` has `source` and `emission` setters), and `SDFScene2D.encode` returns false when it
295
+ had nothing to draw.
296
+
297
+ ```ts
298
+ import {EngineKernel} from 'margoengine/core';
299
+ import {Lighting2D} from 'margoengine/lighting2d';
300
+ const canvas = document.querySelector('canvas')!;
301
+ const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [64, 64]});
302
+ const make = () => engine.gpu!.createTexture({size: [64, 64], format: 'rgba8unorm', usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING});
303
+ const lighting = Lighting2D.attach(engine, {target: make()});
304
+ engine.render({delta: 1 / 60});
305
+ await engine.rebootDevice(); // the first texture is gone with the old device
306
+ lighting.setTarget(make()); // the setter takes the engine's device as it is now
307
+ engine.render({delta: 1 / 60});
308
+ ```
309
+
310
+ ## Lifetime and scene limits
311
+
312
+ All entries are WebGPU-only and reject native WebGL2 with `code: 'unsupported'` and a help link. Each entry owns its GPU
313
+ resources, rebuilds them after device restoration or target format changes, unregisters on disposal, and allows a new pass
314
+ with the same name to attach. Submit a manually supplied command encoder before disposing its pass.
315
+
316
+ The direct-light entries (root, soft, cookie and height) share rect, circle and polygon masks, including inversion and
317
+ pass/light layer filtering. An omitted circle-mask centre is world `(0, 0)`. Mask points are uploaded every frame so mutable
318
+ polygons take effect immediately. Polygon storage is bounded by the device's `maxStorageBufferBindingSize` (16 bytes per
319
+ point). Height occluders cost 48 bytes each, emissive sprites 64 bytes each, bounded by the same limit; neither silently drops
320
+ items beyond 64. Height uniforms cost at least 256 bytes per light, bounded by `maxBufferSize`. Excess storage throws before
321
+ a draw. Soft sample counts must be integers in `[1, 64]`. Camera coordinates and zoom must be finite, with zoom above zero.
322
+
323
+ Height and emissive targets contain the current frame only, including when all lights/sprites are removed. Compose separate
324
+ lighting targets with pixel layers when combining passes. The regression suite includes native WebGL2 refusals, distinct
325
+ height light uniforms, floating volumes, lights below the receiver, 65-item scenes, frame ordering, repeated frames, target
326
+ format changes, name reuse, HDR extraction, the actual Bloom image adapter and device restoration. GI remains the exception
327
+ to the physical-correctness claims above until its known defects are resolved.
328
+
329
+ Height lights accumulate into an owned `rgba16float` image and present once to the target. This retains contributions smaller than one target byte (100 lights at intensity .001 sum to .1); the HDR image is rebuilt on resize or device restoration.
330
+
331
+ Direct-light bind groups use the current mask buffer and normal target every frame. Contiguous uniform fields are packed together; validation still checks every numeric field before rendering.
332
+
333
+ Validation errors identify the field and its allowed range, with a link to the
334
+ pixel-lighting help page. Coordinates, angles and order must be finite; radius,
335
+ dimensions, cone and falloff must also be positive. Intensity, height, glow radius,
336
+ bloom controls and soft source radius allow zero. Softness is in `[0, 1]`, samples
337
+ are integers in `[1, 64]`, and layer masks are integers in `[0, 4294967295]`.
338
+ Cookie scale is positive, offsets and rotation are finite, and mode/wrap errors
339
+ list the accepted names. Rect masks require ordered finite bounds, circles require
340
+ a non-negative radius and optional two-coordinate centre, and polygons require at
341
+ least three finite two-coordinate points. These checks apply before rendering and
342
+ in CPU helpers; changing a mutable light to an invalid value reports that field.
343
+
344
+ ```ts
345
+ import {EmissiveSprite2D, checkEmissiveSprite} from 'margoengine/lighting2d/emissive';
346
+ const sprite = new EmissiveSprite2D({radius: 8, glowRadius: 0});
347
+ sprite.glowRadius = 24;
348
+ checkEmissiveSprite(sprite); // A negative glowRadius reports "must be finite and non-negative".
349
+ ```
350
+
351
+ ## Rendering tiers
352
+
353
+ GPU attachments refuse the small `@margoengine/webgl2-compat/preview` engine during setup with linked `MargoError` code `unsupported`. Use native WebGPU, the full WebGL2 compatibility layer, or awaited [automatic escalation](../webgl2-compat/README.md#automatic-escalation). The package-tier browser regression checks refusal and escalation; the package GPU suite checks drawing on both complete tiers.