@margoengine/voxel-edit 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 (64) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +445 -2
  4. package/dist/animation.d.ts +50 -0
  5. package/dist/animation.js +88 -0
  6. package/dist/assist.d.ts +24 -0
  7. package/dist/assist.js +52 -0
  8. package/dist/brush-gpu.d.ts +62 -0
  9. package/dist/bytes.d.ts +55 -0
  10. package/dist/collab.d.ts +77 -0
  11. package/dist/collab.js +159 -0
  12. package/dist/edit.d.ts +30 -0
  13. package/dist/edit.js +361 -0
  14. package/dist/export.d.ts +58 -0
  15. package/dist/export.js +52 -0
  16. package/dist/file-colors-DHT5vrzW.js +55 -0
  17. package/dist/file-colors.d.ts +16 -0
  18. package/dist/format-plist.d.ts +4 -0
  19. package/dist/formats-extra.d.ts +20 -0
  20. package/dist/formats-extra.js +335 -0
  21. package/dist/formats.d.ts +96 -0
  22. package/dist/formats.js +924 -0
  23. package/dist/generate.d.ts +63 -0
  24. package/dist/generate.js +103 -0
  25. package/dist/gox.d.ts +60 -0
  26. package/dist/gpu.d.ts +74 -0
  27. package/dist/gpu.js +167 -0
  28. package/dist/grid-B2V0TGLV.js +120 -0
  29. package/dist/grid.d.ts +75 -0
  30. package/dist/history.d.ts +65 -0
  31. package/dist/history.js +75 -0
  32. package/dist/index.d.ts +5 -0
  33. package/dist/index.js +631 -0
  34. package/dist/layout.d.ts +76 -0
  35. package/dist/library.d.ts +50 -0
  36. package/dist/library.js +89 -0
  37. package/dist/mesh.d.ts +128 -0
  38. package/dist/mesh.js +365 -0
  39. package/dist/model.d.ts +173 -0
  40. package/dist/pick.d.ts +34 -0
  41. package/dist/pick.js +122 -0
  42. package/dist/raster.d.ts +89 -0
  43. package/dist/rig.d.ts +88 -0
  44. package/dist/rig.js +216 -0
  45. package/dist/select.d.ts +50 -0
  46. package/dist/select.js +94 -0
  47. package/dist/shaders-BaY4gcm9.js +234 -0
  48. package/dist/shaders.d.ts +116 -0
  49. package/dist/shaders.js +1 -0
  50. package/dist/slices.d.ts +75 -0
  51. package/dist/smooth.d.ts +43 -0
  52. package/dist/smooth.js +212 -0
  53. package/dist/sparse.d.ts +239 -0
  54. package/dist/sparse.js +646 -0
  55. package/dist/stamp.d.ts +88 -0
  56. package/dist/vmax.d.ts +48 -0
  57. package/dist/vox-resolve.d.ts +64 -0
  58. package/dist/vox-scene.d.ts +51 -0
  59. package/dist/vox.d.ts +30 -0
  60. package/dist/vox.js +684 -0
  61. package/dist/voxelize.d.ts +70 -0
  62. package/dist/voxelize.js +249 -0
  63. package/dist/vxm.d.ts +54 -0
  64. package/package.json +130 -4
