@margoengine/lighting2d 0.0.0-stage → 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/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +352 -2
- package/dist/cookie.d.ts +104 -0
- package/dist/cookie.js +701 -0
- package/dist/emissive.d.ts +135 -0
- package/dist/emissive.js +345 -0
- package/dist/gi.d.ts +144 -0
- package/dist/gi.js +546 -0
- package/dist/height.d.ts +115 -0
- package/dist/height.js +411 -0
- package/dist/index.d.ts +192 -0
- package/dist/index.js +1 -0
- package/dist/masks.d.ts +11 -0
- package/dist/resources-Cskg0FqE.js +118 -0
- package/dist/resources.d.ts +10 -0
- package/dist/sdf-shader.d.ts +2 -0
- package/dist/sdf.d.ts +68 -0
- package/dist/sdf.js +234 -0
- package/dist/shared/texture-option.d.ts +14 -0
- package/dist/soft.d.ts +85 -0
- package/dist/soft.js +375 -0
- package/dist/src-8W7SHUG7.js +539 -0
- package/dist/validation.d.ts +10 -0
- package/package.json +79 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Scott Campbell
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,353 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @margoengine/lighting2d
|
|
2
2
|
|
|
3
|
-
|
|
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.
|