@margoengine/voxel 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.
Files changed (90) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1670 -2
  4. package/dist/bevel.d.ts +79 -0
  5. package/dist/bevel.js +453 -0
  6. package/dist/blocks-BabtpQT-.js +179 -0
  7. package/dist/blocks.d.ts +220 -0
  8. package/dist/border.d.ts +9 -0
  9. package/dist/chunk-BCoaKSn4.js +158 -0
  10. package/dist/chunk.d.ts +112 -0
  11. package/dist/codec-BmXhcsFt.js +412 -0
  12. package/dist/codec.d.ts +125 -0
  13. package/dist/codec.js +1 -0
  14. package/dist/debris.d.ts +114 -0
  15. package/dist/debris.js +387 -0
  16. package/dist/faces-DUR7LhrN.js +146 -0
  17. package/dist/faces.d.ts +7 -0
  18. package/dist/fluids.d.ts +74 -0
  19. package/dist/fluids.js +226 -0
  20. package/dist/generate.d.ts +78 -0
  21. package/dist/generate.js +99 -0
  22. package/dist/gi.d.ts +76 -0
  23. package/dist/gi.js +264 -0
  24. package/dist/gpu-mesher.d.ts +77 -0
  25. package/dist/gpu-mesher.js +461 -0
  26. package/dist/granular-mpm.d.ts +40 -0
  27. package/dist/granular-mpm.js +46 -0
  28. package/dist/index.d.ts +6 -0
  29. package/dist/index.js +4 -0
  30. package/dist/light-rgb.d.ts +71 -0
  31. package/dist/light-rgb.js +287 -0
  32. package/dist/light-worker.d.ts +84 -0
  33. package/dist/light-worker.js +110 -0
  34. package/dist/light.d.ts +108 -0
  35. package/dist/light.js +332 -0
  36. package/dist/light.worker.d.ts +1 -0
  37. package/dist/lightmap.d.ts +50 -0
  38. package/dist/lightmap.js +68 -0
  39. package/dist/lod.d.ts +87 -0
  40. package/dist/lod.js +182 -0
  41. package/dist/mesher.d.ts +214 -0
  42. package/dist/mesher.js +539 -0
  43. package/dist/mesher.worker.d.ts +1 -0
  44. package/dist/model-data-D_rIKJCQ.js +41 -0
  45. package/dist/model-data.d.ts +21 -0
  46. package/dist/model-mesh-C4Gi6bMM.js +122 -0
  47. package/dist/model-mesh.d.ts +21 -0
  48. package/dist/model-surface.d.ts +5 -0
  49. package/dist/models.d.ts +74 -0
  50. package/dist/models.js +308 -0
  51. package/dist/objects.d.ts +73 -0
  52. package/dist/objects.js +152 -0
  53. package/dist/octants-C_Ic7gdn.js +10 -0
  54. package/dist/octants.d.ts +16 -0
  55. package/dist/origin-DsMelUxs.js +23 -0
  56. package/dist/origin.d.ts +7 -0
  57. package/dist/physics.d.ts +147 -0
  58. package/dist/physics.js +486 -0
  59. package/dist/query.d.ts +166 -0
  60. package/dist/query.js +305 -0
  61. package/dist/render-post.d.ts +6 -0
  62. package/dist/render.d.ts +296 -0
  63. package/dist/render.js +1616 -0
  64. package/dist/shared/borrowed.d.ts +44 -0
  65. package/dist/smooth-CEwHkXli.js +968 -0
  66. package/dist/smooth-clip.d.ts +24 -0
  67. package/dist/smooth-lod.d.ts +118 -0
  68. package/dist/smooth-lod.js +244 -0
  69. package/dist/smooth.d.ts +171 -0
  70. package/dist/smooth.js +1 -0
  71. package/dist/stream.d.ts +201 -0
  72. package/dist/stream.js +402 -0
  73. package/dist/terrain.worker.d.ts +1 -0
  74. package/dist/textures.d.ts +86 -0
  75. package/dist/ticks.d.ts +126 -0
  76. package/dist/ticks.js +239 -0
  77. package/dist/unit-light-Ch7roJgB.js +7 -0
  78. package/dist/vox.d.ts +237 -0
  79. package/dist/vox.js +780 -0
  80. package/dist/wind-data.d.ts +13 -0
  81. package/dist/wind.d.ts +68 -0
  82. package/dist/wind.js +170 -0
  83. package/dist/worker-DlGRxlc4.js +44 -0
  84. package/dist/worker-pool-sPyC6jCE.js +93 -0
  85. package/dist/workers/light.js +1 -0
  86. package/dist/workers/mesher.js +1 -0
  87. package/dist/workers/terrain.js +1 -0
  88. package/dist/world-CelTlft2.js +153 -0
  89. package/dist/world.d.ts +117 -0
  90. package/package.json +173 -4
