@margoengine/splats 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +546 -2
- package/dist/animate.d.ts +138 -0
- package/dist/animate.js +31 -0
- package/dist/brush.d.ts +148 -0
- package/dist/brush.js +36 -0
- package/dist/compat-CDoDsXE8.js +19 -0
- package/dist/compat.d.ts +7 -0
- package/dist/compressed-Bfvhv63J.js +1 -0
- package/dist/compressed.d.ts +40 -0
- package/dist/data-BDt3mxGg.js +2 -0
- package/dist/data.d.ts +28 -0
- package/dist/data.js +1 -0
- package/dist/depth.d.ts +42 -0
- package/dist/depth.js +14 -0
- package/dist/edit.d.ts +48 -0
- package/dist/encode-BfG7xkVn.js +1 -0
- package/dist/encode.d.ts +40 -0
- package/dist/formats.d.ts +24 -0
- package/dist/formats.js +5 -0
- package/dist/index.d.ts +182 -0
- package/dist/index.js +1 -0
- package/dist/lighting.d.ts +89 -0
- package/dist/lighting.js +48 -0
- package/dist/lod-sog.d.ts +44 -0
- package/dist/lod-sog.js +1 -0
- package/dist/lod.d.ts +129 -0
- package/dist/lod.js +4 -0
- package/dist/modify.d.ts +83 -0
- package/dist/modify.js +24 -0
- package/dist/pick.d.ts +75 -0
- package/dist/pick.js +14 -0
- package/dist/ply.d.ts +62 -0
- package/dist/progressive.d.ts +37 -0
- package/dist/progressive.js +5 -0
- package/dist/scene-scope-C5HWuOIb.js +4 -0
- package/dist/session.d.ts +127 -0
- package/dist/session.js +1 -0
- package/dist/set.d.ts +59 -0
- package/dist/set.js +4 -0
- package/dist/shader-B7zZyYz-.js +64 -0
- package/dist/shader.d.ts +17 -0
- package/dist/shared/fog.d.ts +33 -0
- package/dist/shared/pass.d.ts +53 -0
- package/dist/sog-TlM17j4y.js +1 -0
- package/dist/sog.d.ts +20 -0
- package/dist/sort.d.ts +4 -0
- package/dist/spz-ivoWSN9h.js +1 -0
- package/dist/spz.d.ts +23 -0
- package/dist/src-BxooDRB9.js +48 -0
- package/dist/view-DyJeX8rJ.js +1 -0
- package/dist/view-rect-G-t2gTqO.js +1 -0
- package/dist/webp.d.ts +11 -0
- package/dist/zip-Cgj7EvkG.js +1 -0
- package/dist/zip.d.ts +7 -0
- package/dist/zstd-BPbUkXlY.js +1 -0
- package/package.json +105 -4
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
3
|
+
import { type Engine, type EnginePlugin, type FrameGraph, type PassContext } from '@margoengine/core/extension';
|
|
4
|
+
import { type SplatData } from './data.js';
|
|
5
|
+
import type { Splats } from './index.js';
|
|
6
|
+
type Context = Extract<PassContext, {
|
|
7
|
+
backend: 'webgpu';
|
|
8
|
+
}>;
|
|
9
|
+
/** Options of {@link SplatSequence}. */
|
|
10
|
+
export interface SplatSequenceOptions {
|
|
11
|
+
/** Frames per second of the capture. Default 30. */
|
|
12
|
+
fps?: number;
|
|
13
|
+
/** Start again after the last frame (true, the default) or hold it. */
|
|
14
|
+
loop?: boolean;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* WGSL of the sequence pass: frames a and b (per splat: centre and opacity, two covariance vec4s, colour) mixed by
|
|
18
|
+
* `u.mix.x` into the cloud's positions, covariances and colours.
|
|
19
|
+
*/
|
|
20
|
+
export declare const sequenceShader = "struct Mix {mix:vec4f,counts:vec4u}\n@group(0) @binding(0) var<uniform> u:Mix;\n@group(0) @binding(1) var<storage,read> a:array<vec4f>;\n@group(0) @binding(2) var<storage,read> b:array<vec4f>;\n@group(0) @binding(3) var<storage,read_write> positions:array<vec4f>;\n@group(0) @binding(4) var<storage,read_write> covariances:array<vec4f>;\n@group(0) @binding(5) var<storage,read_write> colors:array<vec4f>;\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 t=u.mix.x;\n positions[i]=mix(a[i*4],b[i*4],t);covariances[i*2]=mix(a[i*4+1],b[i*4+1],t);covariances[i*2+1]=mix(a[i*4+2],b[i*4+2],t);\n colors[i]=mix(a[i*4+3],b[i*4+3],t);\n}";
|
|
21
|
+
/** The plugin plumbing both players share: setup checks, the pass at order -7.5, dispose. */
|
|
22
|
+
declare abstract class Player implements EnginePlugin {
|
|
23
|
+
abstract readonly name: string;
|
|
24
|
+
readonly cloud: Splats;
|
|
25
|
+
protected engine?: Engine;
|
|
26
|
+
protected device?: GPUDevice;
|
|
27
|
+
protected uniform?: GPUBuffer;
|
|
28
|
+
protected pipeline?: GPUComputePipeline;
|
|
29
|
+
protected buffers: GPUBuffer[];
|
|
30
|
+
protected dead: boolean;
|
|
31
|
+
constructor(cloud: Splats, what: string);
|
|
32
|
+
setup(engine: Engine): void;
|
|
33
|
+
protected buffer(size: number, usage: number, data?: Float32Array | Uint32Array): GPUBuffer;
|
|
34
|
+
protected compute(code: string): GPUComputePipeline;
|
|
35
|
+
registerPasses(graph: FrameGraph): void;
|
|
36
|
+
/** Writes the pose into the cloud's inputs; `first` is the frame's first view (time advances once a frame). */
|
|
37
|
+
protected abstract pose(c: Context, first: boolean): void;
|
|
38
|
+
protected run(e: GPUCommandEncoder, group: GPUBindGroup): void;
|
|
39
|
+
protected release(): void;
|
|
40
|
+
onDeviceRestored(engine: Engine): void;
|
|
41
|
+
/** True once disposed. */
|
|
42
|
+
get disposed(): boolean;
|
|
43
|
+
dispose(): void;
|
|
44
|
+
[Symbol.dispose]: () => void;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Plays a 4D splat capture: `SplatSequence.attach(engine, cloud, frames, { fps })`, with `frames` a list of clouds of
|
|
48
|
+
* the cloud's splats in the same order. Each frame the cloud draws the mix of the two frames around `time` (centres,
|
|
49
|
+
* covariances, colours and opacity; SH stays the cloud's). `playing`, `time` and `speed` are live. All frames live on
|
|
50
|
+
* the GPU, 64 bytes per splat each. WebGPU only, as `Splats`.
|
|
51
|
+
* @throws TypeError when `cloud` is not a Splats; RangeError for no frames, a frame of another splat count or an
|
|
52
|
+
* invalid one, or an fps that is not above 0; MargoError `'unsupported'` on a WebGL engine.
|
|
53
|
+
*/
|
|
54
|
+
export declare class SplatSequence extends Player {
|
|
55
|
+
private static next;
|
|
56
|
+
readonly name: string;
|
|
57
|
+
/** Frames per second of the capture. */
|
|
58
|
+
readonly fps: number;
|
|
59
|
+
/** Start again after the last frame, or hold it. Live. */
|
|
60
|
+
loop: boolean;
|
|
61
|
+
/** Play time in seconds, advanced by each frame's delta times `speed` while `playing`. Live. */
|
|
62
|
+
time: number;
|
|
63
|
+
/** Play rate (1 real time, negative backwards). Live. */
|
|
64
|
+
speed: number;
|
|
65
|
+
/** Advance `time` each frame. Live. */
|
|
66
|
+
playing: boolean;
|
|
67
|
+
private readonly frames;
|
|
68
|
+
private readonly values;
|
|
69
|
+
private readonly integers;
|
|
70
|
+
private groups;
|
|
71
|
+
private gpuFrames;
|
|
72
|
+
constructor(cloud: Splats, frames: readonly SplatData[], options?: SplatSequenceOptions);
|
|
73
|
+
/** Same as `engine.use(new SplatSequence(cloud, frames, options))`; returns it. */
|
|
74
|
+
static attach(engine: EngineKernel, cloud: Splats, frames: readonly SplatData[], options?: SplatSequenceOptions): SplatSequence;
|
|
75
|
+
/** Number of frames. */
|
|
76
|
+
get length(): number;
|
|
77
|
+
/** Length of the capture in seconds: frames / fps. */
|
|
78
|
+
get duration(): number;
|
|
79
|
+
/**
|
|
80
|
+
* Moves `time` by `delta` seconds times `speed` while `playing`, without drawing (a delta of 0 or less moves
|
|
81
|
+
* nothing). Each frame update runs it, so `seek` from `@margoengine/cutscene/seek` replays it exactly.
|
|
82
|
+
*/
|
|
83
|
+
advanceTime(delta: number): void;
|
|
84
|
+
onPreUpdate(delta: number): void;
|
|
85
|
+
/** The two frames and the mix between them at `time` (looped or held). */
|
|
86
|
+
sample(time?: number): {
|
|
87
|
+
from: number;
|
|
88
|
+
to: number;
|
|
89
|
+
mix: number;
|
|
90
|
+
};
|
|
91
|
+
setup(engine: Engine): void;
|
|
92
|
+
protected pose(c: Context, first: boolean): void;
|
|
93
|
+
protected release(): void;
|
|
94
|
+
}
|
|
95
|
+
/** Options of {@link SplatSkin}. */
|
|
96
|
+
export interface SplatSkinOptions {
|
|
97
|
+
/** Joint count: `matrices` holds 16 floats for each. */
|
|
98
|
+
joints: number;
|
|
99
|
+
/** Four joint indices per splat (unused slots take weight 0). */
|
|
100
|
+
indices: ArrayLike<number>;
|
|
101
|
+
/** Four weights per splat; each splat's are normalised to sum 1 (all zero keeps the splat at rest). */
|
|
102
|
+
weights: ArrayLike<number>;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* WGSL of the skinning pass: the rest pose (copied from the cloud when bound) times the blend of up to four joint
|
|
106
|
+
* matrices per splat, centres by the whole matrix and covariances by its linear part, A S A^T.
|
|
107
|
+
*/
|
|
108
|
+
export declare const skinShader = "struct Skin {counts:vec4u}\n@group(0) @binding(0) var<uniform> u:Skin;\n@group(0) @binding(1) var<storage,read> matrices:array<mat4x4f>;\n@group(0) @binding(2) var<storage,read> influence:array<vec4f>;\n@group(0) @binding(3) var<storage,read> restPositions:array<vec4f>;\n@group(0) @binding(4) var<storage,read> restCovariances:array<vec4f>;\n@group(0) @binding(5) var<storage,read_write> positions:array<vec4f>;\n@group(0) @binding(6) var<storage,read_write> covariances:array<vec4f>;\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 j=bitcast<vec4u>(influence[i*2]);let w=influence[i*2+1];\n var m=matrices[j.x]*w.x+matrices[j.y]*w.y+matrices[j.z]*w.z+matrices[j.w]*w.w;\n if(w.x+w.y+w.z+w.w<=0){m=mat4x4f(vec4f(1,0,0,0),vec4f(0,1,0,0),vec4f(0,0,1,0),vec4f(0,0,0,1));}\n let p=restPositions[i];positions[i]=vec4f((m*vec4f(p.xyz,1)).xyz,positions[i].w);\n let a=restCovariances[i*2];let b=restCovariances[i*2+1];let s=mat3x3f(vec3f(a.x,a.y,a.z),vec3f(a.y,a.w,b.x),vec3f(a.z,b.x,b.y));\n let l=mat3x3f(m[0].xyz,m[1].xyz,m[2].xyz);let c=l*s*transpose(l);\n covariances[i*2]=vec4f(c[0].x,c[0].y,c[0].z,c[1].y);covariances[i*2+1]=vec4f(c[1].z,c[2].z,0,0);\n}";
|
|
109
|
+
/**
|
|
110
|
+
* Poses a splat cloud with a skeleton by linear blend skinning: `const skin = SplatSkin.attach(engine, cloud,
|
|
111
|
+
* { joints, indices, weights })`, then set `skin.matrices` (16 floats per joint, column-major, rest space to posed
|
|
112
|
+
* world) each frame, from `@margoengine/animation` or your own rig. The cloud's centres and covariances when it is
|
|
113
|
+
* first posed (or after `rebind()`) are the rest pose; opacity and colours are kept. WebGPU only, as `Splats`.
|
|
114
|
+
* @throws TypeError when `cloud` is not a Splats; RangeError for a joint count outside 1 to 65,536, indices or
|
|
115
|
+
* weights of another length than 4 per splat, an index outside the joints, or a negative or non-finite weight;
|
|
116
|
+
* MargoError `'unsupported'` on a WebGL engine.
|
|
117
|
+
*/
|
|
118
|
+
export declare class SplatSkin extends Player {
|
|
119
|
+
private static next;
|
|
120
|
+
readonly name: string;
|
|
121
|
+
/** Joint matrices, 16 floats per joint (identity at first), read every frame. Live: write into it. */
|
|
122
|
+
readonly matrices: Float32Array;
|
|
123
|
+
private readonly influence;
|
|
124
|
+
private matrixBuffer?;
|
|
125
|
+
private restPositions?;
|
|
126
|
+
private restCovariances?;
|
|
127
|
+
private bound?;
|
|
128
|
+
private stale;
|
|
129
|
+
constructor(cloud: Splats, options: SplatSkinOptions);
|
|
130
|
+
/** Same as `engine.use(new SplatSkin(cloud, options))`; returns it. */
|
|
131
|
+
static attach(engine: EngineKernel, cloud: Splats, options: SplatSkinOptions): SplatSkin;
|
|
132
|
+
/** Takes the cloud's current centres and covariances as the rest pose on the next frame (after `Splats.write`). */
|
|
133
|
+
rebind(): this;
|
|
134
|
+
setup(engine: Engine): void;
|
|
135
|
+
protected pose(c: Context): void;
|
|
136
|
+
protected release(): void;
|
|
137
|
+
}
|
|
138
|
+
export {};
|
package/dist/animate.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
const t=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
|
+
import{n as e}from"./data-BDt3mxGg.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as n}from"@margoengine/math/errors";var r=`struct Mix {mix:vec4f,counts:vec4u}
|
|
5
|
+
@group(0) @binding(0) var<uniform> u:Mix;
|
|
6
|
+
@group(0) @binding(1) var<storage,read> a:array<vec4f>;
|
|
7
|
+
@group(0) @binding(2) var<storage,read> b:array<vec4f>;
|
|
8
|
+
@group(0) @binding(3) var<storage,read_write> positions:array<vec4f>;
|
|
9
|
+
@group(0) @binding(4) var<storage,read_write> covariances:array<vec4f>;
|
|
10
|
+
@group(0) @binding(5) var<storage,read_write> colors:array<vec4f>;
|
|
11
|
+
@compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u) {
|
|
12
|
+
let i=id.x;if(i>=u.counts.x){return;}let t=u.mix.x;
|
|
13
|
+
positions[i]=mix(a[i*4],b[i*4],t);covariances[i*2]=mix(a[i*4+1],b[i*4+1],t);covariances[i*2+1]=mix(a[i*4+2],b[i*4+2],t);
|
|
14
|
+
colors[i]=mix(a[i*4+3],b[i*4+3],t);
|
|
15
|
+
}`;function i(t,n){if(e(t)!==n)throw RangeError(`Every sequence frame needs ${n} splats, as the cloud has; pass frames of the same splats`);let r=new Float32Array(n*16);for(let e=0;e<n;e++)r.set(t.positions.subarray(e*3,e*3+3),e*16),r[e*16+3]=t.colors[e*4+3],r.set(t.covariances.subarray(e*6,e*6+6),e*16+4),r.set(t.colors.subarray(e*4,e*4+4),e*16+12);return r}var a=class{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);constructor(e,t){if(this.buffers=[],this.dead=!1,!e||typeof e!=`object`||!(`gpuState`in e))throw TypeError(`${t} needs a Splats cloud`);this.cloud=e}setup(e){if(this.dead||!e.gpu)throw new n(this.dead?`disposed`:`unsupported`,`Splat animation needs WebGPU; attach a new player to a WebGPU engine; see https://margoengine.com/errors#webgpu`);this.engine=e,this.device=e.gpu,this.uniform=this.buffer(256,GPUBufferUsage.UNIFORM)}buffer(e,t,n){let r=this.device.createBuffer({size:Math.max(16,e),usage:t|GPUBufferUsage.COPY_DST});return n&&this.device.queue.writeBuffer(r,0,n),this.buffers.push(r),r}compute(e){return this.pipeline??=this.device.createComputePipeline({layout:`auto`,compute:{module:this.device.createShaderModule({code:e}),entryPoint:`main`}})}registerPasses(e){e.add({name:this.name,order:-7.5,execute:e=>{e.backend===`webgpu`&&this.cloud.attached&&this.pose(e,!e.view?.index)}})}run(e,t){let n=e.beginComputePass();n.setPipeline(this.pipeline),n.setBindGroup(0,t),n.dispatchWorkgroups(Math.ceil(this.cloud.count/256)),n.end()}release(){for(let e of this.buffers)e.destroy();this.buffers=[],this.uniform=this.pipeline=void 0}onDeviceRestored(e){this.release(),this.setup(e)}get disposed(){return this.dead}dispose(){this.dead||(this.dead=!0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.release(),this.engine=this.device=void 0)}[Symbol.dispose??Symbol()](){this.dispose()}},o=class e extends a{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static{this.next=0}constructor(t,n,r={}){if(super(t,`SplatSequence`),this.name=`splats-sequence:`+e.next++,this.time=0,this.speed=1,this.playing=!0,this.values=/* @__PURE__ */ new Float32Array(8),this.integers=new Uint32Array(this.values.buffer),this.groups=[],this.gpuFrames=[],!Array.isArray(n)||!n.length)throw RangeError(`SplatSequence needs one frame or more; pass a list of clouds`);let a=r.fps??30;if(!(a>0&&Number.isFinite(a)))throw RangeError(`SplatSequence fps must be above 0; pass the capture rate`);this.fps=a,this.loop=r.loop??!0,this.frames=n.map(e=>i(e,t.count))}static attach(n,r,i,a={}){__margoAssertCore(n,__margoCoreRequirement("1.0.0",import.meta.url));let o=new e(r,i,a);return t(n).use(o),o}get length(){return this.frames.length}get duration(){return this.frames.length/this.fps}advanceTime(e){e>0&&this.playing&&(this.time+=e*this.speed)}onPreUpdate(e){this.advanceTime(e)}sample(e=this.time){let t=this.frames.length,n=e*this.fps;n=this.loop?(n%t+t)%t:Math.min(Math.max(n,0),t-1);let r=Math.floor(n);return{from:r,to:this.loop?(r+1)%t:Math.min(r+1,t-1),mix:n-r}}setup(e){super.setup(e),this.gpuFrames=this.frames.map(e=>this.buffer(e.byteLength,GPUBufferUsage.STORAGE,e)),this.groups=[]}pose(e,t){let{from:n,to:i,mix:a}=this.sample(),o=this.cloud.gpuState,s=this.compute(r),c=this.groups[n*this.frames.length+i];(!c||c.positions!==o.positions)&&(c={group:this.device.createBindGroup({layout:s.getBindGroupLayout(0),entries:[this.uniform,this.gpuFrames[n],this.gpuFrames[i],o.positions,o.covariances,o.inputColors].map((e,t)=>({binding:t,resource:{buffer:e}}))}),positions:o.positions},this.groups[n*this.frames.length+i]=c),this.values[0]=a,this.integers[4]=this.cloud.count,this.device.queue.writeBuffer(this.uniform,0,this.values),this.run(e.encoder,c.group)}release(){super.release(),this.gpuFrames=[],this.groups=[]}},s=`struct Skin {counts:vec4u}
|
|
16
|
+
@group(0) @binding(0) var<uniform> u:Skin;
|
|
17
|
+
@group(0) @binding(1) var<storage,read> matrices:array<mat4x4f>;
|
|
18
|
+
@group(0) @binding(2) var<storage,read> influence:array<vec4f>;
|
|
19
|
+
@group(0) @binding(3) var<storage,read> restPositions:array<vec4f>;
|
|
20
|
+
@group(0) @binding(4) var<storage,read> restCovariances:array<vec4f>;
|
|
21
|
+
@group(0) @binding(5) var<storage,read_write> positions:array<vec4f>;
|
|
22
|
+
@group(0) @binding(6) var<storage,read_write> covariances:array<vec4f>;
|
|
23
|
+
@compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u) {
|
|
24
|
+
let i=id.x;if(i>=u.counts.x){return;}let j=bitcast<vec4u>(influence[i*2]);let w=influence[i*2+1];
|
|
25
|
+
var m=matrices[j.x]*w.x+matrices[j.y]*w.y+matrices[j.z]*w.z+matrices[j.w]*w.w;
|
|
26
|
+
if(w.x+w.y+w.z+w.w<=0){m=mat4x4f(vec4f(1,0,0,0),vec4f(0,1,0,0),vec4f(0,0,1,0),vec4f(0,0,0,1));}
|
|
27
|
+
let p=restPositions[i];positions[i]=vec4f((m*vec4f(p.xyz,1)).xyz,positions[i].w);
|
|
28
|
+
let a=restCovariances[i*2];let b=restCovariances[i*2+1];let s=mat3x3f(vec3f(a.x,a.y,a.z),vec3f(a.y,a.w,b.x),vec3f(a.z,b.x,b.y));
|
|
29
|
+
let l=mat3x3f(m[0].xyz,m[1].xyz,m[2].xyz);let c=l*s*transpose(l);
|
|
30
|
+
covariances[i*2]=vec4f(c[0].x,c[0].y,c[0].z,c[1].y);covariances[i*2+1]=vec4f(c[1].z,c[2].z,0,0);
|
|
31
|
+
}`,c=class e extends a{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static{this.next=0}constructor(t,n){super(t,`SplatSkin`),this.name=`splats-skin:`+e.next++,this.stale=!0;let{joints:r,indices:i,weights:a}=n??{},o=t.count;if(!Number.isInteger(r)||r<1||r>65536)throw RangeError(`SplatSkin needs 1 to 65,536 joints; pass the joint count`);if(i?.length!==o*4||a?.length!==o*4)throw RangeError(`SplatSkin needs 4 joint indices and 4 weights per splat (${o*4} each); pass one set per splat`);this.matrices=new Float32Array(r*16);for(let e=0;e<r;e++)this.matrices[e*16]=this.matrices[e*16+5]=this.matrices[e*16+10]=this.matrices[e*16+15]=1;this.influence=new Float32Array(o*8);let s=new Uint32Array(this.influence.buffer);for(let e=0;e<o;e++){let t=0;for(let n=0;n<4;n++){let o=i[e*4+n],c=a[e*4+n];if(!Number.isInteger(o)||o<0||o>=r)throw RangeError(`SplatSkin joint index ${o} is outside 0 to ${r-1}; fix the indices`);if(!(c>=0&&Number.isFinite(c)))throw RangeError(`SplatSkin weights must be finite and 0 or more; fix the weights`);s[e*8+n]=o,t+=c}for(let n=0;n<4;n++)this.influence[e*8+4+n]=t>0?a[e*4+n]/t:0}}static attach(n,r,i){__margoAssertCore(n,__margoCoreRequirement("1.0.0",import.meta.url));let a=new e(r,i);return t(n).use(a),a}rebind(){return this.stale=!0,this}setup(e){super.setup(e),this.matrixBuffer=this.buffer(this.matrices.byteLength,GPUBufferUsage.STORAGE),this.restPositions=this.buffer(this.cloud.count*16,GPUBufferUsage.STORAGE),this.restCovariances=this.buffer(this.cloud.count*32,GPUBufferUsage.STORAGE),this.bound=void 0,this.stale=!0}pose(e){let t=this.cloud.gpuState,n=this.device,r=this.compute(s),i=this.cloud.count;if(!this.bound||this.bound.positions!==t.positions){let e=this.buffer(this.influence.byteLength,GPUBufferUsage.STORAGE,this.influence);this.bound={group:n.createBindGroup({layout:r.getBindGroupLayout(0),entries:[this.uniform,this.matrixBuffer,e,this.restPositions,this.restCovariances,t.positions,t.covariances].map((e,t)=>({binding:t,resource:{buffer:e}}))}),positions:t.positions},this.stale=!0}this.stale&&=(e.encoder.copyBufferToBuffer(t.positions,0,this.restPositions,0,i*16),e.encoder.copyBufferToBuffer(t.covariances,0,this.restCovariances,0,i*32),!1),n.queue.writeBuffer(this.uniform,0,new Uint32Array([i,0,0,0])),n.queue.writeBuffer(this.matrixBuffer,0,this.matrices),this.run(e.encoder,this.bound.group)}release(){super.release(),this.matrixBuffer=this.restPositions=this.restCovariances=this.bound=void 0}};export{o as SplatSequence,c as SplatSkin,r as sequenceShader,s as skinShader};
|
package/dist/brush.d.ts
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
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
|
+
/** Options of a {@link SplatBrush}. */
|
|
33
|
+
export interface SplatBrushOptions {
|
|
34
|
+
/**
|
|
35
|
+
* How many strokes `undo` can take back, 0 or more; the oldest is dropped past it. Each kept stroke holds a GPU copy
|
|
36
|
+
* of what it changed: 32 bytes a splat for an erase, 16 bytes plus the SH (4 bytes per coefficient) for a paint.
|
|
37
|
+
* Default 32.
|
|
38
|
+
*/
|
|
39
|
+
readonly history?: number;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* GPU picking and brush editing of a splat cloud: `const brush = SplatBrush.attach(engine, cloud)`, then
|
|
43
|
+
* `await brush.pick(x, y)`, `brush.select(region)`, `brush.erase('selection')` or `brush.paint(region, [1, 0, 0])`
|
|
44
|
+
* in pixels of the last drawn frame. Edits change the cloud's GPU buffers at once (shown from the next frame);
|
|
45
|
+
* `await brush.commit()` copies them into the cloud's data (`Splats.read`), which export and device restoration use.
|
|
46
|
+
* Erase and paint keep a stroke history on the GPU: edits between `beginStroke()` and `endStroke()` are one stroke (an
|
|
47
|
+
* edit outside a stroke is a stroke of its own), `undo()` takes the last stroke back and `reset()` restores the cloud
|
|
48
|
+
* as it was before the first edit. Selections are not strokes. The history copies whole buffers, so a `cloud.write`
|
|
49
|
+
* made between strokes is taken back with the stroke after it. WebGPU, or the WebGL2 compatibility layer, as `Splats`.
|
|
50
|
+
* @throws TypeError when `cloud` is not a Splats; MargoError `'unsupported'` on a WebGL engine, `'disposed'` after
|
|
51
|
+
* `dispose()`, `'state'` before the cloud has drawn a frame.
|
|
52
|
+
*/
|
|
53
|
+
export declare class SplatBrush implements EnginePlugin {
|
|
54
|
+
private static next;
|
|
55
|
+
readonly name: string;
|
|
56
|
+
readonly cloud: Splats;
|
|
57
|
+
private engine?;
|
|
58
|
+
private device?;
|
|
59
|
+
private width;
|
|
60
|
+
private height;
|
|
61
|
+
private readonly data;
|
|
62
|
+
private readonly integers;
|
|
63
|
+
private uniform?;
|
|
64
|
+
private result?;
|
|
65
|
+
private mask?;
|
|
66
|
+
private pipeline?;
|
|
67
|
+
private group?;
|
|
68
|
+
private dead;
|
|
69
|
+
private readonly limit;
|
|
70
|
+
private steps;
|
|
71
|
+
private original?;
|
|
72
|
+
private stroke?;
|
|
73
|
+
private stroking;
|
|
74
|
+
/** @throws RangeError for a `history` that is not a whole number of 0 or more. */
|
|
75
|
+
constructor(cloud: Splats, options?: SplatBrushOptions);
|
|
76
|
+
/** Same as `engine.use(new SplatBrush(cloud, options))`; returns it. */
|
|
77
|
+
static attach(engine: EngineKernel, cloud: Splats, options?: SplatBrushOptions): SplatBrush;
|
|
78
|
+
/** Strokes `undo` can take back. */
|
|
79
|
+
get strokes(): number;
|
|
80
|
+
/** Whether a stroke is open (`beginStroke` without its `endStroke`). */
|
|
81
|
+
get inStroke(): boolean;
|
|
82
|
+
/**
|
|
83
|
+
* Starts a stroke: every erase and paint until `endStroke()` is taken back by one `undo()`, as one drag of a brush
|
|
84
|
+
* tool. An open stroke ends first.
|
|
85
|
+
*/
|
|
86
|
+
beginStroke(): this;
|
|
87
|
+
/** Ends the open stroke, if any. */
|
|
88
|
+
endStroke(): this;
|
|
89
|
+
/**
|
|
90
|
+
* Takes back the last stroke (ending an open one first), restoring the positions, opacities, colours and SH it
|
|
91
|
+
* changed. Returns false when there is nothing to undo.
|
|
92
|
+
* @throws MargoError `'disposed'` after `dispose()`.
|
|
93
|
+
*/
|
|
94
|
+
undo(): boolean;
|
|
95
|
+
/**
|
|
96
|
+
* Restores the cloud as it was before the brush's first erase or paint (the scan as loaded, or as last written
|
|
97
|
+
* before that edit) and clears the stroke history. Does nothing before any edit.
|
|
98
|
+
* @throws MargoError `'disposed'` after `dispose()`.
|
|
99
|
+
*/
|
|
100
|
+
reset(): this;
|
|
101
|
+
/** Width and height in pixels of the frame the cloud last drew, the space of every region and pick; 0 before. */
|
|
102
|
+
get frame(): [number, number];
|
|
103
|
+
setup(engine: Engine): void;
|
|
104
|
+
registerPasses(graph: FrameGraph): void;
|
|
105
|
+
/**
|
|
106
|
+
* The index of the nearest splat drawn at pixel (`x`, `y`) whose own opacity there (its Gaussian falloff times its
|
|
107
|
+
* opacity) reaches `threshold`, or -1 when none does.
|
|
108
|
+
* @throws RangeError for a threshold outside 0 to 1 or a non-finite pixel.
|
|
109
|
+
*/
|
|
110
|
+
pick(x: number, y: number, threshold?: number): Promise<number>;
|
|
111
|
+
/**
|
|
112
|
+
* Selects the splats in `region` ('all' for every splat, 'none' for none), replacing the selection, adding to it or
|
|
113
|
+
* taking from it.
|
|
114
|
+
* @throws RangeError for an invalid region or mode.
|
|
115
|
+
*/
|
|
116
|
+
select(region: BrushRegion | 'all' | 'none', mode?: SelectMode): this;
|
|
117
|
+
/** The indices of the selected splats, in order. */
|
|
118
|
+
selection(): Promise<Uint32Array>;
|
|
119
|
+
/** Hides the target's splats (opacity 0), as `Splats.clear` does. The selection is kept. */
|
|
120
|
+
erase(target?: BrushTarget): this;
|
|
121
|
+
/**
|
|
122
|
+
* Blends the target's colour toward `color` (linear RGB, each 0 to 1) by `strength` (0 to 1); opacity is kept.
|
|
123
|
+
* @throws RangeError for a colour or strength outside 0 to 1.
|
|
124
|
+
*/
|
|
125
|
+
paint(target: BrushTarget, color: ArrayLike<number>, strength?: number): this;
|
|
126
|
+
/** Copies the GPU edits into the cloud's data and returns it: `cloud.read()`. */
|
|
127
|
+
commit(): Promise<SplatData>;
|
|
128
|
+
/** Checks the state and writes the region, ready for a dispatch; returns the device. */
|
|
129
|
+
private ready;
|
|
130
|
+
private submit;
|
|
131
|
+
/** Whether a snapshot was taken of the cloud's current buffers (not before a device restore or re-attach). */
|
|
132
|
+
private live;
|
|
133
|
+
/** The live input buffer of a snapshot part. */
|
|
134
|
+
private source;
|
|
135
|
+
/** Copies the `wanted` live buffers into `step` where it holds none yet, in `e`, before the edit. */
|
|
136
|
+
private keep;
|
|
137
|
+
/** Records what an erase or paint is about to change: the cloud before the first edit, and the stroke's step. */
|
|
138
|
+
private remember;
|
|
139
|
+
/** Copies a snapshot back into the live buffers. */
|
|
140
|
+
private restore;
|
|
141
|
+
private drop;
|
|
142
|
+
/** Drops the whole history and the copy of the cloud before the first edit. */
|
|
143
|
+
private forget;
|
|
144
|
+
private run;
|
|
145
|
+
onDeviceRestored(engine: Engine): void;
|
|
146
|
+
dispose(): void;
|
|
147
|
+
[Symbol.dispose]: () => void;
|
|
148
|
+
}
|
package/dist/brush.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
const t=(engine,version="1.0.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=[`positions`,`colors`,`sh`],o=class o{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static{this.next=0}constructor(e,t={}){if(this.name=`splats-brush:`+o.next++,this.width=0,this.height=0,this.data=/* @__PURE__ */ new Float32Array(32),this.integers=new Uint32Array(this.data.buffer),this.dead=!1,this.steps=[],this.stroking=!1,!e||typeof e!=`object`||!(`gpuState`in e))throw TypeError(`SplatBrush needs a Splats cloud`);let n=t?.history??32;if(!(Number.isInteger(n)&&n>=0))throw RangeError(`SplatBrush history must be a whole number of strokes, 0 or more`);this.cloud=e,this.limit=n}static attach(e,n,r){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let i=new o(n,r);return t(e).use(i),i}get strokes(){return this.steps.length}get inStroke(){return this.stroking}beginStroke(){return this.endStroke(),this.stroking=!0,this}endStroke(){return this.stroking=!1,this.stroke=void 0,this}undo(){if(this.endStroke(),this.dead)throw new n(`disposed`,`SplatBrush is disposed; attach a new one`);let e=this.steps.pop();return e?(this.live(e)&&this.restore(e),this.drop(e),!0):!1}reset(){if(this.endStroke(),this.dead)throw new n(`disposed`,`SplatBrush is disposed; attach a new one`);for(let e of this.steps)this.drop(e);return this.steps=[],this.original&&this.live(this.original)&&this.restore(this.original),this}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(e===3||e===4)&&this.remember(r,e===3?[`positions`,`colors`]:[`colors`,`sh`]),this.run(r,e),n.queue.submit([r.finish()]),this}live(e){return!!this.device&&this.cloud.attached&&e.owner===this.cloud.gpuState.positions}source(e){let t=this.cloud.gpuState;return e===`positions`?t.positions:e===`colors`?t.inputColors:t.sh}keep(e,t,n){for(let r of n){if(t[r]||r===`sh`&&!this.cloud.coefficients)continue;let n=this.source(r),i=this.device.createBuffer({size:n.size,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST});e.copyBufferToBuffer(n,0,i,0,n.size),t[r]=i}}remember(e,t){let n=this.cloud.gpuState.positions;if(this.original?.owner!==n&&(this.forget(),this.original={owner:n},this.keep(e,this.original,a)),!this.limit)return;let r=this.stroking?this.stroke:void 0;r||(r={owner:n},this.steps.push(r),this.steps.length>this.limit&&this.drop(this.steps.shift()),this.stroking&&(this.stroke=r)),this.keep(e,r,t)}restore(e){let t=this.device.createCommandEncoder();for(let n of a){let r=e[n];r&&t.copyBufferToBuffer(r,0,this.source(n),0,r.size)}this.device.queue.submit([t.finish()])}drop(e){for(let t of a)e[t]?.destroy()}forget(){for(let e of this.steps)this.drop(e);this.original&&this.drop(this.original),this.steps=[],this.original=this.stroke=void 0}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.steps=[],this.original=this.stroke=void 0,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.forget(),this.uniform=this.result=this.mask=this.pipeline=this.group=this.device=this.engine=void 0}}[Symbol.dispose??Symbol()](){this.dispose()}};export{o 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};
|
package/dist/compat.d.ts
ADDED
|
@@ -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 @@
|
|
|
1
|
+
async function e(e,t){return(await import(`./spz-ivoWSN9h.js`).then(e=>e.n)).parseSpz(e,t)}async function t(e,t){return(await import(`./sog-TlM17j4y.js`).then(e=>e.n)).parseSog(e,t)}async function n(e,t){return(await import(`./encode-BfG7xkVn.js`)).encodeSpz(e,t)}async function r(e){return(await import(`./encode-BfG7xkVn.js`)).encodeSog(e)}export{e as i,n,t as r,r as t};
|
|
@@ -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 D(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=D(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=D(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}var _=(e,t)=>e.sphericalHarmonics?e.sphericalHarmonics.length/t/3:0;function v(e,t){let n=D(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 y(e,r,_(e,n))}function y(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 b(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 v(e,e=>a(o[e*3],o[e*3+1],o[e*3+2])!==r)}function x(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 S(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(x(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(x(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 C(e,t){let n=D(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=_(e,n),r=S(w(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 D(l),l}function w(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 T(...e){if(!e.length)throw RangeError(`mergeSplats needs at least one cloud`);let t=e.map(e=>D(e)),n=new Set(e.map((e,n)=>_(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 D(u),u}function E(e,t){let n=D(e),r=t?.cellSize;if(!(r>0&&r<1/0))throw RangeError(`decimateSplats needs a cellSize above 0, world units`);let i=_(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 D(p),p}function D(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 O(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 D(c),c}export{v as a,g as c,c as d,i as f,E as i,f as l,r as m,D as n,T as o,l as p,b as r,C as s,O as t,h as u};
|
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
|
+
import{a as e,c as t,d as n,i as r,l as i,n as a,o,p as s,r as c,s as l,t as u,u as d}from"./data-BDt3mxGg.js";import{i as f,n as p,r as m,t as h}from"./compressed-Bfvhv63J.js";export{t as attributesFromSplats,c as cropSplats,r as decimateSplats,i as decomposeCovariance,h as encodeSog,d as encodeSplat,p as encodeSpz,e as filterSplats,o as mergeSplats,n as parsePly,m as parseSog,u as parseSplat,f as parseSpz,s as splatsFromAttributes,l as transformSplats,a as validateSplats};
|
package/dist/depth.d.ts
ADDED
|
@@ -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 1.0.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
const t=(engine,version="1.0.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("1.0.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("1.0.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};
|