@luma.gl/engine 9.1.4 → 9.1.5

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/dist.dev.js CHANGED
@@ -1603,7 +1603,6 @@ var __exports__ = (() => {
1603
1603
  );
1604
1604
  const isWebGPU = this.device.type === "webgpu";
1605
1605
  if (isWebGPU && this.props.source) {
1606
- this.props.shaderLayout ||= (0, import_shadertools2.getShaderLayoutFromWGSL)(this.props.source);
1607
1606
  const { source: source3, getUniforms: getUniforms2 } = this.props.shaderAssembler.assembleWGSLShader({
1608
1607
  platformInfo,
1609
1608
  ...this.props,
@@ -1611,6 +1610,7 @@ var __exports__ = (() => {
1611
1610
  });
1612
1611
  this.source = source3;
1613
1612
  this._getModuleUniforms = getUniforms2;
1613
+ this.props.shaderLayout ||= (0, import_shadertools2.getShaderLayoutFromWGSL)(this.source);
1614
1614
  } else {
1615
1615
  const { vs: vs3, fs: fs3, getUniforms: getUniforms2 } = this.props.shaderAssembler.assembleGLSLShaderPair({
1616
1616
  platformInfo,
package/dist/dist.min.js CHANGED
@@ -4,7 +4,7 @@
4
4
  else if (typeof define === 'function' && define.amd) define([], factory);
5
5
  else if (typeof exports === 'object') exports['luma'] = factory();
6
6
  else root['luma'] = factory();})(globalThis, function () {
7
- "use strict";var __exports__=(()=>{var Ui=Object.create;var bt=Object.defineProperty;var $i=Object.getOwnPropertyDescriptor;var ji=Object.getOwnPropertyNames;var Gi=Object.getPrototypeOf,Vi=Object.prototype.hasOwnProperty;var qi=(i,t,e)=>t in i?bt(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var Le=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),Wi=(i,t)=>{for(var e in t)bt(i,e,{get:t[e],enumerable:!0})},Et=(i,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ji(t))!Vi.call(i,n)&&n!==e&&bt(i,n,{get:()=>t[n],enumerable:!(s=$i(t,n))||s.enumerable});return i},kt=(i,t,e)=>(Et(i,t,"default"),e&&Et(e,t,"default")),L=(i,t,e)=>(e=i!=null?Ui(Gi(i)):{},Et(t||!i||!i.__esModule?bt(e,"default",{value:i,enumerable:!0}):e,i)),Hi=i=>Et(bt({},"__esModule",{value:!0}),i);var V=(i,t,e)=>(qi(i,typeof t!="symbol"?t+"":t,e),e);var j=Le((rn,Ne)=>{Ne.exports=globalThis.luma});var rt=Le((wn,Be)=>{Be.exports=globalThis.luma});var St={};Wi(St,{AnimationLoop:()=>ht,AnimationLoopTemplate:()=>Ft,AsyncTexture:()=>it,BackgroundTextureModel:()=>at,BufferTransform:()=>At,ClipSpace:()=>J,Computation:()=>Pt,ConeGeometry:()=>ee,CubeGeometry:()=>ie,CylinderGeometry:()=>se,GPUGeometry:()=>lt,Geometry:()=>D,GroupNode:()=>mt,IcoSphereGeometry:()=>ne,KeyFrames:()=>Nt,LegacyPickingManager:()=>de,Model:()=>q,ModelNode:()=>te,PickingManager:()=>It,PipelineFactory:()=>Z,PlaneGeometry:()=>re,ScenegraphNode:()=>et,ShaderFactory:()=>Q,ShaderInputs:()=>Y,ShaderPassRenderer:()=>ce,SphereGeometry:()=>oe,Swap:()=>gt,SwapBuffers:()=>ae,SwapFramebuffers:()=>xt,TextureTransform:()=>qt,Timeline:()=>Lt,TruncatedConeGeometry:()=>st,cancelAnimationFramePolyfill:()=>Dt,colorPicking:()=>Ni,indexPicking:()=>Li,loadImage:()=>Ye,loadImageBitmap:()=>jt,makeAnimationLoop:()=>De,makeRandomGenerator:()=>Ri,requestAnimationFramePolyfill:()=>zt,setPathPrefix:()=>He});kt(St,L(j(),1));var Yi=1,Xi=1,Lt=class{time=0;channels=new Map;animations=new Map;playing=!1;lastEngineTime=-1;constructor(){}addChannel(t){let{delay:e=0,duration:s=Number.POSITIVE_INFINITY,rate:n=1,repeat:r=1}=t,o=Yi++,a={time:0,delay:e,duration:s,rate:n,repeat:r};return this._setChannelTime(a,this.time),this.channels.set(o,a),o}removeChannel(t){this.channels.delete(t);for(let[e,s]of this.animations)s.channel===t&&this.detachAnimation(e)}isFinished(t){let e=this.channels.get(t);return e===void 0?!1:this.time>=e.delay+e.duration*e.repeat}getTime(t){if(t===void 0)return this.time;let e=this.channels.get(t);return e===void 0?-1:e.time}setTime(t){this.time=Math.max(0,t);let e=this.channels.values();for(let n of e)this._setChannelTime(n,this.time);let s=this.animations.values();for(let n of s){let{animation:r,channel:o}=n;r.setTime(this.getTime(o))}}play(){this.playing=!0}pause(){this.playing=!1,this.lastEngineTime=-1}reset(){this.setTime(0)}attachAnimation(t,e){let s=Xi++;return this.animations.set(s,{animation:t,channel:e}),t.setTime(this.getTime(e)),s}detachAnimation(t){this.animations.delete(t)}update(t){this.playing&&(this.lastEngineTime===-1&&(this.lastEngineTime=t),this.setTime(this.time+(t-this.lastEngineTime)),this.lastEngineTime=t)}_setChannelTime(t,e){let s=e-t.delay,n=t.duration*t.repeat;s>=n?t.time=t.duration*t.rate:(t.time=Math.max(0,s)%t.duration,t.time*=t.rate)}};var Nt=class{startIndex=-1;endIndex=-1;factor=0;times=[];values=[];_lastTime=-1;constructor(t){this.setKeyFrames(t),this.setTime(0)}setKeyFrames(t){let e=t.length;this.times.length=e,this.values.length=e;for(let s=0;s<e;++s)this.times[s]=t[s][0],this.values[s]=t[s][1];this._calculateKeys(this._lastTime)}setTime(t){t=Math.max(0,t),t!==this._lastTime&&(this._calculateKeys(t),this._lastTime=t)}getStartTime(){return this.times[this.startIndex]}getEndTime(){return this.times[this.endIndex]}getStartData(){return this.values[this.startIndex]}getEndData(){return this.values[this.endIndex]}_calculateKeys(t){let e=0,s=this.times.length;for(e=0;e<s-2&&!(this.times[e+1]>t);++e);this.startIndex=e,this.endIndex=e+1;let n=this.times[this.startIndex],r=this.times[this.endIndex];this.factor=Math.min(Math.max(0,(t-n)/(r-n)),1)}};var Ft=class{constructor(t){}async onInitialize(t){return null}};var Fe=L(j(),1);function zt(i){return typeof window<"u"&&window.requestAnimationFrame?window.requestAnimationFrame(i):setTimeout(i,1e3/60)}function Dt(i){return typeof window<"u"&&window.cancelAnimationFrame?window.cancelAnimationFrame(i):clearTimeout(i)}function Mt(){let i;if(typeof window<"u"&&window.performance)i=window.performance.now();else if(typeof process<"u"&&process.hrtime){let t=process.hrtime();i=t[0]*1e3+t[1]/1e6}else i=Date.now();return i}var nt=class{constructor(t,e){this.sampleSize=1,this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this.name=t,this.type=e,this.reset()}reset(){return this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this}setSampleSize(t){return this.sampleSize=t,this}incrementCount(){return this.addCount(1),this}decrementCount(){return this.subtractCount(1),this}addCount(t){return this._count+=t,this._samples++,this._checkSampling(),this}subtractCount(t){return this._count-=t,this._samples++,this._checkSampling(),this}addTime(t){return this._time+=t,this.lastTiming=t,this._samples++,this._checkSampling(),this}timeStart(){return this._startTime=Mt(),this._timerPending=!0,this}timeEnd(){return this._timerPending?(this.addTime(Mt()-this._startTime),this._timerPending=!1,this._checkSampling(),this):this}getSampleAverageCount(){return this.sampleSize>0?this.lastSampleCount/this.sampleSize:0}getSampleAverageTime(){return this.sampleSize>0?this.lastSampleTime/this.sampleSize:0}getSampleHz(){return this.lastSampleTime>0?this.sampleSize/(this.lastSampleTime/1e3):0}getAverageCount(){return this.samples>0?this.count/this.samples:0}getAverageTime(){return this.samples>0?this.time/this.samples:0}getHz(){return this.time>0?this.samples/(this.time/1e3):0}_checkSampling(){this._samples===this.sampleSize&&(this.lastSampleTime=this._time,this.lastSampleCount=this._count,this.count+=this._count,this.time+=this._time,this.samples+=this._samples,this._time=0,this._count=0,this._samples=0)}};var ct=class{constructor(t){this.stats={},this.id=t.id,this.stats={},this._initializeStats(t.stats),Object.seal(this)}get(t,e="count"){return this._getOrCreate({name:t,type:e})}get size(){return Object.keys(this.stats).length}reset(){for(let t of Object.values(this.stats))t.reset();return this}forEach(t){for(let e of Object.values(this.stats))t(e)}getTable(){let t={};return this.forEach(e=>{t[e.name]={time:e.time||0,count:e.count||0,average:e.getAverageTime()||0,hz:e.getHz()||0}}),t}_initializeStats(t=[]){t.forEach(e=>this._getOrCreate(e))}_getOrCreate(t){let{name:e,type:s}=t,n=this.stats[e];return n||(t instanceof nt?n=t:n=new nt(e,s),this.stats[e]=n),n}};var Ki=0,Zi={device:null,onAddHTML:()=>"",onInitialize:async()=>null,onRender:()=>{},onFinalize:()=>{},onError:i=>console.error(i),stats:Fe.luma.stats.get(`animation-loop-${Ki++}`),useDevicePixels:!0,autoResizeViewport:!1,autoResizeDrawingBuffer:!1},ht=class{device=null;canvas=null;props;animationProps=null;timeline=null;stats;cpuTime;gpuTime;frameRate;display;needsRedraw="initialized";_initialized=!1;_running=!1;_animationFrameId=null;_nextFramePromise=null;_resolveNextFrame=null;_cpuStartTime=0;_error=null;constructor(t){if(this.props={...Zi,...t},t=this.props,!t.device)throw new Error("No device provided");let{useDevicePixels:e=!0}=this.props;this.stats=t.stats||new ct({id:"animation-loop-stats"}),this.cpuTime=this.stats.get("CPU Time"),this.gpuTime=this.stats.get("GPU Time"),this.frameRate=this.stats.get("Frame Rate"),this.setProps({autoResizeViewport:t.autoResizeViewport,autoResizeDrawingBuffer:t.autoResizeDrawingBuffer,useDevicePixels:e}),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this._onMousemove=this._onMousemove.bind(this),this._onMouseleave=this._onMouseleave.bind(this)}destroy(){this.stop(),this._setDisplay(null)}delete(){this.destroy()}setError(t){if(this.props.onError(t),this._error=Error(),this.device?.canvasContext?.canvas instanceof HTMLCanvasElement){let s=document.createElement("h1");s.innerHTML=t.message,s.style.position="absolute",s.style.top="20%",s.style.left="10px",s.style.color="black",s.style.backgroundColor="red",document.body.appendChild(s)}}setNeedsRedraw(t){return this.needsRedraw=this.needsRedraw||t,this}setProps(t){return"autoResizeViewport"in t&&(this.props.autoResizeViewport=t.autoResizeViewport||!1),"autoResizeDrawingBuffer"in t&&(this.props.autoResizeDrawingBuffer=t.autoResizeDrawingBuffer||!1),"useDevicePixels"in t&&(this.props.useDevicePixels=t.useDevicePixels||!1),this}async start(){if(this._running)return this;this._running=!0;try{let t;return this._initialized||(this._initialized=!0,await this._initDevice(),this._initialize(),await this.props.onInitialize(this._getAnimationProps())),this._running?(t!==!1&&(this._cancelAnimationFrame(),this._requestAnimationFrame()),this):null}catch(t){let e=t instanceof Error?t:new Error("Unknown error");throw this.props.onError(e),e}}stop(){return this._running&&(this.animationProps&&!this._error&&this.props.onFinalize(this.animationProps),this._cancelAnimationFrame(),this._nextFramePromise=null,this._resolveNextFrame=null,this._running=!1),this}redraw(){return this.device?.isLost||this._error?this:(this._beginFrameTimers(),this._setupFrame(),this._updateAnimationProps(),this._renderFrame(this._getAnimationProps()),this._clearNeedsRedraw(),this._resolveNextFrame&&(this._resolveNextFrame(this),this._nextFramePromise=null,this._resolveNextFrame=null),this._endFrameTimers(),this)}attachTimeline(t){return this.timeline=t,this.timeline}detachTimeline(){this.timeline=null}waitForRender(){return this.setNeedsRedraw("waitForRender"),this._nextFramePromise||(this._nextFramePromise=new Promise(t=>{this._resolveNextFrame=t})),this._nextFramePromise}async toDataURL(){if(this.setNeedsRedraw("toDataURL"),await this.waitForRender(),this.canvas instanceof HTMLCanvasElement)return this.canvas.toDataURL();throw new Error("OffscreenCanvas")}_initialize(){this._startEventHandling(),this._initializeAnimationProps(),this._updateAnimationProps(),this._resizeCanvasDrawingBuffer(),this._resizeViewport()}_setDisplay(t){this.display&&(this.display.destroy(),this.display.animationLoop=null),t&&(t.animationLoop=this),this.display=t}_requestAnimationFrame(){this._running&&(this._animationFrameId=zt(this._animationFrame.bind(this)))}_cancelAnimationFrame(){this._animationFrameId!==null&&(Dt(this._animationFrameId),this._animationFrameId=null)}_animationFrame(){this._running&&(this.redraw(),this._requestAnimationFrame())}_renderFrame(t){if(this.display){this.display._renderFrame(t);return}this.props.onRender(this._getAnimationProps()),this.device?.submit()}_clearNeedsRedraw(){this.needsRedraw=!1}_setupFrame(){this._resizeCanvasDrawingBuffer(),this._resizeViewport()}_initializeAnimationProps(){let t=this.device?.canvasContext?.canvas;if(!this.device||!t)throw new Error("loop");this.animationProps={animationLoop:this,device:this.device,canvas:t,timeline:this.timeline,useDevicePixels:this.props.useDevicePixels,needsRedraw:!1,width:1,height:1,aspect:1,time:0,startTime:Date.now(),engineTime:0,tick:0,tock:0,_mousePosition:null}}_getAnimationProps(){if(!this.animationProps)throw new Error("animationProps");return this.animationProps}_updateAnimationProps(){if(!this.animationProps)return;let{width:t,height:e,aspect:s}=this._getSizeAndAspect();(t!==this.animationProps.width||e!==this.animationProps.height)&&this.setNeedsRedraw("drawing buffer resized"),s!==this.animationProps.aspect&&this.setNeedsRedraw("drawing buffer aspect changed"),this.animationProps.width=t,this.animationProps.height=e,this.animationProps.aspect=s,this.animationProps.needsRedraw=this.needsRedraw,this.animationProps.engineTime=Date.now()-this.animationProps.startTime,this.timeline&&this.timeline.update(this.animationProps.engineTime),this.animationProps.tick=Math.floor(this.animationProps.time/1e3*60),this.animationProps.tock++,this.animationProps.time=this.timeline?this.timeline.getTime():this.animationProps.engineTime}async _initDevice(){if(this.device=await this.props.device,!this.device)throw new Error("No device provided");this.canvas=this.device.canvasContext?.canvas||null}_createInfoDiv(){if(this.canvas&&this.props.onAddHTML){let t=document.createElement("div");document.body.appendChild(t),t.style.position="relative";let e=document.createElement("div");e.style.position="absolute",e.style.left="10px",e.style.bottom="10px",e.style.width="300px",e.style.background="white",this.canvas instanceof HTMLCanvasElement&&t.appendChild(this.canvas),t.appendChild(e);let s=this.props.onAddHTML(e);s&&(e.innerHTML=s)}}_getSizeAndAspect(){if(!this.device)return{width:1,height:1,aspect:1};let[t,e]=this.device?.canvasContext?.getPixelSize()||[1,1],s=1,n=this.device?.canvasContext?.canvas;return n&&n.clientHeight?s=n.clientWidth/n.clientHeight:t>0&&e>0&&(s=t/e),{width:t,height:e,aspect:s}}_resizeViewport(){this.props.autoResizeViewport&&this.device.gl&&this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight)}_resizeCanvasDrawingBuffer(){this.props.autoResizeDrawingBuffer&&this.device?.canvasContext?.resize({useDevicePixels:this.props.useDevicePixels})}_beginFrameTimers(){this.frameRate.timeEnd(),this.frameRate.timeStart(),this.cpuTime.timeStart()}_endFrameTimers(){this.cpuTime.timeEnd()}_startEventHandling(){this.canvas&&(this.canvas.addEventListener("mousemove",this._onMousemove.bind(this)),this.canvas.addEventListener("mouseleave",this._onMouseleave.bind(this)))}_onMousemove(t){t instanceof MouseEvent&&(this._getAnimationProps()._mousePosition=[t.offsetX,t.offsetY])}_onMouseleave(t){this._getAnimationProps()._mousePosition=null}};var ze=L(j(),1);function De(i,t){let e=null,s=t?.device||ze.luma.createDevice({id:"animation-loop",adapters:t?.adapters,createCanvasContext:!0}),n=new ht({...t,device:s,async onInitialize(r){return e=new i(r),await e?.onInitialize(r)},onRender:r=>e?.onRender(r),onFinalize:r=>e?.onFinalize(r)});return n.getInfo=()=>this.AnimationLoopTemplateCtor.info,n}var P=L(j(),1),Gt=L(rt(),1);var vt=L(j(),1);var ue={};function O(i="id"){ue[i]=ue[i]||1;let t=ue[i]++;return`${i}-${t}`}var lt=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(t){if(this.id=t.id||O("geometry"),this.topology=t.topology,this.indices=t.indices||null,this.attributes=t.attributes,this.vertexCount=t.vertexCount,this.bufferLayout=t.bufferLayout||[],this.indices&&!(this.indices.usage&vt.Buffer.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(let t of Object.values(this.attributes))t.destroy()}getVertexCount(){return this.vertexCount}getAttributes(){return this.attributes}getIndexes(){return this.indices||null}_calculateVertexCount(t){return t.byteLength/12}};function Ue(i,t){if(t instanceof lt)return t;let e=Qi(i,t),{attributes:s,bufferLayout:n}=Ji(i,t);return new lt({topology:t.topology||"triangle-list",bufferLayout:n,vertexCount:t.vertexCount,indices:e,attributes:s})}function Qi(i,t){if(!t.indices)return;let e=t.indices.value;return i.createBuffer({usage:vt.Buffer.INDEX,data:e})}function Ji(i,t){let e=[],s={};for(let[r,o]of Object.entries(t.attributes)){let a=r;switch(r){case"POSITION":a="positions";break;case"NORMAL":a="normals";break;case"TEXCOORD_0":a="texCoords";break;case"COLOR_0":a="colors";break}if(o){s[a]=i.createBuffer({data:o.value,id:`${r}-buffer`});let{value:c,size:h,normalized:l}=o;e.push({name:a,format:(0,vt.getVertexFormatFromAttribute)(c,h,l)})}}let n=t._calculateVertexCount(t.attributes,t.indices);return{attributes:s,bufferLayout:e,vertexCount:n}}var ft=L(j(),1);var pe=class{static getDefaultPipelineFactory(t){return t._lumaData.defaultPipelineFactory=t._lumaData.defaultPipelineFactory||new pe(t),t._lumaData.defaultPipelineFactory}device;destroyPolicy;_hashCounter=0;_hashes={};_renderPipelineCache={};_computePipelineCache={};constructor(t){this.device=t,this.destroyPolicy=t.props._factoryDestroyPolicy}createRenderPipeline(t){let e={...ft.RenderPipeline.defaultProps,...t},s=this._hashRenderPipeline(e);if(!this._renderPipelineCache[s]){let n=this.device.createRenderPipeline({...e,id:e.id?`${e.id}-cached`:void 0});n.hash=s,this._renderPipelineCache[s]={pipeline:n,useCount:0}}return this._renderPipelineCache[s].useCount++,this._renderPipelineCache[s].pipeline}createComputePipeline(t){let e={...ft.ComputePipeline.defaultProps,...t},s=this._hashComputePipeline(e);if(!this._computePipelineCache[s]){let n=this.device.createComputePipeline({...e,id:e.id?`${e.id}-cached`:void 0});n.hash=s,this._computePipelineCache[s]={pipeline:n,useCount:0}}return this._computePipelineCache[s].useCount++,this._computePipelineCache[s].pipeline}release(t){let e=t.hash,s=t instanceof ft.ComputePipeline?this._computePipelineCache:this._renderPipelineCache;s[e].useCount--,s[e].useCount===0&&this.destroyPolicy==="unused"&&(s[e].pipeline.destroy(),delete s[e])}_hashComputePipeline(t){return`${this._getHash(t.shader.source)}`}_hashRenderPipeline(t){let e=t.vs?this._getHash(t.vs.source):0,s=t.fs?this._getHash(t.fs.source):0,n="-",r=this._getHash(JSON.stringify(t.bufferLayout));switch(this.device.type){case"webgl":return`${e}/${s}V${n}BL${r}`;default:let o=this._getHash(JSON.stringify(t.parameters));return`${e}/${s}V${n}T${t.topology}P${o}BL${r}`}}_getHash(t){return this._hashes[t]===void 0&&(this._hashes[t]=this._hashCounter++),this._hashes[t]}},Z=pe;V(Z,"defaultProps",{...ft.RenderPipeline.defaultProps});var $e=L(j(),1);var me=class{static getDefaultShaderFactory(t){return t._lumaData.defaultShaderFactory||=new me(t),t._lumaData.defaultShaderFactory}device;destroyPolicy;_cache={};constructor(t){this.device=t,this.destroyPolicy=t.props._factoryDestroyPolicy}createShader(t){let e=this._hashShader(t),s=this._cache[e];if(!s){let n=this.device.createShader({...t,id:t.id?`${t.id}-cached`:void 0});this._cache[e]=s={shader:n,useCount:0}}return s.useCount++,s.shader}release(t){let e=this._hashShader(t),s=this._cache[e];s&&(s.useCount--,s.useCount===0&&this.destroyPolicy==="unused"&&(delete this._cache[e],s.shader.destroy()))}_hashShader(t){return`${t.stage}:${t.source}`}},Q=me;V(Q,"defaultProps",{...$e.Shader.defaultProps});function je(i,t){let e={},s="Values";if(i.attributes.length===0&&!i.varyings?.length)return{"No attributes or varyings":{[s]:"N/A"}};for(let n of i.attributes)if(n){let r=`${n.location} ${n.name}: ${n.type}`;e[`in ${r}`]={[s]:n.stepMode||"vertex"}}for(let n of i.varyings||[]){let r=`${n.location} ${n.name}`;e[`out ${r}`]={[s]:JSON.stringify(n)}}return e}var N=null,ge=null;function Ge(i,{id:t,minimap:e,opaque:s,top:n="0",left:r="0",rgbaScale:o=1}){N||(N=document.createElement("canvas"),N.id=t,N.title=t,N.style.zIndex="100",N.style.position="absolute",N.style.top=n,N.style.left=r,N.style.border="blue 5px solid",N.style.transform="scaleY(-1)",document.body.appendChild(N),ge=N.getContext("2d")),(N.width!==i.width||N.height!==i.height)&&(N.width=i.width/2,N.height=i.height/2,N.style.width="400px",N.style.height="400px");let a=i.device.readPixelsToArrayWebGL(i),c=ge?.createImageData(i.width,i.height);if(c){for(let l=0;l<a.length;l+=4)c.data[0+l+0]=a[l+0]*o,c.data[0+l+1]=a[l+1]*o,c.data[0+l+2]=a[l+2]*o,c.data[0+l+3]=s?255:a[l+3]*o;ge?.putImageData(c,0,0)}}function Bt(i,t,e){if(i===t)return!0;if(!e||!i||!t)return!1;if(Array.isArray(i)){if(!Array.isArray(t)||i.length!==t.length)return!1;for(let s=0;s<i.length;s++)if(!Bt(i[s],t[s],e-1))return!1;return!0}if(Array.isArray(t))return!1;if(typeof i=="object"&&typeof t=="object"){let s=Object.keys(i),n=Object.keys(t);if(s.length!==n.length)return!1;for(let r of s)if(!t.hasOwnProperty(r)||!Bt(i[r],t[r],e-1))return!1;return!0}return!1}var $t=L(j(),1),We=L(rt(),1);function Ve(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function qe(i){return Array.isArray(i)?i.length===0||typeof i[0]=="number":!1}function _t(i){return Ve(i)||qe(i)}function ts(i){return _t(i)||typeof i=="number"||typeof i=="boolean"}function Ut(i){let t={bindings:{},uniforms:{}};return Object.keys(i).forEach(e=>{let s=i[e];ts(s)?t.uniforms[e]=s:t.bindings[e]=s}),t}var Y=class{options={disableWarnings:!1};modules;moduleUniforms;moduleBindings;constructor(t,e){Object.assign(this.options,e);let s=(0,We.getShaderModuleDependencies)(Object.values(t).filter(n=>n.dependencies));for(let n of s)t[n.name]=n;$t.log.log(1,"Creating ShaderInputs with modules",Object.keys(t))(),this.modules=t,this.moduleUniforms={},this.moduleBindings={};for(let[n,r]of Object.entries(t))this._addModule(r),r.name&&n!==r.name&&!this.options.disableWarnings&&$t.log.warn(`Module name: ${n} vs ${r.name}`)()}destroy(){}setProps(t){for(let e of Object.keys(t)){let s=e,n=t[s]||{},r=this.modules[s];if(!r){this.options.disableWarnings||$t.log.warn(`Module ${e} not found`)();continue}let o=this.moduleUniforms[s],a=this.moduleBindings[s],c=r.getUniforms?.(n,o)||n,{uniforms:h,bindings:l}=Ut(c);this.moduleUniforms[s]={...o,...h},this.moduleBindings[s]={...a,...l}}}getModules(){return Object.values(this.modules)}getUniformValues(){return this.moduleUniforms}getBindingValues(){let t={};for(let e of Object.values(this.moduleBindings))Object.assign(t,e);return t}getDebugTable(){let t={};for(let[e,s]of Object.entries(this.moduleUniforms))for(let[n,r]of Object.entries(s))t[`${e}.${n}`]={type:this.modules[e].uniformTypes?.[n],value:String(r)};return t}_addModule(t){let e=t.name;this.moduleUniforms[e]=t.defaultUniforms||{},this.moduleBindings[e]={}}};var xe="";function He(i){xe=i}async function jt(i,t){let e=new Image;return e.crossOrigin=t?.crossOrigin||"anonymous",e.src=i.startsWith("http")?i:xe+i,await e.decode(),t?await createImageBitmap(e,t):await createImageBitmap(e)}async function Ye(i,t){return await new Promise((e,s)=>{try{let n=new Image;n.onload=()=>e(n),n.onerror=()=>s(new Error(`Could not load image ${i}.`)),n.crossOrigin=t?.crossOrigin||"anonymous",n.src=i.startsWith("http")?i:xe+i}catch(n){s(n)}})}var it=class{device;id;texture;sampler;view;ready;isReady=!1;destroyed=!1;resolveReady=()=>{};rejectReady=()=>{};get[Symbol.toStringTag](){return"AsyncTexture"}toString(){return`AsyncTexture:"${this.id}"(${this.isReady?"ready":"loading"})`}constructor(t,e){this.device=t,this.id=e.id||O("async-texture"),typeof e?.data=="string"&&e.dimension==="2d"&&(e={...e,data:jt(e.data)}),this.ready=new Promise((s,n)=>{this.resolveReady=()=>{this.isReady=!0,s()},this.rejectReady=n}),this.initAsync(e)}async initAsync(t){let e,s,n=t.data,r=await Xe(n).then(e,s);if(this.destroyed)return;let o={...t,data:r};this.texture=this.device.createTexture(o),this.sampler=this.texture.sampler,this.view=this.texture.view,this.isReady=!0}destroy(){this.texture&&(this.texture.destroy(),this.texture=null),this.destroyed=!0}resize(t){if(!this.isReady)throw new Error("Cannot resize texture before it is ready");if(t.width===this.texture.width&&t.height===this.texture.height)return!1;if(this.texture){let e=this.texture;this.texture=e.clone(t),e.destroy()}return!0}};async function Xe(i){if(i=await i,Array.isArray(i))return await Promise.all(i.map(Xe));if(i&&typeof i=="object"&&i.constructor===Object){let t=i,e=await Promise.all(Object.values(t)),s=Object.keys(t),n={};for(let r=0;r<s.length;r++)n[s[r]]=e[r];return n}return i}var ot=2,es=1e4,be=class{device;id;source;vs;fs;pipelineFactory;shaderFactory;userData={};parameters;topology;bufferLayout;isInstanced=void 0;instanceCount=0;vertexCount;indexBuffer=null;bufferAttributes={};constantAttributes={};bindings={};uniforms={};vertexArray;transformFeedback=null;pipeline;shaderInputs;_uniformStore;_attributeInfos={};_gpuGeometry=null;_getModuleUniforms;props;_pipelineNeedsUpdate="newly created";_needsRedraw="initializing";_destroyed=!1;_lastDrawTimestamp=-1;get[Symbol.toStringTag](){return"Model"}toString(){return`Model(${this.id})`}constructor(t,e){this.props={...be.defaultProps,...e},e=this.props,this.id=e.id||O("model"),this.device=t,Object.assign(this.userData,e.userData);let s=Object.fromEntries(this.props.modules?.map(c=>[c.name,c])||[]),n=e.shaderInputs||new Y(s,{disableWarnings:this.props.disableWarnings});this.setShaderInputs(n);let r=ss(t),o=(this.props.modules?.length>0?this.props.modules:this.shaderInputs?.getModules())||[];if(this.device.type==="webgpu"&&this.props.source){this.props.shaderLayout||=(0,Gt.getShaderLayoutFromWGSL)(this.props.source);let{source:c,getUniforms:h}=this.props.shaderAssembler.assembleWGSLShader({platformInfo:r,...this.props,modules:o});this.source=c,this._getModuleUniforms=h}else{let{vs:c,fs:h,getUniforms:l}=this.props.shaderAssembler.assembleGLSLShaderPair({platformInfo:r,...this.props,modules:o});this.vs=c,this.fs=h,this._getModuleUniforms=l}this.vertexCount=this.props.vertexCount,this.instanceCount=this.props.instanceCount,this.topology=this.props.topology,this.bufferLayout=this.props.bufferLayout,this.parameters=this.props.parameters,e.geometry&&this.setGeometry(e.geometry),this.pipelineFactory=e.pipelineFactory||Z.getDefaultPipelineFactory(this.device),this.shaderFactory=e.shaderFactory||Q.getDefaultShaderFactory(this.device),this.pipeline=this._updatePipeline(),this.vertexArray=t.createVertexArray({renderPipeline:this.pipeline}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry),"isInstanced"in e&&(this.isInstanced=e.isInstanced),e.instanceCount&&this.setInstanceCount(e.instanceCount),e.vertexCount&&this.setVertexCount(e.vertexCount),e.indexBuffer&&this.setIndexBuffer(e.indexBuffer),e.attributes&&this.setAttributes(e.attributes),e.constantAttributes&&this.setConstantAttributes(e.constantAttributes),e.bindings&&this.setBindings(e.bindings),e.uniforms&&this.setUniformsWebGL(e.uniforms),e.moduleSettings&&this.updateModuleSettingsWebGL(e.moduleSettings),e.transformFeedback&&(this.transformFeedback=e.transformFeedback),Object.seal(this)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&this.shaderFactory.release(this.pipeline.fs),this._uniformStore.destroy(),this._gpuGeometry?.destroy(),this._destroyed=!0)}needsRedraw(){this._getBindingsUpdateTimestamp()>this._lastDrawTimestamp&&this.setNeedsRedraw("contents of bound textures or buffers updated");let t=this._needsRedraw;return this._needsRedraw=!1,t}setNeedsRedraw(t){this._needsRedraw||=t}predraw(){this.updateShaderInputs(),this.pipeline=this._updatePipeline()}draw(t){let e=this._areBindingsLoading();if(e)return P.log.info(ot,`>>> DRAWING ABORTED ${this.id}: ${e} not loaded`)(),!1;try{t.pushDebugGroup(`${this}.predraw(${t})`),this.predraw()}finally{t.popDebugGroup()}let s;try{t.pushDebugGroup(`${this}.draw(${t})`),this._logDrawCallStart(),this.pipeline=this._updatePipeline();let n=this._getBindings();this.pipeline.setBindings(n,{disableWarnings:this.props.disableWarnings}),ye(this.uniforms)||this.pipeline.setUniformsWebGL(this.uniforms);let{indexBuffer:r}=this.vertexArray,o=r?r.byteLength/(r.indexType==="uint32"?4:2):void 0;s=this.pipeline.draw({renderPass:t,vertexArray:this.vertexArray,isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.instanceCount,indexCount:o,transformFeedback:this.transformFeedback||void 0,parameters:this.parameters,topology:this.topology})}finally{t.popDebugGroup(),this._logDrawCallEnd()}return this._logFramebuffer(t),s?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):this._needsRedraw="waiting for resource initialization",s}setGeometry(t){this._gpuGeometry?.destroy();let e=t&&Ue(this.device,t);if(e){this.setTopology(e.topology||"triangle-list");let s=new P._BufferLayoutHelper(this.bufferLayout);this.bufferLayout=s.mergeBufferLayouts(e.bufferLayout,this.bufferLayout),this.vertexArray&&this._setGeometryAttributes(e)}this._gpuGeometry=e}setTopology(t){t!==this.topology&&(this.topology=t,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(t){let e=new P._BufferLayoutHelper(this.bufferLayout);this.bufferLayout=this._gpuGeometry?e.mergeBufferLayouts(t,this._gpuGeometry.bufferLayout):t,this._setPipelineNeedsUpdate("bufferLayout"),this.pipeline=this._updatePipeline(),this.vertexArray=this.device.createVertexArray({renderPipeline:this.pipeline}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry)}setParameters(t){Bt(t,this.parameters,2)||(this.parameters=t,this._setPipelineNeedsUpdate("parameters"))}setInstanceCount(t){this.instanceCount=t,this.isInstanced===void 0&&t>0&&(this.isInstanced=!0),this.setNeedsRedraw("instanceCount")}setVertexCount(t){this.vertexCount=t,this.setNeedsRedraw("vertexCount")}setShaderInputs(t){this.shaderInputs=t,this._uniformStore=new P.UniformStore(this.shaderInputs.modules);for(let[e,s]of Object.entries(this.shaderInputs.modules))if(is(s)){let n=this._uniformStore.getManagedUniformBuffer(this.device,e);this.bindings[`${e}Uniforms`]=n}this.setNeedsRedraw("shaderInputs")}updateShaderInputs(){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues()),this.setBindings(this.shaderInputs.getBindingValues()),this.setNeedsRedraw("shaderInputs")}setBindings(t){Object.assign(this.bindings,t),this.setNeedsRedraw("bindings")}setTransformFeedback(t){this.transformFeedback=t,this.setNeedsRedraw("transformFeedback")}setIndexBuffer(t){this.vertexArray.setIndexBuffer(t),this.setNeedsRedraw("indexBuffer")}setAttributes(t,e){let s=e?.disableWarnings??this.props.disableWarnings;t.indices&&P.log.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)();let n=new P._BufferLayoutHelper(this.bufferLayout);for(let[r,o]of Object.entries(t)){let a=n.getBufferLayout(r);if(!a){s||P.log.warn(`Model(${this.id}): Missing layout for buffer "${r}".`)();continue}let c=n.getAttributeNamesForBuffer(a),h=!1;for(let l of c){let f=this._attributeInfos[l];f&&(this.vertexArray.setBuffer(f.location,o),h=!0)}!h&&!s&&P.log.warn(`Model(${this.id}): Ignoring buffer "${o.id}" for unknown attribute "${r}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(t,e){for(let[s,n]of Object.entries(t)){let r=this._attributeInfos[s];r?this.vertexArray.setConstantWebGL(r.location,n):(e?.disableWarnings??this.props.disableWarnings)||P.log.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${s}"`)()}this.setNeedsRedraw("constants")}setUniforms(t){this.setUniformsWebGL(t)}setUniformsWebGL(t){ye(t)||(this.pipeline.setUniformsWebGL(t),Object.assign(this.uniforms,t)),this.setNeedsRedraw("uniforms")}updateModuleSettingsWebGL(t){let{bindings:e,uniforms:s}=Ut(this._getModuleUniforms(t));Object.assign(this.bindings,e),Object.assign(this.uniforms,s),this.setNeedsRedraw("moduleSettings")}_areBindingsLoading(){for(let t of Object.values(this.bindings))if(t instanceof it&&!t.isReady)return t.id;return!1}_getBindings(){let t={};for(let[e,s]of Object.entries(this.bindings))s instanceof it?s.isReady&&(t[e]=s.texture):t[e]=s;return t}_getBindingsUpdateTimestamp(){let t=0;for(let e of Object.values(this.bindings))e instanceof P.TextureView?t=Math.max(t,e.texture.updateTimestamp):e instanceof P.Buffer||e instanceof P.Texture?t=Math.max(t,e.updateTimestamp):e instanceof it?t=e.texture?Math.max(t,e.texture.updateTimestamp):1/0:e instanceof P.Sampler||(t=Math.max(t,e.buffer.updateTimestamp));return t}_setGeometryAttributes(t){let e={...t.attributes};for(let[s]of Object.entries(e))!this.pipeline.shaderLayout.attributes.find(n=>n.name===s)&&s!=="positions"&&delete e[s];this.vertexCount=t.vertexCount,this.setIndexBuffer(t.indices||null),this.setAttributes(t.attributes,{disableWarnings:!0}),this.setAttributes(e,{disableWarnings:this.props.disableWarnings}),this.setNeedsRedraw("geometry attributes")}_setPipelineNeedsUpdate(t){this._pipelineNeedsUpdate||=t,this.setNeedsRedraw(t)}_updatePipeline(){if(this._pipelineNeedsUpdate){let t=null,e=null;this.pipeline&&(P.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),t=this.pipeline.vs,e=this.pipeline.fs),this._pipelineNeedsUpdate=!1;let s=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders}),n=null;this.source?n=s:this.fs&&(n=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.source||this.fs,debugShaders:this.props.debugShaders})),this.pipeline=this.pipelineFactory.createRenderPipeline({...this.props,bufferLayout:this.bufferLayout,topology:this.topology,parameters:this.parameters,bindings:this._getBindings(),vs:s,fs:n}),this._attributeInfos=(0,P.getAttributeInfosFromLayouts)(this.pipeline.shaderLayout,this.bufferLayout),t&&this.shaderFactory.release(t),e&&this.shaderFactory.release(e)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let t=P.log.level>3?0:es;P.log.level<2||Date.now()-this._lastLogTime<t||(this._lastLogTime=Date.now(),this._logOpen=!0,P.log.group(ot,`>>> DRAWING MODEL ${this.id}`,{collapsed:P.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let t=je(this.pipeline.shaderLayout,this.id);P.log.table(ot,t)();let e=this.shaderInputs.getDebugTable();for(let[n,r]of Object.entries(this.uniforms))e[n]={value:r};P.log.table(ot,e)();let s=this._getAttributeDebugTable();P.log.table(ot,this._attributeInfos)(),P.log.table(ot,s)(),P.log.groupEnd(ot)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(t){let e=this.device.props.debugFramebuffers;if(this._drawCount++,!e)return;let s=t.props.framebuffer;s&&Ge(s,{id:s.id,minimap:!0})}_getAttributeDebugTable(){let t={};for(let[e,s]of Object.entries(this._attributeInfos)){let n=this.vertexArray.attributes[s.location];t[s.location]={name:e,type:s.shaderType,values:n?this._getBufferOrConstantValues(n,s.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){let{indexBuffer:e}=this.vertexArray,s=e.indexType==="uint32"?new Uint32Array(e.debugData):new Uint16Array(e.debugData);t.indices={name:"indices",type:e.indexType,values:s.toString()}}return t}_getBufferOrConstantValues(t,e){let s=(0,P.getTypedArrayFromDataType)(e);return(t instanceof P.Buffer?new s(t.debugData):t).toString()}},q=be;V(q,"defaultProps",{...P.RenderPipeline.defaultProps,source:void 0,vs:null,fs:null,id:"unnamed",handle:void 0,userData:{},defines:{},modules:[],moduleSettings:void 0,geometry:null,indexBuffer:null,attributes:{},constantAttributes:{},varyings:[],isInstanced:void 0,instanceCount:0,vertexCount:0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,transformFeedback:void 0,shaderAssembler:Gt.ShaderAssembler.getDefaultShaderAssembler(),debugShaders:void 0,disableWarnings:void 0});function is(i){return Boolean(i.uniformTypes&&!ye(i.uniformTypes))}function ss(i){return{type:i.type,shaderLanguage:i.info.shadingLanguage,shaderLanguageVersion:i.info.shadingLanguageVersion,gpu:i.info.gpu,features:i.features}}function ye(i){for(let t in i)return!1;return!0}var Ke=L(j(),1),Ze=L(rt(),1);var Vt=class{device;model;transformFeedback;static isSupported(t){return t?.info?.type==="webgl"}constructor(t,e=Vt.defaultProps){if(!Vt.isSupported(t))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=t,this.model=new q(this.device,{id:e.id||"buffer-transform-model",fs:e.fs||(0,Ze.getPassthroughFS)(),topology:e.topology||"point-list",varyings:e.outputs||e.varyings,...e}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:e.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback),Object.seal(this)}destroy(){this.model&&this.model.destroy()}delete(){this.destroy()}run(t){t?.inputBuffers&&this.model.setAttributes(t.inputBuffers),t?.outputBuffers&&this.transformFeedback.setBuffers(t.outputBuffers);let e=this.device.beginRenderPass(t);this.model.draw(e),e.end()}getBuffer(t){return this.transformFeedback.getBuffer(t)}readAsync(t){let e=this.getBuffer(t);if(!e)throw new Error("BufferTransform#getBuffer");if(e instanceof Ke.Buffer)return e.readAsync();let{buffer:s,byteOffset:n=0,byteLength:r=s.byteLength}=e;return s.readAsync(n,r)}},At=Vt;V(At,"defaultProps",{...q.defaultProps,outputs:void 0,feedbackBuffers:void 0});var Qe=L(rt(),1),ns="transform_output",qt=class{device;model;sampler;currentIndex=0;samplerTextureMap=null;bindings=[];resources={};constructor(t,e){this.device=t,this.sampler=t.createSampler({addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",minFilter:"nearest",magFilter:"nearest",mipmapFilter:"nearest"}),this.model=new q(this.device,{id:e.id||"texture-transform-model",fs:e.fs||(0,Qe.getPassthroughFS)({input:e.targetTextureVarying,inputChannels:e.targetTextureChannels,output:ns}),vertexCount:e.vertexCount,...e}),this._initialize(e),Object.seal(this)}destroy(){this.model.destroy();for(let t of this.bindings)t.framebuffer?.destroy()}delete(){this.destroy()}run(t){let{framebuffer:e}=this.bindings[this.currentIndex],s=this.device.beginRenderPass({framebuffer:e,...t});this.model.draw(s),s.end()}getTargetTexture(){let{targetTexture:t}=this.bindings[this.currentIndex];return t}getFramebuffer(){return this.bindings[this.currentIndex].framebuffer}_initialize(t){this._updateBindings(t)}_updateBindings(t){this.bindings[this.currentIndex]=this._updateBinding(this.bindings[this.currentIndex],t)}_updateBinding(t,{sourceBuffers:e,sourceTextures:s,targetTexture:n}){if(t||(t={sourceBuffers:{},sourceTextures:{},targetTexture:null}),Object.assign(t.sourceTextures,s),Object.assign(t.sourceBuffers,e),n){t.targetTexture=n;let{width:r,height:o}=n;t.framebuffer&&t.framebuffer.destroy(),t.framebuffer=this.device.createFramebuffer({id:"transform-framebuffer",width:r,height:o,colorAttachments:[n]}),t.framebuffer.resize({width:r,height:o})}return t}_setSourceTextureParameters(){let t=this.currentIndex,{sourceTextures:e}=this.bindings[t];for(let s in e)e[s].sampler=this.sampler}};var D=class{id;topology;vertexCount;indices;attributes;userData={};constructor(t){let{attributes:e={},indices:s=null,vertexCount:n=null}=t;this.id=t.id||O("geometry"),this.topology=t.topology,s&&(this.indices=ArrayBuffer.isView(s)?{value:s,size:1}:s),this.attributes={};for(let[r,o]of Object.entries(e)){let a=ArrayBuffer.isView(o)?{value:o}:o;if(!ArrayBuffer.isView(a.value))throw new Error(`${this._print(r)}: must be typed array or object with value as typed array`);if((r==="POSITION"||r==="positions")&&!a.size&&(a.size=3),r==="indices"){if(this.indices)throw new Error("Multiple indices detected");this.indices=a}else this.attributes[r]=a}this.indices&&this.indices.isIndexed!==void 0&&(this.indices=Object.assign({},this.indices),delete this.indices.isIndexed),this.vertexCount=n||this._calculateVertexCount(this.attributes,this.indices)}getVertexCount(){return this.vertexCount}getAttributes(){return this.indices?{indices:this.indices,...this.attributes}:this.attributes}_print(t){return`Geometry ${this.id} attribute ${t}`}_setAttributes(t,e){return this}_calculateVertexCount(t,e){if(e)return e.value.length;let s=1/0;for(let n of Object.values(t)){let{value:r,size:o,constant:a}=n;!a&&r&&o!==void 0&&o>=1&&(s=Math.min(s,r.length/o))}return s}};var rs=`struct VertexInputs {
7
+ "use strict";var __exports__=(()=>{var Ui=Object.create;var bt=Object.defineProperty;var $i=Object.getOwnPropertyDescriptor;var ji=Object.getOwnPropertyNames;var Gi=Object.getPrototypeOf,Vi=Object.prototype.hasOwnProperty;var qi=(i,t,e)=>t in i?bt(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var Le=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),Wi=(i,t)=>{for(var e in t)bt(i,e,{get:t[e],enumerable:!0})},Et=(i,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ji(t))!Vi.call(i,n)&&n!==e&&bt(i,n,{get:()=>t[n],enumerable:!(s=$i(t,n))||s.enumerable});return i},kt=(i,t,e)=>(Et(i,t,"default"),e&&Et(e,t,"default")),L=(i,t,e)=>(e=i!=null?Ui(Gi(i)):{},Et(t||!i||!i.__esModule?bt(e,"default",{value:i,enumerable:!0}):e,i)),Hi=i=>Et(bt({},"__esModule",{value:!0}),i);var V=(i,t,e)=>(qi(i,typeof t!="symbol"?t+"":t,e),e);var j=Le((rn,Ne)=>{Ne.exports=globalThis.luma});var rt=Le((wn,Be)=>{Be.exports=globalThis.luma});var St={};Wi(St,{AnimationLoop:()=>ht,AnimationLoopTemplate:()=>Ft,AsyncTexture:()=>it,BackgroundTextureModel:()=>at,BufferTransform:()=>At,ClipSpace:()=>J,Computation:()=>Pt,ConeGeometry:()=>ee,CubeGeometry:()=>ie,CylinderGeometry:()=>se,GPUGeometry:()=>lt,Geometry:()=>D,GroupNode:()=>mt,IcoSphereGeometry:()=>ne,KeyFrames:()=>Nt,LegacyPickingManager:()=>de,Model:()=>q,ModelNode:()=>te,PickingManager:()=>It,PipelineFactory:()=>Z,PlaneGeometry:()=>re,ScenegraphNode:()=>et,ShaderFactory:()=>Q,ShaderInputs:()=>Y,ShaderPassRenderer:()=>ce,SphereGeometry:()=>oe,Swap:()=>gt,SwapBuffers:()=>ae,SwapFramebuffers:()=>xt,TextureTransform:()=>qt,Timeline:()=>Lt,TruncatedConeGeometry:()=>st,cancelAnimationFramePolyfill:()=>Dt,colorPicking:()=>Ni,indexPicking:()=>Li,loadImage:()=>Ye,loadImageBitmap:()=>jt,makeAnimationLoop:()=>De,makeRandomGenerator:()=>Ri,requestAnimationFramePolyfill:()=>zt,setPathPrefix:()=>He});kt(St,L(j(),1));var Yi=1,Xi=1,Lt=class{time=0;channels=new Map;animations=new Map;playing=!1;lastEngineTime=-1;constructor(){}addChannel(t){let{delay:e=0,duration:s=Number.POSITIVE_INFINITY,rate:n=1,repeat:r=1}=t,o=Yi++,a={time:0,delay:e,duration:s,rate:n,repeat:r};return this._setChannelTime(a,this.time),this.channels.set(o,a),o}removeChannel(t){this.channels.delete(t);for(let[e,s]of this.animations)s.channel===t&&this.detachAnimation(e)}isFinished(t){let e=this.channels.get(t);return e===void 0?!1:this.time>=e.delay+e.duration*e.repeat}getTime(t){if(t===void 0)return this.time;let e=this.channels.get(t);return e===void 0?-1:e.time}setTime(t){this.time=Math.max(0,t);let e=this.channels.values();for(let n of e)this._setChannelTime(n,this.time);let s=this.animations.values();for(let n of s){let{animation:r,channel:o}=n;r.setTime(this.getTime(o))}}play(){this.playing=!0}pause(){this.playing=!1,this.lastEngineTime=-1}reset(){this.setTime(0)}attachAnimation(t,e){let s=Xi++;return this.animations.set(s,{animation:t,channel:e}),t.setTime(this.getTime(e)),s}detachAnimation(t){this.animations.delete(t)}update(t){this.playing&&(this.lastEngineTime===-1&&(this.lastEngineTime=t),this.setTime(this.time+(t-this.lastEngineTime)),this.lastEngineTime=t)}_setChannelTime(t,e){let s=e-t.delay,n=t.duration*t.repeat;s>=n?t.time=t.duration*t.rate:(t.time=Math.max(0,s)%t.duration,t.time*=t.rate)}};var Nt=class{startIndex=-1;endIndex=-1;factor=0;times=[];values=[];_lastTime=-1;constructor(t){this.setKeyFrames(t),this.setTime(0)}setKeyFrames(t){let e=t.length;this.times.length=e,this.values.length=e;for(let s=0;s<e;++s)this.times[s]=t[s][0],this.values[s]=t[s][1];this._calculateKeys(this._lastTime)}setTime(t){t=Math.max(0,t),t!==this._lastTime&&(this._calculateKeys(t),this._lastTime=t)}getStartTime(){return this.times[this.startIndex]}getEndTime(){return this.times[this.endIndex]}getStartData(){return this.values[this.startIndex]}getEndData(){return this.values[this.endIndex]}_calculateKeys(t){let e=0,s=this.times.length;for(e=0;e<s-2&&!(this.times[e+1]>t);++e);this.startIndex=e,this.endIndex=e+1;let n=this.times[this.startIndex],r=this.times[this.endIndex];this.factor=Math.min(Math.max(0,(t-n)/(r-n)),1)}};var Ft=class{constructor(t){}async onInitialize(t){return null}};var Fe=L(j(),1);function zt(i){return typeof window<"u"&&window.requestAnimationFrame?window.requestAnimationFrame(i):setTimeout(i,1e3/60)}function Dt(i){return typeof window<"u"&&window.cancelAnimationFrame?window.cancelAnimationFrame(i):clearTimeout(i)}function Mt(){let i;if(typeof window<"u"&&window.performance)i=window.performance.now();else if(typeof process<"u"&&process.hrtime){let t=process.hrtime();i=t[0]*1e3+t[1]/1e6}else i=Date.now();return i}var nt=class{constructor(t,e){this.sampleSize=1,this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this.name=t,this.type=e,this.reset()}reset(){return this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this}setSampleSize(t){return this.sampleSize=t,this}incrementCount(){return this.addCount(1),this}decrementCount(){return this.subtractCount(1),this}addCount(t){return this._count+=t,this._samples++,this._checkSampling(),this}subtractCount(t){return this._count-=t,this._samples++,this._checkSampling(),this}addTime(t){return this._time+=t,this.lastTiming=t,this._samples++,this._checkSampling(),this}timeStart(){return this._startTime=Mt(),this._timerPending=!0,this}timeEnd(){return this._timerPending?(this.addTime(Mt()-this._startTime),this._timerPending=!1,this._checkSampling(),this):this}getSampleAverageCount(){return this.sampleSize>0?this.lastSampleCount/this.sampleSize:0}getSampleAverageTime(){return this.sampleSize>0?this.lastSampleTime/this.sampleSize:0}getSampleHz(){return this.lastSampleTime>0?this.sampleSize/(this.lastSampleTime/1e3):0}getAverageCount(){return this.samples>0?this.count/this.samples:0}getAverageTime(){return this.samples>0?this.time/this.samples:0}getHz(){return this.time>0?this.samples/(this.time/1e3):0}_checkSampling(){this._samples===this.sampleSize&&(this.lastSampleTime=this._time,this.lastSampleCount=this._count,this.count+=this._count,this.time+=this._time,this.samples+=this._samples,this._time=0,this._count=0,this._samples=0)}};var ct=class{constructor(t){this.stats={},this.id=t.id,this.stats={},this._initializeStats(t.stats),Object.seal(this)}get(t,e="count"){return this._getOrCreate({name:t,type:e})}get size(){return Object.keys(this.stats).length}reset(){for(let t of Object.values(this.stats))t.reset();return this}forEach(t){for(let e of Object.values(this.stats))t(e)}getTable(){let t={};return this.forEach(e=>{t[e.name]={time:e.time||0,count:e.count||0,average:e.getAverageTime()||0,hz:e.getHz()||0}}),t}_initializeStats(t=[]){t.forEach(e=>this._getOrCreate(e))}_getOrCreate(t){let{name:e,type:s}=t,n=this.stats[e];return n||(t instanceof nt?n=t:n=new nt(e,s),this.stats[e]=n),n}};var Ki=0,Zi={device:null,onAddHTML:()=>"",onInitialize:async()=>null,onRender:()=>{},onFinalize:()=>{},onError:i=>console.error(i),stats:Fe.luma.stats.get(`animation-loop-${Ki++}`),useDevicePixels:!0,autoResizeViewport:!1,autoResizeDrawingBuffer:!1},ht=class{device=null;canvas=null;props;animationProps=null;timeline=null;stats;cpuTime;gpuTime;frameRate;display;needsRedraw="initialized";_initialized=!1;_running=!1;_animationFrameId=null;_nextFramePromise=null;_resolveNextFrame=null;_cpuStartTime=0;_error=null;constructor(t){if(this.props={...Zi,...t},t=this.props,!t.device)throw new Error("No device provided");let{useDevicePixels:e=!0}=this.props;this.stats=t.stats||new ct({id:"animation-loop-stats"}),this.cpuTime=this.stats.get("CPU Time"),this.gpuTime=this.stats.get("GPU Time"),this.frameRate=this.stats.get("Frame Rate"),this.setProps({autoResizeViewport:t.autoResizeViewport,autoResizeDrawingBuffer:t.autoResizeDrawingBuffer,useDevicePixels:e}),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this._onMousemove=this._onMousemove.bind(this),this._onMouseleave=this._onMouseleave.bind(this)}destroy(){this.stop(),this._setDisplay(null)}delete(){this.destroy()}setError(t){if(this.props.onError(t),this._error=Error(),this.device?.canvasContext?.canvas instanceof HTMLCanvasElement){let s=document.createElement("h1");s.innerHTML=t.message,s.style.position="absolute",s.style.top="20%",s.style.left="10px",s.style.color="black",s.style.backgroundColor="red",document.body.appendChild(s)}}setNeedsRedraw(t){return this.needsRedraw=this.needsRedraw||t,this}setProps(t){return"autoResizeViewport"in t&&(this.props.autoResizeViewport=t.autoResizeViewport||!1),"autoResizeDrawingBuffer"in t&&(this.props.autoResizeDrawingBuffer=t.autoResizeDrawingBuffer||!1),"useDevicePixels"in t&&(this.props.useDevicePixels=t.useDevicePixels||!1),this}async start(){if(this._running)return this;this._running=!0;try{let t;return this._initialized||(this._initialized=!0,await this._initDevice(),this._initialize(),await this.props.onInitialize(this._getAnimationProps())),this._running?(t!==!1&&(this._cancelAnimationFrame(),this._requestAnimationFrame()),this):null}catch(t){let e=t instanceof Error?t:new Error("Unknown error");throw this.props.onError(e),e}}stop(){return this._running&&(this.animationProps&&!this._error&&this.props.onFinalize(this.animationProps),this._cancelAnimationFrame(),this._nextFramePromise=null,this._resolveNextFrame=null,this._running=!1),this}redraw(){return this.device?.isLost||this._error?this:(this._beginFrameTimers(),this._setupFrame(),this._updateAnimationProps(),this._renderFrame(this._getAnimationProps()),this._clearNeedsRedraw(),this._resolveNextFrame&&(this._resolveNextFrame(this),this._nextFramePromise=null,this._resolveNextFrame=null),this._endFrameTimers(),this)}attachTimeline(t){return this.timeline=t,this.timeline}detachTimeline(){this.timeline=null}waitForRender(){return this.setNeedsRedraw("waitForRender"),this._nextFramePromise||(this._nextFramePromise=new Promise(t=>{this._resolveNextFrame=t})),this._nextFramePromise}async toDataURL(){if(this.setNeedsRedraw("toDataURL"),await this.waitForRender(),this.canvas instanceof HTMLCanvasElement)return this.canvas.toDataURL();throw new Error("OffscreenCanvas")}_initialize(){this._startEventHandling(),this._initializeAnimationProps(),this._updateAnimationProps(),this._resizeCanvasDrawingBuffer(),this._resizeViewport()}_setDisplay(t){this.display&&(this.display.destroy(),this.display.animationLoop=null),t&&(t.animationLoop=this),this.display=t}_requestAnimationFrame(){this._running&&(this._animationFrameId=zt(this._animationFrame.bind(this)))}_cancelAnimationFrame(){this._animationFrameId!==null&&(Dt(this._animationFrameId),this._animationFrameId=null)}_animationFrame(){this._running&&(this.redraw(),this._requestAnimationFrame())}_renderFrame(t){if(this.display){this.display._renderFrame(t);return}this.props.onRender(this._getAnimationProps()),this.device?.submit()}_clearNeedsRedraw(){this.needsRedraw=!1}_setupFrame(){this._resizeCanvasDrawingBuffer(),this._resizeViewport()}_initializeAnimationProps(){let t=this.device?.canvasContext?.canvas;if(!this.device||!t)throw new Error("loop");this.animationProps={animationLoop:this,device:this.device,canvas:t,timeline:this.timeline,useDevicePixels:this.props.useDevicePixels,needsRedraw:!1,width:1,height:1,aspect:1,time:0,startTime:Date.now(),engineTime:0,tick:0,tock:0,_mousePosition:null}}_getAnimationProps(){if(!this.animationProps)throw new Error("animationProps");return this.animationProps}_updateAnimationProps(){if(!this.animationProps)return;let{width:t,height:e,aspect:s}=this._getSizeAndAspect();(t!==this.animationProps.width||e!==this.animationProps.height)&&this.setNeedsRedraw("drawing buffer resized"),s!==this.animationProps.aspect&&this.setNeedsRedraw("drawing buffer aspect changed"),this.animationProps.width=t,this.animationProps.height=e,this.animationProps.aspect=s,this.animationProps.needsRedraw=this.needsRedraw,this.animationProps.engineTime=Date.now()-this.animationProps.startTime,this.timeline&&this.timeline.update(this.animationProps.engineTime),this.animationProps.tick=Math.floor(this.animationProps.time/1e3*60),this.animationProps.tock++,this.animationProps.time=this.timeline?this.timeline.getTime():this.animationProps.engineTime}async _initDevice(){if(this.device=await this.props.device,!this.device)throw new Error("No device provided");this.canvas=this.device.canvasContext?.canvas||null}_createInfoDiv(){if(this.canvas&&this.props.onAddHTML){let t=document.createElement("div");document.body.appendChild(t),t.style.position="relative";let e=document.createElement("div");e.style.position="absolute",e.style.left="10px",e.style.bottom="10px",e.style.width="300px",e.style.background="white",this.canvas instanceof HTMLCanvasElement&&t.appendChild(this.canvas),t.appendChild(e);let s=this.props.onAddHTML(e);s&&(e.innerHTML=s)}}_getSizeAndAspect(){if(!this.device)return{width:1,height:1,aspect:1};let[t,e]=this.device?.canvasContext?.getPixelSize()||[1,1],s=1,n=this.device?.canvasContext?.canvas;return n&&n.clientHeight?s=n.clientWidth/n.clientHeight:t>0&&e>0&&(s=t/e),{width:t,height:e,aspect:s}}_resizeViewport(){this.props.autoResizeViewport&&this.device.gl&&this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight)}_resizeCanvasDrawingBuffer(){this.props.autoResizeDrawingBuffer&&this.device?.canvasContext?.resize({useDevicePixels:this.props.useDevicePixels})}_beginFrameTimers(){this.frameRate.timeEnd(),this.frameRate.timeStart(),this.cpuTime.timeStart()}_endFrameTimers(){this.cpuTime.timeEnd()}_startEventHandling(){this.canvas&&(this.canvas.addEventListener("mousemove",this._onMousemove.bind(this)),this.canvas.addEventListener("mouseleave",this._onMouseleave.bind(this)))}_onMousemove(t){t instanceof MouseEvent&&(this._getAnimationProps()._mousePosition=[t.offsetX,t.offsetY])}_onMouseleave(t){this._getAnimationProps()._mousePosition=null}};var ze=L(j(),1);function De(i,t){let e=null,s=t?.device||ze.luma.createDevice({id:"animation-loop",adapters:t?.adapters,createCanvasContext:!0}),n=new ht({...t,device:s,async onInitialize(r){return e=new i(r),await e?.onInitialize(r)},onRender:r=>e?.onRender(r),onFinalize:r=>e?.onFinalize(r)});return n.getInfo=()=>this.AnimationLoopTemplateCtor.info,n}var P=L(j(),1),Gt=L(rt(),1);var vt=L(j(),1);var ue={};function O(i="id"){ue[i]=ue[i]||1;let t=ue[i]++;return`${i}-${t}`}var lt=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(t){if(this.id=t.id||O("geometry"),this.topology=t.topology,this.indices=t.indices||null,this.attributes=t.attributes,this.vertexCount=t.vertexCount,this.bufferLayout=t.bufferLayout||[],this.indices&&!(this.indices.usage&vt.Buffer.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(let t of Object.values(this.attributes))t.destroy()}getVertexCount(){return this.vertexCount}getAttributes(){return this.attributes}getIndexes(){return this.indices||null}_calculateVertexCount(t){return t.byteLength/12}};function Ue(i,t){if(t instanceof lt)return t;let e=Qi(i,t),{attributes:s,bufferLayout:n}=Ji(i,t);return new lt({topology:t.topology||"triangle-list",bufferLayout:n,vertexCount:t.vertexCount,indices:e,attributes:s})}function Qi(i,t){if(!t.indices)return;let e=t.indices.value;return i.createBuffer({usage:vt.Buffer.INDEX,data:e})}function Ji(i,t){let e=[],s={};for(let[r,o]of Object.entries(t.attributes)){let a=r;switch(r){case"POSITION":a="positions";break;case"NORMAL":a="normals";break;case"TEXCOORD_0":a="texCoords";break;case"COLOR_0":a="colors";break}if(o){s[a]=i.createBuffer({data:o.value,id:`${r}-buffer`});let{value:c,size:h,normalized:l}=o;e.push({name:a,format:(0,vt.getVertexFormatFromAttribute)(c,h,l)})}}let n=t._calculateVertexCount(t.attributes,t.indices);return{attributes:s,bufferLayout:e,vertexCount:n}}var ft=L(j(),1);var pe=class{static getDefaultPipelineFactory(t){return t._lumaData.defaultPipelineFactory=t._lumaData.defaultPipelineFactory||new pe(t),t._lumaData.defaultPipelineFactory}device;destroyPolicy;_hashCounter=0;_hashes={};_renderPipelineCache={};_computePipelineCache={};constructor(t){this.device=t,this.destroyPolicy=t.props._factoryDestroyPolicy}createRenderPipeline(t){let e={...ft.RenderPipeline.defaultProps,...t},s=this._hashRenderPipeline(e);if(!this._renderPipelineCache[s]){let n=this.device.createRenderPipeline({...e,id:e.id?`${e.id}-cached`:void 0});n.hash=s,this._renderPipelineCache[s]={pipeline:n,useCount:0}}return this._renderPipelineCache[s].useCount++,this._renderPipelineCache[s].pipeline}createComputePipeline(t){let e={...ft.ComputePipeline.defaultProps,...t},s=this._hashComputePipeline(e);if(!this._computePipelineCache[s]){let n=this.device.createComputePipeline({...e,id:e.id?`${e.id}-cached`:void 0});n.hash=s,this._computePipelineCache[s]={pipeline:n,useCount:0}}return this._computePipelineCache[s].useCount++,this._computePipelineCache[s].pipeline}release(t){let e=t.hash,s=t instanceof ft.ComputePipeline?this._computePipelineCache:this._renderPipelineCache;s[e].useCount--,s[e].useCount===0&&this.destroyPolicy==="unused"&&(s[e].pipeline.destroy(),delete s[e])}_hashComputePipeline(t){return`${this._getHash(t.shader.source)}`}_hashRenderPipeline(t){let e=t.vs?this._getHash(t.vs.source):0,s=t.fs?this._getHash(t.fs.source):0,n="-",r=this._getHash(JSON.stringify(t.bufferLayout));switch(this.device.type){case"webgl":return`${e}/${s}V${n}BL${r}`;default:let o=this._getHash(JSON.stringify(t.parameters));return`${e}/${s}V${n}T${t.topology}P${o}BL${r}`}}_getHash(t){return this._hashes[t]===void 0&&(this._hashes[t]=this._hashCounter++),this._hashes[t]}},Z=pe;V(Z,"defaultProps",{...ft.RenderPipeline.defaultProps});var $e=L(j(),1);var me=class{static getDefaultShaderFactory(t){return t._lumaData.defaultShaderFactory||=new me(t),t._lumaData.defaultShaderFactory}device;destroyPolicy;_cache={};constructor(t){this.device=t,this.destroyPolicy=t.props._factoryDestroyPolicy}createShader(t){let e=this._hashShader(t),s=this._cache[e];if(!s){let n=this.device.createShader({...t,id:t.id?`${t.id}-cached`:void 0});this._cache[e]=s={shader:n,useCount:0}}return s.useCount++,s.shader}release(t){let e=this._hashShader(t),s=this._cache[e];s&&(s.useCount--,s.useCount===0&&this.destroyPolicy==="unused"&&(delete this._cache[e],s.shader.destroy()))}_hashShader(t){return`${t.stage}:${t.source}`}},Q=me;V(Q,"defaultProps",{...$e.Shader.defaultProps});function je(i,t){let e={},s="Values";if(i.attributes.length===0&&!i.varyings?.length)return{"No attributes or varyings":{[s]:"N/A"}};for(let n of i.attributes)if(n){let r=`${n.location} ${n.name}: ${n.type}`;e[`in ${r}`]={[s]:n.stepMode||"vertex"}}for(let n of i.varyings||[]){let r=`${n.location} ${n.name}`;e[`out ${r}`]={[s]:JSON.stringify(n)}}return e}var N=null,ge=null;function Ge(i,{id:t,minimap:e,opaque:s,top:n="0",left:r="0",rgbaScale:o=1}){N||(N=document.createElement("canvas"),N.id=t,N.title=t,N.style.zIndex="100",N.style.position="absolute",N.style.top=n,N.style.left=r,N.style.border="blue 5px solid",N.style.transform="scaleY(-1)",document.body.appendChild(N),ge=N.getContext("2d")),(N.width!==i.width||N.height!==i.height)&&(N.width=i.width/2,N.height=i.height/2,N.style.width="400px",N.style.height="400px");let a=i.device.readPixelsToArrayWebGL(i),c=ge?.createImageData(i.width,i.height);if(c){for(let l=0;l<a.length;l+=4)c.data[0+l+0]=a[l+0]*o,c.data[0+l+1]=a[l+1]*o,c.data[0+l+2]=a[l+2]*o,c.data[0+l+3]=s?255:a[l+3]*o;ge?.putImageData(c,0,0)}}function Bt(i,t,e){if(i===t)return!0;if(!e||!i||!t)return!1;if(Array.isArray(i)){if(!Array.isArray(t)||i.length!==t.length)return!1;for(let s=0;s<i.length;s++)if(!Bt(i[s],t[s],e-1))return!1;return!0}if(Array.isArray(t))return!1;if(typeof i=="object"&&typeof t=="object"){let s=Object.keys(i),n=Object.keys(t);if(s.length!==n.length)return!1;for(let r of s)if(!t.hasOwnProperty(r)||!Bt(i[r],t[r],e-1))return!1;return!0}return!1}var $t=L(j(),1),We=L(rt(),1);function Ve(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function qe(i){return Array.isArray(i)?i.length===0||typeof i[0]=="number":!1}function _t(i){return Ve(i)||qe(i)}function ts(i){return _t(i)||typeof i=="number"||typeof i=="boolean"}function Ut(i){let t={bindings:{},uniforms:{}};return Object.keys(i).forEach(e=>{let s=i[e];ts(s)?t.uniforms[e]=s:t.bindings[e]=s}),t}var Y=class{options={disableWarnings:!1};modules;moduleUniforms;moduleBindings;constructor(t,e){Object.assign(this.options,e);let s=(0,We.getShaderModuleDependencies)(Object.values(t).filter(n=>n.dependencies));for(let n of s)t[n.name]=n;$t.log.log(1,"Creating ShaderInputs with modules",Object.keys(t))(),this.modules=t,this.moduleUniforms={},this.moduleBindings={};for(let[n,r]of Object.entries(t))this._addModule(r),r.name&&n!==r.name&&!this.options.disableWarnings&&$t.log.warn(`Module name: ${n} vs ${r.name}`)()}destroy(){}setProps(t){for(let e of Object.keys(t)){let s=e,n=t[s]||{},r=this.modules[s];if(!r){this.options.disableWarnings||$t.log.warn(`Module ${e} not found`)();continue}let o=this.moduleUniforms[s],a=this.moduleBindings[s],c=r.getUniforms?.(n,o)||n,{uniforms:h,bindings:l}=Ut(c);this.moduleUniforms[s]={...o,...h},this.moduleBindings[s]={...a,...l}}}getModules(){return Object.values(this.modules)}getUniformValues(){return this.moduleUniforms}getBindingValues(){let t={};for(let e of Object.values(this.moduleBindings))Object.assign(t,e);return t}getDebugTable(){let t={};for(let[e,s]of Object.entries(this.moduleUniforms))for(let[n,r]of Object.entries(s))t[`${e}.${n}`]={type:this.modules[e].uniformTypes?.[n],value:String(r)};return t}_addModule(t){let e=t.name;this.moduleUniforms[e]=t.defaultUniforms||{},this.moduleBindings[e]={}}};var xe="";function He(i){xe=i}async function jt(i,t){let e=new Image;return e.crossOrigin=t?.crossOrigin||"anonymous",e.src=i.startsWith("http")?i:xe+i,await e.decode(),t?await createImageBitmap(e,t):await createImageBitmap(e)}async function Ye(i,t){return await new Promise((e,s)=>{try{let n=new Image;n.onload=()=>e(n),n.onerror=()=>s(new Error(`Could not load image ${i}.`)),n.crossOrigin=t?.crossOrigin||"anonymous",n.src=i.startsWith("http")?i:xe+i}catch(n){s(n)}})}var it=class{device;id;texture;sampler;view;ready;isReady=!1;destroyed=!1;resolveReady=()=>{};rejectReady=()=>{};get[Symbol.toStringTag](){return"AsyncTexture"}toString(){return`AsyncTexture:"${this.id}"(${this.isReady?"ready":"loading"})`}constructor(t,e){this.device=t,this.id=e.id||O("async-texture"),typeof e?.data=="string"&&e.dimension==="2d"&&(e={...e,data:jt(e.data)}),this.ready=new Promise((s,n)=>{this.resolveReady=()=>{this.isReady=!0,s()},this.rejectReady=n}),this.initAsync(e)}async initAsync(t){let e,s,n=t.data,r=await Xe(n).then(e,s);if(this.destroyed)return;let o={...t,data:r};this.texture=this.device.createTexture(o),this.sampler=this.texture.sampler,this.view=this.texture.view,this.isReady=!0}destroy(){this.texture&&(this.texture.destroy(),this.texture=null),this.destroyed=!0}resize(t){if(!this.isReady)throw new Error("Cannot resize texture before it is ready");if(t.width===this.texture.width&&t.height===this.texture.height)return!1;if(this.texture){let e=this.texture;this.texture=e.clone(t),e.destroy()}return!0}};async function Xe(i){if(i=await i,Array.isArray(i))return await Promise.all(i.map(Xe));if(i&&typeof i=="object"&&i.constructor===Object){let t=i,e=await Promise.all(Object.values(t)),s=Object.keys(t),n={};for(let r=0;r<s.length;r++)n[s[r]]=e[r];return n}return i}var ot=2,es=1e4,be=class{device;id;source;vs;fs;pipelineFactory;shaderFactory;userData={};parameters;topology;bufferLayout;isInstanced=void 0;instanceCount=0;vertexCount;indexBuffer=null;bufferAttributes={};constantAttributes={};bindings={};uniforms={};vertexArray;transformFeedback=null;pipeline;shaderInputs;_uniformStore;_attributeInfos={};_gpuGeometry=null;_getModuleUniforms;props;_pipelineNeedsUpdate="newly created";_needsRedraw="initializing";_destroyed=!1;_lastDrawTimestamp=-1;get[Symbol.toStringTag](){return"Model"}toString(){return`Model(${this.id})`}constructor(t,e){this.props={...be.defaultProps,...e},e=this.props,this.id=e.id||O("model"),this.device=t,Object.assign(this.userData,e.userData);let s=Object.fromEntries(this.props.modules?.map(c=>[c.name,c])||[]),n=e.shaderInputs||new Y(s,{disableWarnings:this.props.disableWarnings});this.setShaderInputs(n);let r=ss(t),o=(this.props.modules?.length>0?this.props.modules:this.shaderInputs?.getModules())||[];if(this.device.type==="webgpu"&&this.props.source){let{source:c,getUniforms:h}=this.props.shaderAssembler.assembleWGSLShader({platformInfo:r,...this.props,modules:o});this.source=c,this._getModuleUniforms=h,this.props.shaderLayout||=(0,Gt.getShaderLayoutFromWGSL)(this.source)}else{let{vs:c,fs:h,getUniforms:l}=this.props.shaderAssembler.assembleGLSLShaderPair({platformInfo:r,...this.props,modules:o});this.vs=c,this.fs=h,this._getModuleUniforms=l}this.vertexCount=this.props.vertexCount,this.instanceCount=this.props.instanceCount,this.topology=this.props.topology,this.bufferLayout=this.props.bufferLayout,this.parameters=this.props.parameters,e.geometry&&this.setGeometry(e.geometry),this.pipelineFactory=e.pipelineFactory||Z.getDefaultPipelineFactory(this.device),this.shaderFactory=e.shaderFactory||Q.getDefaultShaderFactory(this.device),this.pipeline=this._updatePipeline(),this.vertexArray=t.createVertexArray({renderPipeline:this.pipeline}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry),"isInstanced"in e&&(this.isInstanced=e.isInstanced),e.instanceCount&&this.setInstanceCount(e.instanceCount),e.vertexCount&&this.setVertexCount(e.vertexCount),e.indexBuffer&&this.setIndexBuffer(e.indexBuffer),e.attributes&&this.setAttributes(e.attributes),e.constantAttributes&&this.setConstantAttributes(e.constantAttributes),e.bindings&&this.setBindings(e.bindings),e.uniforms&&this.setUniformsWebGL(e.uniforms),e.moduleSettings&&this.updateModuleSettingsWebGL(e.moduleSettings),e.transformFeedback&&(this.transformFeedback=e.transformFeedback),Object.seal(this)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&this.shaderFactory.release(this.pipeline.fs),this._uniformStore.destroy(),this._gpuGeometry?.destroy(),this._destroyed=!0)}needsRedraw(){this._getBindingsUpdateTimestamp()>this._lastDrawTimestamp&&this.setNeedsRedraw("contents of bound textures or buffers updated");let t=this._needsRedraw;return this._needsRedraw=!1,t}setNeedsRedraw(t){this._needsRedraw||=t}predraw(){this.updateShaderInputs(),this.pipeline=this._updatePipeline()}draw(t){let e=this._areBindingsLoading();if(e)return P.log.info(ot,`>>> DRAWING ABORTED ${this.id}: ${e} not loaded`)(),!1;try{t.pushDebugGroup(`${this}.predraw(${t})`),this.predraw()}finally{t.popDebugGroup()}let s;try{t.pushDebugGroup(`${this}.draw(${t})`),this._logDrawCallStart(),this.pipeline=this._updatePipeline();let n=this._getBindings();this.pipeline.setBindings(n,{disableWarnings:this.props.disableWarnings}),ye(this.uniforms)||this.pipeline.setUniformsWebGL(this.uniforms);let{indexBuffer:r}=this.vertexArray,o=r?r.byteLength/(r.indexType==="uint32"?4:2):void 0;s=this.pipeline.draw({renderPass:t,vertexArray:this.vertexArray,isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.instanceCount,indexCount:o,transformFeedback:this.transformFeedback||void 0,parameters:this.parameters,topology:this.topology})}finally{t.popDebugGroup(),this._logDrawCallEnd()}return this._logFramebuffer(t),s?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):this._needsRedraw="waiting for resource initialization",s}setGeometry(t){this._gpuGeometry?.destroy();let e=t&&Ue(this.device,t);if(e){this.setTopology(e.topology||"triangle-list");let s=new P._BufferLayoutHelper(this.bufferLayout);this.bufferLayout=s.mergeBufferLayouts(e.bufferLayout,this.bufferLayout),this.vertexArray&&this._setGeometryAttributes(e)}this._gpuGeometry=e}setTopology(t){t!==this.topology&&(this.topology=t,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(t){let e=new P._BufferLayoutHelper(this.bufferLayout);this.bufferLayout=this._gpuGeometry?e.mergeBufferLayouts(t,this._gpuGeometry.bufferLayout):t,this._setPipelineNeedsUpdate("bufferLayout"),this.pipeline=this._updatePipeline(),this.vertexArray=this.device.createVertexArray({renderPipeline:this.pipeline}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry)}setParameters(t){Bt(t,this.parameters,2)||(this.parameters=t,this._setPipelineNeedsUpdate("parameters"))}setInstanceCount(t){this.instanceCount=t,this.isInstanced===void 0&&t>0&&(this.isInstanced=!0),this.setNeedsRedraw("instanceCount")}setVertexCount(t){this.vertexCount=t,this.setNeedsRedraw("vertexCount")}setShaderInputs(t){this.shaderInputs=t,this._uniformStore=new P.UniformStore(this.shaderInputs.modules);for(let[e,s]of Object.entries(this.shaderInputs.modules))if(is(s)){let n=this._uniformStore.getManagedUniformBuffer(this.device,e);this.bindings[`${e}Uniforms`]=n}this.setNeedsRedraw("shaderInputs")}updateShaderInputs(){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues()),this.setBindings(this.shaderInputs.getBindingValues()),this.setNeedsRedraw("shaderInputs")}setBindings(t){Object.assign(this.bindings,t),this.setNeedsRedraw("bindings")}setTransformFeedback(t){this.transformFeedback=t,this.setNeedsRedraw("transformFeedback")}setIndexBuffer(t){this.vertexArray.setIndexBuffer(t),this.setNeedsRedraw("indexBuffer")}setAttributes(t,e){let s=e?.disableWarnings??this.props.disableWarnings;t.indices&&P.log.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)();let n=new P._BufferLayoutHelper(this.bufferLayout);for(let[r,o]of Object.entries(t)){let a=n.getBufferLayout(r);if(!a){s||P.log.warn(`Model(${this.id}): Missing layout for buffer "${r}".`)();continue}let c=n.getAttributeNamesForBuffer(a),h=!1;for(let l of c){let f=this._attributeInfos[l];f&&(this.vertexArray.setBuffer(f.location,o),h=!0)}!h&&!s&&P.log.warn(`Model(${this.id}): Ignoring buffer "${o.id}" for unknown attribute "${r}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(t,e){for(let[s,n]of Object.entries(t)){let r=this._attributeInfos[s];r?this.vertexArray.setConstantWebGL(r.location,n):(e?.disableWarnings??this.props.disableWarnings)||P.log.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${s}"`)()}this.setNeedsRedraw("constants")}setUniforms(t){this.setUniformsWebGL(t)}setUniformsWebGL(t){ye(t)||(this.pipeline.setUniformsWebGL(t),Object.assign(this.uniforms,t)),this.setNeedsRedraw("uniforms")}updateModuleSettingsWebGL(t){let{bindings:e,uniforms:s}=Ut(this._getModuleUniforms(t));Object.assign(this.bindings,e),Object.assign(this.uniforms,s),this.setNeedsRedraw("moduleSettings")}_areBindingsLoading(){for(let t of Object.values(this.bindings))if(t instanceof it&&!t.isReady)return t.id;return!1}_getBindings(){let t={};for(let[e,s]of Object.entries(this.bindings))s instanceof it?s.isReady&&(t[e]=s.texture):t[e]=s;return t}_getBindingsUpdateTimestamp(){let t=0;for(let e of Object.values(this.bindings))e instanceof P.TextureView?t=Math.max(t,e.texture.updateTimestamp):e instanceof P.Buffer||e instanceof P.Texture?t=Math.max(t,e.updateTimestamp):e instanceof it?t=e.texture?Math.max(t,e.texture.updateTimestamp):1/0:e instanceof P.Sampler||(t=Math.max(t,e.buffer.updateTimestamp));return t}_setGeometryAttributes(t){let e={...t.attributes};for(let[s]of Object.entries(e))!this.pipeline.shaderLayout.attributes.find(n=>n.name===s)&&s!=="positions"&&delete e[s];this.vertexCount=t.vertexCount,this.setIndexBuffer(t.indices||null),this.setAttributes(t.attributes,{disableWarnings:!0}),this.setAttributes(e,{disableWarnings:this.props.disableWarnings}),this.setNeedsRedraw("geometry attributes")}_setPipelineNeedsUpdate(t){this._pipelineNeedsUpdate||=t,this.setNeedsRedraw(t)}_updatePipeline(){if(this._pipelineNeedsUpdate){let t=null,e=null;this.pipeline&&(P.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),t=this.pipeline.vs,e=this.pipeline.fs),this._pipelineNeedsUpdate=!1;let s=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders}),n=null;this.source?n=s:this.fs&&(n=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.source||this.fs,debugShaders:this.props.debugShaders})),this.pipeline=this.pipelineFactory.createRenderPipeline({...this.props,bufferLayout:this.bufferLayout,topology:this.topology,parameters:this.parameters,bindings:this._getBindings(),vs:s,fs:n}),this._attributeInfos=(0,P.getAttributeInfosFromLayouts)(this.pipeline.shaderLayout,this.bufferLayout),t&&this.shaderFactory.release(t),e&&this.shaderFactory.release(e)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let t=P.log.level>3?0:es;P.log.level<2||Date.now()-this._lastLogTime<t||(this._lastLogTime=Date.now(),this._logOpen=!0,P.log.group(ot,`>>> DRAWING MODEL ${this.id}`,{collapsed:P.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let t=je(this.pipeline.shaderLayout,this.id);P.log.table(ot,t)();let e=this.shaderInputs.getDebugTable();for(let[n,r]of Object.entries(this.uniforms))e[n]={value:r};P.log.table(ot,e)();let s=this._getAttributeDebugTable();P.log.table(ot,this._attributeInfos)(),P.log.table(ot,s)(),P.log.groupEnd(ot)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(t){let e=this.device.props.debugFramebuffers;if(this._drawCount++,!e)return;let s=t.props.framebuffer;s&&Ge(s,{id:s.id,minimap:!0})}_getAttributeDebugTable(){let t={};for(let[e,s]of Object.entries(this._attributeInfos)){let n=this.vertexArray.attributes[s.location];t[s.location]={name:e,type:s.shaderType,values:n?this._getBufferOrConstantValues(n,s.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){let{indexBuffer:e}=this.vertexArray,s=e.indexType==="uint32"?new Uint32Array(e.debugData):new Uint16Array(e.debugData);t.indices={name:"indices",type:e.indexType,values:s.toString()}}return t}_getBufferOrConstantValues(t,e){let s=(0,P.getTypedArrayFromDataType)(e);return(t instanceof P.Buffer?new s(t.debugData):t).toString()}},q=be;V(q,"defaultProps",{...P.RenderPipeline.defaultProps,source:void 0,vs:null,fs:null,id:"unnamed",handle:void 0,userData:{},defines:{},modules:[],moduleSettings:void 0,geometry:null,indexBuffer:null,attributes:{},constantAttributes:{},varyings:[],isInstanced:void 0,instanceCount:0,vertexCount:0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,transformFeedback:void 0,shaderAssembler:Gt.ShaderAssembler.getDefaultShaderAssembler(),debugShaders:void 0,disableWarnings:void 0});function is(i){return Boolean(i.uniformTypes&&!ye(i.uniformTypes))}function ss(i){return{type:i.type,shaderLanguage:i.info.shadingLanguage,shaderLanguageVersion:i.info.shadingLanguageVersion,gpu:i.info.gpu,features:i.features}}function ye(i){for(let t in i)return!1;return!0}var Ke=L(j(),1),Ze=L(rt(),1);var Vt=class{device;model;transformFeedback;static isSupported(t){return t?.info?.type==="webgl"}constructor(t,e=Vt.defaultProps){if(!Vt.isSupported(t))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=t,this.model=new q(this.device,{id:e.id||"buffer-transform-model",fs:e.fs||(0,Ze.getPassthroughFS)(),topology:e.topology||"point-list",varyings:e.outputs||e.varyings,...e}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:e.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback),Object.seal(this)}destroy(){this.model&&this.model.destroy()}delete(){this.destroy()}run(t){t?.inputBuffers&&this.model.setAttributes(t.inputBuffers),t?.outputBuffers&&this.transformFeedback.setBuffers(t.outputBuffers);let e=this.device.beginRenderPass(t);this.model.draw(e),e.end()}getBuffer(t){return this.transformFeedback.getBuffer(t)}readAsync(t){let e=this.getBuffer(t);if(!e)throw new Error("BufferTransform#getBuffer");if(e instanceof Ke.Buffer)return e.readAsync();let{buffer:s,byteOffset:n=0,byteLength:r=s.byteLength}=e;return s.readAsync(n,r)}},At=Vt;V(At,"defaultProps",{...q.defaultProps,outputs:void 0,feedbackBuffers:void 0});var Qe=L(rt(),1),ns="transform_output",qt=class{device;model;sampler;currentIndex=0;samplerTextureMap=null;bindings=[];resources={};constructor(t,e){this.device=t,this.sampler=t.createSampler({addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",minFilter:"nearest",magFilter:"nearest",mipmapFilter:"nearest"}),this.model=new q(this.device,{id:e.id||"texture-transform-model",fs:e.fs||(0,Qe.getPassthroughFS)({input:e.targetTextureVarying,inputChannels:e.targetTextureChannels,output:ns}),vertexCount:e.vertexCount,...e}),this._initialize(e),Object.seal(this)}destroy(){this.model.destroy();for(let t of this.bindings)t.framebuffer?.destroy()}delete(){this.destroy()}run(t){let{framebuffer:e}=this.bindings[this.currentIndex],s=this.device.beginRenderPass({framebuffer:e,...t});this.model.draw(s),s.end()}getTargetTexture(){let{targetTexture:t}=this.bindings[this.currentIndex];return t}getFramebuffer(){return this.bindings[this.currentIndex].framebuffer}_initialize(t){this._updateBindings(t)}_updateBindings(t){this.bindings[this.currentIndex]=this._updateBinding(this.bindings[this.currentIndex],t)}_updateBinding(t,{sourceBuffers:e,sourceTextures:s,targetTexture:n}){if(t||(t={sourceBuffers:{},sourceTextures:{},targetTexture:null}),Object.assign(t.sourceTextures,s),Object.assign(t.sourceBuffers,e),n){t.targetTexture=n;let{width:r,height:o}=n;t.framebuffer&&t.framebuffer.destroy(),t.framebuffer=this.device.createFramebuffer({id:"transform-framebuffer",width:r,height:o,colorAttachments:[n]}),t.framebuffer.resize({width:r,height:o})}return t}_setSourceTextureParameters(){let t=this.currentIndex,{sourceTextures:e}=this.bindings[t];for(let s in e)e[s].sampler=this.sampler}};var D=class{id;topology;vertexCount;indices;attributes;userData={};constructor(t){let{attributes:e={},indices:s=null,vertexCount:n=null}=t;this.id=t.id||O("geometry"),this.topology=t.topology,s&&(this.indices=ArrayBuffer.isView(s)?{value:s,size:1}:s),this.attributes={};for(let[r,o]of Object.entries(e)){let a=ArrayBuffer.isView(o)?{value:o}:o;if(!ArrayBuffer.isView(a.value))throw new Error(`${this._print(r)}: must be typed array or object with value as typed array`);if((r==="POSITION"||r==="positions")&&!a.size&&(a.size=3),r==="indices"){if(this.indices)throw new Error("Multiple indices detected");this.indices=a}else this.attributes[r]=a}this.indices&&this.indices.isIndexed!==void 0&&(this.indices=Object.assign({},this.indices),delete this.indices.isIndexed),this.vertexCount=n||this._calculateVertexCount(this.attributes,this.indices)}getVertexCount(){return this.vertexCount}getAttributes(){return this.indices?{indices:this.indices,...this.attributes}:this.attributes}_print(t){return`Geometry ${this.id} attribute ${t}`}_setAttributes(t,e){return this}_calculateVertexCount(t,e){if(e)return e.value.length;let s=1/0;for(let n of Object.values(t)){let{value:r,size:o,constant:a}=n;!a&&r&&o!==void 0&&o>=1&&(s=Math.min(s,r.length/o))}return s}};var rs=`struct VertexInputs {
8
8
  @location(0) clipSpacePosition: vec2<f32>,
9
9
  @location(1) texCoord: vec2<f32>,
10
10
  @location(2) coordinate: vec2<f32>
package/dist/index.cjs CHANGED
@@ -1364,7 +1364,6 @@ var _Model = class {
1364
1364
  );
1365
1365
  const isWebGPU = this.device.type === "webgpu";
1366
1366
  if (isWebGPU && this.props.source) {
1367
- this.props.shaderLayout ||= (0, import_shadertools2.getShaderLayoutFromWGSL)(this.props.source);
1368
1367
  const { source: source3, getUniforms: getUniforms2 } = this.props.shaderAssembler.assembleWGSLShader({
1369
1368
  platformInfo,
1370
1369
  ...this.props,
@@ -1372,6 +1371,7 @@ var _Model = class {
1372
1371
  });
1373
1372
  this.source = source3;
1374
1373
  this._getModuleUniforms = getUniforms2;
1374
+ this.props.shaderLayout ||= (0, import_shadertools2.getShaderLayoutFromWGSL)(this.source);
1375
1375
  } else {
1376
1376
  const { vs: vs3, fs: fs3, getUniforms: getUniforms2 } = this.props.shaderAssembler.assembleGLSLShaderPair({
1377
1377
  platformInfo,