@margoengine/splats 0.1.0 → 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/dist/pick.js CHANGED
@@ -1,4 +1,4 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
3
 
4
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}
@@ -11,4 +11,4 @@ struct PickOut {@builtin(position) clip:vec4f,@location(0) corner:vec2f,@locatio
11
11
  if(e.center.w==0){o.clip=vec4f(2,2,0,1);}return o;
12
12
  }
13
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};
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};
@@ -1,4 +1,4 @@
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
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
2
  `)>=0?e.indexOf(`end_header
3
3
  `)+11:e.indexOf(`end_header\r
4
4
  `)>=0?e.indexOf(`end_header\r
@@ -1,4 +1,4 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
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};
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};
package/dist/session.js CHANGED
@@ -1 +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};
1
+ import{n as e,s as t}from"./data-BDt3mxGg.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-BfG7xkVn.js`)).encodeSpz(t);if(e===`sog`)return(await import(`./encode-BfG7xkVn.js`)).encodeSog(t);if(e===`splat`)return(await import(`./data-BDt3mxGg.js`).then(e=>e.f)).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.js CHANGED
@@ -1,4 +1,4 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
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};
3
+ const r=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{n as e,s 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";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("1.0.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};
@@ -1,33 +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;
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;
@@ -1,53 +1,53 @@
1
- /** A reusable pass descriptor drawing over the frame: colour load/store, depth and stencil read only. */
2
- export function overlayPass(): GPURenderPassDescriptor & {
3
- colorAttachments: [GPURenderPassColorAttachment];
4
- depthStencilAttachment: GPURenderPassDepthStencilAttachment;
5
- };
6
- /** {@link overlayPass} that also loads and stores depth. */
7
- export function overlayDepthPass(): GPURenderPassDescriptor & {
8
- colorAttachments: [GPURenderPassColorAttachment];
9
- depthStencilAttachment: GPURenderPassDepthStencilAttachment;
10
- };
11
- /** Straight (non-premultiplied) alpha blending. */
12
- export const alphaBlend: GPUBlendState;
13
- /** Straight alpha blending that leaves the target's alpha channel unchanged: precipitation and other overlays drawn into a frame. */
14
- export const overlayBlend: GPUBlendState;
15
-
16
- /** `mesh` when it is null or a core mesh handle (checked live); else a TypeError. */
17
- export function attachableMesh<M extends { check(): void } | null>(mesh: M): M;
18
- /**
19
- * What an order-independent pass offers an effect that is no PBR surface (particles, splats, points), in place of
20
- * gltf/pbr's transparency hook. Same contract, but `surface` declares `fn margoTransparentAt(color:vec4f,clip:vec4f,
21
- * depth:f32)->MargoTransparent`: `clip` is the fragment's position builtin, `depth` its view depth.
22
- */
23
- export interface SurfaceTransparency {
24
- /** Module-scope WGSL: `struct MargoTransparent` (one output per target), `margoTransparentAt` and its bindings in `group`. */
25
- surface(group: number): string;
26
- /** Layout of those bindings, for an effect with explicit pipeline layouts. */
27
- readonly layout: readonly GPUBindGroupLayoutEntry[];
28
- /** Entries for those bindings. */
29
- bindings(): GPUBindGroupEntry[];
30
- /** True: declarations hold `override margoKind:u32`, 0 normal, 1 additive; additive surfaces may draw here. */
31
- readonly blends?: boolean;
32
- /** Colour targets of the transparent pass, in `MargoTransparent` location order. */
33
- readonly targets: readonly GPUColorTargetState[];
34
- /** This frame's transparent pass, begun on the first draw and ended by the owner. */
35
- begin(): GPURenderPassEncoder;
36
- }
37
- /** The fragment entry `transparent` of an effect under a transparency hook: `inputs` are its parameters, the rest WGSL expressions. */
38
- export function surfaceEntry(declarations: string, inputs: string, color: string, clip: string, depth: string): string;
39
- /** Holds an effect's transparency hook: `set` takes it and `released`, and returns the remover. */
40
- export function transparencySlot(): {
41
- hook?: SurfaceTransparency;
42
- released?: () => void;
43
- set(hook: SurfaceTransparency, released?: () => void): () => void;
44
- };
45
- /** `hook`'s pass with `pipeline` set, `group` at group 0 and the hook's bindings at group 1, for an effect with an auto layout. */
46
- export function surfacePass(
47
- device: GPUDevice,
48
- hook: SurfaceTransparency,
49
- pipeline: GPURenderPipeline,
50
- group: GPUBindGroup,
51
- ): GPURenderPassEncoder;
52
- /** The WGSL `make(group)` builds for bind group `group`, made once per group and kept in `cache`. */
53
- export function groupCode(cache: Map<number, string>, group: number, make: (group: number) => string): string;
1
+ /** A reusable pass descriptor drawing over the frame: colour load/store, depth and stencil read only. */
2
+ export function overlayPass(): GPURenderPassDescriptor & {
3
+ colorAttachments: [GPURenderPassColorAttachment];
4
+ depthStencilAttachment: GPURenderPassDepthStencilAttachment;
5
+ };
6
+ /** {@link overlayPass} that also loads and stores depth. */
7
+ export function overlayDepthPass(): GPURenderPassDescriptor & {
8
+ colorAttachments: [GPURenderPassColorAttachment];
9
+ depthStencilAttachment: GPURenderPassDepthStencilAttachment;
10
+ };
11
+ /** Straight (non-premultiplied) alpha blending. */
12
+ export const alphaBlend: GPUBlendState;
13
+ /** Straight alpha blending that leaves the target's alpha channel unchanged: precipitation and other overlays drawn into a frame. */
14
+ export const overlayBlend: GPUBlendState;
15
+
16
+ /** `mesh` when it is null or a core mesh handle (checked live); else a TypeError. */
17
+ export function attachableMesh<M extends { check(): void } | null>(mesh: M): M;
18
+ /**
19
+ * What an order-independent pass offers an effect that is no PBR surface (particles, splats, points), in place of
20
+ * gltf/pbr's transparency hook. Same contract, but `surface` declares `fn margoTransparentAt(color:vec4f,clip:vec4f,
21
+ * depth:f32)->MargoTransparent`: `clip` is the fragment's position builtin, `depth` its view depth.
22
+ */
23
+ export interface SurfaceTransparency {
24
+ /** Module-scope WGSL: `struct MargoTransparent` (one output per target), `margoTransparentAt` and its bindings in `group`. */
25
+ surface(group: number): string;
26
+ /** Layout of those bindings, for an effect with explicit pipeline layouts. */
27
+ readonly layout: readonly GPUBindGroupLayoutEntry[];
28
+ /** Entries for those bindings. */
29
+ bindings(): GPUBindGroupEntry[];
30
+ /** True: declarations hold `override margoKind:u32`, 0 normal, 1 additive; additive surfaces may draw here. */
31
+ readonly blends?: boolean;
32
+ /** Colour targets of the transparent pass, in `MargoTransparent` location order. */
33
+ readonly targets: readonly GPUColorTargetState[];
34
+ /** This frame's transparent pass, begun on the first draw and ended by the owner. */
35
+ begin(): GPURenderPassEncoder;
36
+ }
37
+ /** The fragment entry `transparent` of an effect under a transparency hook: `inputs` are its parameters, the rest WGSL expressions. */
38
+ export function surfaceEntry(declarations: string, inputs: string, color: string, clip: string, depth: string): string;
39
+ /** Holds an effect's transparency hook: `set` takes it and `released`, and returns the remover. */
40
+ export function transparencySlot(): {
41
+ hook?: SurfaceTransparency;
42
+ released?: () => void;
43
+ set(hook: SurfaceTransparency, released?: () => void): () => void;
44
+ };
45
+ /** `hook`'s pass with `pipeline` set, `group` at group 0 and the hook's bindings at group 1, for an effect with an auto layout. */
46
+ export function surfacePass(
47
+ device: GPUDevice,
48
+ hook: SurfaceTransparency,
49
+ pipeline: GPURenderPipeline,
50
+ group: GPUBindGroup,
51
+ ): GPURenderPassEncoder;
52
+ /** The WGSL `make(group)` builds for bind group `group`, made once per group and kept in `cache`. */
53
+ export function groupCode(cache: Map<number, string>, group: number, make: (group: number) => string): string;
@@ -1 +1 @@
1
- import{_ as e,v as t}from"./data-D31W24Wu.js";import{n}from"./zip-DNluwYbe.js";import{MargoError as r}from"@margoengine/math/errors";var i=(e,t)=>Object.assign(Error(e,t===void 0?void 0:{cause:t}),{name:`MargoError`,code:`failed`}),a=e=>Object.assign(Error(e),{name:`MargoError`,code:`unsupported`}),o=e=>{throw i(`Not a valid lossless WebP image: ${e}; pass the complete bytes of the file`)},s=[0,1,1,0,1,1,-1,1,0,2,2,0,1,2,-1,2,2,1,-2,1,2,2,-2,2,0,3,3,0,1,3,-1,3,3,1,-3,1,2,3,-2,3,3,2,-3,2,0,4,4,0,1,4,-1,4,4,1,-4,1,3,3,-3,3,2,4,-2,4,4,2,-4,2,0,5,3,4,-3,4,4,3,-4,3,5,0,1,5,-1,5,5,1,-5,1,2,5,-2,5,5,2,-5,2,4,4,-4,4,3,5,-3,5,5,3,-5,3,0,6,6,0,1,6,-1,6,6,1,-6,1,2,6,-2,6,6,2,-6,2,4,5,-4,5,5,4,-5,4,3,6,-3,6,6,3,-6,3,0,7,7,0,1,7,-1,7,5,5,-5,5,7,1,-7,1,4,6,-4,6,6,4,-6,4,2,7,-2,7,7,2,-7,2,3,7,-3,7,7,3,-7,3,5,6,-5,6,6,5,-6,5,8,0,4,7,-4,7,7,4,-7,4,8,1,8,2,6,6,-6,6,8,3,5,7,-5,7,7,5,-7,5,8,4,6,7,-6,7,7,6,-7,6,8,5,7,7,-7,7,8,6,8,7],c=[17,18,0,1,2,3,4,5,16,6,7,8,9,10,11,12,13,14,15],l=class{constructor(e,t){this.bytes=e,this.offset=t,this.acc=0,this.have=0}read(e){for(;this.have<e;)this.offset>=this.bytes.length&&o(`the data ends early`),this.acc|=this.bytes[this.offset++]<<this.have,this.have+=8;let t=this.acc&(1<<e)-1;return this.acc>>>=e,this.have-=e,t}},u=class{constructor(e){this.count=/* @__PURE__ */ new Uint32Array(16);let t=0,n=0;for(let r=0;r<e.length;r++)e[r]&&(this.count[e[r]]++,t++,n=r);if(this.single=t===1?n:-1,t===0&&o(`an empty prefix code`),t>1){let e=1;for(let t=1;t<16;t++)e=e*2-this.count[t],e<0&&o(`an over-subscribed prefix code`);e!==0&&o(`an incomplete prefix code`)}let r=/* @__PURE__ */ new Uint32Array(17);for(let e=1;e<16;e++)r[e+1]=r[e]+this.count[e];this.symbols=new Uint16Array(t);for(let t=0;t<e.length;t++)e[t]&&(this.symbols[r[e[t]]++]=t)}decode(e){if(this.single>=0)return this.single;let t=0,n=0,r=0;for(let i=1;i<16;i++){t|=e.read(1);let a=this.count[i];if(t-a<n)return this.symbols[r+(t-n)];r+=a,n=n+a<<1,t<<=1}return o(`an invalid prefix code in the data`)}};function d(e,t){let n=new Uint8Array(t);if(e.read(1)){let r=e.read(1),i=e.read(1)?e.read(8):e.read(1);if(i>=t&&o(`a symbol outside its alphabet`),n[i]=1,r){let r=e.read(8);r>=t&&o(`a symbol outside its alphabet`),r===i&&o(`a simple code that repeats a symbol`),n[r]=1}return new u(n)}let r=/* @__PURE__ */ new Uint8Array(19),i=4+e.read(4);for(let t=0;t<i;t++)r[c[t]]=e.read(3);let a=new u(r),s=t;e.read(1)&&(s=2+e.read(2+2*e.read(3)),s>t&&o(`a code-length run longer than the alphabet`));let l=0,d=8;for(;l<t&&s--!==0;){let r=a.decode(e);if(r<16){n[l++]=r,r&&(d=r);continue}let i=r===16?3+e.read(2):r===17?3+e.read(3):11+e.read(7),s=r===16?d:0;l+i>t&&o(`a code-length repeat past the alphabet`);for(let e=0;e<i;e++)n[l++]=s}return new u(n)}var f=(e,t)=>{if(t<4)return t+1;let n=t-2>>1;return(2+(t&1)<<n)+e.read(n)+1};function p(e,t,n,r){let i=0;e.read(1)&&(i=e.read(4),(i<1||i>11)&&o(`a colour cache size outside 1..11 bits`));let a=0,c,l=1;if(r&&e.read(1)){a=e.read(3)+2;let r=p(e,Math.ceil(t/(1<<a)),Math.ceil(n/(1<<a)),!1);c=new Uint32Array(r.length);for(let e=0;e<r.length;e++)c[e]=r[e]>>>8&65535,l=Math.max(l,c[e]+1)}let u=i?1<<i:0,m=[];for(let t=0;t<l;t++)m.push([d(e,280+u),d(e,256),d(e,256),d(e,256),d(e,40)]);let h=new Uint32Array(t*n),g=i?new Uint32Array(u):void 0,_=32-i,v=0,y=0,b=()=>{if(g)for(;y<v;y++)g[Math.imul(506832829,h[y])>>>_]=h[y]};for(;v<h.length;){let n=v%t,r=(v-n)/t,i=c?m[c[(r>>a)*Math.ceil(t/(1<<a))+(n>>a)]]:m[0];i||o(`a pixel that names a missing prefix group`);let l=i[0].decode(e);if(l<256){let t=i[1].decode(e),n=i[2].decode(e),r=i[3].decode(e);h[v++]=(r<<24|t<<16|l<<8|n)>>>0}else if(l<280){let n=f(e,l-256),r=f(e,i[4].decode(e)),a;r>120?a=r-120:(a=s[(r-1)*2]+s[(r-1)*2+1]*t,a<1&&(a=1)),(a>v||v+n>h.length)&&o(`a backward reference outside the image`);for(let e=0;e<n;e++,v++)h[v]=h[v-a]}else g||o(`a colour-cache symbol with no cache`),b(),h[v++]=g[l-280];b()}return h}var m=(e,t)=>(((e^t)&4278124286)>>>1)+(e&t)>>>0,h=e=>e<0?0:e>255?255:e,g=(e,t)=>e>>>t&255;function _(e,t,n,r){let i=t[n-1],a=t[n-r],o=t[n-r+1],s=t[n-r-1];switch(e){case 1:return i;case 2:return a;case 3:return o;case 4:return s;case 5:return m(m(i,o),a);case 6:return m(i,s);case 7:return m(i,a);case 8:return m(s,a);case 9:return m(a,o);case 10:return m(m(i,s),m(a,o));case 11:{let e=0,t=0;for(let n=0;n<32;n+=8){let r=g(i,n)+g(a,n)-g(s,n);e+=Math.abs(r-g(i,n)),t+=Math.abs(r-g(a,n))}return e<t?i:a}case 12:{let e=0;for(let t=0;t<32;t+=8)e+=h(g(i,t)+g(a,t)-g(s,t))*2**t;return e>>>0}case 13:{let e=m(i,a),t=0;for(let n=0;n<32;n+=8)t+=h(g(e,n)+Math.trunc((g(e,n)-g(s,n))/2))*2**n;return t>>>0}default:return 4278190080}}var v=(e,t)=>(((e&4278255360)>>>0)+((t&4278255360)>>>0)&4278255360|(e&16711935)+(t&16711935)&16711935)>>>0,y=(e,t)=>(e<<24>>24)*(t<<24>>24)>>5;function b(e,t,n){let r=[],i=/* @__PURE__ */ new Set,a=t;for(;e.read(1);){let t=e.read(2);i.has(t)&&o(`a repeated transform`),i.add(t);let s={type:t,bits:0,width:a,data:/* @__PURE__ */ new Uint32Array};if(t===0||t===1)s.bits=e.read(3)+2,s.data=p(e,Math.ceil(a/(1<<s.bits)),Math.ceil(n/(1<<s.bits)),!1);else if(t===3){let t=e.read(8)+1,n=p(e,t,1,!1);for(let e=1;e<t;e++)n[e]=v(n[e],n[e-1]);s.data=n,s.bits=t<=2?3:t<=4?2:+(t<=16),a=Math.ceil(a/(1<<s.bits))}r.push(s)}let s=p(e,a,n,!0);for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.type===2)for(let e=0;e<s.length;e++){let t=s[e],n=t>>>8&255;s[e]=(t&4278255360|((t>>>16&255)+n&255)<<16|(t&255)+n&255)>>>0}else if(t.type===1){let e=Math.ceil(t.width/(1<<t.bits));for(let r=0;r<n;r++)for(let n=0;n<t.width;n++){let i=t.data[(r>>t.bits)*e+(n>>t.bits)],a=r*t.width+n,o=s[a],c=o>>>8&255,l=o>>>16&255,u=o&255;l=l+y(i&255,c)&255,u=u+y(i>>>8&255,c)+y(i>>>16&255,l)&255,s[a]=(o&4278255360|l<<16|u)>>>0}}else if(t.type===0){let e=Math.ceil(t.width/(1<<t.bits)),r=t.width;for(let i=0;i<n;i++)for(let n=0;n<r;n++){let a=i*r+n,o;o=i===0?n===0?4278190080:s[a-1]:n===0?s[a-r]:_(t.data[(i>>t.bits)*e+(n>>t.bits)]>>>8&15,s,a,r),s[a]=v(s[a],o)}}else{let e=8>>t.bits,r=(1<<e)-1,i=new Uint32Array(t.width*n),a=t.data,o=Math.ceil(t.width/(1<<t.bits));for(let c=0;c<n;c++)for(let n=0;n<t.width;n++){let l=s[c*o+(n>>t.bits)]>>>8&255,u=t.bits?l>>(n&(1<<t.bits)-1)*e&r:l;i[c*t.width+n]=u<a.length?a[u]:0}s=i}}return s}function x(e,t,n){let r=new l(e.subarray(0,n),t);r.read(8)!==47&&o(`a bad VP8L signature`);let i=r.read(14)+1,a=r.read(14)+1;r.read(1),r.read(3)!==0&&o(`an unknown VP8L version`);let s=b(r,i,a),c=new Uint8Array(i*a*4);for(let e=0;e<i*a;e++){let t=s[e];c[e*4]=t>>>16&255,c[e*4+1]=t>>>8&255,c[e*4+2]=t&255,c[e*4+3]=t>>>24}return{width:i,height:a,data:c}}function S(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);(e.length<20||t.getUint32(0,!0)!==1179011410||t.getUint32(8,!0)!==1346520407)&&o(`missing the RIFF WEBP header`);let n=12,r=-1,i=0;for(;n+8<=e.length;){let e=t.getUint32(n,!0),o=t.getUint32(n+4,!0);if(e===1278758998){r=n+8,i=o;break}if(e===540561494)throw a(`This WebP is lossy (VP8); read it with parseWebP.`);n+=8+o+(o&1)}return(r<0||r+i>e.length)&&o(`no VP8L chunk`),x(e,r,r+i)}var C=/* @__PURE__ */ t({parseSog:()=>E}),w=e=>e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),T=[0,3,8,15,24];async function E(t,i={}){let{signal:a}=i,o;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)){let e=w(t);if(e.length<4||e[0]!==80||e[1]!==75)throw RangeError(`Not a SOG file: a bundled .sog is a ZIP archive; pass the whole file or its loose files.`);o=await n(e,a)}else if(t&&typeof t==`object`)o=new Map(Object.entries(t).map(([e,t])=>{if(!(t instanceof ArrayBuffer)&&!ArrayBuffer.isView(t))throw TypeError(`SOG file ${e} must be an ArrayBuffer or typed array`);return[e,w(t)]}));else throw TypeError(`Expected .sog bytes or a map of SOG file names to bytes; pass an ArrayBuffer, typed array or file map`);let s=o.get(`meta.json`);if(!s)throw RangeError(`The SOG has no meta.json; pass the complete archive or all of its files.`);let c;try{c=JSON.parse(new TextDecoder().decode(s))}catch{throw RangeError(`The SOG meta.json is not valid JSON; check that the file is complete.`)}if(c.version!==2&&c.version!==3)throw RangeError(`SOG version ${c.version} is not supported; this reader handles versions 2 and 3, re-export the scene.`);if(c.model!==void 0&&c.model!==`antialiased`)throw new r(`unsupported`,`SOG model ${c.model} is not supported; 2D Gaussian scenes cannot be drawn here.`);let l=c.count;if(!Number.isInteger(l)||l<1||l>3e6)throw RangeError(`A SOG needs 1 to 3,000,000 splats.`);let u=e=>{a?.throwIfAborted();let t=e===void 0?void 0:o.get(e);if(!t)throw RangeError(`The SOG is missing the texture ${e}; pass the complete archive.`);try{return S(t)}catch(t){throw t.code===`unsupported`?new r(`unsupported`,`The SOG texture ${e} is lossy WebP; re-export the SOG with lossless textures.`):RangeError(`The SOG texture ${e} is damaged; re-export the SOG with lossless textures.`,{cause:t})}},[d,f]=c.means?.files??[],p=u(d),m=u(f),h=u(c.scales?.files?.[0]),g=c.version===2?u(c.quats?.files?.[0]):void 0,_=u(c.sh0?.files?.[0]);for(let e of[m,h,...g?[g]:[],_])if(e.width!==p.width||e.height!==p.height)throw RangeError(`The SOG textures differ in size; the file is damaged.`);if(p.width*p.height<l)throw RangeError(`The SOG textures hold fewer pixels than its splat count; the file is damaged, re-export it`);for(let e of[c.scales?.codebook,c.sh0?.codebook])if(!Array.isArray(e)||e.length!==256)throw RangeError(`A SOG codebook must have 256 entries.`);if(!Array.isArray(c.means.mins)||!Array.isArray(c.means.maxs)||c.means.mins.length!==3||c.means.maxs.length!==3)throw RangeError(`The SOG means need three mins and three maxs.`);let v={count:l,positions:new Float32Array(l*3),logScales:new Float32Array(l*3),rotations:new Float32Array(l*4),dc:new Float32Array(l*3),alphas:new Float32Array(l)},{mins:y,maxs:b}=c.means,x=c.scales.codebook,C=c.sh0.codebook;for(let e=0;e<l;e++){let t=e*4;for(let n=0;n<3;n++){let r=m.data[t+n]*256+p.data[t+n],i=y[n]+(b[n]-y[n])*r/65535;v.positions[e*3+n]=Math.sign(i)*(Math.exp(Math.abs(i))-1),v.logScales[e*3+n]=x[h.data[t+n]],v.dc[e*3+n]=C[_.data[t+n]]}if(v.alphas[e]=c.version===3?(_.data[t+3]/204)**2:_.data[t+3]/255,c.version===3){let n=(p.data[t+3]-128)/127,r=(m.data[t+3]-128)/127,i=(h.data[t+3]-128)/127,a=Math.hypot(n,r,i),o=a*Math.PI/2,s=a>1e-6?Math.sin(o)/a:Math.PI/2;v.rotations.set([Math.cos(o),n*s,r*s,i*s],e*4);continue}let n=g.data[t+3]-252;if(n<0||n>3)throw RangeError(`A SOG rotation has a reserved mode; the file is damaged.`);let r=[0,0,0,0],i=0,a=0;for(let e=0;e<4;e++){if(e===n)continue;let o=(g.data[t+a++]/255*2-1)*Math.SQRT1_2;r[e]=o,i+=o*o}r[n]=Math.sqrt(Math.max(0,1-i)),v.rotations.set(r,e*4)}if(c.shN){let e=c.shN,t=T[e.bands];if(!t||e.bands>(c.version===3?4:3)||!Number.isInteger(e.count)||e.count<1||e.count>(c.version===3?16777216:65536)||!Array.isArray(e.codebook)||e.codebook.length!==256||!Array.isArray(e.files))throw RangeError(`The SOG shN block is damaged; bands must be 1 to 3 and the codebook 256 entries.`);let n=u(e.files[0]),r=u(e.files[1]);if(r.width*r.height<l||n.width<64*t)throw RangeError(`The SOG spherical-harmonic textures are too small for its splat count; the file is damaged, re-export it`);v.rest=new Float32Array(l*t*3);for(let i=0;i<l;i++){let a=r.data[i*4]+r.data[i*4+1]*256+(c.version===3?r.data[i*4+2]*65536:0);if(a>=e.count)throw RangeError(`A SOG spherical-harmonic label is outside its palette; the file is damaged, re-export it`);for(let r=0;r<t;r++){let o=((a>>6)*n.width+(a&63)*t+r)*4;if(o+2>=n.data.length)throw RangeError(`A SOG palette entry lies outside its texture; the file is damaged, re-export it`);for(let a=0;a<3;a++)v.rest[(i*t+r)*3+a]=e.codebook[n.data[o+a]]}}}return e(v)}export{C as n,E as t};
1
+ import{m as e,p as t}from"./data-BDt3mxGg.js";import{n}from"./zip-Cgj7EvkG.js";import{MargoError as r}from"@margoengine/math/errors";var i=(e,t)=>Object.assign(Error(e,t===void 0?void 0:{cause:t}),{name:`MargoError`,code:`failed`}),a=e=>Object.assign(Error(e),{name:`MargoError`,code:`unsupported`}),o=e=>{throw i(`Not a valid lossless WebP image: ${e}; pass the complete bytes of the file`)},s=[0,1,1,0,1,1,-1,1,0,2,2,0,1,2,-1,2,2,1,-2,1,2,2,-2,2,0,3,3,0,1,3,-1,3,3,1,-3,1,2,3,-2,3,3,2,-3,2,0,4,4,0,1,4,-1,4,4,1,-4,1,3,3,-3,3,2,4,-2,4,4,2,-4,2,0,5,3,4,-3,4,4,3,-4,3,5,0,1,5,-1,5,5,1,-5,1,2,5,-2,5,5,2,-5,2,4,4,-4,4,3,5,-3,5,5,3,-5,3,0,6,6,0,1,6,-1,6,6,1,-6,1,2,6,-2,6,6,2,-6,2,4,5,-4,5,5,4,-5,4,3,6,-3,6,6,3,-6,3,0,7,7,0,1,7,-1,7,5,5,-5,5,7,1,-7,1,4,6,-4,6,6,4,-6,4,2,7,-2,7,7,2,-7,2,3,7,-3,7,7,3,-7,3,5,6,-5,6,6,5,-6,5,8,0,4,7,-4,7,7,4,-7,4,8,1,8,2,6,6,-6,6,8,3,5,7,-5,7,7,5,-7,5,8,4,6,7,-6,7,7,6,-7,6,8,5,7,7,-7,7,8,6,8,7],c=[17,18,0,1,2,3,4,5,16,6,7,8,9,10,11,12,13,14,15],l=class{constructor(e,t){this.bytes=e,this.offset=t,this.acc=0,this.have=0}read(e){for(;this.have<e;)this.offset>=this.bytes.length&&o(`the data ends early`),this.acc|=this.bytes[this.offset++]<<this.have,this.have+=8;let t=this.acc&(1<<e)-1;return this.acc>>>=e,this.have-=e,t}},u=class{constructor(e){this.count=/* @__PURE__ */ new Uint32Array(16);let t=0,n=0;for(let r=0;r<e.length;r++)e[r]&&(this.count[e[r]]++,t++,n=r);if(this.single=t===1?n:-1,t===0&&o(`an empty prefix code`),t>1){let e=1;for(let t=1;t<16;t++)e=e*2-this.count[t],e<0&&o(`an over-subscribed prefix code`);e!==0&&o(`an incomplete prefix code`)}let r=/* @__PURE__ */ new Uint32Array(17);for(let e=1;e<16;e++)r[e+1]=r[e]+this.count[e];this.symbols=new Uint16Array(t);for(let t=0;t<e.length;t++)e[t]&&(this.symbols[r[e[t]]++]=t)}decode(e){if(this.single>=0)return this.single;let t=0,n=0,r=0;for(let i=1;i<16;i++){t|=e.read(1);let a=this.count[i];if(t-a<n)return this.symbols[r+(t-n)];r+=a,n=n+a<<1,t<<=1}return o(`an invalid prefix code in the data`)}};function d(e,t){let n=new Uint8Array(t);if(e.read(1)){let r=e.read(1),i=e.read(1)?e.read(8):e.read(1);if(i>=t&&o(`a symbol outside its alphabet`),n[i]=1,r){let r=e.read(8);r>=t&&o(`a symbol outside its alphabet`),r===i&&o(`a simple code that repeats a symbol`),n[r]=1}return new u(n)}let r=/* @__PURE__ */ new Uint8Array(19),i=4+e.read(4);for(let t=0;t<i;t++)r[c[t]]=e.read(3);let a=new u(r),s=t;e.read(1)&&(s=2+e.read(2+2*e.read(3)),s>t&&o(`a code-length run longer than the alphabet`));let l=0,d=8;for(;l<t&&s--!==0;){let r=a.decode(e);if(r<16){n[l++]=r,r&&(d=r);continue}let i=r===16?3+e.read(2):r===17?3+e.read(3):11+e.read(7),s=r===16?d:0;l+i>t&&o(`a code-length repeat past the alphabet`);for(let e=0;e<i;e++)n[l++]=s}return new u(n)}var f=(e,t)=>{if(t<4)return t+1;let n=t-2>>1;return(2+(t&1)<<n)+e.read(n)+1};function p(e,t,n,r){let i=0;e.read(1)&&(i=e.read(4),(i<1||i>11)&&o(`a colour cache size outside 1..11 bits`));let a=0,c,l=1;if(r&&e.read(1)){a=e.read(3)+2;let r=p(e,Math.ceil(t/(1<<a)),Math.ceil(n/(1<<a)),!1);c=new Uint32Array(r.length);for(let e=0;e<r.length;e++)c[e]=r[e]>>>8&65535,l=Math.max(l,c[e]+1)}let u=i?1<<i:0,m=[];for(let t=0;t<l;t++)m.push([d(e,280+u),d(e,256),d(e,256),d(e,256),d(e,40)]);let h=new Uint32Array(t*n),g=i?new Uint32Array(u):void 0,_=32-i,v=0,y=0,b=()=>{if(g)for(;y<v;y++)g[Math.imul(506832829,h[y])>>>_]=h[y]};for(;v<h.length;){let n=v%t,r=(v-n)/t,i=c?m[c[(r>>a)*Math.ceil(t/(1<<a))+(n>>a)]]:m[0];i||o(`a pixel that names a missing prefix group`);let l=i[0].decode(e);if(l<256){let t=i[1].decode(e),n=i[2].decode(e),r=i[3].decode(e);h[v++]=(r<<24|t<<16|l<<8|n)>>>0}else if(l<280){let n=f(e,l-256),r=f(e,i[4].decode(e)),a;r>120?a=r-120:(a=s[(r-1)*2]+s[(r-1)*2+1]*t,a<1&&(a=1)),(a>v||v+n>h.length)&&o(`a backward reference outside the image`);for(let e=0;e<n;e++,v++)h[v]=h[v-a]}else g||o(`a colour-cache symbol with no cache`),b(),h[v++]=g[l-280];b()}return h}var m=(e,t)=>(((e^t)&4278124286)>>>1)+(e&t)>>>0,h=e=>e<0?0:e>255?255:e,g=(e,t)=>e>>>t&255;function _(e,t,n,r){let i=t[n-1],a=t[n-r],o=t[n-r+1],s=t[n-r-1];switch(e){case 1:return i;case 2:return a;case 3:return o;case 4:return s;case 5:return m(m(i,o),a);case 6:return m(i,s);case 7:return m(i,a);case 8:return m(s,a);case 9:return m(a,o);case 10:return m(m(i,s),m(a,o));case 11:{let e=0,t=0;for(let n=0;n<32;n+=8){let r=g(i,n)+g(a,n)-g(s,n);e+=Math.abs(r-g(i,n)),t+=Math.abs(r-g(a,n))}return e<t?i:a}case 12:{let e=0;for(let t=0;t<32;t+=8)e+=h(g(i,t)+g(a,t)-g(s,t))*2**t;return e>>>0}case 13:{let e=m(i,a),t=0;for(let n=0;n<32;n+=8)t+=h(g(e,n)+Math.trunc((g(e,n)-g(s,n))/2))*2**n;return t>>>0}default:return 4278190080}}var v=(e,t)=>(((e&4278255360)>>>0)+((t&4278255360)>>>0)&4278255360|(e&16711935)+(t&16711935)&16711935)>>>0,y=(e,t)=>(e<<24>>24)*(t<<24>>24)>>5;function b(e,t,n){let r=[],i=/* @__PURE__ */ new Set,a=t;for(;e.read(1);){let t=e.read(2);i.has(t)&&o(`a repeated transform`),i.add(t);let s={type:t,bits:0,width:a,data:/* @__PURE__ */ new Uint32Array};if(t===0||t===1)s.bits=e.read(3)+2,s.data=p(e,Math.ceil(a/(1<<s.bits)),Math.ceil(n/(1<<s.bits)),!1);else if(t===3){let t=e.read(8)+1,n=p(e,t,1,!1);for(let e=1;e<t;e++)n[e]=v(n[e],n[e-1]);s.data=n,s.bits=t<=2?3:t<=4?2:+(t<=16),a=Math.ceil(a/(1<<s.bits))}r.push(s)}let s=p(e,a,n,!0);for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.type===2)for(let e=0;e<s.length;e++){let t=s[e],n=t>>>8&255;s[e]=(t&4278255360|((t>>>16&255)+n&255)<<16|(t&255)+n&255)>>>0}else if(t.type===1){let e=Math.ceil(t.width/(1<<t.bits));for(let r=0;r<n;r++)for(let n=0;n<t.width;n++){let i=t.data[(r>>t.bits)*e+(n>>t.bits)],a=r*t.width+n,o=s[a],c=o>>>8&255,l=o>>>16&255,u=o&255;l=l+y(i&255,c)&255,u=u+y(i>>>8&255,c)+y(i>>>16&255,l)&255,s[a]=(o&4278255360|l<<16|u)>>>0}}else if(t.type===0){let e=Math.ceil(t.width/(1<<t.bits)),r=t.width;for(let i=0;i<n;i++)for(let n=0;n<r;n++){let a=i*r+n,o;o=i===0?n===0?4278190080:s[a-1]:n===0?s[a-r]:_(t.data[(i>>t.bits)*e+(n>>t.bits)]>>>8&15,s,a,r),s[a]=v(s[a],o)}}else{let e=8>>t.bits,r=(1<<e)-1,i=new Uint32Array(t.width*n),a=t.data,o=Math.ceil(t.width/(1<<t.bits));for(let c=0;c<n;c++)for(let n=0;n<t.width;n++){let l=s[c*o+(n>>t.bits)]>>>8&255,u=t.bits?l>>(n&(1<<t.bits)-1)*e&r:l;i[c*t.width+n]=u<a.length?a[u]:0}s=i}}return s}function x(e,t,n){let r=new l(e.subarray(0,n),t);r.read(8)!==47&&o(`a bad VP8L signature`);let i=r.read(14)+1,a=r.read(14)+1;r.read(1),r.read(3)!==0&&o(`an unknown VP8L version`);let s=b(r,i,a),c=new Uint8Array(i*a*4);for(let e=0;e<i*a;e++){let t=s[e];c[e*4]=t>>>16&255,c[e*4+1]=t>>>8&255,c[e*4+2]=t&255,c[e*4+3]=t>>>24}return{width:i,height:a,data:c}}function S(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);(e.length<20||t.getUint32(0,!0)!==1179011410||t.getUint32(8,!0)!==1346520407)&&o(`missing the RIFF WEBP header`);let n=12,r=-1,i=0;for(;n+8<=e.length;){let e=t.getUint32(n,!0),o=t.getUint32(n+4,!0);if(e===1278758998){r=n+8,i=o;break}if(e===540561494)throw a(`This WebP is lossy (VP8); read it with parseWebP.`);n+=8+o+(o&1)}return(r<0||r+i>e.length)&&o(`no VP8L chunk`),x(e,r,r+i)}var C=/* @__PURE__ */ e({parseSog:()=>E}),w=e=>e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),T=[0,3,8,15,24];async function E(e,i={}){let{signal:a}=i,o;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){let t=w(e);if(t.length<4||t[0]!==80||t[1]!==75)throw RangeError(`Not a SOG file: a bundled .sog is a ZIP archive; pass the whole file or its loose files.`);o=await n(t,a)}else if(e&&typeof e==`object`)o=new Map(Object.entries(e).map(([e,t])=>{if(!(t instanceof ArrayBuffer)&&!ArrayBuffer.isView(t))throw TypeError(`SOG file ${e} must be an ArrayBuffer or typed array`);return[e,w(t)]}));else throw TypeError(`Expected .sog bytes or a map of SOG file names to bytes; pass an ArrayBuffer, typed array or file map`);let s=o.get(`meta.json`);if(!s)throw RangeError(`The SOG has no meta.json; pass the complete archive or all of its files.`);let c;try{c=JSON.parse(new TextDecoder().decode(s))}catch{throw RangeError(`The SOG meta.json is not valid JSON; check that the file is complete.`)}if(c.version!==2&&c.version!==3)throw RangeError(`SOG version ${c.version} is not supported; this reader handles versions 2 and 3, re-export the scene.`);if(c.model!==void 0&&c.model!==`antialiased`)throw new r(`unsupported`,`SOG model ${c.model} is not supported; 2D Gaussian scenes cannot be drawn here.`);let l=c.count;if(!Number.isInteger(l)||l<1||l>3e6)throw RangeError(`A SOG needs 1 to 3,000,000 splats.`);let u=e=>{a?.throwIfAborted();let t=e===void 0?void 0:o.get(e);if(!t)throw RangeError(`The SOG is missing the texture ${e}; pass the complete archive.`);try{return S(t)}catch(t){throw t.code===`unsupported`?new r(`unsupported`,`The SOG texture ${e} is lossy WebP; re-export the SOG with lossless textures.`):RangeError(`The SOG texture ${e} is damaged; re-export the SOG with lossless textures.`,{cause:t})}},[d,f]=c.means?.files??[],p=u(d),m=u(f),h=u(c.scales?.files?.[0]),g=c.version===2?u(c.quats?.files?.[0]):void 0,_=u(c.sh0?.files?.[0]);for(let e of[m,h,...g?[g]:[],_])if(e.width!==p.width||e.height!==p.height)throw RangeError(`The SOG textures differ in size; the file is damaged.`);if(p.width*p.height<l)throw RangeError(`The SOG textures hold fewer pixels than its splat count; the file is damaged, re-export it`);for(let e of[c.scales?.codebook,c.sh0?.codebook])if(!Array.isArray(e)||e.length!==256)throw RangeError(`A SOG codebook must have 256 entries.`);if(!Array.isArray(c.means.mins)||!Array.isArray(c.means.maxs)||c.means.mins.length!==3||c.means.maxs.length!==3)throw RangeError(`The SOG means need three mins and three maxs.`);let v={count:l,positions:new Float32Array(l*3),logScales:new Float32Array(l*3),rotations:new Float32Array(l*4),dc:new Float32Array(l*3),alphas:new Float32Array(l)},{mins:y,maxs:b}=c.means,x=c.scales.codebook,C=c.sh0.codebook;for(let e=0;e<l;e++){let t=e*4;for(let n=0;n<3;n++){let r=m.data[t+n]*256+p.data[t+n],i=y[n]+(b[n]-y[n])*r/65535;v.positions[e*3+n]=Math.sign(i)*(Math.exp(Math.abs(i))-1),v.logScales[e*3+n]=x[h.data[t+n]],v.dc[e*3+n]=C[_.data[t+n]]}if(v.alphas[e]=c.version===3?(_.data[t+3]/204)**2:_.data[t+3]/255,c.version===3){let n=(p.data[t+3]-128)/127,r=(m.data[t+3]-128)/127,i=(h.data[t+3]-128)/127,a=Math.hypot(n,r,i),o=a*Math.PI/2,s=a>1e-6?Math.sin(o)/a:Math.PI/2;v.rotations.set([Math.cos(o),n*s,r*s,i*s],e*4);continue}let n=g.data[t+3]-252;if(n<0||n>3)throw RangeError(`A SOG rotation has a reserved mode; the file is damaged.`);let r=[0,0,0,0],i=0,a=0;for(let e=0;e<4;e++){if(e===n)continue;let o=(g.data[t+a++]/255*2-1)*Math.SQRT1_2;r[e]=o,i+=o*o}r[n]=Math.sqrt(Math.max(0,1-i)),v.rotations.set(r,e*4)}if(c.shN){let e=c.shN,t=T[e.bands];if(!t||e.bands>(c.version===3?4:3)||!Number.isInteger(e.count)||e.count<1||e.count>(c.version===3?16777216:65536)||!Array.isArray(e.codebook)||e.codebook.length!==256||!Array.isArray(e.files))throw RangeError(`The SOG shN block is damaged; bands must be 1 to 3 and the codebook 256 entries.`);let n=u(e.files[0]),r=u(e.files[1]);if(r.width*r.height<l||n.width<64*t)throw RangeError(`The SOG spherical-harmonic textures are too small for its splat count; the file is damaged, re-export it`);v.rest=new Float32Array(l*t*3);for(let i=0;i<l;i++){let a=r.data[i*4]+r.data[i*4+1]*256+(c.version===3?r.data[i*4+2]*65536:0);if(a>=e.count)throw RangeError(`A SOG spherical-harmonic label is outside its palette; the file is damaged, re-export it`);for(let r=0;r<t;r++){let o=((a>>6)*n.width+(a&63)*t+r)*4;if(o+2>=n.data.length)throw RangeError(`A SOG palette entry lies outside its texture; the file is damaged, re-export it`);for(let a=0;a<3;a++)v.rest[(i*t+r)*3+a]=e.codebook[n.data[o+a]]}}}return t(v)}export{C as n,E as t};
@@ -1 +1 @@
1
- import{_ as e,v as t}from"./data-D31W24Wu.js";import{t as n}from"./zip-DNluwYbe.js";var r=/* @__PURE__ */ t({SPZ_BODY_MAX:()=>a,decodeSpzBody:()=>u,parseSpz:()=>o}),i=[0,3,8,15],a=16+195e6;async function o(e,t={}){if(!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError(`Expected .spz bytes; pass an ArrayBuffer or typed array of the file`);let r=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(r.length>=8&&new DataView(r.buffer,r.byteOffset).getUint32(0,!0)===1347635022)return u(await s(r,t.signal),4);if(r.length<2||r[0]!==31||r[1]!==139)throw RangeError(`Not an SPZ file: it starts with neither gzip (versions 2-3) nor NGSP (version 4); check that the file is a complete .spz.`);return u(await n(r,`gzip`,t.signal,a),3)}async function s(e,t){let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.length<32)throw RangeError(`The SPZ header is truncated; check that the file is complete.`);let r=n.getUint32(4,!0),a=n.getUint32(8,!0),o=e[12],s=e[15],u=n.getUint32(16,!0);if(r!==4)throw RangeError(`SPZ version ${r} with a plain header is not supported; re-export the scene as SPZ version 4 or 3.`);l(a,o);let d=i[o]*3,f=[a*9,a,a*3,a*3,a*4,a*d],p=d?6:5;if(s<p)throw RangeError(`This SPZ file holds ${s} attribute streams where ${p} are needed; check that the file is complete.`);if(u<32||u+s*16>e.length)throw RangeError(`The SPZ table of contents lies outside the file; check that the file is complete.`);let m=new Uint8Array(16+f.reduce((e,t)=>e+t,0));m.set(e.subarray(0,16));let{decompressZstd:h}=await import(`./zstd-BPbUkXlY.js`),g=u+s*16,_=16;for(let r=0;r<s;r++){let i=u+r*16,a=c(n,i),o=c(n,i+8);if(g+a>e.length)throw RangeError(`An SPZ attribute stream runs past the end of the file; check that the file is complete.`);if(r<p){if(o!==f[r])throw RangeError(`SPZ attribute stream ${r} holds ${o} bytes where ${f[r]} are needed; check that the file is complete.`);let n=await h(e.subarray(g,g+a),{signal:t,maxOutputSize:o,maxWindowSize:Math.max(o,1<<27)});if(n.length!==o)throw RangeError(`SPZ attribute stream ${r} decodes to ${n.length} bytes where ${o} are needed; check that the file is complete.`);m.set(n,_),_+=o}g+=a}return m}function c(e,t){let n=e.getUint32(t+4,!0);if(n>2097151)throw RangeError(`An SPZ stream size is too large; check that the file is complete.`);return n*2**32+e.getUint32(t,!0)}function l(e,t){if(!Number.isInteger(e)||e<1||e>3e6)throw RangeError(`An SPZ file needs 1 to 3,000,000 splats.`);if(t>3)throw RangeError(`SPZ spherical-harmonic degree ${t} is not supported; Margo draws degrees 0 to 3.`)}function u(t,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.length<16||r.getUint32(0,!0)!==1347635022)throw RangeError(`Not an SPZ file: the magic number is wrong; check that the file is complete.`);let a=r.getUint32(4,!0),o=r.getUint32(8,!0),s=t[12],c=t[13];if(a<(n===4?4:2)||a>n)throw RangeError(`SPZ version ${a} is not supported here; re-export the scene as SPZ version 3 or 4.`);l(o,s);let u=i[s]*3,d=a===2?3:4;if(t.length<16+o*(16+d+u))throw RangeError(`The SPZ data is shorter than its header promises; check that the file is complete.`);let f={count:o,positions:new Float32Array(o*3),logScales:new Float32Array(o*3),rotations:new Float32Array(o*4),dc:new Float32Array(o*3),alphas:new Float32Array(o),rest:u?new Float32Array(o*u):void 0},p=16+o*9,m=p+o,h=m+o*3,g=h+o*3,_=g+o*d,v=1/2**c;for(let e=0;e<o;e++){for(let n=0;n<3;n++){let r=16+e*9+n*3,i=t[r]|t[r+1]<<8|t[r+2]<<16;f.positions[e*3+n]=(i<<8>>8)*v,f.dc[e*3+n]=(t[m+e*3+n]/255-.5)/.15,f.logScales[e*3+n]=t[h+e*3+n]/16-10}f.alphas[e]=t[p+e]/255;let n=g+e*d;if(a!==2){let t=r.getUint32(n,!0),i=t>>>30,a=[0,0,0,0],o=0;for(let e=3;e>=0;e--){if(e===i)continue;let n=t&511,r=t>>>9&1;t>>>=10;let s=Math.SQRT1_2*n/511;a[e]=r?-s:s,o+=s*s}a[i]=Math.sqrt(Math.max(0,1-o)),f.rotations.set([a[3],a[0],a[1],a[2]],e*4)}else{let r=t[n]/127.5-1,i=t[n+1]/127.5-1,a=t[n+2]/127.5-1;f.rotations.set([Math.sqrt(Math.max(0,1-r*r-i*i-a*a)),r,i,a],e*4)}if(f.rest)for(let n=0;n<u;n++)f.rest[e*u+n]=(t[_+e*u+n]-128)/128}return e(f)}export{r as n,u as t};
1
+ import{m as e,p as t}from"./data-BDt3mxGg.js";import{t as n}from"./zip-Cgj7EvkG.js";var r=/* @__PURE__ */ e({SPZ_BODY_MAX:()=>a,decodeSpzBody:()=>u,parseSpz:()=>o}),i=[0,3,8,15],a=16+195e6;async function o(e,t={}){if(!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError(`Expected .spz bytes; pass an ArrayBuffer or typed array of the file`);let r=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(r.length>=8&&new DataView(r.buffer,r.byteOffset).getUint32(0,!0)===1347635022)return u(await s(r,t.signal),4);if(r.length<2||r[0]!==31||r[1]!==139)throw RangeError(`Not an SPZ file: it starts with neither gzip (versions 2-3) nor NGSP (version 4); check that the file is a complete .spz.`);return u(await n(r,`gzip`,t.signal,a),3)}async function s(e,t){let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.length<32)throw RangeError(`The SPZ header is truncated; check that the file is complete.`);let r=n.getUint32(4,!0),a=n.getUint32(8,!0),o=e[12],s=e[15],u=n.getUint32(16,!0);if(r!==4)throw RangeError(`SPZ version ${r} with a plain header is not supported; re-export the scene as SPZ version 4 or 3.`);l(a,o);let d=i[o]*3,f=[a*9,a,a*3,a*3,a*4,a*d],p=d?6:5;if(s<p)throw RangeError(`This SPZ file holds ${s} attribute streams where ${p} are needed; check that the file is complete.`);if(u<32||u+s*16>e.length)throw RangeError(`The SPZ table of contents lies outside the file; check that the file is complete.`);let m=new Uint8Array(16+f.reduce((e,t)=>e+t,0));m.set(e.subarray(0,16));let{decompressZstd:h}=await import(`./zstd-BPbUkXlY.js`),g=u+s*16,_=16;for(let r=0;r<s;r++){let i=u+r*16,a=c(n,i),o=c(n,i+8);if(g+a>e.length)throw RangeError(`An SPZ attribute stream runs past the end of the file; check that the file is complete.`);if(r<p){if(o!==f[r])throw RangeError(`SPZ attribute stream ${r} holds ${o} bytes where ${f[r]} are needed; check that the file is complete.`);let n=await h(e.subarray(g,g+a),{signal:t,maxOutputSize:o,maxWindowSize:Math.max(o,1<<27)});if(n.length!==o)throw RangeError(`SPZ attribute stream ${r} decodes to ${n.length} bytes where ${o} are needed; check that the file is complete.`);m.set(n,_),_+=o}g+=a}return m}function c(e,t){let n=e.getUint32(t+4,!0);if(n>2097151)throw RangeError(`An SPZ stream size is too large; check that the file is complete.`);return n*2**32+e.getUint32(t,!0)}function l(e,t){if(!Number.isInteger(e)||e<1||e>3e6)throw RangeError(`An SPZ file needs 1 to 3,000,000 splats.`);if(t>3)throw RangeError(`SPZ spherical-harmonic degree ${t} is not supported; Margo draws degrees 0 to 3.`)}function u(e,n){let r=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.length<16||r.getUint32(0,!0)!==1347635022)throw RangeError(`Not an SPZ file: the magic number is wrong; check that the file is complete.`);let a=r.getUint32(4,!0),o=r.getUint32(8,!0),s=e[12],c=e[13];if(a<(n===4?4:2)||a>n)throw RangeError(`SPZ version ${a} is not supported here; re-export the scene as SPZ version 3 or 4.`);l(o,s);let u=i[s]*3,d=a===2?3:4;if(e.length<16+o*(16+d+u))throw RangeError(`The SPZ data is shorter than its header promises; check that the file is complete.`);let f={count:o,positions:new Float32Array(o*3),logScales:new Float32Array(o*3),rotations:new Float32Array(o*4),dc:new Float32Array(o*3),alphas:new Float32Array(o),rest:u?new Float32Array(o*u):void 0},p=16+o*9,m=p+o,h=m+o*3,g=h+o*3,_=g+o*d,v=1/2**c;for(let t=0;t<o;t++){for(let n=0;n<3;n++){let r=16+t*9+n*3,i=e[r]|e[r+1]<<8|e[r+2]<<16;f.positions[t*3+n]=(i<<8>>8)*v,f.dc[t*3+n]=(e[m+t*3+n]/255-.5)/.15,f.logScales[t*3+n]=e[h+t*3+n]/16-10}f.alphas[t]=e[p+t]/255;let n=g+t*d;if(a!==2){let e=r.getUint32(n,!0),i=e>>>30,a=[0,0,0,0],o=0;for(let t=3;t>=0;t--){if(t===i)continue;let n=e&511,r=e>>>9&1;e>>>=10;let s=Math.SQRT1_2*n/511;a[t]=r?-s:s,o+=s*s}a[i]=Math.sqrt(Math.max(0,1-o)),f.rotations.set([a[3],a[0],a[1],a[2]],t*4)}else{let r=e[n]/127.5-1,i=e[n+1]/127.5-1,a=e[n+2]/127.5-1;f.rotations.set([Math.sqrt(Math.max(0,1-r*r-i*i-a*a)),r,i,a],t*4)}if(f.rest)for(let n=0;n<u;n++)f.rest[t*u+n]=(e[_+t*u+n]-128)/128}return t(f)}export{r as n,u as t};
@@ -0,0 +1,48 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const p=(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"./view-DyJeX8rJ.js";import{c as n,d as r,f as i,l as a,o,p as s,r as c,s as l,t as u,u as d}from"./shader-B7zZyYz-.js";import{t as f}from"./view-rect-G-t2gTqO.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as m}from"@margoengine/math/errors";function h(e){if(e.length!==2||!e.every(Number.isFinite)||e[0]<0||e[1]>1||e[0]>e[1])throw RangeError(`Dither fade needs 0 <= lower <= upper <= 1; correct the coverage interval`)}var g=`fn margoDitherRank(p:vec2f)->u32 {
5
+ let x=u32(p.x)&3u;let y=u32(p.y)&3u;
6
+ return 4u*(2u*((x&1u)^(y&1u))+(y&1u))+2u*(((x>>1u)&1u)^((y>>1u)&1u))+((y>>1u)&1u);
7
+ }`,_=`struct Sort {count:u32,groups:u32,blocks:u32,shift:u32}
8
+ @group(0) @binding(0) var<uniform> sort:Sort;`,v=_+`
9
+ @group(0) @binding(1) var<storage,read> input:array<vec2u>;
10
+ @group(0) @binding(2) var<storage,read_write> histograms:array<u32>;
11
+ var<workgroup> bins:array<atomic<u32>,16>;
12
+ @compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u,@builtin(local_invocation_index) lane:u32,@builtin(workgroup_id) group:vec3u){
13
+ if(lane<16){atomicStore(&bins[lane],0);}workgroupBarrier();
14
+ if(id.x<sort.count){atomicAdd(&bins[(input[id.x].x>>sort.shift)&15],1);}workgroupBarrier();
15
+ if(lane<16){histograms[lane*sort.groups+group.x]=atomicLoad(&bins[lane]);}}`,y=_+`
16
+ @group(0) @binding(1) var<storage,read> histograms:array<u32>;
17
+ @group(0) @binding(2) var<storage,read_write> offsets:array<u32>;
18
+ @group(0) @binding(3) var<storage,read_write> totals:array<u32>;
19
+ var<workgroup> values:array<u32,256>;
20
+ @compute @workgroup_size(256) fn main(@builtin(local_invocation_index) lane:u32,@builtin(workgroup_id) group:vec3u){
21
+ let index=group.x*256+lane;values[lane]=0;if(index<sort.groups){values[lane]=histograms[group.y*sort.groups+index];}workgroupBarrier();
22
+ for(var stride=1u;stride<256;stride*=2){let at=(lane+1)*stride*2-1;if(at<256){values[at]+=values[at-stride];}workgroupBarrier();}
23
+ if(lane==0){totals[group.y*sort.blocks+group.x]=values[255];values[255]=0;}workgroupBarrier();
24
+ for(var stride=128u;stride>0;stride/=2){let at=(lane+1)*stride*2-1;if(at<256){let left=values[at-stride];values[at-stride]=values[at];values[at]+=left;}workgroupBarrier();}
25
+ if(index<sort.groups){offsets[group.y*sort.groups+index]=values[lane];}}`,b=_+`
26
+ @group(0) @binding(1) var<storage,read> totals:array<u32>;
27
+ @group(0) @binding(2) var<storage,read_write> bases:array<u32>;
28
+ var<workgroup> values:array<u32,1024>;
29
+ @compute @workgroup_size(256) fn main(@builtin(local_invocation_index) lane:u32){
30
+ for(var i=lane;i<1024;i+=256){values[i]=0;if(i<sort.blocks*16){values[i]=totals[i];}}workgroupBarrier();
31
+ for(var stride=1u;stride<1024;stride*=2){for(var i=lane;i<1024/(stride*2);i+=256){let at=(i+1)*stride*2-1;values[at]+=values[at-stride];}workgroupBarrier();}
32
+ if(lane==0){values[1023]=0;}workgroupBarrier();
33
+ for(var stride=512u;stride>0;stride/=2){for(var i=lane;i<1024/(stride*2);i+=256){let at=(i+1)*stride*2-1;let left=values[at-stride];values[at-stride]=values[at];values[at]+=left;}workgroupBarrier();}
34
+ for(var i=lane;i<sort.blocks*16;i+=256){bases[i]=values[i];}}`,x=_+`
35
+ @group(0) @binding(1) var<storage,read> input:array<vec2u>;
36
+ @group(0) @binding(2) var<storage,read_write> output:array<vec2u>;
37
+ @group(0) @binding(3) var<storage,read> offsets:array<u32>;
38
+ @group(0) @binding(4) var<storage,read> bases:array<u32>;
39
+ var<workgroup> masks:array<atomic<u32>,128>;
40
+ @compute @workgroup_size(256) fn main(@builtin(global_invocation_id) id:vec3u,@builtin(local_invocation_index) lane:u32,@builtin(workgroup_id) group:vec3u){
41
+ if(lane<128){atomicStore(&masks[lane],0);}workgroupBarrier();
42
+ var item=vec2u(0);var digit=0u;let word=lane/32;let bit=lane%32;
43
+ if(id.x<sort.count){item=input[id.x];digit=(item.x>>sort.shift)&15;atomicOr(&masks[digit*8+word],1u<<bit);}workgroupBarrier();
44
+ if(id.x<sort.count){var rank=countOneBits(atomicLoad(&masks[digit*8+word])&((1u<<bit)-1));
45
+ for(var i=0u;i<word;i++){rank+=countOneBits(atomicLoad(&masks[digit*8+i]));}
46
+ let destination=bases[digit*sort.blocks+group.x/256]+offsets[digit*sort.groups+group.x]+rank;output[destination]=item;}}`;function S(e){return e?.adapterInfo?.vendor===`margo-webgl2`?`webgl2`:`native`}function C(e,t){return S(e)===`webgl2`?t():void 0}function w(e){return e?e.then(()=>void 0,()=>void 0):Promise.resolve()}var T=e=>typeof e==`string`&&e.endsWith(`float`),E=0,D=class _{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);constructor(t){this.name=`splats:`+E++,this.buffers=[],this.inputs=[],this.keys=[],this.projectionBuffers=[],this.fogSource=null,this.fogData=/* @__PURE__ */ new Float32Array(12),this.sortPipelines=[],this.sortGroups=[],this.routeReady=Promise.resolve(),this.renders=/* @__PURE__ */ new Map,this.disposed=!1,this.mip=!1,this.writes=0,this.transparency=d(),this.attachment={view:void 0,loadOp:`load`,storeOp:`store`},this.plainDepth={view:void 0,depthReadOnly:!0},this.stencilDepth={view:void 0,depthReadOnly:!0,stencilReadOnly:!0},this.presentation={colorAttachments:[this.attachment],depthStencilAttachment:this.plainDepth},this.values=/* @__PURE__ */ new Float32Array(48),this.integers=new Uint32Array(this.values.buffer),this.view=this.values.subarray(16,32),this.count=e(t),this.positions=new Float32Array(this.count*4),this.covariances=new Float32Array(this.count*8),this.colors=t.colors.slice(),this.sh=t.sphericalHarmonics?.slice()??/* @__PURE__ */ new Float32Array(4);for(let e=0;e<this.count;e++)this.positions.set(t.positions.subarray(e*3,e*3+3),e*4),this.positions[e*4+3]=t.colors[e*4+3],this.covariances.set(t.covariances.subarray(e*6,e*6+6),e*8)}static reserve(e,t=0){if(![0,4,9,16,25].includes(t))throw RangeError(`Splat SH coefficients must be 0, 4, 9, 16 or 25`);if(!Number.isInteger(e)||e<1||e>3e6)throw RangeError(`Splats.reserve needs 1 to 3,000,000 splats`);let n=new Float32Array(e*6);for(let t=0;t<e;t++)n[t*6]=n[t*6+3]=n[t*6+5]=1;return new _({positions:new Float32Array(e*3),covariances:n,colors:new Float32Array(e*4),...t?{sphericalHarmonics:new Float32Array(e*t*3)}:{}})}get coefficients(){return this.sh.length===4?0:this.sh.length/this.count/3}write(t,n){let r=e(n),i=this.coefficients;if((n.sphericalHarmonics?n.sphericalHarmonics.length/r/3:0)!==i)throw RangeError(`Splats.write needs ${i} SH coefficients per channel, as the cloud has`);this.range(t,r);for(let e=0;e<r;e++)this.positions.set(n.positions.subarray(e*3,e*3+3),(t+e)*4),this.positions[(t+e)*4+3]=n.colors[e*4+3],this.covariances.set(n.covariances.subarray(e*6,e*6+6),(t+e)*8);return this.colors.set(n.colors,t*4),i&&this.sh.set(n.sphericalHarmonics,t*i*3),this.upload(t,r,!0)}clear(e,t){this.range(e,t);for(let n=e;n<e+t;n++)this.positions[n*4+3]=this.colors[n*4+3]=0;return this.upload(e,t,!1)}setOpacities(e,t,n=1){if(this.range(e,t.length),!(n>=0&&n<=1))throw RangeError(`Splats.setOpacities scale must be 0 to 1`);for(let r=0;r<t.length;r++)this.positions[(e+r)*4+3]=this.colors[(e+r)*4+3]=t[r]*n;return this.upload(e,t.length,!1)}range(e,t){if(this.disposed)throw new m(`disposed`,`The splats were disposed; write to a live cloud`);if(!Number.isInteger(e)||!Number.isInteger(t)||e<0||t<0||e+t>this.count)throw RangeError(`Splats ${e} to ${e+t-1} are outside this cloud of ${this.count}; keep first + count within the cloud`)}upload(e,t,n){this.writes++;let[r,i,a,o]=this.inputs,s=this.device?.queue,c=this.coefficients;return!s||!r||!t||(s.writeBuffer(r,e*16,this.positions,e*4,t*4),s.writeBuffer(a,e*16,this.colors,e*4,t*4),n&&s.writeBuffer(i,e*32,this.covariances,e*8,t*8),n&&c&&s.writeBuffer(o,e*c*12,this.sh,e*c*3,t*c*3)),this}get ditherFadeBytes(){return this.fadeData?.byteLength??0}setDitherFade(e,t,n=0,r=1){this.range(e,t),h([n,r]),this.fadeData||(this.fadeData=new Uint32Array(this.count).fill(4096),this.record=void 0,this.renders.clear());let i=Math.ceil(Math.fround(n)*16-.5),a=Math.ceil(Math.fround(r)*16-.5),o=Math.max(0,i)|Math.max(0,a)<<8;return this.fadeData.fill(o,e,e+t),this.device&&(this.fadeBuffer?t&&this.device.queue.writeBuffer(this.fadeBuffer,e*4,this.fadeData,e,t):this.prepareFade()),this}prepareFade(){if(!this.fadeData||!this.device||this.fadeBuffer)return;let e=this.device;this.fadeBuffer=e.createBuffer({size:this.fadeData.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.buffers.push(this.fadeBuffer),e.queue.writeBuffer(this.fadeBuffer,0,this.fadeData)}async read(){this.range(0,0);let e=this.device,[t,n,r,i]=this.inputs;for(let a=-1;e&&t&&a!==this.writes;){a=this.writes;let o=[[t,this.positions],[n,this.covariances],[r,this.colors],[i,this.sh]],s=e.createCommandEncoder(),c=o.map(([t,n])=>{let r=e.createBuffer({size:n.byteLength,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST});return s.copyBufferToBuffer(t,0,r,0,n.byteLength),r});e.queue.submit([s.finish()]);try{await Promise.all(c.map(e=>e.mapAsync(GPUMapMode.READ))),a===this.writes&&c.forEach((e,t)=>o[t][1].set(new Float32Array(e.getMappedRange())))}finally{for(let e of c)e.destroy()}}let a=this.count,o={positions:new Float32Array(a*3),covariances:new Float32Array(a*6),colors:this.colors.slice()};for(let e=0;e<a;e++)o.positions.set(this.positions.subarray(e*4,e*4+3),e*3),o.covariances.set(this.covariances.subarray(e*8,e*8+6),e*6);return this.coefficients&&(o.sphericalHarmonics=this.sh.slice()),o}get antialias(){return this.mip}set antialias(e){this.mip=!!e}get fog(){return this.fogSource}setFog(e){return this.fogSource=r(e),this}static attach(e,t){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let n=new _(t);return p(e).use(n),n}setup(e){if(this.disposed||!e.gpu)throw new m(this.disposed?`disposed`:`unsupported`,`Splats require WebGPU and a live cloud; attach a new Splats to a WebGPU engine; see https://margoengine.com/errors#webgpu`);this.engine=e,this.device=e.gpu;let t=this.device,n=Math.ceil(this.count/256),r=Math.ceil(n/256);if(r*16>1024||n>t.limits.maxComputeWorkgroupsPerDimension||t.limits.maxComputeInvocationsPerWorkgroup<256||t.limits.maxComputeWorkgroupSizeX<256||t.limits.maxStorageBuffersPerShaderStage<7)throw RangeError(`Splat compute exceeds device limits; use fewer splats or a device with larger compute limits.`);for(let e of[this.positions.byteLength,this.covariances.byteLength,this.colors.byteLength,this.sh.byteLength,this.count*32,this.count*16,this.count*8,n*16*4])if(e>t.limits.maxBufferSize||e>t.limits.maxStorageBufferBindingSize)throw RangeError(`Splat attributes exceed device storage limits; use fewer splats.`);let i=(e,n,r)=>{let i=t.createBuffer({size:e,usage:n|GPUBufferUsage.COPY_DST});return this.buffers.push(i),r&&t.queue.writeBuffer(i,0,r),i};this.prepareFade(),this.uniform=i(192,GPUBufferUsage.UNIFORM),this.index=i(24,GPUBufferUsage.INDEX,new Uint32Array([0,1,2,2,1,3]));let a=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC,o=i(this.positions.byteLength,a,this.positions),s=i(this.covariances.byteLength,a,this.covariances),l=i(this.colors.byteLength,a,this.colors),u=i(this.sh.byteLength,a,this.sh);this.inputs=[o,s,l,u],this.projected=i(this.count*32,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC),this.evaluated=i(this.count*16,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC),this.keys=[0,1].map(()=>i(this.count*8,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC));let d=i(n*16*4,GPUBufferUsage.STORAGE),f=i(n*16*4,GPUBufferUsage.STORAGE),p=i(r*16*4,GPUBufferUsage.STORAGE),h=i(r*16*4,GPUBufferUsage.STORAGE),g=e=>t.createComputePipeline({layout:`auto`,compute:{module:t.createShaderModule({code:e}),entryPoint:`main`}}),_=(e,n)=>t.createBindGroup({layout:e.getBindGroupLayout(0),entries:n.map((e,t)=>({binding:t,resource:{buffer:e}}))});this.projection=g(c),this.projectionBuffers=[this.uniform,o,s,l,u,this.projected,this.evaluated,this.keys[0]],this.projectionGroup=_(this.projection,this.projectionBuffers),this.sortPipelines=[v,y,b,x].map(g);let S=[];for(let e=0;e<8;e++){let t=i(16,GPUBufferUsage.UNIFORM,new Uint32Array([this.count,n,r,e*4])),a=e%2;S.push(t),this.sortGroups.push([_(this.sortPipelines[0],[t,this.keys[a],d]),_(this.sortPipelines[1],[t,d,f,p]),_(this.sortPipelines[2],[t,p,h]),_(this.sortPipelines[3],[t,this.keys[a],this.keys[1-a],f,h])])}let T=this.keys,E=C(t,()=>import(`./compat-CDoDsXE8.js`));E?.then(({splatCompatSort:e})=>{this.keys===T&&(this.compatSort=e(t,S[0],T))}),this.routeReady=w(E)}get ready(){return this.routeReady}registerPasses(e){e.add({name:this.name+`:project-sort`,order:-7,execute:e=>{e.backend===`webgpu`&&this.sort(e)}}),e.add({name:this.name+`:draw`,order:3,execute:e=>{e.backend===`webgpu`&&this.draw(e)}})}sort(e){this.values.set(e.camera.matrix),t(this.view,e.camera),this.values.set(e.camera.position,32);let n=e.height/(2*Math.tan(e.camera.fov*Math.PI/360)),r=this.values,a=this.integers,o=e.encoder;r[36]=e.width,r[37]=e.height,r[38]=r[39]=n,r[40]=e.camera.near,r[41]=e.camera.far,r[42]=+T(e.format),r[43]=0;let c=s(e.camera.matrix,e.camera.position);c&&(r[38]=c.sx*e.width/2,r[39]=c.sy*e.height/2,r[40]=c.near,r[41]=c.far,r[43]=1),a[44]=this.count,a[45]=this.sh.length===4?0:this.sh.length/this.count/3,a[46]=+this.mip,a[47]=0,e.device.queue.writeBuffer(this.uniform,0,this.values);let l=this.fogSource&&this.fogResources(e.device);l&&(i(this.fogSource,e.camera.position,this.fogData),e.device.queue.writeBuffer(l.buffer,0,this.fogData));let u=Math.ceil(this.count/256),d=Math.ceil(u/256),f=o.beginComputePass();try{if(l?this.dispatch(f,l.pipeline,l.group,u,1):this.dispatch(f,this.projection,this.projectionGroup,u,1),this.transparency.hook)return;if(this.compatSort)this.dispatch(f,this.compatSort.pipeline,this.compatSort.group,1,1);else for(let e=0;e<8;e++){let t=this.sortGroups[e];this.dispatch(f,this.sortPipelines[0],t[0],u,1),this.dispatch(f,this.sortPipelines[1],t[1],d,16),this.dispatch(f,this.sortPipelines[2],t[2],1,1),this.dispatch(f,this.sortPipelines[3],t[3],u,1)}}finally{f.end()}}fogResources(e){if(this.fogged)return this.fogged;let t=e.createBuffer({size:48,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.buffers.push(t);let n=e.createComputePipeline({layout:`auto`,compute:{module:e.createShaderModule({code:u()}),entryPoint:`main`}});return this.fogged={buffer:t,pipeline:n,group:e.createBindGroup({layout:n.getBindGroupLayout(0),entries:[...this.projectionBuffers,t].map((e,t)=>({binding:t,resource:{buffer:e}}))})}}dispatch(e,t,n,r,i){e.setPipeline(t),e.setBindGroup(0,n),e.dispatchWorkgroups(r,i)}fadeShader(e){return this.fadeData?g+`
47
+ @group(0) @binding(4) var<storage,read> fadeRanges:array<u32>;
48
+ `+e.replace(`@location(1) color:vec4f}`,`@location(1) color:vec4f,@location(3) @interpolate(flat) margoFade:u32}`).replace(`@location(1) color:vec4f,@location(2) margoDepth:f32}`,`@location(1) color:vec4f,@location(2) margoDepth:f32,@location(3) @interpolate(flat) margoFade:u32}`).replace(`o.corner=corner;`,`o.corner=corner;o.margoFade=fadeRanges[index];`).replace(`let power=-4.5*dot(i.corner,i.corner);`,`let fade=margoDitherRank(i.clip.xy);if(fade<(i.margoFade&255u)||fade>=(i.margoFade>>8u)){discard;}let power=-4.5*dot(i.corner,i.corner);`):e}pipeline(e,t,r){t+=this.fadeData?`|dither`:``;let i=this.renders.get(t);if(i)return i;let a=r?.surface(1),s=e.device.createShaderModule({code:this.fadeShader(a?l(a):o)}),c=e.device.createRenderPipeline({layout:`auto`,vertex:{module:s,entryPoint:`vertex`},fragment:{module:s,entryPoint:r?`transparent`:`fragment`,...r?.blends?{constants:{margoKind:0}}:{},targets:r?[...r.targets]:[{format:e.format,blend:n}]},multisample:e.descriptor.multisample,depthStencil:{format:e.descriptor.depthStencil.format,depthWriteEnabled:!1,depthCompare:`greater-equal`}});return i={pipeline:c,group:e.device.createBindGroup({layout:c.getBindGroupLayout(0),entries:[this.uniform,this.projected,this.evaluated,this.keys[0],...this.fadeBuffer?[this.fadeBuffer]:[]].map((e,t)=>({binding:t,resource:{buffer:e}}))})},this.renders.set(t,i),i}draw(e){if(this.transparency.hook)return;let t=e.descriptor.multisample?.count,n=e.descriptor.depthStencil.format,r=this.record;(!r||this.recordSamples!==t||this.recordFormat!==e.format||this.recordDepth!==n)&&(r=this.pipeline(e,t+`:`+e.format+`:`+n),this.record=r,this.recordSamples=t,this.recordFormat=e.format,this.recordDepth=n,this.presentation.depthStencilAttachment=n.includes(`stencil`)?this.stencilDepth:this.plainDepth),this.attachment.view=e.color,this.presentation.depthStencilAttachment.view=e.depth;let i=e.encoder.beginRenderPass(this.presentation);f(i,e),i.setPipeline(r.pipeline),i.setBindGroup(0,r.group),i.setIndexBuffer(this.index,`uint32`),i.drawIndexed(6,this.count),i.end(),this.engine.stats.drawCalls++}setTransparency(e,t){return this.transparency.set(e,t)}drawTransparent(e,t){if(!this.uniform)return;let n=t.surface(1),{pipeline:r,group:i}=this.pipeline(e,e.descriptor.multisample?.count+`:`+e.format+`:`+e.descriptor.depthStencil.format+n,t),o=a(e.device,t,r,i);o.setIndexBuffer(this.index,`uint32`),o.drawIndexed(6,this.count),this.engine.stats.drawCalls++}get attached(){return!!this.projected}get gpuState(){if(!this.projected||!this.evaluated||!this.keys.length)throw new m(`state`,`Splats are not attached; attach them to an engine first`);let[e,t,n,r]=this.inputs;return{sorted:this.keys[0],ellipses:this.projected,colors:this.evaluated,positions:e,covariances:t,inputColors:n,sh:r}}release(){for(let e of this.buffers)e.destroy();this.buffers=[],this.inputs=[],this.keys=[],this.sortGroups=[],this.sortPipelines=[],this.compatSort=void 0,this.renders.clear(),this.record=void 0,this.fadeBuffer=void 0,this.uniform=this.index=this.projected=this.evaluated=void 0,this.projection=void 0,this.projectionGroup=void 0,this.projectionBuffers=[],this.fogged=void 0}onDeviceRestored(e){this.release(),this.setup(e)}dispose(){this.disposed||(this.disposed=!0,this.transparency.released?.(),this.engine?.sceneOf(this)?.removePlugin(this.name),this.release(),this.engine=this.device=void 0)}[Symbol.dispose??Symbol()](){this.dispose()}destroy(){this.dispose()}};export{D as t};
@@ -0,0 +1 @@
1
+ import{MargoError as e}from"@margoengine/math/errors";var t={deflate:[120,156,3,0,0,0,0,1],"deflate-raw":[3,0],gzip:[31,139,8,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0]},n=/* @__PURE__ */ new Map;async function r(e,t){let n=new Blob([e]).stream().pipeThrough(new DecompressionStream(t)).getReader();try{for(;!(await n.read()).done;);return!0}catch{return!1}}function i(e){if(!(e in t))throw TypeError(`format must be deflate, deflate-raw or gzip (got ${e})`);let i=n.get(e);return i||(i=r(new Uint8Array([...t[e],0]),e),n.set(e,i)),i}async function a(e,t){return!await i(t)||e.byteLength===0?!1:r(e.subarray(0,e.byteLength-1),t)}async function o(t,n,r,i){if(r?.throwIfAborted(),typeof DecompressionStream>`u`)throw new e(`unsupported`,`This runtime has no DecompressionStream; use a current browser or Node 18+.`);let o=new Blob([t]).stream().pipeThrough(new DecompressionStream(n)).getReader(),s=[],c=0;try{for(;;){r?.throwIfAborted();let{done:e,value:t}=await o.read();if(e||(s.push(t),c+=t.length,c>i))break}}catch(e){throw r?.aborted?r.reason:RangeError(`The compressed data is damaged (${e.message}); check that the file is complete.`)}if(c>i)throw await o.cancel().catch(()=>{}),RangeError(`The compressed data expands past ${i} bytes, more than the file can hold; check that the file is complete and not damaged.`);if(await a(t,n))throw RangeError(`The compressed data is damaged (data after the end of the stream); check that the file is complete.`);let l=new Uint8Array(c),u=0;for(let e of s)l.set(e,u),u+=e.length;return l}async function s(t,n){let r=new DataView(t.buffer,t.byteOffset,t.byteLength),i=e=>{throw RangeError(`Not a readable ZIP archive: ${e}; check that the file is complete.`)},a=-1;for(let e=t.length-22;e>=Math.max(0,t.length-22-65535);e--)if(r.getUint32(e,!0)===101010256){a=e;break}a<0&&i(`no end-of-directory record`);let s=r.getUint16(a+10,!0),c=r.getUint32(a+16,!0);if(s===65535||c===4294967295)throw new e(`unsupported`,`ZIP64 archives are not supported; re-export the SOG.`);let l=/* @__PURE__ */ new Map;for(let a=0;a<s;a++){(c+46>t.length||r.getUint32(c,!0)!==33639248)&&i(`a damaged central directory`);let a=r.getUint16(c+10,!0),s=r.getUint32(c+20,!0),u=r.getUint32(c+24,!0),d=r.getUint16(c+28,!0),f=r.getUint16(c+30,!0),p=r.getUint16(c+32,!0),m=r.getUint32(c+42,!0),h=new TextDecoder().decode(t.subarray(c+46,c+46+d));if(c+=46+d+f+p,h.endsWith(`/`))continue;(m+30>t.length||r.getUint32(m,!0)!==67324752)&&i(`a damaged local header`);let g=m+30+r.getUint16(m+26,!0)+r.getUint16(m+28,!0);g+s>t.length&&i(`an entry that runs past the end of the file`);let _=t.subarray(g,g+s),v;if(a===0)v=_;else if(a===8)v=await o(_,`deflate-raw`,n,u);else throw new e(`unsupported`,`ZIP entry ${h} uses compression method ${a}; only stored and deflate are supported.`);v.length!==u&&i(`entry ${h} has the wrong size`),l.set(h,v)}return l}export{s as n,o as t};