@margoengine/points 0.0.0-stage → 0.1.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 (52) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +794 -3
  4. package/dist/attributes-DNc-1pdr.js +256 -0
  5. package/dist/attributes.d.ts +48 -0
  6. package/dist/clip.d.ts +55 -0
  7. package/dist/clip.js +122 -0
  8. package/dist/cloud-B4O_G-Df.js +545 -0
  9. package/dist/cloud.d.ts +155 -0
  10. package/dist/color.d.ts +1 -0
  11. package/dist/copc.d.ts +55 -0
  12. package/dist/copc.js +130 -0
  13. package/dist/depth-video.d.ts +98 -0
  14. package/dist/depth-video.js +164 -0
  15. package/dist/e57.d.ts +163 -0
  16. package/dist/e57.js +624 -0
  17. package/dist/frame.d.ts +9 -0
  18. package/dist/index.d.ts +16 -0
  19. package/dist/index.js +1246 -0
  20. package/dist/las.d.ts +213 -0
  21. package/dist/las.js +500 -0
  22. package/dist/laz.d.ts +50 -0
  23. package/dist/laz.js +1025 -0
  24. package/dist/material.d.ts +167 -0
  25. package/dist/math.d.ts +103 -0
  26. package/dist/octree.d.ts +182 -0
  27. package/dist/octree.js +360 -0
  28. package/dist/pick.d.ts +76 -0
  29. package/dist/pick.js +192 -0
  30. package/dist/plugin.d.ts +235 -0
  31. package/dist/potree.d.ts +70 -0
  32. package/dist/potree.js +451 -0
  33. package/dist/range-BQuJAjUM.js +23 -0
  34. package/dist/range.d.ts +4 -0
  35. package/dist/screen-door-CALlYs39.js +7 -0
  36. package/dist/shaders-Deu8H36P.js +278 -0
  37. package/dist/shaders.d.ts +52 -0
  38. package/dist/shared/fog.d.ts +33 -0
  39. package/dist/shared/pass.d.ts +53 -0
  40. package/dist/shared/selection-mask.d.ts +52 -0
  41. package/dist/shared/style-expression.d.ts +18 -0
  42. package/dist/sprites.d.ts +78 -0
  43. package/dist/storage-limit.d.ts +6 -0
  44. package/dist/style.d.ts +124 -0
  45. package/dist/style.js +708 -0
  46. package/dist/surfels.d.ts +95 -0
  47. package/dist/surfels.js +538 -0
  48. package/dist/survey-DToZwkJv.js +46 -0
  49. package/dist/survey.d.ts +10 -0
  50. package/dist/tier-BcFbLPVT.js +91 -0
  51. package/dist/tier.d.ts +6 -0
  52. package/package.json +96 -6
