@margoengine/splats 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 (57) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +443 -3
  4. package/dist/animate.d.ts +138 -0
  5. package/dist/animate.js +31 -0
  6. package/dist/brush.d.ts +94 -0
  7. package/dist/brush.js +36 -0
  8. package/dist/compat-CDoDsXE8.js +19 -0
  9. package/dist/compat.d.ts +7 -0
  10. package/dist/compressed.d.ts +40 -0
  11. package/dist/data-D31W24Wu.js +2 -0
  12. package/dist/data.d.ts +28 -0
  13. package/dist/data.js +1 -0
  14. package/dist/depth.d.ts +42 -0
  15. package/dist/depth.js +14 -0
  16. package/dist/edit.d.ts +48 -0
  17. package/dist/encode-BA6xu973.js +1 -0
  18. package/dist/encode.d.ts +40 -0
  19. package/dist/formats.d.ts +24 -0
  20. package/dist/formats.js +5 -0
  21. package/dist/index.d.ts +167 -0
  22. package/dist/index.js +1 -0
  23. package/dist/lighting.d.ts +89 -0
  24. package/dist/lighting.js +48 -0
  25. package/dist/lod-sog.d.ts +44 -0
  26. package/dist/lod-sog.js +1 -0
  27. package/dist/lod.d.ts +129 -0
  28. package/dist/lod.js +4 -0
  29. package/dist/modify.d.ts +83 -0
  30. package/dist/modify.js +24 -0
  31. package/dist/pick.d.ts +75 -0
  32. package/dist/pick.js +14 -0
  33. package/dist/ply.d.ts +62 -0
  34. package/dist/progressive.d.ts +37 -0
  35. package/dist/progressive.js +5 -0
  36. package/dist/scene-scope-C5HWuOIb.js +4 -0
  37. package/dist/session.d.ts +127 -0
  38. package/dist/session.js +1 -0
  39. package/dist/set.d.ts +59 -0
  40. package/dist/set.js +4 -0
  41. package/dist/shader-B7zZyYz-.js +64 -0
  42. package/dist/shader.d.ts +17 -0
  43. package/dist/shared/fog.d.ts +33 -0
  44. package/dist/shared/pass.d.ts +53 -0
  45. package/dist/sog-D0LYo48N.js +1 -0
  46. package/dist/sog.d.ts +20 -0
  47. package/dist/sort.d.ts +4 -0
  48. package/dist/spz-BTy6CPTp.js +1 -0
  49. package/dist/spz.d.ts +23 -0
  50. package/dist/src-DlpBlCx1.js +48 -0
  51. package/dist/view-DyJeX8rJ.js +1 -0
  52. package/dist/view-rect-G-t2gTqO.js +1 -0
  53. package/dist/webp.d.ts +11 -0
  54. package/dist/zip-DNluwYbe.js +1 -0
  55. package/dist/zip.d.ts +7 -0
  56. package/dist/zstd-BPbUkXlY.js +1 -0
  57. package/package.json +107 -6
