@margoengine/splats 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +443 -3
- package/dist/animate.d.ts +138 -0
- package/dist/animate.js +31 -0
- package/dist/brush.d.ts +94 -0
- package/dist/brush.js +36 -0
- package/dist/compat-CDoDsXE8.js +19 -0
- package/dist/compat.d.ts +7 -0
- package/dist/compressed.d.ts +40 -0
- package/dist/data-D31W24Wu.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-BA6xu973.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 +167 -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-D0LYo48N.js +1 -0
- package/dist/sog.d.ts +20 -0
- package/dist/sort.d.ts +4 -0
- package/dist/spz-BTy6CPTp.js +1 -0
- package/dist/spz.d.ts +23 -0
- package/dist/src-DlpBlCx1.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-DNluwYbe.js +1 -0
- package/dist/zip.d.ts +7 -0
- package/dist/zstd-BPbUkXlY.js +1 -0
- package/package.json +107 -6
package/dist/modify.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// @margo/core-built 0.1.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
const n=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
|
+
import{n as e}from"./data-D31W24Wu.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("0.1.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("0.1.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 0.1.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("0.1.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{h as e,t}from"./data-D31W24Wu.js";import{t as n}from"./src-DlpBlCx1.js";import{t as r}from"./scene-scope-C5HWuOIb.js";import{t as i}from"./spz-BTy6CPTp.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 0.1.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("0.1.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("0.1.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
|
+
}
|
package/dist/session.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,s as t}from"./data-D31W24Wu.js";var n=1,r=2,i=.2820947918,a=(e,t)=>e?.length===t&&Array.from(e).every(Number.isFinite),o=class o{constructor(t){this.undoStack=[],this.redoStack=[],this.maxHistory=64,this.count=e(t),this.positions=t.positions.slice(),this.covariances=t.covariances.slice(),this.colors=t.colors.slice(),this.sh=t.sphericalHarmonics?.slice(),this.per=this.sh?this.sh.length/this.count/3:0,this.selected=new Uint8Array(this.count),this.state=new Uint8Array(this.count)}static async fromCloud(e){return new o(await e.read())}get selectedCount(){let e=0;for(let t=0;t<this.count;t++)e+=this.selected[t];return e}get selection(){return Uint32Array.from({length:this.count},(e,t)=>t).filter(e=>this.selected[e])}get visibleCount(){let e=0;for(let t=0;t<this.count;t++)e+=+(this.state[t]===0);return e}get canUndo(){return this.undoStack.length>0}get canRedo(){return this.redoStack.length>0}pickWhere(e,t){if(![`replace`,`add`,`subtract`].includes(t))throw RangeError(`Selection mode must be 'replace', 'add' or 'subtract'`);let n=this.selected.slice();for(let r=0;r<this.count;r++){let i=this.state[r]===0&&e(r);t===`replace`?n[r]=+!!i:i&&(n[r]=+(t===`add`))}return this.setSelection(n)}setSelection(e){return e.every((e,t)=>e===this.selected[t])||(this.push({selection:this.selected}),this.selected=e),this}selectAll(){return this.pickWhere(()=>!0,`replace`)}clearSelection(){return this.setSelection(new Uint8Array(this.count))}invertSelection(){let e=new Uint8Array(this.count);for(let t=0;t<this.count;t++)e[t]=+(this.state[t]===0&&!this.selected[t]);return this.setSelection(e)}selectBox(e,t,n=`replace`){if(!a(e,3)||!a(t,3))throw RangeError(`selectBox needs finite min and max of 3 numbers`);let r=this.positions;return this.pickWhere(n=>r[n*3]>=e[0]&&r[n*3]<=t[0]&&r[n*3+1]>=e[1]&&r[n*3+1]<=t[1]&&r[n*3+2]>=e[2]&&r[n*3+2]<=t[2],n)}selectSphere(e,t,n=`replace`){if(!a(e,3)||!(t>=0&&t<1/0))throw RangeError(`selectSphere needs a centre and a radius of 0 or more`);let r=this.positions;return this.pickWhere(n=>(r[n*3]-e[0])**2+(r[n*3+1]-e[1])**2+(r[n*3+2]-e[2])**2<=t*t,n)}project(e){let t=e?.viewProjection;if(!t||t.length!==16||!Array.from(t).every(Number.isFinite)||!(e.width>0)||!(e.height>0))throw RangeError(`A selection view needs a 16-number viewProjection and a positive width and height`);let n=this.positions;return r=>{let i=n[r*3],a=n[r*3+1],o=n[r*3+2],s=t[3]*i+t[7]*a+t[11]*o+t[15];return s>0?[((t[0]*i+t[4]*a+t[8]*o+t[12])/s+1)/2*e.width,(1-(t[1]*i+t[5]*a+t[9]*o+t[13])/s)/2*e.height]:null}}selectBrush(e,t,n,r,i=`replace`){if(![t,n,r].every(Number.isFinite)||r<0)throw RangeError(`selectBrush needs finite x, y and a radius of 0 or more`);let a=this.project(e);return this.pickWhere(e=>{let i=a(e);return!!i&&(i[0]-t)**2+(i[1]-n)**2<=r*r},i)}selectRect(e,t,n,r,i,a=`replace`){if(![t,n,r,i].every(Number.isFinite))throw RangeError(`selectRect needs 4 finite pixel coordinates`);let o=this.project(e),[s,c]=[Math.min(t,r),Math.max(t,r)],[l,u]=[Math.min(n,i),Math.max(n,i)];return this.pickWhere(e=>{let t=o(e);return!!t&&t[0]>=s&&t[0]<=c&&t[1]>=l&&t[1]<=u},a)}selectLasso(e,t,n=`replace`){if(!Array.isArray(t)||t.length<3||!t.every(e=>a(e,2)))throw RangeError(`selectLasso needs a polygon of at least 3 finite [x, y] points`);let r=this.project(e);return this.pickWhere(e=>{let n=r(e);if(!n)return!1;let i=!1;for(let e=0,r=t.length-1;e<t.length;r=e++){let[a,o]=t[e],[s,c]=t[r];o>n[1]!=c>n[1]&&n[0]<(s-a)*(n[1]-o)/(c-o)+a&&(i=!i)}return i},n)}selectByColor(e,t,n=`replace`){if(!a(e,3)||!(t>=0))throw RangeError(`selectByColor needs an RGB colour and a tolerance of 0 or more`);return this.pickWhere(n=>{let r=this.baseColor(n);return(r[0]-e[0])**2+(r[1]-e[1])**2+(r[2]-e[2])**2<=t*t},n)}selectByOpacity(e,t,n=`replace`){if(!(e<=t)||![e,t].every(Number.isFinite))throw RangeError(`selectByOpacity needs min <= max`);return this.pickWhere(n=>this.colors[n*4+3]>=e&&this.colors[n*4+3]<=t,n)}baseColor(e){if(!this.sh)return[this.colors[e*4],this.colors[e*4+1],this.colors[e*4+2]];let t=e*this.per*3;return[0,1,2].map(e=>Math.min(1,Math.max(0,.5+i*this.sh[t+e])))}hideSelected(){return this.markSelected(n)}deleteSelected(){return this.markSelected(r)}markSelected(e){let t=this.indicesOf(this.selected);if(!t.length)return this;this.push({...this.capture(t),selection:this.selected});for(let n of t)this.state[n]|=e;return this.selected=new Uint8Array(this.count),this}unhideAll(){let e=this.indicesOf(this.state,n);if(!e.length)return this;this.push(this.capture(e));for(let t of e)this.state[t]&=-2;return this}transformSelected(e,n={}){let r=this.indicesOf(this.selected),i=Array.from(e??[]),o=n.about;if(o){if(!a(o,3))throw RangeError("transformSelected `about` needs 3 finite numbers");if(i.length===16)for(let e=0;e<3;e++)i[12+e]+=o[e]-(i[e]*o[0]+i[4+e]*o[1]+i[8+e]*o[2])}let s=t(this.subset(r.length?r:[0]),i);return r.length&&(this.push(this.capture(r)),r.forEach((e,t)=>{this.positions.set(s.positions.subarray(t*3,t*3+3),e*3),this.covariances.set(s.covariances.subarray(t*6,t*6+6),e*6),this.sh&&this.sh.set(s.sphericalHarmonics.subarray(t*this.per*3,(t+1)*this.per*3),e*this.per*3)})),this}adjustColor(e){let{brightness:t=1,contrast:n=1,saturation:r=1,hue:a=0,opacity:o=1}=e??{};if(![t,n,r,a,o].every(Number.isFinite)||t<0||r<0||o<0)throw RangeError(`adjustColor needs finite numbers; brightness, saturation and opacity of 0 or more`);let s=this.indicesOf(this.selected);if(!s.length)return this;this.push(this.capture(s));let c=a*Math.PI/180,l=Math.cos(c),u=Math.sin(c),d=(1-l)/3,f=Math.sqrt(1/3)*u,p=[l+d,d-f,d+f,d+f,l+d,d-f,d-f,d+f,l+d];for(let e of s){let a=this.baseColor(e).map(e=>(e*t-.5)*n+.5),s=.2126*a[0]+.7152*a[1]+.0722*a[2];a=a.map(e=>s+(e-s)*r),a=[0,1,2].map(e=>p[e*3]*a[0]+p[e*3+1]*a[1]+p[e*3+2]*a[2]).map(e=>Math.min(1,Math.max(0,e)));for(let t=0;t<3;t++)this.colors[e*4+t]=a[t],this.sh&&(this.sh[e*this.per*3+t]=(a[t]-.5)/i);this.colors[e*4+3]=Math.min(1.5625,this.colors[e*4+3]*o)}return this}undo(){return this.step(this.undoStack,this.redoStack)}redo(){return this.step(this.redoStack,this.undoStack)}step(e,t){let n=e.pop();return n?(t.push(this.swap(n)),!0):!1}push(e){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>this.maxHistory&&this.undoStack.splice(0,this.undoStack.length-this.maxHistory)}capture(e){let t=this.subset(e);return{indices:e,positions:t.positions,covariances:t.covariances,colors:t.colors,sh:t.sphericalHarmonics,state:Uint8Array.from(e,e=>this.state[e])}}swap(e){e.selection&&([e.selection,this.selected]=[this.selected,e.selection]);let t=e.indices;if(t){let n=this.per*3,r=(e,n,r)=>{e&&n&&t.forEach((t,i)=>{for(let a=0;a<r;a++){let o=e[t*r+a];e[t*r+a]=n[i*r+a],n[i*r+a]=o}})};r(this.positions,e.positions,3),r(this.covariances,e.covariances,6),r(this.colors,e.colors,4),r(this.sh,e.sh,n),t.forEach((t,n)=>{let r=this.state[t];this.state[t]=e.state[n],e.state[n]=r})}return e}indicesOf(e,t=255){let n=[];for(let r=0;r<this.count;r++)e[r]&t&&n.push(r);return Uint32Array.from(n)}subset(e){let t=e.length,n=this.per*3,r={positions:new Float32Array(t*3),covariances:new Float32Array(t*6),colors:new Float32Array(t*4)};this.sh&&(r.sphericalHarmonics=new Float32Array(t*n));for(let i=0;i<t;i++){let t=e[i];r.positions.set(this.positions.subarray(t*3,t*3+3),i*3),r.covariances.set(this.covariances.subarray(t*6,t*6+6),i*6),r.colors.set(this.colors.subarray(t*4,t*4+4),i*4),this.sh&&r.sphericalHarmonics.set(this.sh.subarray(t*n,(t+1)*n),i*n)}return r}toData(){let e=Uint32Array.from({length:this.count},(e,t)=>t).filter(e=>this.state[e]===0);if(!e.length)throw RangeError(`No splats are left; undo the deletes or unhide them.`);return this.subset(e)}async encode(e){let t=this.toData();if(e===`ply`)return(await import(`./formats.js`)).encodePly(t);if(e===`spz`)return(await import(`./encode-BA6xu973.js`)).encodeSpz(t);if(e===`sog`)return(await import(`./encode-BA6xu973.js`)).encodeSog(t);if(e===`splat`)return(await import(`./data-D31W24Wu.js`).then(e=>e.g)).encodeSplat(t);throw RangeError(`Export format must be 'ply', 'spz', 'splat' or 'sog'`)}applyTo(e){if(e.count!==this.count)throw RangeError(`applyTo needs a cloud of ${this.count} splats; this one has ${e.count}`);let t=this.subset(Uint32Array.from({length:this.count},(e,t)=>t));for(let e=0;e<this.count;e++)this.state[e]&&(t.colors[e*4+3]=0);return e.write(0,t),e}};export{o as SplatEditSession};
|
package/dist/set.d.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
3
|
+
import { type SplatData } from './data.js';
|
|
4
|
+
import { Splats } from './index.js';
|
|
5
|
+
/** Options of {@link SplatSet}. */
|
|
6
|
+
export interface SplatSetOptions {
|
|
7
|
+
/** Splats the set can hold at once (1 to 3,000,000). Default 1,000,000. */
|
|
8
|
+
capacity?: number;
|
|
9
|
+
/** SH coefficients per channel of every added cloud: 0, 4, 9 or 16. Default 0. */
|
|
10
|
+
coefficients?: number;
|
|
11
|
+
}
|
|
12
|
+
/** A cloud in a {@link SplatSet}: its range in the pool, and how to move or remove it. */
|
|
13
|
+
export interface SplatSetMember {
|
|
14
|
+
/** First pool index of its splats. */
|
|
15
|
+
readonly first: number;
|
|
16
|
+
readonly count: number;
|
|
17
|
+
/** Places the cloud by a column-major 4x4 affine matrix (from its own data, as `transformSplats`). */
|
|
18
|
+
setMatrix(matrix: ArrayLike<number> | null): void;
|
|
19
|
+
/** Whether the cloud is drawn. Default true. Setting it re-uploads only the cloud's positions and colours. */
|
|
20
|
+
visible: boolean;
|
|
21
|
+
/** The cloud's opacity factor, 0 to 1 (default 1), applied to every splat's own opacity. */
|
|
22
|
+
opacity: number;
|
|
23
|
+
/** Takes the cloud out of the set; its range is free again. */
|
|
24
|
+
remove(): void;
|
|
25
|
+
[Symbol.dispose](): void;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Many splat clouds sorted together: `SplatSet.attach(engine, {capacity})`, then `set.add(data, {matrix})` per cloud.
|
|
29
|
+
* Every member's splats go into one `Splats` (`set.cloud`) of `capacity` splats, so the GPU sort orders them all.
|
|
30
|
+
* WebGPU only, as `Splats`.
|
|
31
|
+
* @throws RangeError for a capacity outside 1 to 3,000,000 or other coefficients.
|
|
32
|
+
*/
|
|
33
|
+
export declare class SplatSet {
|
|
34
|
+
readonly cloud: Splats;
|
|
35
|
+
readonly capacity: number;
|
|
36
|
+
private free;
|
|
37
|
+
private readonly members;
|
|
38
|
+
private disposed;
|
|
39
|
+
constructor(options?: SplatSetOptions);
|
|
40
|
+
/** Makes a set and attaches its cloud to `engine`. */
|
|
41
|
+
static attach(engine: EngineKernel, options?: SplatSetOptions): SplatSet;
|
|
42
|
+
/** Splats held by the members. */
|
|
43
|
+
get used(): number;
|
|
44
|
+
/** The members, in the order they were added. */
|
|
45
|
+
get clouds(): readonly SplatSetMember[];
|
|
46
|
+
/**
|
|
47
|
+
* Adds a cloud (with the set's SH coefficient count), placed by `matrix` when given, into the first free range that
|
|
48
|
+
* holds it.
|
|
49
|
+
* @throws RangeError when `data` is invalid, has another SH count, or no free range holds it (`capacity` or
|
|
50
|
+
* fragmentation); MargoError `'disposed'` after `dispose()`.
|
|
51
|
+
*/
|
|
52
|
+
add(data: SplatData, options?: {
|
|
53
|
+
matrix?: ArrayLike<number>;
|
|
54
|
+
}): SplatSetMember;
|
|
55
|
+
private release;
|
|
56
|
+
/** Removes every member and disposes the cloud. */
|
|
57
|
+
dispose(): void;
|
|
58
|
+
[Symbol.dispose]: () => void;
|
|
59
|
+
}
|
package/dist/set.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @margo/core-built 0.1.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
const r=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
|
+
import{n as e,s as t}from"./data-D31W24Wu.js";import{t as n}from"./src-DlpBlCx1.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as i}from"@margoengine/math/errors";var a=class a{constructor(e={}){this.members=/* @__PURE__ */ new Set,this.disposed=!1,this.capacity=e.capacity??1e6,this.cloud=n.reserve(this.capacity,e.coefficients??0),this.free=[[0,this.capacity]]}static attach(e,t={}){__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));let n=new a(t);return r(e).use(n.cloud),n}get used(){let e=0;for(let t of this.members)e+=t.count;return e}get clouds(){return[...this.members]}add(n,r={}){if(this.disposed)throw new i(`disposed`,`This SplatSet was disposed; make a new one`);let a=e(n),o=this.free.findIndex(([,e])=>e>=a);if(o<0)throw RangeError(`No free range of ${a} splats in this SplatSet (${this.capacity-this.used} free); remove clouds or raise capacity`);let s=this.free[o][0];this.cloud.write(s,r.matrix?t(n,r.matrix):n),this.free[o][1]===a?this.free.splice(o,1):this.free[o]=[s+a,this.free[o][1]-a];let c=this,l=new Float32Array(a).map((e,t)=>n.colors[t*4+3]),u=!0,d=!0,f=1,p=()=>c.cloud.setOpacities(s,l,d?f:0),m=()=>{if(!u)throw new i(`disposed`,`This cloud was removed from its SplatSet; add it again with set.add`)},h={first:s,count:a,setMatrix(e){m(),c.cloud.write(s,e?t(n,e):n),(!d||f!==1)&&p()},get visible(){return d},set visible(e){m(),d!==!!e&&(d=!!e,p())},get opacity(){return f},set opacity(e){if(m(),!(e>=0&&e<=1))throw RangeError(`SplatSetMember.opacity must be 0 to 1`);f=e,d&&p()},remove(){u&&(u=!1,c.members.delete(h),!c.disposed&&(c.cloud.clear(s,a),c.release(s,a)))},[Symbol.dispose](){h.remove()}};return this.members.add(h),h}release(e,t){let n=this.free,r=n.findIndex(([t])=>t>e);r<0&&(r=n.length),n.splice(r,0,[e,t]),r+1<n.length&&n[r][0]+n[r][1]===n[r+1][0]&&(n[r][1]+=n[r+1][1],n.splice(r+1,1)),r>0&&n[r-1][0]+n[r-1][1]===n[r][0]&&(n[r-1][1]+=n[r][1],n.splice(r,1))}dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.members])e.remove();this.cloud.dispose()}}[Symbol.dispose??Symbol()](){this.dispose()}};export{a as SplatSet};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import{LinearToSRGB as e,parseColor as t}from"@margoengine/math/color";import{MargoError as n}from"@margoengine/math/errors";function r(e,t){if(!e||e[3]||e[7]||e[11])return null;let n=n=>e[n]*t[0]+e[4+n]*t[1]+e[8+n]*t[2]+e[12+n],r=Math.hypot(e[2],e[6],e[10]),i=n(2);return{sx:Math.hypot(e[0],e[4],e[8]),sy:Math.hypot(e[1],e[5],e[9]),sz:r,ox:n(0),oy:n(1),near:(i-1)/r,far:i/r}}var i=(e,t)=>`
|
|
2
|
+
struct MargoFog {color:vec4f,params:vec4f,eye:vec4f}
|
|
3
|
+
@group(${e}) @binding(${t}) var<uniform> margoFog:MargoFog;
|
|
4
|
+
fn fogAmount(p:vec3f)->f32 {
|
|
5
|
+
let d=distance(p,margoFog.eye.xyz);let q=margoFog.params;
|
|
6
|
+
let amount=select(clamp((d-q.x)/max(q.y-q.x,1e-6),0.0,1.0),1.0-exp(-q.z*q.z*d*d),q.z>0.0);
|
|
7
|
+
return amount*exp(-q.w*max(p.y-margoFog.color.w,0.0));
|
|
8
|
+
}
|
|
9
|
+
`,a=(e,t,n,r)=>{let i=e===void 0?t:e;if(typeof i!=`number`||!Number.isFinite(i)||i<r)throw RangeError(`Fog ${n} is ${String(i)}; pass a finite number${r===0?`, 0 or more`:``}`);return i};function o(e){if(e!==null&&(typeof e!=`object`||Array.isArray(e)))throw TypeError(`Fog must be an object with Fog fields; pass an environment Fog, such an object or null`);return e&&s(e,[0,0,0],/* @__PURE__ */ new Float32Array(12)),e}function s(n,r,i,o=!1){let s=n.enabled??!0;if(typeof s!=`boolean`)throw TypeError(`Fog enabled is ${String(s)}; pass true or false`);let c=a(n.height,0,`height`,-1/0),l=a(n.near,1,`near`,0),u=a(n.far,1e3,`far`,0),d=a(n.density,0,`density`,0),f=a(n.heightFalloff,0,`heightFalloff`,0);if(t(n.color??`#ffffff`,i,0),o)for(let t=0;t<3;t++)i[t]=e(i[t]);i[3]=c,i[4]=l,i[5]=u,i[6]=d,i[7]=f,s||(i.fill(0,0,8),i[4]=i[5]=34028234663852886e22),i[8]=r[0],i[9]=r[1],i[10]=r[2],i[11]=0}var c=/* @__PURE__ */ Object.freeze({color:{srcFactor:`src-alpha`,dstFactor:`one-minus-src-alpha`,operation:`add`},alpha:{srcFactor:`one`,dstFactor:`one-minus-src-alpha`,operation:`add`}});function l(e,t,n,r,i){let a=e.includes(`var<private> margoCoverage:u32`);return`\n@fragment fn transparent(${t}${a?`,@builtin(sample_mask) margoMask:u32`:``})->MargoTransparent {${a?`margoCoverage=margoMask;`:``}return margoTransparentAt(${n},${r},${i});}\n`}function u(){return{hook:void 0,released:void 0,set(e,t){return this.hook=e,this.released=t,()=>{this.hook===e&&(this.hook=this.released=void 0)}}}}function d(e,t,n,r){let i=t.begin();return i.setPipeline(n),i.setBindGroup(0,r),i.setBindGroup(1,e.createBindGroup({layout:n.getBindGroupLayout(1),entries:t.bindings()})),i}var f=`struct Frame {camera:mat4x4f,view:mat4x4f,eye:vec4f,viewport:vec4f,settings:vec4f,counts:vec4u}
|
|
10
|
+
@group(0) @binding(0) var<uniform> f:Frame;
|
|
11
|
+
struct Ellipse {center:vec4f,axes:vec4f}`,p=`
|
|
12
|
+
@group(0) @binding(1) var<storage,read> positions:array<vec4f>;
|
|
13
|
+
@group(0) @binding(2) var<storage,read> covariances:array<vec4f>;`,m=`
|
|
14
|
+
struct Projected {ellipse:Ellipse,key:u32}
|
|
15
|
+
fn projectSplat(index:u32)->Projected {
|
|
16
|
+
let world=positions[index];let p=f.view*vec4f(world.xyz,1);let depth=-p.z;
|
|
17
|
+
var ellipse:Ellipse;ellipse.center=vec4f(2,2,0,0);ellipse.axes=vec4f(0);var key=0xffffffffu;
|
|
18
|
+
if(depth>=f.settings.x&&depth<=f.settings.y&&world.w>0){
|
|
19
|
+
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));
|
|
20
|
+
let rotation=mat3x3f(f.view[0].xyz,f.view[1].xyz,f.view[2].xyz);let c=rotation*covariance*transpose(rotation);
|
|
21
|
+
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);
|
|
22
|
+
if(f.settings.w>0.5){jx=vec3f(f.viewport.z,0,0);jy=vec3f(0,f.viewport.w,0);}
|
|
23
|
+
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;
|
|
24
|
+
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));}
|
|
25
|
+
let mid=(xx+yy)*0.5;let radius=sqrt(max(0.0,(xx-yy)*(xx-yy)*0.25+xy*xy));
|
|
26
|
+
let major=max(mid+radius,0.3);let minor=max(mid-radius,0.3);var axis=vec2f(1,0);
|
|
27
|
+
if(abs(xy)>0.000001){axis=normalize(vec2f(xy,major-xx));}else if(yy>xx){axis=vec2f(0,1);}
|
|
28
|
+
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;
|
|
29
|
+
let clip=f.camera*vec4f(world.xyz,1);let ndc=clip.xyz/clip.w;let extent=abs(first)+abs(second);
|
|
30
|
+
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));}
|
|
31
|
+
}return Projected(ellipse,key);
|
|
32
|
+
}`,h=f+p+m+`
|
|
33
|
+
@group(0) @binding(3) var<storage,read> colors:array<vec4f>;
|
|
34
|
+
@group(0) @binding(4) var<storage,read> sh:array<f32>;
|
|
35
|
+
@group(0) @binding(5) var<storage,read_write> ellipses:array<Ellipse>;
|
|
36
|
+
@group(0) @binding(6) var<storage,read_write> evaluated:array<vec4f>;
|
|
37
|
+
@group(0) @binding(7) var<storage,read_write> keys:array<vec2u>;
|
|
38
|
+
fn color(index:u32)->vec3f {
|
|
39
|
+
if(f.counts.y==0){return colors[index].rgb;}
|
|
40
|
+
var direction=normalize(positions[index].xyz-f.eye.xyz);if(f.settings.w>0.5){direction=-vec3f(f.view[0].z,f.view[1].z,f.view[2].z);}let x=direction.x;let y=direction.y;let z=direction.z;
|
|
41
|
+
var basis:array<f32,25>;basis[0]=0.2820947918;basis[1]=-0.4886025119*y;basis[2]=0.4886025119*z;basis[3]=-0.4886025119*x;
|
|
42
|
+
basis[4]=1.0925484306*x*y;basis[5]=-1.0925484306*y*z;basis[6]=0.3153915653*(3*z*z-1);basis[7]=-1.0925484306*x*z;basis[8]=0.5462742153*(x*x-y*y);
|
|
43
|
+
basis[9]=-0.5900435899*y*(3*x*x-y*y);basis[10]=2.8906114426*x*y*z;basis[11]=-0.4570457995*y*(5*z*z-1);basis[12]=0.3731763326*z*(5*z*z-3);
|
|
44
|
+
basis[13]=-0.4570457995*x*(5*z*z-1);basis[14]=1.4453057213*z*(x*x-y*y);basis[15]=-0.5900435899*x*(x*x-3*y*y);
|
|
45
|
+
basis[16]=2.5033429418*x*y*(x*x-y*y);basis[17]=-1.7701307698*y*z*(3*x*x-y*y);basis[18]=0.9461746958*x*y*(7*z*z-1);
|
|
46
|
+
basis[19]=-0.6690465436*y*z*(7*z*z-3);basis[20]=0.1057855469*(35*z*z*z*z-30*z*z+3);basis[21]=-0.6690465436*x*z*(7*z*z-3);
|
|
47
|
+
basis[22]=0.4730873479*(x*x-y*y)*(7*z*z-1);basis[23]=-1.7701307698*x*z*(x*x-3*y*y);basis[24]=0.6258357354*(x*x*x*x-6*x*x*y*y+y*y*y*y);
|
|
48
|
+
var c=vec3f(0.5);for(var i=0u;i<f.counts.y;i++){let at=(index*f.counts.y+i)*3;c+=basis[i]*vec3f(sh[at],sh[at+1],sh[at+2]);}return max(c,vec3f(0));
|
|
49
|
+
}
|
|
50
|
+
@compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u) {
|
|
51
|
+
let index=id.x;if(index>=f.counts.x){return;}let world=positions[index];let projected=projectSplat(index);
|
|
52
|
+
ellipses[index]=projected.ellipse;keys[index]=vec2u(projected.key,index);evaluated[index]=vec4f(color(index),world.w);
|
|
53
|
+
}`;function g(){let e=`evaluated[index]=vec4f(color(index),world.w);`;if(h.split(e).length!==2)throw new n(`unsupported`,`Splat fog needs the projection shader it was written for; update its fog edit`);return h.replace(e,`evaluated[index]=vec4f(mix(color(index),margoFog.color.rgb,fogAmount(world.xyz)),world.w);`)+i(0,8)}var _=f+`
|
|
54
|
+
@group(0) @binding(1) var<storage,read> ellipses:array<Ellipse>;
|
|
55
|
+
@group(0) @binding(2) var<storage,read> colors:array<vec4f>;
|
|
56
|
+
@group(0) @binding(3) var<storage,read> sorted:array<vec2u>;
|
|
57
|
+
struct Out {@builtin(position) clip:vec4f,@location(0) corner:vec2f,@location(1) color:vec4f}
|
|
58
|
+
@vertex fn vertex(@builtin(vertex_index) vertex:u32,@builtin(instance_index) instance:u32)->Out {
|
|
59
|
+
let corners=array<vec2f,4>(vec2f(-1,-1),vec2f(1,-1),vec2f(-1,1),vec2f(1,1));let index=sorted[instance].y;let e=ellipses[index];let corner=corners[vertex];var o:Out;
|
|
60
|
+
o.clip=vec4f(e.center.xy+e.axes.xy*corner.x+e.axes.zw*corner.y,e.center.z,1);o.corner=corner;o.color=vec4f(colors[index].rgb,e.center.w);
|
|
61
|
+
if(e.center.w==0){o.clip=vec4f(2,2,0,1);}return o;
|
|
62
|
+
}
|
|
63
|
+
@fragment fn fragment(i:Out)->@location(0) vec4f {let power=-4.5*dot(i.corner,i.corner);if(power<-4.5){discard;}let alpha=min(0.99,i.color.a*exp(power));if(alpha<1.0/255){discard;}
|
|
64
|
+
var c=i.color.rgb;if(f.settings.z<0.5){c=clamp(c,vec3f(0),vec3f(1));c=select(c*12.92,1.055*pow(c,vec3f(1.0/2.4))-0.055,c>=vec3f(0.0031308));}return vec4f(c,alpha);}`,v=[[`@location(1) color:vec4f}`,`@location(1) color:vec4f,@location(2) margoDepth:f32}`],[`o.corner=corner;`,`o.corner=corner;o.margoDepth=bitcast<f32>(~sorted[instance].x)+select(0.0,f.settings.x,f.settings.w>0.5);`],[`@fragment fn fragment(i:Out)->@location(0) vec4f {`,`fn margoShade(i:Out)->vec4f {`]];function y(e){let t=_;for(let[e,r]of v){if(t.split(e).length!==2)throw new n(`unsupported`,`Splat transparency needs the render shader it was written for; update its edits`);t=t.replace(e,r)}return e+t+l(e,`i:Out`,`margoShade(i)`,`i.clip`,`i.margoDepth`)}export{m as a,c,o as d,s as f,p as i,d as l,f as n,_ as o,r as p,h as r,y as s,g as t,u};
|
package/dist/shader.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare const frame = "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}";
|
|
2
|
+
/** The two inputs the projection reads (bindings 1 and 2), read only, so a vertex shader can project as well. */
|
|
3
|
+
export declare const projectInputs = "\n@group(0) @binding(1) var<storage,read> positions:array<vec4f>;\n@group(0) @binding(2) var<storage,read> covariances:array<vec4f>;";
|
|
4
|
+
/**
|
|
5
|
+
* One splat's screen ellipse (centre in NDC with its opacity in w, the two 3 sigma half axes in NDC) and sort key, or
|
|
6
|
+
* a culled one (opacity 0, off screen) with key 0xffffffff. Reads only `f`, `positions` and `covariances`.
|
|
7
|
+
*/
|
|
8
|
+
export declare const projectSplat = "\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}";
|
|
9
|
+
export declare const project: string;
|
|
10
|
+
/**
|
|
11
|
+
* The projection pass with scene fog (`setFog`, uniform at binding 8): each splat's evaluated colour fades toward the
|
|
12
|
+
* fog colour by the fog at its centre, in linear before the render pass clamps and encodes it. `project` is unchanged.
|
|
13
|
+
*/
|
|
14
|
+
export declare function foggedProject(): string;
|
|
15
|
+
export declare const render: string;
|
|
16
|
+
/** `render` with its fragment feeding a transparency hook. */
|
|
17
|
+
export declare function transparentRender(declarations: string): string;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { ColorInput } from '@margoengine/math/color';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Fog as `@margoengine/environment`'s `Fog` exposes it: pass that Fog, or any object with these fields. Read every
|
|
5
|
+
* frame, so changing the Fog changes the fog at once. Missing fields take Fog's defaults. A negative or non-finite
|
|
6
|
+
* distance, density or falloff (or a non-finite height) throws a RangeError, a malformed colour a TypeError or
|
|
7
|
+
* RangeError, a non-boolean `enabled` a TypeError.
|
|
8
|
+
*/
|
|
9
|
+
export interface FogLike {
|
|
10
|
+
/** Fog colour: hex is sRGB, `[r, g, b]` linear. Default '#ffffff'. */
|
|
11
|
+
readonly color?: ColorInput;
|
|
12
|
+
/** Linear fog start distance from the camera. Default 1. */
|
|
13
|
+
readonly near?: number;
|
|
14
|
+
/** Linear fog end distance, where fog is full. Default 1000. */
|
|
15
|
+
readonly far?: number;
|
|
16
|
+
/** Above 0 selects exponential-squared fog `1 - exp(-(density * distance)^2)`. Default 0. */
|
|
17
|
+
readonly density?: number;
|
|
18
|
+
/** Height fog: fog thins by `exp(-heightFalloff * (y - height))` above world height `height`. Default 0 (off). */
|
|
19
|
+
readonly heightFalloff?: number;
|
|
20
|
+
/** World height below which fog is at full strength. Default 0. */
|
|
21
|
+
readonly height?: number;
|
|
22
|
+
/** False mixes in no fog; switching never recompiles. Default true. */
|
|
23
|
+
readonly enabled?: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Bytes of the fog uniform: colour and height, near/far/density/falloff, camera position. */
|
|
27
|
+
export const FOG_BYTES: 48;
|
|
28
|
+
/** WGSL: the fog uniform at `@group(group) @binding(binding)` and `fogAmount(world position)`, 0 (clear) to 1. */
|
|
29
|
+
export function fogWgsl(group: number, binding: number): string;
|
|
30
|
+
/** Throws when `fog` is neither null nor an object; `setFog` calls it so a wrong argument fails where it is passed. */
|
|
31
|
+
export function checkFog(fog: FogLike | null): FogLike | null;
|
|
32
|
+
/** Validates `fog` and writes the 12-float fog uniform into `out` (colour sRGB-encoded with `encode`). */
|
|
33
|
+
export function writeFog(fog: FogLike, eye: ArrayLike<number>, out: Float32Array, encode?: boolean): void;
|