@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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +445 -2
- package/dist/animation.d.ts +50 -0
- package/dist/animation.js +88 -0
- package/dist/assist.d.ts +24 -0
- package/dist/assist.js +52 -0
- package/dist/brush-gpu.d.ts +62 -0
- package/dist/bytes.d.ts +55 -0
- package/dist/collab.d.ts +77 -0
- package/dist/collab.js +159 -0
- package/dist/edit.d.ts +30 -0
- package/dist/edit.js +361 -0
- package/dist/export.d.ts +58 -0
- package/dist/export.js +52 -0
- package/dist/file-colors-DHT5vrzW.js +55 -0
- package/dist/file-colors.d.ts +16 -0
- package/dist/format-plist.d.ts +4 -0
- package/dist/formats-extra.d.ts +20 -0
- package/dist/formats-extra.js +335 -0
- package/dist/formats.d.ts +96 -0
- package/dist/formats.js +924 -0
- package/dist/generate.d.ts +63 -0
- package/dist/generate.js +103 -0
- package/dist/gox.d.ts +60 -0
- package/dist/gpu.d.ts +74 -0
- package/dist/gpu.js +167 -0
- package/dist/grid-B2V0TGLV.js +120 -0
- package/dist/grid.d.ts +75 -0
- package/dist/history.d.ts +65 -0
- package/dist/history.js +75 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +631 -0
- package/dist/layout.d.ts +76 -0
- package/dist/library.d.ts +50 -0
- package/dist/library.js +89 -0
- package/dist/mesh.d.ts +128 -0
- package/dist/mesh.js +365 -0
- package/dist/model.d.ts +173 -0
- package/dist/pick.d.ts +34 -0
- package/dist/pick.js +122 -0
- package/dist/raster.d.ts +89 -0
- package/dist/rig.d.ts +88 -0
- package/dist/rig.js +216 -0
- package/dist/select.d.ts +50 -0
- package/dist/select.js +94 -0
- package/dist/shaders-BaY4gcm9.js +234 -0
- package/dist/shaders.d.ts +116 -0
- package/dist/shaders.js +1 -0
- package/dist/slices.d.ts +75 -0
- package/dist/smooth.d.ts +43 -0
- package/dist/smooth.js +212 -0
- package/dist/sparse.d.ts +239 -0
- package/dist/sparse.js +646 -0
- package/dist/stamp.d.ts +88 -0
- package/dist/vmax.d.ts +48 -0
- package/dist/vox-resolve.d.ts +64 -0
- package/dist/vox-scene.d.ts +51 -0
- package/dist/vox.d.ts +30 -0
- package/dist/vox.js +684 -0
- package/dist/voxelize.d.ts +70 -0
- package/dist/voxelize.js +249 -0
- package/dist/vxm.d.ts +54 -0
- package/package.json +130 -4
package/README.md
CHANGED
|
@@ -1,3 +1,446 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @margoengine/voxel-edit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Import `margoengine/voxel-edit` from the `margoengine` package, or `@margoengine/voxel-edit` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
|
|
4
|
+
|
|
5
|
+
Editing voxel models for voxel editors and tools: dense and sparse grids, modeling operations, brushes and
|
|
6
|
+
selections, picking, export meshing, `.vox` scene editing and frame animation. CPU only (but `./shaders` and `./gpu`, which run on a GPUDevice), no renderer, no DOM: every
|
|
7
|
+
function is pure and can run in a worker. Optional and tree-shakable; core and the stage never import it.
|
|
8
|
+
|
|
9
|
+
An empty `meshGrid` result has empty arrays. Core `Geometry` accepts that empty result;
|
|
10
|
+
attach it normally when the last voxel is erased. The node,
|
|
11
|
+
transform and material survive, so the next edit can attach geometry again:
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { Geometry, Engine } from '@margoengine/core';
|
|
15
|
+
import { meshGrid } from '@margoengine/voxel-edit/mesh';
|
|
16
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
17
|
+
const node = engine.createMesh();
|
|
18
|
+
const grid = { size: [1, 1, 1] as const, voxels: new Uint8Array(1) };
|
|
19
|
+
const { mesh } = meshGrid(grid);
|
|
20
|
+
node.setGeometry(new Geometry(mesh.positions, mesh.normals, mesh.indices));
|
|
21
|
+
node.dispose();
|
|
22
|
+
engine.dispose();
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`VoxelHistory.push(grid, label?)`, `undo()`, `redo()`, `go(index)` and `current`
|
|
26
|
+
all return an owned `VoxelGrid` directly; read
|
|
27
|
+
`history.label` for the current operation's name. Every returned grid is an owned
|
|
28
|
+
copy. Navigation at either endpoint returns the current grid.
|
|
29
|
+
With `maxBytes`, a push that would retain more bytes drops the oldest steps until it fits (the redo branch goes
|
|
30
|
+
first), the way GIMP's "Maximum undo memory" works; the new step always stays, so one step larger than the whole
|
|
31
|
+
budget is kept as the only step and `history.bytes` is over `maxBytes` only then.
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import { VoxelHistory } from '@margoengine/voxel-edit/history';
|
|
35
|
+
const grid = { size: [1, 1, 1] as const, voxels: new Uint8Array(1) };
|
|
36
|
+
const history = new VoxelHistory(grid);
|
|
37
|
+
grid.voxels[0] = 2;
|
|
38
|
+
const pushed = history.push(grid, 'Paint');
|
|
39
|
+
const previous = history.undo();
|
|
40
|
+
const restored = history.redo();
|
|
41
|
+
console.log(pushed.voxels[0], previous.voxels[0], restored.voxels[0], history.label);
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
import { combineGrids, mergePalettes, rotateGrid, type VoxelGrid } from 'margoengine/voxel-edit';
|
|
46
|
+
import { sphereCells, connectedCells } from 'margoengine/voxel-edit/edit';
|
|
47
|
+
import { pickRay, raycastGrid } from 'margoengine/voxel-edit/pick';
|
|
48
|
+
import { meshGrid } from 'margoengine/voxel-edit/mesh';
|
|
49
|
+
import {Engine} from 'margoengine/core';
|
|
50
|
+
const ndcX = 0;
|
|
51
|
+
const ndcY = 0;
|
|
52
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
53
|
+
|
|
54
|
+
const model: VoxelGrid = { size: [32, 32, 32], voxels: new Uint8Array(32 * 32 * 32) };
|
|
55
|
+
const { grid } = rotateGrid(model, { axis: 'y', degrees: 90 }); // a new grid; `model` is unchanged
|
|
56
|
+
const prop: VoxelGrid = { size: [8, 8, 8], voxels: new Uint8Array(8 * 8 * 8) };
|
|
57
|
+
const baseKeys = Array.from({ length: 256 }, (_, i) => `base:${i}`), toolKeys = Array.from({ length: 256 }, (_, i) => `tool:${i}`);
|
|
58
|
+
const baseUsed = new Uint8Array(256), toolUsed = new Uint8Array(256);
|
|
59
|
+
const { paletteMap } = mergePalettes({ baseKeys, toolKeys, baseUsed, toolUsed });
|
|
60
|
+
const merged = combineGrids(grid, prop, { operation: 'union', offset: [4, 0, 4], paletteMap });
|
|
61
|
+
|
|
62
|
+
const ray = pickRay(engine.camera.matrix, ndcX, ndcY, { backend: engine.backend }); // then into the model's cells
|
|
63
|
+
const hit = ray && raycastGrid(merged.grid, ray); // {cell, adjacent, normal, value, distance}
|
|
64
|
+
const { mesh } = meshGrid(merged.grid, { ambientOcclusion: true, pivot: [16, 0, 16] });
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Grids
|
|
68
|
+
|
|
69
|
+
A `VoxelGrid` is `{size, voxels}`: one palette index per cell, 0 for air and 1-255 for filled cells, Y up, cell
|
|
70
|
+
(x, y, z) at `x + size[0] * (z + size[2] * y)` (`cellIndex`, `cellAt`, `insideGrid`). Operations never change their
|
|
71
|
+
input; each returns `{grid, changed, clipped}`: a new grid, the cells that differ (cells outside either grid read as
|
|
72
|
+
air) and the filled cells pushed out of bounds. Every operation checks its arguments and its `maxCells` budget
|
|
73
|
+
(default 16,777,216 cells, at most 67,108,864) before allocating anything. The layout operations (`flipGrid` to
|
|
74
|
+
`fitGrid`) also take a `selection` of cell indexes and return it mapped, with `mapPoint` for pivots and joints in
|
|
75
|
+
corner coordinates.
|
|
76
|
+
|
|
77
|
+
| Root entry | Does |
|
|
78
|
+
| --- | --- |
|
|
79
|
+
| `combineGrids` | union (with a `paletteMap`), `intersect`, `subtract` of a tool grid at a whole-cell offset |
|
|
80
|
+
| `mergePalettes` | the `paletteMap` for a union: reuses equal identities, takes free indexes, never changes used base entries; throws past 255 |
|
|
81
|
+
| `shearGrid`, `reflectDiagonal`, `wrapGrid`, `rotateGrid` | shear by layers, mirror or symmetrize across a square plane's diagonal, move with wrap-around, turn by any angle inside the box |
|
|
82
|
+
| `repeatGrid`, `resampleGrid` | tile, or scale by nearest-cell sampling (indexes are never blended) |
|
|
83
|
+
| `dilateGrid`, `erodeGrid`, `fillEnclosed` | grow or shrink along chosen axis directions, fill closed cavities |
|
|
84
|
+
| `generateMaze` | a seeded perfect maze, one-cell walls and corridors |
|
|
85
|
+
| `flipGrid`, `turnGrid`, `shiftGrid` | exact whole-cell layout: mirror along a principal axis, right-handed quarter turns that swap the other two sizes (so nothing clips; `rotateGrid` turns inside the same box instead), move by an offset with the cells that leave counted in `clipped` |
|
|
86
|
+
| `occupiedBounds`, `cropGrid`, `fitGrid` | the filled box; crop or extend to a size anchored at a caller's origin (a resize keeping the corner is origin [0, 0, 0]); shrink to the filled box |
|
|
87
|
+
| `invertGrid` | swap filled and empty cells, air taking an explicit palette index |
|
|
88
|
+
| `sliceLayout`, `stackSlices` | sprite-sheet RGBA frames (explicit frame size, columns, count, stack axis, order and alpha threshold) stacked into an indexed Y-up grid, each RGBA colour exact: indexes in reading order up to 255, or the first exact index of a palette you pass; anything else refuses |
|
|
89
|
+
| `ByteLedger`, `ownedBuffers`, `retainedBytes` | bytes of the storage grids, cels, packed frames, images and sparse snapshots keep alive, each buffer counted once through its token (`SparseGrid.ownedBuffers`, `SparseGrid.deltaBuffers`); the ledger retains and releases values for an undo budget |
|
|
90
|
+
|
|
91
|
+
## Entries
|
|
92
|
+
|
|
93
|
+
| Entry | Holds |
|
|
94
|
+
| --- | --- |
|
|
95
|
+
| `./edit` | brush footprints `lineCells`, `boxCells`, `sphereCells`; selections `floodCells` (same index), `connectedCells` (any filled), `faceCells` (an exposed layer), returned as cell indexes in a `Float64Array`; `mirrorCells` expands brush samples through XYZ mirrors (a centre-plane cell once) and `stampCells` writes them as one fill, paint or erase edit; `pasteCells` pastes clip cells with exact palette identities (every identity match is taken before a new slot is handed out), the selection and an explicit `'overflow'` result when the palette is full; rasterizers `ellipsoidCells`, `cylinderCells`, `ringCells`, `thickLineCells` (cube per step, `'ceil'` or `'span'` step rule) and `taperedLineCells` (spheres of changing radius) give the cell indexes of a grid with exact centre, radius and thickness rules, refusing or clipping cells outside (a clipped stroke visits only cells inside the grid) |
|
|
96
|
+
| `./pick` | `pickRay` (pointer ray from the camera matrix; pass `{ backend: engine.backend }` so a WebGL2 matrix's -1 to 1 depth is read the right way round, default WebGPU reverse depth), `raycastGrid` (first filled cell, the face and the cell in front of it), `groundCell` |
|
|
97
|
+
| `./sparse` | `SparseGrid`: models far larger than memory holds densely (a 1,000,000-wide grid with two cells holds two chunks), stored as `@margoengine/voxel` chunks, edited by copy-on-write snapshots with `restore` undo; `editWindow` fills, erases, paints, dilates or erodes a box; `serialize` / `deserialize`; `snapshot` / `fromSnapshot` / `restoreSnapshots` and `deltaSnapshot` / `applyDeltaSnapshot` for workers (`snapshotBuffers` is the transfer list); `toWorld` writes into a `VoxelWorld` |
|
|
98
|
+
| `./mesh` | `meshGrid`: greedy quads per palette index with optional corner ambient occlusion (Lysenko 2013 levels 0 to 3 as light 0.4 to 1.0, each unequal quad split along its darker diagonal) and crease-limited smooth normals; dense or sparse, chunk seams leave no inner faces; `partitionMesh` splits a mesh into one-palette parts of at most 250,000 quads (one million vertices, the most one `@margoengine/materials` mesh takes), attributes copied; `chamferGrid` bevels the exposed faces by a width in cells into a triangle mesh with a palette index per triangle |
|
|
99
|
+
| `./vox` | `gridFromVox` / `voxFromGrid` (MagicaVoxel's Z up to Y up and back; an unedited model is returned as it was) and scene-graph edits: layers, names, transform and shape keys, groups, instances, `moveVoxNode` (keeps world poses), `deleteVoxNode`; `resolveVoxScene` places every shape instance at a frame (held keys, visibility, names, layers, matrix) under an explicit centering, and `voxFrameRange` gives the key span; `voxTiles` splits a large dense or sparse grid into filled tiles of at most 256 cells per axis, each with its exact cell offset and no axis turned |
|
|
100
|
+
| `./animation` | `packFrames` / `unpackFrames` (each distinct model stored once) and `localFrame` (a clip's clock: offset, speed, loop or hold) |
|
|
101
|
+
| `./history` | `VoxelHistory`: undo/redo of copied grids with depth, per-grid cell and total byte budgets; a push past `maxBytes` drops the oldest steps (never the new one), and a single step larger than the whole budget is kept as the only step |
|
|
102
|
+
| `./export` | `gridToExportSource`: meshes a grid into one primitive per palette material (corner AO as vertex colours), the `{nodes}` scene `exportGLB`, `exportUSDZ` and `exportOBJ` take |
|
|
103
|
+
| `./formats` | voxel files other tools write: `parseQB` / `writeQB` and `parseQEF` / `writeQEF` (Qubicle), `parseGOX` / `writeGOX` (Goxel), `parseVXM` / `writeVXM` (VoxEdit), `parseBinvox`, `parseKVX` and `parseVXL`; models, palette, positions, with cell budgets |
|
|
104
|
+
| `./smooth` | `smoothGrid`: a smooth Surface Nets mesh of a grid, with relaxation, optional blur and gradient normals, for `gridToExportSource` |
|
|
105
|
+
| `./voxelize` | `voxelizeMesh`: a triangle mesh to a grid and palette, surface or solid, with vertex or texture colours and median cut; `AbortSignal` |
|
|
106
|
+
| `./assist` | `noiseFill` (seeded random fill), `suggestPalette` (seeded hues, linear sRGB) and `paletteUsage` (cells per index, within `maxCells`) |
|
|
107
|
+
| `./library` | `fetchLibrary` / `fetchAsset` / `resolveLibraryUrl`: list and fetch `.vox` packs from a JSON index, with a body size limit (reading stops at `maxBytes`, Content-Length or not) and abort; with no absolute base a relative index gives relative asset URLs |
|
|
108
|
+
| `./shaders` | `ShaderBrush`: your own WGSL `fn brush(p, value)` run on the GPU for every selected cell, pass after pass, to grow, erode or generate; presets `brushes.grow`, `erode`, `noise`, `smooth`; `brushSource` |
|
|
109
|
+
| `./rig` | `VoxelRig`: voxel parts on a skeleton, posed by bone rotations (any bone name, `constructor` included: only the pose's own keys turn a bone); part matrices for drawing and `bake` to one grid; `sampleRigClip`, `rigRotation`, `slerpRotation` |
|
|
110
|
+
| `./gpu` | `GpuGrid`: a grid kept on the GPU for bulk edits on multi-million-cell models: `fill` (box, sphere), `combine` (union, intersect, subtract), `dilate`, `erode`, `smooth`, `remap`, `brush` (any `ShaderBrush`, the same input checks as `ShaderBrush.run`), then `read` once; at most 16,777,216 cells per side |
|
|
111
|
+
| `./collab` | `VoxelReplica`: shared editing, where edits from several users merge to the same cells in any order with no server; `encodeVoxelOp` / `decodeVoxelOp` for the network |
|
|
112
|
+
| `./generate` | `heightmapToVoxels` (Grey8 or RGBA8 image to Y columns; `alphaThreshold` applies to RGBA only) and `textToVoxels` (a canvas font's mask extruded along z, cropped to the ink) |
|
|
113
|
+
| `./select` | `screenSelection`, `rectangleSelection`, `lassoSelection` (even-odd) and `colorSelection`: filled cells whose centres project into a screen shape; pass `{ backend: engine.backend }` with a WebGL2 camera matrix (-1 to 1 depth) |
|
|
114
|
+
|
|
115
|
+
Selections, picking and meshing take a dense or a sparse grid. Errors follow
|
|
116
|
+
[docs/conventions.md](../../docs/conventions.md): `TypeError` and `RangeError` for arguments and budgets,
|
|
117
|
+
`MargoError` with code `state` for a stale undo token, a non-empty target world, or a `.vox` edit the scene's
|
|
118
|
+
structure refuses (the last key of a track, the root, a cycle, moving a visible node into a hidden group).
|
|
119
|
+
|
|
120
|
+
## .vox placement
|
|
121
|
+
|
|
122
|
+
`resolveVoxScene(scene, {frame, centering})` needs a centering, because two placements are in use and they differ by
|
|
123
|
+
one cell along a flipped axis of odd size. `'box-v1'` keeps a turned box on the span `t - floor(s / 2)` to
|
|
124
|
+
`t - floor(s / 2) + s` on every axis and mirrors cells inside it: `@margoengine/voxel/vox` `pasteVoxModel`'s placement,
|
|
125
|
+
and the one Margo Voxel Studio saves. `'pivot-v1'` turns the model about its corner `floor(size / 2)`:
|
|
126
|
+
`@margoengine/voxel-pathtracer` `magicaVoxelMatrix`. Each name is a fixed contract; a new convention gets a new name.
|
|
127
|
+
The resolver uses the key in force at the frame (the latest at or before it, else the earliest; the first listed
|
|
128
|
+
among keys of one frame), while `pasteVoxModel` uses each track's first-listed key.
|
|
129
|
+
|
|
130
|
+
## Voxel files
|
|
131
|
+
|
|
132
|
+
`./formats` reads the files other voxel tools write into the grid and palette the rest of this package uses. Index i of
|
|
133
|
+
the palette sits at `4 * i`, as in `parseVox`.
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
import { parseQB, writeQEF } from '@margoengine/voxel-edit/formats';
|
|
137
|
+
|
|
138
|
+
const bytes = new Uint8Array(await (await fetch('/models/robot.qb')).arrayBuffer());
|
|
139
|
+
const { models, palette, colorsReduced } = parseQB(bytes, { maxCells: 16_000_000 });
|
|
140
|
+
if (colorsReduced) console.warn('over 255 colours: nearby ones were merged');
|
|
141
|
+
const text = writeQEF(models[0].grid, palette);
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
| Format | Read | Write | What to know |
|
|
145
|
+
| --- | --- | --- | --- |
|
|
146
|
+
| Qubicle `.qb` | `parseQB` | `writeQB` | every matrix with its name and position; RGBA or BGRA, RLE or plain, left or right handed; alpha 0 is air; a visibility mask counts as opaque |
|
|
147
|
+
| Qubicle `.qef` | `parseQEF` | `writeQEF` | one model; text; mask 0 is hidden; no alpha |
|
|
148
|
+
| `binvox` | `parseBinvox` | | one model of index 1 (version 2 files: the voxel values 1 to 255 as indices), plus the header's `translate` and `scale` |
|
|
149
|
+
| KVX | `parseKVX` | | the first, largest mip; colour 255 is air; file colour k is index k + 1; `pivot` in cells; a column offset outside the voxel data is refused as damage |
|
|
150
|
+
| VXL | `parseVXL` | | Voxlap maps, with a header or bare (`size`, default 512 x 512 x 64); solid cells without a colour take the last one above them |
|
|
151
|
+
| Goxel `.gox` | `parseGOX` | `writeGOX` (async) | every layer with its name, `visible`, blend `mode` and `material`; clone and shape layers built; Z up in the file, so file (x, y, z) is cell (x, z, -y); any non-zero alpha is solid |
|
|
152
|
+
| VoxEdit `.vxm` | `parseVXM` | `writeVXM` | versions 3 to 13 read, 12 written; every model (one size, no positions), materials as palette indices 1 to 255, `emissive` flags and `pivot`; the file's X runs mirrored |
|
|
153
|
+
|
|
154
|
+
KVX and VXL have z running down in the file, so they turn to Y up on reading: the file's y becomes z. A true-colour file
|
|
155
|
+
with over 255 colours loses low bits from each channel, the same on every run, until 255 are left, and `colorsReduced`
|
|
156
|
+
is true. Block-game `.schematic` is left out on purpose.
|
|
157
|
+
|
|
158
|
+
MagicaVoxel `.vox` files are read and written by `@margoengine/voxel/vox` (`parseVox`, `writeVox`); `./vox` here turns a
|
|
159
|
+
model into this package's Y-up grid and back. A parsed scene writes back byte for byte, edits included.
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
import { gridFromVox, voxFromGrid } from '@margoengine/voxel-edit/vox';
|
|
163
|
+
import { parseVox, writeVox, type VoxScene } from '@margoengine/voxel/vox';
|
|
164
|
+
|
|
165
|
+
const palette = new Uint8Array(1024);
|
|
166
|
+
palette.set([232, 48, 21, 255], 4); // index 1: red
|
|
167
|
+
const scene: VoxScene = {
|
|
168
|
+
version: 200,
|
|
169
|
+
models: [{ size: [2, 1, 1], voxels: Uint8Array.of(0, 0, 0, 1, 1, 0, 0, 1) }], // x, y, z, index per voxel
|
|
170
|
+
palette,
|
|
171
|
+
materials: [],
|
|
172
|
+
nodes: [],
|
|
173
|
+
layers: [],
|
|
174
|
+
};
|
|
175
|
+
const file = writeVox(scene); // Uint8Array of a .vox
|
|
176
|
+
const read = parseVox(file);
|
|
177
|
+
const grid = gridFromVox(read.models[0]); // Y up: .vox (x, y, z) is cell (x, z, sizeY - 1 - y)
|
|
178
|
+
grid.voxels[0] = 2; // edit a cell
|
|
179
|
+
read.models[0] = voxFromGrid(grid, read.models[0]);
|
|
180
|
+
console.log(grid.size, writeVox(read).length > 0); // [ 2, 1, 1 ] true
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Goxel and VoxEdit files move both ways. A `.gox` keeps each layer's place, so a round trip gives back the same cells,
|
|
184
|
+
positions and colours; a `.vxm` has no positions, so its models share one size and sit at the origin.
|
|
185
|
+
|
|
186
|
+
```ts
|
|
187
|
+
import type { VoxelGrid } from '@margoengine/voxel-edit';
|
|
188
|
+
import { parseGOX, parseVXM, writeGOX, writeVXM } from '@margoengine/voxel-edit/formats';
|
|
189
|
+
|
|
190
|
+
const palette = new Uint8Array(1024);
|
|
191
|
+
palette.set([232, 48, 21, 255], 4); // index 1: red
|
|
192
|
+
const grid: VoxelGrid = { size: [2, 1, 1], voxels: Uint8Array.of(1, 1) };
|
|
193
|
+
const gox = await writeGOX({ name: 'body', position: [0, 0, 0], grid }, palette); // Uint8Array of a .gox
|
|
194
|
+
const read = parseGOX(gox); // one layer `body`, cropped to its voxels; one default material
|
|
195
|
+
const vxm = writeVXM(read.models, read.palette, { pivot: [0.5, 0, 0.5] }); // version 12
|
|
196
|
+
const { models: back, pivot, emissive } = parseVXM(vxm);
|
|
197
|
+
console.log(back[0].grid.voxels, read.materials[0].name, pivot, emissive[1]); // Uint8Array [1, 1] 'default' [0.5, 0, 0.5] 0
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
[docs/limits.md](../../docs/limits.md) ("Goxel and VoxEdit files") lists what the two readers leave out or cannot know. In
|
|
201
|
+
short: `.gox` cameras, light, preview and the fork-only chunks are skipped and chunk CRCs are not checked (writers put
|
|
202
|
+
0); `.vxm` baked meshes, textures and the trailer are skipped, only versions 4 and 12 were checked against real files,
|
|
203
|
+
and whether VoxEdit opens a written file without a baked mesh is not known.
|
|
204
|
+
|
|
205
|
+
## Smooth meshes
|
|
206
|
+
|
|
207
|
+
`./smooth` meshes a grid as a rounded surface in place of cubes. Its mesh has the same shape as `meshGrid`'s, so
|
|
208
|
+
`partitionMesh` and the exporters take it.
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
import { gridToExportSource } from '@margoengine/voxel-edit/export';
|
|
212
|
+
import { smoothGrid } from '@margoengine/voxel-edit/smooth';
|
|
213
|
+
|
|
214
|
+
const grid = { size: [3, 3, 3] as const, voxels: new Uint8Array(27).fill(1) };
|
|
215
|
+
const { mesh, stats } = smoothGrid(grid, { iterations: 4, blur: 1 });
|
|
216
|
+
const source = gridToExportSource(grid, [{ index: 1, color: [0.8, 0.3, 0.1] }], { mesh });
|
|
217
|
+
console.log(stats.quads, source.nodes[0].primitives.length);
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
`iterations` (default 2, up to 64) relaxes the points; each stays inside its own net cell, so the model never drifts.
|
|
221
|
+
`blur` (default 0, up to 8) is a box blur radius over the occupancy: rounder, but a part thinner than `2 * blur + 1` fades
|
|
222
|
+
away. Each quad takes the palette index of the nearest filled voxel. Cells that touch only along an edge or corner share a
|
|
223
|
+
surface point there, so such a model is closed but not manifold at that point.
|
|
224
|
+
|
|
225
|
+
## Mesh to voxels
|
|
226
|
+
|
|
227
|
+
`./voxelize` turns any triangle mesh into the grid and palette the rest of this package uses. Pass `size` (cells along
|
|
228
|
+
the longest axis) or `voxelSize` (mesh units per cell). `'surface'` fills each cell a triangle touches, one cell thick at
|
|
229
|
+
least; `'solid'` fills each cell whose centre is inside, which needs a closed mesh (`openRows` counts the x rows that
|
|
230
|
+
show a hole).
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
import { voxelizeMesh } from '@margoengine/voxel-edit/voxelize';
|
|
234
|
+
|
|
235
|
+
const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]);
|
|
236
|
+
const indices = [0, 2, 1, 0, 1, 3, 0, 3, 2, 1, 2, 3];
|
|
237
|
+
const uvs = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);
|
|
238
|
+
const texture = { width: 1, height: 1, data: new Uint8Array([200, 80, 40, 255]) };
|
|
239
|
+
const { grid, palette, origin, voxelSize, openRows } = await voxelizeMesh(positions, indices, {
|
|
240
|
+
size: 32,
|
|
241
|
+
fill: 'solid',
|
|
242
|
+
colors: { uvs, texture },
|
|
243
|
+
paletteSize: 64,
|
|
244
|
+
maxCells: 1_000_000,
|
|
245
|
+
signal: AbortSignal.timeout(10_000),
|
|
246
|
+
});
|
|
247
|
+
console.log(grid.size, palette.length, origin, voxelSize, openRows);
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
`colors` is `{vertex}` (RGB or RGBA per vertex, bytes in a `Uint8Array`, 0 to 1 otherwise) or `{uvs, texture}` (RGBA8, nearest
|
|
251
|
+
texel, repeating, row 0 at v = 0). Colours reach the palette as given and alpha is ignored. Without `colors` every cell is
|
|
252
|
+
index 1, white. Over `paletteSize` colours (default 255) median cut merges the nearest ones and `colorsReduced` is true.
|
|
253
|
+
`maxCells` defaults to 16,777,216. The call yields to the event loop while it runs, so a `signal` can stop it.
|
|
254
|
+
|
|
255
|
+
## Saved formats
|
|
256
|
+
|
|
257
|
+
`SparseGrid.serialize` writes `{format: 'margo-sparse-volume', version: 1, ...}` and `packFrames` writes
|
|
258
|
+
`{version: 1, banks, keys}`: plain JSON, read back with full validation, so untrusted files are safe to load.
|
|
259
|
+
|
|
260
|
+
A sparse grid's engine cells (`origin + cell`) stay in one of two envelopes, chosen by `SparseGrid.empty`'s
|
|
261
|
+
`envelope` option. `'world'` (the default) is a `VoxelWorld`'s range: Y from -32,768 to 32,767, X and Z 32-bit; such
|
|
262
|
+
grids save as version 1, as before. `'wide'` allows any whole number up to 2^53 - 1 in size on every axis; a grid past
|
|
263
|
+
the world range saves as version 2 with the same fields (older readers refuse it rather than misplace it), and
|
|
264
|
+
`toWorld` refuses cells a world cannot hold. Either way a grid holds at most 2^53 - 1 cells, so a cell index
|
|
265
|
+
(`x + size[0] * (z + size[2] * y)`, the selections of `./edit`) is an exact double. Mesh positions are float32, exact
|
|
266
|
+
within 2^24 cells of the pivot.
|
|
267
|
+
|
|
268
|
+
## Workers
|
|
269
|
+
|
|
270
|
+
`grid.snapshot()` packs a sparse grid into five typed arrays on new buffers that nothing else refers to; post it with
|
|
271
|
+
`snapshotBuffers(snapshot)` as the transfer list, which moves the bytes instead of copying them and leaves the grid
|
|
272
|
+
unchanged. `SparseGrid.fromSnapshot` (one grid) and `restoreSnapshots` (several, one `maxBytes` budget across them)
|
|
273
|
+
check everything before decoding and copy what they keep, so the receiver may drop or reuse the buffers.
|
|
274
|
+
`SparseGrid.deltaSnapshot(delta)` packs only the chunks one edit touched, before and after; a worker holding the grid
|
|
275
|
+
before the edit replays it with `applyDeltaSnapshot` (or undoes it with side `'before'`), which refuses with a
|
|
276
|
+
`MargoError` code `state` unless the worker's grid holds exactly the chunks the delta starts from.
|
|
277
|
+
|
|
278
|
+
## Shader brushes (`./shaders`)
|
|
279
|
+
|
|
280
|
+
`ShaderBrush` runs a small WGSL function on the GPU (WebGPU compute) for every selected cell of a grid. The function
|
|
281
|
+
gets the cell and its palette index and returns the new index; it can read any cell of the grid as it was before the
|
|
282
|
+
pass, so brushes that grow, erode, smooth or generate shapes are a few lines. The grid you pass is never changed.
|
|
283
|
+
|
|
284
|
+
```ts
|
|
285
|
+
import { dilateGrid, type VoxelGrid } from 'margoengine/voxel-edit';
|
|
286
|
+
import { brushes, ShaderBrush } from 'margoengine/voxel-edit/shaders';
|
|
287
|
+
|
|
288
|
+
const adapter = await navigator.gpu.requestAdapter();
|
|
289
|
+
const device = await adapter!.requestDevice();
|
|
290
|
+
const model: VoxelGrid = { size: [64, 64, 64], voxels: new Uint8Array(64 ** 3) };
|
|
291
|
+
model.voxels[32 + 64 * (32 + 64 * 32)] = 5; // one cell in the middle
|
|
292
|
+
|
|
293
|
+
const grow = await ShaderBrush.create(device, brushes.grow);
|
|
294
|
+
const { grid, changed } = await grow.run(model, { passes: 3 }); // the same cells as dilateGrid(model, {iterations: 3})
|
|
295
|
+
const reference = dilateGrid(model, { iterations: 3 }).grid;
|
|
296
|
+
console.log(changed, grid.voxels.every((v, i) => v === reference.voxels[i]));
|
|
297
|
+
|
|
298
|
+
// Your own brush: rings of colour by height inside the selection, rough edges from noise.
|
|
299
|
+
const rings = await ShaderBrush.create(
|
|
300
|
+
device,
|
|
301
|
+
`fn brush(p: vec3<i32>, value: u32) -> u32 {
|
|
302
|
+
if (value == 0u || noise(vec3<f32>(p) * param(0)) < 0.3) { return value; }
|
|
303
|
+
return 1u + u32(p.y / 4) % 3u;
|
|
304
|
+
}`,
|
|
305
|
+
);
|
|
306
|
+
const shaded = await rings.run(grid, { params: [0.2], seed: 7 });
|
|
307
|
+
grow.dispose();
|
|
308
|
+
rings.dispose();
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
- **What the code can call.** `cell(q)` (the index at any cell, 0 outside), `inside(q)`, `cell_index(q)`, `grid_size()`,
|
|
312
|
+
`face_offset(d)` (d 0 to 5: -x, +x, -y, +y, -z, +z), `param(i)` (the run's `params`, up to 16 numbers),
|
|
313
|
+
`pass_number()`, `tool(q)` (a second grid placed at `toolOffset`), `lookup(i)` (the run's 256-entry `table`),
|
|
314
|
+
`hash(q, salt)` (0 to 1, mixed with `seed`) and `noise(x)` (value noise 0 to 1). The result is clamped to 255.
|
|
315
|
+
- **Presets.** `brushes.grow` and `brushes.erode` give exactly `dilateGrid` and `erodeGrid` with all six directions
|
|
316
|
+
(`params: [color]` colours the grown cells); `brushes.noise` fills where `noise(p * param(0)) > param(1)` with
|
|
317
|
+
`param(2)`; `brushes.smooth` keeps a cell filled when most of its 27 neighbourhood cells are.
|
|
318
|
+
- **Runs.** `run(grid, {selection, passes, params, seed, tool, toolOffset, table, maxCells, signal})`: `selection` is
|
|
319
|
+
cell indexes (as `./edit` returns them; default every cell), `passes` 1 to 1,024, each reading the one before. It
|
|
320
|
+
resolves to `{grid, changed, clipped: 0}` like the CPU operations.
|
|
321
|
+
- **Errors.** `TypeError` for a wrong device, code without `fn brush`, or a bad option; `RangeError` for a value out of
|
|
322
|
+
range or a grid over the device's storage binding limit; `MargoError` `failed` for WGSL that does not compile, naming
|
|
323
|
+
the line of your code, and `disposed` after `dispose()`. `label` names the GPU objects for debuggers.
|
|
324
|
+
|
|
325
|
+
## Bones and posed voxel parts (`./rig`)
|
|
326
|
+
|
|
327
|
+
`VoxelRig` attaches voxel parts to the bones of a skeleton, the way blocky characters are animated: each part moves
|
|
328
|
+
rigidly with its bone, and a bone turns about its joint carrying its children with it. `matrices(pose)` gives every
|
|
329
|
+
part a model matrix (column-major, cells to model cells) to draw its `meshGrid` mesh with; `bake(pose)` resamples the
|
|
330
|
+
posed parts into one grid (each cell takes the part cell under its centre, so turned parts keep no holes), for frames,
|
|
331
|
+
export or a world. Joints and offsets are in model cells, Y up.
|
|
332
|
+
|
|
333
|
+
```ts
|
|
334
|
+
import type { VoxelGrid } from 'margoengine/voxel-edit';
|
|
335
|
+
import { meshGrid } from 'margoengine/voxel-edit/mesh';
|
|
336
|
+
import { rigRotation, sampleRigClip, VoxelRig } from 'margoengine/voxel-edit/rig';
|
|
337
|
+
|
|
338
|
+
const block = (sx: number, sy: number, sz: number, value: number): VoxelGrid => ({
|
|
339
|
+
size: [sx, sy, sz],
|
|
340
|
+
voxels: new Uint8Array(sx * sy * sz).fill(value),
|
|
341
|
+
});
|
|
342
|
+
const rig = new VoxelRig({
|
|
343
|
+
bones: [
|
|
344
|
+
{ name: 'body', joint: [4, 0, 2] },
|
|
345
|
+
{ name: 'arm', parent: 'body', joint: [8, 9, 2] },
|
|
346
|
+
],
|
|
347
|
+
parts: [
|
|
348
|
+
{ bone: 'body', grid: block(8, 10, 4, 1) },
|
|
349
|
+
{ bone: 'arm', grid: block(2, 8, 2, 2), offset: [8, 2, 1] },
|
|
350
|
+
],
|
|
351
|
+
});
|
|
352
|
+
const wave = {
|
|
353
|
+
duration: 1,
|
|
354
|
+
loop: true,
|
|
355
|
+
tracks: [{ bone: 'arm', times: [0, 0.5, 1], rotations: [rigRotation([0, 0, 1], 0), rigRotation([0, 0, 1], 90), rigRotation([0, 0, 1], 0)] }],
|
|
356
|
+
};
|
|
357
|
+
const pose = { rotations: sampleRigClip(wave, 0.25) };
|
|
358
|
+
const [, armMatrix] = rig.matrices(pose); // draw meshGrid(part.grid) with these
|
|
359
|
+
const { grid, origin } = rig.bake(pose); // the posed character as one grid; origin is its corner in model cells
|
|
360
|
+
console.log(armMatrix.length, grid.size, origin, meshGrid(grid).mesh.positions.length > 0);
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
- **Poses.** `rotations` maps bone names to unit quaternions `[x, y, z, w]` (`rigRotation(axis, degrees)` builds one),
|
|
364
|
+
applied about the bone's joint after its parent's turn; a bone left out turns with its parent. `translation` moves
|
|
365
|
+
the whole model. A non-unit quaternion, an unknown bone or a parent listed after its child is refused with a fix.
|
|
366
|
+
- **Clips.** `sampleRigClip(clip, time)` interpolates each track's keys by spherical interpolation (the short way
|
|
367
|
+
round), holds the first and last key, and wraps time when `loop` is true.
|
|
368
|
+
- **Baking.** A quarter turn bakes exactly as `turnGrid`; other angles resample at cell centres, so a part keeps its
|
|
369
|
+
cell count only roughly. Later parts draw over earlier ones. The posed box is limited by `maxCells` (default
|
|
370
|
+
16,777,216).
|
|
371
|
+
- **Rigid parts.** Each part follows one bone (rigid skinning, as blocky characters use); cells are not blended
|
|
372
|
+
between bones. For smooth skinned meshes use `@margoengine/rigging` and `@margoengine/animation`.
|
|
373
|
+
|
|
374
|
+
## GPU bulk edits (`./gpu`)
|
|
375
|
+
|
|
376
|
+
`GpuGrid` keeps a grid on the GPU (WebGPU compute) so large fills, booleans and filters run as compute passes, one
|
|
377
|
+
after another with no read-back in between; `read()` brings the cells back once at the end. Every operation gives
|
|
378
|
+
exactly the cells of its CPU counterpart: `fill` the cells of `boxCells` (with `max` exclusive) or `sphereCells`,
|
|
379
|
+
`combine` those of `combineGrids`, `dilate` and `erode` those of `dilateGrid` and `erodeGrid` (all six directions),
|
|
380
|
+
`smooth` the `smooth` shader brush, and `brush` any `ShaderBrush` made on the same device.
|
|
381
|
+
|
|
382
|
+
```ts
|
|
383
|
+
import type { VoxelGrid } from 'margoengine/voxel-edit';
|
|
384
|
+
import { GpuGrid } from 'margoengine/voxel-edit/gpu';
|
|
385
|
+
|
|
386
|
+
const adapter = await navigator.gpu.requestAdapter();
|
|
387
|
+
const device = await adapter!.requestDevice();
|
|
388
|
+
const n = 256; // 16.7 million cells
|
|
389
|
+
const model: VoxelGrid = { size: [n, n, n], voxels: new Uint8Array(n ** 3) };
|
|
390
|
+
const tool: VoxelGrid = { size: [32, 32, 32], voxels: new Uint8Array(32 ** 3).fill(2) };
|
|
391
|
+
const map = Uint8Array.from({ length: 256 }, (_, i) => i); // tool indexes kept as they are
|
|
392
|
+
|
|
393
|
+
const grid = await GpuGrid.create(device, model);
|
|
394
|
+
grid
|
|
395
|
+
.fill({ shape: 'box', min: [0, 0, 0], max: [n, 64, n] }, 1) // a floor 64 cells deep
|
|
396
|
+
.fill({ shape: 'sphere', center: [128, 64, 128], radius: 40 }, 0); // a crater in it
|
|
397
|
+
const clipped = grid.combine(tool, { operation: 'union', offset: [240, 64, 240], paletteMap: map });
|
|
398
|
+
grid.dilate({ iterations: 2 }).erode().smooth();
|
|
399
|
+
const edited = await grid.read();
|
|
400
|
+
console.log(clipped, edited.voxels.filter((v) => v !== 0).length);
|
|
401
|
+
grid.dispose();
|
|
402
|
+
```
|
|
403
|
+
|
|
404
|
+
- **Order.** Edits queue at once and run in order on the GPU; each reads the grid the edit before left. `combine`
|
|
405
|
+
returns the tool cells that fall outside the grid, counted on the CPU.
|
|
406
|
+
- **Limits.** A grid must fit one storage binding (128 MiB by default: raise `maxStorageBufferBindingSize` when
|
|
407
|
+
requesting the device) and `maxCells` (default 16,777,216, at most 67,108,864). `write(grid)` replaces every cell;
|
|
408
|
+
`remap(table)` replaces each index `i` by `table[i]`.
|
|
409
|
+
- **Lifetime.** `dispose()` (or `using`) frees the GPU buffers; any call after it throws a `MargoError` with code
|
|
410
|
+
`disposed`.
|
|
411
|
+
|
|
412
|
+
## Shared editing (`./collab`)
|
|
413
|
+
|
|
414
|
+
`VoxelReplica` lets several people edit one model at once. Each user holds a replica of the grid; `edit` makes an
|
|
415
|
+
operation to send to the others and `apply` takes anyone's operation, in any order and any number of times. Every
|
|
416
|
+
operation carries a Lamport clock, and each cell keeps the write with the highest clock (the higher site name breaks a
|
|
417
|
+
tie), so replicas that have applied the same operations hold the same cells: there is no conflict to resolve and no
|
|
418
|
+
server to order the edits. Send operations over any channel (WebSocket, WebRTC, a `BroadcastChannel`) as bytes.
|
|
419
|
+
|
|
420
|
+
```ts
|
|
421
|
+
import { decodeVoxelOp, encodeVoxelOp, VoxelReplica } from 'margoengine/voxel-edit/collab';
|
|
422
|
+
|
|
423
|
+
const start = { size: [32, 16, 32] as [number, number, number], voxels: new Uint8Array(32 * 16 * 32) };
|
|
424
|
+
const ann = new VoxelReplica(start, { site: 'ann' });
|
|
425
|
+
const bo = new VoxelReplica(start, { site: 'bo' });
|
|
426
|
+
|
|
427
|
+
// Both paint cell 40 at the same moment, neither having seen the other's edit.
|
|
428
|
+
const fromAnn = encodeVoxelOp(ann.edit([40, 41], 3));
|
|
429
|
+
const fromBo = encodeVoxelOp(bo.edit([40], 7));
|
|
430
|
+
bo.apply(decodeVoxelOp(fromAnn));
|
|
431
|
+
ann.apply(decodeVoxelOp(fromBo));
|
|
432
|
+
console.log(ann.get(40), bo.get(40), ann.get(41)); // 7 7 3: the same cells on both
|
|
433
|
+
|
|
434
|
+
// A peer that was away catches up with only what it lacks; a newcomer starts from a snapshot.
|
|
435
|
+
for (const op of ann.since(bo.version)) bo.apply(op);
|
|
436
|
+
const cy = VoxelReplica.fromSnapshot(ann.snapshot(), { site: 'cy' });
|
|
437
|
+
cy.onChange((op, changed) => console.log(`${op.site} changed ${changed} cells`));
|
|
438
|
+
cy.apply(ann.edit([42], 1)); // ann changed 1 cells
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
- **Order.** Apply operations as they arrive; a repeat does nothing. `version` counts, per site, the operations held
|
|
442
|
+
with none missing before them, so `since(version)` also resends anything that arrived out of order.
|
|
443
|
+
- **Memory.** A replica keeps 7 bytes a cell (the cell, its last write's clock and site) and every operation it has
|
|
444
|
+
seen, so a long session grows by 5 bytes per edited cell. `maxCells` defaults to 16,777,216; 65,535 sites at most.
|
|
445
|
+
- **Scope.** Each cell takes the latest value written to it; edits are not combined (two users drawing over each other
|
|
446
|
+
leave the later stroke). Operations name cells by index, so every replica must start from a grid of the same size.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { Vec3 } from '@margoengine/math';
|
|
2
|
+
import { type GridLimits, type VoxelGrid } from './grid.js';
|
|
3
|
+
/** A model as stored in a packed animation: a grid and an optional pivot. */
|
|
4
|
+
export interface FrameBank extends VoxelGrid {
|
|
5
|
+
/** Pivot point in cells, each within +-1,000,000; may lie outside the grid. */
|
|
6
|
+
pivot?: Vec3;
|
|
7
|
+
}
|
|
8
|
+
/** One key of a frame animation: the model shown from `frame` on. */
|
|
9
|
+
export interface GridFrame extends FrameBank {
|
|
10
|
+
/** Frame number, 0 to 2,147,483,647. */
|
|
11
|
+
frame: number;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A packed frame animation ({@link packFrames}): each distinct model once in `banks`, and per key the bank it shows.
|
|
15
|
+
* Plain data, safe to save; the field names are a stable format.
|
|
16
|
+
*/
|
|
17
|
+
export interface PackedFrames {
|
|
18
|
+
version: 1;
|
|
19
|
+
banks: FrameBank[];
|
|
20
|
+
keys: {
|
|
21
|
+
frame: number;
|
|
22
|
+
bank: number;
|
|
23
|
+
}[];
|
|
24
|
+
}
|
|
25
|
+
/** A clip's own clock inside a document's frame count. */
|
|
26
|
+
export interface LocalTimeline {
|
|
27
|
+
/** Document frame where the clip starts, within int32. */
|
|
28
|
+
offset: number;
|
|
29
|
+
/** First and last clip frame played, 0 to 2,147,483,647, `startFrame <= endFrame`. */
|
|
30
|
+
startFrame: number;
|
|
31
|
+
endFrame: number;
|
|
32
|
+
/** Clip frames per document frame, 1/256 to 256. */
|
|
33
|
+
speed: number;
|
|
34
|
+
/** Repeat from `startFrame` after `endFrame` (true) or hold `endFrame` (false). */
|
|
35
|
+
loop: boolean;
|
|
36
|
+
}
|
|
37
|
+
/** Throws unless `value` is a valid {@link LocalTimeline}. */
|
|
38
|
+
export declare function checkTimeline(value: unknown): asserts value is LocalTimeline;
|
|
39
|
+
/**
|
|
40
|
+
* The clip frame showing at document frame `frame`: `frame` itself without a timeline. Fractional results let callers
|
|
41
|
+
* interpolate; before `offset` the clip shows `startFrame`.
|
|
42
|
+
*/
|
|
43
|
+
export declare function localFrame(frame: number, timeline?: LocalTimeline): number;
|
|
44
|
+
/**
|
|
45
|
+
* Packs keys (sorted by frame, at most 4,096, `maxCells` cells in all) so equal models (same size, pivot and cells)
|
|
46
|
+
* are stored once. The result owns copies; changing the input later does not change it.
|
|
47
|
+
*/
|
|
48
|
+
export declare function packFrames(frames: readonly GridFrame[], limits?: GridLimits): PackedFrames;
|
|
49
|
+
/** Unpacks {@link PackedFrames} (untrusted input is fine) into keys that each own their grid. */
|
|
50
|
+
export declare function unpackFrames(packed: PackedFrames, limits?: GridLimits): GridFrame[];
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { c as e, o as t } from "./grid-B2V0TGLV.js";
|
|
2
|
+
//#region src/animation.ts
|
|
3
|
+
var n = 2147483647, r = 4096, i = 1e6;
|
|
4
|
+
function a(e, t, n, r) {
|
|
5
|
+
if (typeof e != "number" || !Number.isSafeInteger(e) || e < t || e > n) throw RangeError(`${r} must be an integer from ${t} to ${n}; pass one`);
|
|
6
|
+
}
|
|
7
|
+
function o(e) {
|
|
8
|
+
if (typeof e != "object" || !e || Array.isArray(e)) throw TypeError("A timeline is not an object; pass {offset, startFrame, endFrame, speed, loop}");
|
|
9
|
+
let t = e;
|
|
10
|
+
if (a(t.offset, -2147483647, n, "Timeline offset"), a(t.startFrame, 0, n, "Timeline startFrame"), a(t.endFrame, t.startFrame, n, "Timeline endFrame"), !Number.isFinite(t.speed) || t.speed < 1 / 256 || t.speed > 256) throw RangeError("Timeline speed must be 1/256 to 256; pass a speed in range");
|
|
11
|
+
if (typeof t.loop != "boolean") throw TypeError("Timeline loop is not a boolean; pass true or false");
|
|
12
|
+
}
|
|
13
|
+
function s(e, t) {
|
|
14
|
+
if (a(e, 0, n, "Document frame"), !t) return e;
|
|
15
|
+
o(t);
|
|
16
|
+
let r = Math.max(0, e - t.offset) * t.speed, i = t.endFrame - t.startFrame;
|
|
17
|
+
return t.startFrame + (t.loop ? r % (i + 1) : Math.min(i, r));
|
|
18
|
+
}
|
|
19
|
+
function c(t, n) {
|
|
20
|
+
let r = e(t, n, "Frame grid"), a = t.pivot;
|
|
21
|
+
if (a !== void 0) {
|
|
22
|
+
if (!Array.isArray(a) || a.length !== 3) throw TypeError("Frame pivot is not [x, y, z]; pass three numbers");
|
|
23
|
+
if (!Array.from(a).every((e) => Number.isFinite(e) && Math.abs(e) <= i)) throw RangeError(`Frame pivot must be finite within +-${i}; move the pivot closer`);
|
|
24
|
+
}
|
|
25
|
+
return r;
|
|
26
|
+
}
|
|
27
|
+
function l(e) {
|
|
28
|
+
let t = {
|
|
29
|
+
size: [
|
|
30
|
+
e.size[0],
|
|
31
|
+
e.size[1],
|
|
32
|
+
e.size[2]
|
|
33
|
+
],
|
|
34
|
+
voxels: e.voxels.slice()
|
|
35
|
+
};
|
|
36
|
+
return e.pivot && (t.pivot = [
|
|
37
|
+
e.pivot[0],
|
|
38
|
+
e.pivot[1],
|
|
39
|
+
e.pivot[2]
|
|
40
|
+
]), t;
|
|
41
|
+
}
|
|
42
|
+
function u(e, t) {
|
|
43
|
+
if (e.voxels.length !== t.voxels.length) return !1;
|
|
44
|
+
for (let n = 0; n < e.voxels.length; n++) if (e.voxels[n] !== t.voxels[n]) return !1;
|
|
45
|
+
return !0;
|
|
46
|
+
}
|
|
47
|
+
function d(e) {
|
|
48
|
+
let t = 2166136261;
|
|
49
|
+
for (let n of e.voxels) t = Math.imul(t ^ n, 16777619) >>> 0;
|
|
50
|
+
return `${e.size.join(",")}/${e.pivot?.join(",") ?? "-"}/${t}`;
|
|
51
|
+
}
|
|
52
|
+
function f(e, i = {}) {
|
|
53
|
+
if (!Array.isArray(e)) throw TypeError("packFrames frames is not an array; pass the keys");
|
|
54
|
+
if (e.length > r) throw RangeError(`packFrames takes at most ${r} keys; split the clip`);
|
|
55
|
+
let o = t(i), s = -1, f = 0;
|
|
56
|
+
for (let t of e) {
|
|
57
|
+
if (a(t?.frame, 0, n, "Frame number"), t.frame <= s) throw RangeError("packFrames keys are not sorted and unique by frame; sort them");
|
|
58
|
+
if (s = t.frame, f += c(t, o), f > o) throw RangeError(`packFrames keys hold over ${o} cells; raise maxCells or split the clip`);
|
|
59
|
+
}
|
|
60
|
+
let p = {
|
|
61
|
+
version: 1,
|
|
62
|
+
banks: [],
|
|
63
|
+
keys: []
|
|
64
|
+
}, m = /* @__PURE__ */ new Map();
|
|
65
|
+
for (let t of e) {
|
|
66
|
+
let e = d(t), n = m.get(e) ?? [], r = n.find((e) => u(p.banks[e], t));
|
|
67
|
+
r === void 0 && (r = p.banks.push(l(t)) - 1, n.push(r), m.set(e, n)), p.keys.push({
|
|
68
|
+
frame: t.frame,
|
|
69
|
+
bank: r
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
return p;
|
|
73
|
+
}
|
|
74
|
+
function p(e, i = {}) {
|
|
75
|
+
if (typeof e != "object" || !e || e.version !== 1) throw TypeError("unpackFrames data is not packed frames version 1; pass what packFrames returned");
|
|
76
|
+
if (!Array.isArray(e.banks) || !Array.isArray(e.keys) || e.banks.length > r || e.keys.length > r) throw RangeError(`unpackFrames data holds over ${r} banks or keys; split the clip`);
|
|
77
|
+
let o = t(i), s = e.banks.map((e) => c(e, o)), u = -1, d = 0;
|
|
78
|
+
for (let t of e.keys) {
|
|
79
|
+
if (a(t?.frame, 0, n, "Frame number"), a(t.bank, 0, e.banks.length - 1, "Frame bank reference"), t.frame <= u) throw RangeError("unpackFrames keys are not sorted and unique by frame; fix the data");
|
|
80
|
+
if (u = t.frame, d += s[t.bank], d > o) throw RangeError(`unpackFrames keys hold over ${o} cells; raise maxCells`);
|
|
81
|
+
}
|
|
82
|
+
return e.keys.map((t) => ({
|
|
83
|
+
frame: t.frame,
|
|
84
|
+
...l(e.banks[t.bank])
|
|
85
|
+
}));
|
|
86
|
+
}
|
|
87
|
+
//#endregion
|
|
88
|
+
export { o as checkTimeline, s as localFrame, f as packFrames, p as unpackFrames };
|
package/dist/assist.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type GridLimits, type VoxelGrid } from './grid.js';
|
|
2
|
+
/**
|
|
3
|
+
* A new grid of `size` where each cell is filled with `palette` (default 1) when a seeded random value in [0, 1)
|
|
4
|
+
* exceeds `threshold` (default 0.5). Cells are independent (white noise, not smooth noise); the same `seed` (a 32-bit
|
|
5
|
+
* integer, default 1) gives the same grid.
|
|
6
|
+
* @throws RangeError when `size` is not three positive integers or holds more than 16,777,216 cells, `threshold` is
|
|
7
|
+
* outside [0, 1], `seed` is not an integer, or `palette` is not an integer from 1 to 255.
|
|
8
|
+
*/
|
|
9
|
+
export declare function noiseFill(size: [number, number, number], options?: {
|
|
10
|
+
threshold?: number;
|
|
11
|
+
seed?: number;
|
|
12
|
+
palette?: number;
|
|
13
|
+
}): VoxelGrid;
|
|
14
|
+
/**
|
|
15
|
+
* `count` (1 to 16) colours of seeded random hue at fixed saturation and lightness, as a quick starting palette.
|
|
16
|
+
* Returns linear sRGB `[r, g, b]` colours, 0 to 1, the engine's linear colour convention.
|
|
17
|
+
* @throws RangeError when `count` is not an integer from 1 to 16.
|
|
18
|
+
*/
|
|
19
|
+
export declare function suggestPalette(count: number, seed?: number): [number, number, number][];
|
|
20
|
+
/**
|
|
21
|
+
* How many cells of each palette index a grid uses, 256 counts. Index 0 is air and is included.
|
|
22
|
+
* @throws RangeError past `maxCells` (default 16,777,216, at most 67,108,864), like every grid operation.
|
|
23
|
+
*/
|
|
24
|
+
export declare function paletteUsage(grid: VoxelGrid, limits?: GridLimits): Uint32Array;
|