UNPKG

@luma.gl/engine

Version:

3D Engine Components for luma.gl

7 lines 127 kB
(function webpackUniversalModuleDefinition(root, factory) { if (typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define([], factory); else if (typeof exports === 'object') exports['luma'] = factory(); else root['luma'] = factory();})(globalThis, function () { "use strict";var __exports__=(()=>{var Wn=Object.create;var Et=Object.defineProperty;var Yn=Object.getOwnPropertyDescriptor;var Kn=Object.getOwnPropertyNames;var Zn=Object.getPrototypeOf,Qn=Object.prototype.hasOwnProperty;var Jn=(i,t,e)=>t in i?Et(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var ui=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),tr=(i,t)=>{for(var e in t)Et(i,e,{get:t[e],enumerable:!0})},Wt=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Kn(t))!Qn.call(i,r)&&r!==e&&Et(i,r,{get:()=>t[r],enumerable:!(n=Yn(t,r))||n.enumerable});return i},Yt=(i,t,e)=>(Wt(i,t,"default"),e&&Wt(e,t,"default")),k=(i,t,e)=>(e=i!=null?Wn(Zn(i)):{},Wt(t||!i||!i.__esModule?Et(e,"default",{value:i,enumerable:!0}):e,i)),er=i=>Wt(Et({},"__esModule",{value:!0}),i);var Y=(i,t,e)=>(Jn(i,typeof t!="symbol"?t+"":t,e),e);var U=ui((io,mi)=>{mi.exports=globalThis.luma});var nt=ui((vo,bi)=>{bi.exports=globalThis.luma});var $t={};tr($t,{AnimationLoop:()=>lt,AnimationLoopTemplate:()=>Qt,AsyncTexture:()=>to,BackgroundTextureModel:()=>Mt,BufferTransform:()=>Bt,ClipSpace:()=>st,Computation:()=>jt,ConeGeometry:()=>ct,CubeGeometry:()=>be,CylinderGeometry:()=>ye,DirectionalLightModel:()=>ge,DynamicTexture:()=>B,GPUGeometry:()=>mt,Geometry:()=>$,GroupNode:()=>ft,IcoSphereGeometry:()=>Me,KeyFrames:()=>Zt,LegacyPickingManager:()=>Se,Material:()=>yt,MaterialFactory:()=>bt,Model:()=>H,ModelNode:()=>xe,PickingManager:()=>Ut,PlaneGeometry:()=>_e,PointLightModel:()=>me,ScenegraphNode:()=>et,ShaderInputs:()=>G,ShaderPassRenderer:()=>ve,SphereGeometry:()=>_t,SpotLightModel:()=>pe,Swap:()=>At,SwapBuffers:()=>Ie,SwapFramebuffers:()=>Tt,TextureTransform:()=>re,Timeline:()=>Kt,TruncatedConeGeometry:()=>at,cancelAnimationFramePolyfill:()=>te,colorPicking:()=>Gt,indexPicking:()=>Pe,legacyColorPicking:()=>$n,loadImage:()=>Rn,loadImageBitmap:()=>On,makeAnimationLoop:()=>xi,makeRandomGenerator:()=>Ln,picking:()=>Un,requestAnimationFramePolyfill:()=>Jt,resolvePickingBackend:()=>jn,resolvePickingMode:()=>Te,setPathPrefix:()=>Cn,supportsIndexPicking:()=>di});Yt($t,k(U(),1));var ir=1,nr=1,Kt=class{time=0;channels=new Map;animations=new Map;playing=!1;lastEngineTime=-1;constructor(){}addChannel(t){let{delay:e=0,duration:n=Number.POSITIVE_INFINITY,rate:r=1,repeat:s=1}=t,o=ir++,a={time:0,delay:e,duration:n,rate:r,repeat:s};return this._setChannelTime(a,this.time),this.channels.set(o,a),o}removeChannel(t){this.channels.delete(t);for(let[e,n]of this.animations)n.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 r of e)this._setChannelTime(r,this.time);let n=this.animations.values();for(let r of n){let{animation:s,channel:o}=r;s.setTime(this.getTime(o))}}play(){this.playing=!0}pause(){this.playing=!1,this.lastEngineTime=-1}reset(){this.setTime(0)}attachAnimation(t,e){let n=nr++;return this.animations.set(n,{animation:t,channel:e}),t.setTime(this.getTime(e)),n}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 n=e-t.delay,r=t.duration*t.repeat;n>=r?t.time=t.duration*t.rate:(t.time=Math.max(0,n)%t.duration,t.time*=t.rate)}};var Zt=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 n=0;n<e;++n)this.times[n]=t[n][0],this.values[n]=t[n][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,n=this.times.length;for(e=0;e<n-2&&!(this.times[e+1]>t);++e);this.startIndex=e,this.endIndex=e+1;let r=this.times[this.startIndex],s=this.times[this.endIndex];this.factor=Math.min(Math.max(0,(t-r)/(s-r)),1)}};var Qt=class{constructor(t){}async onInitialize(t){return null}};var pi=k(U(),1);function Jt(i){let t=typeof window<"u"?window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame:null;return t?t.call(window,i):setTimeout(()=>i(typeof performance<"u"?performance.now():Date.now()),1e3/60)}function te(i){let t=typeof window<"u"?window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame:null;if(t){t.call(window,i);return}clearTimeout(i)}function Lt(){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 ht=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=Lt(),this._timerPending=!0,this}timeEnd(){return this._timerPending?(this.addTime(Lt()-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 ut=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:n}=t,r=this.stats[e];return r||(t instanceof ht?r=t:r=new ht(e,n),this.stats[e]=r),r}};var rr=0,sr="Animation Loop",Ee=class{device=null;canvas=null;props;animationProps=null;timeline=null;stats;sharedStats;cpuTime;gpuTime;frameRate;display;_needsRedraw="initialized";_initialized=!1;_running=!1;_animationFrameId=null;_nextFramePromise=null;_resolveNextFrame=null;_cpuStartTime=0;_error=null;_lastFrameTime=0;constructor(t){if(this.props={...Ee.defaultAnimationLoopProps,...t},t=this.props,!t.device)throw new Error("No device provided");this.stats=t.stats||new ut({id:`animation-loop-${rr++}`}),this.sharedStats=pi.luma.stats.get(sr),this.frameRate=this.stats.get("Frame Rate"),this.frameRate.setSampleSize(1),this.cpuTime=this.stats.get("CPU Time"),this.gpuTime=this.stats.get("GPU Time"),this.setProps({autoResizeViewport:t.autoResizeViewport}),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),this.device?._disableDebugGPUTime()}delete(){this.destroy()}reportError(t){this.props.onError(t),this._error=t}setNeedsRedraw(t){return this._needsRedraw=this._needsRedraw||t,this}needsRedraw(){let t=this._needsRedraw;return this._needsRedraw=!1,t}setProps(t){return"autoResizeViewport"in t&&(this.props.autoResizeViewport=t.autoResizeViewport||!1),this}async start(){if(this._running)return this;this._running=!0;try{let t;if(!this._initialized){if(this._initialized=!0,await this._initDevice(),this._initialize(),!this._running)return null;await this.props.onInitialize(this._getAnimationProps())}return 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._lastFrameTime=0),this}redraw(t){return this.device?.isLost||this._error?this:(this._beginFrameTimers(t),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._resizeViewport(),this.device?._enableDebugGPUTime()}_setDisplay(t){this.display&&(this.display.destroy(),this.display.animationLoop=null),t&&(t.animationLoop=this),this.display=t}_requestAnimationFrame(){this._running&&(this._animationFrameId=Jt(this._animationFrame.bind(this)))}_cancelAnimationFrame(){this._animationFrameId!==null&&(te(this._animationFrameId),this._animationFrameId=null)}_animationFrame(t){this._running&&(this.redraw(t),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._resizeViewport()}_initializeAnimationProps(){let t=this.device?.getDefaultCanvasContext();if(!this.device||!t)throw new Error("loop");let e=t?.canvas,n=t.props.useDevicePixels;this.animationProps={animationLoop:this,device:this.device,canvasContext:t,canvas:e,useDevicePixels:n,timeline:this.timeline,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:n}=this._getSizeAndAspect();(t!==this.animationProps.width||e!==this.animationProps.height)&&this.setNeedsRedraw("drawing buffer resized"),n!==this.animationProps.aspect&&this.setNeedsRedraw("drawing buffer aspect changed"),this.animationProps.width=t,this.animationProps.height=e,this.animationProps.aspect=n,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.getDefaultCanvasContext().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 n=this.props.onAddHTML(e);n&&(e.innerHTML=n)}}_getSizeAndAspect(){if(!this.device)return{width:1,height:1,aspect:1};let[t,e]=this.device.getDefaultCanvasContext().getDrawingBufferSize(),n=t>0&&e>0?t/e:1;return{width:t,height:e,aspect:n}}_resizeViewport(){this.props.autoResizeViewport&&this.device.gl&&this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight)}_beginFrameTimers(t){let e=t??(typeof performance<"u"?performance.now():Date.now());if(this._lastFrameTime){let n=e-this._lastFrameTime;n>0&&this.frameRate.addTime(n)}this._lastFrameTime=e,this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeStart()}_endFrameTimers(){this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeEnd(),this._updateSharedStats()}_consumeEncodedGpuTime(){if(!this.device)return;let t=this.device.commandEncoder._gpuTimeMs;t!==void 0&&(this.gpuTime.addTime(t),this.device.commandEncoder._gpuTimeMs=void 0)}_updateSharedStats(){if(this.stats!==this.sharedStats){for(let t of Object.keys(this.sharedStats.stats))this.stats.stats[t]||delete this.sharedStats.stats[t];this.stats.forEach(t=>{let e=this.sharedStats.get(t.name,t.type);e.sampleSize=t.sampleSize,e.time=t.time,e.count=t.count,e.samples=t.samples,e.lastTiming=t.lastTiming,e.lastSampleTime=t.lastSampleTime,e.lastSampleCount=t.lastSampleCount,e._count=t._count,e._time=t._time,e._samples=t._samples,e._startTime=t._startTime,e._timerPending=t._timerPending})}}_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}},lt=Ee;Y(lt,"defaultAnimationLoopProps",{device:null,onAddHTML:()=>"",onInitialize:async()=>null,onRender:()=>{},onFinalize:()=>{},onError:t=>console.error(t),stats:void 0,autoResizeViewport:!1});var gi=k(U(),1);function xi(i,t){let e=null,n=t?.device||gi.luma.createDevice({id:"animation-loop",adapters:t?.adapters,createCanvasContext:!0}),r=new lt({...t,device:n,async onInitialize(s){ar(s.animationLoop.device);try{return e=new i(s),await e?.onInitialize(s)}catch(o){return console.error(o),or(s.animationLoop.device,o),null}},onRender:s=>e?.onRender(s),onFinalize:s=>e?.onFinalize(s)});return r.getInfo=()=>this.AnimationLoopTemplateCtor.info,r}function or(i,t){if(!i)return;let e=i.getDefaultCanvasContext().canvas;if(e instanceof HTMLCanvasElement){e.style.overflow="visible";let n=document.getElementById("animation-loop-error");n?.remove(),n=document.createElement("h1"),n.id="animation-loop-error",n.innerHTML=t.message,n.style.position="absolute",n.style.top="10px",n.style.left="10px",n.style.color="black",n.style.backgroundColor="red",e.parentElement?.appendChild(n)}}function ar(i){if(!i)return;let t=document.getElementById("animation-loop-error");t&&t.remove()}var w=k(U(),1),Fi=k(nt(),1);var Ct=k(U(),1);var Le={};function S(i="id"){Le[i]=Le[i]||1;let t=Le[i]++;return`${i}-${t}`}var mt=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(t){if(this.id=t.id||S("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&Ct.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 yi(i,t){if(t instanceof mt)return t;let e=cr(i,t),{attributes:n,bufferLayout:r}=hr(i,t);return new mt({topology:t.topology||"triangle-list",bufferLayout:r,vertexCount:t.vertexCount,indices:e,attributes:n})}function cr(i,t){if(!t.indices)return;let e=t.indices.value;return i.createBuffer({usage:Ct.Buffer.INDEX,data:e})}function hr(i,t){let e=[],n={};for(let[s,o]of Object.entries(t.attributes)){let a=s;switch(s){case"POSITION":a="positions";break;case"NORMAL":a="normals";break;case"TEXCOORD_0":a="texCoords";break;case"TEXCOORD_1":a="texCoords1";break;case"COLOR_0":a="colors";break}if(o){n[a]=i.createBuffer({data:o.value,id:`${s}-buffer`});let{value:c,size:h,normalized:l}=o;if(h===void 0)throw new Error(`Attribute ${s} is missing a size`);e.push({name:a,format:Ct.vertexFormatDecoder.getVertexFormatFromAttribute(c,h,l)})}}let r=t._calculateVertexCount(t.attributes,t.indices);return{attributes:n,bufferLayout:e,vertexCount:r}}function Mi(i,t){let e={},n="Values";if(i.attributes.length===0&&!i.varyings?.length)return{"No attributes or varyings":{[n]:"N/A"}};for(let r of i.attributes)if(r){let s=`${r.location} ${r.name}: ${r.type}`;e[`in ${s}`]={[n]:r.stepMode||"vertex"}}for(let r of i.varyings||[]){let s=`${r.location} ${r.name}`;e[`out ${s}`]={[n]:JSON.stringify(r)}}return e}var _i="__debugFramebufferState";function vi(i,t,e){if(i.device.type!=="webgl")return;let n=fr(i.device);if(!n.flushing){if(mr(i)){lr(i,e,n);return}t&&ur(t)&&t.handle!==null&&(n.queuedFramebuffers.includes(t)||n.queuedFramebuffers.push(t))}}function lr(i,t,e){if(e.queuedFramebuffers.length===0)return;let n=i.device,{gl:r}=n,s=r.getParameter(36010),o=r.getParameter(36006),[a,c]=i.device.getDefaultCanvasContext().getDrawingBufferSize(),h=Ii(t.top,8),l=Ii(t.left,8);e.flushing=!0;try{for(let d of e.queuedFramebuffers){let[f,p,g,u,b]=dr({framebuffer:d,targetWidth:a,targetHeight:c,topPx:h,leftPx:l,minimap:t.minimap});r.bindFramebuffer(36008,d.handle),r.bindFramebuffer(36009,null),r.blitFramebuffer(0,0,d.width,d.height,f,p,g,u,16384,9728),h+=b+8}}finally{r.bindFramebuffer(36008,s),r.bindFramebuffer(36009,o),e.flushing=!1}}function dr(i){let{framebuffer:t,targetWidth:e,targetHeight:n,topPx:r,leftPx:s,minimap:o}=i,a=o?Math.max(Math.floor(e/4),1):e,c=o?Math.max(Math.floor(n/4),1):n,h=Math.min(a/t.width,c/t.height),l=Math.max(Math.floor(t.width*h),1),d=Math.max(Math.floor(t.height*h),1),f=s,p=Math.max(n-r-d,0),g=f+l,u=p+d;return[f,p,g,u,d]}function fr(i){return i.userData[_i]||={flushing:!1,queuedFramebuffers:[]},i.userData[_i]}function ur(i){return"colorAttachments"in i}function mr(i){let t=i.props.framebuffer;return!t||t.handle===null}function Ii(i,t){if(!i)return t;let e=Number.parseInt(i,10);return Number.isFinite(e)?e:t}function ee(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 n=0;n<i.length;n++)if(!ee(i[n],t[n],e-1))return!1;return!0}if(Array.isArray(t))return!1;if(typeof i=="object"&&typeof t=="object"){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let s of n)if(!t.hasOwnProperty(s)||!ee(i[s],t[s],e-1))return!1;return!0}return!1}var wi=k(U(),1),pt=class{bufferLayouts;constructor(t){this.bufferLayouts=t}getBufferLayout(t){return this.bufferLayouts.find(e=>e.name===t)||null}getAttributeNamesForBuffer(t){return t.attributes?t.attributes?.map(e=>e.attribute):[t.name]}mergeBufferLayouts(t,e){let n=[...t];for(let r of e){let s=n.findIndex(o=>o.name===r.name);s<0?n.push(r):n[s]=r}return n}getBufferIndex(t){let e=this.bufferLayouts.findIndex(n=>n.name===t);return e===-1&&wi.log.warn(`BufferLayout: Missing buffer for "${t}".`)(),e}};function Ai(i,t){let e=1/0;for(let n of i){let r=t[n];r!==void 0&&(e=Math.min(e,r))}return e}function Ti(i,t){let e=Object.fromEntries(i.attributes.map(r=>[r.name,r.location])),n=t.slice();return n.sort((r,s)=>{let o=r.attributes?r.attributes.map(l=>l.attribute):[r.name],a=s.attributes?s.attributes.map(l=>l.attribute):[s.name],c=Ai(o,e),h=Ai(a,e);return c-h}),n}function gt(i,t){if(!i||!t.some(n=>n.bindingLayout?.length))return i;let e={...i,bindings:i.bindings.map(n=>({...n}))};"attributes"in(i||{})&&(e.attributes=i?.attributes||[]);for(let n of t)for(let r of n.bindingLayout||[])for(let s of pr(r.name)){let o=e.bindings.find(a=>a.name===s);o?.group===0&&(o.group=r.group)}return e}function xt(i){return Boolean(i.uniformTypes&&!gr(i.uniformTypes))}function pr(i){let t=new Set([i,`${i}Uniforms`]);return i.endsWith("Uniforms")||t.add(`${i}Sampler`),[...t]}function gr(i){for(let t in i)return!1;return!0}var ie=k(U(),1),Ci=k(nt(),1);function Pi(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function Si(i){return Array.isArray(i)?i.length===0||typeof i[0]=="number":!1}function Ot(i){return Pi(i)||Si(i)}function xr(i){return Ot(i)||typeof i=="number"||typeof i=="boolean"}function Ei(i,t={}){let e={bindings:{},uniforms:{}};return Object.keys(i).forEach(n=>{let r=i[n];Object.prototype.hasOwnProperty.call(t,n)||xr(r)?e.uniforms[n]=r:e.bindings[n]=r}),e}var G=class{options={disableWarnings:!1};modules;moduleUniforms;moduleBindings;constructor(t,e){Object.assign(this.options,e);let n=(0,Ci.getShaderModuleDependencies)(Object.values(t).filter(br));for(let r of n)t[r.name]=r;ie.log.log(1,"Creating ShaderInputs with modules",Object.keys(t))(),this.modules=t,this.moduleUniforms={},this.moduleBindings={};for(let[r,s]of Object.entries(t))s&&(this._addModule(s),s.name&&r!==s.name&&!this.options.disableWarnings&&ie.log.warn(`Module name: ${r} vs ${s.name}`)())}destroy(){}setProps(t){for(let e of Object.keys(t)){let n=e,r=t[n]||{},s=this.modules[n];if(!s)this.options.disableWarnings||ie.log.warn(`Module ${e} not found`)();else{let o=this.moduleUniforms[n],a=this.moduleBindings[n],c=s.getUniforms?.(r,o)||r,{uniforms:h,bindings:l}=Ei(c,s.uniformTypes);this.moduleUniforms[n]=Li(o,h,s.uniformTypes),this.moduleBindings[n]={...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,n]of Object.entries(this.moduleUniforms))for(let[r,s]of Object.entries(n))t[`${e}.${r}`]={type:this.modules[e].uniformTypes?.[r],value:String(s)};return t}_addModule(t){let e=t.name;this.moduleUniforms[e]=Li({},t.defaultUniforms||{},t.uniformTypes),this.moduleBindings[e]={}}};function Li(i={},t={},e={}){let n={...i};for(let[r,s]of Object.entries(t))s!==void 0&&(n[r]=Ce(i[r],s,e[r]));return n}function Ce(i,t,e){if(!e||typeof e=="string")return Rt(t);if(Array.isArray(e)){if(Oe(t)||!Array.isArray(t))return Rt(t);let o=Array.isArray(i)&&!Oe(i)?[...i]:[],a=o.slice();for(let c=0;c<t.length;c++){let h=t[c];h!==void 0&&(a[c]=Ce(o[c],h,e[0]))}return a}if(!Re(t))return Rt(t);let n=e,r=Re(i)?i:{},s={...r};for(let[o,a]of Object.entries(t))a!==void 0&&(s[o]=Ce(r[o],a,n[o]));return s}function Rt(i){return ArrayBuffer.isView(i)?Array.prototype.slice.call(i):Array.isArray(i)?Oe(i)?i.slice():i.map(e=>e===void 0?void 0:Rt(e)):Re(i)?Object.fromEntries(Object.entries(i).map(([t,e])=>[t,e===void 0?void 0:Rt(e)])):i}function Oe(i){return ArrayBuffer.isView(i)||Array.isArray(i)&&(i.length===0||typeof i[0]=="number")}function Re(i){return Boolean(i)&&typeof i=="object"&&!Array.isArray(i)&&!ArrayBuffer.isView(i)}function br(i){return Boolean(i?.dependencies)}var R=k(U(),1);var Dt=k(U(),1);var ke={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function kt(i){return i?Array.isArray(i)?i[0]??null:i:null}function Oi(i){let{dimension:t,data:e}=i;if(!e)return null;switch(t){case"1d":{let n=kt(e);if(!n)return null;let{width:r}=Nt(n);return{width:r,height:1}}case"2d":{let n=kt(e);return n?Nt(n):null}case"3d":case"2d-array":{if(!Array.isArray(e)||e.length===0)return null;let n=kt(e[0]);return n?Nt(n):null}case"cube":{let n=Object.keys(e)[0]??null;if(!n)return null;let r=e[n],s=kt(r);return s?Nt(s):null}case"cube-array":{if(!Array.isArray(e)||e.length===0)return null;let n=e[0],r=Object.keys(n)[0]??null;if(!r)return null;let s=kt(n[r]);return s?Nt(s):null}default:return null}}function Nt(i){if((0,Dt.isExternalImage)(i))return(0,Dt.getExternalImageSize)(i);if(typeof i=="object"&&"width"in i&&"height"in i)return{width:i.width,height:i.height};throw new Error("Unsupported mip-level data")}function yr(i){return typeof i=="object"&&i!==null&&"data"in i&&"width"in i&&"height"in i}function Mr(i){return ArrayBuffer.isView(i)}function Ne(i){let{textureFormat:t,format:e}=i;if(t&&e&&t!==e)throw new Error(`Conflicting texture formats "${t}" and "${e}" provided for the same mip level`);return t??e}function Ri(i){let t=ke[i];if(t===void 0)throw new Error(`Invalid cube face: ${i}`);return t}function _r(i,t){return 6*i+Ri(t)}function De(i){throw new Error("setTexture1DData not supported in WebGL.")}function Ir(i){return Array.isArray(i)?i:[i]}function dt(i,t,e,n){let r=Ir(t),s=i,o=[];for(let a=0;a<r.length;a++){let c=r[a];if((0,Dt.isExternalImage)(c))o.push({type:"external-image",image:c,z:s,mipLevel:a});else if(yr(c))o.push({type:"texture-data",data:c,textureFormat:Ne(c),z:s,mipLevel:a});else if(Mr(c)&&e)o.push({type:"texture-data",data:{data:c,width:Math.max(1,e.width>>a),height:Math.max(1,e.height>>a),...n?{format:n}:{}},textureFormat:n,z:s,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return o}function Fe(i){let t=[];for(let e=0;e<i.length;e++)t.push(...dt(e,i[e]));return t}function Be(i){let t=[];for(let e=0;e<i.length;e++)t.push(...dt(e,i[e]));return t}function ze(i){let t=[];for(let[e,n]of Object.entries(i)){let r=Ri(e);t.push(...dt(r,n))}return t}function je(i){let t=[];return i.forEach((e,n)=>{for(let[r,s]of Object.entries(e)){let o=_r(n,r);t.push(...dt(o,s))}}),t}var Ge=class{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;resolveReady=()=>{};rejectReady=()=>{};get texture(){if(!this._texture)throw new Error("Texture not initialized yet");return this._texture}get sampler(){if(!this._sampler)throw new Error("Sampler not initialized yet");return this._sampler}get view(){if(!this._view)throw new Error("View not initialized yet");return this._view}get[Symbol.toStringTag](){return"DynamicTexture"}toString(){let t=this._texture?.width??this.props.width??"?",e=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${t}x${e}px:(${this.isReady?"ready":"loading..."})`}constructor(t,e){this.device=t;let n=S("dynamic-texture"),r=e;this.props={...Ge.defaultProps,id:n,...e,data:null},this.id=this.props.id,this.ready=new Promise((s,o)=>{this.resolveReady=s,this.rejectReady=o}),this.initAsync(r)}async initAsync(t){try{let e=await this._loadAllData(t);this._checkNotDestroyed();let n=e.data?vr({...e,width:t.width,height:t.height,format:t.format}):[],r="format"in t&&t.format!==void 0,s="usage"in t&&t.usage!==void 0,a=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};let u=Oi(e);return u||{width:this.props.width||1,height:this.props.height||1}})();if(!a||a.width<=0||a.height<=0)throw new Error(`${this} size could not be determined or was zero`);let c=wr(this.device,n,a,{format:r?t.format:void 0}),h=c.format??this.props.format,l={...this.props,...a,format:h,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(h)&&!s&&(l.usage=R.Texture.SAMPLE|R.Texture.COPY_DST);let d=this.props.mipmaps&&!c.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(h);if(this.device.type==="webgpu"&&d){let u=this.props.dimension==="3d"?R.Texture.SAMPLE|R.Texture.STORAGE|R.Texture.COPY_DST|R.Texture.COPY_SRC:R.Texture.SAMPLE|R.Texture.RENDER|R.Texture.COPY_DST|R.Texture.COPY_SRC;l.usage|=u}let f=this.device.getMipLevelCount(l.width,l.height),p=c.hasExplicitMipChain?c.mipLevels:this.props.mipLevels==="auto"?f:Math.max(1,Math.min(f,this.props.mipLevels??1)),g={...l,mipLevels:p};this._texture=this.device.createTexture(g),this._sampler=this.texture.sampler,this._view=this.texture.view,c.subresources.length&&this._setTextureSubresources(c.subresources),this.props.mipmaps&&!c.hasExplicitMipChain&&!d&&R.log.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),d&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),R.log.info(0,`${this} created`)()}catch(e){let n=e instanceof Error?e:new Error(String(e));this.rejectReady(n)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?this.texture.generateMipmapsWebGL():this.device.type==="webgpu"?this.device.generateMipmapsWebGPU(this.texture):R.log.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(t={}){this._checkReady();let e=t instanceof R.Sampler?t:this.device.createSampler(t);this.texture.setSampler(e),this._sampler=e}async readBuffer(t={}){this.isReady||await this.ready;let e=t.width??this.texture.width,n=t.height??this.texture.height,r=t.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:e,height:n,depthOrArrayLayers:r}),o=this.device.createBuffer({byteLength:s.byteLength,usage:R.Buffer.COPY_DST|R.Buffer.MAP_READ});this.texture.readBuffer({...t,width:e,height:n,depthOrArrayLayers:r},o);let a=this.device.createFence();return await a.signaled,a.destroy(),o}async readAsync(t={}){this.isReady||await this.ready;let e=t.width??this.texture.width,n=t.height??this.texture.height,r=t.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:e,height:n,depthOrArrayLayers:r}),o=await this.readBuffer(t),a=await o.readAsync(0,s.byteLength);return o.destroy(),a.buffer}resize(t){if(this._checkReady(),t.width===this.texture.width&&t.height===this.texture.height)return!1;let e=this.texture;return this._texture=e.clone(t),this._sampler=this.texture.sampler,this._view=this.texture.view,e.destroy(),R.log.info(`${this} resized`),!0}getCubeFaceIndex(t){let e=ke[t];if(e===void 0)throw new Error(`Invalid cube face: ${t}`);return e}getCubeArrayFaceIndex(t,e){return 6*t+this.getCubeFaceIndex(e)}setTexture1DData(t){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);let e=De(t);this._setTextureSubresources(e)}setTexture2DData(t,e=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let n=dt(e,t);this._setTextureSubresources(n)}setTexture3DData(t){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let e=Fe(t);this._setTextureSubresources(e)}setTextureArrayData(t){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let e=Be(t);this._setTextureSubresources(e)}setTextureCubeData(t){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let e=ze(t);this._setTextureSubresources(e)}setTextureCubeArrayData(t){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let e=je(t);this._setTextureSubresources(e)}_setTextureSubresources(t){for(let e of t){let{z:n,mipLevel:r}=e;switch(e.type){case"external-image":let{image:s,flipY:o}=e;this.texture.copyExternalImage({image:s,z:n,mipLevel:r,flipY:o});break;case"texture-data":let{data:a,textureFormat:c}=e;if(c&&c!==this.texture.format)throw new Error(`${this} mip level ${r} uses format "${c}" but texture format is "${this.texture.format}"`);this.texture.writeData(a.data,{x:0,y:0,z:n,width:a.width,height:a.height,depthOrArrayLayers:1,mipLevel:r});break;default:throw new Error("Unsupported 2D mip-level payload")}}}async _loadAllData(t){let e=await Ue(t.data);return{dimension:t.dimension??"2d",data:e??null}}_checkNotDestroyed(){this.destroyed&&R.log.warn(`${this} already destroyed`)}_checkReady(){this.isReady||R.log.warn(`${this} Cannot perform this operation before ready`)}},B=Ge;Y(B,"defaultProps",{...R.Texture.defaultProps,dimension:"2d",data:null,mipmaps:!1});function vr(i){if(!i.data)return[];let t=i.width&&i.height?{width:i.width,height:i.height}:void 0,e="format"in i?i.format:void 0;switch(i.dimension){case"1d":return De(i.data);case"2d":return dt(0,i.data,t,e);case"3d":return Fe(i.data);case"2d-array":return Be(i.data);case"cube":return ze(i.data);case"cube-array":return je(i.data);default:throw new Error(`Unhandled dimension ${i.dimension}`)}}function wr(i,t,e,n){if(t.length===0)return{subresources:t,mipLevels:1,format:n.format,hasExplicitMipChain:!1};let r=new Map;for(let l of t){let d=r.get(l.z)??[];d.push(l),r.set(l.z,d)}let s=t.some(l=>l.mipLevel>0),o=n.format,a=Number.POSITIVE_INFINITY,c=[];for(let[l,d]of r){let f=[...d].sort((I,m)=>I.mipLevel-m.mipLevel),p=f[0];if(!p||p.mipLevel!==0)throw new Error(`DynamicTexture: slice ${l} is missing mip level 0`);let g=Ni(i,p);if(g.width!==e.width||g.height!==e.height)throw new Error(`DynamicTexture: slice ${l} base level dimensions ${g.width}x${g.height} do not match expected ${e.width}x${e.height}`);let u=ki(p);if(u){if(o&&o!==u)throw new Error(`DynamicTexture: slice ${l} base level format "${u}" does not match texture format "${o}"`);o=u}let b=o&&i.isTextureFormatCompressed(o)?Ar(i,g.width,g.height,o):i.getMipLevelCount(g.width,g.height),M=0;for(let I=0;I<f.length;I++){let m=f[I];if(!m||m.mipLevel!==I||I>=b)break;let x=Ni(i,m),y=Math.max(1,g.width>>I),_=Math.max(1,g.height>>I);if(x.width!==y||x.height!==_)break;let T=ki(m);if(T&&(o||(o=T),T!==o))break;M++,c.push(m)}a=Math.min(a,M)}let h=Number.isFinite(a)?Math.max(1,a):1;return{subresources:c.filter(l=>l.mipLevel<h),mipLevels:h,format:o,hasExplicitMipChain:s}}function ki(i){if(i.type==="texture-data")return i.textureFormat??Ne(i.data)}function Ni(i,t){switch(t.type){case"external-image":return i.getExternalImageSize(t.image);case"texture-data":return{width:t.data.width,height:t.data.height};default:throw new Error("Unsupported texture subresource")}}function Ar(i,t,e,n){let{blockWidth:r=1,blockHeight:s=1}=i.getTextureFormatInfo(n),o=1;for(let a=1;;a++){let c=Math.max(1,t>>a),h=Math.max(1,e>>a);if(c<r||h<s)break;o++}return o}async function Ue(i){if(i=await i,Array.isArray(i))return await Promise.all(i.map(Ue));if(i&&typeof i=="object"&&i.constructor===Object){let t=i,e=await Promise.all(Object.values(t).map(Ue)),n=Object.keys(t),r={};for(let s=0;s<n.length;s++)r[n[s]]=e[s];return r}return i}var rt=2,Tr=1e4,Di="render pipeline initialization failed",$e=class{device;id;source;vs;fs;pipelineFactory;shaderFactory;userData={};parameters;topology;bufferLayout;isInstanced=void 0;instanceCount=0;vertexCount;indexBuffer=null;bufferAttributes={};constantAttributes={};bindings={};vertexArray;transformFeedback=null;pipeline;shaderInputs;material=null;_uniformStore;_attributeInfos={};_gpuGeometry=null;props;_pipelineNeedsUpdate="newly created";_needsRedraw="initializing";_destroyed=!1;_lastDrawTimestamp=-1;_bindingTable=[];get[Symbol.toStringTag](){return"Model"}toString(){return`Model(${this.id})`}constructor(t,e){this.props={...$e.defaultProps,...e},e=this.props,this.id=e.id||S("model"),this.device=t,Object.assign(this.userData,e.userData),this.material=e.material||null;let n=Object.fromEntries(this.props.modules?.map(c=>[c.name,c])||[]),r=e.shaderInputs||new G(n,{disableWarnings:this.props.disableWarnings});this.setShaderInputs(r);let s=Pr(t),o=(this.props.modules?.length>0?this.props.modules:this.shaderInputs?.getModules())||[];if(this.props.shaderLayout=gt(this.props.shaderLayout,o)||null,this.device.type==="webgpu"&&this.props.source){let{source:c,getUniforms:h,bindingTable:l}=this.props.shaderAssembler.assembleWGSLShader({platformInfo:s,...this.props,modules:o});this.source=c,this._getModuleUniforms=h,this._bindingTable=l;let d=t.getShaderLayout?.(this.source);this.props.shaderLayout=gt(this.props.shaderLayout||d||null,o)||null}else{let{vs:c,fs:h,getUniforms:l}=this.props.shaderAssembler.assembleGLSLShaderPair({platformInfo:s,...this.props,modules:o});this.vs=c,this.fs=h,this._getModuleUniforms=l,this._bindingTable=[]}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||w.PipelineFactory.getDefaultPipelineFactory(this.device),this.shaderFactory=e.shaderFactory||w.ShaderFactory.getDefaultShaderFactory(this.device),this.pipeline=this._updatePipeline(),this.vertexArray=t.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),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.transformFeedback&&(this.transformFeedback=e.transformFeedback)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&this.pipeline.fs!==this.pipeline.vs&&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}getBindingDebugTable(){return this._bindingTable}predraw(){this.updateShaderInputs(),this.pipeline=this._updatePipeline()}draw(t){let e=this._areBindingsLoading();if(e)return w.log.info(rt,`>>> DRAWING ABORTED ${this.id}: ${e} not loaded`)(),!1;try{t.pushDebugGroup(`${this}.predraw(${t})`),this.predraw()}finally{t.popDebugGroup()}let n,r=this.pipeline.isErrored;try{if(t.pushDebugGroup(`${this}.draw(${t})`),this._logDrawCallStart(),this.pipeline=this._updatePipeline(),r=this.pipeline.isErrored,r)w.log.info(rt,`>>> DRAWING ABORTED ${this.id}: ${Di}`)(),n=!1;else{let s=this._getBindings(),o=this._getBindGroups(),{indexBuffer:a}=this.vertexArray,c=a?a.byteLength/(a.indexType==="uint32"?4:2):void 0;n=this.pipeline.draw({renderPass:t,vertexArray:this.vertexArray,isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.instanceCount,indexCount:c,transformFeedback:this.transformFeedback||void 0,bindings:s,bindGroups:o,_bindGroupCacheKeys:this._getBindGroupCacheKeys(),uniforms:this.props.uniforms,parameters:this.parameters,topology:this.topology})}}finally{t.popDebugGroup(),this._logDrawCallEnd()}return this._logFramebuffer(t),n?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):r?this._needsRedraw=Di:this._needsRedraw="waiting for resource initialization",n}setGeometry(t){this._gpuGeometry?.destroy();let e=t&&yi(this.device,t);if(e){this.setTopology(e.topology||"triangle-list");let n=new pt(this.bufferLayout);this.bufferLayout=n.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 pt(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({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry)}setParameters(t){ee(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 w.UniformStore(this.device,this.shaderInputs.modules);for(let[e,n]of Object.entries(this.shaderInputs.modules))if(xt(n)&&!this.material?.ownsModule(e)){let r=this._uniformStore.getManagedUniformBuffer(e);this.bindings[`${e}Uniforms`]=r}this.setNeedsRedraw("shaderInputs")}setMaterial(t){this.material=t,this.setNeedsRedraw("material")}updateShaderInputs(){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues()),this.setBindings(this._getNonMaterialBindings(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 n=e?.disableWarnings??this.props.disableWarnings;t.indices&&w.log.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(),this.bufferLayout=Ti(this.pipeline.shaderLayout,this.bufferLayout);let r=new pt(this.bufferLayout);for(let[s,o]of Object.entries(t)){let a=r.getBufferLayout(s);if(!a){n||w.log.warn(`Model(${this.id}): Missing layout for buffer "${s}".`)();continue}let c=r.getAttributeNamesForBuffer(a),h=!1;for(let l of c){let d=this._attributeInfos[l];if(d){let f=this.device.type==="webgpu"?r.getBufferIndex(d.bufferName):d.location;this.vertexArray.setBuffer(f,o),h=!0}}!h&&!n&&w.log.warn(`Model(${this.id}): Ignoring buffer "${o.id}" for unknown attribute "${s}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(t,e){for(let[n,r]of Object.entries(t)){let s=this._attributeInfos[n];s?this.vertexArray.setConstantWebGL(s.location,r):(e?.disableWarnings??this.props.disableWarnings)||w.log.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${n}"`)()}this.setNeedsRedraw("constants")}_areBindingsLoading(){for(let t of Object.values(this.bindings))if(t instanceof B&&!t.isReady)return t.id;for(let t of Object.values(this.material?.bindings||{}))if(t instanceof B&&!t.isReady)return t.id;return!1}_getBindings(){let t={};for(let[e,n]of Object.entries(this.bindings))n instanceof B?n.isReady&&(t[e]=n.texture):t[e]=n;return t}_getBindGroups(){let t=this.pipeline?.shaderLayout||this.props.shaderLayout||{bindings:[]},e=t.bindings.length?(0,w.normalizeBindingsByGroup)(t,this._getBindings()):{0:this._getBindings()};if(!this.material)return e;for(let[n,r]of Object.entries(this.material.getBindingsByGroup())){let s=Number(n);e[s]={...e[s]||{},...r}}return e}_getBindGroupCacheKeys(){let t=this.material?.getBindGroupCacheKey(3);return t?{3:t}:{}}_getBindingsUpdateTimestamp(){let t=0;for(let e of Object.values(this.bindings))e instanceof w.TextureView?t=Math.max(t,e.texture.updateTimestamp):e instanceof w.Buffer||e instanceof w.Texture?t=Math.max(t,e.updateTimestamp):e instanceof B?t=e.texture?Math.max(t,e.texture.updateTimestamp):1/0:e instanceof w.Sampler||(t=Math.max(t,e.buffer.updateTimestamp));return Math.max(t,this.material?.getBindingsUpdateTimestamp()||0)}_setGeometryAttributes(t){let e={...t.attributes};for(let[n]of Object.entries(e))!this.pipeline.shaderLayout.attributes.find(r=>r.name===n)&&n!=="positions"&&delete e[n];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&&(w.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),t=this.pipeline.vs,e=this.pipeline.fs),this._pipelineNeedsUpdate=!1;let n=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders}),r=null;this.source?r=n:this.fs&&(r=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,bindings:void 0,bufferLayout:this.bufferLayout,topology:this.topology,parameters:this.parameters,bindGroups:this._getBindGroups(),vs:n,fs:r}),this._attributeInfos=(0,w.getAttributeInfosFromLayouts)(this.pipeline.shaderLayout,this.bufferLayout),t&&this.shaderFactory.release(t),e&&e!==t&&this.shaderFactory.release(e)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let t=w.log.level>3?0:Tr;w.log.level<2||Date.now()-this._lastLogTime<t||(this._lastLogTime=Date.now(),this._logOpen=!0,w.log.group(rt,`>>> DRAWING MODEL ${this.id}`,{collapsed:w.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let t=Mi(this.pipeline.shaderLayout,this.id);w.log.table(rt,t)();let e=this.shaderInputs.getDebugTable();w.log.table(rt,e)();let n=this._getAttributeDebugTable();w.log.table(rt,this._attributeInfos)(),w.log.table(rt,n)(),w.log.groupEnd(rt)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(t){let e=this.device.props.debugFramebuffers;if(this._drawCount++,!e)return;let n=t.props.framebuffer;vi(t,n,{id:n?.id||`${this.id}-framebuffer`,minimap:!0})}_getAttributeDebugTable(){let t={};for(let[e,n]of Object.entries(this._attributeInfos)){let r=this.vertexArray.attributes[n.location];t[n.location]={name:e,type:n.shaderType,values:r?this._getBufferOrConstantValues(r,n.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){let{indexBuffer:e}=this.vertexArray,n=e.indexType==="uint32"?new Uint32Array(e.debugData):new Uint16Array(e.debugData);t.indices={name:"indices",type:e.indexType,values:n.toString()}}return t}_getBufferOrConstantValues(t,e){let n=w.dataTypeDecoder.getTypedArrayConstructor(e);return(t instanceof w.Buffer?new n(t.debugData):t).toString()}_getNonMaterialBindings(t){if(!this.material)return t;let e={};for(let[n,r]of Object.entries(t))this.material.ownsBinding(n)||(e[n]=r);return e}},H=$e;Y(H,"defaultProps",{...w.RenderPipeline.defaultProps,source:void 0,vs:null,fs:null,id:"unnamed",handle:void 0,userData:{},defines:{},modules:[],geometry:null,indexBuffer:null,attributes:{},constantAttributes:{},bindings:{},uniforms:{},varyings:[],isInstanced:void 0,instanceCount:0,vertexCount:0,shaderInputs:void 0,material:void 0,pipelineFactory:void 0,shaderFactory:void 0,transformFeedback:void 0,shaderAssembler:Fi.ShaderAssembler.getDefaultShaderAssembler(),debugShaders:void 0,disableWarnings:void 0});function Pr(i){return{type:i.type,shaderLanguage:i.info.shadingLanguage,shaderLanguageVersion:i.info.shadingLanguageVersion,gpu:i.info.gpu,features:i.features}}var Q=k(U(),1);var Ft=3,bt=class{device;modules;_materialBindingNames;_materialModuleNames;constructor(t,e={}){this.device=t,this.modules=e.modules||[];let n=new G(Object.fromEntries(this.modules.map(r=>[r.name,r])));this._materialBindingNames=Sr(n),this._materialModuleNames=Er(n)}createMaterial(t={}){return new yt(this.device,{...t,factory:this})}getBindingNames(){return Array.from(this._materialBindingNames)}ownsBinding(t){if(this._materialBindingNames.has(t))return!0;let e=Ve(t);return e?this._materialModuleNames.has(e):!1}ownsModule(t){return this._materialModuleNames.has(t)}getBindingsByGroup(t){return Object.keys(t).length>0?{[Ft]:t}:{}}};function Ve(i){return i.endsWith("Uniforms")?i.slice(0,-8):null}function Sr(i){let t=new Set;for(let e of Object.values(i.modules))for(let n of e.bindingLayout||[])n.group===Ft&&t.add(n.name);return t}function Er(i){let t=new Set;for(let e of Object.values(i.modules))e.name&&e.bindingLayout?.some(n=>n.group===Ft&&n.name===e.name)&&t.add(e.name);return t}var yt=class{id;device;factory;shaderInputs;bindings={};_uniformStore;_bindGroupCacheToken={};constructor(t,e={}){this.id=e.id||S("material"),this.device=t,this.factory=e.factory||new bt(t,{modules:e.modules||e.shaderInputs?.getModules()||[]});let n=Object.fromEntries((e.shaderInputs?.getModules()||this.factory.modules).map(r=>[r.name,r]));this.shaderInputs=e.shaderInputs||new G(n),this._uniformStore=new Q.UniformStore(this.device,this.shaderInputs.modules);for(let[r,s]of Object.entries(this.shaderInputs.modules))if(this.ownsModule(r)&&xt(s)){let o=this._uniformStore.getManagedUniformBuffer(r);this.bindings[`${r}Uniforms`]=o}this.updateShaderInputs(),e.bindings&&this._replaceOwnedBindings(e.bindings)}destroy(){this._uniformStore.destroy()}clone(t={}){let e=this.factory.createMaterial({id:t.id,shaderInputs:t.shaderInputs,bindings:{...this.getResourceBindings(),...t.bindings}});return t.shaderInputs||e.setProps(this.shaderInputs.getUniformValues()),t.moduleProps&&e.setProps(t.moduleProps),e}ownsBinding(t){return this.factory.ownsBinding(t)}ownsModule(t){return this.factory.ownsModule(t)}setProps(t){this.shaderInputs.setProps(t),this.up