@@ -0,0 +1,167 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ import { type Engine, type EnginePlugin, type FrameGraph, type PassContext } from '@margoengine/core/extension';
3
+ import { type SplatData } from './data.js';
4
+ import { type FogLike } from './shared/fog.js';
5
+ export type { FogLike } from './shared/fog.js';
6
+ import { type SurfaceTransparency } from './shared/pass.js';
7
+ export { parseSplat, validateSplats, type SplatData } from './data.js';
8
+ export { parsePly, encodeSplat, decomposeCovariance, splatsFromAttributes, attributesFromSplats, type GaussianAttributes, } from './ply.js';
9
+ export { parseSpz, parseSog, encodeSpz, encodeSog, type ParseSpzOptions, type ParseSogOptions, type SogFiles, type EncodeSpzOptions, } from './compressed.js';
10
+ export { cropSplats, filterSplats, transformSplats, mergeSplats, decimateSplats, type SplatRegion } from './edit.js';
11
+ type Context = Extract<PassContext, {
12
+ backend: 'webgpu';
13
+ }>;
14
+ /**
15
+ * A Gaussian splat cloud: GPU projection to screen ellipses, an 8-pass radix depth sort and far-to-near blending
16
+ * against the scene depth, every frame with no CPU sorting. `Splats.attach(engine, data)`; WebGPU only.
17
+ * @throws TypeError / RangeError from the constructor when `data` is invalid (see `validateSplats`); RangeError when
18
+ * attaching a cloud that exceeds the adapter's compute or storage limits.
19
+ * @throws MargoError `'unsupported'` on a WebGL engine, `'disposed'` after `dispose()`, `'state'` from `gpuState`
20
+ * before the cloud is attached.
21
+ */
22
+ export declare class Splats implements EnginePlugin {
23
+ readonly name: string;
24
+ readonly count: number;
25
+ private readonly positions;
26
+ private readonly covariances;
27
+ private readonly colors;
28
+ private readonly sh;
29
+ private engine?;
30
+ private device?;
31
+ private buffers;
32
+ private inputs;
33
+ private uniform?;
34
+ private fadeData?;
35
+ private fadeBuffer?;
36
+ private index?;
37
+ private projected?;
38
+ private evaluated?;
39
+ private keys;
40
+ private projection?;
41
+ private projectionGroup?;
42
+ private projectionBuffers;
43
+ private fogSource;
44
+ private fogged?;
45
+ private readonly fogData;
46
+ private sortPipelines;
47
+ private sortGroups;
48
+ private compatSort?;
49
+ private renders;
50
+ private disposed;
51
+ private mip;
52
+ private writes;
53
+ private readonly transparency;
54
+ private readonly attachment;
55
+ private readonly plainDepth;
56
+ private readonly stencilDepth;
57
+ private readonly presentation;
58
+ private record?;
59
+ private recordSamples?;
60
+ private recordFormat?;
61
+ private recordDepth?;
62
+ private readonly values;
63
+ private readonly integers;
64
+ private readonly view;
65
+ constructor(data: SplatData);
66
+ /**
67
+ * A cloud of `count` hidden splats (opacity 0) with `coefficients` SH coefficients per channel (0, 4, 9, 16 or 25), to
68
+ * fill later with `write`: a pool for streamed or edited splats. Hidden splats are culled before the sort.
69
+ * @throws RangeError for a count outside 1 to 3,000,000 or another coefficient count.
70
+ */
71
+ static reserve(count: number, coefficients?: number): Splats;
72
+ /** SH coefficients per channel: 0, 4, 9, 16 or 25. */
73
+ get coefficients(): number;
74
+ /**
75
+ * Replaces splats `first` to `first + n - 1` with the `n` splats of `data` (same SH coefficient count as the cloud),
76
+ * in the copy kept for device restoration and, when attached, on the GPU before the next frame.
77
+ * @throws RangeError when `data` is invalid, has another SH coefficient count or does not fit; MargoError
78
+ * `'disposed'` after `dispose()`.
79
+ */
80
+ write(first: number, data: SplatData): this;
81
+ /**
82
+ * Hides splats `first` to `first + count - 1` (opacity 0), as `write` would.
83
+ * @throws RangeError when the range does not fit; MargoError `'disposed'` after `dispose()`.
84
+ */
85
+ clear(first: number, count: number): this;
86
+ /**
87
+ * Sets the opacity of splats `first` to `first + alphas.length - 1` to `alphas[i] * scale`, uploading only their
88
+ * positions and colours (32 of the 128 bytes a splat takes), not covariances or SH: a cheap fade or hide of a range
89
+ * whose own opacities you keep. `scale` 0 hides them (culled before the sort).
90
+ * @throws RangeError when the range does not fit or `scale` is outside 0 to 1; MargoError `'disposed'` after `dispose()`.
91
+ */
92
+ setOpacities(first: number, alphas: Float32Array, scale?: number): this;
93
+ private range;
94
+ private upload;
95
+ /** GPU bytes of the optional per-splat screen-door intervals; zero until enabled. */
96
+ get ditherFadeBytes(): number;
97
+ /** Sets coverage [lower,upper] for an original-order content range. Default full coverage; no opacity or sort edits. */
98
+ setDitherFade(first: number, count: number, lower?: number, upper?: number): this;
99
+ private prepareFade;
100
+ /**
101
+ * The cloud as data, after any edits or poses made on the GPU (`./edit`, `./animate`): when attached, centres,
102
+ * covariances, opacities, colours and SH are read back into the copy kept for device restoration first. For export
103
+ * (`encodeSplat`, `encodeSpz`, `encodeSog`) and to keep GPU edits through a device loss.
104
+ * @throws MargoError `'disposed'` after `dispose()`; the GPU's error when the device is lost during the read.
105
+ */
106
+ read(): Promise<SplatData>;
107
+ /**
108
+ * Anti-aliasing (Mip-Splatting's 2D filter): when true, each splat's opacity is scaled by
109
+ * sqrt(det(S) / det(S + 0.3 I)) of its screen covariance S, so a splat smaller than a pixel fades with its true
110
+ * coverage instead of drawing as a 0.3 px^2 blob at full opacity, and distant or small captures stop shimmering.
111
+ * Default false (the look trained 3DGS files were made with). Live: read each frame, no recompile.
112
+ */
113
+ get antialias(): boolean;
114
+ set antialias(on: boolean);
115
+ /** The fog the splats are drawn in (see `setFog`), or null. */
116
+ get fog(): FogLike | null;
117
+ /**
118
+ * Fogs the cloud: `fog` is `@margoengine/environment`'s `Fog` or any object with its fields, read every frame, with
119
+ * Fog's maths (linear near/far, exp2 density, height falloff). Each splat's colour fades toward the fog colour by the
120
+ * fog at its centre, in the projection pass (so `gpuState.colors` holds fogged colours); its opacity is unchanged.
121
+ * `null` (the default) draws exactly as without fog. The first fogged frame compiles a second projection shader;
122
+ * changing the fog or its `enabled` flag never does.
123
+ * @throws TypeError when `fog` is neither an object nor null; RangeError or TypeError for an invalid field.
124
+ */
125
+ setFog(fog: FogLike | null): this;
126
+ static attach(instance: EngineKernel, data: SplatData): Splats;
127
+ setup(engine: Engine): void;
128
+ registerPasses(graph: FrameGraph): void;
129
+ private sort;
130
+ /** The fog uniform and the fogged projection pipeline and group, made on the first fogged frame. */
131
+ private fogResources;
132
+ private dispatch;
133
+ /** Pipeline and group 0 for this target, and for `hook` when given. */
134
+ private fadeShader;
135
+ private pipeline;
136
+ private draw;
137
+ /**
138
+ * Leaves the frame's draw (order 3) and the depth sort to an order-independent pass, which calls `drawTransparent`. Use
139
+ * `addEffect` from `@margoengine/oit/vfx`. `gpuState.sorted` then holds the keys unsorted. Returns a remover; `released`
140
+ * runs if this cloud is disposed first.
141
+ */
142
+ setTransparency(hook: SurfaceTransparency, released?: () => void): () => void;
143
+ /** Draws the cloud into `hook`'s pass, depth tested and not written. */
144
+ drawTransparent(c: Context, hook: SurfaceTransparency): void;
145
+ /** Whether the cloud is attached to a live engine, so `gpuState` holds its buffers. */
146
+ get attached(): boolean;
147
+ /**
148
+ * The cloud's GPU buffers, for entries that draw or edit it: `sorted` keys, projected `ellipses`, evaluated `colors`
149
+ * (rgb, opacity) and the inputs `positions` (xyz, opacity), `covariances` (two vec4f per splat), `inputColors` (rgb,
150
+ * opacity) and `sh` (SH coefficients, RGB interleaved; 4 unused floats without SH).
151
+ */
152
+ get gpuState(): {
153
+ sorted: GPUBuffer;
154
+ ellipses: GPUBuffer;
155
+ colors: GPUBuffer;
156
+ positions: GPUBuffer;
157
+ covariances: GPUBuffer;
158
+ inputColors: GPUBuffer;
159
+ sh: GPUBuffer;
160
+ };
161
+ private release;
162
+ onDeviceRestored(engine: Engine): void;
163
+ dispose(): void;
164
+ [Symbol.dispose]: () => void;
165
+ /** @deprecated Use dispose(); kept as an alias until 1.0. */
166
+ destroy(): void;
167
+ }
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{_ as e,a as t,c as n,d as r,f as i,h as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,s as p,t as m,u as h}from"./data-D31W24Wu.js";import{t as g}from"./src-DlpBlCx1.js";export{g as Splats,i as attributesFromSplats,f as cropSplats,o as decimateSplats,d as decomposeCovariance,n as encodeSog,c as encodeSplat,s as encodeSpz,t as filterSplats,u as mergeSplats,a as parsePly,h as parseSog,m as parseSplat,r as parseSpz,e as splatsFromAttributes,p as transformSplats,l as validateSplats};
@@ -0,0 +1,89 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin, type FrameGraph } from '@margoengine/core/extension';
4
+ import type { Splats } from './index.js';
5
+ /** Options of {@link SplatLighting}. */
6
+ export interface SplatLightingOptions {
7
+ /**
8
+ * Shadow coverage. Unset (the default): stochastic, a splat blocks each shadow-map texel with the probability of its
9
+ * opacity there, so a capture's many small overlapping splats shade as their combined opacity (noisy at a texel,
10
+ * smoothed by the shadow filter). A number from 0 to 1: a splat blocks where its opacity reaches it, as `./depth`
11
+ * (no noise, but a sparse capture leaves gaps). Live: `lighting.threshold`.
12
+ */
13
+ threshold?: number;
14
+ /** Relight the cloud with the scene light (false keeps its captured colours; it still casts). Default true. Live. */
15
+ relight?: boolean;
16
+ }
17
+ /** What `@margoengine/shadows` hands a custom caster for one cascade (its `ShadowContext`). */
18
+ export interface SplatShadowContext {
19
+ context: {
20
+ device: GPUDevice;
21
+ };
22
+ pass: GPURenderPassEncoder;
23
+ /** The cascade's light view-projection matrix, 16 floats, column-major. */
24
+ matrix: Float32Array;
25
+ /** Cascade index, 0 to 3. */
26
+ cascade: number;
27
+ }
28
+ /**
29
+ * WGSL of the relight pass. Uniform: eye, light (xyz toward the light, unit; w intensity), radiance (rgb; w ambient),
30
+ * ambient rgb, counts (x splats, y 1 to relight).
31
+ */
32
+ export declare const relightShader = "struct Light {eye:vec4f,light:vec4f,radiance:vec4f,ambient:vec4f,counts:vec4u}\n@group(0) @binding(0) var<uniform> u:Light;\n@group(0) @binding(1) var<storage,read> positions:array<vec4f>;\n@group(0) @binding(2) var<storage,read> covariances:array<vec4f>;\n@group(0) @binding(3) var<storage,read_write> evaluated:array<vec4f>;\n\nfn flatAxis(m:mat3x3f,view:vec3f)->vec3f {\n let p1=m[0].y*m[0].y+m[0].z*m[0].z+m[1].z*m[1].z;let q=(m[0].x+m[1].y+m[2].z)/3.0;\n let p2=(m[0].x-q)*(m[0].x-q)+(m[1].y-q)*(m[1].y-q)+(m[2].z-q)*(m[2].z-q)+2.0*p1;let p=sqrt(p2/6.0);\n if(p<=1e-6*max(abs(q),1e-30)){return view;}\n let bm=(m-mat3x3f(vec3f(q,0,0),vec3f(0,q,0),vec3f(0,0,q)))*(1.0/p);let r=clamp(determinant(bm)*0.5,-1.0,1.0);\n let smallest=q+2.0*p*cos(acos(r)/3.0+2.0943951024);\n let s=m-mat3x3f(vec3f(smallest,0,0),vec3f(0,smallest,0),vec3f(0,0,smallest));\n let c0=cross(s[0],s[1]);let c1=cross(s[0],s[2]);let c2=cross(s[1],s[2]);\n var n=c0;if(dot(c1,c1)>dot(n,n)){n=c1;}if(dot(c2,c2)>dot(n,n)){n=c2;}\n if(dot(n,n)<1e-30){return view;}return normalize(n);\n}\n@compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u) {\n let index=id.x;if(index>=u.counts.x||u.counts.y==0u){return;}let world=positions[index];if(world.w<=0){return;}\n let a=covariances[index*2];let b=covariances[index*2+1];let cov=mat3x3f(vec3f(a.x,a.y,a.z),vec3f(a.y,a.w,b.x),vec3f(a.z,b.x,b.y));\n let view=normalize(u.eye.xyz-world.xyz);var n=flatAxis(cov,view);if(dot(n,view)<0){n=-n;}\n let nl=max(dot(n,u.light.xyz),0.0);let e=evaluated[index];\n evaluated[index]=vec4f(e.rgb*(u.radiance.rgb*u.light.w*nl/3.14159265+u.radiance.w*u.ambient.rgb),e.a);\n}";
33
+ /**
34
+ * WGSL of the shadow caster: the colour pass's 3 sigma quad and falloff in the light's clip space, with the Jacobian
35
+ * of clip/w by position. threshold.x: the coverage threshold (negative for stochastic); threshold.yz: the colour pass's
36
+ * 0.3 px^2 dilation in shadow-map texels, so a capture's sub-texel splats still cover texels as they cover pixels.
37
+ */
38
+ export declare const shadowShader = "struct Caster {m:mat4x4f,threshold:vec4f}\n@group(0) @binding(0) var<uniform> u:Caster;\n@group(0) @binding(1) var<storage,read> positions:array<vec4f>;\n@group(0) @binding(2) var<storage,read> covariances:array<vec4f>;\nstruct Out {@builtin(position) @invariant clip:vec4f,@location(0) corner:vec2f,@location(1) @interpolate(flat) opacity:f32,@location(2) @interpolate(flat) index:u32}\n@vertex fn vertex(@builtin(vertex_index) vertex:u32,@builtin(instance_index) index:u32)->Out {\n let corners=array<vec2f,4>(vec2f(-1,-1),vec2f(1,-1),vec2f(-1,1),vec2f(1,1));let world=positions[index];var o:Out;\n o.corner=corners[vertex];o.opacity=world.w;o.index=index;o.clip=vec4f(2,2,0,1);\n let c=u.m*vec4f(world.xyz,1);if(world.w<=0||world.w<u.threshold.x||c.w<=0){return o;}\n let a=covariances[index*2];let b=covariances[index*2+1];let cov=mat3x3f(vec3f(a.x,a.y,a.z),vec3f(a.y,a.w,b.x),vec3f(a.z,b.x,b.y));\n let rw=vec3f(u.m[0].w,u.m[1].w,u.m[2].w);\n let jx=(vec3f(u.m[0].x,u.m[1].x,u.m[2].x)-rw*(c.x/c.w))/c.w;let jy=(vec3f(u.m[0].y,u.m[1].y,u.m[2].y)-rw*(c.y/c.w))/c.w;\n let xx=dot(jx,cov*jx)+u.threshold.y;let xy=dot(jx,cov*jy);let yy=dot(jy,cov*jy)+u.threshold.z;let mid=(xx+yy)*0.5;\n let radius=sqrt(max(0.0,(xx-yy)*(xx-yy)*0.25+xy*xy));let major=max(mid+radius,0.0);let minor=max(mid-radius,0.0);\n var axis=vec2f(1,0);if(abs(xy)>1e-12){axis=normalize(vec2f(xy,major-xx));}else if(yy>xx){axis=vec2f(0,1);}\n let first=axis*(3*sqrt(major));let second=vec2f(-axis.y,axis.x)*(3*sqrt(minor));\n o.clip=vec4f(c.xy/c.w+first*o.corner.x+second*o.corner.y,c.z/c.w,1);return o;\n}\nfn hash(v:u32)->u32 {let s=v*747796405u+2891336453u;let w=((s>>((s>>28u)+4u))^s)*277803737u;return (w>>22u)^w;}\n@fragment fn fragment(i:Out) {let power=-4.5*dot(i.corner,i.corner);if(power<-4.5){discard;}let alpha=min(0.99,i.opacity*exp(power));\n\n var cut=u.threshold.x;if(cut<0){let t=vec2u(i.clip.xy);cut=f32(hash(hash(hash(i.index)^t.x)^t.y)>>8u)/16777216.0;}if(alpha<cut){discard;}}";
39
+ /**
40
+ * Scene light and shadows for a splat cloud: `const lit = SplatLighting.attach(engine, cloud)` relights it with
41
+ * `engine.lighting` every frame, and `shadows.add(lit)` (a `@margoengine/shadows` `Shadows`) makes it cast on meshes.
42
+ * WebGPU only, as `Splats`.
43
+ * @throws RangeError for a threshold outside 0 to 1 (unset is stochastic); TypeError when `cloud` is not a Splats.
44
+ * @throws MargoError `'unsupported'` on a WebGL engine, `'disposed'` when attached after `dispose()`.
45
+ */
46
+ export declare class SplatLighting implements EnginePlugin {
47
+ private static next;
48
+ readonly name: string;
49
+ readonly cloud: Splats;
50
+ /** Relight with the scene light; false keeps the captured colours. */
51
+ relight: boolean;
52
+ private value;
53
+ private engine?;
54
+ private uniform?;
55
+ private casterUniform?;
56
+ private readonly data;
57
+ private readonly integers;
58
+ private readonly caster;
59
+ private compute?;
60
+ private group?;
61
+ private shadow?;
62
+ private shadows?;
63
+ private dead;
64
+ constructor(cloud: Splats, options?: SplatLightingOptions);
65
+ /** Same as `engine.use(new SplatLighting(cloud, options))`; returns it. */
66
+ static attach(engine: EngineKernel, cloud: Splats, options?: SplatLightingOptions): SplatLighting;
67
+ /** Opacity a splat must reach at a shadow-map texel to block the light (0 to 1), or undefined for stochastic. */
68
+ get threshold(): number | undefined;
69
+ set threshold(value: number | undefined);
70
+ /** True once disposed (`@margoengine/shadows` then drops it). */
71
+ get disposed(): boolean;
72
+ setup(engine: Engine): void;
73
+ registerPasses(graph: FrameGraph): void;
74
+ private light;
75
+ /**
76
+ * Called by `Shadows.add(lighting)`: the shadow map size, read each frame, sets the splats' smallest footprint there.
77
+ * Returns the remover.
78
+ */
79
+ addLighting(shadows: {
80
+ options?: {
81
+ resolution?: number | readonly [number, number];
82
+ };
83
+ }): () => void;
84
+ /** Draws the cloud's depth into one shadow cascade (the `ShadowSource` contract of `@margoengine/shadows`). */
85
+ drawShadow({ context, pass, matrix, cascade }: SplatShadowContext): void;
86
+ onDeviceRestored(engine: Engine): void;
87
+ dispose(): void;
88
+ [Symbol.dispose]: () => void;
89
+ }
@@ -0,0 +1,48 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const e=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as t}from"@margoengine/math/errors";var n=`let a=covariances[index*2];let b=covariances[index*2+1];let cov=mat3x3f(vec3f(a.x,a.y,a.z),vec3f(a.y,a.w,b.x),vec3f(a.z,b.x,b.y));`,r=`struct Light {eye:vec4f,light:vec4f,radiance:vec4f,ambient:vec4f,counts:vec4u}
5
+ @group(0) @binding(0) var<uniform> u:Light;
6
+ @group(0) @binding(1) var<storage,read> positions:array<vec4f>;
7
+ @group(0) @binding(2) var<storage,read> covariances:array<vec4f>;
8
+ @group(0) @binding(3) var<storage,read_write> evaluated:array<vec4f>;
9
+
10
+ fn flatAxis(m:mat3x3f,view:vec3f)->vec3f {
11
+ let p1=m[0].y*m[0].y+m[0].z*m[0].z+m[1].z*m[1].z;let q=(m[0].x+m[1].y+m[2].z)/3.0;
12
+ let p2=(m[0].x-q)*(m[0].x-q)+(m[1].y-q)*(m[1].y-q)+(m[2].z-q)*(m[2].z-q)+2.0*p1;let p=sqrt(p2/6.0);
13
+ if(p<=1e-6*max(abs(q),1e-30)){return view;}
14
+ let bm=(m-mat3x3f(vec3f(q,0,0),vec3f(0,q,0),vec3f(0,0,q)))*(1.0/p);let r=clamp(determinant(bm)*0.5,-1.0,1.0);
15
+ let smallest=q+2.0*p*cos(acos(r)/3.0+2.0943951024);
16
+ let s=m-mat3x3f(vec3f(smallest,0,0),vec3f(0,smallest,0),vec3f(0,0,smallest));
17
+ let c0=cross(s[0],s[1]);let c1=cross(s[0],s[2]);let c2=cross(s[1],s[2]);
18
+ var n=c0;if(dot(c1,c1)>dot(n,n)){n=c1;}if(dot(c2,c2)>dot(n,n)){n=c2;}
19
+ if(dot(n,n)<1e-30){return view;}return normalize(n);
20
+ }
21
+ @compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u) {
22
+ let index=id.x;if(index>=u.counts.x||u.counts.y==0u){return;}let world=positions[index];if(world.w<=0){return;}
23
+ ${n}
24
+ let view=normalize(u.eye.xyz-world.xyz);var n=flatAxis(cov,view);if(dot(n,view)<0){n=-n;}
25
+ let nl=max(dot(n,u.light.xyz),0.0);let e=evaluated[index];
26
+ evaluated[index]=vec4f(e.rgb*(u.radiance.rgb*u.light.w*nl/3.14159265+u.radiance.w*u.ambient.rgb),e.a);
27
+ }`,i=`struct Caster {m:mat4x4f,threshold:vec4f}
28
+ @group(0) @binding(0) var<uniform> u:Caster;
29
+ @group(0) @binding(1) var<storage,read> positions:array<vec4f>;
30
+ @group(0) @binding(2) var<storage,read> covariances:array<vec4f>;
31
+ struct Out {@builtin(position) @invariant clip:vec4f,@location(0) corner:vec2f,@location(1) @interpolate(flat) opacity:f32,@location(2) @interpolate(flat) index:u32}
32
+ @vertex fn vertex(@builtin(vertex_index) vertex:u32,@builtin(instance_index) index:u32)->Out {
33
+ let corners=array<vec2f,4>(vec2f(-1,-1),vec2f(1,-1),vec2f(-1,1),vec2f(1,1));let world=positions[index];var o:Out;
34
+ o.corner=corners[vertex];o.opacity=world.w;o.index=index;o.clip=vec4f(2,2,0,1);
35
+ let c=u.m*vec4f(world.xyz,1);if(world.w<=0||world.w<u.threshold.x||c.w<=0){return o;}
36
+ ${n}
37
+ let rw=vec3f(u.m[0].w,u.m[1].w,u.m[2].w);
38
+ let jx=(vec3f(u.m[0].x,u.m[1].x,u.m[2].x)-rw*(c.x/c.w))/c.w;let jy=(vec3f(u.m[0].y,u.m[1].y,u.m[2].y)-rw*(c.y/c.w))/c.w;
39
+ let xx=dot(jx,cov*jx)+u.threshold.y;let xy=dot(jx,cov*jy);let yy=dot(jy,cov*jy)+u.threshold.z;let mid=(xx+yy)*0.5;
40
+ let radius=sqrt(max(0.0,(xx-yy)*(xx-yy)*0.25+xy*xy));let major=max(mid+radius,0.0);let minor=max(mid-radius,0.0);
41
+ var axis=vec2f(1,0);if(abs(xy)>1e-12){axis=normalize(vec2f(xy,major-xx));}else if(yy>xx){axis=vec2f(0,1);}
42
+ let first=axis*(3*sqrt(major));let second=vec2f(-axis.y,axis.x)*(3*sqrt(minor));
43
+ o.clip=vec4f(c.xy/c.w+first*o.corner.x+second*o.corner.y,c.z/c.w,1);return o;
44
+ }
45
+ fn hash(v:u32)->u32 {let s=v*747796405u+2891336453u;let w=((s>>((s>>28u)+4u))^s)*277803737u;return (w>>22u)^w;}
46
+ @fragment fn fragment(i:Out) {let power=-4.5*dot(i.corner,i.corner);if(power<-4.5){discard;}let alpha=min(0.99,i.opacity*exp(power));
47
+
48
+ var cut=u.threshold.x;if(cut<0){let t=vec2u(i.clip.xy);cut=f32(hash(hash(hash(i.index)^t.x)^t.y)>>8u)/16777216.0;}if(alpha<cut){discard;}}`,a=class n{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);static{this.next=0}constructor(e,t={}){if(this.name=`splats-lighting:`+n.next++,this.data=/* @__PURE__ */ new Float32Array(20),this.integers=new Uint32Array(this.data.buffer),this.caster=/* @__PURE__ */ new Float32Array(20),this.dead=!1,!e||typeof e!=`object`||!(`gpuState`in e))throw TypeError(`SplatLighting needs a Splats cloud`);this.cloud=e,this.value=t.threshold===void 0?void 0:o(t.threshold),this.relight=t.relight??!0}static attach(t,r,i={}){__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));let a=new n(r,i);return e(t).use(a),a}get threshold(){return this.value}set threshold(e){this.value=e===void 0?void 0:o(e)}get disposed(){return this.dead}setup(e){if(this.dead||!e.gpu)throw new t(this.dead?`disposed`:`unsupported`,`SplatLighting needs WebGPU; attach a new SplatLighting to a WebGPU engine; see https://margoengine.com/errors#webgpu`);this.engine=e,this.uniform=e.gpu.createBuffer({size:80,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})}registerPasses(e){e.add({name:this.name,order:-6.5,execute:e=>{e.backend===`webgpu`&&this.light(e)}})}light(e){if(!this.relight||!this.cloud.attached)return;let t=this.cloud.gpuState,n=e.device;this.compute??=n.createComputePipeline({layout:`auto`,compute:{module:n.createShaderModule({code:r}),entryPoint:`main`}}),(!this.group||this.group.colors!==t.colors||this.group.positions!==t.positions)&&(this.group={group:n.createBindGroup({layout:this.compute.getBindGroupLayout(0),entries:[this.uniform,t.positions,t.covariances,t.colors].map((e,t)=>({binding:t,resource:{buffer:e}}))}),colors:t.colors,positions:t.positions});let{direction:i,radiance:a,ambient:o}=this.engine.lighting,s=this.data,c=Math.hypot(i[0],i[1],i[2])||1;s.set(e.camera.position,0);for(let e=0;e<3;e++)s[4+e]=i[e]/c;s[7]=i[3],s.set(a,8),o?s.set(o,12):s[12]=s[13]=s[14]=1,this.integers[16]=this.cloud.count,this.integers[17]=1,n.queue.writeBuffer(this.uniform,0,s);let l=e.encoder.beginComputePass();l.setPipeline(this.compute),l.setBindGroup(0,this.group.group),l.dispatchWorkgroups(Math.ceil(this.cloud.count/256)),l.end()}addLighting(e){return this.shadows=e,()=>{this.shadows===e&&(this.shadows=void 0)}}drawShadow({context:e,pass:t,matrix:n,cascade:r}){if(this.dead||!this.cloud.attached)return;let a=this.cloud.gpuState,o=e.device;if(!this.shadow||this.shadow.positions!==a.positions||this.shadow.device!==o){this.casterUniform?.destroy(),this.casterUniform=o.createBuffer({size:1024,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let e=o.createShaderModule({code:i}),t=o.createRenderPipeline({layout:`auto`,vertex:{module:e,entryPoint:`vertex`},fragment:{module:e,entryPoint:`fragment`,targets:[]},primitive:{topology:`triangle-strip`},depthStencil:{format:`depth32float`,depthWriteEnabled:!0,depthCompare:`less-equal`}}),n=t.getBindGroupLayout(0),r=[0,1,2,3].map(e=>o.createBindGroup({layout:n,entries:[{binding:0,resource:{buffer:this.casterUniform,offset:e*256,size:80}},{binding:1,resource:{buffer:a.positions}},{binding:2,resource:{buffer:a.covariances}}]}));this.shadow={pipeline:t,groups:r,positions:a.positions,device:o}}this.caster.set(n),this.caster[16]=this.value??-1;let s=this.shadows?.options?.resolution??2048,[c,l]=typeof s==`number`?[s,s]:s;this.caster[17]=.3*(2/c)**2,this.caster[18]=.3*(2/l)**2,o.queue.writeBuffer(this.casterUniform,r*256,this.caster),t.setPipeline(this.shadow.pipeline),t.setBindGroup(0,this.shadow.groups[r]),t.draw(4,this.cloud.count)}onDeviceRestored(e){this.compute=this.group=this.shadow=this.casterUniform=void 0,this.setup(e)}dispose(){this.dead||(this.dead=!0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.uniform?.destroy(),this.casterUniform?.destroy(),this.uniform=this.casterUniform=this.engine=this.compute=this.group=this.shadow=void 0)}[Symbol.dispose??Symbol()](){this.dispose()}};function o(e){if(typeof e!=`number`||!(e>=0&&e<=1))throw RangeError(`SplatLighting threshold must be 0 to 1`);return e}export{a as SplatLighting,r as relightShader,i as shadowShader};
@@ -0,0 +1,44 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { SplatData } from './data.js';
3
+ import type { SplatLodNode, SplatLodSource } from './lod.js';
4
+ /** Loading options for a streamed SOG hierarchy. */
5
+ export interface StreamedSogOptions {
6
+ /** Cancels manifest, metadata and subsequent chunk requests. */
7
+ signal?: AbortSignal;
8
+ /** Fetch implementation, for authentication or local file maps. Default global fetch. */
9
+ fetch?: typeof fetch;
10
+ /** Most decoded, idle chunks retained on the CPU. Default 2; zero retains none. */
11
+ cacheChunks?: number;
12
+ }
13
+ /**
14
+ * An abortable, lazy streamed SOG source. Spatial interior nodes hold no splats; each leaf is a chain from its
15
+ * coarsest available LOD to its finest. The environment is an unconditional sibling of the spatial tree.
16
+ * Metadata is resident; texture requests and decoded chunks are shared, with independent caller cancellation.
17
+ */
18
+ export declare class StreamedSogSource implements SplatLodSource {
19
+ readonly nodes: readonly SplatLodNode[];
20
+ /** Uniform coefficient count, promoted to the largest chunk's degree (0, 4, 9, 16 or 25). */
21
+ readonly coefficients: number;
22
+ private readonly abort;
23
+ private readonly idle;
24
+ private readonly cacheChunks;
25
+ private readonly ranges;
26
+ private readonly chunks;
27
+ private readonly fetcher;
28
+ private readonly stop?;
29
+ private readonly signal?;
30
+ private dead;
31
+ /** Use {@link loadStreamedSog}; the constructor takes validated manifest metadata. */
32
+ private constructor();
33
+ /** Loads a manifest and its small chunk metadata; no texture is fetched until `load`. */
34
+ static open(url: string | URL, options?: StreamedSogOptions): Promise<StreamedSogSource>;
35
+ /** Fetches and decodes only the chunk holding this node, then copies its storage-order run. */
36
+ load(index: number, signal: AbortSignal): Promise<SplatData>;
37
+ private acquire;
38
+ private decode;
39
+ /** Releases decoded chunks and cancels pending requests. Idempotent. */
40
+ dispose(): void;
41
+ [Symbol.dispose]: () => void;
42
+ }
43
+ /** Opens a streamed SOG v1 or pre-release manifest as a lazy {@link SplatLodSource}. */
44
+ export declare function loadStreamedSog(url: string | URL, options?: StreamedSogOptions): Promise<StreamedSogSource>;
@@ -0,0 +1 @@
1
+ import{t as e}from"./sog-D0LYo48N.js";import{MargoError as t}from"@margoengine/math/errors";var n=class n{constructor(e,t,n,r){this.abort=new AbortController,this.idle=/* @__PURE__ */ new Map,this.dead=!1,this.nodes=e,this.ranges=t,this.chunks=n,this.fetcher=r.fetch??globalThis.fetch,this.cacheChunks=r.cacheChunks??2,this.coefficients=n.reduce((e,t)=>Math.max(e,t.meta.shN?(t.meta.shN.bands+1)**2:0),0),this.signal=r.signal,this.stop=r.signal?()=>this.dispose():void 0,r.signal?.addEventListener(`abort`,this.stop,{once:!0})}static async open(e,i={}){i.signal?.throwIfAborted();let a=i.cacheChunks??2;if(!Number.isSafeInteger(a)||a<0)throw RangeError(`cacheChunks must be an integer of 0 or more; set the decoded chunk cache size`);let o=i.fetch??globalThis.fetch,s=new URL(e,globalThis.location?.href),c=await r(s,o,i.signal);if(c.version!==void 0&&c.version!==1)throw RangeError(`Unsupported streamed SOG version; export version 1`);if(!Number.isSafeInteger(c.lodLevels)||c.lodLevels<1||!Array.isArray(c.filenames)||!c.filenames.length||c.filenames.some(e=>typeof e!=`string`||!e))throw RangeError(`Invalid streamed SOG levels or filenames; supply a complete lod-meta.json`);if(c.model!==void 0&&c.model!==`antialiased`)throw new t(`unsupported`,`Streamed SOG model ${c.model} is not supported; 2D Gaussian scenes cannot be drawn here.`);let l=[...c.filenames];if(c.environment!=null){if(typeof c.environment!=`string`||!c.environment)throw RangeError(`Invalid environment path; use a SOG meta.json path`);l.push(c.environment)}let u=Array(l.length),d=0;await Promise.all(Array.from({length:Math.min(8,l.length)},async()=>{for(;d<l.length;){let e=d++,n=new URL(l[e],s),r=await o(n,{signal:i.signal});if(!r.ok)throw new t(`failed`,`SOG metadata ${n} returned HTTP ${r.status}; check the URL and server access`);let a=new Uint8Array(await r.arrayBuffer()),c=JSON.parse(new TextDecoder().decode(a));if(![2,3].includes(c.version)||!Number.isSafeInteger(c.count)||c.count<1||c.count>3e6||c.shN&&(!Number.isInteger(c.shN.bands)||c.shN.bands<1||c.shN.bands>(c.version===3?4:3)))throw RangeError(`Invalid SOG chunk version, count or SH degree; supply SOG v2 or v3 chunks`);u[e]={url:n,bytes:a,meta:c}}}));let f=[],p=[],m=c.filenames.map(()=>[]),h=Array(c.lodLevels).fill(0),g=/* @__PURE__ */ new Set,_=e=>{let{min:t,max:n}=e?.bound??{};if(!Array.isArray(t)||!Array.isArray(n)||t.length!==3||n.length!==3||t.some((e,t)=>!Number.isFinite(e)||!Number.isFinite(n[t])||e>n[t]))throw RangeError(`Invalid streamed SOG bounds; supply finite ordered xyz min/max`);return{center:t.map((e,t)=>e/2+n[t]/2),radius:Math.hypot(...n.map((e,n)=>e/2-t[n]/2))}},v=(e,t)=>{if(t>128||g.has(e))throw RangeError(`Invalid streamed SOG tree depth or cycle; supply an acyclic spatial tree`);g.add(e);let n=_(e),r=f.length;if(e.children){if(e.lods||!Array.isArray(e.children)||e.children.length!==2)throw RangeError(`A streamed SOG interior needs exactly two children and no lods; repair the manifest`);f.push({...n,count:0,error:0,children:[]}),p.push(void 0);let i=e.children.map(e=>v(e,t+1));f[r]={...n,count:0,error:0,children:i}}else{if(!e.lods||typeof e.lods!=`object`)throw RangeError(`A streamed SOG leaf needs lods; repair the manifest`);let t=Object.keys(e.lods).map(t=>{let n=Number(t),r=e.lods[t];if(!/^\d+$/.test(t)||!Number.isSafeInteger(n)||n>=c.lodLevels||!r||!Number.isSafeInteger(r.file)||r.file<0||r.file>=c.filenames.length||!Number.isSafeInteger(r.offset)||r.offset<0||!Number.isSafeInteger(r.count)||r.count<1||r.offset+r.count>u[r.file].meta.count)throw RangeError(`Invalid streamed SOG LOD range; use in-bounds file, offset and count`);return m[r.file].push({...r,level:n}),h[n]+=r.count,n}).sort((e,t)=>t-e);if(!t.length)throw RangeError(`A streamed SOG leaf has no levels; supply at least one splat range`);if(c.lodErrors===!0){let n=-1/0;for(let r of[...t].reverse()){let t=e.errors?.[r];if(t===void 0||!Number.isFinite(t)||t<0||t<n)throw RangeError(`Invalid streamed SOG errors; supply non-negative non-decreasing errors for held levels`);n=t}}let r=e.lods[String(t.at(-1))].count;t.forEach((i,a)=>{let o=e.lods[String(i)],s=a===t.length-1;f.push({...n,count:o.count,error:s?0:c.lodErrors===!0?e.errors[i]:n.radius*Math.cbrt(Math.max(0,1-o.count/r)),children:s?[]:[f.length+1]}),p.push(o)})}return r};if(c.environment!=null){let e=_(c.tree);f.push({...e,count:0,error:0,children:[]}),p.push(void 0);let t=u.length-1;f.push({...e,count:u[t].meta.count,error:0,children:[]}),p.push({file:t,offset:0,count:u[t].meta.count});let n=v(c.tree,0);f[0]={...e,count:0,error:0,children:[1,n]}}else v(c.tree,0);for(let e=0;e<m.length;e++){let t=m[e].sort((e,t)=>e.offset-t.offset),n=0;for(let e of t){if(e.offset!==n||e.level!==t[0].level)throw RangeError(`SOG chunk runs must cover a single level without overlaps or gaps; repair the manifest`);n+=e.count}if(n!==u[e].meta.count)throw RangeError(`SOG chunk runs do not cover its count; repair the manifest`)}if(c.count!==void 0&&c.count!==h.reduce((e,t)=>e+t,0)||c.counts!==void 0&&(!Array.isArray(c.counts)||c.counts.length!==h.length||h.some((e,t)=>e!==c.counts[t])))throw RangeError(`Streamed SOG count totals disagree with its ranges; repair the manifest`);return i.signal?.throwIfAborted(),new n(f,p,u,i)}async load(e,n){if(n.throwIfAborted(),this.signal?.throwIfAborted(),this.dead)throw new t(`disposed`,`Streamed SOG source was disposed; open a new source`);let r=this.ranges[e];if(!Number.isInteger(e)||!this.nodes[e])throw RangeError(`Unknown streamed SOG node; use an index from nodes`);if(!r)return{positions:/* @__PURE__ */ new Float32Array,covariances:/* @__PURE__ */ new Float32Array,colors:/* @__PURE__ */ new Float32Array};let i=this.chunks[r.file],a=await this.acquire(i,n),{offset:o,count:s}=r,c=this.coefficients,l=c?new Float32Array(s*c*3):void 0,u=a.sphericalHarmonics?a.sphericalHarmonics.length/(a.positions.length/3)/3:0;if(n.throwIfAborted(),this.abort.signal.throwIfAborted(),l)for(let e=0;e<s;e++)if(u)l.set(a.sphericalHarmonics.subarray((o+e)*u*3,(o+e+1)*u*3),e*c*3);else for(let t=0;t<3;t++)l[e*c*3+t]=(a.colors[(o+e)*4+t]-.5)/.2820947918;return{positions:a.positions.slice(o*3,(o+s)*3),covariances:a.covariances.slice(o*6,(o+s)*6),colors:a.colors.slice(o*4,(o+s)*4),...l?{sphericalHarmonics:l}:{}}}async acquire(e,t){if(e.data)return this.idle.delete(e),this.idle.set(e,e.data),e.data;if(!e.pending){let t=new AbortController,n=AbortSignal.any([t.signal,this.abort.signal]);e.pending={controller:t,promise:this.decode(e,n),users:0}}let n=e.pending;n.users++;try{let r=await new Promise((e,r)=>{let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),n.promise.then(e,r).finally(()=>t.removeEventListener(`abort`,i))});if(t.throwIfAborted(),this.abort.signal.throwIfAborted(),this.cacheChunks)for(e.data=r,this.idle.delete(e),this.idle.set(e,r);this.idle.size>this.cacheChunks;){let e=this.idle.keys().next().value;e.data=void 0,this.idle.delete(e)}return r}finally{--n.users===0&&(n.controller.abort(),e.pending===n&&(e.pending=void 0))}}async decode(n,r){let i={"meta.json":n.bytes},a=/* @__PURE__ */ new Set;for(let e of Object.values(n.meta))if(e&&typeof e==`object`&&`files`in e&&Array.isArray(e.files))for(let t of e.files){if(typeof t!=`string`)throw RangeError(`Invalid SOG texture name; supply string filenames`);a.add(t)}return await Promise.all([...a].map(async e=>{let a=await this.fetcher(new URL(e,n.url),{signal:r});if(!a.ok)throw new t(`failed`,`SOG texture ${e} returned HTTP ${a.status}; check the chunk files`);i[e]=await a.arrayBuffer()})),e(i,{signal:r})}dispose(){if(!this.dead){this.dead=!0,this.abort.abort(new t(`disposed`,`Streamed SOG source was disposed; open a new source`)),this.signal?.removeEventListener(`abort`,this.stop);for(let e of this.chunks)e.data=void 0;this.idle.clear()}}[Symbol.dispose??Symbol()](){this.dispose()}};async function r(e,n,r){let i=await n(e,{signal:r});if(!i.ok)throw new t(`failed`,`Streamed SOG manifest returned HTTP ${i.status}; check ${e}`);return i.json()}function i(e,t={}){return n.open(e,t)}export{n as StreamedSogSource,i as loadStreamedSog};
package/dist/lod.d.ts ADDED
@@ -0,0 +1,129 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin, type FrameGraph } from '@margoengine/core/extension';
4
+ import { type SplatData } from './data.js';
5
+ import { Splats } from './index.js';
6
+ /** One node of a {@link SplatLodSource}: a bounding sphere, its error and its children. */
7
+ export interface SplatLodNode {
8
+ /** Bounding sphere of the node's splat centres (and its children's), world units. */
9
+ readonly center: readonly [number, number, number];
10
+ readonly radius: number;
11
+ /** World-space size of the detail this node leaves out; 0 for a leaf (the trained splats). */
12
+ readonly error: number;
13
+ /** Splats in the node's own cloud. Zero denotes a structural node, refined unconditionally without loading. */
14
+ readonly count: number;
15
+ /** Indices of the child nodes; empty for a leaf. */
16
+ readonly children: readonly number[];
17
+ }
18
+ /** A splat hierarchy: node 0 is the root. `load` returns a node's cloud; it may fetch it. */
19
+ export interface SplatLodSource {
20
+ readonly nodes: readonly SplatLodNode[];
21
+ /** Spherical-harmonics coefficients per channel of every node's cloud: 0, 4, 9, 16 or 25. */
22
+ readonly coefficients: number;
23
+ load(index: number, signal: AbortSignal): Promise<SplatData>;
24
+ }
25
+ /** Options of {@link buildSplatLod}. */
26
+ export interface BuildSplatLodOptions {
27
+ /** Most splats in one node, leaf or inner. Default 65,536. */
28
+ leafSize?: number;
29
+ }
30
+ /**
31
+ * Builds an in-memory hierarchy from a capture: an octree of its splat centres split until a cell holds at most
32
+ * `leafSize` splats (leaves keep the splats untouched), and for each inner cell a moment-matched cloud of at most
33
+ * `leafSize` splats from its leaves, with the grid cell it merged as its error. A server can store each node's cloud
34
+ * (for instance with `encodeSplat`) and serve its own `SplatLodSource` with the same nodes.
35
+ * @throws RangeError when `data` is invalid or `leafSize` is under 64.
36
+ */
37
+ export declare function buildSplatLod(data: SplatData, options?: BuildSplatLodOptions): SplatLodSource;
38
+ /** The view a {@link chooseSplatNodes} call refines for. */
39
+ export interface SplatLodView {
40
+ /** Camera position, world units. */
41
+ readonly eye: readonly [number, number, number];
42
+ /** Pixels per world unit at distance 1 (perspective: height / (2 tan(fov / 2))). */
43
+ readonly focal: number;
44
+ /** Nearest distance an error is projected from (the near plane). */
45
+ readonly near: number;
46
+ }
47
+ /**
48
+ * The cut of the tree to draw for `view`: starting at the root, the node with the largest projected error
49
+ * (`error * focal / distance`, in pixels) is replaced by its children while that error exceeds `maxError`, all its
50
+ * children are in `loaded` and the cut stays within `budget` splats. Returns the cut and the nodes to load next (the
51
+ * children that held a refinement back, largest error first).
52
+ */
53
+ export declare function chooseSplatNodes(nodes: readonly SplatLodNode[], view: SplatLodView, options: {
54
+ maxError: number;
55
+ budget: number;
56
+ loaded: (index: number) => boolean;
57
+ maxNodes?: number;
58
+ }): {
59
+ selected: number[];
60
+ wanted: number[];
61
+ };
62
+ /** Options of {@link SplatLod}. */
63
+ export interface SplatLodOptions {
64
+ /**
65
+ * Most splats drawn at once (the GPU pool, rounded down to whole node slots and to no more slots than the source has
66
+ * leaves, the most nodes a cut can hold). Default 1,000,000.
67
+ */
68
+ budget?: number;
69
+ /** Largest projected error left unrefined, in pixels. Default 2. */
70
+ maxError?: number;
71
+ /** Most node loads in flight. Default 4. */
72
+ concurrency?: number;
73
+ /** Most splats of loaded nodes kept on the CPU (drawn ones included). Default twice the budget. */
74
+ cache?: number;
75
+ /** Aborts every load; the hierarchy keeps what it has. */
76
+ signal?: AbortSignal;
77
+ }
78
+ /**
79
+ * A streamed splat hierarchy: `SplatLod.attach(engine, source, options)`. Each frame, before the splats project, the
80
+ * view picks the cut (`chooseSplatNodes`), starts loads for the nodes it lacks, and writes changed nodes into the
81
+ * slots of `cloud`, one `Splats` of `budget` splats that sorts every drawn node together. `attach` attaches `cloud`
82
+ * too. WebGPU only.
83
+ * @throws RangeError for invalid options or a source whose nodes are invalid or larger than the budget; MargoError
84
+ * `'unsupported'` from attach on a WebGL engine.
85
+ */
86
+ export declare class SplatLod implements EnginePlugin {
87
+ private static next;
88
+ readonly name: string;
89
+ /** The cloud every drawn node is written into. */
90
+ readonly cloud: Splats;
91
+ readonly source: SplatLodSource;
92
+ readonly maxError: number;
93
+ private readonly slot;
94
+ private readonly concurrency;
95
+ private readonly cacheSize;
96
+ private readonly abort;
97
+ private readonly loaded;
98
+ private readonly pending;
99
+ private readonly failures;
100
+ private readonly slots;
101
+ private readonly at;
102
+ private cut;
103
+ private used;
104
+ private waiters;
105
+ private disposed;
106
+ private engine?;
107
+ constructor(source: SplatLodSource, options?: SplatLodOptions);
108
+ static attach(engine: EngineKernel, source: SplatLodSource, options?: SplatLodOptions): SplatLod;
109
+ /** The nodes drawn now, in index order. */
110
+ get selected(): readonly number[];
111
+ /** Where each drawn node sits in `cloud`: node index to the pool index of its first splat (for picking or editing). */
112
+ get placement(): ReadonlyMap<number, number>;
113
+ /** Splats drawn now (sum of the selected nodes). */
114
+ get drawn(): number;
115
+ /** Loads in flight. */
116
+ get loading(): number;
117
+ /** Errors of loads that failed (the node stays unloaded and is not asked for again). */
118
+ get errors(): readonly unknown[];
119
+ /** Resolves after the next frame that drew a cut needing no load (the view is fully streamed in). */
120
+ settled(): Promise<void>;
121
+ setup(engine: Engine): void;
122
+ registerPasses(graph: FrameGraph): void;
123
+ private update;
124
+ private request;
125
+ /** Drops loaded nodes that are not drawn, oldest first, while the cache holds more than `cache` splats. */
126
+ private evict;
127
+ dispose(): void;
128
+ [Symbol.dispose]: () => void;
129
+ }
package/dist/lod.js ADDED
@@ -0,0 +1,4 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const r=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{i as e,n as t}from"./data-D31W24Wu.js";import{t as n}from"./src-DlpBlCx1.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as i}from"@margoengine/math/errors";function a(n,r={}){let i=t(n),a=r.leafSize??65536;if(!Number.isInteger(a)||a<64)throw RangeError(`buildSplatLod leafSize must be an integer of 64 or more`);let c=n.sphericalHarmonics?n.sphericalHarmonics.length/i/3:0,l=[],u=[],d=n.positions,f=new Uint32Array(i);for(let e=0;e<i;e++)f[e]=e;let p=(t,r,i,f)=>{let m=l.length;l.push(void 0),u.push(void 0);let h=[];if(t.length>a&&f<21){let e=i/2,n=new Uint8Array(t.length),a=/* @__PURE__ */ new Uint32Array(8);t.forEach((t,i)=>{let o=0;for(let n=0;n<3;n++)d[t*3+n]>=r[n]+e&&(o|=1<<n);n[i]=o,a[o]++});for(let i=0;i<8;i++){if(!a[i])continue;let o=new Uint32Array(a[i]),s=0;t.forEach((e,t)=>{n[t]===i&&(o[s++]=e)}),h.push(p(o,[0,1,2].map(t=>r[t]+(i>>t&1)*e),e,f+1))}h.length===1&&l[h[0]].children.length===0&&f>=20&&(h=[])}let g=o(n,t,c),_=g,v=0;if(h.length)for(let t=i/64;_=e(g,{cellSize:t}),v=t,!(_.positions.length/3<=a);t*=2);let y=s(_.positions,h.map(e=>l[e]));return l[m]={center:y.center,radius:y.radius,error:v,count:_.positions.length/3,children:h},u[m]=_,m},m=[1/0,1/0,1/0],h=[-1/0,-1/0,-1/0];for(let e=0;e<i;e++)for(let t=0;t<3;t++)m[t]=Math.min(m[t],d[e*3+t]),h[t]=Math.max(h[t],d[e*3+t]);return p(f,m,Math.max(h[0]-m[0],h[1]-m[1],h[2]-m[2])*(1+1e-6)||1,0),{nodes:l,coefficients:c,load:(e,t)=>t.aborted?Promise.reject(t.reason):u[e]?Promise.resolve(u[e]):Promise.reject(/* @__PURE__ */ RangeError(`No splat node ${e}`))}}function o(e,t,n){let r=t.length,i=new Float32Array(r*3),a=new Float32Array(r*6),o=new Float32Array(r*4),s=n?new Float32Array(r*n*3):void 0,c=n*3;return t.forEach((t,n)=>{i.set(e.positions.subarray(t*3,t*3+3),n*3),a.set(e.covariances.subarray(t*6,t*6+6),n*6),o.set(e.colors.subarray(t*4,t*4+4),n*4),s&&s.set(e.sphericalHarmonics.subarray(t*c,t*c+c),n*c)}),{positions:i,covariances:a,colors:o,...s?{sphericalHarmonics:s}:{}}}function s(e,t){let n=[1/0,1/0,1/0],r=[-1/0,-1/0,-1/0];for(let t=0;t<e.length;t+=3)for(let i=0;i<3;i++)n[i]=Math.min(n[i],e[t+i]),r[i]=Math.max(r[i],e[t+i]);for(let e of t)for(let t=0;t<3;t++)n[t]=Math.min(n[t],e.center[t]-e.radius),r[t]=Math.max(r[t],e.center[t]+e.radius);let i=[0,1,2].map(e=>(n[e]+r[e])/2),a=0;for(let t=0;t<e.length;t+=3)a=Math.max(a,(e[t]-i[0])**2+(e[t+1]-i[1])**2+(e[t+2]-i[2])**2);let o=Math.sqrt(a);for(let e of t)o=Math.max(o,Math.hypot(e.center[0]-i[0],e.center[1]-i[1],e.center[2]-i[2])+e.radius);return{center:i,radius:o}}function c(e,t,n){let r=[];if(!e.length)return{selected:[],wanted:r};if(!n.loaded(0))return{selected:[],wanted:[0]};let i=n=>{let r=e[n];if(!r.children.length)return 0;if(!r.count)return 1/0;let i=Math.hypot(r.center[0]-t.eye[0],r.center[1]-t.eye[1],r.center[2]-t.eye[2])-r.radius;return r.error*t.focal/Math.max(i,t.near)},a=[[i(0),0]],o=[],s=e[0].count,c=+(e[0].count>0);for(;a.length;){a.sort((e,t)=>t[0]-e[0]||e[1]-t[1]);let[t,l]=a.shift(),u=e[l];if(t<=n.maxError){o.push(l,...a.map(e=>e[1]));break}let d=u.children.filter(e=>!n.loaded(e)),f=s-u.count+u.children.reduce((t,n)=>t+e[n].count,0),p=c-+(u.count>0)+u.children.filter(t=>e[t].count>0).length;if(d.length||f>n.budget||p>(n.maxNodes??1/0))d.length&&f<=n.budget&&p<=(n.maxNodes??1/0)&&r.push(...d),o.push(l);else{s=f,c=p;for(let e of u.children)a.push([i(e),e])}}return{selected:o.sort((e,t)=>e-t),wanted:r}}var l=class e{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);static{this.next=0}constructor(t,r={}){this.name=`splats-lod:`+e.next++,this.abort=new AbortController,this.loaded=/* @__PURE__ */ new Map,this.pending=/* @__PURE__ */ new Set,this.failures=[],this.at=/* @__PURE__ */ new Map,this.cut=[],this.used=0,this.waiters=[],this.disposed=!1;let i=t?.nodes;if(!Array.isArray(i)||!i.length||typeof t.load!=`function`)throw TypeError(`SplatLod needs a source with nodes and load(index, signal)`);if(![0,4,9,16,25].includes(t.coefficients))throw RangeError(`SplatLod source coefficients must be 0, 4, 9, 16 or 25`);let a=r.budget??1e6;this.maxError=r.maxError??2,this.concurrency=r.concurrency??4;for(let[e,t,n]of[[`budget`,a,1],[`maxError`,this.maxError,0],[`concurrency`,this.concurrency,1]])if(!(t>=n)||!Number.isFinite(t))throw RangeError(`SplatLod ${e} must be ${n} or more`);let o=0;if(i.forEach((e,t)=>{if(!(e.count>=0)||!e.count&&!e.children.length||!Number.isInteger(e.count)||!(e.radius>=0)||!(e.error>=0)||e.children.some(e=>!(e>t&&e<i.length)))throw RangeError(`SplatLod node ${t} is invalid (count, radius, error, or a child that is not a later node); give each node a count of 1 or more and only later children`);o=Math.max(o,e.count)}),o>a)throw RangeError(`SplatLod budget ${a} is under the largest node, ${o} splats; raise the budget or split the node`);this.source=t,this.slot=o;let s=i.filter(e=>!e.children.length).length;this.slots=Array(Math.min(Math.floor(a/o),s)).fill(void 0);let c=e=>i[e].count?1:i[e].children.reduce((e,t)=>e+c(t),0);if(c(0)>this.slots.length)throw RangeError(`SplatLod budget needs at least ${c(0)*o} splats to cover all structural branches; raise budget`);this.cacheSize=r.cache??this.slots.length*o*2,this.cloud=n.reserve(this.slots.length*o,t.coefficients),r.signal?.addEventListener(`abort`,()=>this.abort.abort(r.signal.reason),{once:!0})}static attach(t,n,i={}){__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));let a=new e(n,i),o=r(t);return o.use(a.cloud),o.use(a),a}get selected(){return this.cut}get placement(){let e=/* @__PURE__ */ new Map;for(let[t,n]of this.at)e.set(t,n*this.slot);return e}get drawn(){return this.used}get loading(){return this.pending.size}get errors(){return this.failures}settled(){return new Promise(e=>this.waiters.push(e))}setup(e){if(this.disposed||!e.gpu)throw new i(this.disposed?`disposed`:`unsupported`,`SplatLod needs WebGPU and a live hierarchy; attach a new SplatLod to a WebGPU engine; see https://margoengine.com/errors#webgpu`);this.engine=e}registerPasses(e){e.add({name:this.name,order:-8,execute:e=>{e.backend===`webgpu`&&this.update(e)}})}update(e){let t=e.height/(2*Math.tan(e.camera.fov*Math.PI/360)),n={eye:e.camera.position,focal:t,near:e.camera.near},{selected:r,wanted:i}=c(this.source.nodes,n,{maxError:this.maxError,budget:this.slots.length*this.slot,loaded:e=>this.loaded.has(e),maxNodes:this.slots.length});for(let e of i)this.request(e);let a=new Set(r);for(let e of this.cut)if(!a.has(e)&&this.source.nodes[e].count){let t=this.at.get(e);this.cloud.clear(t*this.slot,this.slot),this.slots[t]=void 0,this.at.delete(e)}for(let e of r)if(this.source.nodes[e].count&&!this.at.has(e)){let t=this.slots.indexOf(void 0);this.slots[t]=e,this.at.set(e,t),this.cloud.clear(t*this.slot,this.slot),this.source.nodes[e].count&&this.cloud.write(t*this.slot,this.loaded.get(e))}if(this.cut=r,this.used=r.reduce((e,t)=>e+this.source.nodes[t].count,0),this.evict(a),!i.length&&!this.pending.size&&this.waiters.length){let e=this.waiters;this.waiters=[];for(let t of e)t()}}request(e){this.source.nodes[e].count?this.pending.has(e)||this.pending.size>=this.concurrency||this.abort.signal.aborted||this.failures.some(t=>t.node===e)||(this.pending.add(e),this.source.load(e,this.abort.signal).then(n=>{if(this.pending.delete(e),this.disposed)return;let r=t(n),i=n.sphericalHarmonics?n.sphericalHarmonics.length/r/3:0;r!==this.source.nodes[e].count||i!==this.source.coefficients?this.failures.push(Object.assign(/* @__PURE__ */ RangeError(`Splat node ${e} loaded ${r} splats with ${i} SH coefficients, not ${this.source.nodes[e].count} with ${this.source.coefficients}`),{node:e})):this.loaded.set(e,n)},t=>{this.pending.delete(e),this.abort.signal.aborted||this.failures.push(Object.assign(t instanceof Error?t:Error(String(t)),{node:e}))})):this.loaded.set(e,{positions:/* @__PURE__ */ new Float32Array,covariances:/* @__PURE__ */ new Float32Array,colors:/* @__PURE__ */ new Float32Array})}evict(e){let t=0;for(let e of this.loaded.keys())t+=this.source.nodes[e].count;for(let n of[...this.loaded.keys()]){if(t<=this.cacheSize)break;e.has(n)||n===0||(this.loaded.delete(n),t-=this.source.nodes[n].count)}}dispose(){if(!this.disposed){this.disposed=!0,this.abort.abort(new i(`disposed`,`The SplatLod was disposed`)),this.engine?.sceneOf(this)?.removePlugin(this.name),this.engine=void 0,this.cloud.dispose(),this.loaded.clear();for(let e of this.waiters)e();this.waiters=[]}}[Symbol.dispose??Symbol()](){this.dispose()}};export{l as SplatLod,a as buildSplatLod,c as chooseSplatNodes};
@@ -0,0 +1,83 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin, type FrameGraph } from '@margoengine/core/extension';
4
+ import { type SplatData } from './data.js';
5
+ import type { Splats } from './index.js';
6
+ /** WGSL function bodies of a per-frame splat modifier. All hooks can read time, delta and u.parameters[0..15]. */
7
+ export interface SplatModifierOptions {
8
+ /** WGSL body returning vec3f; arguments index:u32 and position:vec3f (canonical centre). Default return position. */
9
+ position?: string;
10
+ /** WGSL body returning f32; arguments index:u32, position:vec3f (modified) and opacity:f32 (canonical). Default return opacity. */
11
+ opacity?: string;
12
+ /** WGSL body returning vec3f; arguments index:u32, position:vec3f (modified) and color:vec3f (evaluated linear SH/fog). Default return color. */
13
+ color?: string;
14
+ /** Shared WGSL functions/constants, appended to both modules. Default empty. */
15
+ declarations?: string;
16
+ /** Initial values of the 64 live parameter floats. Default all zero; remaining floats are zero. */
17
+ parameters?: ArrayLike<number>;
18
+ /** Cancels creation and disposes the modifier when aborted. */
19
+ signal?: AbortSignal;
20
+ }
21
+ /** Builds the pre-projection position/opacity and post-projection colour compute modules. */
22
+ export declare function splatModifierShaders(options?: SplatModifierOptions): {
23
+ position: string;
24
+ color: string;
25
+ };
26
+ /**
27
+ * A GPU modifier with independent position, opacity and evaluated-colour hooks. Create/attach asynchronously to
28
+ * snapshot canonical centres and opacity once. Geometry runs before projection/sorting; colour runs after SH/fog
29
+ * and before relighting. Source colours, SH and covariances are preserved. Each frame starts at the canonical data.
30
+ */
31
+ export declare class SplatModifier implements EnginePlugin {
32
+ private static next;
33
+ readonly name: string;
34
+ readonly cloud: Splats;
35
+ /** 64 live floats, exposed to WGSL as u.parameters:array<vec4f,16>. */
36
+ readonly parameters: Float32Array<ArrayBuffer>;
37
+ /** Effect clock in seconds; manually seek while playing is false. Default 0. */
38
+ time: number;
39
+ /** Advance time once per frame. Default true. */
40
+ playing: boolean;
41
+ /** Clock multiplier, including negative playback. Default 1. */
42
+ speed: number;
43
+ /** False restores canonical geometry and skips colour modification. Default true. */
44
+ enabled: boolean;
45
+ private readonly canonical;
46
+ private readonly shaders;
47
+ private readonly values;
48
+ private readonly integers;
49
+ private engine?;
50
+ private device?;
51
+ private uniform?;
52
+ private rest?;
53
+ private pipelines;
54
+ private groups;
55
+ private bound?;
56
+ private evaluated?;
57
+ private dead;
58
+ private readonly signal?;
59
+ private readonly abort?;
60
+ private constructor();
61
+ /** Snapshots a cloud's current GPU/CPU data once, with caller cancellation; returns an unattached plugin. */
62
+ static create(cloud: Splats, options?: SplatModifierOptions): Promise<SplatModifier>;
63
+ /** Creates the canonical snapshot, then attaches the modifier to engine. */
64
+ static attach(engine: EngineKernel, cloud: Splats, options?: SplatModifierOptions): Promise<SplatModifier>;
65
+ /** Replaces canonical centres/opacity from a complete cloud of the same count. Other attributes remain the cloud's. */
66
+ setRest(data: SplatData): this;
67
+ setup(engine: Engine): void;
68
+ registerPasses(graph: FrameGraph): void;
69
+ private run;
70
+ /** True after disposal. */
71
+ get disposed(): boolean;
72
+ private release;
73
+ /**
74
+ * Moves `time` by `delta` seconds times `speed` while `playing`, without drawing (a delta of 0 or less moves
75
+ * nothing). Each frame update runs it, so `seek` from `@margoengine/cutscene/seek` replays it exactly.
76
+ */
77
+ advanceTime(delta: number): void;
78
+ onPreUpdate(delta: number): void;
79
+ onDeviceRestored(engine: Engine): void;
80
+ /** Restores canonical centres/opacity, removes the passes and releases GPU buffers. Idempotent. */
81
+ dispose(): void;
82
+ [Symbol.dispose]: () => void;
83
+ }