@@ -0,0 +1,63 @@
1
+ import { type GridLimits, type VoxelGrid } from './grid.js';
2
+ /** Row-major, top-left image. One byte per grey sample or four straight RGBA8 bytes per pixel. */
3
+ export interface VoxelImage {
4
+ /** Positive integer width in pixels. */
5
+ width: number;
6
+ /** Positive integer height in pixels. */
7
+ height: number;
8
+ /** Grey8 or RGBA8 samples; the length determines the layout. */
9
+ data: Uint8Array | Uint8ClampedArray;
10
+ }
11
+ /** An owned grid and its palette, index 0 reserved for air. */
12
+ export interface GeneratedVoxels {
13
+ /** Y-up cells. */
14
+ grid: VoxelGrid;
15
+ /** 256 RGBA8 entries, index i at 4*i. */
16
+ palette: Uint8Array;
17
+ /** True if more than 255 colours required deterministic low-bit reduction. */
18
+ colorsReduced: boolean;
19
+ }
20
+ /** Image column generation options. */
21
+ export interface HeightmapOptions extends GridLimits {
22
+ /** Maximum column height in whole cells. Default 32. Black is zero; white is this height. */
23
+ height?: number;
24
+ /** Height source for RGBA; grey input always uses its sample. Default 'luma' (BT.709 encoded RGB). */
25
+ channel?: 'luma' | 'red' | 'green' | 'blue' | 'alpha';
26
+ /** RGBA samples at or below this alpha are air (grey samples have no alpha). Default 0. */
27
+ alphaThreshold?: number;
28
+ /** Invert the height sample before scaling. Default false. */
29
+ invert?: boolean;
30
+ /** Cancellation checked before allocation and each image row. */
31
+ signal?: AbortSignal;
32
+ }
33
+ /**
34
+ * Columns along Y, image columns along X and top-to-bottom rows along Z. Heights round to the nearest cell;
35
+ * RGBA columns retain their source colour. The image is unchanged.
36
+ * @throws RangeError for invalid dimensions, channels, thresholds or cell budgets; pass valid image options.
37
+ */
38
+ export declare function heightmapToVoxels(image: VoxelImage, options?: HeightmapOptions): GeneratedVoxels;
39
+ /** Text rasterization and mask extrusion options. */
40
+ export interface TextVoxelOptions extends GridLimits {
41
+ /** CSS canvas font, including pixel size and family. Required; fonts must already be loaded. */
42
+ font: string;
43
+ /** Extrusion along positive Z, in cells. Default 1. */
44
+ depth?: number;
45
+ /** Coverage must exceed this byte to fill a cell. Default 127. */
46
+ alphaThreshold?: number;
47
+ /** Filled RGBA8 colour. Default [255, 255, 255, 255]. */
48
+ color?: readonly [number, number, number, number];
49
+ /** Baseline distance for multiline text in pixels. Default measured font height times 1.2. */
50
+ lineHeight?: number;
51
+ /** Canvas context to use, resized and cleared. Default a new offscreen canvas or DOM canvas at call time. */
52
+ context?: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
53
+ /** Cancellation checked before rasterization and each image row. */
54
+ signal?: AbortSignal;
55
+ }
56
+ /**
57
+ * Rasterizes Unicode text using the supplied CSS font, crops to ink bounds and extrudes the mask into Z.
58
+ * Font shaping and ligatures use the platform text engine; await FontFace.load() before calling for custom fonts.
59
+ * A blank string yields one empty cell. No browser objects are accessed on import.
60
+ * @throws TypeError without a canvas 2D context; provide options.context in hosts without Canvas.
61
+ * @throws RangeError for invalid font, extrusion, colour, line spacing or budget; pass valid text options.
62
+ */
63
+ export declare function textToVoxels(text: string, options: TextVoxelOptions): GeneratedVoxels;
@@ -0,0 +1,103 @@
1
+ import { a as e, g as t, l as n, o as r } from "./grid-B2V0TGLV.js";
2
+ import { r as i, t as a } from "./file-colors-DHT5vrzW.js";
3
+ //#region src/generate.ts
4
+ function o(e, t) {
5
+ if (!Number.isSafeInteger(e) || e < 1) throw RangeError(`${t} must be a positive integer; pass whole cells`);
6
+ return e;
7
+ }
8
+ function s(e) {
9
+ if (!Number.isInteger(e) || e < 0 || e > 255) throw RangeError("alphaThreshold must be 0 to 255; pass an RGBA8 alpha");
10
+ return e;
11
+ }
12
+ function c(e, r) {
13
+ if (n(e, "image"), t([
14
+ e.width,
15
+ 1,
16
+ e.height
17
+ ], r, "image"), !(e.data instanceof Uint8Array || e.data instanceof Uint8ClampedArray)) throw TypeError("image data must hold bytes; pass Grey8 or RGBA8 samples");
18
+ let i = e.data.length / (e.width * e.height);
19
+ if (i !== 1 && i !== 4) throw RangeError("image data length does not match its dimensions; pass Grey8 or RGBA8 samples");
20
+ return i;
21
+ }
22
+ function l(t, l = {}) {
23
+ n(l, "heightmapToVoxels"), l.signal?.throwIfAborted();
24
+ let u = r(l), d = c(t, u), f = o(l.height ?? 32, "height"), p = s(l.alphaThreshold ?? 0), m = l.channel ?? "luma", h = l.invert ?? !1;
25
+ if (![
26
+ "luma",
27
+ "red",
28
+ "green",
29
+ "blue",
30
+ "alpha"
31
+ ].includes(m)) throw RangeError("height channel is unknown; use luma, red, green, blue or alpha");
32
+ if (typeof h != "boolean") throw TypeError("invert must be boolean; pass true or false");
33
+ let g = [
34
+ t.width,
35
+ f,
36
+ t.height
37
+ ], _ = new a(u), v = _.add(g, [
38
+ 0,
39
+ 0,
40
+ 0
41
+ ], void 0, "heightmap");
42
+ for (let n = 0; n < t.height; n++) {
43
+ l.signal?.throwIfAborted();
44
+ for (let r = 0; r < t.width; r++) {
45
+ let a = (r + n * t.width) * d, o = t.data[a], s = d === 1 ? o : t.data[a + 1], c = d === 1 ? o : t.data[a + 2], l = d === 1 ? 255 : t.data[a + 3];
46
+ if (d === 4 && l <= p) continue;
47
+ let u = d === 1 ? o : m === "luma" ? .2126 * o + .7152 * s + .0722 * c : m === "red" ? o : m === "green" ? s : m === "blue" ? c : l, _ = Math.round((h ? 255 - u : u) * f / 255), y = i(o, s, c, l);
48
+ for (let t = 0; t < _; t++) v[e(g, r, t, n)] = y;
49
+ }
50
+ }
51
+ let y = _.finish();
52
+ return {
53
+ grid: y.models[0].grid,
54
+ palette: y.palette,
55
+ colorsReduced: y.colorsReduced
56
+ };
57
+ }
58
+ function u(i, a) {
59
+ if (n(a, "textToVoxels"), a.signal?.throwIfAborted(), typeof i != "string" || typeof a.font != "string" || !a.font.trim()) throw TypeError("text and font must be strings; pass text and a CSS font with size and family");
60
+ let c = r(a), l = o(a.depth ?? 1, "depth"), u = s(a.alphaThreshold ?? 127), d = a.color ?? [
61
+ 255,
62
+ 255,
63
+ 255,
64
+ 255
65
+ ];
66
+ if (d.length !== 4 || !Array.from(d).every((e) => Number.isInteger(e) && e >= 0 && e <= 255) || !d[3]) throw RangeError("text colour must be nontransparent RGBA8; pass four bytes with positive alpha");
67
+ let f = a.context?.canvas ?? (typeof OffscreenCanvas < "u" ? new OffscreenCanvas(1, 1) : typeof document < "u" ? document.createElement("canvas") : void 0), p = a.context ?? f?.getContext("2d");
68
+ if (!f || !p) throw TypeError("text needs Canvas 2D; provide a context or use a browser with Canvas");
69
+ f.width = f.height = 1;
70
+ let m = () => {
71
+ p.font = "1px serif", p.font = a.font, p.textAlign = "left", p.textBaseline = "alphabetic";
72
+ };
73
+ if (m(), p.font === "1px serif" && a.font !== "1px serif") throw RangeError("font is not a valid canvas font; include a size such as 16px and a family");
74
+ let h = p.measureText("Mg"), g = i.split(/\r\n|\r|\n/), _ = a.lineHeight ?? Math.max(1, h.actualBoundingBoxAscent + h.actualBoundingBoxDescent) * 1.2;
75
+ if (!Number.isFinite(_) || _ <= 0) throw RangeError("lineHeight must be positive; pass pixel spacing");
76
+ let v = Infinity, y = -Infinity, b = Infinity, x = -Infinity;
77
+ g.forEach((e, t) => {
78
+ let n = p.measureText(e);
79
+ n.actualBoundingBoxLeft + n.actualBoundingBoxRight <= 0 || n.actualBoundingBoxAscent + n.actualBoundingBoxDescent <= 0 || (v = Math.min(v, -n.actualBoundingBoxLeft), y = Math.max(y, n.actualBoundingBoxRight), b = Math.min(b, t * _ - n.actualBoundingBoxAscent), x = Math.max(x, t * _ + n.actualBoundingBoxDescent));
80
+ }), v === Infinity && (v = y = b = x = 0), v = Math.floor(v), b = Math.floor(b);
81
+ let S = Math.max(1, Math.ceil(y) - v), C = Math.max(1, Math.ceil(x) - b), w = [
82
+ S,
83
+ C,
84
+ l
85
+ ], T = new Uint8Array(t(w, c, "text"));
86
+ f.width = S, f.height = C, m(), p.fillStyle = "#fff", g.forEach((e, t) => p.fillText(e, -v, t * _ - b));
87
+ let E = p.getImageData(0, 0, S, C).data;
88
+ for (let t = 0; t < C; t++) {
89
+ a.signal?.throwIfAborted();
90
+ for (let n = 0; n < S; n++) if (E[(t * S + n) * 4 + 3] > u) for (let r = 0; r < l; r++) T[e(w, n, C - 1 - t, r)] = 1;
91
+ }
92
+ let D = /* @__PURE__ */ new Uint8Array(1024);
93
+ return D.set(d, 4), {
94
+ grid: {
95
+ size: w,
96
+ voxels: T
97
+ },
98
+ palette: D,
99
+ colorsReduced: !1
100
+ };
101
+ }
102
+ //#endregion
103
+ export { l as heightmapToVoxels, u as textToVoxels };
package/dist/gox.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ import type { Vec3 } from '@margoengine/math';
2
+ import type { VoxelFile, VoxelFileModel } from './formats.js';
3
+ import { type GridLimits } from './grid.js';
4
+ /** One layer of a `.gox` file, as a model. */
5
+ export interface GOXLayer extends VoxelFileModel {
6
+ /** The layer's `visible` flag; true when the file leaves it out. */
7
+ visible: boolean;
8
+ /** Blend mode stored in the file: 0 over, 1 and 2 subtract, 3 paint, 4 max, 5 and 6 intersect, 7 multiply, 8 replace. */
9
+ mode: number;
10
+ /** Index into {@link GOXFile.materials}, or -1 when the file names no material that exists. */
11
+ material: number;
12
+ }
13
+ /** One `MATE` chunk of a `.gox` file. */
14
+ export interface GOXMaterial {
15
+ name: string;
16
+ /** Base colour, linear RGBA 0 to 1. */
17
+ color: readonly [number, number, number, number];
18
+ metallic: number;
19
+ roughness: number;
20
+ /** Emitted colour, linear RGB. */
21
+ emission: Vec3;
22
+ }
23
+ /** What {@link parseGOX} returns. */
24
+ export interface GOXFile extends VoxelFile {
25
+ /** Layers in file order, clone and shape layers already built. */
26
+ models: GOXLayer[];
27
+ /** Materials in file order. */
28
+ materials: GOXMaterial[];
29
+ /** The file's version, 1 or 2. */
30
+ version: number;
31
+ }
32
+ /** A model for {@link writeGOX}: any {@link VoxelFileModel}, with an optional `visible` (default true). */
33
+ export interface GOXWriteModel extends VoxelFileModel {
34
+ visible?: boolean;
35
+ }
36
+ /** Options of {@link writeGOX}. */
37
+ export interface GOXWriteOptions {
38
+ /** Stops the write; the promise rejects with the signal's reason. */
39
+ signal?: AbortSignal;
40
+ }
41
+ /**
42
+ * Reads a Goxel `.gox` (version 1 or 2): one model per layer, voxel layers from their BL16 blocks, clone layers moved
43
+ * by their matrix and shape layers (sphere, cube, cylinder) filled. The file's Z up turns to Y up here: file (x, y, z)
44
+ * is cell (x, z, -y), which keeps the model right-handed. Each model is cropped to its solid voxels and `position` is
45
+ * its lowest corner; an empty layer is a 1 x 1 x 1 grid of air at the origin. Any non-zero alpha is solid. Cameras,
46
+ * the light, the preview image and unknown chunks are skipped; chunk CRCs are not checked (Goxel writes 0).
47
+ *
48
+ * @throws TypeError when the bytes are not a `.gox`; RangeError on a cut-off or damaged file, an unknown version or
49
+ * past `maxCells`, which counts each layer's block bounds before cropping. MargoError `failed` on a broken block PNG.
50
+ */
51
+ export declare function parseGOX(bytes: Uint8Array | ArrayBuffer, limits?: GridLimits): GOXFile;
52
+ /**
53
+ * Writes a Goxel `.gox` of version 2: one layer per model, its voxels in 16^3 blocks at multiples of 16 (identical
54
+ * blocks stored once), one default material, identity layer matrices and no camera, light or preview. Cell (x, y, z)
55
+ * of a model at `position` p becomes file voxel (p.x + x, -(p.z + z), p.y + y), the inverse of {@link parseGOX}, so a
56
+ * round trip gives back the same cells, positions and colours. Takes the shape {@link parseGOX} returns.
57
+ *
58
+ * @throws RangeError when the palette is not 1,024 bytes, a used colour has alpha 0 or a name is over 255 bytes.
59
+ */
60
+ export declare function writeGOX(models: GOXWriteModel | readonly GOXWriteModel[], palette: Uint8Array, options?: GOXWriteOptions): Promise<Uint8Array>;
package/dist/gpu.d.ts ADDED
@@ -0,0 +1,74 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { Vec3 } from '@margoengine/math';
3
+ import { type GridLimits, type VoxelGrid } from './grid.js';
4
+ import { type ShaderBrush, type ShaderBrushRunOptions } from './shaders.js';
5
+ /** Options of {@link GpuGrid.combine}: those of `combineGrids`. */
6
+ export interface GpuCombineOptions {
7
+ operation: 'union' | 'intersect' | 'subtract';
8
+ offset?: Vec3;
9
+ paletteMap?: Uint8Array;
10
+ overlap?: 'base' | 'tool';
11
+ }
12
+ /**
13
+ * A grid kept on the GPU for bulk edits. Edits queue compute passes and return at once (each later edit reads the
14
+ * result of the one before); {@link GpuGrid.read} reads the cells back. `fill`, `combine`, `dilate`, `erode`, `smooth`
15
+ * and `remap` give exactly the cells of `boxCells` or `sphereCells` stamped, `combineGrids`, `dilateGrid`, `erodeGrid`
16
+ * (all six directions), the `smooth` shader brush and a palette lookup; `brush` runs any {@link ShaderBrush}.
17
+ */
18
+ export declare class GpuGrid {
19
+ #private;
20
+ readonly size: Vec3;
21
+ readonly cells: number;
22
+ private constructor();
23
+ /**
24
+ * Uploads `grid` to `device` (the grid is not kept).
25
+ * @throws TypeError for a wrong device or grid; RangeError past `maxCells` (default 16,777,216, at most 67,108,864),
26
+ * past 16,777,216 cells on one side, or past the device's storage binding limit.
27
+ */
28
+ static create(device: GPUDevice, grid: VoxelGrid, limits?: GridLimits): Promise<GpuGrid>;
29
+ /**
30
+ * Sets every cell of the box `[min, max)` (`shape: 'box'`, like `boxCells` with `max` exclusive) or within `radius`
31
+ * of the cell `center` (`'sphere'`, like `sphereCells`) to `value` (0 erases). Cells outside the grid are skipped.
32
+ */
33
+ fill(shape: {
34
+ shape: 'box';
35
+ min: Vec3;
36
+ max: Vec3;
37
+ } | {
38
+ shape: 'sphere';
39
+ center: Vec3;
40
+ radius: number;
41
+ }, value: number): this;
42
+ /**
43
+ * `combineGrids(this, tool, options)` on the GPU: union (with a `paletteMap`, `overlap` 'base' or 'tool'),
44
+ * intersect or subtract of `tool` placed at `offset`. Returns the filled tool cells that fall outside (clipped).
45
+ * @throws TypeError or RangeError as `combineGrids` does.
46
+ */
47
+ combine(tool: VoxelGrid, options: GpuCombineOptions): number;
48
+ /** `dilateGrid` with all six directions: `iterations` passes (default 1), added cells `color` or their source's. */
49
+ dilate(options?: {
50
+ iterations?: number;
51
+ color?: number;
52
+ }): this;
53
+ /** `erodeGrid` with all six directions, `iterations` passes (default 1). */
54
+ erode(options?: {
55
+ iterations?: number;
56
+ }): this;
57
+ /** The `smooth` shader brush (majority of the 27 cells around each), `iterations` passes (default 1). */
58
+ smooth(options?: {
59
+ iterations?: number;
60
+ }): this;
61
+ /** Replaces each cell's index `i` by `table[i]` (256 entries 0 to 255): recolour, isolate or delete colours. */
62
+ remap(table: ArrayLike<number>): this;
63
+ /** Runs a compiled {@link ShaderBrush} on the grid with the options of `ShaderBrush.run` (no `signal`). */
64
+ brush(brush: ShaderBrush, options?: Omit<ShaderBrushRunOptions, 'signal' | 'maxCells'>): this;
65
+ /** Replaces every cell with `grid`'s, which must have this grid's size. */
66
+ write(grid: VoxelGrid): this;
67
+ /** Reads the cells back after every queued edit. @throws MargoError `'disposed'` after dispose(). */
68
+ read(options?: {
69
+ signal?: AbortSignal;
70
+ }): Promise<VoxelGrid>;
71
+ /** Frees the GPU buffers. Calling it again does nothing. */
72
+ dispose(): void;
73
+ [Symbol.dispose](): void;
74
+ }
package/dist/gpu.js ADDED
@@ -0,0 +1,167 @@
1
+ import { c as e, l as t, o as n, s as r, u as i } from "./grid-B2V0TGLV.js";
2
+ import { a, c as o, i as s, n as c, r as l, s as u } from "./shaders-BaY4gcm9.js";
3
+ import { MargoError as d } from "@margoengine/math/errors";
4
+ //#region src/gpu.ts
5
+ var f = "\nfn brush(p: vec3<i32>, value: u32) -> u32 {\n if (param(7) == 0.0) {\n let lo = vec3<i32>(i32(param(0)), i32(param(1)), i32(param(2)));\n let hi = vec3<i32>(i32(param(3)), i32(param(4)), i32(param(5)));\n if (all(p >= lo) && all(p < hi)) { return u32(param(6)); }\n return value;\n }\n let d = p - info.tool_offset.xyz;\n if (any(abs(d) > vec3<i32>(128))) { return value; }\n if (f32(dot(d, d)) <= param(3)) { return u32(param(6)); }\n return value;\n}", p = "\nfn brush(p: vec3<i32>, value: u32) -> u32 {\n let t = tool(p);\n let op = u32(param(0));\n if (op == 2u) {\n if (t == 0u) { return 0u; }\n return value;\n }\n if (t == 0u) { return value; }\n if (op == 3u) { return 0u; }\n if (op == 0u && value != 0u) { return value; }\n return lookup(t);\n}", m = "\nfn brush(p: vec3<i32>, value: u32) -> u32 { return lookup(value); }", h = 16777216, g = /* @__PURE__ */ new WeakMap(), _ = (e, t, n) => {
6
+ let r = g.get(e);
7
+ r || g.set(e, r = /* @__PURE__ */ new Map());
8
+ let i = r.get(t);
9
+ return i || r.set(t, i = u(e, n, `voxel-edit gpu ${t}`)), i;
10
+ }, v = {
11
+ passes: 1,
12
+ params: [],
13
+ seed: 0,
14
+ mask: null,
15
+ tool: null,
16
+ toolOffset: [
17
+ 0,
18
+ 0,
19
+ 0
20
+ ],
21
+ table: null
22
+ }, y = class u {
23
+ #e;
24
+ #t;
25
+ #n;
26
+ #r = !1;
27
+ constructor(e, t, n) {
28
+ this.#e = e, this.#t = t, this.size = t.size, this.cells = t.count, this.#n = n;
29
+ }
30
+ static async create(r, i, a = {}) {
31
+ if (!o(r)) throw TypeError("GpuGrid.create needs a GPUDevice; pass (await adapter.requestDevice())");
32
+ if (t(a, "GpuGrid.create"), e(i, n(a)), i.size.some((e) => e > h)) throw RangeError(`GpuGrid.create grid is ${i.size.join(" x ")}; pass at most ${h} cells per side (f32 cell bounds)`);
33
+ let s = {
34
+ fill: f,
35
+ combine: p,
36
+ remap: m,
37
+ ...c
38
+ }, d = await Promise.all(Object.entries(s).map(async ([e, t]) => [e, await _(r, e, t)]));
39
+ return new u(r, new l(r, i, "GpuGrid"), Object.fromEntries(d));
40
+ }
41
+ #i(e, t, n = !1) {
42
+ if (this.#r) throw new d("disposed", "GpuGrid is disposed; create a new one");
43
+ return n || this.#t.run(this.#n[e], {
44
+ ...v,
45
+ ...t
46
+ }), this;
47
+ }
48
+ fill(e, n) {
49
+ if (t(e, "GpuGrid.fill shape"), i(n, "GpuGrid.fill value", 0), e.shape === "box") {
50
+ r(e.min, "GpuGrid.fill min"), r(e.max, "GpuGrid.fill max");
51
+ let t = e.min.map((e, t) => Math.min(Math.max(e, 0), this.size[t])), i = e.max.map((e, t) => Math.min(Math.max(e, 0), this.size[t]));
52
+ return this.#i("fill", { params: [
53
+ ...t,
54
+ ...i,
55
+ n,
56
+ 0
57
+ ] }, t.some((e, t) => e >= i[t]));
58
+ }
59
+ if (e.shape !== "sphere") throw TypeError("GpuGrid.fill shape is unknown; pass {shape: 'box'} or {shape: 'sphere'}");
60
+ if (!Array.isArray(e.center) || e.center.length !== 3 || !e.center.every(Number.isFinite)) throw TypeError("GpuGrid.fill center must be three finite numbers; pass [x, y, z]");
61
+ if (typeof e.radius != "number" || !(e.radius >= 0) || e.radius > 128) throw RangeError(`GpuGrid.fill radius is ${e.radius}; pass 0 to 128`);
62
+ let a = e.center.map(Math.round), o = Math.ceil(e.radius), s = a.some((e, t) => e + o < 0 || e - o >= this.size[t]);
63
+ return this.#i("fill", {
64
+ toolOffset: a,
65
+ params: [
66
+ 0,
67
+ 0,
68
+ 0,
69
+ Math.floor(e.radius * e.radius),
70
+ 0,
71
+ 0,
72
+ n,
73
+ 1
74
+ ]
75
+ }, s);
76
+ }
77
+ combine(n, i) {
78
+ t(i, "GpuGrid.combine");
79
+ let a = e(n, Infinity, "Tool grid"), { operation: o, offset: s = [
80
+ 0,
81
+ 0,
82
+ 0
83
+ ], paletteMap: c, overlap: l } = i;
84
+ if (o !== "union" && o !== "intersect" && o !== "subtract") throw TypeError("GpuGrid.combine operation is unknown; pass 'union', 'intersect' or 'subtract'");
85
+ if (r(s, "GpuGrid.combine offset"), l !== void 0 && l !== "base" && l !== "tool") throw TypeError("GpuGrid.combine overlap is unknown; pass 'base' or 'tool'");
86
+ if (o === "union") {
87
+ if (!(c instanceof Uint8Array) || c.length !== 256) throw TypeError("GpuGrid.combine union needs a paletteMap; pass 256 entries (see mergePalettes)");
88
+ if (c[0] !== 0) throw RangeError("GpuGrid.combine paletteMap fills air; keep entry 0 at 0");
89
+ for (let e = 0; e < a; e++) if (n.voxels[e] && !c[n.voxels[e]]) throw RangeError(`GpuGrid.combine paletteMap empties tool index ${n.voxels[e]}; map it to 1-255`);
90
+ }
91
+ let u = o === "union" ? +(l === "tool") : o === "intersect" ? 2 : 3;
92
+ this.#i("combine", {
93
+ params: [u],
94
+ tool: n,
95
+ toolOffset: s,
96
+ table: c ?? null
97
+ });
98
+ let [d, f, p] = this.size, [m, h, g] = n.size, _ = 0;
99
+ for (let e = 0; e < h; e++) for (let t = 0; t < g; t++) for (let r = 0; r < m; r++) {
100
+ if (!n.voxels[r + m * (t + g * e)]) continue;
101
+ let i = r + s[0], a = e + s[1], o = t + s[2];
102
+ (i < 0 || a < 0 || o < 0 || i >= d || a >= f || o >= p) && _++;
103
+ }
104
+ return _;
105
+ }
106
+ dilate(e = {}) {
107
+ t(e, "GpuGrid.dilate");
108
+ let n = b(e.iterations, "GpuGrid.dilate");
109
+ return e.color !== void 0 && i(e.color, "GpuGrid.dilate color"), n ? this.#i("grow", {
110
+ passes: n,
111
+ params: [e.color ?? 0]
112
+ }) : this;
113
+ }
114
+ erode(e = {}) {
115
+ t(e, "GpuGrid.erode");
116
+ let n = b(e.iterations, "GpuGrid.erode");
117
+ return n ? this.#i("erode", { passes: n }) : this;
118
+ }
119
+ smooth(e = {}) {
120
+ t(e, "GpuGrid.smooth");
121
+ let n = b(e.iterations, "GpuGrid.smooth");
122
+ return n ? this.#i("smooth", { passes: n }) : this;
123
+ }
124
+ remap(e) {
125
+ if (typeof e?.length != "number" || e.length !== 256) throw TypeError("GpuGrid.remap table must hold 256 numbers; pass a Uint8Array(256)");
126
+ for (let t = 0; t < 256; t++) if (!Number.isInteger(e[t]) || e[t] < 0 || e[t] > 255) throw RangeError(`GpuGrid.remap table[${t}] is ${e[t]}; pass whole numbers 0 to 255`);
127
+ return this.#i("remap", { table: e });
128
+ }
129
+ brush(e, n = {}) {
130
+ let r = a.get(e);
131
+ if (!r) throw TypeError("GpuGrid.brush needs a live ShaderBrush; pass await ShaderBrush.create(device, code)");
132
+ if (r.device !== this.#e) throw TypeError("GpuGrid.brush brush was made on another device; create it with this grid's device");
133
+ t(n, "GpuGrid.brush");
134
+ let i = s(n, this.cells, Infinity, "GpuGrid.brush");
135
+ if (this.#r) throw new d("disposed", "GpuGrid is disposed; create a new one");
136
+ return this.#t.run(r.pipeline, i), this;
137
+ }
138
+ write(t) {
139
+ if (this.#r) throw new d("disposed", "GpuGrid is disposed; create a new one");
140
+ if (e(t, Infinity), t.size.some((e, t) => e !== this.size[t])) throw RangeError(`GpuGrid.write grid is ${t.size.join(" x ")}, not ${this.size.join(" x ")}; pass a grid of this size`);
141
+ return this.#t.write(t.voxels), this;
142
+ }
143
+ async read(e = {}) {
144
+ if (this.#r) throw new d("disposed", "GpuGrid is disposed; create a new one");
145
+ return {
146
+ size: [
147
+ this.size[0],
148
+ this.size[1],
149
+ this.size[2]
150
+ ],
151
+ voxels: await this.#t.read(e?.signal)
152
+ };
153
+ }
154
+ dispose() {
155
+ this.#r || (this.#r = !0, this.#t.destroy());
156
+ }
157
+ [Symbol.dispose]() {
158
+ this.dispose();
159
+ }
160
+ };
161
+ function b(e, t) {
162
+ let n = e ?? 1;
163
+ if (!Number.isInteger(n) || n < 0 || n > 1024) throw RangeError(`${t} iterations must be an integer from 0 to 1024; pass one`);
164
+ return n;
165
+ }
166
+ //#endregion
167
+ export { y as GpuGrid };
@@ -0,0 +1,120 @@
1
+ //#region src/grid.ts
2
+ var e = 16777216, t = 67108864;
3
+ function n(e, t, n, r) {
4
+ return t + e[0] * (r + e[2] * n);
5
+ }
6
+ function r(e, t) {
7
+ let n = Math.floor(t / e[0]);
8
+ return [
9
+ t - n * e[0],
10
+ Math.floor(n / e[2]),
11
+ n % e[2]
12
+ ];
13
+ }
14
+ function i(e, t, n, r) {
15
+ return Number.isInteger(t) && Number.isInteger(n) && Number.isInteger(r) && t >= 0 && n >= 0 && r >= 0 && t < e[0] && n < e[1] && r < e[2];
16
+ }
17
+ function a(e, t) {
18
+ if (typeof e != "object" || !e) throw TypeError(`${t} options are missing; pass an options object`);
19
+ }
20
+ function o(n, r = e) {
21
+ let i = n.maxCells ?? r;
22
+ if (!Number.isSafeInteger(i) || i < 1 || i > 67108864) throw RangeError(`maxCells is out of range; pass an integer from 1 to ${t}`);
23
+ return i;
24
+ }
25
+ function s(e, t) {
26
+ if (!Array.isArray(e) || e.length !== 3) throw TypeError(`${t} is not [x, y, z]; pass three numbers`);
27
+ if (!Number.isSafeInteger(e[0]) || !Number.isSafeInteger(e[1]) || !Number.isSafeInteger(e[2])) throw RangeError(`${t} is not whole cells; pass three integers`);
28
+ }
29
+ function c(e, t) {
30
+ if (!Array.isArray(e) || e.length !== 3) throw TypeError(`${t} is not [x, y, z]; pass three numbers`);
31
+ if (!Number.isFinite(e[0]) || !Number.isFinite(e[1]) || !Number.isFinite(e[2])) throw RangeError(`${t} is not finite; pass three finite numbers`);
32
+ }
33
+ function l(e, t) {
34
+ let n = Math.max(Math.abs(e[0]), Math.abs(e[1]), Math.abs(e[2]));
35
+ if (!n) throw RangeError(`${t} direction is zero; pass a nonzero direction`);
36
+ let r = e[0] / n, i = e[1] / n, a = e[2] / n, o = Math.hypot(r, i, a);
37
+ return [
38
+ r / o,
39
+ i / o,
40
+ a / o
41
+ ];
42
+ }
43
+ function u(e, t, n, r) {
44
+ let i = [
45
+ 0,
46
+ 0,
47
+ 0
48
+ ], a = -1, o = -Infinity;
49
+ for (let i of t) {
50
+ let t = [
51
+ e[0],
52
+ e[1],
53
+ e[2]
54
+ ];
55
+ t[i] -= Math.sign(n[i]);
56
+ let s = (r(t[0], t[1], t[2]) ? 0 : 2) + Math.abs(n[i]);
57
+ s > o && (o = s, a = i);
58
+ }
59
+ return a >= 0 && (i[a] = -Math.sign(n[a])), i;
60
+ }
61
+ function d(e, t, n = "Grid size") {
62
+ if (s(e, n), e.some((e) => e < 1)) throw RangeError(`${n} has an empty axis; pass sizes of at least 1`);
63
+ let r = e[0] * e[1] * e[2];
64
+ if (!Number.isSafeInteger(r) || r > t) throw RangeError(`${n} exceeds maxCells (${t}); make it smaller or raise maxCells`);
65
+ return r;
66
+ }
67
+ function f(e, t, n = "Grid") {
68
+ if (typeof e != "object" || !e) throw TypeError(`${n} is missing; pass {size, voxels}`);
69
+ let r = d(e.size, t, `${n} size`);
70
+ if (!(e.voxels instanceof Uint8Array)) throw TypeError(`${n} voxels are not a Uint8Array; pass one`);
71
+ if (e.voxels.length !== r) throw RangeError(`${n} voxels hold ${e.voxels.length} cells, not ${r}; match the size`);
72
+ return r;
73
+ }
74
+ function p(e, t, n = 1) {
75
+ if (!Number.isInteger(e) || e < n || e > 255) throw RangeError(`${t} is not a palette index; pass an integer from ${n} to 255`);
76
+ }
77
+ function m(e, t) {
78
+ let n = [
79
+ "x",
80
+ "y",
81
+ "z"
82
+ ].indexOf(e);
83
+ if (n < 0) throw TypeError(`${t} is not an axis; pass 'x', 'y' or 'z'`);
84
+ return n;
85
+ }
86
+ function h(e, t, n, r = e.size) {
87
+ let i = {
88
+ size: [
89
+ r[0],
90
+ r[1],
91
+ r[2]
92
+ ],
93
+ voxels: t
94
+ };
95
+ return {
96
+ grid: i,
97
+ changed: g(e, i),
98
+ clipped: n
99
+ };
100
+ }
101
+ function g(e, t) {
102
+ let [n, r, i] = e.size, [a, o, s] = t.size, c = 0;
103
+ if (n === a && r === o && i === s) {
104
+ for (let n = 0; n < e.voxels.length; n++) e.voxels[n] !== t.voxels[n] && c++;
105
+ return c;
106
+ }
107
+ for (let l = 0; l < r; l++) for (let r = 0; r < i; r++) for (let u = 0; u < n; u++) {
108
+ let d = u < a && l < o && r < s ? t.voxels[u + a * (r + s * l)] : 0;
109
+ e.voxels[u + n * (r + i * l)] !== d && c++;
110
+ }
111
+ for (let e = 0; e < o; e++) for (let o = 0; o < s; o++) for (let l = 0; l < a; l++) (l >= n || e >= r || o >= i) && t.voxels[l + a * (o + s * e)] && c++;
112
+ return c;
113
+ }
114
+ function _(e, t) {
115
+ if (e === void 0 || e === "webgpu") return [1, 0];
116
+ if (e === "webgl2") return [-1, 1];
117
+ throw TypeError(`${t} backend is unknown; pass engine.backend ('webgpu' or 'webgl2')`);
118
+ }
119
+ //#endregion
120
+ export { l as _, n as a, f as c, c as d, _ as f, d as g, i as h, r as i, a as l, u as m, t as n, o, h as p, m as r, s, e as t, p as u };
package/dist/grid.d.ts ADDED
@@ -0,0 +1,75 @@
1
+ import type { MutableVec3, Vec3 } from '@margoengine/math';
2
+ /**
3
+ * A dense voxel model: one palette index per cell, 0 for air and 1 to 255 for filled cells, Y up. Cell (x, y, z) is
4
+ * `voxels[x + size[0] * (z + size[2] * y)]`, the layout {@link cellIndex} computes. Operations never change a grid
5
+ * they are given; they return a new one.
6
+ */
7
+ export interface VoxelGrid {
8
+ /** Cells along x, y and z, each a positive integer. */
9
+ readonly size: Vec3;
10
+ /** Palette indexes, `size[0] * size[1] * size[2]` of them. */
11
+ readonly voxels: Uint8Array;
12
+ }
13
+ /** The cell budget of an operation, checked before it allocates anything. */
14
+ export interface GridLimits {
15
+ /** Most cells the operation may allocate or visit, 1 to 67,108,864. Default 16,777,216 (256 x 256 x 256). */
16
+ maxCells?: number;
17
+ }
18
+ /** What a grid operation returns: a new grid and what changed. */
19
+ export interface GridEdit {
20
+ /** The result, with its own `voxels` and `size`. */
21
+ grid: VoxelGrid;
22
+ /** Cells whose palette index differs between input and result; cells outside either grid read as air. */
23
+ changed: number;
24
+ /** Filled cells the operation moved or copied out of the result's bounds and so dropped. */
25
+ clipped: number;
26
+ }
27
+ /** A ray hit on a grid, in local cells. */
28
+ export interface GridHit {
29
+ /** The filled cell hit. */
30
+ cell: MutableVec3;
31
+ /** The cell in front of the face hit, `cell + normal`: where a new voxel goes. */
32
+ adjacent: MutableVec3;
33
+ /** Outward normal of the face the ray entered through; [0, 0, 0] when the ray starts inside the cell. */
34
+ normal: MutableVec3;
35
+ /** The cell's palette index, 1-255. */
36
+ value: number;
37
+ /** Distance along the normalized ray to the face hit (0 when starting inside). */
38
+ distance: number;
39
+ }
40
+ /** @internal Default and hard ceiling of {@link GridLimits.maxCells}. */
41
+ export declare const DEFAULT_CELLS = 16777216, MAX_CELLS = 67108864;
42
+ /** Index of cell (x, y, z) in a grid of `size`: `x + size[0] * (z + size[2] * y)`. */
43
+ export declare function cellIndex(size: Vec3, x: number, y: number, z: number): number;
44
+ /** The cell at `index` in a grid of `size`, the inverse of {@link cellIndex}. */
45
+ export declare function cellAt(size: Vec3, index: number): MutableVec3;
46
+ /** Whether (x, y, z) is an integer cell inside a grid of `size`. */
47
+ export declare function insideGrid(size: Vec3, x: number, y: number, z: number): boolean;
48
+ /** @internal Throws unless `options` is an object. */
49
+ export declare function checkOptions(options: unknown, subject: string): asserts options is object;
50
+ /** @internal The validated `maxCells` of `options`. */
51
+ export declare function cellLimit(options: GridLimits, fallback?: number): number;
52
+ /** @internal Throws unless `value` holds three safe integers. */
53
+ export declare function checkCell(value: unknown, subject: string): asserts value is Vec3;
54
+ /** @internal Throws unless `value` holds three finite numbers. */
55
+ export declare function checkPoint(value: unknown, subject: string): asserts value is Vec3;
56
+ /** @internal Unit direction without overflowing or underflowing its length. The vector is already finite. */
57
+ export declare function unitDirection(direction: Vec3, subject: string): MutableVec3;
58
+ /**
59
+ * @internal Outward normal of the face a ray crossed to enter `cell` along unit `dir`. `tied` lists the axes crossed
60
+ * at once: on an edge or corner the face whose neighbour is empty (`filled` false) wins, then the face most head-on
61
+ * to the ray. No tied axis gives a zero normal.
62
+ */
63
+ export declare function exposedNormal(cell: readonly number[], tied: readonly number[], dir: readonly number[], filled: (x: number, y: number, z: number) => boolean): MutableVec3;
64
+ /** @internal The cell count of a grid of `size`, checked against `limit` before anything is allocated. */
65
+ export declare function sizeCells(size: unknown, limit: number, subject?: string): number;
66
+ /** @internal Checks a grid's size against `limit` and its buffer against its size; returns its cell count. */
67
+ export declare function checkGrid(grid: VoxelGrid, limit: number, subject?: string): number;
68
+ /** @internal Throws unless `value` is a palette index from `min` (0 or 1) to 255. */
69
+ export declare function checkPalette(value: unknown, subject: string, min?: 0 | 1): asserts value is number;
70
+ /** @internal 0, 1 or 2 for 'x', 'y' or 'z'. */
71
+ export declare function axisIndex(axis: unknown, subject: string): 0 | 1 | 2;
72
+ /** @internal A result grid of `size` (default the source's) and its counts against `source`. */
73
+ export declare function edited(source: VoxelGrid, voxels: Uint8Array, clipped: number, size?: Vec3): GridEdit;
74
+ /** @internal The NDC depths of the near and far planes for `backend`. */
75
+ export declare function depthRange(backend: unknown, subject: string): [near: number, far: number];