@@ -0,0 +1,287 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const c=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { t as e } from "./blocks-BabtpQT-.js";
5
+ import { n as t } from "./chunk-BCoaKSn4.js";
6
+ import { n, t as r } from "./world-CelTlft2.js";
7
+ import { VoxelLighting as i } from "./light.js";
8
+ import { n as a, r as o } from "./origin-DsMelUxs.js";
9
+ import { MargoError as s } from "@margoengine/math/errors";
10
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
11
+ //#region src/light-rgb.ts
12
+ var l = 40, u = (e) => `
13
+ @group(${e}) @binding(${l}) var voxelRgbVolume:texture_3d<f32>;
14
+ @group(${e}) @binding(41) var voxelRgbSampler:sampler;
15
+ struct VoxelRgbFrame {corner:vec4f,wrap:vec4f}
16
+ @group(${e}) @binding(42) var<uniform> voxelRgbWindow:VoxelRgbFrame;
17
+
18
+
19
+
20
+
21
+
22
+ fn voxelRgbLight(p:vec3f,n:vec3f,base:vec3f)->vec3f {
23
+ let size=vec3f(textureDimensions(voxelRgbVolume));let q=p+n*0.5;let l=q-voxelRgbWindow.corner.xyz;
24
+ if(any(l<vec3f(0.5))||any(l>size-vec3f(0.5))){return vec3f(0.0);}
25
+ let t=textureSampleLevel(voxelRgbVolume,voxelRgbSampler,(q+voxelRgbWindow.wrap.xyz)/size,0.0);
26
+ if(t.a<0.002){return vec3f(0.0);}
27
+ let lightness=clamp(t.rgb/t.a,vec3f(0.0),vec3f(1.0))*100.0;let cube=(lightness+16.0)/116.0;
28
+ return base*select(lightness*(27.0/24389.0),cube*cube*cube,lightness>vec3f(8.0))*voxelRgbWindow.corner.w;
29
+ }`, d = (e) => {
30
+ if (typeof e != "number" || !(e >= 0) || e === Infinity) throw RangeError(`VoxelColorLight strength is ${String(e)}; pass a finite number >= 0 such as 1`);
31
+ return e;
32
+ }, f = (e) => Array.isArray(e) && e.length === 3 && e.every((e) => typeof e == "number" && e >= 0 && e <= 1), p = class p {
33
+ #e = /* @__PURE__ */ new Map();
34
+ #t;
35
+ #n;
36
+ #r;
37
+ #i;
38
+ #a = /* @__PURE__ */ new Set();
39
+ #o;
40
+ #s;
41
+ #c = /* @__PURE__ */ new Map();
42
+ #l = !1;
43
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
44
+ return new p(e, t);
45
+ }
46
+ constructor(a, o) {
47
+ if (!a || typeof a != "object") throw TypeError("VoxelColorLight.attach expects (engine, {world})");
48
+ if (!o || !(o.world instanceof r)) throw TypeError("VoxelColorLight world must be a VoxelWorld; pass {world}");
49
+ let { world: s, colors: c = {}, budget: l = 4096, extent: u = [
50
+ 128,
51
+ 64,
52
+ 128
53
+ ], strength: p = 1 } = o;
54
+ if (!Array.isArray(u) || u.length !== 3 || !u.every((e) => Number.isInteger(e) && e >= 32 && e <= 1024 && e % 32 == 0)) throw RangeError(`VoxelColorLight extent ${u} must be three multiples of 32 from 32 to 1024`);
55
+ if (!c || typeof c != "object") throw TypeError("VoxelColorLight colors must be {name: [r, g, b]}");
56
+ for (let [e, t] of Object.entries(c)) {
57
+ if (!f(t)) throw RangeError(`VoxelColorLight color of "${e}" must be [r, g, b] in 0..1`);
58
+ this.#e.set(e, [
59
+ t[0],
60
+ t[1],
61
+ t[2]
62
+ ]);
63
+ }
64
+ this.strength = d(p), this.owner = a, this.world = s, this.#r = [
65
+ u[0],
66
+ u[1],
67
+ u[2]
68
+ ], this.#t = [
69
+ 0,
70
+ 1,
71
+ 2
72
+ ].map(() => {
73
+ let t = new e(), n = new r({
74
+ blocks: t,
75
+ minY: s.minY,
76
+ maxY: s.maxY
77
+ });
78
+ return {
79
+ blocks: t,
80
+ world: n,
81
+ lighting: i.attach(n, { budget: l })
82
+ };
83
+ }), this.#u(), this.#n = [s.onChunk((e, r, i, a) => {
84
+ for (let n of this.#t) n.world.getChunk(e, r, i) && n.world.removeChunk(e, r, i), a && n.world.addChunk(e, r, i, t.unpack({
85
+ ...a.pack(),
86
+ light: 0
87
+ }));
88
+ this.#a.add(n(e, r, i));
89
+ }), s.onChange((e, t, n, r) => {
90
+ this.world.blocks.table.length !== this.#t[0].blocks.table.length && this.#u();
91
+ for (let i of this.#t) i.world.setBlock(e, t, n, r);
92
+ })];
93
+ }
94
+ #u() {
95
+ let e = this.world.blocks.table;
96
+ this.#t.forEach((t, n) => {
97
+ for (let r = t.blocks.table.length; r < e.length; r++) {
98
+ let i = e[r];
99
+ t.blocks.define(i.name, {
100
+ layer: i.layer,
101
+ shape: i.shape,
102
+ ...i.model ? { model: i.model } : {},
103
+ solid: i.solid,
104
+ liquid: i.liquid,
105
+ light: this.#d(i, n),
106
+ opacity: i.opacity,
107
+ ...i.waterlog ? { waterlog: i.waterlog } : {}
108
+ });
109
+ }
110
+ });
111
+ }
112
+ #d(e, t) {
113
+ return Math.round(e.light * (this.#e.get(e.name)?.[t] ?? 1));
114
+ }
115
+ setColor(n, a) {
116
+ if (!f(a)) throw RangeError(`VoxelColorLight color of "${n}" must be [r, g, b] in 0..1`);
117
+ if (!this.world.blocks.table.find((e) => e.name === n)) throw RangeError(`VoxelColorLight block "${n}" is not defined; define it with blocks.define()`);
118
+ this.#e.set(n, [
119
+ a[0],
120
+ a[1],
121
+ a[2]
122
+ ]);
123
+ let o = this.#t[0].lighting.budget;
124
+ for (let e of this.#t) e.lighting.dispose();
125
+ let s = [];
126
+ this.world.onChunk((e, t, n, r) => {
127
+ r && s.push([
128
+ e,
129
+ t,
130
+ n,
131
+ r
132
+ ]);
133
+ })(), this.#t = [
134
+ 0,
135
+ 1,
136
+ 2
137
+ ].map(() => {
138
+ let t = new e(), n = new r({
139
+ blocks: t,
140
+ minY: this.world.minY,
141
+ maxY: this.world.maxY
142
+ });
143
+ return {
144
+ blocks: t,
145
+ world: n,
146
+ lighting: i.attach(n, { budget: o })
147
+ };
148
+ }), this.#u();
149
+ for (let [e, n, r, i] of s) for (let a of this.#t) a.world.addChunk(e, n, r, t.unpack({
150
+ ...i.pack(),
151
+ light: 0
152
+ }));
153
+ }
154
+ levels(e, t, n) {
155
+ return this.#t.map((r) => r.lighting.blockLight(e, t, n));
156
+ }
157
+ update() {
158
+ if (this.#l) throw new s("disposed", "VoxelColorLight is disposed; attach a new one");
159
+ d(this.strength), this.world.blocks.table.length !== this.#t[0].blocks.table.length && this.#u();
160
+ let e = 0;
161
+ for (let t of this.#t) {
162
+ e += t.lighting.update();
163
+ for (let e of t.world.dirty) this.#a.add(e);
164
+ t.world.dirty.clear();
165
+ }
166
+ let t = c(this.owner).gpu;
167
+ return t && this.#f(t), e;
168
+ }
169
+ #f(e) {
170
+ let [t, r, i] = this.#r, s = this.#o;
171
+ if (!s || s.device !== e) {
172
+ s?.texture.destroy(), s?.window.destroy();
173
+ let n = e.createTexture({
174
+ size: [
175
+ t,
176
+ r,
177
+ i
178
+ ],
179
+ dimension: "3d",
180
+ format: "rgba8unorm",
181
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
182
+ label: "voxel coloured light"
183
+ }), a = e.createSampler({
184
+ magFilter: "linear",
185
+ minFilter: "linear",
186
+ addressModeU: "repeat",
187
+ addressModeV: "repeat",
188
+ addressModeW: "repeat"
189
+ }), o = e.createBuffer({
190
+ size: 32,
191
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
192
+ });
193
+ s = this.#o = {
194
+ device: e,
195
+ texture: n,
196
+ sampler: a,
197
+ window: o,
198
+ entries: [
199
+ {
200
+ binding: l,
201
+ resource: n.createView()
202
+ },
203
+ {
204
+ binding: 41,
205
+ resource: a
206
+ },
207
+ {
208
+ binding: 42,
209
+ resource: { buffer: o }
210
+ }
211
+ ]
212
+ }, this.#i = void 0;
213
+ }
214
+ let c = a(this.#s?.origin, "VoxelColorLight"), u = this.owner.camera.position, d = [
215
+ u[0] + c[0],
216
+ u[1] + c[1],
217
+ u[2] + c[2]
218
+ ], f = [
219
+ Math.floor(d[0] / 32) - (t >> 6),
220
+ Math.floor(d[1] / 32) - (r >> 6),
221
+ Math.floor(d[2] / 32) - (i >> 6)
222
+ ], p = this.#i, m = (e, n, a, o) => n >= e[0] && a >= e[1] && o >= e[2] && n < e[0] + t / 32 && a < e[1] + r / 32 && o < e[2] + i / 32;
223
+ if (!p || p.some((e, t) => e !== f[t])) {
224
+ for (let e = f[2]; e < f[2] + i / 32; e++) for (let i = f[1]; i < f[1] + r / 32; i++) for (let r = f[0]; r < f[0] + t / 32; r++) (!p || !m(p, r, i, e)) && this.#a.add(n(r, i, e));
225
+ this.#i = f;
226
+ }
227
+ e.queue.writeBuffer(s.window, 0, Float32Array.of(f[0] * 32 - c[0], f[1] * 32 - c[1], f[2] * 32 - c[2], this.strength, o(c[0], t), o(c[1], r), o(c[2], i), 0));
228
+ let h = /* @__PURE__ */ new Uint8Array(131072), g = this.world.blocks.table;
229
+ for (let n of this.#a) {
230
+ let [a, o, c] = n.split(",").map(Number);
231
+ if (!m(f, a, o, c)) continue;
232
+ let l = this.world.getChunk(a, o, c), u = this.#t[0].world.getChunk(a, o, c), d = this.#t[1].world.getChunk(a, o, c), p = this.#t[2].world.getChunk(a, o, c);
233
+ if (h.fill(0), l && u && d && p) for (let e = 0, t = 0; e < 32; e++) for (let n = 0; n < 32; n++) for (let r = 0; r < 32; r++, t += 4) {
234
+ let i = g[l.get(r, e, n) & 65535];
235
+ i && i.layer === "opaque" && i.shape === "cube" || (h[t] = (u.getLight(r, e, n) & 15) * 17, h[t + 1] = (d.getLight(r, e, n) & 15) * 17, h[t + 2] = (p.getLight(r, e, n) & 15) * 17, h[t + 3] = 255);
236
+ }
237
+ let _ = new Uint8Array(h.length);
238
+ for (let e = 0; e < 32; e++) for (let t = 0; t < 32; t++) _.set(h.subarray((e * 32 + t) * 128, (e * 32 + t + 1) * 128), (t * 32 + e) * 128);
239
+ e.queue.writeTexture({
240
+ texture: s.texture,
241
+ origin: [
242
+ (a * 32 % t + t) % t,
243
+ (o * 32 % r + r) % r,
244
+ (c * 32 % i + i) % i
245
+ ]
246
+ }, _, {
247
+ bytesPerRow: 128,
248
+ rowsPerImage: 32
249
+ }, [
250
+ 32,
251
+ 32,
252
+ 32
253
+ ]);
254
+ }
255
+ this.#a.clear();
256
+ }
257
+ add(e) {
258
+ let t = e.addLighting(this);
259
+ return this.#s = e, () => {
260
+ t(), this.#s === e && (this.#s = void 0);
261
+ };
262
+ }
263
+ pbr(e) {
264
+ if (!this.#o || this.#l) return;
265
+ let t = this.#c.get(e);
266
+ return t || (t = {
267
+ declarations: u(e),
268
+ light: "voxelRgbLight(i.position,s.n,s.base.rgb)"
269
+ }, this.#c.set(e, t)), t;
270
+ }
271
+ bindings() {
272
+ return this.#o?.entries ?? [];
273
+ }
274
+ dispose() {
275
+ if (!this.#l) {
276
+ this.#l = !0;
277
+ for (let e of this.#n) e();
278
+ for (let e of this.#t) e.lighting.dispose();
279
+ this.#o?.texture.destroy(), this.#o?.window.destroy(), this.#o = void 0;
280
+ }
281
+ }
282
+ [Symbol.dispose]() {
283
+ this.dispose();
284
+ }
285
+ };
286
+ //#endregion
287
+ export { p as VoxelColorLight };
@@ -0,0 +1,84 @@
1
+ import type { BlockType } from './blocks.js';
2
+ import { type VoxelChunk } from './chunk.js';
3
+ import { VoxelWorld } from './world.js';
4
+ /** Options of {@link VoxelLightWorker.attach}. */
5
+ export interface VoxelLightWorkerOptions {
6
+ /**
7
+ * The worker to run, for tests and bundlers that cannot follow `new URL(..., import.meta.url)`. Default the bundled
8
+ * `dist/workers/light.js`.
9
+ */
10
+ worker?: Worker;
11
+ }
12
+ /** A batch for the worker, in the order things happened on the page. */
13
+ export interface LightJob {
14
+ init?: {
15
+ minY: number;
16
+ maxY: number;
17
+ };
18
+ /** Block types defined since the last batch (all of them in the first). */
19
+ types?: readonly BlockType[];
20
+ /** Chunk loads (packed blocks, light dropped) and unloads (`chunk` undefined), in order. */
21
+ chunks: {
22
+ cx: number;
23
+ cy: number;
24
+ cz: number;
25
+ generation: number;
26
+ chunk?: ReturnType<VoxelChunk['pack']>;
27
+ }[];
28
+ /** Edits since the last batch: x, y, z, state per edit. */
29
+ edits: Int32Array;
30
+ /** Number of this batch. */
31
+ batch: number;
32
+ }
33
+ /** The worker's answer to a batch: light of the chunks it changed. */
34
+ export interface LightReply {
35
+ batch: number;
36
+ /** Light of every chunk whose light, or one-cell shell, may have changed (remesh them). */
37
+ chunks: {
38
+ cx: number;
39
+ cy: number;
40
+ cz: number;
41
+ generation: number;
42
+ light: number | Uint8Array;
43
+ }[];
44
+ /** Heightmaps of the columns of those chunks: cx, cz and 1,024 int16 heights. */
45
+ columns: {
46
+ cx: number;
47
+ cz: number;
48
+ heights: Int16Array;
49
+ }[];
50
+ }
51
+ /**
52
+ * Sky and block light like `VoxelLighting` (`@margoengine/voxel/light`), computed in a Web Worker: the same levels, the
53
+ * same rules, written into the same light bytes, so a renderer and mesher see no difference, but a roof removed or a
54
+ * chunk loaded costs the page only the copies. Light arrives a frame or more after the change.
55
+ */
56
+ export declare class VoxelLightWorker {
57
+ #private;
58
+ readonly world: VoxelWorld;
59
+ /**
60
+ * Starts the worker and gives it the chunks loaded now; later loads, unloads and edits follow.
61
+ * @throws TypeError for a wrong world or options.
62
+ * @throws MargoError `unsupported` without Web Workers, `attached` when the world already has one.
63
+ */
64
+ static attach(world: VoxelWorld, options?: VoxelLightWorkerOptions): VoxelLightWorker;
65
+ private constructor();
66
+ /** True while the worker has changes it has not answered yet. */
67
+ get busy(): boolean;
68
+ /**
69
+ * Sends the edits and chunk loads since the last call to the worker, and writes the light it has finished into the
70
+ * world's chunks (a chunk unloaded or loaded again since is skipped), adding them to `world.dirty`. Call it once a
71
+ * frame. Returns the chunks written.
72
+ * @throws MargoError `disposed` after `dispose()`; the worker's error once it failed.
73
+ */
74
+ update(): number;
75
+ /**
76
+ * Resolves once the worker has answered every change made so far (call {@link VoxelLightWorker.update} after it to
77
+ * write the light), for loading screens and tests.
78
+ * @throws MargoError `disposed` after `dispose()`.
79
+ */
80
+ settled(signal?: AbortSignal): Promise<void>;
81
+ /** Stops the worker and following the world. Light already written stays. */
82
+ dispose(): void;
83
+ [Symbol.dispose](): void;
84
+ }
@@ -0,0 +1,110 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import { l as e } from "./chunk-BCoaKSn4.js";
5
+ import { n as t, t as n } from "./world-CelTlft2.js";
6
+ import { MargoError as r } from "@margoengine/math/errors";
7
+ //#region src/light-worker.ts
8
+ var i = /* @__PURE__ */ new WeakSet(), a = class a {
9
+ #e;
10
+ #t = [];
11
+ #n = [];
12
+ #r = [];
13
+ #i = [];
14
+ #a = /* @__PURE__ */ new Map();
15
+ #o = 0;
16
+ #s = 0;
17
+ #c = 0;
18
+ #l = 0;
19
+ #u;
20
+ #d = [];
21
+ #f = !1;
22
+ static attach(e, t = {}) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
23
+ return new a(e, t);
24
+ }
25
+ constructor(e, t) {
26
+ if (!(e instanceof n)) throw TypeError("VoxelLightWorker.attach expects a VoxelWorld; pass new VoxelWorld({blocks})");
27
+ if (!t || typeof t != "object") throw TypeError("VoxelLightWorker options must be an object");
28
+ if (t.worker !== void 0 && typeof t.worker?.postMessage != "function") throw TypeError("VoxelLightWorker worker must be a Worker; leave it out for the bundled one");
29
+ if (!t.worker && typeof Worker != "function") throw new r("unsupported", "VoxelLightWorker needs Web Workers; use VoxelLighting from @margoengine/voxel/light on this thread");
30
+ if (i.has(e)) throw new r("attached", "VoxelWorld already has a VoxelLightWorker; dispose() it before attaching another");
31
+ i.add(e), this.world = e, this.#e = t.worker ?? new Worker(new URL("./workers/light.js?no-inline",
32
+ import.meta.url
33
+ ), { name: "margoengine-light" }), this.#e.onmessage = ({ data: e }) => {
34
+ if (e?.error) this.#h(Object.assign(Error(e.error.message), { name: e.error.name }));
35
+ else if (e?.result && (this.#i.push(e.result), this.#l = e.result.batch, this.#l === this.#s)) for (let e of this.#d.splice(0)) e();
36
+ }, this.#e.onerror = (e) => {
37
+ e.preventDefault?.(), this.#h(new r("failed", `VoxelLightWorker worker failed: ${e.message}; check the worker URL`));
38
+ }, this.#t.push(e.onChunk((e, t, n, r) => this.#p(e, t, n, r)), e.onChange((e, t, n, r) => this.#r.push(e, t, n, r))), this.#m({
39
+ minY: e.minY,
40
+ maxY: e.maxY
41
+ });
42
+ }
43
+ #p(e, n, r, i) {
44
+ let a = ++this.#o, o = t(e, n, r);
45
+ i ? this.#a.set(o, a) : this.#a.delete(o), this.#r.length && this.#m();
46
+ let s = i?.pack();
47
+ s && (s.light = 0), this.#n.push({
48
+ cx: e,
49
+ cy: n,
50
+ cz: r,
51
+ generation: a,
52
+ chunk: s
53
+ });
54
+ }
55
+ #m(e) {
56
+ let t = this.world.blocks.table;
57
+ if (!e && !this.#n.length && !this.#r.length && this.#c === t.length) return;
58
+ let n = {
59
+ chunks: this.#n,
60
+ edits: Int32Array.from(this.#r),
61
+ batch: ++this.#s
62
+ };
63
+ e && (n.init = e), this.#c !== t.length && (n.types = t.slice(this.#c)), this.#c = t.length, this.#n = [], this.#r.length = 0;
64
+ let r = [n.edits.buffer];
65
+ for (let { chunk: e } of n.chunks) e && r.push(e.palette.buffer, e.words.buffer);
66
+ this.#e.postMessage(n, r);
67
+ }
68
+ #h(e) {
69
+ this.#u ??= e;
70
+ for (let e of this.#d.splice(0)) e();
71
+ }
72
+ get busy() {
73
+ return this.#l !== this.#s || this.#r.length > 0 || this.#n.length > 0;
74
+ }
75
+ update() {
76
+ if (this.#f) throw new r("disposed", "VoxelLightWorker is disposed; attach a new one");
77
+ if (this.#u) throw this.#u;
78
+ this.#m();
79
+ let n = 0;
80
+ for (let r of this.#i.splice(0)) {
81
+ for (let { cx: i, cy: a, cz: o, generation: s, light: c } of r.chunks) {
82
+ let r = t(i, a, o), l = this.world.getChunk(i, a, o);
83
+ l && this.#a.get(r) === s && (e(l, c), this.world.dirty.add(r), n++);
84
+ }
85
+ for (let { cx: e, cz: t, heights: n } of r.columns) this.world.heightmap(e, t)?.set(n);
86
+ }
87
+ return n;
88
+ }
89
+ async settled(e) {
90
+ if (this.#f) throw new r("disposed", "VoxelLightWorker is disposed; attach a new one");
91
+ if (this.#m(), e?.throwIfAborted(), this.#l !== this.#s && !this.#u && await new Promise((t, n) => {
92
+ let r = () => n(e?.reason);
93
+ e?.addEventListener("abort", r, { once: !0 }), this.#d.push(() => {
94
+ e?.removeEventListener("abort", r), t();
95
+ });
96
+ }), this.#u) throw this.#u;
97
+ }
98
+ dispose() {
99
+ if (!this.#f) {
100
+ this.#f = !0;
101
+ for (let e of this.#t) e();
102
+ this.#e.terminate(), i.delete(this.world), this.#h(new r("disposed", "VoxelLightWorker is disposed; attach a new one"));
103
+ }
104
+ }
105
+ [Symbol.dispose]() {
106
+ this.dispose();
107
+ }
108
+ };
109
+ //#endregion
110
+ export { a as VoxelLightWorker };
@@ -0,0 +1,108 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import { VoxelWorld } from './world.js';
3
+ /** Brightest light level: sky light under open sky, and the most a block type can emit. */
4
+ export declare const MAX_LIGHT = 15;
5
+ /** Options of {@link VoxelLighting.attach}. */
6
+ export interface VoxelLightingOptions {
7
+ /** Most cells one {@link VoxelLighting.update} call processes (an integer >= 1, or Infinity). Default 4096. */
8
+ budget?: number;
9
+ }
10
+ /**
11
+ * Sky and block light of a {@link VoxelWorld}, kept in its chunks' light bytes (sky light in the high nibble, block
12
+ * light in the low). Sky light is {@link MAX_LIGHT} in every cell above its column's heightmap (the highest cell with
13
+ * opacity > 0, or a slab or stair) and spreads from there; block light spreads from each block type's `light`. Each step
14
+ * to a neighbour costs 1 plus the entered cell's `opacity`, across chunk borders. Slabs and stairs pass light through
15
+ * their open part: light does not cross a face their boxes cover whole (a slab's bottom, a stair's back), and one whose
16
+ * top is open is lit as open sky when it tops its column. Edits and chunk loads are queued as they happen and
17
+ * {@link VoxelLighting.update} (call it once a frame) works through at most `budget` cells, so big changes spread over
18
+ * frames. Chunks whose light changed, and loaded neighbours whose border shell holds a changed cell, go into
19
+ * `world.dirty`. A removed chunk's cells keep their heights in the heightmap, so caves stay dark when the chunks above
20
+ * them unload; light that reached other chunks through it goes.
21
+ * Breadth-first flood fill (textbook); 4-bit levels 0-15 are a common block-game design choice.
22
+ */
23
+ export declare class VoxelLighting {
24
+ private readonly world;
25
+ private limit;
26
+ private flags;
27
+ private parts;
28
+ private wet;
29
+ private types;
30
+ private disposed;
31
+ private readonly sections;
32
+ private readonly columns;
33
+ private readonly loads;
34
+ private loadHead;
35
+ private readonly edits;
36
+ private editHead;
37
+ private readonly addS;
38
+ private readonly addI;
39
+ private addHead;
40
+ private readonly cutS;
41
+ private readonly cutE;
42
+ private cutHead;
43
+ private readonly touched;
44
+ private j;
45
+ private readonly offChange;
46
+ private readonly offChunk;
47
+ /**
48
+ * Lights `world`: queues every loaded chunk now and each chunk load, removal and light-relevant edit from then on.
49
+ * Light bytes already in added chunks are recomputed. Run {@link VoxelLighting.update} to apply the queue.
50
+ * @throws TypeError when `world` is not a VoxelWorld or `budget` is not a number.
51
+ * @throws RangeError when `budget` is not an integer >= 1 or Infinity.
52
+ * @throws MargoError `'attached'` when another VoxelLighting lights `world`.
53
+ */
54
+ static attach(world: VoxelWorld, options?: VoxelLightingOptions): VoxelLighting;
55
+ private constructor();
56
+ /**
57
+ * Most cells one {@link VoxelLighting.update} call processes: an integer >= 1, or Infinity to finish every queued
58
+ * change in one call. A chunk load is never split; it counts the cells it lights plus an eighth of those it scans
59
+ * (about 130 for open sky beside open sky, up to about 13,000 for mixed blocks with emitters). Raise it while a
60
+ * loading screen is up.
61
+ * @throws TypeError for a non-number. @throws RangeError unless it is an integer >= 1 or Infinity.
62
+ */
63
+ get budget(): number;
64
+ set budget(value: number);
65
+ /**
66
+ * Sky light (0-15) of cell (x, y, z). An unloaded cell reads {@link MAX_LIGHT} above its column's heightmap (or in
67
+ * a column with no loaded chunk) and 0 below it.
68
+ * @throws RangeError (TypeError for non-numbers) when a coordinate is not a 32-bit integer.
69
+ */
70
+ skyLight(x: number, y: number, z: number): number;
71
+ /**
72
+ * Block light (0-15) of cell (x, y, z); 0 for an unloaded cell.
73
+ * @throws RangeError (TypeError for non-numbers) when a coordinate is not a 32-bit integer.
74
+ */
75
+ blockLight(x: number, y: number, z: number): number;
76
+ /**
77
+ * Applies queued chunk loads and removals, then edits, then spreads and removes light, stopping once `budget`
78
+ * cells are processed; marks the chunks whose light changed in `world.dirty`. Call it once a frame. Returns the
79
+ * cells processed: 0 when the light is up to date.
80
+ * @throws MargoError `'disposed'` after {@link VoxelLighting.dispose}.
81
+ */
82
+ update(): number;
83
+ /** Stops following the world's changes and drops queued work; the light bytes stay as they are. */
84
+ dispose(): void;
85
+ [Symbol.dispose]: () => void;
86
+ private chunkAt;
87
+ private refresh;
88
+ private state;
89
+ private shut;
90
+ private top;
91
+ private cover;
92
+ private light;
93
+ private put;
94
+ private push;
95
+ private cut;
96
+ private near;
97
+ private relax;
98
+ private spread;
99
+ private unspread;
100
+ private clear;
101
+ private pull;
102
+ private shade;
103
+ private open;
104
+ private edit;
105
+ private load;
106
+ private unload;
107
+ private flush;
108
+ }