package/README.md CHANGED
@@ -1,3 +1,794 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @margoengine/points
2
+
3
+ Import `margoengine/points` from the `margoengine` package, or `@margoengine/points` 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
+ Large point clouds and instanced sprites for Margo Engine, WebGPU, built for big scans: the browser test culls and draws a 2,000,000-point cloud under a 500,000-point budget.
6
+
7
+ Build from source with `npm run build` in `packages/points`.
8
+
9
+ ```ts
10
+ import {Engine} from 'margoengine/core';
11
+ import {PointsPlugin, PointCloud, SpriteBatch, atlasRect} from 'margoengine/points';
12
+ import {createMesh} from 'margoengine/materials';
13
+ import {box} from 'margoengine/core';
14
+ const canvas = document.querySelector('canvas')!;
15
+
16
+ const engine = await Engine.create(canvas);
17
+ const mesh = engine.createMesh().setGeometry(box());
18
+ const points = PointsPlugin.attach(engine, {pointBudget: 2_000_000});
19
+
20
+ // Any {positions, colors?, normals?} works, including the point-cloud output of @margoengine/loaders.
21
+ const positions = new Float32Array(30_000).map(() => Math.random() * 10), colors = new Float32Array(30_000).fill(1);
22
+ const cloud = points.add(new PointCloud({
23
+ positions, // Float32Array, xyz per point (used in place)
24
+ colors, // RGB or RGBA, floats 0..1 or a Uint8Array 0..255
25
+ material: {size: 2, shape: 'round', edl: true},
26
+ }));
27
+ cloud.attach(mesh); // follow a core mesh's world matrix
28
+
29
+ // Change 100 points: only those 1200 bytes are written to the GPU.
30
+ const newXyz = new Float32Array(300).map(() => Math.random() * 10);
31
+ cloud.updatePositions(5000, newXyz);
32
+
33
+ // Thousands of camera-facing sprites in one draw call.
34
+ const atlas = new OffscreenCanvas(64, 64);
35
+ const ctx = atlas.getContext('2d')!;
36
+ ctx.fillStyle = 'white';
37
+ ctx.fillRect(0, 0, 64, 64);
38
+ const labels = points.add(new SpriteBatch({material: {map: atlas}}));
39
+ labels.add({position: [0, 2, 0], size: 0.5, uv: atlasRect(3, 4, 4)});
40
+ engine.render();
41
+
42
+ // CPU picking of the nearest drawn point.
43
+ canvas.addEventListener('click', event => {
44
+ const hit = points.pick(event.offsetX, event.offsetY, {radius: 8});
45
+ if (hit) console.log(hit.index, hit.position);
46
+ });
47
+ ```
48
+
49
+ ## How it works
50
+
51
+ - **Blocks.** `new PointCloud()` splits the points into spatially compact blocks of at most `blockSize` points (median splits along the longest axis, like a kd-tree) and records each block's bounds. Each frame the plugin transforms every block's bounds by the model matrix and frustum-culls it on the CPU against `camera.planes`.
52
+ - **Point budget and level of detail.** The points inside each block are shuffled once with a seeded PRNG, so the first `k` slots of a block are an even random sample of it. Visible blocks share `pointBudget` in proportion to their projected screen area, and blocks that need less than their share give the rest to the others. Each block then draws a prefix of its slots: one `draw(4, k, 0, firstSlot)` call per visible block. This is the progressive subsampling Potree uses, without its octree files.
53
+ - **GPU data.** Positions (f32 xyz), packed RGBA8 colors, optional f32 sizes and the shuffled slot order live in storage buffers; the vertex shader expands each point into a quad (a 4-vertex triangle strip per instance). The arrays stay in your order, so `updatePositions`, `updateColors` and `updateSizes` call `writeBuffer` on exactly the changed byte range. Position updates also grow the affected blocks' bounds.
54
+ - **Frame uploads.** Points and sprites share a 144-byte camera uniform. Consecutive views with identical uniform bytes reuse the last upload; camera, viewport, format or projection changes upload again. Device restoration always uploads to the new buffer. This removes one queue write per unchanged view; timing is pending the quiet rerun.
55
+ - **Shapes and shading.** Square points cover exactly `size x size` pixels. Round points are an antialiased disc with an extra pixel of quad. A `map` (any `GPUTexture`, or an `ImageBitmap`, canvas, image, video or `ImageData` that the plugin uploads as `rgba8unorm-srgb`) is sampled across the point, with `alphaTest` or blending. `shading: 'sphere'` lights each point as a sphere impostor and writes its curved depth with `frag_depth`. `edl: true` adds eye-dome lighting: points also write their view depth into an `r32float` target and a full-screen pass multiplies the color by `exp(-32 * strength * mean(max(0, log2 d - log2 d_neighbor)))` over 8 neighbors `edlRadius` pixels away (Boucheny's eye-dome lighting; background neighbors count as 0).
56
+ - **Depth.** Points test against the scene with reversed-Z `greater-equal` and opaque points write depth, so they hide behind meshes and occlude each other. Transparent materials blend without writing depth.
57
+ - **Engine views.** Point sizes and level of detail follow the view being drawn. `pick(x, y)` picks through the canvas view under the point with that view's camera; `pick(x, y, {view: id})` through a named one (`RenderView.id`). A view not drawn for a frame is forgotten.
58
+ - **Orthographic cameras.** Everything is read from `camera.matrix`, so any projection whose clip w is constant (such as `CameraProjection` from `@margoengine/cameras`) works without a dependency on it: world-unit sizes use the matrix's pixels per world unit and stay the same at every depth, sphere impostors write linear depth, eye-dome lighting shades linear depth steps (scaled like the log steps a perspective camera with the same zoom would give), block budgets ignore distance, and picking breaks ties by distance from the near plane (`depth` is then measured from the near plane).
59
+ - **Cropped and off-axis projections.** A perspective world-unit size also comes from `camera.matrix` (its y row without the share along the w row), so a tile of a cropped projection, as tiled image export draws, covers the same pixels per splat as the whole image.
60
+ - **Sprites.** A `SpriteBatch` keeps 16 floats per sprite (position, rotation, size, pivot, atlas UV rectangle, color) in one storage buffer and draws every sprite with one instanced call. Quads face the camera using the camera's right and up vectors; with `sizeUnits: 'pixels'` (`sizeAttenuation: false`) they are expanded in screen space instead.
61
+ - **Colors.** Material and sprite colors take `'#rrggbb'` (sRGB) or linear `[r, g, b]`, like `PbrMaterial`. Per-point colors are sRGB by default, which matches the loaders package and 8-bit scanner data; set `colorSpace: 'linear'` otherwise. Output is sRGB-encoded in the shader on non `-srgb` canvas formats, the same way core does it.
62
+ - **Device loss.** `onDeviceRestored` rebuilds every buffer, pipeline and uploaded texture from the CPU copies. `dispose` (and `engine.removePlugin`) destroys them all. Clouds and batches stay registered, so a plugin can be reused.
63
+ - **SSR.** Nothing touches `window`, `navigator` or GPU globals at import or construction time.
64
+
65
+ ## HDR colors
66
+
67
+ By default per-point colors are bytes, clamped to 0..1. With `colorFormat: 'float'` a cloud stores each color as four float32, so emissive and HDR points keep their energy for bloom and tone mapping. On a plain 8-bit canvas values above 1 still clip at the end; they count when the engine draws to an HDR target or a material `color` scales them down.
68
+
69
+ ```ts
70
+ import {Engine} from 'margoengine/core';
71
+ import {PointsPlugin, PointCloud} from 'margoengine/points';
72
+ const engine = await Engine.create(document.querySelector('canvas')!);
73
+ const points = PointsPlugin.attach(engine);
74
+ const sparks = points.add(new PointCloud({
75
+ positions: new Float32Array([0, 0, 0, 1, 0, 0]),
76
+ colors: new Float32Array([8, 3, 0.5, 0.2, 4, 12]), // linear, may pass 1
77
+ colorFormat: 'float',
78
+ material: {size: 6, shape: 'round'},
79
+ }));
80
+ sparks.updateColors(1, [0, 0, 20]);
81
+ console.log(sparks.floatColors?.[6]); // 20
82
+ ```
83
+
84
+ Float colors default to `colorSpace: 'linear'`. Byte arrays are still read as 0..255. `cloud.floatColors` is a live view; after writing into it call `markDirty('colors')`. `OctreeCloud` takes it as `cloud: {colorFormat: 'float'}`, and `SurfelPlugin` reads it too.
85
+
86
+ ## Loader interop
87
+
88
+ `PointCloud` accepts the object `@margoengine/loaders` returns for PLY, PCD, XYZ and other point clouds without importing that package: `{kind: 'points', positions: Float32Array, colors?: Float32Array (sRGB rgb 0..1), normals?: Float32Array}`. Pass it straight in: `new PointCloud({...loaded, material: {size: 2}})`. Normals are kept on `cloud.normals` but not used for shading.
89
+
90
+ ## Export
91
+
92
+ `points.pointClouds` is the live, read-only set of clouds the plugin draws, in the order added (empty by default;
93
+ `add` puts a cloud in, `remove` takes it out). The `@margoengine/exporters` scene writers read it through
94
+ `engine.plugins`, so `exportGLB(engine)` writes each visible cloud as a glTF POINTS primitive with its colours,
95
+ normals and its `size` in the primitive's extras as `pointSize` and `pointSizeUnits` (`sizes` as `_WIDTH`):
96
+
97
+ ```ts
98
+ import {Engine} from 'margoengine/core';
99
+ import {PointsPlugin, PointCloud} from 'margoengine/points';
100
+ import {exportGLB} from 'margoengine/exporters';
101
+
102
+ const engine = await Engine.create(document.querySelector<HTMLCanvasElement>('canvas')!);
103
+ const points = new PointsPlugin();
104
+ engine.use(points);
105
+ points.add(new PointCloud({positions: [0, 0, 0, 1, 0, 0], material: {size: 3}}));
106
+ console.log(points.pointClouds.size); // 1
107
+ const glb = exportGLB(engine);
108
+ ```
109
+
110
+ ## Options
111
+
112
+ `PointsPlugin`
113
+
114
+ | Option | Default | |
115
+ | --- | --- | --- |
116
+ | `pointBudget` | 1,000,000 | Most points drawn per frame across all clouds |
117
+ | `edlStrength`, `edlRadius` | 1, 1.4 px | Eye-dome lighting |
118
+ | `order` | 10 | Frame graph order: after the scene, before fat lines (20) and post (30) |
119
+ | `name` | `'points'` | Unique per engine |
120
+
121
+ `PointCloud`
122
+
123
+ | Option | Default | |
124
+ | --- | --- | --- |
125
+ | `positions` | required | xyz per point |
126
+ | `colors`, `colorComponents` | none, inferred | RGB or RGBA, float 0..1 or Uint8 0..255 |
127
+ | `sizes` | none | Per-point multiplier of `material.size` |
128
+ | `blockSize` | 16384 | Points per culling block |
129
+ | `colorFormat` | `'rgba8'` | `'float'` keeps HDR colors above 1, at 16 bytes a point instead of 4 |
130
+ | `colorSpace` | `'srgb'`, `'linear'` with `colorFormat: 'float'` | Of per-point colors |
131
+ | `reorder` | false | Permute the arrays into block order for sequential GPU reads; `sourceIndex` maps back |
132
+ | `cullMargin` | 0 | World units added to the frustum test |
133
+ | `seed` | 1 | Shuffle seed |
134
+
135
+ `PointsMaterial` (`SpriteMaterial` shares the first block)
136
+
137
+ | Option | Default | |
138
+ | --- | --- | --- |
139
+ | `color`, `opacity` | white, 1 | |
140
+ | `map`, `mapFilter` | null, `'linear'` | GPUTexture, `(device) => GPUTexture` or image source |
141
+ | `mipmaps` | true (sprites: false) | Generate mips of an uploaded map |
142
+ | `alphaTest` | 0 | |
143
+ | `transparent`, `blending` | false (sprites: true), `'normal'` | `'additive'` also available |
144
+ | `depthTest`, `depthWrite` | true, `!transparent` | |
145
+ | `size` | 4 | Diameter in pixels, or world units with `sizeUnits: 'world'` |
146
+ | `sizeUnits` / `sizeAttenuation` | `'pixels'` / false | Sprites default to `'world'` |
147
+ | `minPixelSize`, `maxPixelSize` | 1, 256 | |
148
+ | `shape` | `'square'` | or `'round'` |
149
+ | `vertexColors` | true | |
150
+ | `shading` | `'flat'` | or `'sphere'` |
151
+ | `edl` | false | On the WebGPU compatibility level it costs a second pass of the same draws and a draw per sample; the frame is the same. On the WebGL2 layer below its full tier the depth target is `rgba8unorm` holding the float's bytes, since that tier rounds `r32float`. |
152
+ | `fog` | true | Fogged by the plugin's `setFog` (sprites too); false keeps the material clear |
153
+
154
+ Sprites: `add({position, size, rotation, center, color, opacity, uv})`, `set(index, ...)`, `remove(index)` (moves the last sprite into the slot), `clear()`. `SpriteMaterial.rotation` adds to every sprite.
155
+
156
+ ## Mipmaps
157
+
158
+ A map drawn on a small point shimmers, as each pixel lands on one texel of a large image. Points generate a full mip chain of an uploaded map by default and pick the level from their size on screen, so a 256 px map on a 4 px point reads as its average. `mapFilter: 'nearest'` still blends nothing between levels. Sprites keep `mipmaps: false` by default, as mips bleed between the cells of an atlas; set it to true for a batch that draws one image per sprite, or leave a gutter around atlas cells.
159
+
160
+ ```ts
161
+ import {Engine} from 'margoengine/core';
162
+ import {PointsPlugin, PointCloud, SpriteBatch} from 'margoengine/points';
163
+ const engine = await Engine.create(document.querySelector('canvas')!);
164
+ const points = PointsPlugin.attach(engine);
165
+ const map = await createImageBitmap(new ImageData(new Uint8ClampedArray(64 * 64 * 4).fill(255), 64, 64));
166
+ points.add(new PointCloud({positions: new Float32Array([0, 0, 0]), material: {map, size: 6}}));
167
+ points.add(new SpriteBatch({material: {map, mipmaps: true}})).add({position: [1, 0, 0], size: 0.1});
168
+ ```
169
+
170
+ Pass a `GPUTexture` map as a function of the device: the plugin calls it once per device, so after a driver reset or
171
+ `rebootDevice()` the map comes back by itself.
172
+
173
+ ```ts
174
+ import {Engine} from 'margoengine/core';
175
+ import {PointsPlugin, PointCloud} from 'margoengine/points';
176
+ const engine = await Engine.create(document.querySelector('canvas')!);
177
+ const points = PointsPlugin.attach(engine);
178
+ const map = (device: GPUDevice) => {
179
+ const texture = device.createTexture({
180
+ size: [1, 1], format: 'rgba8unorm', usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
181
+ });
182
+ device.queue.writeTexture({texture}, new Uint8Array([255, 0, 0, 255]), {bytesPerRow: 4}, [1, 1]);
183
+ return texture;
184
+ };
185
+ points.add(new PointCloud({positions: new Float32Array([0, 0, 0]), material: {map, size: 6}}));
186
+ ```
187
+
188
+ A plain `GPUTexture` belongs to the device that made it. After a device restore the material draws untextured and the
189
+ plugin reports it once through `engine.onError` (`MargoError` `'state'`, help `borrowed-lost`) until `material.map` is
190
+ given a texture made on `engine.gpu` (docs/conventions.md, "Borrowed GPU objects").
191
+
192
+ A `GPUTexture` you pass keeps the mips it has, and they are used. A map with `alphaTest` tests the filtered alpha, so holes in a map soften as a point shrinks. Every upload, including `needsUpdate()` on a video or canvas, makes the chain again. A browser that takes no video as a copy source (Firefox) gets each frame through a canvas it is drawn on: the same pixels, one extra draw an upload.
193
+
194
+ ## Selection masks
195
+
196
+ `cloud.setMask(values, style?)` marks points selected (true or above 0, one value a point in stored order) and the
197
+ shader fades, highlights or hides the others while every other look stays: shapes, per-point sizes, sphere shading,
198
+ eye-dome lighting, fog, clipping and GPU picking (hidden points cannot be picked, and the CPU fallback `pick` skips
199
+ them too). The mask is one bit a point after a
200
+ 16-byte style header, so `updateMask(start, values)` uploads count/8 bytes once at the next frame and never reallocates
201
+ or recompiles. Styles: `mode` 'fade' (default; unselected points show `fade` of their displayed sRGB colour, default
202
+ 0.12), 'highlight' (fade plus selected points moved `highlightAmount`, default 0.7, toward `highlight`, default
203
+ `[1, 0.4508, 0.0194]`, linear #ffb326) or 'filter' (unselected points hidden). `setMaskStyle` changes the style, `isSelected(i)` reads a bit and
204
+ `setMask(null)` removes the mask. `@margoengine/sciviz/link`'s `bindSelection` drives this mask.
205
+
206
+ ```ts
207
+ import {PointsPlugin, PointCloud} from 'margoengine/points';
208
+ import {Engine} from 'margoengine/core';
209
+ const engine = await Engine.create(document.querySelector('canvas')!);
210
+ const points = PointsPlugin.attach(engine);
211
+ const positions = Float32Array.from({length: 3000}, () => Math.random() * 4 - 2);
212
+ const cloud = points.add(new PointCloud({positions, sizes: Array(1000).fill(2), material: {edl: true}}));
213
+ cloud.setMask(Array.from({length: 1000}, (_, i) => i % 2 === 0), {mode: 'highlight'});
214
+ cloud.updateMask(0, [false, true]); // one upload of the mask at the next frame
215
+ cloud.setMaskStyle({mode: 'filter'});
216
+ console.log(cloud.isSelected(1)); // true
217
+ ```
218
+
219
+ ## Fog
220
+
221
+ `points.setFog(fog)` fogs every cloud and sprite batch whose material has `fog: true` (the default) with
222
+ `@margoengine/environment`'s `Fog` or any object with its fields (`color`, `near`, `far`, `density`, `heightFalloff`,
223
+ `height`, `enabled`), read every frame with Fog's maths. A point takes the fog at its centre, a sprite at each pixel.
224
+ `'normal'` blending fades toward the fog colour; `'additive'` fades toward adding nothing, so fog hides a glow instead of
225
+ painting it in the fog colour. Points does not import environment. `fog.enabled = false` clears it without recompiling;
226
+ `points.setFog(null)` (the default) draws exactly as before.
227
+
228
+ ```ts
229
+ import {Fog} from 'margoengine/environment';
230
+ import {PointsPlugin, SpriteBatch} from 'margoengine/points';
231
+ import {Engine} from 'margoengine/core';
232
+ const engine = await Engine.create(document.querySelector('canvas')!);
233
+ const points = PointsPlugin.attach(engine);
234
+ const atlas = await createImageBitmap(await (await fetch('/labels.png')).blob());
235
+ const labels = points.add(new SpriteBatch({material: {map: atlas}}));
236
+ points.setFog(Fog.attach(engine, {color: '#8090a0', density: 0.03}));
237
+ labels.material.fog = false; // keep this batch clear
238
+ ```
239
+
240
+ ## With glass
241
+
242
+ Transparent clouds and sprites blend over the scene at order 10. `addEffect` from
243
+ [`margoengine/oit/vfx`](../oit/README.md#particles-splats-and-points-addeffect) draws those that test depth and write none
244
+ in the same pass as glass; the rest keep their draw:
245
+
246
+ ```ts
247
+ import {Engine} from 'margoengine/core';
248
+ import {OIT} from 'margoengine/oit';
249
+ import {addEffect} from 'margoengine/oit/vfx';
250
+ import {PointsPlugin, PointCloud} from 'margoengine/points';
251
+ const engine = await Engine.create(document.querySelector('canvas')!);
252
+ const points = PointsPlugin.attach(engine);
253
+ points.add(new PointCloud({positions: new Float32Array([0, 0, 0]), material: {size: 8, transparent: true, opacity: 0.5}}));
254
+ addEffect(OIT.attach(engine, {blending: true}), points);
255
+ ```
256
+
257
+ Culling and the point budget run before anything draws, so the pass, at order 8, finds this frame's points. Additive
258
+ materials join only `blending`. Surfels stay out.
259
+
260
+ ## Clipping planes
261
+
262
+ `PointsMaterial.clippingPlanes` and `SpriteMaterial.clippingPlanes` take up to 6 world-space planes `[a, b, c, d]`;
263
+ fragments where `a x + b y + c z + d < 0` are cut away (the `@margoengine/materials` convention). A point tests each
264
+ fragment's world position on its camera-facing disc (on the sphere for `shading: 'sphere'`), so a plane can cut a large
265
+ point in half; world-sized sprites test each fragment on the quad, pixel-sized sprites (`sizeUnits: 'pixels'`) their
266
+ centre. Planes are normalised on assignment and reading returns copies; assign a new list to change them (live, next
267
+ frame, no recompile). More than 6 planes throw a RangeError, a malformed plane or a zero normal a TypeError.
268
+ `clipIntersection: true` cuts only fragments behind every plane (their intersection) instead of any.
269
+
270
+ ```ts
271
+ import {Engine} from 'margoengine/core';
272
+ import {PointsPlugin, PointCloud} from 'margoengine/points';
273
+ const canvas = document.querySelector('canvas')!;
274
+ const engine = await Engine.create(canvas);
275
+ const points = PointsPlugin.attach(engine);
276
+ // Section a scan: keep x <= 2 and z >= 0.
277
+ const cloud = points.add(new PointCloud({
278
+ positions: new Float32Array([0, 0, 0, 3, 0, 1, 1, 1, -1]),
279
+ material: {size: 3, clippingPlanes: [[-1, 0, 0, 2], [0, 0, 1, 0]]},
280
+ }));
281
+ cloud.material.clippingPlanes = [[-1, 0, 0, 2]]; // live: drop the z cut
282
+ ```
283
+
284
+ ## LAS and LAZ scans (`margoengine/points/las`)
285
+
286
+ `parseLAS(bytes)` reads ASPRS LAS 1.0 to 1.5: point formats 0 to 10, extra bytes (scaled, with no-data as NaN), every
287
+ VLR and EVLR, and the CRS (OGC WKT record 2112 and the GeoTIFF keys 34735 to 34737, with the EPSG code). Positions come
288
+ back as float32 relative to `origin` (the bounding box centre by default, float64), so a survey 500 km from the CRS
289
+ origin keeps millimetres. LAS is z-up; the engine is y-up, so swap axes when you place it. Where a non-zero legacy
290
+ 32-bit count disagrees with its 64-bit twin, the legacy value is used, as LAS 1.4 R16 and 1.5 say. A LAS 1.5 header
291
+ also gives `header.timeOffset` and `header.gpsTimeRange`: with global encoding bits 0 and 6 set, a point's standard GPS
292
+ time is `gpsTime + 1e6 * timeOffset`.
293
+
294
+ ```ts
295
+ import { Engine } from 'margoengine/core';
296
+ import { PointCloud, PointsPlugin, classificationColors } from 'margoengine/points';
297
+ import { loadLAS } from 'margoengine/points/las';
298
+ const engine = await Engine.create(document.querySelector('canvas')!);
299
+ const points = PointsPlugin.attach(engine);
300
+ const las = await loadLAS('/scans/site.las', { stride: 1 });
301
+ const positions = new Float32Array(las.count * 3);
302
+ for (let i = 0; i < las.count; i++) // z-up survey to y-up world
303
+ positions.set([las.positions[i * 3], las.positions[i * 3 + 2], -las.positions[i * 3 + 1]], i * 3);
304
+ points.add(new PointCloud({ positions, colors: classificationColors(las.classification), colorComponents: 4 }));
305
+ console.log(las.crs?.epsg, las.header.pointFormat, Object.keys(las.extra));
306
+ ```
307
+
308
+ | Option | Default | Meaning |
309
+ | --- | --- | --- |
310
+ | `origin` | box centre | World point positions are stored relative to, or `'min'` for the box's minimum corner. When the first point lies outside the header's box, a fault of some writers, the first point is the origin instead; `las.origin` says which. |
311
+ | `maxPoints` / `stride` | all / 1 | Read fewer points (a preview). |
312
+ | `partial` | `false` | Read what a cut-short file holds instead of throwing a `RangeError`. |
313
+ | `laz` | built-in decoder | A LAZ decompressor of your own (see below). |
314
+ | `signal` | none | `AbortSignal`. |
315
+
316
+ LAZ files (compressed LAS) are recognised by the header's compression bit and open as they are: the decoder below loads
317
+ the first time a compressed file arrives, so a plain LAS file never pays for it. `options.laz` replaces it with a
318
+ function of your own that returns the uncompressed point records (`LazDecoder`). `writeLAS` writes uncompressed LAS
319
+ 1.0 to 1.5 (extra bytes, WKT or EPSG, points by return always filled in) for tools and tests. An EPSG code alone is
320
+ GeoTIFF, which LAS allows only for formats 0 to 5 before 1.5; formats 6 to 10 and LAS 1.5 take the CRS as `wkt`.
321
+
322
+ ```ts
323
+ import { parseLAS, writeLAS } from 'margoengine/points/las';
324
+
325
+ const bytes = writeLAS({ positions: [0, 0, 0, 1, 2, 3], versionMinor: 5, wkt: 'GEOGCS["WGS 84"]' });
326
+ const copy = await parseLAS(bytes);
327
+ console.log(copy.header.versionMinor, copy.header.pointsByReturn[0], copy.crs?.wkt);
328
+ ```
329
+
330
+ Formats 4, 5, 9 and 10 carry wave packets: `las.wavePackets` holds the descriptor, offset, size, location and direction
331
+ of each point. `lasWaveDescriptors(records)` reads the descriptors, and `lasWaveform(las, index, source)` reads one
332
+ point's samples, from the file itself or from the `.wdp` file beside it, as `raw`, `volts` and `spacing` in picoseconds.
333
+ It returns `undefined` for a point with no wave.
334
+
335
+ ```ts
336
+ import { lasWaveDescriptors, lasWaveform, loadLAS } from 'margoengine/points/las';
337
+
338
+ const scan = await loadLAS('/scans/fullwave.laz');
339
+ const samples = new Uint8Array(await (await fetch('/scans/fullwave.wdp')).arrayBuffer());
340
+ const wave = lasWaveform(scan, 0, samples);
341
+ console.log(lasWaveDescriptors(scan.records).size, wave?.raw.length, wave?.volts[0], wave?.spacing);
342
+ ```
343
+
344
+ ## LAZ decoder (`margoengine/points/laz`)
345
+
346
+ `parseLAS` and `loadLAS` use `createLazDecoder()` by default. It decodes one chunk at a time straight into the point
347
+ arrays, so the uncompressed file is never held in memory, and `signal` stops it between chunks.
348
+ `lazChunks(bytes, header, records, {signal})` is the same decoder as an async iterator of uncompressed record blocks, one
349
+ per chunk, for streaming tools; `lazInfo(records)` reads the LASzip record (compressor, chunk size, items).
350
+
351
+ ```ts
352
+ import { loadLAS } from 'margoengine/points/las';
353
+
354
+ const controller = new AbortController();
355
+ const scan = await loadLAS('/scans/site.laz', { stride: 4, signal: controller.signal });
356
+ console.log(scan.count, scan.header.pointFormat, scan.gpsTime?.[0], scan.rgb?.length);
357
+ ```
358
+
359
+ | Point formats | LASzip items read |
360
+ | --- | --- |
361
+ | 0 to 3 | POINT10, GPSTIME11, RGB12 and extra bytes (BYTE), version 2, pointwise chunks |
362
+ | 4, 5 | The same, with WAVEPACKET13 version 1 |
363
+ | 6 to 8 | POINT14, RGB14, RGBNIR14 and extra bytes (BYTE14), version 3, layered chunks with per-scanner-channel contexts |
364
+ | 9, 10 | The same, with WAVEPACKET14 version 3 |
365
+
366
+ Compressors 0 (plain records), 1 (one stream, no chunk table), 2 and 3 are read, in fixed and variable chunks, with a
367
+ chunk table whose offset was written at the end of the file. Anything else throws a `MargoError` with code `unsupported`
368
+ that names it: item version 1, the coding of LASzip 1.0, which neither the LAZ specification 1.4 nor the LASzip paper
369
+ describes; coders other than arithmetic; compressors above 3; chunk table versions other than 0. Corrupt data throws a
370
+ `RangeError` or `TypeError` that names the chunk; every read stays inside its chunk. The chunk table sits after the
371
+ points, so a cut-short LAZ file cannot be read, even with `partial`. A LAS 1.4 compatibility mode file reads as stored.
372
+
373
+ Verification: the decoder was written clean room from the LASzip paper and the LAZ specification. `tests/laz-real.test.js`
374
+ holds what LASzip and lazrs decode from real files, as digests, and every record and field matches in every point
375
+ format: public files of formats 0 to 3, 7, 8 and 10 (`tests/fixtures/NOTICE.md`), the real USGS 3DEP tile of format 6
376
+ (`tests/laz-usgs.test.js`), and real points LASzip compressed for formats 4, 5 and 9 and for channels that switch. The
377
+ reference decoders are not part of the repository. Compressor 0, compressor 1 with version 2 items and chunk size 0 are
378
+ checked only against the test encoder, a stand-in, because no tool here writes them.
379
+
380
+ ## E57 scans (`margoengine/points/e57`)
381
+
382
+ `parseE57(bytes)` reads ASTM E57 files from terrestrial scanners: the 1024-byte pages (each CRC-32C checked), the XML
383
+ section, and every `data3D` scan's compressed vector (bitPack codec: Float, ScaledInteger and Integer fields packed into
384
+ bytestreams across data packets). Cartesian or spherical coordinates, each scan's pose (quaternion and translation),
385
+ `cartesianInvalidState` / `sphericalInvalidState` (invalid points dropped unless `keepInvalid`), intensity normalised by
386
+ `intensityLimits`, colour by `colorLimits`, and any other field (return index, time stamp, row and column) by name.
387
+ All scans land in one world frame, float32 relative to `origin`.
388
+
389
+ ```ts
390
+ import { Engine } from 'margoengine/core';
391
+ import { PointCloud, PointsPlugin } from 'margoengine/points';
392
+ import { loadE57 } from 'margoengine/points/e57';
393
+ const engine = await Engine.create(document.querySelector('canvas')!);
394
+ const points = PointsPlugin.attach(engine);
395
+ const e57 = await loadE57('/scans/plant-room.e57');
396
+ for (const scan of e57.scans) {
397
+ const positions = new Float32Array(scan.count * 3);
398
+ for (let i = 0; i < scan.count; i++) // z-up scan to y-up world
399
+ positions.set([scan.positions[i * 3], scan.positions[i * 3 + 2], -scan.positions[i * 3 + 1]], i * 3);
400
+ points.add(new PointCloud({ positions, colors: scan.colors, colorComponents: 4 }));
401
+ }
402
+ ```
403
+
404
+ | Option | Default | Meaning |
405
+ | --- | --- | --- |
406
+ | `origin` | centre of all scans | World point positions are stored relative to. |
407
+ | `verifyChecksums` | `true` | Check every page's CRC-32C (a failure is a `RangeError` naming the page). |
408
+ | `keepInvalid` | `false` | Keep points flagged invalid. |
409
+ | `signal` | none | `AbortSignal`. |
410
+
411
+ Codecs other than bitPack and String and Blob prototype fields are not read (codes `unsupported` or
412
+ skipped). `writeE57` writes double, scaled-integer or spherical scans with intensity, colour, pose and invalid flags,
413
+ for tools and round-trip tests.
414
+
415
+ ### Pictures (`images2D`)
416
+
417
+ `e57.images` holds every picture the file carries, with its camera pose and projection (`pinhole`, `spherical`,
418
+ `cylindrical` or `visualReference`): the encoded JPEG or PNG bytes, an optional PNG mask, width and height, the
419
+ guid of the scan it belongs to, and the projection parameters by name (`focalLength`, `pixelWidth`, `principalPointX`,
420
+ `radius`, ...). Poses are in the file's world frame; subtract `e57.origin` to match the recentred scan positions.
421
+ `writeE57Document(scans, { images })` writes them. Pass `images: false` to skip reading them.
422
+
423
+ ```ts
424
+ import { loadE57 } from 'margoengine/points/e57';
425
+ const e57 = await loadE57('/scans/plant-room.e57');
426
+ for (const image of e57.images) {
427
+ const bitmap = await createImageBitmap(new Blob([image.data], { type: image.mime }));
428
+ console.log(image.name, image.projection, bitmap.width, bitmap.height, image.pose.translation);
429
+ }
430
+ ```
431
+
432
+ ## Large clouds: octree level of detail (`margoengine/points/octree`)
433
+
434
+ `buildOctree(cloud)` splits a cloud into a nested-sample octree: each node keeps one point per cell of a 128-cell grid
435
+ over its cube (in a seeded shuffle, so the sample is even), and its eight children hold the rest; every point lands in
436
+ exactly one node. Colours given as a Uint8Array or Uint8ClampedArray stay 0..255 bytes; any other array is read as
437
+ 0..1 floats. `maxDepth` is a whole number from 0 to 64 (RangeError otherwise). `OctreeCloud` draws the nodes the camera needs, largest on screen first, under `pointBudget`, loads
438
+ them from any `OctreeSource` (the built octree, or your own that fetches nodes from a server) and frees the least
439
+ recently used past `maxLoadedPoints`. Refinement is additive, so a parent's points stay drawn under its children and
440
+ nothing ever leaves a hole.
441
+
442
+ ```ts
443
+ import { Engine } from 'margoengine/core';
444
+ import { PointsPlugin } from 'margoengine/points';
445
+ import { OctreeCloud, buildOctree } from 'margoengine/points/octree';
446
+ const engine = await Engine.create(document.querySelector('canvas')!);
447
+ const points = PointsPlugin.attach(engine, { pointBudget: 3_000_000 });
448
+ const positions = new Float32Array(3_000_000).map(() => Math.random() * 100);
449
+ const octree = buildOctree({ positions }, { maxPointsPerNode: 20_000 });
450
+ OctreeCloud.attach(engine, points, octree, { pointBudget: 1_000_000, material: { size: 2, edl: true } });
451
+ ```
452
+
453
+ | `OctreeCloud` option | Default | Meaning |
454
+ | --- | --- | --- |
455
+ | `pointBudget` | 2,000,000 | Most points drawn per frame. |
456
+ | `minNodePixels` | 150 | Refine a node while it spans more than this many pixels. |
457
+ | `maxLoadedPoints` | 3 x `pointBudget` | Points kept loaded before eviction. |
458
+ | `maxConcurrentLoads` | 4 | Nodes loading at once (the rest wait; unwanted loads are aborted). |
459
+ | `material` | defaults | `PointsMaterial` or its options, shared by every node (`octreeCloud.material`). |
460
+ | `cloud` | defaults | `PointCloud` options of every node. |
461
+ | `adaptiveSize` | `false` | Grow points to fill the gaps left by subsampled nodes; `true` or `{scale}`. |
462
+
463
+ ### Placing an octree in a scene
464
+
465
+ An `OctreeCloud` has a `matrix`, or follows a mesh with `attach(mesh)`, including the mesh's visibility. Culling, level of detail and point sizes all work through the transform, and `points.pick` answers in world positions, so a scan can be placed, rotated and animated like any object.
466
+
467
+ ```ts
468
+ import { Engine } from 'margoengine/core';
469
+ import { PointsPlugin } from 'margoengine/points';
470
+ import { OctreeCloud, buildOctree } from 'margoengine/points/octree';
471
+ const engine = await Engine.create(document.querySelector('canvas')!);
472
+ const points = PointsPlugin.attach(engine);
473
+ const positions = new Float32Array(300_000).map(() => Math.random() * 10);
474
+ const scan = OctreeCloud.attach(engine, points, buildOctree({ positions }));
475
+ scan.matrix[12] = 20; // move it 20 units along x; takes effect next frame
476
+
477
+ const turntable = engine.createMesh();
478
+ scan.attach(turntable); // or follow a mesh
479
+ turntable.setPosition([0, 1, 0]);
480
+ ```
481
+
482
+ All nodes share the matrix, so moving a scan writes nothing but 16 floats. Node choice runs before the frame's update, so it lags a moving transform by one frame while the points themselves do not. `select` takes the camera in world coordinates.
483
+
484
+ A failing node is reported to `onError(listener)` (or `engine.onError`) and skipped until `retry()`.
485
+
486
+ ### Adaptive point size
487
+
488
+ Far parts of a scan draw only coarse nodes, so fixed-size points leave holes. With `adaptiveSize`, each point gets a
489
+ world-unit diameter of `scale` (default 1.5) times the spacing around it. The spacing comes from the density of every
490
+ drawn node at that spot: the node and its parents, and the drawn children the point falls in. A node's density is its
491
+ sample grid, or its point count over its cube's face when it holds fewer points than the grid. So a point shrinks as
492
+ children load around it and stays large in the octants that have none, and a change of level never leaves a hole.
493
+
494
+ ```ts
495
+ import { Engine } from 'margoengine/core';
496
+ import { PointsPlugin } from 'margoengine/points';
497
+ import { OctreeCloud, buildOctree } from 'margoengine/points/octree';
498
+ const engine = await Engine.create(document.querySelector('canvas')!);
499
+ const points = PointsPlugin.attach(engine, { pointBudget: 500_000 });
500
+ const positions = new Float32Array(3_000_000).map(() => Math.random() * 100);
501
+ OctreeCloud.attach(engine, points, buildOctree({ positions }), {
502
+ pointBudget: 500_000,
503
+ adaptiveSize: { scale: 1.5 },
504
+ material: { size: 2, shape: 'round' }, // 2 px stays the smallest a point draws
505
+ });
506
+ ```
507
+
508
+ The material is changed to world units with `size` 1 and each point carries its own size. A pixel `size` becomes the
509
+ `minPixelSize`, a world `size` the smallest world diameter, and `maxPixelSize` (default 256) still caps the growth.
510
+ Sizes are rewritten on the CPU only for nodes whose drawn children changed, at most 500,000 points a selection.
511
+
512
+ ## COPC files (`margoengine/points/copc`)
513
+
514
+ A Cloud Optimized Point Cloud is a LAZ 1.4 file that a viewer reads in pieces. `CopcSource.open` reads the header and every hierarchy page by HTTP range requests, then `OctreeCloud` fetches each node's chunk when it is shown:
515
+
516
+ ```ts
517
+ import { EngineKernel } from 'margoengine/core';
518
+ import { PointsPlugin } from 'margoengine/points';
519
+ import { OctreeCloud } from 'margoengine/points/octree';
520
+ import { CopcSource } from 'margoengine/points/copc';
521
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, { backend: 'webgpu' });
522
+ const source = await CopcSource.open('/scan.copc.laz'); // options: fetch, signal
523
+ OctreeCloud.attach(engine, PointsPlugin.attach(engine, { pointBudget: 2_000_000 }), source, { pointBudget: 2_000_000 });
524
+ ```
525
+
526
+ Positions and bounds are relative to `source.origin`, the cube's centre, which keeps float32 positions exact for a scan far from zero. Reads only: there is no COPC writer. It reads point formats 6 to 8, as the specification requires. Tested against files written here from the public specification with the package's own test encoder, not yet against files from another tool.
527
+
528
+ ## GPU picking (`margoengine/points/pick`)
529
+
530
+ `points.pick` runs on the CPU, so meshes do not block it and clipping planes do not cut it. `PointPicking` adds a `PointsPlugin` to `Picking` from `margoengine/selection`: one `picking.pick` or `engine.pick` then answers whichever of points and meshes is nearest at the pixel. A point behind a mesh is not hit, a part cut by a clipping plane is not hit, and `pickMany` works too.
531
+
532
+ ```ts
533
+ import { Engine, box } from 'margoengine/core';
534
+ import { PointCloud, PointsPlugin } from 'margoengine/points';
535
+ import { PointPicking } from 'margoengine/points/pick';
536
+ import { Picking } from 'margoengine/selection';
537
+ const canvas = document.querySelector('canvas')!;
538
+ const engine = await Engine.create(canvas);
539
+ const points = PointsPlugin.attach(engine);
540
+ const scan = points.add(new PointCloud({ positions: [0, 0, 0, 1, 0, 0], material: { size: 8 } }));
541
+ engine.createMesh().setGeometry(box());
542
+
543
+ const picking = Picking.attach(engine);
544
+ PointPicking.attach(picking, points);
545
+
546
+ canvas.addEventListener('pointerdown', async (event) => {
547
+ const hit = await picking.pick(event.offsetX, event.offsetY);
548
+ if (hit?.cloud === scan) console.log('point', hit.point, 'at', hit.position);
549
+ else if (hit) console.log('mesh', hit.mesh);
550
+ });
551
+ ```
552
+
553
+ - `hit.cloud`, `hit.point` and `hit.position` name the point. `hit.mesh` is the mesh the cloud follows, or else an empty mesh made for that cloud, which draws nothing and which `cloudOf` maps back; stand-ins go with their cloud or with `dispose()`. Attach `PointsPlugin` to the engine first.
554
+ - A point hits where it shows: its shape, map, `alphaTest` and clipping planes apply, and fully transparent points such as a hidden class do not hit. A sphere impostor hits at its curved depth. Like every pick, the 3 x 3 tile also finds a neighbouring pixel when the exact one is empty.
555
+ - Only points drawn in the view's latest frame pick, at their level of detail and transform, so an `OctreeCloud` picks through its nodes on screen. It answers the nearest thing only. Sprites and `SurfelPlugin` clouds do not pick.
556
+ - Clouds at most 268,435,456 points in all per pick (the ID range `Picking` gives an overlay); the drawn clouds after the one that would pass it are not hit. A default device cannot reach it: that is 24 clouds at the 11,184,810-point cap, 3 GB of positions. While an overlay is registered, each pick draws every drawn point of that view again, with no culling to the pixel.
557
+
558
+ ## Potree folders (`margoengine/points/potree`)
559
+
560
+ Potree is the most common format for scans published on the web. `PotreeSource.open` reads a folder's metadata and whole hierarchy, then `OctreeCloud` fetches each node when it is shown. Pass the folder, or its `metadata.json` or `cloud.js`.
561
+
562
+ ```ts
563
+ import { Engine } from 'margoengine/core';
564
+ import { PointsPlugin } from 'margoengine/points';
565
+ import { OctreeCloud } from 'margoengine/points/octree';
566
+ import { PotreeSource } from 'margoengine/points/potree';
567
+ const engine = await Engine.create(document.querySelector('canvas')!);
568
+ const points = PointsPlugin.attach(engine, { pointBudget: 2_000_000 });
569
+ const source = await PotreeSource.open('/scans/site/'); // options below
570
+ OctreeCloud.attach(engine, points, source, { pointBudget: 2_000_000, adaptiveSize: true });
571
+ engine.camera.position = [0, 50, 200]; // positions are relative to source.origin, the centre of the box
572
+ console.log(source.version, source.points, source.origin);
573
+ ```
574
+
575
+ | Version | Files | Read |
576
+ | --- | --- | --- |
577
+ | 2.0 | `metadata.json`, `hierarchy.bin`, `octree.bin` | Range requests. Encodings `DEFAULT` and `BROTLI`. |
578
+ | 1.5 to 1.8 | `cloud.js`, `.hrc`, one `.bin`, `.las` or `.laz` per node | Whole files per node. |
579
+ | 1.4 | `cloud.js` with the hierarchy inside, one `.bin`, `.las` or `.laz` per node in one folder | Whole files per node. |
580
+
581
+ Everything a folder needs loads by itself, only when a folder needs it: `parseLAS` for LAS and LAZ nodes, and `decodeBrotli` of `@margoengine/decoders/brotli` for `BROTLI` folders. A folder of binary nodes pays for neither.
582
+
583
+ | Option | Default | What it does |
584
+ | --- | --- | --- |
585
+ | `fetch`, `signal` | `globalThis.fetch`, none | The fetch used for every request; cancels the reads of `open`. |
586
+ | `hierarchy` | `'lazy'` | `'lazy'` reads the first hierarchy page at open and each further page when `load` reaches its node, so a very deep folder opens with one request. `'eager'` reads every page at open. `source.expand(node)` reads one page by hand. |
587
+ | `attributes` | `['intensity', 'classification']` | Which attributes `load` gives back in `attributes`, or `'all'`. Names are lower case joined by `_`, so `return_number`, `gps_time`. |
588
+ | `colorBy` | `'rgb'` | `'classification'` colours through `classificationColors`, `'intensity'` through `rampColors` over the range the folder states. |
589
+ | `parseLAS`, `laz`, `brotli` | loaded when met | Replace the LAS reader, LAZ decoder or Brotli decoder. |
590
+
591
+ ```ts
592
+ import { PotreeSource } from 'margoengine/points/potree';
593
+
594
+ const source = await PotreeSource.open('/scans/site/', { attributes: 'all', colorBy: 'classification' });
595
+ const { positions, attributes } = await source.load(source.root, new AbortController().signal);
596
+ console.log(positions.length / 3, attributes?.classification, attributes?.gps_time);
597
+ ```
598
+
599
+ A 1.7 hierarchy file lists leaves with 0 points in real folders, so a leaf's `count` comes from its file once `load` has read it. Other encodings and versions before 1.4 throw a `MargoError` with code `unsupported`. The reader is checked on real PotreeConverter output: see `tests/potree-check.mjs`.
600
+
601
+ The runnable README uses the complete published `lion_takanawa_normals` Potree 1.7
602
+ folder (BSD-2-Clause; provenance in `tests/fixtures/NOTICE.md`), served as `/scans/site/`.
603
+ From a clone, run `node scripts/fetch-readme-assets.mjs` to acquire its 80 pinned files
604
+ in the shared external cache. Serve that folder intact, including `cloud.js` and all
605
+ relative `data/` files. The package test requires it and checks every coordinate and
606
+ RGB value of all 341,989 points across 77 nodes against their raw records. This
607
+ establishes complete-file reading, not surveyed accuracy or production rendering quality.
608
+
609
+ ## Depth video (`margoengine/points/depth-video`)
610
+
611
+ `depthVideoPoints(frame, options, depth?)` turns one RGB + depth frame into points; `DepthVideoCloud` keeps a `PointCloud` that follows a video, one rewrite per frame. Each pixel is unprojected through a pinhole camera looking down -Z with Y up: `x = (u - cx) z / fx`, `y = (cy - v) z / fy`, `z = -depth` (Hartley and Zisserman, Multiple View Geometry, section 6.1). The frame is RGBA bytes (an `ImageData` fits, from `canvas.getContext('2d').getImageData` after `drawImage(video)`).
612
+
613
+ ```ts
614
+ import { depthVideoPoints, DepthVideoCloud } from 'margoengine/points/depth-video';
615
+
616
+ // A 4 x 4 side-by-side frame: colour on the left half, grey depth on the right half (8 x 4 pixels).
617
+ const frame = {width: 8, height: 4, data: new Uint8Array(8 * 4 * 4).fill(128)};
618
+ const {positions, colors, count} = depthVideoPoints(frame, {near: 0.5, far: 4, fov: 60});
619
+ console.log(count, positions.length, colors.length); // 16 points, xyz and rgb each
620
+
621
+ // A cloud for a live video: the point count is fixed, holes and flying pixels get size 0.
622
+ const cloud = new DepthVideoCloud({width: 4, height: 4, near: 0.5, far: 4});
623
+ console.log(cloud.update(frame)); // points showing
624
+ // plugin.add(cloud.cloud) draws it; call cloud.update(imageData) every video frame.
625
+ ```
626
+
627
+ | Option | Default | What it does |
628
+ | --- | --- | --- |
629
+ | `layout` | `'side-by-side'` | Where the depth sits: `'side-by-side'` (colour left), `'top-bottom'`, or `'separate'` (a second picture, which may differ in size) |
630
+ | `encoding` | `'gray'` | `'gray'` (red channel), `'rg16'` (red high byte, green low byte) or `'millimeters'` (16 bits read as mm); a stored 0 is a hole |
631
+ | `near`, `far` | 0.3, 5 | Metres at the lowest and highest stored values; points outside are dropped |
632
+ | `invert` | false | The highest stored value is near (`gray` and `rg16`) |
633
+ | `fov`, `intrinsics` | 60, none | Vertical field of view in degrees, or `{fx, fy, cx, cy}` in pixels of the colour picture |
634
+ | `stride` | 1 | Keep every n-th pixel |
635
+ | `maxJump` | 0.05 | Drop a pixel whose depth differs from a neighbour's by more than this share of its own (flying pixels at edges); 0 keeps all |
636
+
637
+ Use a lossless or high-bitrate depth video: video compression bends gray depth, and `'rg16'` needs lossless frames. Reading frames from a `<video>` is left to the app (it is one `drawImage` and one `getImageData`).
638
+
639
+ ## Surfels (`margoengine/points/surfels`)
640
+
641
+ `SurfelPlugin` draws clouds as small blended discs, so a scan reads as one continuous surface instead of overlapping dots. It runs three passes: every disc writes depth pushed back a little, discs within that push of the front add colour and weight into a float target, and a full-screen pass divides one by the other and draws it over the scene. The weight is Gaussian across the disc and falls with depth behind the front surface, so a wall does not bleed through the floor in front of it. Discs share the scene's depth, so meshes and surfels hide each other.
642
+
643
+ ```ts
644
+ import { Engine } from 'margoengine/core';
645
+ import { PointCloud } from 'margoengine/points';
646
+ import { SurfelPlugin } from 'margoengine/points/surfels';
647
+ const engine = await Engine.create(document.querySelector('canvas')!);
648
+ const surfels = SurfelPlugin.attach(engine, { pointBudget: 2_000_000, overlap: 2 });
649
+ const positions = new Float32Array(300_000).map(() => Math.random() * 10);
650
+ surfels.add(new PointCloud({ positions, material: { size: 0.1, sizeUnits: 'world', color: '#c0a080' } }));
651
+ ```
652
+
653
+ | `SurfelPlugin` option | Default | Meaning |
654
+ | --- | --- | --- |
655
+ | `pointBudget` | 1,000,000 | Most points drawn per frame, shared as in `PointsPlugin`. |
656
+ | `overlap` | 1.5 | Disc diameter as a multiple of the point's size. Discs must overlap to blend. |
657
+ | `blendDepth` | 1 | Depth behind the front surface that still blends, as a multiple of the disc's radius. |
658
+ | `order`, `name` | 10, `'surfels'` | As `PointsPlugin`. |
659
+
660
+ Pass `normals` on the cloud and each disc lies flat on its surface; without them discs face the camera. For large scans give `OctreeCloud` this plugin in place of `PointsPlugin`, with `adaptiveSize` so each disc fits the spacing around it: `OctreeCloud.attach(engine, surfels, source, {adaptiveSize: {scale: 2}})`.
661
+
662
+ `setFog` works as on `PointsPlugin`, a disc taking the fog at its centre. A cloud belongs to one plugin. From `PointsMaterial` a surfel reads `color`, `size`, `sizeUnits`, `minPixelSize`, `maxPixelSize`, `vertexColors`, `alphaTest` (a point's alpha also weighs it, so alpha 0 hides it), `fog`, `clippingPlanes` and `clipIntersection`. Surfels are opaque and always test and write depth: `opacity`, `transparent`, `blending`, `map`, `shape`, `shading`, `edl`, `depthTest` and `depthWrite` have no effect. `PointsPlugin.pick` does not see them. It costs two draws of every point plus a full-screen pass, and its extra targets take about 100 MB at 1920 x 1080 with 4x MSAA. At 4x on the WebGPU compatibility level (which multisamples no `r32float` or `rgba16float`) the front depth is packed into `rgba8unorm` and the sums go into two `rg16float` targets, the same memory and precision; the full-screen pass is one draw per sample there. On native WebGPU at 4x the full level takes the same one draw per sample (four draws in place of one `sample_index` draw, since 2026-11-21): on an Intel Arc 140V (Dawn D3D12) the one `sample_index` draw over the 4x blended sums did not repeat exactly, up to 33 of 255 apart from frame to frame, a fault in the GPU's 4x blending (`docs/known-bugs.md`, KB2481); the per-sample draws repeat bit for bit. The WebGL2 layer keeps the one draw. On the WebGL2 layer below its full tier (`/tiers`) the front depth is packed the same way, as that tier would store `r32float` in half floats, and the LDR tier is refused (`unsupported`), as its 8-bit targets would clamp the sums.
663
+
664
+ ## Attribute filters and style expressions (`margoengine/points/style`)
665
+
666
+ Show, hide, colour and size points by their attributes: Potree's filters (classification, return number, number of
667
+ returns, GPS time, point source, intensity, any other column) and the OGC 3D Tiles styling language (`show`, `color`,
668
+ `pointSize`, `defines`, conditions, `color()`, `rgb()`, `hsl()`, vectors, maths and regular expressions). A `LASPoints`
669
+ from `margoengine/points/las` is a table as it is; so is an octree node's `attributes`, or any object of typed arrays.
670
+
671
+ ```ts
672
+ import {Engine} from 'margoengine/core';
673
+ import {PointsPlugin, PointCloud} from 'margoengine/points';
674
+ import {parseLAS, writeLAS} from 'margoengine/points/las';
675
+ import {PointStyle, bindPointStyle, createStyledCloud} from 'margoengine/points/style';
676
+ const engine = await Engine.create(document.querySelector('canvas')!);
677
+ const points = PointsPlugin.attach(engine);
678
+
679
+ // A small survey: ground (class 2), vegetation (class 5) and noise (class 7), with first and later returns.
680
+ const n = 3000, world = new Float64Array(n * 3), classification = new Uint8Array(n), returnNumber = new Uint8Array(n);
681
+ for (let i = 0; i < n; i++) {
682
+ world.set([i % 60, (i % 7) * 0.5, Math.floor(i / 60)], i * 3);
683
+ classification[i] = [2, 5, 7][i % 3];
684
+ returnNumber[i] = 1 + (i % 2);
685
+ }
686
+ const las = await parseLAS(writeLAS({positions: world, classification, returnNumber, numberOfReturns: returnNumber.map(() => 2)}));
687
+ const cloud = points.add(new PointCloud({positions: las.positions, material: {size: 3}}));
688
+
689
+ // Hide noise and later returns; colour by class, as a 3D Tiles style. `${Classification}` finds `classification`.
690
+ const style = bindPointStyle(cloud, las, {
691
+ filter: {classification: [2, 5], returnNumber: [1, 1]},
692
+ color: {conditions: [['${Classification} === 2', "color('#a0522d')"], ['true', "color('forestgreen')"]]},
693
+ pointSize: '${POSITION}.y > 2.0 ? 5.0 : 3.0',
694
+ });
695
+ console.log(style.result.shown, 'of', cloud.count, 'shown');
696
+ style.update({show: '${GpsTime} >= 0.0', color: "hsl(${intensity} / 65535.0, 1.0, 0.5)"}); // live: one write
697
+ style.dispose(); // the cloud's own colours, sizes and mask come back
698
+
699
+ // Or keep only the points a style shows, in a new cloud: hidden points then take no memory or budget.
700
+ const ground = createStyledCloud(cloud, las, new PointStyle({filter: {classification: [2]}}));
701
+ points.add(ground.cloud);
702
+ engine.render();
703
+ ```
704
+
705
+ - `bindPointStyle(cloud, table, style)` writes the cloud in place and returns a binding (`update`, `dispose`, `using`).
706
+ Hidden points go through the cloud's selection mask in `'filter'` mode: they draw nothing and cannot be picked, but
707
+ stay in the cloud's blocks, so they still count against the point budget. The binding owns the mask while it lives.
708
+ - `createStyledCloud(source, table, style)` builds a new cloud of the shown points (and their `indices`), as
709
+ `createClippedCloud` does for volumes.
710
+ - `styleSource(octreeSource, style)` styles each node of a `PotreeSource`, `CopcSource` or `MemoryOctree` as it loads:
711
+ hidden points are dropped and `color` becomes the node's colours. Give the wrapped source to `OctreeCloud`.
712
+ - `new PointStyle(options).evaluate(table)` gives the raw result: `show` (1 or 0 a point), `colors` (sRGB RGBA) and
713
+ `sizes`, for exports and charts.
714
+
715
+ Rules, from the 3D Tiles styling specification: `show` must give a boolean and `color` four numbers, or a MargoError
716
+ `state` says which; a property the table lacks reads `undefined`; a define reads the column of its own name. Margo's
717
+ choices: a `color` whose conditions all fail keeps the point's own colour (its `${COLOR}`), not white; `pointSize` is
718
+ in the material's units (pixels by default, as in 3D Tiles), clamped by `minPixelSize` and `maxPixelSize`; column names
719
+ match exactly first, then ignoring case, `_`, `-` and spaces. Filters are inclusive `[min, max]` ranges, and
720
+ `classification` lists the classes to show. Styles run on the CPU, once per call: about one pass over the columns per
721
+ `update`, so restyle on a change, not every frame. `pointSize` does not apply to octree nodes. The same interpreter
722
+ drives `margoengine/tiles/style` for 3D Tiles.
723
+
724
+ ## Colours and measures
725
+
726
+ `classificationColors(classes, {palette, hidden})` colours by ASPRS class (`ASPRS_CLASSES` names them, 19 to 22 of
727
+ LAS 1.4 R15 included; hidden classes get alpha 0). `rampColors(values, {min, max, gamma, stops})` maps intensity, height or any attribute through a ramp
728
+ (1st to 99th percentile by default; `ELEVATION_STOPS` is a blue-to-red ramp). `rgb16ToRgba8` turns 16-bit scanner RGB
729
+ into bytes (and keeps 8-bit values stored in 16-bit fields). With `points.pick` hits, `measurePointDistance`, `measurePath`,
730
+ `measureArea` (planar polygon), `measureHeight` (along +y) and `measureAngle` (degrees) give the usual survey measures.
731
+
732
+ ## Limits
733
+
734
+ - Requires native WebGPU or the full WebGL2 compatibility layer. The small preview throws linked `unsupported` during setup.
735
+ - Each per-point buffer of a cloud must fit one storage binding, so the widest bounds it: 12-byte positions (and surfel normals) give `maxStorageBufferBindingSize / 12` points (11,184,810 at the default 128 MiB limit); `colorFormat: 'float'` colours take 16 bytes, so 8,388,608. A bigger cloud throws a `RangeError` naming its ceiling before any buffer is made. Split bigger clouds into several `PointCloud`s, or keep RGBA8 colours.
736
+ - `points.pick` is CPU-side over the points drawn in the latest frame; meshes do not occlude it, and clipping planes do not apply to it. `PointPicking` does both on the GPU, but answers later, through a promise.
737
+ - Block bounds only grow on updates; call `rebuild()` to tighten them or to include points that turned finite. Non-finite points are never drawn. A `reorder`ed cloud cannot be rebuilt.
738
+ - Per-point colors are stored as RGBA8 by default, so HDR vertex colors are clamped to 0..1; `colorFormat: 'float'` keeps them, at four times the color memory. A float color must be finite and 0 or more.
739
+ - A `GPUTexture` you pass is created on a device the plugin does not own: after a device loss the material draws untextured (reported once through `engine.onError`, help `borrowed-lost`) until you assign a new texture, or pass `(device) => GPUTexture` so it comes back by itself. Uploaded image sources are rebuilt automatically.
740
+ - Transparent points and sprites are not sorted per point on their own draw. For correct overlap of translucent clouds, add the plugin to an order-independent pass with `addEffect` from `margoengine/oit/vfx` (weighted blended or moments, and exact per-pixel layers on native WebGPU, where the compatibility layer refuses `ExactOIT` with a coded `unsupported`); otherwise use `alphaTest` or additive blending. Round antialiased edges of opaque points write depth.
741
+ - A plain `PointCloud` keeps its point size when the budget subsamples its blocks unless its material sets `adaptiveSize` (a limit on the growth; see Adaptive size under a budget). The budget is shared again every frame, so raising `pointBudget` draws more points at once. `OctreeCloud` has its own `adaptiveSize`, which sizes points from the node spacing. `OctreeCloud` streams nodes from any `OctreeSource`, but the package has no on-disk octree format of its own; it reads COPC and Potree.
742
+
743
+ ## Adaptive size under a budget
744
+
745
+ When `pointBudget` is lower than the points in view, the plugin thins every block and gaps open between the points left. `adaptiveSize` on `PointsMaterial` grows the points to cover them: the diameter and both pixel clamps are multiplied by the square root of visible over drawn points, up to the value you set. 0 or 1 (the default) keeps the size. The multiple is one per cloud, so a cloud whose blocks are thinned unevenly is sized by its average.
746
+
747
+ ```ts
748
+ import {PointCloud, PointsPlugin} from 'margoengine/points';
749
+
750
+ const plugin=new PointsPlugin({pointBudget:250_000});
751
+ const positions=new Float32Array(3*1_000_000);
752
+ for(let i=0;i<positions.length;i++) positions[i]=Math.random();
753
+ const cloud=new PointCloud({positions,material:{size:2,adaptiveSize:4}});
754
+ plugin.add(cloud);
755
+ // Four times fewer points are drawn than are visible, so each is drawn twice as wide.
756
+ console.log(cloud.material.adaptiveSize); // 4
757
+ ```
758
+
759
+ ## Tests
760
+
761
+ `npm test` in `packages/points` runs Node checks: chunking (coverage, block sizes, bounds, determinism, non-finite points) on random data and the real PCL `bunny.pcd` scan, even subsampling of shuffled prefixes, bounds growth, frustum culling against core `Camera.planes` with a randomized no-false-negative check, screen area, budget water-filling invariants, projection and picking against brute force, orthographic screen area and picking, color packing, ranges, atlas cells, `PointCloud` and `SpriteBatch` bookkeeping, materials, SSR safety and the linked WebGL2 preview refusal.
762
+
763
+ The LAZ tests (`tests/laz.test.js`) compress random, survey-like and mixed points of formats 0 to 10 with
764
+ the test-only encoder (`tests/laz-encoder.js`) in fixed and variable chunks, check that decoding returns every record
765
+ byte for byte (`tests/laz-usgs.test.js` runs the real USGS tile through the same decoder and checks it against the file's header) and that `parseLAS` with the decoder matches the uncompressed file, and fuzz truncated and corrupt
766
+ files (only coded errors, no hang). `tests/laz-real.test.js` reads the real files in `tests/fixtures/laz` against LASzip and lazrs.
767
+
768
+ `npm run test:browser` (a real-GPU script, not in CI) renders with a real engine in Chromium (or Edge via `BROWSER_CHANNEL`): exact square coverage at 2 to 16 px, round coverage within 4% of the disc area with empty corners, per-point byte and float colors, depth against a core mesh and between points, attachment to a mesh, size attenuation, a 2,000,000 point cloud culled and drawn within a 500,000 point budget, subrange updates that issue exactly one `writeBuffer` per changed range, sprites that stay square after an orbit with the right atlas cell, rotation, pivot and pixel size, 5000 sprites in one draw call, textured points with alpha test, sphere shading, eye-dome lighting, CPU picking, an orthographic camera (world sizes equal at two depths, sphere impostor depth against a box, EDL at a depth step, nearer-point picking), zero WebGPU validation errors, device restore and dispose. It saves `test-results/points-gallery.png` and `test-results/points-browser.json`.
769
+
770
+ Apache-2.0 licensed.
771
+
772
+ ## Preview tier contract
773
+
774
+ The small `@margoengine/webgl2-compat/preview` renderer reports `backend: 'webgl2'` and has no GPU device. GPU-only attachments throw a linked `MargoError` with code `unsupported` before allocating resources. Native WebGPU and the full WebGL2 compatibility layer both report `backend: 'webgpu'`. Use [`autoEngine` with `loadCompat`](../webgl2-compat/README.md#automatic-escalation) during scene setup to select a complete tier automatically.
775
+
776
+ The renderer now refuses the preview during setup, allowing automatic escalation instead of accepting an attachment that cannot draw.
777
+
778
+ ### Shared CPU projection
779
+
780
+ `projectToPixels` delegates to `@margoengine/math/mat4` `projectPoint` with
781
+ WebGPU reversed-Z depth. Width and height are device pixels. It returns false
782
+ for a point behind the camera or outside normalized depth 0..1 (including NaN)
783
+ and leaves `out` unchanged. Offscreen x/y still project for radius picking.
784
+ The third output is clip w in perspective and normalized near-to-far depth for
785
+ orthographic matrices. The call is synchronous and reuses internal scratch.
786
+
787
+ ```js
788
+ import { projectToPixels } from '@margoengine/points';
789
+ const matrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
790
+ const screen = new Float64Array(3);
791
+ if (projectToPixels(matrix, 0, 0, 0.5, 640, 480, screen)) {
792
+ console.log(screen); // Float64Array [320, 240, 0.5]
793
+ }
794
+ ```