@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,94 @@
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
+ /**
7
+ * A brush region in pixels of the frame the cloud last drew (`SplatBrush.frame`), from its top-left corner: a circle
8
+ * (`x`, `y`, `radius`) or a rectangle (`x`, `y`, `width`, `height`). A splat is in the region when its projected
9
+ * centre is, and it was drawn in that frame.
10
+ */
11
+ export type BrushRegion = {
12
+ x: number;
13
+ y: number;
14
+ radius: number;
15
+ } | {
16
+ x: number;
17
+ y: number;
18
+ width: number;
19
+ height: number;
20
+ };
21
+ /** How `select` combines a region with the current selection. */
22
+ export type SelectMode = 'replace' | 'add' | 'subtract';
23
+ /** What `erase` and `paint` change: the splats in a region, the selected splats, or every splat. */
24
+ export type BrushTarget = BrushRegion | 'selection' | 'all';
25
+ /**
26
+ * WGSL of the brush, one entry point for every operation. Uniform: view matrix, region (circle x, y, radius or rect
27
+ * x0, y0, x1, y1, pixels), colour (rgb, a strength), params (x pick threshold, y and z frame size), counts (x splats,
28
+ * y operation: 0 to 2 select replace, add, subtract, 3 erase, 4 paint, 5 and 6 the two pick passes; z target: 0 circle,
29
+ * 1 rect, 2 selection, 3 all; w SH coefficients per channel).
30
+ */
31
+ export declare const brushShader = "struct Brush {view:mat4x4f,region:vec4f,color:vec4f,params:vec4f,counts:vec4u}\nstruct Ellipse {center:vec4f,axes:vec4f}\n@group(0) @binding(0) var<uniform> u:Brush;\n@group(0) @binding(1) var<storage,read> ellipses:array<Ellipse>;\n@group(0) @binding(2) var<storage,read_write> positions:array<vec4f>;\n@group(0) @binding(3) var<storage,read_write> colors:array<vec4f>;\n@group(0) @binding(4) var<storage,read_write> sh:array<f32>;\n@group(0) @binding(5) var<storage,read_write> mask:array<u32>;\n@group(0) @binding(6) var<storage,read_write> result:array<atomic<u32>,2>;\nfn drawn(i:u32)->bool {let e=ellipses[i];return positions[i].w>0&&e.center.w>0&&any(e.axes!=vec4f(0));}\nfn inside(i:u32)->bool {\n let t=u.counts.z;if(t==3u){return true;}if(t==2u){return mask[i]!=0u;}if(!drawn(i)){return false;}\n let c=ellipses[i].center;let p=vec2f((c.x+1)*0.5*u.params.y,(1-c.y)*0.5*u.params.z);\n if(t==0u){let d=p-u.region.xy;return dot(d,d)<=u.region.z*u.region.z;}return all(p>=u.region.xy)&&all(p<=u.region.zw);\n}\n@compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u) {\n let i=id.x;if(i>=u.counts.x){return;}let op=u.counts.y;\n if(op<=2u){let hit=inside(i);if(op==0u){mask[i]=u32(hit);}else if(hit){mask[i]=u32(op==1u);}return;}\n if(op==3u){if(inside(i)){positions[i].w=0;colors[i].a=0;}return;}\n if(op==4u){\n if(positions[i].w<=0||!inside(i)){return;}let s=u.color.a;let c=colors[i];colors[i]=vec4f(mix(c.rgb,u.color.rgb,s),c.a);\n let k=u.counts.w;if(k==0u){return;}let at=i*k*3;let dc=vec3f(sh[at],sh[at+1],sh[at+2]);\n let n=(mix(vec3f(0.5)+0.2820947918*dc,u.color.rgb,s)-vec3f(0.5))/0.2820947918;sh[at]=n.x;sh[at+1]=n.y;sh[at+2]=n.z;\n for(var j=3u;j<k*3u;j++){sh[at+j]*=1-s;}return;\n }\n if(!drawn(i)){return;}let e=ellipses[i];\n let d=vec2f(2*(u.region.x+0.5)/u.params.y-1,1-2*(u.region.y+0.5)/u.params.z)-e.center.xy;\n let a=dot(d,e.axes.xy)/dot(e.axes.xy,e.axes.xy);let b=dot(d,e.axes.zw)/dot(e.axes.zw,e.axes.zw);let power=-4.5*(a*a+b*b);\n if(power<-4.5||min(0.99,e.center.w*exp(power))<u.params.x){return;}\n\n let bits=bitcast<u32>(-(u.view*vec4f(positions[i].xyz,1)).z);let key=select(bits^0x80000000u,~bits,(bits>>31u)==1u);\n if(op==5u){atomicMin(&result[0],key);}else if(key==atomicLoad(&result[0])){atomicMin(&result[1],i);}\n}";
32
+ /**
33
+ * GPU picking and brush editing of a splat cloud: `const brush = SplatBrush.attach(engine, cloud)`, then
34
+ * `await brush.pick(x, y)`, `brush.select(region)`, `brush.erase('selection')` or `brush.paint(region, [1, 0, 0])`
35
+ * in pixels of the last drawn frame. Edits change the cloud's GPU buffers at once (shown from the next frame);
36
+ * `await brush.commit()` copies them into the cloud's data (`Splats.read`), which export and device restoration use.
37
+ * WebGPU only, as `Splats`.
38
+ * @throws TypeError when `cloud` is not a Splats; MargoError `'unsupported'` on a WebGL engine, `'disposed'` after
39
+ * `dispose()`, `'state'` before the cloud has drawn a frame.
40
+ */
41
+ export declare class SplatBrush implements EnginePlugin {
42
+ private static next;
43
+ readonly name: string;
44
+ readonly cloud: Splats;
45
+ private engine?;
46
+ private device?;
47
+ private width;
48
+ private height;
49
+ private readonly data;
50
+ private readonly integers;
51
+ private uniform?;
52
+ private result?;
53
+ private mask?;
54
+ private pipeline?;
55
+ private group?;
56
+ private dead;
57
+ constructor(cloud: Splats);
58
+ /** Same as `engine.use(new SplatBrush(cloud))`; returns it. */
59
+ static attach(engine: EngineKernel, cloud: Splats): SplatBrush;
60
+ /** Width and height in pixels of the frame the cloud last drew, the space of every region and pick; 0 before. */
61
+ get frame(): [number, number];
62
+ setup(engine: Engine): void;
63
+ registerPasses(graph: FrameGraph): void;
64
+ /**
65
+ * The index of the nearest splat drawn at pixel (`x`, `y`) whose own opacity there (its Gaussian falloff times its
66
+ * opacity) reaches `threshold`, or -1 when none does.
67
+ * @throws RangeError for a threshold outside 0 to 1 or a non-finite pixel.
68
+ */
69
+ pick(x: number, y: number, threshold?: number): Promise<number>;
70
+ /**
71
+ * Selects the splats in `region` ('all' for every splat, 'none' for none), replacing the selection, adding to it or
72
+ * taking from it.
73
+ * @throws RangeError for an invalid region or mode.
74
+ */
75
+ select(region: BrushRegion | 'all' | 'none', mode?: SelectMode): this;
76
+ /** The indices of the selected splats, in order. */
77
+ selection(): Promise<Uint32Array>;
78
+ /** Hides the target's splats (opacity 0), as `Splats.clear` does. The selection is kept. */
79
+ erase(target?: BrushTarget): this;
80
+ /**
81
+ * Blends the target's colour toward `color` (linear RGB, each 0 to 1) by `strength` (0 to 1); opacity is kept.
82
+ * @throws RangeError for a colour or strength outside 0 to 1.
83
+ */
84
+ paint(target: BrushTarget, color: ArrayLike<number>, strength?: number): this;
85
+ /** Copies the GPU edits into the cloud's data and returns it: `cloud.read()`. */
86
+ commit(): Promise<SplatData>;
87
+ /** Checks the state and writes the region, ready for a dispatch; returns the device. */
88
+ private ready;
89
+ private submit;
90
+ private run;
91
+ onDeviceRestored(engine: Engine): void;
92
+ dispose(): void;
93
+ [Symbol.dispose]: () => void;
94
+ }
package/dist/brush.js ADDED
@@ -0,0 +1,36 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const t=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{t as e}from"./view-DyJeX8rJ.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as n}from"@margoengine/math/errors";var r=`struct Brush {view:mat4x4f,region:vec4f,color:vec4f,params:vec4f,counts:vec4u}
5
+ struct Ellipse {center:vec4f,axes:vec4f}
6
+ @group(0) @binding(0) var<uniform> u:Brush;
7
+ @group(0) @binding(1) var<storage,read> ellipses:array<Ellipse>;
8
+ @group(0) @binding(2) var<storage,read_write> positions:array<vec4f>;
9
+ @group(0) @binding(3) var<storage,read_write> colors:array<vec4f>;
10
+ @group(0) @binding(4) var<storage,read_write> sh:array<f32>;
11
+ @group(0) @binding(5) var<storage,read_write> mask:array<u32>;
12
+ @group(0) @binding(6) var<storage,read_write> result:array<atomic<u32>,2>;
13
+ fn drawn(i:u32)->bool {let e=ellipses[i];return positions[i].w>0&&e.center.w>0&&any(e.axes!=vec4f(0));}
14
+ fn inside(i:u32)->bool {
15
+ let t=u.counts.z;if(t==3u){return true;}if(t==2u){return mask[i]!=0u;}if(!drawn(i)){return false;}
16
+ let c=ellipses[i].center;let p=vec2f((c.x+1)*0.5*u.params.y,(1-c.y)*0.5*u.params.z);
17
+ if(t==0u){let d=p-u.region.xy;return dot(d,d)<=u.region.z*u.region.z;}return all(p>=u.region.xy)&&all(p<=u.region.zw);
18
+ }
19
+ @compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u) {
20
+ let i=id.x;if(i>=u.counts.x){return;}let op=u.counts.y;
21
+ if(op<=2u){let hit=inside(i);if(op==0u){mask[i]=u32(hit);}else if(hit){mask[i]=u32(op==1u);}return;}
22
+ if(op==3u){if(inside(i)){positions[i].w=0;colors[i].a=0;}return;}
23
+ if(op==4u){
24
+ if(positions[i].w<=0||!inside(i)){return;}let s=u.color.a;let c=colors[i];colors[i]=vec4f(mix(c.rgb,u.color.rgb,s),c.a);
25
+ let k=u.counts.w;if(k==0u){return;}let at=i*k*3;let dc=vec3f(sh[at],sh[at+1],sh[at+2]);
26
+ let n=(mix(vec3f(0.5)+0.2820947918*dc,u.color.rgb,s)-vec3f(0.5))/0.2820947918;sh[at]=n.x;sh[at+1]=n.y;sh[at+2]=n.z;
27
+ for(var j=3u;j<k*3u;j++){sh[at+j]*=1-s;}return;
28
+ }
29
+ if(!drawn(i)){return;}let e=ellipses[i];
30
+ let d=vec2f(2*(u.region.x+0.5)/u.params.y-1,1-2*(u.region.y+0.5)/u.params.z)-e.center.xy;
31
+ let a=dot(d,e.axes.xy)/dot(e.axes.xy,e.axes.xy);let b=dot(d,e.axes.zw)/dot(e.axes.zw,e.axes.zw);let power=-4.5*(a*a+b*b);
32
+ if(power<-4.5||min(0.99,e.center.w*exp(power))<u.params.x){return;}
33
+
34
+ let bits=bitcast<u32>(-(u.view*vec4f(positions[i].xyz,1)).z);let key=select(bits^0x80000000u,~bits,(bits>>31u)==1u);
35
+ if(op==5u){atomicMin(&result[0],key);}else if(key==atomicLoad(&result[0])){atomicMin(&result[1],i);}
36
+ }`,i={circle:0,rect:1,selection:2,all:3},a=class a{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);static{this.next=0}constructor(e){if(this.name=`splats-brush:`+a.next++,this.width=0,this.height=0,this.data=/* @__PURE__ */ new Float32Array(32),this.integers=new Uint32Array(this.data.buffer),this.dead=!1,!e||typeof e!=`object`||!(`gpuState`in e))throw TypeError(`SplatBrush needs a Splats cloud`);this.cloud=e}static attach(e,n){__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));let r=new a(n);return t(e).use(r),r}get frame(){return[this.width,this.height]}setup(e){if(this.dead||!e.gpu)throw new n(this.dead?`disposed`:`unsupported`,`SplatBrush needs WebGPU; attach a new SplatBrush to a WebGPU engine; see https://margoengine.com/errors#webgpu`);this.engine=e,this.device=e.gpu,this.uniform=e.gpu.createBuffer({size:128,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.result=e.gpu.createBuffer({size:8,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST})}registerPasses(t){t.add({name:this.name,order:-6.9,execute:t=>{t.backend===`webgpu`&&this.cloud.attached&&(this.width=t.width,this.height=t.height,e(this.data.subarray(0,16),t.camera))}})}async pick(e,t,n=.1){if(!(n>=0&&n<=1))throw RangeError(`SplatBrush.pick threshold must be 0 to 1`);let r=this.ready({x:e,y:t,radius:0}),i=r.createBuffer({size:8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST});this.data[24]=n,r.queue.writeBuffer(this.result,0,new Uint32Array([4294967295,4294967295])),this.submit(5,{x:e,y:t,radius:0});let a=r.createCommandEncoder();this.run(a,6),a.copyBufferToBuffer(this.result,0,i,0,8),r.queue.submit([a.finish()]);try{await i.mapAsync(GPUMapMode.READ);let e=new Uint32Array(i.getMappedRange())[1];return e===4294967295?-1:e}finally{i.destroy()}}select(e,t=`replace`){let n=[`replace`,`add`,`subtract`].indexOf(t);if(n<0)throw RangeError(`SplatBrush.select mode must be 'replace', 'add' or 'subtract'`);return e===`none`?t===`replace`?this.submit(2,`all`):this:this.submit(n,e)}async selection(){let e=this.ready(`all`),t=this.cloud.count*4,n=e.createBuffer({size:t,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),r=e.createCommandEncoder();r.copyBufferToBuffer(this.mask,0,n,0,t),e.queue.submit([r.finish()]);try{await n.mapAsync(GPUMapMode.READ);let e=new Uint32Array(n.getMappedRange()),t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(n);return Uint32Array.from(t)}finally{n.destroy()}}erase(e=`selection`){return this.submit(3,e)}paint(e,t,n=1){if(t?.length!==3||![...Array.from(t),n].every(e=>e>=0&&e<=1))throw RangeError(`SplatBrush.paint needs an RGB colour and a strength, each 0 to 1`);return this.data.set([t[0],t[1],t[2],n],20),this.submit(4,e)}commit(){return this.cloud.read()}ready(e){if(this.dead||!this.device)throw new n(`disposed`,`SplatBrush is disposed or not attached; attach a new one`);if(!this.width||!this.cloud.attached)throw new n(`state`,`SplatBrush works on a drawn frame; render the engine once before editing`);let t=this.device,a=this.cloud.gpuState,o=this.data,s;if(typeof e==`string`)s=i[e];else{let t=`radius`in e,n=t?[e.x,e.y,e.radius]:[e.x,e.y,e.width,e.height];if(!n.every(Number.isFinite)||n.slice(2).some(e=>e<0))throw RangeError(`A brush region needs finite x and y and a radius, or a width and height, of 0 or more`);s=+!t,o.set(t?[e.x,e.y,e.radius,0]:[e.x,e.y,e.x+n[2],e.y+n[3]],16)}if(s===void 0)throw RangeError(`A brush target must be a region, 'selection' or 'all'`);return o[25]=this.width,o[26]=this.height,this.integers[28]=this.cloud.count,this.integers[30]=s,this.integers[31]=this.cloud.coefficients,(!this.group||this.group.ellipses!==a.ellipses)&&(this.mask?.destroy(),this.mask=t.createBuffer({size:this.cloud.count*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),this.pipeline??=t.createComputePipeline({layout:`auto`,compute:{module:t.createShaderModule({code:r}),entryPoint:`main`}}),this.group={group:t.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[this.uniform,a.ellipses,a.positions,a.inputColors,a.sh,this.mask,this.result].map((e,t)=>({binding:t,resource:{buffer:e}}))}),ellipses:a.ellipses}),t}submit(e,t){let n=this.ready(t),r=n.createCommandEncoder();return this.run(r,e),n.queue.submit([r.finish()]),this}run(e,t){this.integers[29]=t,this.device.queue.writeBuffer(this.uniform,0,this.data);let n=e.beginComputePass();n.setPipeline(this.pipeline),n.setBindGroup(0,this.group.group),n.dispatchWorkgroups(Math.ceil(this.cloud.count/256)),n.end()}onDeviceRestored(e){this.mask?.destroy(),this.mask=this.pipeline=this.group=void 0,this.width=0,this.setup(e)}dispose(){if(!this.dead){this.dead=!0,this.engine?.sceneOf(this)?.removePlugin(this.name);for(let e of[this.uniform,this.result,this.mask])e?.destroy();this.uniform=this.result=this.mask=this.pipeline=this.group=this.device=this.engine=void 0}}[Symbol.dispose??Symbol()](){this.dispose()}};export{a as SplatBrush,r as brushShader};
@@ -0,0 +1,19 @@
1
+ var e=`struct Sort {count:u32,groups:u32,blocks:u32,shift:u32}
2
+ @group(0) @binding(0) var<uniform> sort:Sort;
3
+ @group(0) @binding(1) var<storage,read_write> keys:array<vec2u>;
4
+ @group(0) @binding(2) var<storage,read_write> spare:array<vec2u>;
5
+ @compute @workgroup_size(1) fn main() {
6
+ var at:array<u32,256>;
7
+ for(var p=0u;p<4u;p++){
8
+ let shift=p*8u;let even=p%2u==0u;
9
+ for(var d=0u;d<256u;d++){at[d]=0u;}
10
+ for(var i=0u;i<sort.count;i++){
11
+ var key=0u;if(even){key=keys[i].x;}else{key=spare[i].x;}at[(key>>shift)&255u]+=1u;
12
+ }
13
+ var sum=0u;for(var d=0u;d<256u;d++){let n=at[d];at[d]=sum;sum+=n;}
14
+ for(var i=0u;i<sort.count;i++){
15
+ if(even){let k=keys[i];let d=(k.x>>shift)&255u;spare[at[d]]=k;at[d]+=1u;}
16
+ else{let k=spare[i];let d=(k.x>>shift)&255u;keys[at[d]]=k;at[d]+=1u;}
17
+ }
18
+ }
19
+ }`;function t(t,n,r){let i=t.createComputePipeline({layout:`auto`,compute:{module:t.createShaderModule({code:e}),entryPoint:`main`}});return{pipeline:i,group:t.createBindGroup({layout:i.getBindGroupLayout(0),entries:[n,r[0],r[1]].map((e,t)=>({binding:t,resource:{buffer:e}}))})}}export{e as cpuSort,t as splatCompatSort};
@@ -0,0 +1,7 @@
1
+ /** One invocation: `keys` sorted by `.x`, stable, through `spare`; the result ends in `keys`, as on WebGPU. */
2
+ export declare const cpuSort = "struct Sort {count:u32,groups:u32,blocks:u32,shift:u32}\n@group(0) @binding(0) var<uniform> sort:Sort;\n@group(0) @binding(1) var<storage,read_write> keys:array<vec2u>;\n@group(0) @binding(2) var<storage,read_write> spare:array<vec2u>;\n@compute @workgroup_size(1) fn main() {\n var at:array<u32,256>;\n for(var p=0u;p<4u;p++){\n let shift=p*8u;let even=p%2u==0u;\n for(var d=0u;d<256u;d++){at[d]=0u;}\n for(var i=0u;i<sort.count;i++){\n var key=0u;if(even){key=keys[i].x;}else{key=spare[i].x;}at[(key>>shift)&255u]+=1u;\n }\n var sum=0u;for(var d=0u;d<256u;d++){let n=at[d];at[d]=sum;sum+=n;}\n for(var i=0u;i<sort.count;i++){\n if(even){let k=keys[i];let d=(k.x>>shift)&255u;spare[at[d]]=k;at[d]+=1u;}\n else{let k=spare[i];let d=(k.x>>shift)&255u;keys[at[d]]=k;at[d]+=1u;}\n }\n }\n}";
3
+ /** The sort pipeline and its bind group: `sort` holds the splat count first, `keys` the projected keys and a spare. */
4
+ export declare function splatCompatSort(device: GPUDevice, sort: GPUBuffer, keys: readonly GPUBuffer[]): {
5
+ pipeline: GPUComputePipeline;
6
+ group: GPUBindGroup;
7
+ };
@@ -0,0 +1,40 @@
1
+ import type { SplatData } from './data.js';
2
+ import type { ParseSogOptions, SogFiles } from './sog.js';
3
+ import type { ParseSpzOptions } from './spz.js';
4
+ import type { EncodeSpzOptions } from './encode.js';
5
+ /**
6
+ * Decodes an SPZ file (versions 2, 3 and 4) to {@link SplatData}. Loads the decoder on first use (the Zstandard
7
+ * decoder only when a version 4 file is read).
8
+ * @throws TypeError when `input` is not bytes; RangeError for a damaged file or unknown version; MargoError
9
+ * `unsupported` for a version 4 stream that needs a Zstandard dictionary.
10
+ * @example
11
+ * const splats = await parseSpz(await (await fetch('scene.spz')).arrayBuffer());
12
+ */
13
+ export declare function parseSpz(input: ArrayBuffer | ArrayBufferView, options?: ParseSpzOptions): Promise<SplatData>;
14
+ /**
15
+ * Decodes a SOG scene (version 2, bundled `.sog` or loose files) to {@link SplatData}. Loads the decoder on first use.
16
+ * @throws TypeError when `input` is not bytes or a file map; RangeError for a damaged archive, texture or `meta.json`;
17
+ * MargoError `unsupported` for lossy textures or ZIP64.
18
+ * @example
19
+ * const splats = await parseSog(await (await fetch('scene.sog')).arrayBuffer());
20
+ */
21
+ export declare function parseSog(input: ArrayBuffer | ArrayBufferView | SogFiles, options?: ParseSogOptions): Promise<SplatData>;
22
+ /**
23
+ * Encodes a cloud as an SPZ file (version 3, gzip), which `parseSpz` and SPZ readers decode. Loads the writer on
24
+ * first use. Positions are 24-bit fixed point, opacity, colour and log scale one byte each, rotations the
25
+ * smallest-three 10-bit packing, spherical harmonics one byte per coefficient.
26
+ * @throws RangeError when `data` fails `validateSplats` or a coordinate does not fit the fixed point; MargoError
27
+ * `unsupported` without `CompressionStream`.
28
+ * @example
29
+ * const bytes = await encodeSpz(parsePly(await (await fetch('scene.ply')).arrayBuffer()));
30
+ */
31
+ export declare function encodeSpz(data: SplatData, options?: EncodeSpzOptions): Promise<Uint8Array<ArrayBuffer>>;
32
+ /**
33
+ * Encodes a cloud as a bundled SOG scene (version 2: a ZIP of `meta.json` and lossless WebP textures), which
34
+ * `parseSog` and SOG version 2 readers decode. Loads the writer on first use.
35
+ * @throws RangeError when `data` fails `validateSplats`.
36
+ * @example
37
+ * const bytes = await encodeSog(parsePly(await (await fetch('scene.ply')).arrayBuffer()));
38
+ */
39
+ export declare function encodeSog(data: SplatData): Promise<Uint8Array<ArrayBuffer>>;
40
+ export type { EncodeSpzOptions, ParseSogOptions, ParseSpzOptions, SogFiles };
@@ -0,0 +1,2 @@
1
+ import{SRGBToLinear as e}from"@margoengine/math/color";import{MargoError as t}from"@margoengine/math/errors";var n=Object.defineProperty,r=(e,t)=>{let r={};for(var i in e)n(r,i,{get:e[i],enumerable:!0});return t||n(r,Symbol.toStringTag,{value:`Module`}),r},i=/* @__PURE__ */ r({attributesFromSplats:()=>g,decomposeCovariance:()=>f,encodeSplat:()=>h,parsePly:()=>c,splatsFromAttributes:()=>l}),a=.2820947918,o={char:[1,(e,t)=>e.getInt8(t)],int8:[1,(e,t)=>e.getInt8(t)],uchar:[1,(e,t)=>e.getUint8(t)],uint8:[1,(e,t)=>e.getUint8(t)],short:[2,(e,t)=>e.getInt16(t,!0)],int16:[2,(e,t)=>e.getInt16(t,!0)],ushort:[2,(e,t)=>e.getUint16(t,!0)],uint16:[2,(e,t)=>e.getUint16(t,!0)],int:[4,(e,t)=>e.getInt32(t,!0)],int32:[4,(e,t)=>e.getInt32(t,!0)],uint:[4,(e,t)=>e.getUint32(t,!0)],uint32:[4,(e,t)=>e.getUint32(t,!0)],float:[4,(e,t)=>e.getFloat32(t,!0)],float32:[4,(e,t)=>e.getFloat32(t,!0)],double:[8,(e,t)=>e.getFloat64(t,!0)],float64:[8,(e,t)=>e.getFloat64(t,!0)]},s=e=>{let t=Math.min(1,Math.max(0,e));return t<=.04045?1/12.92:2.4/1.055*((t+.055)/1.055)**1.4};function c(e){if(!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError(`Expected .ply bytes; pass an ArrayBuffer or typed array of the file`);let n=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=Math.min(n.length,65536),i=-1,a=new TextDecoder(`latin1`).decode(n.subarray(0,r)),s=a.indexOf(`end_header`);if(a.startsWith(`ply`)&&s>=0&&(i=a.indexOf(`
2
+ `,s)+1),i<=0)throw RangeError(`Not a PLY file: it must start with "ply" and have an end_header line.`);let c=a.slice(0,i).split(/\r?\n/),u=``,d=-1,f=!1,p=[];for(let e of c){let n=e.trim().split(/\s+/);if(n[0]===`format`)u=n[1];else if(n[0]===`element`){if(f=n[1]===`vertex`,f)d=Number(n[2]);else if(n[1]===`chunk`)throw new t(`unsupported`,`Packed (chunked) splat PLY files are not supported; export an uncompressed Gaussian-splat PLY.`)}else if(n[0]===`property`&&f){if(n[1]===`list`)throw RangeError(`Splat PLY vertex properties must be scalars, not lists.`);if(!o[n[1]])throw RangeError(`Unknown PLY property type ${n[1]}; use float, double or an integer type.`);p.push({type:n[1],name:n[2]})}}if(u===`binary_big_endian`)throw new t(`unsupported`,`Big-endian PLY files are not supported; export binary_little_endian or ascii.`);if(u!==`binary_little_endian`&&u!==`ascii`)throw RangeError(`Unknown PLY format ${u}; use binary_little_endian or ascii.`);if(!Number.isInteger(d)||d<1||d>3e6)throw RangeError(`A splat PLY needs 1 to 3,000,000 vertices.`);let m=new Map(p.map((e,t)=>[e.name,t])),h=[`x`,`y`,`z`,`f_dc_0`,`f_dc_1`,`f_dc_2`,`opacity`,`scale_0`,`scale_1`,`scale_2`,`rot_0`,`rot_1`,`rot_2`,`rot_3`].filter(e=>!m.has(e));if(h.length)throw RangeError(`Not a Gaussian-splat PLY: missing ${h.join(`, `)}; export the splat attributes.`);let g=0;for(;m.has(`f_rest_${g}`);)g++;let _=g/3+1;if(g%3||![1,4,9,16,25].includes(_))throw RangeError(`Splat PLY f_rest_* must hold 3, 8, 15 or 24 coefficients per colour channel (SH degree 1-4).`);let v=p.length,y=new Float64Array(d*v);if(u===`ascii`){let e=new TextDecoder(`latin1`).decode(n.subarray(i)).trim().split(/\s+/);if(e.length<d*v)throw RangeError(`The ascii PLY has fewer values than its header promises; check that the file is complete.`);for(let t=0;t<d*v;t++)y[t]=Number(e[t])}else{let e=[],t=0;for(let n of p)e.push(t),t+=o[n.type][0];if(n.length-i<d*t)throw RangeError(`The PLY file is shorter than its header promises; check that it downloaded completely.`);let r=new DataView(n.buffer,n.byteOffset+i,d*t),a=p.map(e=>o[e.type][1]);for(let n=0;n<d;n++)for(let i=0;i<v;i++)y[n*v+i]=a[i](r,n*t+e[i])}let b=e=>m.get(e),x=b(`x`),S=b(`f_dc_0`),C=b(`opacity`),w=b(`scale_0`),T=b(`rot_0`),E=g?b(`f_rest_0`):0,D=_-1,O={count:d,positions:new Float32Array(d*3),logScales:new Float32Array(d*3),rotations:new Float32Array(d*4),dc:new Float32Array(d*3),alphas:new Float32Array(d),rest:D?new Float32Array(d*D*3):void 0};for(let e=0;e<d;e++){let t=t=>y[e*v+t];if(O.positions.set([t(x),t(b(`y`)),t(b(`z`))],e*3),O.rotations.set([t(T),t(T+1),t(T+2),t(T+3)],e*4),O.logScales.set([t(w),t(w+1),t(w+2)],e*3),O.dc.set([t(S),t(S+1),t(S+2)],e*3),O.alphas[e]=1/(1+Math.exp(-t(C))),O.rest)for(let n=0;n<3;n++)for(let r=0;r<D;r++)O.rest[(e*D+r)*3+n]=t(E+n*D+r)}return l(O)}function l(t,{linear:n=!1}={}){let{count:r}=t,i=t.rest?t.rest.length/r/3:0,o=i+1;if(!Number.isInteger(i)||![0,3,8,15,24].includes(i))throw RangeError(`Splat spherical harmonics must hold 3, 8, 15 or 24 coefficients per colour channel (degree 1-4).`);let c=new Float32Array(r*6),l=new Float32Array(r*4),u=i?new Float32Array(r*o*3):void 0;for(let f=0;f<r;f++){let r=t.rotations[f*4],p=t.rotations[f*4+1],m=t.rotations[f*4+2],h=t.rotations[f*4+3],g=Math.hypot(r,p,m,h);if(!(g>0))throw RangeError(`A splat rotation is the zero quaternion; check the file.`);r/=g,p/=g,m/=g,h/=g,d(c,f,[p,m,h,r],[Math.exp(t.logScales[f*3]),Math.exp(t.logScales[f*3+1]),Math.exp(t.logScales[f*3+2])]),l[f*4+3]=t.alphas[f];for(let r=0;r<3;r++){let c=.5+a*t.dc[f*3+r],d=Math.min(1,Math.max(0,c)),p=n?d:e(d);if(l[f*4+r]=p,!u)continue;let m=n?1:s(c);u[f*o*3+r]=(p-.5)/a;for(let e=1;e<o;e++)u[(f*o+e)*3+r]=t.rest[(f*i+e-1)*3+r]*m}}let f=u?{positions:t.positions,covariances:c,colors:l,sphericalHarmonics:u}:{positions:t.positions,covariances:c,colors:l};return j(f),f}var u=2**-20;function d(e,t,n,r){let[i,a,o,s]=n,c=[1-2*(a*a+o*o),2*(i*a-o*s),2*(i*o+a*s),2*(i*a+o*s),1-2*(i*i+o*o),2*(a*o-i*s),2*(i*o-a*s),2*(a*o+i*s),1-2*(i*i+a*a)],l=[r[0]*r[0],r[1]*r[1],r[2]*r[2]],d=Math.max(Math.max(...l)*u,1e-30),f=l.map(e=>Math.max(e,d)),p=0;for(let n=0;n<3;n++)for(let r=n;r<3;r++)e[t*6+p++]=c[n*3]*c[r*3]*f[0]+c[n*3+1]*c[r*3+1]*f[1]+c[n*3+2]*c[r*3+2]*f[2]}function f(e,t=0){let n=[[e[t],e[t+1],e[t+2]],[e[t+1],e[t+3],e[t+4]],[e[t+2],e[t+4],e[t+5]]],r=[[1,0,0],[0,1,0],[0,0,1]];for(let e=0;e<32&&!(Math.abs(n[0][1])+Math.abs(n[0][2])+Math.abs(n[1][2])<1e-30*(Math.abs(n[0][0])+Math.abs(n[1][1])+Math.abs(n[2][2])));e++)for(let[e,t]of[[0,1],[0,2],[1,2]]){if(n[e][t]===0)continue;let i=(n[t][t]-n[e][e])/(2*n[e][t]),a=Math.sign(i||1)/(Math.abs(i)+Math.sqrt(i*i+1)),o=1/Math.sqrt(a*a+1),s=a*o;for(let r=0;r<3;r++){let i=n[r][e],a=n[r][t];n[r][e]=o*i-s*a,n[r][t]=s*i+o*a}for(let r=0;r<3;r++){let i=n[e][r],a=n[t][r];n[e][r]=o*i-s*a,n[t][r]=s*i+o*a}for(let n=0;n<3;n++){let i=r[n][e],a=r[n][t];r[n][e]=o*i-s*a,r[n][t]=s*i+o*a}}if(r[0][0]*(r[1][1]*r[2][2]-r[1][2]*r[2][1])-r[0][1]*(r[1][0]*r[2][2]-r[1][2]*r[2][0])+r[0][2]*(r[1][0]*r[2][1]-r[1][1]*r[2][0])<0)for(let e=0;e<3;e++)r[e][2]=-r[e][2];return{scale:[0,1,2].map(e=>Math.sqrt(Math.max(n[e][e],0))),rotation:p(r)}}function p(e){let t=e[0][0]+e[1][1]+e[2][2],n,r,i,a;if(t>0){let o=Math.sqrt(t+1)*2;a=o/4,n=(e[2][1]-e[1][2])/o,r=(e[0][2]-e[2][0])/o,i=(e[1][0]-e[0][1])/o}else if(e[0][0]>e[1][1]&&e[0][0]>e[2][2]){let t=Math.sqrt(1+e[0][0]-e[1][1]-e[2][2])*2;a=(e[2][1]-e[1][2])/t,n=t/4,r=(e[0][1]+e[1][0])/t,i=(e[0][2]+e[2][0])/t}else if(e[1][1]>e[2][2]){let t=Math.sqrt(1+e[1][1]-e[0][0]-e[2][2])*2;a=(e[0][2]-e[2][0])/t,n=(e[0][1]+e[1][0])/t,r=t/4,i=(e[1][2]+e[2][1])/t}else{let t=Math.sqrt(1+e[2][2]-e[0][0]-e[1][1])*2;a=(e[1][0]-e[0][1])/t,n=(e[0][2]+e[2][0])/t,r=(e[1][2]+e[2][1])/t,i=t/4}let o=Math.hypot(n,r,i,a);return[n/o,r/o,i/o,a/o]}var m=e=>{let t=Math.min(1,Math.max(0,e));return t<=.0031308?t*12.92:1.055*t**(1/2.4)-.055};function h(e){let t=j(e),n=new Uint8Array(t*32),r=new DataView(n.buffer);if(e.colors.some((e,t)=>t%4==3&&e>1))throw RangeError(`The .splat format stores opacity through 1; use SOG for this cloud`);for(let i=0;i<t;i++){let t=i*32;for(let n=0;n<3;n++)r.setFloat32(t+n*4,e.positions[i*3+n],!0);let{scale:a,rotation:o}=f(e.covariances,i*6);for(let e=0;e<3;e++)r.setFloat32(t+12+e*4,Math.max(a[e],1e-12),!0);for(let r=0;r<3;r++)n[t+24+r]=Math.round(m(e.colors[i*4+r])*255);n[t+27]=Math.round(e.colors[i*4+3]*255);let[s,c,l,u]=o;[u,s,c,l].forEach((e,r)=>n[t+28+r]=Math.min(255,Math.max(0,Math.round(e*128+128))))}return n}function g(e){let t=j(e),n=e.sphericalHarmonics,r=n?n.length/t/3:1,i={count:t,positions:e.positions.slice(),logScales:new Float32Array(t*3),rotations:new Float32Array(t*4),dc:new Float32Array(t*3),alphas:new Float32Array(t),...n?{rest:new Float32Array(t*(r-1)*3)}:{}};for(let o=0;o<t;o++){let{scale:t,rotation:c}=f(e.covariances,o*6),[l,u,d,p]=c;for(let e=0;e<3;e++)i.logScales[o*3+e]=Math.log(Math.max(t[e],1e-30));i.rotations.set([p,l,u,d],o*4),i.alphas[o]=e.colors[o*4+3];for(let t=0;t<3;t++){let c=m(n?.5+a*n[o*r*3+t]:e.colors[o*4+t]),l=s(c);i.dc[o*3+t]=(c-.5)/a;for(let e=1;e<r;e++)i.rest[(o*(r-1)+e-1)*3+t]=n[(o*r+e)*3+t]/l}}return i}async function _(e,t){return(await import(`./spz-BTy6CPTp.js`).then(e=>e.n)).parseSpz(e,t)}async function v(e,t){return(await import(`./sog-D0LYo48N.js`).then(e=>e.n)).parseSog(e,t)}async function y(e,t){return(await import(`./encode-BA6xu973.js`)).encodeSpz(e,t)}async function b(e){return(await import(`./encode-BA6xu973.js`)).encodeSog(e)}var x=(e,t)=>e.sphericalHarmonics?e.sphericalHarmonics.length/t/3:0;function S(e,t){let n=j(e);if(typeof t!=`function`)throw TypeError(`filterSplats needs a keep(index) function`);let r=[];for(let i=0;i<n;i++)t(i,e)&&r.push(i);return C(e,r,x(e,n))}function C(e,t,n){if(!t.length)throw RangeError(`No splats are left; widen the region or the filter.`);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;return t.forEach((t,r)=>{i.set(e.positions.subarray(t*3,t*3+3),r*3),a.set(e.covariances.subarray(t*6,t*6+6),r*6),o.set(e.colors.subarray(t*4,t*4+4),r*4),s&&s.set(e.sphericalHarmonics.subarray(t*n*3,(t+1)*n*3),r*n*3)}),s?{positions:i,covariances:a,colors:o,sphericalHarmonics:s}:{positions:i,covariances:a,colors:o}}function w(e,t,n={}){let r=n.invert??!1,i=e=>Array.isArray(e)&&e.length===3&&e.every(e=>typeof e==`number`&&Number.isFinite(e)),a;if(t&&`box`in t&&i(t.box?.min)&&i(t.box?.max)){let{min:e,max:n}=t.box;a=(t,r,i)=>t>=e[0]&&t<=n[0]&&r>=e[1]&&r<=n[1]&&i>=e[2]&&i<=n[2]}else if(t&&`sphere`in t&&i(t.sphere?.center)&&t.sphere.radius>=0){let{center:e,radius:n}=t.sphere;a=(t,r,i)=>(t-e[0])**2+(r-e[1])**2+(i-e[2])**2<=n*n}else throw RangeError(`Invalid crop region; pass {box: {min: [x, y, z], max: [x, y, z]}} or {sphere: {center: [x, y, z], radius}}`);let o=e?.positions;return S(e,e=>a(o[e*3],o[e*3+1],o[e*3+2])!==r)}function T(e,t,n,r){return r[0]=.2820947918,r[1]=-.4886025119*t,r[2]=.4886025119*n,r[3]=-.4886025119*e,r[4]=1.0925484306*e*t,r[5]=-1.0925484306*t*n,r[6]=.3153915653*(3*n*n-1),r[7]=-1.0925484306*e*n,r[8]=.5462742153*(e*e-t*t),r[9]=-.5900435899*t*(3*e*e-t*t),r[10]=2.8906114426*e*t*n,r[11]=-.4570457995*t*(5*n*n-1),r[12]=.3731763326*n*(5*n*n-3),r[13]=-.4570457995*e*(5*n*n-1),r[14]=1.4453057213*n*(e*e-t*t),r[15]=-.5900435899*e*(e*e-3*t*t),r[16]=2.5033429418*e*t*(e*e-t*t),r[17]=-1.7701307698*t*n*(3*e*e-t*t),r[18]=.9461746958*e*t*(7*n*n-1),r[19]=-.6690465436*t*n*(7*n*n-3),r[20]=.1057855469*(35*n**4-30*n*n+3),r[21]=-.6690465436*e*n*(7*n*n-3),r[22]=.4730873479*(e*e-t*t)*(7*n*n-1),r[23]=-1.7701307698*e*n*(e*e-3*t*t),r[24]=.6258357354*(e**4-6*e*e*t*t+t**4),r}function E(e,t){let n=new Float64Array(t),r=[],i=[];for(let a=0;a<128;a++){let o=1-2*(a+.5)/128,s=Math.sqrt(1-o*o),c=a*Math.PI*(3-Math.sqrt(5)),l=[Math.cos(c)*s,o,Math.sin(c)*s];r.push(T(l[0],l[1],l[2],new Float64Array(t)).slice(0,t));let u=[e[0]*l[0]+e[3]*l[1]+e[6]*l[2],e[1]*l[0]+e[4]*l[1]+e[7]*l[2],e[2]*l[0]+e[5]*l[1]+e[8]*l[2]];i.push(T(u[0],u[1],u[2],n).slice(0,t))}let a=new Float64Array(t*t),o=new Float64Array(t*t);for(let e=0;e<128;e++)for(let n=0;n<t;n++)for(let s=0;s<t;s++)a[n*t+s]+=r[e][n]*r[e][s],o[n*t+s]+=r[e][n]*i[e][s];for(let e=0;e<t;e++){let n=e;for(let r=e+1;r<t;r++)Math.abs(a[r*t+e])>Math.abs(a[n*t+e])&&(n=r);for(let r=0;r<t;r++)[a[e*t+r],a[n*t+r]]=[a[n*t+r],a[e*t+r]],[o[e*t+r],o[n*t+r]]=[o[n*t+r],o[e*t+r]];for(let n=0;n<t;n++){if(n===e)continue;let r=a[n*t+e]/a[e*t+e];if(r)for(let i=0;i<t;i++)a[n*t+i]-=r*a[e*t+i],o[n*t+i]-=r*o[e*t+i]}}for(let e=0;e<t;e++)for(let n=0;n<t;n++)o[e*t+n]/=a[e*t+e];return o}function D(e,t){let n=j(e);if(!t||t.length!==16||!Array.from(t).every(Number.isFinite))throw RangeError(`Invalid splat transform; pass a 4x4 column-major matrix of 16 finite numbers`);let r=t,i=[r[0],r[4],r[8],r[1],r[5],r[9],r[2],r[6],r[10]],a=i[0]*(i[4]*i[8]-i[5]*i[7])-i[1]*(i[3]*i[8]-i[5]*i[6])+i[2]*(i[3]*i[7]-i[4]*i[6]);if(!(Math.abs(a)>1e-12))throw RangeError(`A splat transform needs an invertible linear part (no zero scale); fix the matrix.`);let o=new Float32Array(n*3),s=new Float32Array(n*6),c=e.colors.slice();for(let t=0;t<n;t++){let n=e.positions[t*3],a=e.positions[t*3+1],c=e.positions[t*3+2];for(let e=0;e<3;e++)o[t*3+e]=i[e*3]*n+i[e*3+1]*a+i[e*3+2]*c+r[12+e];let l=e.covariances.subarray(t*6,t*6+6),u=[l[0],l[1],l[2],l[1],l[3],l[4],l[2],l[4],l[5]],d=/* @__PURE__ */ new Float64Array(9);for(let e=0;e<3;e++)for(let t=0;t<3;t++)d[e*3+t]=i[e*3]*u[t]+i[e*3+1]*u[3+t]+i[e*3+2]*u[6+t];let f=0;for(let e=0;e<3;e++)for(let n=e;n<3;n++)s[t*6+f++]=d[e*3]*i[n*3]+d[e*3+1]*i[n*3+1]+d[e*3+2]*i[n*3+2]}let l={positions:o,covariances:s,colors:c},u=e.sphericalHarmonics;if(u){let t=x(e,n),r=E(O(i),t),a=new Float32Array(u.length);for(let e=0;e<n;e++)for(let n=0;n<3;n++)for(let i=0;i<t;i++){let o=0;for(let a=0;a<t;a++)o+=r[i*t+a]*u[(e*t+a)*3+n];a[(e*t+i)*3+n]=o}l.sphericalHarmonics=a}return j(l),l}function O(e){let t=e.slice();for(let e=0;e<64;e++){let e=t[0]*(t[4]*t[8]-t[5]*t[7])-t[1]*(t[3]*t[8]-t[5]*t[6])+t[2]*(t[3]*t[7]-t[4]*t[6]),n=[t[4]*t[8]-t[5]*t[7],t[5]*t[6]-t[3]*t[8],t[3]*t[7]-t[4]*t[6],t[2]*t[7]-t[1]*t[8],t[0]*t[8]-t[2]*t[6],t[1]*t[6]-t[0]*t[7],t[1]*t[5]-t[2]*t[4],t[2]*t[3]-t[0]*t[5],t[0]*t[4]-t[1]*t[3]],r=t.map((t,r)=>(t+n[r]/e)/2),i=r.reduce((e,n,r)=>e+Math.abs(n-t[r]),0);if(t=r,i<1e-14)break}return t}function k(...e){if(!e.length)throw RangeError(`mergeSplats needs at least one cloud`);let t=e.map(e=>j(e)),n=new Set(e.map((e,n)=>x(e,t[n])));if(n.size>1)throw RangeError(`Merged clouds need the same spherical-harmonics degree; drop sphericalHarmonics from all or give all the same degree.`);let r=t.reduce((e,t)=>e+t,0),i=[...n][0],a=new Float32Array(r*3),o=new Float32Array(r*6),s=new Float32Array(r*4),c=i?new Float32Array(r*i*3):void 0,l=0;e.forEach((e,n)=>{a.set(e.positions,l*3),o.set(e.covariances,l*6),s.set(e.colors,l*4),c&&c.set(e.sphericalHarmonics,l*i*3),l+=t[n]});let u=c?{positions:a,covariances:o,colors:s,sphericalHarmonics:c}:{positions:a,covariances:o,colors:s};return j(u),u}function A(e,t){let n=j(e),r=t?.cellSize;if(!(r>0&&r<1/0))throw RangeError(`decimateSplats needs a cellSize above 0, world units`);let i=x(e,n),a=/* @__PURE__ */ new Map,o=e.positions;for(let e=0;e<n;e++){let t=`${Math.floor(o[e*3]/r)},${Math.floor(o[e*3+1]/r)},${Math.floor(o[e*3+2]/r)}`,n=a.get(t);n||a.set(t,n=[]),n.push(e)}let s=a.size,c=new Float32Array(s*3),l=new Float32Array(s*6),u=new Float32Array(s*4),d=i?new Float32Array(s*i*3):void 0,f=0;for(let t of a.values()){let n=t.map(t=>{let n=e.covariances.subarray(t*6,t*6+6),r=n[0]*(n[3]*n[5]-n[4]*n[4])-n[1]*(n[1]*n[5]-n[4]*n[2])+n[2]*(n[1]*n[4]-n[3]*n[2]);return Math.max(e.colors[t*4+3],1e-6)*Math.sqrt(Math.max(r,0))}),r=n.reduce((e,t)=>e+t,0)||1,a=[0,0,0];t.forEach((e,t)=>{for(let i=0;i<3;i++)a[i]+=n[t]/r*o[e*3+i]});let s=/* @__PURE__ */ new Float64Array(6);t.forEach((t,c)=>{let l=n[c]/r,p=[o[t*3]-a[0],o[t*3+1]-a[1],o[t*3+2]-a[2]],m=e.covariances.subarray(t*6,t*6+6),h=0;for(let e=0;e<3;e++)for(let t=e;t<3;t++,h++)s[h]+=l*(m[h]+p[e]*p[t]);for(let n=0;n<4;n++)u[f*4+n]+=l*e.colors[t*4+n];if(d)for(let n=0;n<i*3;n++)d[f*i*3+n]+=l*e.sphericalHarmonics[t*i*3+n]}),c.set(a,f*3),l.set(s,f*6),f++}let p=d?{positions:c,covariances:l,colors:u,sphericalHarmonics:d}:{positions:c,covariances:l,colors:u};for(let e=0;e<s*4;e++)p.colors[e]=Math.min(e%4==3?1.5625:1,Math.max(0,p.colors[e]));return j(p),p}function j(e){if(!e||!(e.positions instanceof Float32Array)||!(e.covariances instanceof Float32Array)||!(e.colors instanceof Float32Array))throw TypeError(`Splat data must use Float32 arrays`);let t=e.positions.length/3,n=e.sphericalHarmonics;if(!Number.isInteger(t)||t<1||t>3e6||e.covariances.length!==t*6||e.colors.length!==t*4||n!==void 0&&(!(n instanceof Float32Array)||![4,9,16,25].includes(n.length/t/3)))throw RangeError(`Splat data needs 1 to 3,000,000 splats, covariances of 6 and colors of 4 per splat, and spherical harmonics of 4, 9, 16 or 25 coefficients per channel; fix the array lengths.`);for(let t of[e.positions,e.covariances,e.colors,...n?[n]:[]])for(let e of t)if(!Number.isFinite(e))throw RangeError(`Splat attributes must be finite`);for(let n=0;n<t;n++){let t=n*6,r=e.covariances[t],i=e.covariances[t+1],a=e.covariances[t+2],o=e.covariances[t+3],s=e.covariances[t+4],c=e.covariances[t+5];if(r<=0||r*o-i*i<=0||r*(o*c-s*s)-i*(i*c-a*s)+a*(i*s-a*o)<=0)throw RangeError(`Splat covariance must be positive definite`);for(let t=0;t<4;t++)if(e.colors[n*4+t]<0||e.colors[n*4+t]>(t===3?1.5625:1))throw RangeError(`Splat colors must be 0..1 and opacity 0..1.5625; fix the attribute values`)}return t}function M(t){if(!(t instanceof ArrayBuffer)&&!ArrayBuffer.isView(t))throw TypeError(`Expected .splat bytes`);let n=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength),r=n.length/32;if(!Number.isInteger(r)||r<1||r>3e6)throw RangeError(`A .splat file must hold 1 to 3,000,000 splats of 32 bytes each; check that the file is complete.`);let i=new DataView(n.buffer,n.byteOffset,n.byteLength),a=new Float32Array(r*3),o=new Float32Array(r*6),s=new Float32Array(r*4);for(let t=0;t<r;t++){let r=t*32;for(let e=0;e<3;e++)a[t*3+e]=i.getFloat32(r+e*4,!0);let c=i.getFloat32(r+12,!0),l=i.getFloat32(r+16,!0),u=i.getFloat32(r+20,!0);if(![c,l,u].every(e=>Number.isFinite(e)&&e>0))throw RangeError(`A .splat scale must be finite and above 0; check that the file is a valid .splat.`);let d=(n[r+28]-128)/128,f=(n[r+29]-128)/128,p=(n[r+30]-128)/128,m=(n[r+31]-128)/128,h=Math.hypot(d,f,p,m);if(!h)throw RangeError(`A .splat rotation is the zero quaternion (all four bytes are 128); check that the file is a valid .splat.`);d/=h,f/=h,p/=h,m/=h;let g=[1-2*(p*p+m*m),2*(f*p-m*d),2*(f*m+p*d),2*(f*p+m*d),1-2*(f*f+m*m),2*(p*m-f*d),2*(f*m-p*d),2*(p*m+f*d),1-2*(f*f+p*p)],_=[c*c,l*l,u*u],v=0;for(let e=0;e<3;e++)for(let n=e;n<3;n++)o[t*6+v++]=g[e*3]*g[n*3]*_[0]+g[e*3+1]*g[n*3+1]*_[1]+g[e*3+2]*g[n*3+2]*_[2];for(let i=0;i<3;i++)s[t*4+i]=e(n[r+24+i]/255);s[t*4+3]=n[r+27]/255}let c={positions:a,covariances:o,colors:s};return j(c),c}export{l as _,S as a,b as c,_ as d,g as f,i as g,c as h,A as i,y as l,h as m,j as n,k as o,f as p,w as r,D as s,M as t,v as u,r as v};
package/dist/data.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ /** A Gaussian splat cloud of 1-3,000,000 splats in world space. */
2
+ export interface SplatData {
3
+ /** Centres, 3 floats (x, y, z) per splat, world units. */
4
+ positions: Float32Array;
5
+ /** Positive-definite 3D covariances, 6 floats per splat (xx, xy, xz, yy, yz, zz), world units squared. */
6
+ covariances: Float32Array;
7
+ /** Linear RGB (0..1) and opacity (0..1.5625), 4 floats per splat. */
8
+ colors: Float32Array;
9
+ /** Optional view-dependent colour: 4, 9, 16 or 25 SH coefficients per splat, RGB interleaved; replaces `colors`' RGB. */
10
+ sphericalHarmonics?: Float32Array;
11
+ }
12
+ /**
13
+ * Checks a cloud and returns its splat count.
14
+ * @throws TypeError when an attribute is not a Float32Array.
15
+ * @throws RangeError on a wrong count or length, a non-finite value, a covariance that is not positive definite, or a
16
+ * RGB outside 0..1 or opacity outside 0..1.5625.
17
+ */
18
+ export declare function validateSplats(data: SplatData): number;
19
+ /**
20
+ * Decodes the common 32-byte `.splat` layout (xyz, positive xyz scales, byte sRGB RGBA, byte wxyz quaternion) into
21
+ * {@link SplatData}: sRGB to linear, normalised quaternions, covariance from scale and rotation.
22
+ * @throws TypeError when `input` is not bytes; RangeError when the length is not 32 bytes x 1-3,000,000 splats, a
23
+ * scale is not finite and positive, a quaternion is zero, or the decoded cloud fails `validateSplats`.
24
+ */
25
+ export declare function parseSplat(input: ArrayBuffer | ArrayBufferView): SplatData;
26
+ export { parsePly, encodeSplat, decomposeCovariance, splatsFromAttributes, attributesFromSplats, type GaussianAttributes, } from './ply.js';
27
+ export { parseSpz, parseSog, encodeSpz, encodeSog, type ParseSpzOptions, type ParseSogOptions, type SogFiles, type EncodeSpzOptions, } from './compressed.js';
28
+ export { cropSplats, filterSplats, transformSplats, mergeSplats, decimateSplats, type SplatRegion } from './edit.js';
package/dist/data.js ADDED
@@ -0,0 +1 @@
1
+ export{f as attributesFromSplats,r as cropSplats,i as decimateSplats,p as decomposeCovariance,c as encodeSog,m as encodeSplat,l as encodeSpz,a as filterSplats,o as mergeSplats,h as parsePly,u as parseSog,t as parseSplat,d as parseSpz,_ as splatsFromAttributes,s as transformSplats,n as validateSplats}from"./data-D31W24Wu.js";
@@ -0,0 +1,42 @@
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 SplatDepth}. */
6
+ export interface SplatDepthOptions {
7
+ /** Opacity (0 to 1) a splat must reach at a pixel to write its depth there. Default 0.5. Live: `depth.threshold`. */
8
+ threshold?: number;
9
+ /** Frame-graph order of the depth pass. Default 3.5: right after the clouds draw (order 3). */
10
+ order?: number;
11
+ }
12
+ /**
13
+ * Depth for a splat cloud: `SplatDepth.attach(engine, cloud)`. Each frame after the cloud draws, its splats write their
14
+ * depth (reversed Z, greater wins) where their opacity reaches `threshold`; no colour is written. WebGPU only.
15
+ * @throws RangeError for a threshold outside 0 to 1 or a non-finite order; TypeError when `cloud` is not a Splats.
16
+ * @throws MargoError `'unsupported'` on a WebGL engine, `'disposed'` when attached after `dispose()`.
17
+ */
18
+ export declare class SplatDepth implements EnginePlugin {
19
+ private static next;
20
+ readonly name: string;
21
+ readonly cloud: Splats;
22
+ readonly order: number;
23
+ private value;
24
+ private engine?;
25
+ private uniform?;
26
+ private readonly data;
27
+ private pipelines;
28
+ private group?;
29
+ private disposed;
30
+ constructor(cloud: Splats, options?: SplatDepthOptions);
31
+ /** Same as `engine.use(new SplatDepth(cloud, options))`; returns it. */
32
+ static attach(engine: EngineKernel, cloud: Splats, options?: SplatDepthOptions): SplatDepth;
33
+ /** Opacity a splat must reach at a pixel to write its depth (0 to 1). */
34
+ get threshold(): number;
35
+ set threshold(value: number);
36
+ setup(engine: Engine): void;
37
+ registerPasses(graph: FrameGraph): void;
38
+ private draw;
39
+ onDeviceRestored(engine: Engine): void;
40
+ dispose(): void;
41
+ [Symbol.dispose]: () => void;
42
+ }
package/dist/depth.js ADDED
@@ -0,0 +1,14 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const t=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{t as e}from"./view-rect-G-t2gTqO.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as n}from"@margoengine/math/errors";var r=`struct Ellipse {center:vec4f,axes:vec4f}
5
+ @group(0) @binding(0) var<uniform> threshold:vec4f;
6
+ @group(0) @binding(1) var<storage,read> ellipses:array<Ellipse>;
7
+ @group(0) @binding(2) var<storage,read> sorted:array<vec2u>;
8
+ struct Out {@builtin(position) clip:vec4f,@location(0) corner:vec2f,@location(1) @interpolate(flat) opacity:f32}
9
+ @vertex fn vertex(@builtin(vertex_index) vertex:u32,@builtin(instance_index) instance:u32)->Out {
10
+ let corners=array<vec2f,4>(vec2f(-1,-1),vec2f(1,-1),vec2f(-1,1),vec2f(1,1));let e=ellipses[sorted[instance].y];let corner=corners[vertex];var o:Out;
11
+ o.clip=vec4f(e.center.xy+e.axes.xy*corner.x+e.axes.zw*corner.y,e.center.z,1);o.corner=corner;o.opacity=e.center.w;
12
+ if(e.center.w<threshold.x){o.clip=vec4f(2,2,0,1);}return o;
13
+ }
14
+ @fragment fn fragment(i:Out) {let power=-4.5*dot(i.corner,i.corner);if(power<-4.5||min(0.99,i.opacity*exp(power))<threshold.x){discard;}}`,i=class i{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);static{this.next=0}constructor(e,t={}){if(this.name=`splats-depth:`+i.next++,this.data=/* @__PURE__ */ new Float32Array(4),this.pipelines=/* @__PURE__ */ new Map,this.disposed=!1,!e||typeof e!=`object`||!(`gpuState`in e))throw TypeError(`SplatDepth needs a Splats cloud`);if(this.cloud=e,this.value=a(t.threshold??.5),this.order=t.order??3.5,!Number.isFinite(this.order))throw RangeError(`SplatDepth order must be a finite number`)}static attach(e,n,r={}){__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));let a=new i(n,r);return t(e).use(a),a}get threshold(){return this.value}set threshold(e){this.value=a(e)}setup(e){if(this.disposed||!e.gpu)throw new n(this.disposed?`disposed`:`unsupported`,`SplatDepth needs WebGPU and a live depth pass; attach a new SplatDepth to a WebGPU engine; see https://margoengine.com/errors#webgpu`);this.engine=e,this.uniform=e.gpu.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})}registerPasses(e){e.add({name:this.name,order:this.order,execute:e=>{e.backend===`webgpu`&&this.draw(e)}})}draw(t){if(!this.cloud.attached)return;let n=this.cloud.gpuState,i=t.descriptor.multisample?.count??1,a=t.descriptor.depthStencil.format,o=i+`:`+a,s=this.pipelines.get(o);if(!s){let e=t.device.createShaderModule({code:r});s=t.device.createRenderPipeline({layout:`auto`,vertex:{module:e,entryPoint:`vertex`},fragment:{module:e,entryPoint:`fragment`,targets:[]},primitive:{topology:`triangle-strip`},multisample:t.descriptor.multisample,depthStencil:{format:a,depthWriteEnabled:!0,depthCompare:`greater`}}),this.pipelines.set(o,s)}let c=s.getBindGroupLayout(0);(!this.group||this.group.ellipses!==n.ellipses||this.group.sorted!==n.sorted||this.group.layout!==c)&&(this.group={group:t.device.createBindGroup({layout:c,entries:[this.uniform,n.ellipses,n.sorted].map((e,t)=>({binding:t,resource:{buffer:e}}))}),ellipses:n.ellipses,sorted:n.sorted,layout:c}),this.data[0]=this.value,t.device.queue.writeBuffer(this.uniform,0,this.data);let l=a.includes(`stencil`),u=t.encoder.beginRenderPass({colorAttachments:[],depthStencilAttachment:{view:t.depth,depthLoadOp:`load`,depthStoreOp:`store`,...l?{stencilReadOnly:!0}:{}}});e(u,t),u.setPipeline(s),u.setBindGroup(0,this.group.group),u.draw(4,this.cloud.count),u.end(),this.engine.stats.drawCalls++}onDeviceRestored(e){this.pipelines.clear(),this.group=void 0,this.setup(e)}dispose(){this.disposed||(this.disposed=!0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.uniform?.destroy(),this.uniform=this.group=this.engine=void 0,this.pipelines.clear())}[Symbol.dispose??Symbol()](){this.dispose()}};function a(e){if(typeof e!=`number`||!(e>=0&&e<=1))throw RangeError(`SplatDepth threshold must be 0 to 1`);return e}export{i as SplatDepth};
package/dist/edit.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ import { type SplatData } from './data.js';
2
+ /** A region of {@link cropSplats}: an axis-aligned box or a sphere, world units. */
3
+ export type SplatRegion = {
4
+ box: {
5
+ min: readonly [number, number, number];
6
+ max: readonly [number, number, number];
7
+ };
8
+ } | {
9
+ sphere: {
10
+ center: readonly [number, number, number];
11
+ radius: number;
12
+ };
13
+ };
14
+ /**
15
+ * The splats for which `keep(index, data)` returns true, as a new cloud (SH included).
16
+ * @throws RangeError when nothing is kept or `data` is invalid.
17
+ */
18
+ export declare function filterSplats(data: SplatData, keep: (index: number, data: SplatData) => boolean): SplatData;
19
+ /**
20
+ * The splats whose centres lie inside `region` (or outside it, with `invert`): crop a capture to its subject or cut
21
+ * away a floater. Returns a new cloud.
22
+ * @throws RangeError for an invalid region or when no splat is left.
23
+ */
24
+ export declare function cropSplats(data: SplatData, region: SplatRegion, options?: {
25
+ invert?: boolean;
26
+ }): SplatData;
27
+ /**
28
+ * The cloud moved by a 4x4 affine `matrix` (column-major, as Margo's math and glTF use): positions by the matrix,
29
+ * covariances by its linear part (A Σ Aᵀ, so scale and shear stretch the splats), and spherical harmonics turned by
30
+ * the matrix's rotation (from its polar decomposition), so view-dependent colour follows the turn. Returns a new cloud.
31
+ * @throws RangeError for a matrix that is not 16 finite numbers with an invertible linear part.
32
+ */
33
+ export declare function transformSplats(data: SplatData, matrix: ArrayLike<number>): SplatData;
34
+ /**
35
+ * One cloud from several (a scan in parts, a prop placed in a capture). The clouds must all have spherical harmonics
36
+ * of the same degree or none.
37
+ * @throws RangeError for an empty list, mixed SH degrees, or more than 3,000,000 splats in all.
38
+ */
39
+ export declare function mergeSplats(...clouds: SplatData[]): SplatData;
40
+ /**
41
+ * A coarser level of detail: the splats of each `cellSize` grid cell merge into one Gaussian with the same weighted
42
+ * mean and second moment (covariance of the mixture), weighted by opacity times volume. Colour, opacity and SH are
43
+ * the weighted means. Use it for distant views or a quick preview; `cellSize` sets the detail kept.
44
+ * @throws RangeError for a cellSize that is not a positive finite number.
45
+ */
46
+ export declare function decimateSplats(data: SplatData, options: {
47
+ cellSize: number;
48
+ }): SplatData;
@@ -0,0 +1 @@
1
+ import{f as e}from"./data-D31W24Wu.js";import{MargoError as t}from"@margoengine/math/errors";var n;function r(){n=/* @__PURE__ */ new Int32Array(2048);for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=t&1?3988292384^t>>>1:t>>>1;n[e]=t}for(let e=0;e<256;e++)for(let t=1;t<8;t++){let r=n[(t-1)*256+e];n[t*256+e]=r>>>8^n[r&255]}return n}function i(e,t=0){let i=n??r(),a=e.length,o=a-(a&7),s=~t,c=0;for(;c<o;c+=8)s^=e[c]|e[c+1]<<8|e[c+2]<<16|e[c+3]<<24,s=i[1792+(s&255)]^i[1536+(s>>>8&255)]^i[1280+(s>>>16&255)]^i[1024+(s>>>24)]^i[768+e[c+4]]^i[512+e[c+5]]^i[256+e[c+6]]^i[e[c+7]];for(;c<a;c++)s=i[(s^e[c])&255]^s>>>8;return~s>>>0}var a=[17,18,0,1,2,3,4,5,16,6,7,8,9,10,11,12,13,14,15],o=class{constructor(){this.bytes=/* @__PURE__ */ new Uint8Array(65536),this.at=0,this.acc=0,this.have=0}write(e,t){for(this.acc|=(e&(1<<t)-1)<<this.have,this.have+=t;this.have>=8;){if(this.at===this.bytes.length){let e=new Uint8Array(this.bytes.length*2);e.set(this.bytes),this.bytes=e}this.bytes[this.at++]=this.acc&255,this.acc>>>=8,this.have-=8}}finish(){return this.have&&this.write(0,8-this.have),this.bytes.subarray(0,this.at)}};function s(e,t){let n=e.length,r=new Uint8Array(n),i=Array.from(e,e=>e);for(;;){let e=[];for(let t=0;t<n;t++)i[t]>0&&e.push(t);if(r.fill(0),e.length<2){for(let t of e)r[t]=1;return r}let a=e.slice().sort((e,t)=>i[e]-i[t]||e-t),o=a.length,s=new Float64Array(o*2),c=new Int32Array(o*2);a.forEach((e,t)=>s[t]=i[e]);let l=o,u=0,d=o,f=()=>u<o&&(d>=l||s[u]<=s[d])?u++:d++;for(;l<o*2-1;){let e=f(),t=f();s[l]=s[e]+s[t],c[e]=c[t]=l++}let p=0,m=new Uint8Array(o*2);for(let e=o*2-3;e>=0;e--)m[e]=m[c[e]]+1;if(a.forEach((e,t)=>{r[e]=m[t],p=Math.max(p,m[t])}),p<=t)return r;for(let t of e)i[t]=Math.max(1,i[t]>>1)}}function c(e){let t=/* @__PURE__ */ new Uint32Array(16),n=/* @__PURE__ */ new Uint32Array(16),r=new Uint32Array(e.length);for(let n of e)n&&t[n]++;for(let e=1,r=0;e<16;e++)n[e]=r,r=r+t[e]<<1;for(let t=0;t<e.length;t++){let i=e[t];if(!i)continue;let a=n[i]++,o=0;for(let e=0;e<i;e++)o=o<<1|a&1,a>>=1;r[t]=o}return r}function l(e,t){let n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);if(n.length||n.push(0),n.length<=2&&n[n.length-1]<256){e.write(1,1),e.write(n.length-1,1);let r=n[0]>1;e.write(+r,1),e.write(n[0],r?8:1),n.length===2&&e.write(n[1],8);let i=new Uint8Array(t.length);return n.length===2&&(i[n[0]]=i[n[1]]=1),{lengths:i,codes:c(i)}}let r=s(t,15),i=/* @__PURE__ */ new Uint32Array(19);for(let e of r)i[e]++;i.filter(e=>e).length<2&&i[+!!i[0]]++;let o=s(i,7),l=c(o),u=19;for(;u>4&&!o[a[u-1]];)u--;e.write(0,1),e.write(u-4,4);for(let t=0;t<u;t++)e.write(o[a[t]],3);e.write(0,1);for(let t of r)e.write(l[t],o[t]);return{lengths:r,codes:c(r)}}function u(e,t,n){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1||t>16384||n>16384)throw RangeError(`A lossless WebP must be 1 to 16,384 pixels on each side; split the texture`);if(e.length!==t*n*4)throw RangeError(`A lossless WebP needs 4 bytes per pixel; pass width x height x 4`);let r=[/* @__PURE__ */ new Uint32Array(280),/* @__PURE__ */ new Uint32Array(256),/* @__PURE__ */ new Uint32Array(256),/* @__PURE__ */ new Uint32Array(256)],i=!0;for(let t=0;t<e.length;t+=4)r[0][e[t+1]]++,r[1][e[t]]++,r[2][e[t+2]]++,r[3][e[t+3]]++,e[t+3]!==255&&(i=!1);let a=new o;a.write(47,8),a.write(t-1,14),a.write(n-1,14),a.write(+!i,1),a.write(0,3),a.write(0,1),a.write(0,1),a.write(0,1);let[s,c,u,d]=r.map(e=>l(a,e));l(a,/* @__PURE__ */ new Uint32Array(40));for(let t=0;t<e.length;t+=4)a.write(s.codes[e[t+1]],s.lengths[e[t+1]]),a.write(c.codes[e[t]],c.lengths[e[t]]),a.write(u.codes[e[t+2]],u.lengths[e[t+2]]),a.write(d.codes[e[t+3]],d.lengths[e[t+3]]);let f=a.finish(),p=f.length+(f.length&1),m=new Uint8Array(20+p),h=new DataView(m.buffer);return m.set([82,73,70,70],0),h.setUint32(4,12+p,!0),m.set([87,69,66,80,86,80,56,76],8),h.setUint32(16,f.length,!0),m.set(f,20),m}var d={0:0,3:1,8:2,15:3};async function f(t,n={}){let r=e(t),i=r.count,a=r.rest?r.rest.length/i:0;if(a>45||r.alphas.some(e=>e>1))throw RangeError(`SPZ v3 stores SH through degree 3 and opacity through 1; use SOG for this cloud`);let o=0;for(let e of r.positions)o=Math.max(o,Math.abs(e));let s=2**23-1,c=n.fractionalBits??Math.max(0,Math.min(16,Math.floor(Math.log2(s/Math.max(o,1e-30)))));if(!Number.isInteger(c)||c<0||c>23)throw RangeError(`SPZ fractionalBits must be an integer from 0 to 23; pass a smaller value`);if(Math.round(o*2**c)>s)throw RangeError(`A coordinate of ${o} does not fit SPZ positions at ${c} fractional bits; use fewer bits`);let l=new Uint8Array(16+i*(20+a)),u=new DataView(l.buffer),f=e=>Math.min(255,Math.max(0,Math.round(e)));u.setUint32(0,1347635022,!0),u.setUint32(4,3,!0),u.setUint32(8,i,!0),l[12]=d[a/3],l[13]=c,l[14]=+!!n.antialiased;let h=16+i*9,g=h+i,_=g+i*3,v=_+i*3,y=v+i*4;for(let e=0;e<i;e++){for(let t=0;t<3;t++){let n=Math.round(r.positions[e*3+t]*2**c)&16777215,i=16+e*9+t*3;l[i]=n&255,l[i+1]=n>>8&255,l[i+2]=n>>16,l[g+e*3+t]=f((r.dc[e*3+t]*.15+.5)*255),l[_+e*3+t]=f((r.logScales[e*3+t]+10)*16)}l[h+e]=f(r.alphas[e]*255),u.setUint32(v+e*4,p(r.rotations,e),!0);for(let t=0;t<a;t++)l[y+e*a+t]=f(r.rest[e*a+t]*128+128)}return m(l)}function p(e,t){let[n,r,i,a]=e.subarray(t*4,t*4+4),o=Math.hypot(n,r,i,a),s=[r/o,i/o,a/o,n/o],c=0;for(let e=1;e<4;e++)Math.abs(s[e])>Math.abs(s[c])&&(c=e);let l=s[c]<0?-1:1,u=0;for(let e=0;e<4;e++){if(e===c)continue;let t=s[e]*l,n=Math.min(511,Math.round(Math.abs(t)/Math.SQRT1_2*511));u=u<<10|(t<0)<<9|n}return(c<<30|u)>>>0}async function m(e){if(typeof CompressionStream>`u`)throw new t(`unsupported`,`This runtime has no CompressionStream; use a current browser or Node 18+.`);let n=new Blob([e]).stream().pipeThrough(new CompressionStream(`gzip`));return new Uint8Array(await new Response(n).arrayBuffer())}function h(e){let t=Float32Array.from(e).sort(),n=t.length,r=[];for(let e=0,i=0;e<n;e++)if(e===n-1||t[e+1]-t[i]>1e-6*Math.max(Math.abs(t[i]),.001)){if(r.length>256)break;let n=0;for(let r=i;r<=e;r++)n+=t[r];r.push(n/(e-i+1)),i=e+1}let i=r.length<=256,a=i?Array.from({length:256},(e,t)=>r[Math.min(t,r.length-1)]):Array.from({length:256},(e,r)=>t[Math.min(n-1,Math.floor((r+.5)*n/256))]);for(let e=0;e<(i?0:8);e++){let e=/* @__PURE__ */ new Float64Array(256),r=/* @__PURE__ */ new Uint32Array(256);for(let i=0,o=0;i<n;i++){for(;o<255&&t[i]-a[o]>a[o+1]-t[i];)o++;e[o]+=t[i],r[o]++}for(let t=0;t<256;t++)r[t]&&(a[t]=e[t]/r[t]);a.sort((e,t)=>e-t)}let o=new Uint8Array(e.length);for(let t=0;t<e.length;t++){let n=e[t],r=0,i=255;for(;r<i;){let e=r+i+1>>1;a[e]<=n?r=e:i=e-1}o[t]=r<255&&a[r+1]-n<n-a[r]?r+1:r}return{book:a.map(e=>Math.fround(e)),index:o}}async function g(t){let n=e(t),r=n.count,i=(n.rest?.length??0)/r===72||n.alphas.some(e=>e>1),a=Math.ceil(Math.sqrt(r)),o=Math.ceil(r/a),s=()=>new Uint8Array(a*o*4).fill(255),c=s(),l=s(),f=s(),p=s(),m=s(),g=[1/0,1/0,1/0],y=[-1/0,-1/0,-1/0],b=n.positions.map(e=>Math.sign(e)*Math.log(Math.abs(e)+1));for(let e=0;e<r*3;e++)g[e%3]=Math.min(g[e%3],b[e]),y[e%3]=Math.max(y[e%3],b[e]);let x=h(n.logScales),S=h(n.dc);for(let e=0;e<r;e++){let t=e*4;for(let n=0;n<3;n++){let r=y[n]-g[n],i=r>0?Math.round((b[e*3+n]-g[n])/r*65535):0;c[t+n]=i&255,l[t+n]=i>>8,f[t+n]=x.index[e*3+n],m[t+n]=S.index[e*3+n]}m[t+3]=Math.round(i?204*Math.sqrt(n.alphas[e]):n.alphas[e]*255);let r=n.rotations.subarray(e*4,e*4+4),a=Math.hypot(r[0],r[1],r[2],r[3]);if(i){let e=r[0]<0?-1:1,n=Math.hypot(r[1],r[2],r[3]),i=n>1e-10?2/Math.PI*Math.atan2(n,r[0]*e)/n*e:0;c[t+3]=Math.round(r[1]*i*127+128),l[t+3]=Math.round(r[2]*i*127+128),f[t+3]=Math.round(r[3]*i*127+128);continue}let o=0;for(let e=1;e<4;e++)Math.abs(r[e])>Math.abs(r[o])&&(o=e);let s=r[o]<0?-1:1;for(let e=0,n=0;e<4;e++)e!==o&&(p[t+n++]=Math.round((r[e]*s/a/Math.SQRT1_2+1)*127.5));p[t+3]=252+o}let C={version:i?3:2,count:r,means:{mins:g,maxs:y,files:[`means_l.webp`,`means_u.webp`]},scales:{codebook:x.book,files:[`scales.webp`]},...i?{}:{quats:{files:[`quats.webp`]}},...i?{opacity:{max:n.alphas.reduce((e,t)=>Math.max(e,t),0)}}:{},sh0:{codebook:S.book,files:[`sh0.webp`]}},w=[[`means_l.webp`,u(c,a,o)],[`means_u.webp`,u(l,a,o)],[`scales.webp`,u(f,a,o)],[`sh0.webp`,u(m,a,o)]];if(i||w.push([`quats.webp`,u(p,a,o)]),n.rest){let e=n.rest.length/r/3,{centroids:t,labels:i,count:c}=_(n.rest,r,e*3),l=h(t),f=Math.ceil(c/64),p=new Uint8Array(64*e*f*4).fill(255),m=s();for(let t=0;t<c;t++)for(let n=0;n<e;n++)for(let r=0;r<3;r++)p[((t>>6)*64*e+(t&63)*e+n)*4+r]=l.index[(t*e+n)*3+r];for(let e=0;e<r;e++)m[e*4]=i[e]&255,m[e*4+1]=i[e]>>8,m[e*4+2]=0;C.shN={count:c,bands:e===24?4:d[e],codebook:l.book,files:[`shN_centroids.webp`,`shN_labels.webp`]},w.push([`shN_centroids.webp`,u(p,64*e,f)]),w.push([`shN_labels.webp`,u(m,a,o)])}return w.unshift([`meta.json`,new TextEncoder().encode(JSON.stringify(C))]),v(w)}function _(e,t,n){let r=new Uint16Array(t);if(t<=65536){for(let e=0;e<t;e++)r[e]=e;return{centroids:e,labels:r,count:t}}let i=new Float64Array(n);for(let r=0;r<t;r++)for(let a=0;a<n;a++)i[a]+=e[r*n+a]/t;let a=new Float64Array(n).fill(1/Math.sqrt(n));for(let r=0;r<8;r++){let r=new Float64Array(n);for(let o=0;o<t;o++){let t=0;for(let r=0;r<n;r++)t+=(e[o*n+r]-i[r])*a[r];for(let a=0;a<n;a++)r[a]+=t*(e[o*n+a]-i[a])}let o=Math.hypot(...r)||1;a=r.map(e=>e/o)}let o=new Float32Array(t);for(let r=0;r<t;r++)for(let t=0;t<n;t++)o[r]+=e[r*n+t]*a[t];let s=Uint32Array.from({length:t},(e,t)=>t).sort((e,t)=>o[e]-o[t]),c=65536,l=new Float32Array(c*n),u=new Uint32Array(c);for(let i=0;i<t;i++){let a=s[i],o=Math.floor(i*c/t);r[a]=o,u[o]++;for(let t=0;t<n;t++)l[o*n+t]+=e[a*n+t]}for(let e=0;e<c;e++)for(let t=0;t<n;t++)l[e*n+t]/=u[e]||1;return{centroids:l,labels:r,count:c}}function v(e){let t=new TextEncoder,n=e.map(([e])=>t.encode(e)),r=e.reduce((e,[,t],r)=>e+30+n[r].length+t.length+46+n[r].length,22),a=new Uint8Array(r),o=new DataView(a.buffer),s=[],c=[],l=0;e.forEach(([,e],t)=>{c.push(i(e)),s.push(l),o.setUint32(l,67324752,!0),o.setUint16(l+4,20,!0),o.setUint32(l+14,c[t],!0),o.setUint32(l+18,e.length,!0),o.setUint32(l+22,e.length,!0),o.setUint16(l+26,n[t].length,!0),a.set(n[t],l+30),a.set(e,l+30+n[t].length),l+=30+n[t].length+e.length});let u=l;return e.forEach(([,e],t)=>{o.setUint32(l,33639248,!0),o.setUint16(l+4,20,!0),o.setUint16(l+6,20,!0),o.setUint32(l+16,c[t],!0),o.setUint32(l+20,e.length,!0),o.setUint32(l+24,e.length,!0),o.setUint16(l+28,n[t].length,!0),o.setUint32(l+42,s[t],!0),a.set(n[t],l+46),l+=46+n[t].length}),o.setUint32(l,101010256,!0),o.setUint16(l+8,e.length,!0),o.setUint16(l+10,e.length,!0),o.setUint32(l+12,l-u,!0),o.setUint32(l+16,u,!0),a}export{g as encodeSog,f as encodeSpz};
@@ -0,0 +1,40 @@
1
+ import type { SplatData } from './data.js';
2
+ /** Options for {@link encodeSpz}. */
3
+ export interface EncodeSpzOptions {
4
+ /**
5
+ * Fractional bits of the 24-bit fixed-point positions (the step is 2^-bits). Default: the most that fit the cloud's
6
+ * largest coordinate, up to 16 (12, the format's usual value, holds coordinates to 2,048).
7
+ */
8
+ fractionalBits?: number;
9
+ /** Sets the header's antialiased flag (bit 0 of byte 14), for clouds trained with an anti-aliasing filter. */
10
+ antialiased?: boolean;
11
+ }
12
+ /**
13
+ * Encodes a cloud as an SPZ file (version 3: a gzip stream of a 16-byte header and the attributes), which `parseSpz`
14
+ * and SPZ version 3 readers decode. Positions are 24-bit fixed point, opacity, colour and log scale one byte each,
15
+ * rotations the smallest-three 10-bit packing and spherical harmonics one signed byte per coefficient.
16
+ * @throws RangeError when `data` fails `validateSplats`, a coordinate does not fit 24-bit fixed point at the chosen
17
+ * fractional bits, or `fractionalBits` is not 0 to 23; MargoError `'unsupported'` without `CompressionStream`.
18
+ * @example
19
+ * const bytes = await encodeSpz(await cloud.read());
20
+ */
21
+ export declare function encodeSpz(data: SplatData, options?: EncodeSpzOptions): Promise<Uint8Array<ArrayBuffer>>;
22
+ /**
23
+ * A 256-entry codebook for `values` and the nearest entry of each value: each distinct value (up to float rounding)
24
+ * its own entry when there are at most 256, else 1D k-means started at the quantiles. Entries are increasing.
25
+ */
26
+ export declare function codebook(values: Float32Array): {
27
+ book: number[];
28
+ index: Uint8Array;
29
+ };
30
+ /**
31
+ * Encodes a cloud as a bundled SOG scene (a ZIP of `meta.json` and lossless WebP textures), which
32
+ * `parseSog` decodes. Version 3 is selected for degree 4 or opacity above 1; otherwise version 2. Positions are 16-bit after a log transform within the cloud's bounds;
33
+ * log scales and base colours are 256-entry codebooks; rotations are the smallest-three in bytes; opacity is a byte;
34
+ * spherical harmonic bands are a palette of up to 65,536 entries (each splat's own when the cloud has at most that
35
+ * many, else groups along the bands' principal axis) quantised with a 256-entry codebook.
36
+ * @throws RangeError when `data` fails `validateSplats`.
37
+ * @example
38
+ * const bytes = await encodeSog(await cloud.read());
39
+ */
40
+ export declare function encodeSog(data: SplatData): Promise<Uint8Array<ArrayBuffer>>;
@@ -0,0 +1,24 @@
1
+ import { type SplatData } from './data.js';
2
+ /**
3
+ * Reads complete KSplat version 0.1 captures, compression 0 (float32), 1 (half) and 2 (half plus byte SH).
4
+ * Supports multiple sections, full and partial spatial buckets, section capacities and SH degrees 0 to 2.
5
+ * A mixed-degree file is promoted to its largest degree with zero missing higher bands.
6
+ * @throws RangeError for incomplete or inconsistent headers, counts, bucket tables or attributes.
7
+ */
8
+ export declare function parseKsplat(input: ArrayBuffer | ArrayBufferView): SplatData;
9
+ /**
10
+ * Reads SuperSplat compressed PLY: 256-splat chunks, packed position/rotation/scale/colour, optional colour ranges
11
+ * and channel-major uchar SH through degree 3. Returns ordinary linear-colour SplatData for every renderer entry.
12
+ */
13
+ export declare function parseCompressedPly(input: ArrayBuffer | ArrayBufferView): SplatData;
14
+ /** Options for encodePly. */
15
+ export interface EncodePlyOptions {
16
+ /** Standard PLY encoding. Default binary_little_endian. */
17
+ format?: 'binary_little_endian' | 'ascii';
18
+ }
19
+ /**
20
+ * Writes standard Gaussian PLY including full SH, log scales, wxyz rotation and logit opacity.
21
+ * Values retain float32 precision in binary or decimal round-trip precision in ASCII. Opacity endpoints use
22
+ * IEEE infinity logits, preserving exact 0 and 1 when read. No splats are dropped or reordered.
23
+ */
24
+ export declare function encodePly(data: SplatData, options?: EncodePlyOptions): Uint8Array<ArrayBuffer>;
@@ -0,0 +1,5 @@
1
+ import{_ as e,f as t,n}from"./data-D31W24Wu.js";import{MargoError as r}from"@margoengine/math/errors";var i=.2820947918;function a(e){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw TypeError(`Pass an ArrayBuffer or typed array containing the complete splat file`)}function o(e,t=0){if(!Number.isInteger(e)||e<1||e>3e6)throw RangeError(`Use a capture with 1 to 3,000,000 splats`);return{count:e,positions:new Float32Array(e*3),logScales:new Float32Array(e*3),rotations:new Float32Array(e*4),dc:new Float32Array(e*3),alphas:new Float32Array(e),...t?{rest:new Float32Array(e*((t+1)**2-1)*3)}:{}}}function s(e){let t=e&32768?-1:1,n=e>>>10&31,r=e&1023;return t*(n===0?r*2**-24:n===31?r?NaN:1/0:(1+r/1024)*2**(n-15))}function c(t){let n=a(t),r=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n.length<4096||n[0]!==0||n[1]!==1)throw RangeError(`Expected a complete KSplat version 0.1 file; re-export this capture`);let c=r.getUint32(4,!0),l=r.getUint32(8,!0),u=r.getUint32(16,!0),d=r.getUint16(20,!0);if(c<l||l<1||4096+c*1024>n.length||d>2||r.getUint32(12,!0)<u)throw RangeError(`KSplat section table or compression level is invalid; check the complete file`);let f=[],p=0,m=0;for(let e=0;e<l;e++){let t=4096+e*1024,n=r.getUint32(t,!0),i=r.getUint32(t+4,!0),a=r.getUint16(t+40,!0);if(n>i||i>3e6||a>2)throw RangeError(`Invalid KSplat section capacity or SH degree; re-export the capture`);p=Math.max(p,a),m+=n;let o=(d?24:44)+((a+1)**2-1)*3*(d===0?4:d===1?2:1);f.push({header:t,count:n,capacity:i,degree:a,stride:o,size:r.getUint32(t+28,!0),bucketSize:r.getUint32(t+8,!0),buckets:r.getUint32(t+12,!0),full:r.getUint32(t+32,!0),partial:r.getUint32(t+36,!0),block:r.getFloat32(t+16,!0),range:r.getUint32(t+24,!0)||32767,bucketBytes:r.getUint16(t+20,!0)})}if(m!==u)throw RangeError(`KSplat section counts disagree with its header; download the complete capture`);let h=o(u,p),g=(p+1)**2-1,_=r.getFloat32(36,!0),v=r.getFloat32(40,!0);if(d===2&&(!Number.isFinite(_)||!Number.isFinite(v)||_>v))throw RangeError(`KSplat SH range is invalid; re-export the capture`);let y=4096+c*1024,b=0;for(let e of f){let t=e.partial*4,a=y+t,o=a+e.buckets*e.bucketBytes;if(y+e.size>n.length||o+e.capacity*e.stride>y+e.size||e.size<1)throw RangeError(`KSplat section runs outside the file; download the complete capture`);let c=[];if(d){if(e.full+e.partial!==e.buckets||e.bucketSize<1||e.bucketBytes<12||!(e.block>0)||!Number.isFinite(e.block)||e.range<1)throw RangeError(`Invalid KSplat spatial bucket table; re-export this capture`);for(let t=0;t<e.buckets;t++){let n=t<e.full?e.bucketSize:r.getUint32(y+(t-e.full)*4,!0);if(n<1||n>e.bucketSize)throw RangeError(`KSplat partial bucket length is invalid; re-export this capture`);c.push(n)}if(c.reduce((e,t)=>e+t,0)!==e.capacity)throw RangeError(`KSplat bucket lengths disagree with its capacity; check the file`)}let l=0,u=c[0]??e.capacity,f=e.block/(2*e.range);for(let t=0;t<e.count;t++,b++){for(;t>=u;)u+=c[++l];let p=o+t*e.stride;for(let t=0;t<3;t++){h.positions[b*3+t]=d?r.getFloat32(a+l*e.bucketBytes+t*4,!0)+(r.getUint16(p+t*2,!0)-e.range)*f:r.getFloat32(p+t*4,!0);let o=d?s(r.getUint16(p+6+t*2,!0)):r.getFloat32(p+12+t*4,!0);if(!(o>0)||!Number.isFinite(o))throw RangeError(`KSplat axis scale must be finite and positive; re-export this capture`);h.logScales[b*3+t]=Math.log(o),h.dc[b*3+t]=(n[p+(d?20:40)+t]/255-.5)/i}h.alphas[b]=n[p+(d?23:43)]/255;for(let e=0;e<4;e++)h.rotations[b*4+e]=d?s(r.getUint16(p+12+e*2,!0)):r.getFloat32(p+24+e*4,!0);if(h.rest){let t=p+(d?24:44),i=d===0?4:d===1?2:1;for(let a=1;a<=e.degree;a++)for(let e=0;e<3;e++)for(let o=0;o<2*a+1;o++){let c=t+((a*a-1)*3+e*(2*a+1)+o)*i;h.rest[(b*g+a*a-1+o)*3+e]=d===0?r.getFloat32(c,!0):d===1?s(r.getUint16(c,!0)):_+n[c]/255*(v-_)}}}y+=e.size}if(y!==n.length)throw RangeError(`KSplat has trailing or missing sections; check the complete file`);return e(h)}var l={float:4,float32:4,uint:4,uint32:4,uchar:1,uint8:1};function u(e){let t=new TextDecoder(`latin1`).decode(e.subarray(0,65536)),n=/^end_header\r?\n/m.exec(t);if(!t.startsWith(`ply
2
+ `)&&!t.startsWith(`ply\r
3
+ `)||!n)throw RangeError(`Expected a complete PLY header under 64 KiB; check the file`);let i=n.index+n[0].length,a=t.slice(0,i);if(!/^format binary_little_endian 1\.0\r?$/m.test(a))throw new r(`unsupported`,`Compressed PLY requires binary_little_endian 1.0; re-export this capture`);let o=/* @__PURE__ */ new Map,s;for(let e of a.split(/\r?\n/)){let t=e.trim().split(/\s+/);if(t[0]===`element`){if(o.has(t[1]))throw RangeError(`PLY elements must have unique names; fix the header`);let e=Number(t[2]);if(!Number.isInteger(e)||e<0||e>3e6)throw RangeError(`PLY element count must be between 0 and 3,000,000; check the header`);s={name:t[1],count:e,stride:0,offset:0,properties:/* @__PURE__ */ new Map},o.set(t[1],s)}else if(t[0]===`property`&&s){if(!l[t[1]]||s.properties.has(t[2]))throw RangeError(`Compressed PLY needs unique scalar float, uint and uchar properties; fix the header`);s.properties.set(t[2],{offset:s.stride,type:t[1]}),s.stride+=l[t[1]]}}let c=i;for(let e of o.values())e.offset=c,c+=e.count*e.stride;if(c!==e.length)throw RangeError(`Compressed PLY byte length disagrees with its header; download the complete file`);return o}function d(t){let n=a(t),r=u(n),s=r.get(`chunk`),c=r.get(`vertex`),l=r.get(`sh`);if(!s||!c||s.count!==Math.ceil(c.count/256))throw RangeError(`Compressed PLY needs one chunk per 256 vertices; check the header`);let d=new DataView(n.buffer,n.byteOffset,n.byteLength),f=(e,t,r,i)=>{let a=e.properties.get(r);if(!a||!{float:[`float`,`float32`],uint:[`uint`,`uint32`],uchar:[`uchar`,`uint8`]}[i].includes(a.type))throw RangeError(`Compressed PLY property ${r} is missing or has the wrong type; re-export this capture`);let o=e.offset+t*e.stride+a.offset;return i===`float`?d.getFloat32(o,!0):i===`uint`?d.getUint32(o,!0):n[o]},p=l?l.properties.size/3:0,m=Math.sqrt(p+1)-1;if(![0,1,2,3].includes(m)||l&&l.count!==c.count)throw RangeError(`Compressed PLY SH needs 9, 24 or 45 bytes per vertex; check the sh element`);let h=o(c.count,m),g=s.properties.has(`min_r`),_=(e,t)=>t===0?(e>>>21)/2047:t===1?(e>>>11&1023)/1023:(e&2047)/2047,v=(e,t,n)=>e+(t-e)*n;for(let e=0;e<c.count;e++){let t=Math.floor(e/256),n=f(c,e,`packed_position`,`uint`),r=f(c,e,`packed_scale`,`uint`),a=f(c,e,`packed_rotation`,`uint`),o=f(c,e,`packed_color`,`uint`);for(let a=0;a<3;a++){let c=[`x`,`y`,`z`][a],l=f(s,t,`min_${c}`,`float`),u=f(s,t,`max_${c}`,`float`),d=f(s,t,`min_scale_${c}`,`float`),p=f(s,t,`max_scale_${c}`,`float`);if(![l,u,d,p].every(Number.isFinite)||u<l||p<d)throw RangeError(`Compressed PLY bounds are invalid; re-export the capture`);h.positions[e*3+a]=v(l,u,_(n,a)),h.logScales[e*3+a]=v(d,p,_(r,a));let m=[`r`,`g`,`b`][a],y=g?f(s,t,`min_${m}`,`float`):0,b=g?f(s,t,`max_${m}`,`float`):1;if(!Number.isFinite(y)||!Number.isFinite(b)||y>b)throw RangeError(`Compressed PLY colour bounds are invalid; re-export the capture`);h.dc[e*3+a]=(v(y,b,(o>>>24-a*8&255)/255)-.5)/i}h.alphas[e]=(o&255)/255;let u=a>>>30,d=[0,0,0,0],m=0,y=0;for(let e=0;e<4;e++)if(e!==u){let t=((a>>>20-y++*10&1023)/1023-.5)*Math.SQRT2;d[e]=t,m+=t*t}if(d[u]=Math.sqrt(Math.max(0,1-m)),h.rotations.set(d,e*4),l&&h.rest)for(let t=0;t<3;t++)for(let n=0;n<p;n++){let r=f(l,e,`f_rest_${t*p+n}`,`uchar`);h.rest[(e*p+n)*3+t]=r===0?-4:r===255?4:((r+.5)/256-.5)*8}}return e(h)}function f(e,r={}){let i=n(e),a=r.format??`binary_little_endian`;if(a!==`binary_little_endian`&&a!==`ascii`)throw RangeError(`Choose binary_little_endian or ascii as the PLY format`);if(e.colors.some((e,t)=>t%4==3&&e>1))throw RangeError(`Gaussian PLY logit opacity cannot exceed 1; use SOG for this cloud`);let o=t(e),s=(o.rest?.length??0)/i/3,c=[`x`,`y`,`z`,`nx`,`ny`,`nz`,`f_dc_0`,`f_dc_1`,`f_dc_2`,...Array.from({length:s*3},(e,t)=>`f_rest_${t}`),`opacity`,`scale_0`,`scale_1`,`scale_2`,`rot_0`,`rot_1`,`rot_2`,`rot_3`],l=new TextEncoder().encode(`ply\nformat ${a} 1.0\nelement vertex ${i}\n${c.map(e=>`property float ${e}\n`).join(``)}end_header\n`),u=a===`binary_little_endian`?new Uint8Array(l.length+i*c.length*4):void 0,d=u?new DataView(u.buffer):void 0,f=[];u?.set(l);for(let e=0;e<i;e++){let t=[...o.positions.subarray(e*3,e*3+3),0,0,0,...o.dc.subarray(e*3,e*3+3)];if(o.rest)for(let n=0;n<3;n++)for(let r=0;r<s;r++)t.push(o.rest[(e*s+r)*3+n]);let n=o.alphas[e];if(t.push(Math.log(n/(1-n)),...o.logScales.subarray(e*3,e*3+3),...o.rotations.subarray(e*4,e*4+4)),d)for(let n=0;n<t.length;n++)d.setFloat32(l.length+(e*c.length+n)*4,t[n],!0);else f.push(t.map(e=>String(Math.fround(e))).join(` `))}if(u)return u;let p=new TextEncoder().encode(f.join(`
4
+ `)+`
5
+ `),m=new Uint8Array(l.length+p.length);return m.set(l),m.set(p,l.length),m}export{f as encodePly,d as parseCompressedPly,c as parseKsplat};