@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
package/dist/lod.d.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
3
|
+
import { type Engine, type EnginePlugin, type FrameGraph } from '@margoengine/core/extension';
|
|
4
|
+
import { type SplatData } from './data.js';
|
|
5
|
+
import { Splats } from './index.js';
|
|
6
|
+
/** One node of a {@link SplatLodSource}: a bounding sphere, its error and its children. */
|
|
7
|
+
export interface SplatLodNode {
|
|
8
|
+
/** Bounding sphere of the node's splat centres (and its children's), world units. */
|
|
9
|
+
readonly center: readonly [number, number, number];
|
|
10
|
+
readonly radius: number;
|
|
11
|
+
/** World-space size of the detail this node leaves out; 0 for a leaf (the trained splats). */
|
|
12
|
+
readonly error: number;
|
|
13
|
+
/** Splats in the node's own cloud. Zero denotes a structural node, refined unconditionally without loading. */
|
|
14
|
+
readonly count: number;
|
|
15
|
+
/** Indices of the child nodes; empty for a leaf. */
|
|
16
|
+
readonly children: readonly number[];
|
|
17
|
+
}
|
|
18
|
+
/** A splat hierarchy: node 0 is the root. `load` returns a node's cloud; it may fetch it. */
|
|
19
|
+
export interface SplatLodSource {
|
|
20
|
+
readonly nodes: readonly SplatLodNode[];
|
|
21
|
+
/** Spherical-harmonics coefficients per channel of every node's cloud: 0, 4, 9, 16 or 25. */
|
|
22
|
+
readonly coefficients: number;
|
|
23
|
+
load(index: number, signal: AbortSignal): Promise<SplatData>;
|
|
24
|
+
}
|
|
25
|
+
/** Options of {@link buildSplatLod}. */
|
|
26
|
+
export interface BuildSplatLodOptions {
|
|
27
|
+
/** Most splats in one node, leaf or inner. Default 65,536. */
|
|
28
|
+
leafSize?: number;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Builds an in-memory hierarchy from a capture: an octree of its splat centres split until a cell holds at most
|
|
32
|
+
* `leafSize` splats (leaves keep the splats untouched), and for each inner cell a moment-matched cloud of at most
|
|
33
|
+
* `leafSize` splats from its leaves, with the grid cell it merged as its error. A server can store each node's cloud
|
|
34
|
+
* (for instance with `encodeSplat`) and serve its own `SplatLodSource` with the same nodes.
|
|
35
|
+
* @throws RangeError when `data` is invalid or `leafSize` is under 64.
|
|
36
|
+
*/
|
|
37
|
+
export declare function buildSplatLod(data: SplatData, options?: BuildSplatLodOptions): SplatLodSource;
|
|
38
|
+
/** The view a {@link chooseSplatNodes} call refines for. */
|
|
39
|
+
export interface SplatLodView {
|
|
40
|
+
/** Camera position, world units. */
|
|
41
|
+
readonly eye: readonly [number, number, number];
|
|
42
|
+
/** Pixels per world unit at distance 1 (perspective: height / (2 tan(fov / 2))). */
|
|
43
|
+
readonly focal: number;
|
|
44
|
+
/** Nearest distance an error is projected from (the near plane). */
|
|
45
|
+
readonly near: number;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The cut of the tree to draw for `view`: starting at the root, the node with the largest projected error
|
|
49
|
+
* (`error * focal / distance`, in pixels) is replaced by its children while that error exceeds `maxError`, all its
|
|
50
|
+
* children are in `loaded` and the cut stays within `budget` splats. Returns the cut and the nodes to load next (the
|
|
51
|
+
* children that held a refinement back, largest error first).
|
|
52
|
+
*/
|
|
53
|
+
export declare function chooseSplatNodes(nodes: readonly SplatLodNode[], view: SplatLodView, options: {
|
|
54
|
+
maxError: number;
|
|
55
|
+
budget: number;
|
|
56
|
+
loaded: (index: number) => boolean;
|
|
57
|
+
maxNodes?: number;
|
|
58
|
+
}): {
|
|
59
|
+
selected: number[];
|
|
60
|
+
wanted: number[];
|
|
61
|
+
};
|
|
62
|
+
/** Options of {@link SplatLod}. */
|
|
63
|
+
export interface SplatLodOptions {
|
|
64
|
+
/**
|
|
65
|
+
* Most splats drawn at once (the GPU pool, rounded down to whole node slots and to no more slots than the source has
|
|
66
|
+
* leaves, the most nodes a cut can hold). Default 1,000,000.
|
|
67
|
+
*/
|
|
68
|
+
budget?: number;
|
|
69
|
+
/** Largest projected error left unrefined, in pixels. Default 2. */
|
|
70
|
+
maxError?: number;
|
|
71
|
+
/** Most node loads in flight. Default 4. */
|
|
72
|
+
concurrency?: number;
|
|
73
|
+
/** Most splats of loaded nodes kept on the CPU (drawn ones included). Default twice the budget. */
|
|
74
|
+
cache?: number;
|
|
75
|
+
/** Aborts every load; the hierarchy keeps what it has. */
|
|
76
|
+
signal?: AbortSignal;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* A streamed splat hierarchy: `SplatLod.attach(engine, source, options)`. Each frame, before the splats project, the
|
|
80
|
+
* view picks the cut (`chooseSplatNodes`), starts loads for the nodes it lacks, and writes changed nodes into the
|
|
81
|
+
* slots of `cloud`, one `Splats` of `budget` splats that sorts every drawn node together. `attach` attaches `cloud`
|
|
82
|
+
* too. WebGPU only.
|
|
83
|
+
* @throws RangeError for invalid options or a source whose nodes are invalid or larger than the budget; MargoError
|
|
84
|
+
* `'unsupported'` from attach on a WebGL engine.
|
|
85
|
+
*/
|
|
86
|
+
export declare class SplatLod implements EnginePlugin {
|
|
87
|
+
private static next;
|
|
88
|
+
readonly name: string;
|
|
89
|
+
/** The cloud every drawn node is written into. */
|
|
90
|
+
readonly cloud: Splats;
|
|
91
|
+
readonly source: SplatLodSource;
|
|
92
|
+
readonly maxError: number;
|
|
93
|
+
private readonly slot;
|
|
94
|
+
private readonly concurrency;
|
|
95
|
+
private readonly cacheSize;
|
|
96
|
+
private readonly abort;
|
|
97
|
+
private readonly loaded;
|
|
98
|
+
private readonly pending;
|
|
99
|
+
private readonly failures;
|
|
100
|
+
private readonly slots;
|
|
101
|
+
private readonly at;
|
|
102
|
+
private cut;
|
|
103
|
+
private used;
|
|
104
|
+
private waiters;
|
|
105
|
+
private disposed;
|
|
106
|
+
private engine?;
|
|
107
|
+
constructor(source: SplatLodSource, options?: SplatLodOptions);
|
|
108
|
+
static attach(engine: EngineKernel, source: SplatLodSource, options?: SplatLodOptions): SplatLod;
|
|
109
|
+
/** The nodes drawn now, in index order. */
|
|
110
|
+
get selected(): readonly number[];
|
|
111
|
+
/** Where each drawn node sits in `cloud`: node index to the pool index of its first splat (for picking or editing). */
|
|
112
|
+
get placement(): ReadonlyMap<number, number>;
|
|
113
|
+
/** Splats drawn now (sum of the selected nodes). */
|
|
114
|
+
get drawn(): number;
|
|
115
|
+
/** Loads in flight. */
|
|
116
|
+
get loading(): number;
|
|
117
|
+
/** Errors of loads that failed (the node stays unloaded and is not asked for again). */
|
|
118
|
+
get errors(): readonly unknown[];
|
|
119
|
+
/** Resolves after the next frame that drew a cut needing no load (the view is fully streamed in). */
|
|
120
|
+
settled(): Promise<void>;
|
|
121
|
+
setup(engine: Engine): void;
|
|
122
|
+
registerPasses(graph: FrameGraph): void;
|
|
123
|
+
private update;
|
|
124
|
+
private request;
|
|
125
|
+
/** Drops loaded nodes that are not drawn, oldest first, while the cache holds more than `cache` splats. */
|
|
126
|
+
private evict;
|
|
127
|
+
dispose(): void;
|
|
128
|
+
[Symbol.dispose]: () => void;
|
|
129
|
+
}
|
package/dist/lod.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
const r=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
|
+
import{i as e,n as t}from"./data-BDt3mxGg.js";import{t as n}from"./src-BxooDRB9.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as i}from"@margoengine/math/errors";function a(n,r={}){let i=t(n),a=r.leafSize??65536;if(!Number.isInteger(a)||a<64)throw RangeError(`buildSplatLod leafSize must be an integer of 64 or more`);let c=n.sphericalHarmonics?n.sphericalHarmonics.length/i/3:0,l=[],u=[],d=n.positions,f=new Uint32Array(i);for(let e=0;e<i;e++)f[e]=e;let p=(t,r,i,f)=>{let m=l.length;l.push(void 0),u.push(void 0);let h=[];if(t.length>a&&f<21){let e=i/2,n=new Uint8Array(t.length),a=/* @__PURE__ */ new Uint32Array(8);t.forEach((t,i)=>{let o=0;for(let n=0;n<3;n++)d[t*3+n]>=r[n]+e&&(o|=1<<n);n[i]=o,a[o]++});for(let i=0;i<8;i++){if(!a[i])continue;let o=new Uint32Array(a[i]),s=0;t.forEach((e,t)=>{n[t]===i&&(o[s++]=e)}),h.push(p(o,[0,1,2].map(t=>r[t]+(i>>t&1)*e),e,f+1))}h.length===1&&l[h[0]].children.length===0&&f>=20&&(h=[])}let g=o(n,t,c),_=g,v=0;if(h.length)for(let t=i/64;_=e(g,{cellSize:t}),v=t,!(_.positions.length/3<=a);t*=2);let y=s(_.positions,h.map(e=>l[e]));return l[m]={center:y.center,radius:y.radius,error:v,count:_.positions.length/3,children:h},u[m]=_,m},m=[1/0,1/0,1/0],h=[-1/0,-1/0,-1/0];for(let e=0;e<i;e++)for(let t=0;t<3;t++)m[t]=Math.min(m[t],d[e*3+t]),h[t]=Math.max(h[t],d[e*3+t]);return p(f,m,Math.max(h[0]-m[0],h[1]-m[1],h[2]-m[2])*(1+1e-6)||1,0),{nodes:l,coefficients:c,load:(e,t)=>t.aborted?Promise.reject(t.reason):u[e]?Promise.resolve(u[e]):Promise.reject(/* @__PURE__ */ RangeError(`No splat node ${e}`))}}function o(e,t,n){let r=t.length,i=new Float32Array(r*3),a=new Float32Array(r*6),o=new Float32Array(r*4),s=n?new Float32Array(r*n*3):void 0,c=n*3;return t.forEach((t,n)=>{i.set(e.positions.subarray(t*3,t*3+3),n*3),a.set(e.covariances.subarray(t*6,t*6+6),n*6),o.set(e.colors.subarray(t*4,t*4+4),n*4),s&&s.set(e.sphericalHarmonics.subarray(t*c,t*c+c),n*c)}),{positions:i,covariances:a,colors:o,...s?{sphericalHarmonics:s}:{}}}function s(e,t){let n=[1/0,1/0,1/0],r=[-1/0,-1/0,-1/0];for(let t=0;t<e.length;t+=3)for(let i=0;i<3;i++)n[i]=Math.min(n[i],e[t+i]),r[i]=Math.max(r[i],e[t+i]);for(let e of t)for(let t=0;t<3;t++)n[t]=Math.min(n[t],e.center[t]-e.radius),r[t]=Math.max(r[t],e.center[t]+e.radius);let i=[0,1,2].map(e=>(n[e]+r[e])/2),a=0;for(let t=0;t<e.length;t+=3)a=Math.max(a,(e[t]-i[0])**2+(e[t+1]-i[1])**2+(e[t+2]-i[2])**2);let o=Math.sqrt(a);for(let e of t)o=Math.max(o,Math.hypot(e.center[0]-i[0],e.center[1]-i[1],e.center[2]-i[2])+e.radius);return{center:i,radius:o}}function c(e,t,n){let r=[];if(!e.length)return{selected:[],wanted:r};if(!n.loaded(0))return{selected:[],wanted:[0]};let i=n=>{let r=e[n];if(!r.children.length)return 0;if(!r.count)return 1/0;let i=Math.hypot(r.center[0]-t.eye[0],r.center[1]-t.eye[1],r.center[2]-t.eye[2])-r.radius;return r.error*t.focal/Math.max(i,t.near)},a=[[i(0),0]],o=[],s=e[0].count,c=+(e[0].count>0);for(;a.length;){a.sort((e,t)=>t[0]-e[0]||e[1]-t[1]);let[t,l]=a.shift(),u=e[l];if(t<=n.maxError){o.push(l,...a.map(e=>e[1]));break}let d=u.children.filter(e=>!n.loaded(e)),f=s-u.count+u.children.reduce((t,n)=>t+e[n].count,0),p=c-+(u.count>0)+u.children.filter(t=>e[t].count>0).length;if(d.length||f>n.budget||p>(n.maxNodes??1/0))d.length&&f<=n.budget&&p<=(n.maxNodes??1/0)&&r.push(...d),o.push(l);else{s=f,c=p;for(let e of u.children)a.push([i(e),e])}}return{selected:o.sort((e,t)=>e-t),wanted:r}}var l=class e{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static{this.next=0}constructor(t,r={}){this.name=`splats-lod:`+e.next++,this.abort=new AbortController,this.loaded=/* @__PURE__ */ new Map,this.pending=/* @__PURE__ */ new Set,this.failures=[],this.at=/* @__PURE__ */ new Map,this.cut=[],this.used=0,this.waiters=[],this.disposed=!1;let i=t?.nodes;if(!Array.isArray(i)||!i.length||typeof t.load!=`function`)throw TypeError(`SplatLod needs a source with nodes and load(index, signal)`);if(![0,4,9,16,25].includes(t.coefficients))throw RangeError(`SplatLod source coefficients must be 0, 4, 9, 16 or 25`);let a=r.budget??1e6;this.maxError=r.maxError??2,this.concurrency=r.concurrency??4;for(let[e,t,n]of[[`budget`,a,1],[`maxError`,this.maxError,0],[`concurrency`,this.concurrency,1]])if(!(t>=n)||!Number.isFinite(t))throw RangeError(`SplatLod ${e} must be ${n} or more`);let o=0;if(i.forEach((e,t)=>{if(!(e.count>=0)||!e.count&&!e.children.length||!Number.isInteger(e.count)||!(e.radius>=0)||!(e.error>=0)||e.children.some(e=>!(e>t&&e<i.length)))throw RangeError(`SplatLod node ${t} is invalid (count, radius, error, or a child that is not a later node); give each node a count of 1 or more and only later children`);o=Math.max(o,e.count)}),o>a)throw RangeError(`SplatLod budget ${a} is under the largest node, ${o} splats; raise the budget or split the node`);this.source=t,this.slot=o;let s=i.filter(e=>!e.children.length).length;this.slots=Array(Math.min(Math.floor(a/o),s)).fill(void 0);let c=e=>i[e].count?1:i[e].children.reduce((e,t)=>e+c(t),0);if(c(0)>this.slots.length)throw RangeError(`SplatLod budget needs at least ${c(0)*o} splats to cover all structural branches; raise budget`);this.cacheSize=r.cache??this.slots.length*o*2,this.cloud=n.reserve(this.slots.length*o,t.coefficients),r.signal?.addEventListener(`abort`,()=>this.abort.abort(r.signal.reason),{once:!0})}static attach(t,n,i={}){__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));let a=new e(n,i),o=r(t);return o.use(a.cloud),o.use(a),a}get selected(){return this.cut}get placement(){let e=/* @__PURE__ */ new Map;for(let[t,n]of this.at)e.set(t,n*this.slot);return e}get drawn(){return this.used}get loading(){return this.pending.size}get errors(){return this.failures}settled(){return new Promise(e=>this.waiters.push(e))}setup(e){if(this.disposed||!e.gpu)throw new i(this.disposed?`disposed`:`unsupported`,`SplatLod needs WebGPU and a live hierarchy; attach a new SplatLod to a WebGPU engine; see https://margoengine.com/errors#webgpu`);this.engine=e}registerPasses(e){e.add({name:this.name,order:-8,execute:e=>{e.backend===`webgpu`&&this.update(e)}})}update(e){let t=e.height/(2*Math.tan(e.camera.fov*Math.PI/360)),n={eye:e.camera.position,focal:t,near:e.camera.near},{selected:r,wanted:i}=c(this.source.nodes,n,{maxError:this.maxError,budget:this.slots.length*this.slot,loaded:e=>this.loaded.has(e),maxNodes:this.slots.length});for(let e of i)this.request(e);let a=new Set(r);for(let e of this.cut)if(!a.has(e)&&this.source.nodes[e].count){let t=this.at.get(e);this.cloud.clear(t*this.slot,this.slot),this.slots[t]=void 0,this.at.delete(e)}for(let e of r)if(this.source.nodes[e].count&&!this.at.has(e)){let t=this.slots.indexOf(void 0);this.slots[t]=e,this.at.set(e,t),this.cloud.clear(t*this.slot,this.slot),this.source.nodes[e].count&&this.cloud.write(t*this.slot,this.loaded.get(e))}if(this.cut=r,this.used=r.reduce((e,t)=>e+this.source.nodes[t].count,0),this.evict(a),!i.length&&!this.pending.size&&this.waiters.length){let e=this.waiters;this.waiters=[];for(let t of e)t()}}request(e){this.source.nodes[e].count?this.pending.has(e)||this.pending.size>=this.concurrency||this.abort.signal.aborted||this.failures.some(t=>t.node===e)||(this.pending.add(e),this.source.load(e,this.abort.signal).then(n=>{if(this.pending.delete(e),this.disposed)return;let r=t(n),i=n.sphericalHarmonics?n.sphericalHarmonics.length/r/3:0;r!==this.source.nodes[e].count||i!==this.source.coefficients?this.failures.push(Object.assign(/* @__PURE__ */ RangeError(`Splat node ${e} loaded ${r} splats with ${i} SH coefficients, not ${this.source.nodes[e].count} with ${this.source.coefficients}`),{node:e})):this.loaded.set(e,n)},t=>{this.pending.delete(e),this.abort.signal.aborted||this.failures.push(Object.assign(t instanceof Error?t:Error(String(t)),{node:e}))})):this.loaded.set(e,{positions:/* @__PURE__ */ new Float32Array,covariances:/* @__PURE__ */ new Float32Array,colors:/* @__PURE__ */ new Float32Array})}evict(e){let t=0;for(let e of this.loaded.keys())t+=this.source.nodes[e].count;for(let n of[...this.loaded.keys()]){if(t<=this.cacheSize)break;e.has(n)||n===0||(this.loaded.delete(n),t-=this.source.nodes[n].count)}}dispose(){if(!this.disposed){this.disposed=!0,this.abort.abort(new i(`disposed`,`The SplatLod was disposed`)),this.engine?.sceneOf(this)?.removePlugin(this.name),this.engine=void 0,this.cloud.dispose(),this.loaded.clear();for(let e of this.waiters)e();this.waiters=[]}}[Symbol.dispose??Symbol()](){this.dispose()}};export{l as SplatLod,a as buildSplatLod,c as chooseSplatNodes};
|
package/dist/modify.d.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
3
|
+
import { type Engine, type EnginePlugin, type FrameGraph } from '@margoengine/core/extension';
|
|
4
|
+
import { type SplatData } from './data.js';
|
|
5
|
+
import type { Splats } from './index.js';
|
|
6
|
+
/** WGSL function bodies of a per-frame splat modifier. All hooks can read time, delta and u.parameters[0..15]. */
|
|
7
|
+
export interface SplatModifierOptions {
|
|
8
|
+
/** WGSL body returning vec3f; arguments index:u32 and position:vec3f (canonical centre). Default return position. */
|
|
9
|
+
position?: string;
|
|
10
|
+
/** WGSL body returning f32; arguments index:u32, position:vec3f (modified) and opacity:f32 (canonical). Default return opacity. */
|
|
11
|
+
opacity?: string;
|
|
12
|
+
/** WGSL body returning vec3f; arguments index:u32, position:vec3f (modified) and color:vec3f (evaluated linear SH/fog). Default return color. */
|
|
13
|
+
color?: string;
|
|
14
|
+
/** Shared WGSL functions/constants, appended to both modules. Default empty. */
|
|
15
|
+
declarations?: string;
|
|
16
|
+
/** Initial values of the 64 live parameter floats. Default all zero; remaining floats are zero. */
|
|
17
|
+
parameters?: ArrayLike<number>;
|
|
18
|
+
/** Cancels creation and disposes the modifier when aborted. */
|
|
19
|
+
signal?: AbortSignal;
|
|
20
|
+
}
|
|
21
|
+
/** Builds the pre-projection position/opacity and post-projection colour compute modules. */
|
|
22
|
+
export declare function splatModifierShaders(options?: SplatModifierOptions): {
|
|
23
|
+
position: string;
|
|
24
|
+
color: string;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* A GPU modifier with independent position, opacity and evaluated-colour hooks. Create/attach asynchronously to
|
|
28
|
+
* snapshot canonical centres and opacity once. Geometry runs before projection/sorting; colour runs after SH/fog
|
|
29
|
+
* and before relighting. Source colours, SH and covariances are preserved. Each frame starts at the canonical data.
|
|
30
|
+
*/
|
|
31
|
+
export declare class SplatModifier implements EnginePlugin {
|
|
32
|
+
private static next;
|
|
33
|
+
readonly name: string;
|
|
34
|
+
readonly cloud: Splats;
|
|
35
|
+
/** 64 live floats, exposed to WGSL as u.parameters:array<vec4f,16>. */
|
|
36
|
+
readonly parameters: Float32Array<ArrayBuffer>;
|
|
37
|
+
/** Effect clock in seconds; manually seek while playing is false. Default 0. */
|
|
38
|
+
time: number;
|
|
39
|
+
/** Advance time once per frame. Default true. */
|
|
40
|
+
playing: boolean;
|
|
41
|
+
/** Clock multiplier, including negative playback. Default 1. */
|
|
42
|
+
speed: number;
|
|
43
|
+
/** False restores canonical geometry and skips colour modification. Default true. */
|
|
44
|
+
enabled: boolean;
|
|
45
|
+
private readonly canonical;
|
|
46
|
+
private readonly shaders;
|
|
47
|
+
private readonly values;
|
|
48
|
+
private readonly integers;
|
|
49
|
+
private engine?;
|
|
50
|
+
private device?;
|
|
51
|
+
private uniform?;
|
|
52
|
+
private rest?;
|
|
53
|
+
private pipelines;
|
|
54
|
+
private groups;
|
|
55
|
+
private bound?;
|
|
56
|
+
private evaluated?;
|
|
57
|
+
private dead;
|
|
58
|
+
private readonly signal?;
|
|
59
|
+
private readonly abort?;
|
|
60
|
+
private constructor();
|
|
61
|
+
/** Snapshots a cloud's current GPU/CPU data once, with caller cancellation; returns an unattached plugin. */
|
|
62
|
+
static create(cloud: Splats, options?: SplatModifierOptions): Promise<SplatModifier>;
|
|
63
|
+
/** Creates the canonical snapshot, then attaches the modifier to engine. */
|
|
64
|
+
static attach(engine: EngineKernel, cloud: Splats, options?: SplatModifierOptions): Promise<SplatModifier>;
|
|
65
|
+
/** Replaces canonical centres/opacity from a complete cloud of the same count. Other attributes remain the cloud's. */
|
|
66
|
+
setRest(data: SplatData): this;
|
|
67
|
+
setup(engine: Engine): void;
|
|
68
|
+
registerPasses(graph: FrameGraph): void;
|
|
69
|
+
private run;
|
|
70
|
+
/** True after disposal. */
|
|
71
|
+
get disposed(): boolean;
|
|
72
|
+
private release;
|
|
73
|
+
/**
|
|
74
|
+
* Moves `time` by `delta` seconds times `speed` while `playing`, without drawing (a delta of 0 or less moves
|
|
75
|
+
* nothing). Each frame update runs it, so `seek` from `@margoengine/cutscene/seek` replays it exactly.
|
|
76
|
+
*/
|
|
77
|
+
advanceTime(delta: number): void;
|
|
78
|
+
onPreUpdate(delta: number): void;
|
|
79
|
+
onDeviceRestored(engine: Engine): void;
|
|
80
|
+
/** Restores canonical centres/opacity, removes the passes and releases GPU buffers. Idempotent. */
|
|
81
|
+
dispose(): void;
|
|
82
|
+
[Symbol.dispose]: () => void;
|
|
83
|
+
}
|
package/dist/modify.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
const n=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
|
+
import{n as e}from"./data-BDt3mxGg.js";import{t}from"./scene-scope-C5HWuOIb.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as r}from"@margoengine/math/errors";function i(e={}){for(let t of[`position`,`opacity`,`color`,`declarations`])if(e[t]!==void 0&&(typeof e[t]!=`string`||t!==`declarations`&&!e[t].trim()))throw TypeError(`Splat modifier hooks must be nonempty WGSL strings; pass function bodies returning the documented types`);let t=`struct ModifierFrame {clock:vec4f,counts:vec4u,parameters:array<vec4f,16>}
|
|
5
|
+
@group(0) @binding(0) var<uniform> u:ModifierFrame;
|
|
6
|
+
${e.declarations??``}`,n=`let time=u.clock.x;let delta=u.clock.y;`;return{position:t+`
|
|
7
|
+
@group(0) @binding(1) var<storage,read> canonical:array<vec4f>;
|
|
8
|
+
@group(0) @binding(2) var<storage,read_write> positions:array<vec4f>;
|
|
9
|
+
@group(0) @binding(3) var<storage,read_write> sourceColors:array<vec4f>;
|
|
10
|
+
fn modifyPosition(index:u32,position:vec3f)->vec3f {${n}${e.position??`return position;`}}
|
|
11
|
+
fn modifyOpacity(index:u32,position:vec3f,opacity:f32)->f32 {${n}${e.opacity??`return opacity;`}}
|
|
12
|
+
@compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u) {
|
|
13
|
+
let index=id.x;if(index>=u.counts.x){return;}let rest=canonical[index];var result=rest;
|
|
14
|
+
if(u.clock.z>0.5){result=vec4f(modifyPosition(index,rest.xyz),rest.w);result.w=clamp(modifyOpacity(index,result.xyz,rest.w),0.0,1.5625);}
|
|
15
|
+
positions[index]=result;
|
|
16
|
+
sourceColors[index]=vec4f(sourceColors[index].rgb,result.w);
|
|
17
|
+
}`,color:t+`
|
|
18
|
+
@group(0) @binding(1) var<storage,read> positions:array<vec4f>;
|
|
19
|
+
@group(0) @binding(2) var<storage,read_write> evaluated:array<vec4f>;
|
|
20
|
+
fn modifyColor(index:u32,position:vec3f,color:vec3f)->vec3f {${n}${e.color??`return color;`}}
|
|
21
|
+
@compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u) {
|
|
22
|
+
let index=id.x;if(index>=u.counts.x||u.clock.z<0.5){return;}let original=evaluated[index];
|
|
23
|
+
evaluated[index]=vec4f(max(vec3f(0),modifyColor(index,positions[index].xyz,original.rgb)),original.a);
|
|
24
|
+
}`}}var a=/* @__PURE__ */ new WeakMap,o=class o{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static{this.next=0}constructor(e,t,n){if(this.name=`splats-modifier:`+o.next++,this.parameters=/* @__PURE__ */ new Float32Array(64),this.time=0,this.playing=!0,this.speed=1,this.enabled=!0,this.values=/* @__PURE__ */ new Float32Array(72),this.integers=new Uint32Array(this.values.buffer),this.pipelines=[],this.groups=[],this.dead=!1,this.cloud=e,this.shaders=i(n),this.canonical=new Float32Array(e.count*4),this.setRest(t),n.parameters!==void 0){if(!Number.isSafeInteger(n.parameters.length)||n.parameters.length>64||n.parameters.length<0)throw RangeError(`Splat modifier takes up to 64 parameter floats; shorten the parameter list`);for(let e=0;e<n.parameters.length;e++){if(!Number.isFinite(Math.fround(n.parameters[e])))throw RangeError(`Splat modifier parameters must be finite; fix the parameter values`);this.parameters[e]=n.parameters[e]}}this.signal=n.signal,this.abort=n.signal?()=>this.dispose():void 0,n.signal?.addEventListener(`abort`,this.abort,{once:!0})}static async create(e,t={}){if(!e||typeof e.read!=`function`||!Number.isInteger(e.count))throw TypeError(`SplatModifier needs a Splats cloud; pass the cloud to modify`);t.signal?.throwIfAborted(),i(t);let n=t.signal,r=e.read(),a=await new Promise((e,t)=>{let i=()=>{n?.removeEventListener(`abort`,i),t(n.reason)};n?.addEventListener(`abort`,i,{once:!0}),n?.aborted&&i(),r.then(e,t).finally(()=>n?.removeEventListener(`abort`,i))});return n?.throwIfAborted(),new o(e,a,t)}static async attach(e,r,i={}){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let a=t(e),s=await o.create(r,i);try{return i.signal?.throwIfAborted(),a.run(()=>n(e).use(s)),s}catch(e){throw s.dispose(),e}}setRest(t){if(this.dead)throw new r(`disposed`,`Splat modifier was disposed; create a new modifier`);if(e(t)!==this.cloud.count)throw RangeError(`Canonical splat count differs from the cloud; pass a full cloud of the same count`);for(let e=0;e<this.cloud.count;e++)this.canonical.set(t.positions.subarray(e*3,e*3+3),e*4),this.canonical[e*4+3]=t.colors[e*4+3];return this.rest&&this.device.queue.writeBuffer(this.rest,0,this.canonical),this}setup(e){if(this.dead||!e.gpu)throw new r(this.dead?`disposed`:`unsupported`,`SplatModifier needs a live WebGPU engine; see https://margoengine.com/errors#webgpu`);if(a.has(this.cloud)&&a.get(this.cloud)!==this)throw new r(`attached`,`This cloud already has a modifier; combine its WGSL hooks or dispose it first`);let t=e.gpu;this.engine=e,this.device=t,this.uniform=t.createBuffer({size:this.values.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.rest=t.createBuffer({size:this.canonical.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(this.rest,0,this.canonical),this.pipelines=[this.shaders.position,this.shaders.color].map(e=>t.createComputePipeline({layout:`auto`,compute:{module:t.createShaderModule({code:e}),entryPoint:`main`}})),a.set(this.cloud,this)}registerPasses(e){for(let[t,n]of[[0,-7.25],[1,-6.95]])e.add({name:this.name+`:`+t,order:n,execute:e=>{e.backend===`webgpu`&&this.cloud.attached&&this.run(e,t)}})}run(e,t){if(t===0){if(!Number.isFinite(Math.fround(this.time))||!Number.isFinite(Math.fround(e.delta))||!Number.isFinite(this.speed)||!this.parameters.every(Number.isFinite))throw RangeError(`Modifier clock and parameters must be finite; fix time, speed or parameter values`);this.values.set([this.time,e.delta,+this.enabled,0]),this.integers[4]=this.cloud.count,this.values.set(this.parameters,8),e.device.queue.writeBuffer(this.uniform,0,this.values)}let n=this.cloud.gpuState;(this.bound!==n.positions||this.evaluated!==n.colors)&&(this.groups=[[this.uniform,this.rest,n.positions,n.inputColors],[this.uniform,n.positions,n.colors]].map((t,n)=>e.device.createBindGroup({layout:this.pipelines[n].getBindGroupLayout(0),entries:t.map((e,t)=>({binding:t,resource:{buffer:e}}))})),this.bound=n.positions,this.evaluated=n.colors);let r=e.encoder.beginComputePass();r.setPipeline(this.pipelines[t]),r.setBindGroup(0,this.groups[t]),r.dispatchWorkgroups(Math.ceil(this.cloud.count/256)),r.end()}get disposed(){return this.dead}release(){this.uniform?.destroy(),this.rest?.destroy(),this.uniform=this.rest=this.bound=this.evaluated=void 0,this.groups=[],this.pipelines=[]}advanceTime(e){e>0&&this.playing&&(this.time+=e*this.speed)}onPreUpdate(e){this.advanceTime(e)}onDeviceRestored(e){this.release(),this.setup(e)}dispose(){if(!this.dead){if(this.dead=!0,this.cloud.attached&&this.bound===this.cloud.gpuState.positions&&this.device&&this.rest){let e=this.device.createCommandEncoder();this.values[2]=0,this.integers[4]=this.cloud.count,this.device.queue.writeBuffer(this.uniform,0,this.values);let t=e.beginComputePass();t.setPipeline(this.pipelines[0]),t.setBindGroup(0,this.groups[0]),t.dispatchWorkgroups(Math.ceil(this.cloud.count/256)),t.end(),this.device.queue.submit([e.finish()])}a.get(this.cloud)===this&&a.delete(this.cloud),this.signal?.removeEventListener(`abort`,this.abort),this.engine?.sceneOf(this)?.removePlugin(this.name),this.release(),this.engine=this.device=void 0}}[Symbol.dispose??Symbol()](){this.dispose()}};export{o as SplatModifier,i as splatModifierShaders};
|
package/dist/pick.d.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import type { Camera, Mesh } from '@margoengine/core';
|
|
3
|
+
import type { Splats } from './index.js';
|
|
4
|
+
/** What `Picking` hands an overlay for one pick. */
|
|
5
|
+
export interface SplatPickContext {
|
|
6
|
+
encoder: GPUCommandEncoder;
|
|
7
|
+
/** The r32uint pick tile, 3 x 3 pixels around the picked pixel. */
|
|
8
|
+
color: GPUTextureView;
|
|
9
|
+
/** Its depth32float depth (reversed Z), holding the meshes already drawn. */
|
|
10
|
+
depth: GPUTextureView;
|
|
11
|
+
/** The camera's view-projection matrix, cropped to the tile. */
|
|
12
|
+
matrix: Float32Array;
|
|
13
|
+
camera: Camera;
|
|
14
|
+
/** The picked view's rectangle in drawing-buffer pixels. */
|
|
15
|
+
rect: readonly number[];
|
|
16
|
+
/** The ID of this overlay's splat 0. */
|
|
17
|
+
firstId: number;
|
|
18
|
+
}
|
|
19
|
+
/** A splat hit: `hit.mesh` is an empty stand-in mesh for the cloud (see `splatsOf`), as `engine.pick` answers meshes. */
|
|
20
|
+
export interface SplatPickHit {
|
|
21
|
+
mesh: Mesh;
|
|
22
|
+
/** The cloud the splat belongs to. */
|
|
23
|
+
splats: Splats;
|
|
24
|
+
/** Index of the splat in the cloud (the order of its `SplatData`, or a pool index under `SplatSet` and `SplatLod`). */
|
|
25
|
+
splat: number;
|
|
26
|
+
}
|
|
27
|
+
/** What `SplatPicking.attach` needs of `@margoengine/selection`'s Picking. */
|
|
28
|
+
export interface SplatPickHost {
|
|
29
|
+
addOverlay(overlay: {
|
|
30
|
+
drawPick(context: SplatPickContext): void;
|
|
31
|
+
pickHit(index: number): SplatPickHit | null;
|
|
32
|
+
}): () => void;
|
|
33
|
+
}
|
|
34
|
+
/** Options of `SplatPicking.attach`. */
|
|
35
|
+
export interface SplatPickingOptions {
|
|
36
|
+
/** The opacity a splat's Gaussian must reach at the pixel to hit, 0 to 1. Default 0.1, as `SplatBrush.pick`. */
|
|
37
|
+
threshold?: number;
|
|
38
|
+
}
|
|
39
|
+
/** The projection of shader.ts in a vertex shader, the colour pass's falloff and cap, and an ID for a fragment. */
|
|
40
|
+
export declare const splatPickShader = "struct Frame {camera:mat4x4f,view:mat4x4f,eye:vec4f,viewport:vec4f,settings:vec4f,counts:vec4u}\n@group(0) @binding(0) var<uniform> f:Frame;\nstruct Ellipse {center:vec4f,axes:vec4f}\n@group(0) @binding(1) var<storage,read> positions:array<vec4f>;\n@group(0) @binding(2) var<storage,read> covariances:array<vec4f>;\nstruct Projected {ellipse:Ellipse,key:u32}\nfn projectSplat(index:u32)->Projected {\n let world=positions[index];let p=f.view*vec4f(world.xyz,1);let depth=-p.z;\n var ellipse:Ellipse;ellipse.center=vec4f(2,2,0,0);ellipse.axes=vec4f(0);var key=0xffffffffu;\n if(depth>=f.settings.x&&depth<=f.settings.y&&world.w>0){\n let a=covariances[index*2];let b=covariances[index*2+1];let covariance=mat3x3f(vec3f(a.x,a.y,a.z),vec3f(a.y,a.w,b.x),vec3f(a.z,b.x,b.y));\n let rotation=mat3x3f(f.view[0].xyz,f.view[1].xyz,f.view[2].xyz);let c=rotation*covariance*transpose(rotation);\n let lim=0.65*f.viewport.xy/f.viewport.zw;let t=clamp(p.xy/depth,-lim,lim);var jx=vec3f(f.viewport.z/depth,0,f.viewport.z*t.x/depth);var jy=vec3f(0,f.viewport.w/depth,f.viewport.w*t.y/depth);\n if(f.settings.w>0.5){jx=vec3f(f.viewport.z,0,0);jy=vec3f(0,f.viewport.w,0);}\n let xx=dot(jx,c*jx)+0.3;let xy=dot(jx,c*jy);let yy=dot(jy,c*jy)+0.3;var opacity=world.w;\n if(f.counts.z==1u){opacity*=sqrt(max((xx-0.3)*(yy-0.3)-xy*xy,0.0)/max(xx*yy-xy*xy,1e-12));}\n let mid=(xx+yy)*0.5;let radius=sqrt(max(0.0,(xx-yy)*(xx-yy)*0.25+xy*xy));\n let major=max(mid+radius,0.3);let minor=max(mid-radius,0.3);var axis=vec2f(1,0);\n if(abs(xy)>0.000001){axis=normalize(vec2f(xy,major-xx));}else if(yy>xx){axis=vec2f(0,1);}\n let scale=vec2f(2)/f.viewport.xy;let first=axis*(3*sqrt(major))*scale;let second=vec2f(-axis.y,axis.x)*(3*sqrt(minor))*scale;\n let clip=f.camera*vec4f(world.xyz,1);let ndc=clip.xyz/clip.w;let extent=abs(first)+abs(second);\n if(all(abs(ndc.xy)<=vec2f(1)+extent)) {ellipse.center=vec4f(ndc,opacity);ellipse.axes=vec4f(first,second);key=~bitcast<u32>(select(depth,depth-f.settings.x,f.settings.w>0.5));}\n }return Projected(ellipse,key);\n}\nstruct Pick {threshold:f32,first:u32}\n@group(1) @binding(0) var<uniform> pick:Pick;\nstruct PickOut {@builtin(position) clip:vec4f,@location(0) corner:vec2f,@location(1) @interpolate(flat) opacity:f32,@location(2) @interpolate(flat) splat:u32}\n@vertex fn vertex(@builtin(vertex_index) vertex:u32,@builtin(instance_index) index:u32)->PickOut {\n let corners=array<vec2f,4>(vec2f(-1,-1),vec2f(1,-1),vec2f(-1,1),vec2f(1,1));let e=projectSplat(index).ellipse;let corner=corners[vertex];var o:PickOut;\n 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;o.splat=index;\n if(e.center.w==0){o.clip=vec4f(2,2,0,1);}return o;\n}\n@fragment fn fragment(i:PickOut)->@location(0) u32 {let power=-4.5*dot(i.corner,i.corner);if(power<-4.5){discard;}\n let alpha=min(0.99,i.opacity*exp(power));if(alpha<max(pick.threshold,1.0/255)){discard;}return pick.first+i.splat;}";
|
|
41
|
+
/**
|
|
42
|
+
* Makes a `Splats` cloud pickable by `@margoengine/selection`'s `Picking`, and so by `engine.pick`, `picking.pick` and
|
|
43
|
+
* `pickMany` once Picking is attached. Splats and meshes share one depth test: a mesh in front blocks the pick, a splat
|
|
44
|
+
* in front of a mesh wins it. The splats are projected for the pick with the current camera, so a pick needs no drawn
|
|
45
|
+
* frame. `hit.splats` and `hit.splat` name what was hit; `hit.mesh` is an empty stand-in mesh (`splatsOf` maps it back).
|
|
46
|
+
*/
|
|
47
|
+
export declare class SplatPicking {
|
|
48
|
+
readonly splats: Splats;
|
|
49
|
+
private gpu?;
|
|
50
|
+
private mesh?;
|
|
51
|
+
private remove?;
|
|
52
|
+
private value;
|
|
53
|
+
private readonly frameData;
|
|
54
|
+
private readonly integers;
|
|
55
|
+
private readonly params;
|
|
56
|
+
/**
|
|
57
|
+
* Registers `splats` with `picking`; undo with `dispose`.
|
|
58
|
+
* @throws MargoError `state` when `splats` is not attached to an engine yet; RangeError for a threshold outside 0 to 1.
|
|
59
|
+
*/
|
|
60
|
+
static attach(picking: SplatPickHost, splats: Splats, options?: SplatPickingOptions): SplatPicking;
|
|
61
|
+
private constructor();
|
|
62
|
+
/** The opacity a splat's Gaussian must reach at the pixel to hit, 0 to 1; takes effect at the next pick. */
|
|
63
|
+
get threshold(): number;
|
|
64
|
+
set threshold(value: number);
|
|
65
|
+
/** The cloud `mesh` stands in for, from a `hit.mesh` or an `engine.pick` answer; null for any other mesh. */
|
|
66
|
+
splatsOf(mesh: Mesh | null): Splats | null;
|
|
67
|
+
private resources;
|
|
68
|
+
/** @internal Picking's turn: projects every splat for the tile and draws the ones that reach it, with IDs from `firstId`. */
|
|
69
|
+
drawPick(c: SplatPickContext): void;
|
|
70
|
+
/** @internal The hit of ID `index` of the last `drawPick`. */
|
|
71
|
+
pickHit(index: number): SplatPickHit | null;
|
|
72
|
+
/** Leaves Picking and frees the stand-in mesh and GPU buffers; the cloud itself stays. */
|
|
73
|
+
dispose(): void;
|
|
74
|
+
[Symbol.dispose](): void;
|
|
75
|
+
}
|
package/dist/pick.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
|
+
|
|
4
|
+
import{t as e}from"./view-DyJeX8rJ.js";import{a as t,i as n,n as r,p as i}from"./shader-B7zZyYz-.js";import{MargoError as a}from"@margoengine/math/errors";var o=192,s=`${r}${n}${t}
|
|
5
|
+
struct Pick {threshold:f32,first:u32}
|
|
6
|
+
@group(1) @binding(0) var<uniform> pick:Pick;
|
|
7
|
+
struct PickOut {@builtin(position) clip:vec4f,@location(0) corner:vec2f,@location(1) @interpolate(flat) opacity:f32,@location(2) @interpolate(flat) splat:u32}
|
|
8
|
+
@vertex fn vertex(@builtin(vertex_index) vertex:u32,@builtin(instance_index) index:u32)->PickOut {
|
|
9
|
+
let corners=array<vec2f,4>(vec2f(-1,-1),vec2f(1,-1),vec2f(-1,1),vec2f(1,1));let e=projectSplat(index).ellipse;let corner=corners[vertex];var o:PickOut;
|
|
10
|
+
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;o.splat=index;
|
|
11
|
+
if(e.center.w==0){o.clip=vec4f(2,2,0,1);}return o;
|
|
12
|
+
}
|
|
13
|
+
@fragment fn fragment(i:PickOut)->@location(0) u32 {let power=-4.5*dot(i.corner,i.corner);if(power<-4.5){discard;}
|
|
14
|
+
let alpha=min(0.99,i.opacity*exp(power));if(alpha<max(pick.threshold,1.0/255)){discard;}return pick.first+i.splat;}`;function c(e){if(!(e>=0&&e<=1))throw RangeError(`SplatPicking threshold must be 0 to 1`);return e}var l=class t{static attach(e,n,r={}){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let i=n.engine;if(!i)throw new a(`state`,`Attach Splats to the engine before SplatPicking.attach`);let o=new t(n,c(r.threshold??.1));return o.mesh=i.createMesh(),o.remove=e.addOverlay(o),o}constructor(e,t){this.splats=e,this.frameData=new Float32Array(o/4),this.integers=new Uint32Array(this.frameData.buffer),this.params=/* @__PURE__ */ new ArrayBuffer(16),this.value=t}get threshold(){return this.value}set threshold(e){this.value=c(e)}splatsOf(e){return e&&e===this.mesh?this.splats:null}resources(e){if(this.gpu?.device===e)return this.gpu;this.gpu?.frame.destroy(),this.gpu?.params.destroy();let t=e.createShaderModule({code:s}),n=e.createRenderPipeline({layout:`auto`,vertex:{module:t,entryPoint:`vertex`},fragment:{module:t,entryPoint:`fragment`,targets:[{format:`r32uint`}]},primitive:{topology:`triangle-strip`,cullMode:`none`},depthStencil:{format:`depth32float`,depthWriteEnabled:!0,depthCompare:`greater-equal`}}),r=e.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});return this.gpu={device:e,frame:e.createBuffer({size:o,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),params:r,pipeline:n,paramsGroup:e.createBindGroup({layout:n.getBindGroupLayout(1),entries:[{binding:0,resource:{buffer:r}}]})}}drawPick(t){let n=this.splats,r=n.device,a=n.inputs;if(!r||n.disposed||a.length<2||!n.count)return;let o=this.resources(r);(o.inputs?.[0]!==a[0]||o.inputs?.[1]!==a[1])&&(o.inputs=[a[0],a[1]],o.group=r.createBindGroup({layout:o.pipeline.getBindGroupLayout(0),entries:[o.frame,a[0],a[1]].map((e,t)=>({binding:t,resource:{buffer:e}}))}));let s=this.frameData,c=this.integers,l=t.camera,[,,u,d]=t.rect;s.set(t.matrix,0),e(s.subarray(16,32),l),s.set(l.position,32),s[35]=0,s[36]=s[37]=3,s[38]=s[39]=d/(2*Math.tan(l.fov*Math.PI/360)),s[40]=l.near,s[41]=l.far,s[42]=s[43]=0;let f=i(l.matrix,l.position);f&&(s[38]=f.sx*u/2,s[39]=f.sy*d/2,s[40]=f.near,s[41]=f.far,s[43]=1),c[44]=n.count,c[45]=0,c[46]=+n.mip,c[47]=0,new Float32Array(this.params,0,1)[0]=this.value,new Uint32Array(this.params,4,1)[0]=t.firstId,r.queue.writeBuffer(o.frame,0,s),r.queue.writeBuffer(o.params,0,this.params);let p=t.encoder.beginRenderPass({colorAttachments:[{view:t.color,loadOp:`load`,storeOp:`store`}],depthStencilAttachment:{view:t.depth,depthLoadOp:`load`,depthStoreOp:`store`}});p.setPipeline(o.pipeline),p.setBindGroup(0,o.group),p.setBindGroup(1,o.paramsGroup),p.draw(4,n.count),p.end()}pickHit(e){let t=this.mesh;return!t||!(e>=0&&e<this.splats.count)?null:{mesh:t,splats:this.splats,splat:e}}dispose(){this.remove?.(),this.remove=void 0,this.mesh?.dispose(),this.mesh=void 0,this.gpu?.frame.destroy(),this.gpu?.params.destroy(),this.gpu=void 0}[Symbol.dispose](){this.dispose()}};export{l as SplatPicking,s as splatPickShader};
|
package/dist/ply.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { type SplatData } from './data.js';
|
|
2
|
+
/**
|
|
3
|
+
* Decodes a Gaussian-splat PLY (`format binary_little_endian` or `ascii`, one `vertex` element with `x y z`,
|
|
4
|
+
* `f_dc_0..2`, optional `f_rest_*` (degree 1-4), `opacity` (logit), `scale_0..2` (log) and `rot_0..3` (w x y z)).
|
|
5
|
+
* Opacity goes through the sigmoid, scales through exp, and rotation and scale become a covariance. Colours are
|
|
6
|
+
* display (sRGB) values in these files, so the base colour is converted to linear exactly and the view-dependent
|
|
7
|
+
* terms to first order around it (Margo's splat renderer works in linear). Coordinates are kept as stored: captures
|
|
8
|
+
* trained in a Y-down camera frame need `transformSplats` with a 180-degree turn about X to stand up in Margo's Y-up.
|
|
9
|
+
* @throws TypeError when `input` is not bytes; RangeError for a file that is not a splat PLY, names the missing
|
|
10
|
+
* properties, or fails `validateSplats`; MargoError `unsupported` for big-endian or packed (chunked) PLY files.
|
|
11
|
+
*/
|
|
12
|
+
export declare function parsePly(input: ArrayBuffer | ArrayBufferView): SplatData;
|
|
13
|
+
/**
|
|
14
|
+
* Gaussian-splat attributes as stored by the training PLY and the compressed formats, before they become
|
|
15
|
+
* {@link SplatData}. Shared by the PLY, SPZ and SOG readers.
|
|
16
|
+
*/
|
|
17
|
+
export interface GaussianAttributes {
|
|
18
|
+
count: number;
|
|
19
|
+
/** Centres, 3 floats per splat. */
|
|
20
|
+
positions: Float32Array;
|
|
21
|
+
/** Natural log of the three axis scales, 3 floats per splat. */
|
|
22
|
+
logScales: Float32Array;
|
|
23
|
+
/** Rotations as (w, x, y, z), 4 floats per splat; normalised on conversion. */
|
|
24
|
+
rotations: Float32Array;
|
|
25
|
+
/** Band-0 spherical-harmonic coefficients (display colour = 0.5 + C0 * dc), 3 floats per splat. */
|
|
26
|
+
dc: Float32Array;
|
|
27
|
+
/** Opacity 0..1.5625. */
|
|
28
|
+
alphas: Float32Array;
|
|
29
|
+
/** Bands 1 and up: `(perChannel - 1) * 3` floats per splat, coefficient-major with the colour channel innermost. */
|
|
30
|
+
rest?: Float32Array;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Converts raw Gaussian attributes to {@link SplatData}: normalised rotations, covariance from rotation and scale,
|
|
34
|
+
* display-space colour to linear (exactly for the base band, to first order for the view-dependent terms). With
|
|
35
|
+
* `linear: true` the stored colour is linear already and only clamps.
|
|
36
|
+
* @throws RangeError for a zero rotation, an unsupported SH size, or a cloud that fails `validateSplats`.
|
|
37
|
+
*/
|
|
38
|
+
export declare function splatsFromAttributes(raw: GaussianAttributes, { linear: stored }?: {
|
|
39
|
+
linear?: boolean | undefined;
|
|
40
|
+
}): SplatData;
|
|
41
|
+
/**
|
|
42
|
+
* Eigen-decomposition of a symmetric 3x3 covariance (xx, xy, xz, yy, yz, zz) by cyclic Jacobi rotations: the axis
|
|
43
|
+
* scales (square roots of the eigenvalues) and the rotation whose columns are the axes, as a unit quaternion.
|
|
44
|
+
*/
|
|
45
|
+
export declare function decomposeCovariance(c: ArrayLike<number>, at?: number): {
|
|
46
|
+
scale: number[];
|
|
47
|
+
rotation: number[];
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Encodes a cloud as the 32-byte `.splat` layout `parseSplat` reads (xyz, axis scales, byte sRGB RGBA, byte wxyz
|
|
51
|
+
* quaternion), for saving a cropped or edited cloud. Covariances are split into axis scales and a rotation;
|
|
52
|
+
* spherical harmonics are not stored by this format, so the base (view-independent) colour is written.
|
|
53
|
+
* @throws RangeError when `data` fails `validateSplats`.
|
|
54
|
+
*/
|
|
55
|
+
export declare function encodeSplat(data: SplatData): Uint8Array<ArrayBuffer>;
|
|
56
|
+
/**
|
|
57
|
+
* The stored Gaussian attributes of a cloud, the inverse of `splatsFromAttributes`: axis scales and rotation from
|
|
58
|
+
* the covariance (`decomposeCovariance`), display colour from linear (exactly for the base band, to first order for
|
|
59
|
+
* the view-dependent terms), for the SPZ and SOG writers.
|
|
60
|
+
* @throws RangeError when `data` fails `validateSplats`.
|
|
61
|
+
*/
|
|
62
|
+
export declare function attributesFromSplats(data: SplatData): GaussianAttributes;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
3
|
+
import { Splats } from './index.js';
|
|
4
|
+
import { type SplatData } from './data.js';
|
|
5
|
+
/** Byte source with backpressure. A response's body can be passed directly. */
|
|
6
|
+
export type SplatByteStream = ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>;
|
|
7
|
+
/** Streaming decoder options. */
|
|
8
|
+
export interface ProgressiveSplatOptions {
|
|
9
|
+
/** Container, required because raw splat records have no magic. */
|
|
10
|
+
format: 'ply' | 'splat' | 'spz';
|
|
11
|
+
/** Maximum records per emitted batch. Default 16,384. */
|
|
12
|
+
batchSize?: number;
|
|
13
|
+
/** Required for raw splat; PLY and SPZ read their count from the header. */
|
|
14
|
+
count?: number;
|
|
15
|
+
/** Cancels pending reads, decompression and upload. */
|
|
16
|
+
signal?: AbortSignal;
|
|
17
|
+
}
|
|
18
|
+
/** A drawable batch. SPZ's final batch replaces its base-colour preview with full SH. */
|
|
19
|
+
export interface ProgressiveSplatBatch {
|
|
20
|
+
/** Pool offset to replace. */
|
|
21
|
+
first: number;
|
|
22
|
+
/** Total capture count from its header or options. */
|
|
23
|
+
total: number;
|
|
24
|
+
/** Largest opacity-weighted covariance volume first within this available batch. */
|
|
25
|
+
data: SplatData;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Decodes and yields complete records as bytes arrive. Sorting is coarse first among currently available records;
|
|
29
|
+
* records not received cannot be prioritised without a server-side ordering. SPZ previews start as soon as their
|
|
30
|
+
* rotation records arrive, before SH and the gzip trailer; final replacement restores full SH precision.
|
|
31
|
+
*/
|
|
32
|
+
export declare function readSplatsProgressive(source: SplatByteStream, options: ProgressiveSplatOptions): AsyncGenerator<ProgressiveSplatBatch>;
|
|
33
|
+
/**
|
|
34
|
+
* Uploads batches to a reserved cloud. Call engine.start() before awaiting this function to see streaming frames.
|
|
35
|
+
* The returned cloud remains attached; on failure the incomplete cloud is disposed. No callback or global state.
|
|
36
|
+
*/
|
|
37
|
+
export declare function loadProgressiveSplats(engine: EngineKernel, source: SplatByteStream, options: ProgressiveSplatOptions): Promise<Splats>;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{d as e,t}from"./data-BDt3mxGg.js";import{t as n}from"./src-BxooDRB9.js";import{t as r}from"./scene-scope-C5HWuOIb.js";import{t as i}from"./spz-ivoWSN9h.js";var a=class{constructor(){this.bytes=/* @__PURE__ */ new Uint8Array(4096),this.length=0}append(e){if(!(e instanceof Uint8Array))throw TypeError(`Stream chunks must be Uint8Array; pass response.body`);if(this.length+e.length>this.bytes.length){let t=new Uint8Array(Math.max(this.length+e.length,this.bytes.length*2));t.set(this.bytes.subarray(0,this.length)),this.bytes=t}this.bytes.set(e,this.length),this.length+=e.length}get view(){return this.bytes.subarray(0,this.length)}};function o(e,t){return t?new Promise((n,r)=>{let i=()=>t.removeEventListener(`abort`,a),a=()=>{i(),r(t.reason)};t.addEventListener(`abort`,a,{once:!0}),Promise.resolve(e).then(e=>{i(),n(e)},e=>{i(),r(e)}),t.aborted&&a()}):Promise.resolve(e)}async function*s(e,t){if(t?.throwIfAborted(),e instanceof ReadableStream){let n=e.getReader(),r=()=>{n.cancel(t?.reason)};t?.addEventListener(`abort`,r,{once:!0});let i=!1;try{for(;;){let e=await n.read();if(t?.throwIfAborted(),e.done){i=!0;break}yield e.value}}finally{t?.removeEventListener(`abort`,r),i||await n.cancel(),n.releaseLock()}}else{let n=e[Symbol.asyncIterator](),r=!1;try{for(;;){t?.throwIfAborted();let e=await o(n.next(),t);if(t?.throwIfAborted(),e.done){r=!0;break}yield e.value}}finally{!r&&n.return&&await o(n.return(),t)}}}function c(e){let t=e.positions.length/3,n=e.covariances,r=t=>{let r=t*6;return e.colors[t*4+3]*Math.sqrt(Math.max(0,n[r]*(n[r+3]*n[r+5]-n[r+4]**2)-n[r+1]*(n[r+1]*n[r+5]-n[r+2]*n[r+4])+n[r+2]*(n[r+1]*n[r+4]-n[r+2]*n[r+3])))},i=Array.from({length:t},(e,t)=>r(t)),a=Array.from({length:t},(e,t)=>t).sort((e,t)=>i[t]-i[e]),o=(e,n)=>{let r=new Float32Array(e.length);for(let i=0;i<t;i++)r.set(e.subarray(a[i]*n,(a[i]+1)*n),i*n);return r};return{positions:o(e.positions,3),covariances:o(n,6),colors:o(e.colors,4),...e.sphericalHarmonics?{sphericalHarmonics:o(e.sphericalHarmonics,e.sphericalHarmonics.length/t)}:{}}}async function*l(e,t){let n=s(e,t)[Symbol.asyncIterator](),r=new a;try{for(;r.length<2;){let e=await n.next();if(e.done)throw RangeError(`SPZ header is truncated; download the complete file`);r.append(e.value)}if(r.bytes[0]===31&&r.bytes[1]===139){let e=!0;yield*s(new ReadableStream({async pull(t){if(e){e=!1,t.enqueue(r.view.slice());return}let i=await n.next();i.done?t.close():t.enqueue(i.value.slice())},async cancel(){await n.return?.(void 0)}}).pipeThrough(new DecompressionStream(`gzip`)),t);return}let e=async e=>{for(;r.length<e;){let e=await n.next();if(e.done)throw RangeError(`SPZ attribute is truncated; download the complete file`);r.append(e.value)}};await e(32);let i=()=>new DataView(r.bytes.buffer);if(i().getUint32(0,!0)!==1347635022||i().getUint32(4,!0)!==4)throw RangeError(`Unknown SPZ header; export SPZ version 2, 3 or 4`);let a=r.bytes[15],o=i().getUint32(16,!0),c=i().getUint32(8,!0),l=r.bytes[12];if(o<32||o>65536||c<1||c>3e6||l>3||a<(l?6:5))throw RangeError(`Invalid SPZ table of contents; check the capture header`);await e(o+a*16),yield r.bytes.slice(0,16);let u=[c*9,c,c*3,c*3,c*4,c*[0,9,24,45][l]],d=o+a*16,{decompressZstd:f}=await import(`./zstd-BPbUkXlY.js`);for(let n=0;n<a;n++){let a=Number(i().getBigUint64(o+n*16,!0)),s=Number(i().getBigUint64(o+n*16+8,!0));if(!Number.isSafeInteger(a)||a<1||a>1e9||n<(l?6:5)&&s!==u[n])throw RangeError(`Invalid SPZ stream size; check the capture table of contents`);if(await e(d+a),n<(l?6:5)){let e=await f(r.bytes.subarray(d,d+a),{signal:t,maxOutputSize:s,maxWindowSize:Math.max(s,1<<27)});if(e.length!==s)throw RangeError(`SPZ attribute size differs from its header; check the file`);yield e}d+=a}}finally{await n.return?.(void 0)}}async function*u(n,r){let{format:o,signal:u}=r,d=r.batchSize??16384;if(!Number.isInteger(d)||d<1)throw RangeError(`batchSize must be a positive integer; use 16384`);if(![`ply`,`splat`,`spz`].includes(o))throw RangeError(`Choose ply, splat or spz as the stream format`);let f=r.count??0,p=0,m=``,h=0,g=32,_=!1,v=0,y=0,b=!1,x=new a,S=o===`spz`?l(n,u):s(n,u);async function*C(){yield*S,b=!0,yield/* @__PURE__ */ new Uint8Array}for await(let n of C()){if(u?.throwIfAborted(),x.append(n),o===`ply`&&!m){let e=new TextDecoder(`latin1`).decode(x.view.subarray(0,65536)),t=e.indexOf(`end_header
|
|
2
|
+
`)>=0?e.indexOf(`end_header
|
|
3
|
+
`)+11:e.indexOf(`end_header\r
|
|
4
|
+
`)>=0?e.indexOf(`end_header\r
|
|
5
|
+
`)+12:0;if(!t){if(x.length>=65536)throw RangeError(`PLY header exceeds 64 KiB; check the file`);continue}if(m=e.slice(0,t),h=t,f=Number(/element vertex (\d+)/.exec(m)?.[1]),_=m.includes(`format ascii `),!_&&!m.includes(`format binary_little_endian `))throw RangeError(`Choose little-endian or ASCII Gaussian PLY for streaming`);let n={char:1,uchar:1,int8:1,uint8:1,short:2,ushort:2,int16:2,uint16:2,int:4,uint:4,int32:4,uint32:4,float:4,float32:4,double:8,float64:8},r=!1;g=0;for(let e of m.split(/\r?\n/)){let t=e.split(/\s+/);if(t[0]===`element`&&(r=t[1]===`vertex`,!r))throw RangeError(`Stream standard vertex-only Gaussian PLY; use the formats reader for packed files`);if(r&&t[0]===`property`){if(!n[t[1]])throw RangeError(`Use scalar PLY properties for streaming`);g+=n[t[1]],y++}}}if(o===`spz`){if(x.length<16)continue;let e=new DataView(x.bytes.buffer),t=e.getUint32(4,!0);if(f=e.getUint32(8,!0),v=[0,4,9,16][x.bytes[12]],![2,3,4].includes(t)||v===void 0)throw RangeError(`Use SPZ version 2 to 4 with SH degree 0 to 3`);g=t===2?3:4,h=16+f*16}if(!Number.isInteger(f)||f<1||f>3e6)throw RangeError(`Set a capture count of 1 to 3,000,000 splats`);let r=_?new TextDecoder().decode(x.view.subarray(h)):``,a=r.trim()?r.trim().split(/\s+/):[];_&&!b&&!/\s$/.test(r)&&a.pop();let s=Math.min(f,_?Math.floor(a.length/y):Math.max(0,Math.floor((x.length-h)/g)));for(;p<s;){u?.throwIfAborted();let n=Math.min(d,s-p),r;if(o===`spz`){let e=new Uint8Array(16+n*(16+g));e.set(x.view.subarray(0,16)),new DataView(e.buffer).setUint32(8,n,!0),e[12]=0;let t=16,a=16;for(let r of[9,1,3,3,g])e.set(x.view.subarray(t+p*r,t+(p+n)*r),a),t+=f*r,a+=n*r;if(r=i(e,x.bytes[4]===4?4:3),v){r.sphericalHarmonics=new Float32Array(n*v*3);for(let e=0;e<n;e++)for(let t=0;t<3;t++)r.sphericalHarmonics[e*v*3+t]=(r.colors[e*4+t]-.5)/.2820947918}}else if(o===`splat`)r=t(x.view.subarray(p*32,(p+n)*32));else{let t=new TextEncoder().encode(m.replace(/element vertex \d+/,`element vertex ${n}`)),i=_?new TextEncoder().encode(a.slice(p*y,(p+n)*y).join(` `)):x.view.subarray(h+p*g,h+(p+n)*g),o=new Uint8Array(t.length+i.length);o.set(t),o.set(i,t.length),r=e(o)}yield{first:p,total:f,data:c(r)},p+=n}}if(u?.throwIfAborted(),o===`spz`){let e=i(x.view,x.bytes[4]===4?4:3);yield{first:0,total:f,data:c(e)}}else if(p!==f||!_&&x.length!==h+f*g)throw RangeError(`Splat stream is truncated or has extra records; check its declared count`)}async function d(e,t,i){let a,o=r(e);try{for await(let r of u(t,i)){if(!a){a=n.reserve(r.total,r.data.sphericalHarmonics?r.data.sphericalHarmonics.length/r.data.positions.length:0);let t=a;o.run(()=>e.use(t))}a.write(r.first,r.data)}if(!a)throw RangeError(`The stream contains no splats; check the capture`);return a}catch(e){throw a?.dispose(),e}}export{d as loadProgressiveSplats,u as readSplatsProgressive};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
|
|
4
|
+
var e=0,t=(t,n)=>{let r=n+e++;for(;t.plugins?.has(r);)r+=`:`;return r};function n(e){let n;if(typeof e?.sceneOf==`function`){for(let t of e.plugins?.values()??[])if(n=e.sceneOf(t))break;if(!n){let r={coreRequirement:/*@__PURE__*/__margoCoreRequirement("1.0.0",import.meta.url),name:t(e,`scene-scope:`),setup(){n=e.sceneOf(r)}};e.use(r),e.removePlugin(r.name)}}return r(e,n)}function r(e,n){return{scene:n,run(r){if(!n)return r();let i,a={coreRequirement:/*@__PURE__*/__margoCoreRequirement("1.0.0",import.meta.url),name:t(e,`scene-scope:`),setup(){i=r()}};return n.use(a),n.removePlugin(a.name),i}}}export{n as t};
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { type SplatData } from './data.js';
|
|
2
|
+
import type { Splats } from './index.js';
|
|
3
|
+
/** How a selection tool combines its hits with the current selection. */
|
|
4
|
+
export type SelectionMode = 'replace' | 'add' | 'subtract';
|
|
5
|
+
/** A camera and viewport for screen-space selection: `viewProjection` column-major 4x4, pixels from the top left. */
|
|
6
|
+
export interface SelectionView {
|
|
7
|
+
viewProjection: ArrayLike<number>;
|
|
8
|
+
width: number;
|
|
9
|
+
height: number;
|
|
10
|
+
}
|
|
11
|
+
/** Colour changes of {@link SplatEditSession.adjustColor}; each defaults to no change. */
|
|
12
|
+
export interface ColorAdjust {
|
|
13
|
+
/** Linear multiplier of RGB. Default 1. */
|
|
14
|
+
brightness?: number;
|
|
15
|
+
/** Scale about mid grey 0.5. Default 1. */
|
|
16
|
+
contrast?: number;
|
|
17
|
+
/** 0 grey, 1 unchanged, above 1 more vivid. Default 1. */
|
|
18
|
+
saturation?: number;
|
|
19
|
+
/** Hue turn in degrees about the grey axis. Default 0. */
|
|
20
|
+
hue?: number;
|
|
21
|
+
/** Multiplier of opacity (result kept within 0 to 1.5625). Default 1. */
|
|
22
|
+
opacity?: number;
|
|
23
|
+
}
|
|
24
|
+
/** Export formats of {@link SplatEditSession.encode}. */
|
|
25
|
+
export type SplatExportFormat = 'ply' | 'spz' | 'splat' | 'sog';
|
|
26
|
+
/**
|
|
27
|
+
* `new SplatEditSession(data)` (the data is copied), then select, edit and `toData()` / `encode('ply')`. Hidden and
|
|
28
|
+
* deleted splats are never selected. Selection tools return `this` and are undoable like every edit.
|
|
29
|
+
* @throws TypeError / RangeError when `data` is invalid (`validateSplats`).
|
|
30
|
+
*/
|
|
31
|
+
export declare class SplatEditSession {
|
|
32
|
+
readonly count: number;
|
|
33
|
+
private readonly positions;
|
|
34
|
+
private readonly covariances;
|
|
35
|
+
private readonly colors;
|
|
36
|
+
private readonly sh;
|
|
37
|
+
private readonly per;
|
|
38
|
+
private selected;
|
|
39
|
+
private readonly state;
|
|
40
|
+
private undoStack;
|
|
41
|
+
private redoStack;
|
|
42
|
+
/** Steps kept for undo. Default 64. */
|
|
43
|
+
maxHistory: number;
|
|
44
|
+
constructor(data: SplatData);
|
|
45
|
+
/** A session over a cloud's current data, GPU edits included (`Splats.read`). */
|
|
46
|
+
static fromCloud(cloud: Splats): Promise<SplatEditSession>;
|
|
47
|
+
/** Splats selected. */
|
|
48
|
+
get selectedCount(): number;
|
|
49
|
+
/** Indices of the selected splats, ascending. */
|
|
50
|
+
get selection(): Uint32Array;
|
|
51
|
+
/** Splats neither hidden nor deleted. */
|
|
52
|
+
get visibleCount(): number;
|
|
53
|
+
get canUndo(): boolean;
|
|
54
|
+
get canRedo(): boolean;
|
|
55
|
+
/** Selects the visible splats `hit(index)` accepts, combined by `mode`. */
|
|
56
|
+
private pickWhere;
|
|
57
|
+
private setSelection;
|
|
58
|
+
/** Selects every visible splat. */
|
|
59
|
+
selectAll(): this;
|
|
60
|
+
/** Empties the selection. */
|
|
61
|
+
clearSelection(): this;
|
|
62
|
+
/** Selects the visible splats that are not selected and deselects the rest. */
|
|
63
|
+
invertSelection(): this;
|
|
64
|
+
/** Splats whose centre is inside the axis-aligned box, world units. */
|
|
65
|
+
selectBox(min: ArrayLike<number>, max: ArrayLike<number>, mode?: SelectionMode): this;
|
|
66
|
+
/** Splats whose centre is within `radius` of `center`, world units. */
|
|
67
|
+
selectSphere(center: ArrayLike<number>, radius: number, mode?: SelectionMode): this;
|
|
68
|
+
/** Projects every centre to pixels; `null` for centres behind the camera. */
|
|
69
|
+
private project;
|
|
70
|
+
/** The brush: splats whose projected centre is within `radius` pixels of (`x`, `y`). */
|
|
71
|
+
selectBrush(view: SelectionView, x: number, y: number, radius: number, mode?: SelectionMode): this;
|
|
72
|
+
/** The rectangle: splats whose projected centre is inside the pixel rectangle (`x0`, `y0`) to (`x1`, `y1`). */
|
|
73
|
+
selectRect(view: SelectionView, x0: number, y0: number, x1: number, y1: number, mode?: SelectionMode): this;
|
|
74
|
+
/** The lasso: splats whose projected centre is inside the closed polygon of pixel points `[x, y]` (even-odd rule). */
|
|
75
|
+
selectLasso(view: SelectionView, polygon: ReadonlyArray<readonly [number, number]>, mode?: SelectionMode): this;
|
|
76
|
+
/** Splats whose display colour is within `tolerance` (Euclidean, linear RGB 0 to 1.74) of `rgb`; SH base band used when present. */
|
|
77
|
+
selectByColor(rgb: ArrayLike<number>, tolerance: number, mode?: SelectionMode): this;
|
|
78
|
+
/** Splats whose opacity is within `min` to `max` (inclusive); select faint floaters with `selectByOpacity(0, 0.1)`. */
|
|
79
|
+
selectByOpacity(min: number, max: number, mode?: SelectionMode): this;
|
|
80
|
+
private baseColor;
|
|
81
|
+
/** Hides the selected splats (kept, not exported or selectable) and deselects them. */
|
|
82
|
+
hideSelected(): this;
|
|
83
|
+
/** Deletes the selected splats (removed from `toData()`; undo brings them back) and deselects them. */
|
|
84
|
+
deleteSelected(): this;
|
|
85
|
+
private markSelected;
|
|
86
|
+
/** Shows every hidden splat again (deleted ones stay deleted). */
|
|
87
|
+
unhideAll(): this;
|
|
88
|
+
/**
|
|
89
|
+
* Moves, turns and scales the selected splats by a column-major 4x4 affine `matrix` (`transformSplats`: covariances
|
|
90
|
+
* and SH turn with it), about `about` when given (default the world origin).
|
|
91
|
+
* @throws RangeError for an invalid or singular matrix or pivot.
|
|
92
|
+
*/
|
|
93
|
+
transformSelected(matrix: ArrayLike<number>, options?: {
|
|
94
|
+
about?: ArrayLike<number>;
|
|
95
|
+
}): this;
|
|
96
|
+
/** Changes the colour (and opacity) of the selected splats; with SH only the base band is adjusted. */
|
|
97
|
+
adjustColor(adjust: ColorAdjust): this;
|
|
98
|
+
/** Reverts the last edit or selection change; returns whether there was one. */
|
|
99
|
+
undo(): boolean;
|
|
100
|
+
/** Reapplies the last undone step; returns whether there was one. */
|
|
101
|
+
redo(): boolean;
|
|
102
|
+
private step;
|
|
103
|
+
private push;
|
|
104
|
+
/** Rows of `idx` as they are now (state included), to restore later. */
|
|
105
|
+
private capture;
|
|
106
|
+
/** Exchanges the patch's content with the session's: the patch then holds what was replaced. */
|
|
107
|
+
private swap;
|
|
108
|
+
private indicesOf;
|
|
109
|
+
private subset;
|
|
110
|
+
/**
|
|
111
|
+
* The edited cloud without hidden and deleted splats, as a new data set.
|
|
112
|
+
* @throws RangeError when none are left.
|
|
113
|
+
*/
|
|
114
|
+
toData(): SplatData;
|
|
115
|
+
/**
|
|
116
|
+
* The edited cloud written as a file: `'ply'` (Gaussian PLY), `'spz'`, `'splat'` or `'sog'`, by the package's
|
|
117
|
+
* encoders. Hidden and deleted splats are left out.
|
|
118
|
+
* @throws RangeError for another format or when no splats are left; the encoder's errors (SPZ needs `CompressionStream`).
|
|
119
|
+
*/
|
|
120
|
+
encode(format: SplatExportFormat): Promise<Uint8Array<ArrayBuffer>>;
|
|
121
|
+
/**
|
|
122
|
+
* Writes the edited splats into `cloud` (same splat count, as `fromCloud` made it): hidden and deleted splats take
|
|
123
|
+
* opacity 0, so the draw shows the edit without a new cloud.
|
|
124
|
+
* @throws RangeError when the counts differ.
|
|
125
|
+
*/
|
|
126
|
+
applyTo(cloud: Splats): Splats;
|
|
127
|
+
}
|