@hology/core 0.0.242 → 0.0.244

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.
@@ -1,4 +1,4 @@
1
- import*as e from"three";import{GpuVfxScheduler as t}from"./gpu-vfx-scheduler.js";import{calculateGpuSpriteOptionalStateLayout as s,GPU_SPRITE_BASE_COMMAND_BYTES as i,GPU_SPRITE_EMITTER_BYTES as r,GPU_SPRITE_TRANSFORM_COMMAND_BYTES as n,GpuSpriteRuntime as a}from"./gpu-sprite-runtime.js";import{GpuSpriteTemplateCache as l,instantiateGpuSpriteTemplate as h}from"./gpu-sprite-template.js";export class GpuSpriteSchedulerRuntime{constructor(t,s,i,r,n,a,l,h,c,u,o){this.maximumInstances=n,this.emittersPerInstance=a,this.instanceDuration=l,this.maximumParticleLife=h,this.emitterCapacities=c,this.emitterPositionOffsets=u,this.inputBindings=o,this.activePages=new Set,this.positionScratch=new e.Vector3,this.activePagesDirty=!1,this.runtime=t,this.scheduler=s,this.compatibility=i,this.reasons=r,this.activeBySlot=new Array(n).fill(null),this.emitterIndexScratch=new Array(a).fill(0),this.instanceParticleCapacity=c.reduce((e,t)=>e+t,0),this.stoppingDeadlines=new Float64Array(n),this.stoppingDeadlines.fill(Number.POSITIVE_INFINITY);for(let e=0;e<t.emitters.length;e++)t.setEmitterActive(e,!1);t.setActivePages([])}static async create(c){const u=Math.max(1,Math.floor(c.maximumInstances)),o=(await(c.templateCache??new l).resolve(c.asset,{assets:c.assets,renderClassCache:c.cache,resolveCustomMaterial:c.resolveCustomMaterial,revision:c.templateRevision})).template;if(null==o)return null;const m=o.particleCapacity,d=Math.max(1,Math.floor(c.particlePageSize??m)),p=Math.ceil(m/d)*d*u,f=m*u,I=u*o.emitters.length,P=o.renderClasses.some(e=>null!=e.meshVertices),g=o.renderClasses.some(e=>!0===e.localSpace&&null==e.trail),S=I*(o.emitters.some(e=>!0===e.localSpace&&null!=o.renderClasses[e.renderClass??0]?.trail)?n:i),y=P||o.emitters.some(e=>1!==e.meshScaleStart.x||1!==e.meshScaleStart.y||1!==e.meshScaleStart.z||1!==e.meshScaleEnd.x||1!==e.meshScaleEnd.y||1!==e.meshScaleEnd.z),v=o.emitters.reduce((e,t)=>{const s=o.renderClasses[t.renderClass??0]?.trail;return e+(null==s?0:t.capacity*(s.historyLength+1))},0)*u,x=s({capacity:p,particleTransforms:y,vortex:o.emitters.some(e=>e.hasVortex),disperse:o.emitters.some(e=>e.hasDisperse),trailHistoryEntries:v}),C=P?16*I*4+o.renderClasses.reduce((e,t)=>e+(t.meshVertices?.byteLength??0),0):0;if(16*p*4+4*f+4*p+4*p*4+I*r+Math.max(i,S)+160+16*o.renderClasses.length*2+C+x.bytes+(g&&!P?16*I*4:0)>(c.maximumStorageBytes??Number.POSITIVE_INFINITY))return null;if(null!=c.device){const e=c.device.limits.maxStorageBufferBindingSize;if([16*p*4,4*f,4*p,4*p*4,I*r,Math.max(i,S),...P||g?[16*I*4]:[],...x.bytes>0?[x.bytes]:[]].some(t=>t>e))return null;if(7+(x.bytes>0?1:0)>c.device.limits.maxStorageBuffersPerShaderStage)return null}const E=new e.Vector3,D=h(o,new Array(u).fill(E)),T=new a(D,o.renderClasses,void 0,{pageSize:d,capacity:p,aliveCountReadback:c.aliveCountReadback});return new GpuSpriteSchedulerRuntime(T,new t({pageSize:d,maximumParticles:p}),o.compatibility,o.reasons,u,o.emitters.length,o.duration,o.emitters.reduce((e,t)=>Math.max(e,t.life),0),o.emitters.map(e=>e.capacity),o.emitters.map(e=>e.position.clone()),o.inputBindings)}spawn(e){const t=this.scheduler.createInstance({particleCapacity:this.instanceParticleCapacity,duration:this.instanceDuration});if(null==t)return null;const s=this.scheduler.arena.get(t).pages;if(0===s.length)return this.scheduler.destroyInstance(t),null;const i={handle:t,pages:s};this.activeBySlot[t.slot]=i;for(const e of s)this.activePages.add(e);this.activePagesDirty=!0;for(let e=0;e<this.emittersPerInstance;e++)this.emitterIndexScratch[e]=t.slot*this.emittersPerInstance+e;this.runtime.mapParticlePages(s,this.emitterIndexScratch,this.emitterCapacities);for(let s=0;s<this.emittersPerInstance;s++){const i=t.slot*this.emittersPerInstance+s;this.positionScratch.copy(this.emitterPositionOffsets[s]),!0!==this.runtime.emitters[i].localSpace&&null==this.runtime.emitters[i].parentEmitter&&this.positionScratch.add(e),this.runtime.queueEmitterState(i,this.positionScratch,!0,!0)}return this.scheduler.play(t),i}destroy(e){if(null==this.scheduler.getInstance(e.handle))return!1;for(let t=0;t<this.emittersPerInstance;t++){const s=e.handle.slot*this.emittersPerInstance+t;this.runtime.queueEmitterState(s,this.runtime.emitters[s].position,!1)}for(const t of e.pages)this.activePages.delete(t);return this.activePagesDirty=!0,this.activeBySlot[e.handle.slot]=null,this.scheduler.destroyInstance(e.handle)}setPosition(e,t){if(null==this.scheduler.getInstance(e.handle))return!1;for(let s=0;s<this.emittersPerInstance;s++){const i=e.handle.slot*this.emittersPerInstance+s;!0!==this.runtime.emitters[i].localSpace&&null==this.runtime.emitters[i].parentEmitter&&(this.positionScratch.copy(t).add(this.emitterPositionOffsets[s]),this.runtime.queueEmitterState(i,this.positionScratch,!0))}return!0}setTransform(e,t){if(null==this.scheduler.getInstance(e.handle))return!1;for(let s=0;s<this.emittersPerInstance;s++)this.runtime.setEmitterTransform(e.handle.slot*this.emittersPerInstance+s,t);return!0}pause(e){if(!this.scheduler.pause(e.handle))return!1;for(let t=0;t<this.emittersPerInstance;t++)this.runtime.queueEmitterPaused(e.handle.slot*this.emittersPerInstance+t,!0);return!0}play(e){if(!this.scheduler.play(e.handle))return!1;for(let t=0;t<this.emittersPerInstance;t++)this.runtime.queueEmitterPaused(e.handle.slot*this.emittersPerInstance+t,!1);return!0}setTimescale(e,t){if(!this.scheduler.setTimescale(e.handle,t))return!1;for(let s=0;s<this.emittersPerInstance;s++)this.runtime.queueEmitterTimescale(e.handle.slot*this.emittersPerInstance+s,t);return!0}setInput(e,t,s){if(null==this.scheduler.getInstance(e.handle))return!1;let i=!1;for(const r of this.inputBindings){if(r.inputId!==t)continue;const n=e.handle.slot*this.emittersPerInstance+r.emitterIndex;i=this.runtime.setEmitterBoundValue(n,r,s)||i}return i&&this.scheduler.setDuration(e.handle,this.calculateInstanceDuration(e.handle.slot)),i}calculateInstanceDuration(e){let t=0;for(let s=0;s<this.emittersPerInstance;s++){const i=this.runtime.emitters[e*this.emittersPerInstance+s],r="continuous"===i.rate.type?i.rate.duration<0?Number.POSITIVE_INFINITY:i.rate.delay+i.rate.duration+i.life:i.rate.delay+i.life;t=Math.max(t,r)}return t}restart(e){if(!this.scheduler.restart(e.handle))return!1;this.stoppingDeadlines[e.handle.slot]=Number.POSITIVE_INFINITY;for(let t=0;t<this.emittersPerInstance;t++){const s=e.handle.slot*this.emittersPerInstance+t;this.runtime.queueEmitterState(s,this.runtime.emitters[s].position,!0,!0)}return!0}stop(e,t){const s=this.scheduler.getInstance(e.handle);if(null==s||!this.scheduler.stop(e.handle))return!1;const i=null==t?this.maximumParticleLife:Math.max(0,t);this.stoppingDeadlines[e.handle.slot]=s.elapsedTime+i;for(let s=0;s<this.emittersPerInstance;s++)this.runtime.queueEmitterStop(e.handle.slot*this.emittersPerInstance+s,t);return!0}update(e){this.scheduler.update(e),this.runtime.update(e);for(const e of this.activeBySlot){if(null==e)continue;const t=this.scheduler.getInstance(e.handle);null!=t&&((!1===t.playing&&t.elapsedTime>=this.instanceDuration||t.stopping&&t.elapsedTime>=this.stoppingDeadlines[e.handle.slot])&&this.destroy(e))}this.flushActivePages()}flushActivePages(){this.activePagesDirty&&(this.runtime.setActivePages(this.activePages),this.activePagesDirty=!1)}getStats(){return{scheduler:this.scheduler.getStats(),particles:this.runtime.getStats()}}dispose(){this.runtime.dispose();for(const e of this.activeBySlot)null!=e&&this.scheduler.destroyInstance(e.handle);this.activeBySlot.fill(null)}}/*
1
+ import*as e from"three";import{GpuVfxScheduler as t}from"./gpu-vfx-scheduler.js";import{calculateGpuSpriteOptionalStateLayout as s,GPU_SPRITE_BASE_COMMAND_BYTES as i,GPU_SPRITE_EMITTER_BYTES as r,GPU_SPRITE_TRANSFORM_COMMAND_BYTES as n,GpuSpriteRuntime as a}from"./gpu-sprite-runtime.js";import{GpuSpriteTemplateCache as l,instantiateGpuSpriteTemplate as h}from"./gpu-sprite-template.js";export class GpuSpriteSchedulerRuntime{constructor(t,s,i,r,n,a,l,h,c,o,u){this.maximumInstances=n,this.emittersPerInstance=a,this.instanceDuration=l,this.maximumParticleLife=h,this.emitterCapacities=c,this.emitterPositionOffsets=o,this.inputBindings=u,this.activePages=new Set,this.positionScratch=new e.Vector3,this.activePagesDirty=!1,this.runtime=t,this.scheduler=s,this.compatibility=i,this.reasons=r,this.activeBySlot=new Array(n).fill(null),this.emitterIndexScratch=new Array(a).fill(0),this.instanceParticleCapacity=c.reduce((e,t)=>e+t,0),this.stoppingDeadlines=new Float64Array(n),this.stoppingDeadlines.fill(Number.POSITIVE_INFINITY);for(let e=0;e<t.emitters.length;e++)t.setEmitterActive(e,!1);t.setActivePages([])}static async create(c){const o=Math.max(1,Math.floor(c.maximumInstances)),u=(await(c.templateCache??new l).resolve(c.asset,{assets:c.assets,renderClassCache:c.cache,resolveCustomMaterial:c.resolveCustomMaterial,revision:c.templateRevision})).template;if(null==u)return null;const m=u.particleCapacity,d=Math.max(1,Math.floor(c.particlePageSize??m)),p=Math.ceil(m/d)*d*o,f=m*o,I=o*u.emitters.length,S=u.renderClasses.some(e=>null!=e.meshVertices),P=u.renderClasses.some(e=>!0===e.localSpace&&null==e.trail),g=I*(u.emitters.some(e=>!0===e.localSpace&&null!=u.renderClasses[e.renderClass??0]?.trail)?n:i),y=S||u.emitters.some(e=>1!==e.meshScaleStart.x||1!==e.meshScaleStart.y||1!==e.meshScaleStart.z||1!==e.meshScaleEnd.x||1!==e.meshScaleEnd.y||1!==e.meshScaleEnd.z),v=u.emitters.reduce((e,t)=>{const s=u.renderClasses[t.renderClass??0]?.trail;return e+(null==s?0:t.capacity*(s.historyLength+1))},0)*o,x=s({capacity:p,particleTransforms:y,vortex:u.emitters.some(e=>e.hasVortex),disperse:u.emitters.some(e=>e.hasDisperse),trailHistoryEntries:v}),E=S?16*I*4+u.renderClasses.reduce((e,t)=>e+(t.meshVertices?.byteLength??0),0):0;if(16*p*4+4*f+4*p+4*p*4+I*r+Math.max(i,g)+160+16*u.renderClasses.length*2+E+x.bytes+(P&&!S?16*I*4:0)>(c.maximumStorageBytes??Number.POSITIVE_INFINITY))return null;if(null!=c.device){const e=c.device.limits.maxStorageBufferBindingSize;if([16*p*4,4*f,4*p,4*p*4,I*r,Math.max(i,g),...S||P?[16*I*4]:[],...x.bytes>0?[x.bytes]:[]].some(t=>t>e))return null;if(7+(x.bytes>0?1:0)>c.device.limits.maxStorageBuffersPerShaderStage)return null}const C=new e.Vector3,D=h(u,new Array(o).fill(C)),T=new a(D,u.renderClasses,void 0,{pageSize:d,capacity:p,aliveCountReadback:c.aliveCountReadback});return new GpuSpriteSchedulerRuntime(T,new t({pageSize:d,maximumParticles:p}),u.compatibility,u.reasons,o,u.emitters.length,u.duration,u.emitters.reduce((e,t)=>Math.max(e,t.life),0),u.emitters.map(e=>e.capacity),u.emitters.map(e=>e.position.clone()),u.inputBindings)}spawn(e){const t=this.scheduler.createInstance({particleCapacity:this.instanceParticleCapacity,duration:this.instanceDuration});if(null==t)return null;const s=this.scheduler.arena.get(t).pages;if(0===s.length)return this.scheduler.destroyInstance(t),null;const i={handle:t,pages:s};this.activeBySlot[t.slot]=i;for(const e of s)this.activePages.add(e);this.activePagesDirty=!0;for(let e=0;e<this.emittersPerInstance;e++)this.emitterIndexScratch[e]=t.slot*this.emittersPerInstance+e;this.runtime.mapParticlePages(s,this.emitterIndexScratch,this.emitterCapacities);for(let s=0;s<this.emittersPerInstance;s++){const i=t.slot*this.emittersPerInstance+s;this.positionScratch.copy(this.emitterPositionOffsets[s]),!0!==this.runtime.emitters[i].localSpace&&null==this.runtime.emitters[i].parentEmitter&&this.positionScratch.add(e),this.runtime.queueEmitterState(i,this.positionScratch,!0,!0)}return this.scheduler.play(t),i}destroy(e){if(null==this.scheduler.getInstance(e.handle))return!1;for(let t=0;t<this.emittersPerInstance;t++){const s=e.handle.slot*this.emittersPerInstance+t;this.runtime.queueEmitterState(s,this.runtime.emitters[s].position,!1)}for(const t of e.pages)this.activePages.delete(t);return this.activePagesDirty=!0,this.activeBySlot[e.handle.slot]=null,this.scheduler.destroyInstance(e.handle)}setPosition(e,t){if(null==this.scheduler.getInstance(e.handle))return!1;for(let s=0;s<this.emittersPerInstance;s++){const i=e.handle.slot*this.emittersPerInstance+s;!0!==this.runtime.emitters[i].localSpace&&null==this.runtime.emitters[i].parentEmitter&&(this.positionScratch.copy(t).add(this.emitterPositionOffsets[s]),this.runtime.queueEmitterState(i,this.positionScratch,!0))}return!0}setTransform(e,t){if(null==this.scheduler.getInstance(e.handle))return!1;for(let s=0;s<this.emittersPerInstance;s++){const i=e.handle.slot*this.emittersPerInstance+s,r=this.runtime.emitters[i];this.runtime.setEmitterTransform(i,t),!0!==r.localSpace&&null==r.parentEmitter&&(this.positionScratch.copy(this.emitterPositionOffsets[s]).applyMatrix4(t),this.runtime.queueEmitterState(i,this.positionScratch,!0))}return!0}pause(e){if(!this.scheduler.pause(e.handle))return!1;for(let t=0;t<this.emittersPerInstance;t++)this.runtime.queueEmitterPaused(e.handle.slot*this.emittersPerInstance+t,!0);return!0}play(e){if(!this.scheduler.play(e.handle))return!1;for(let t=0;t<this.emittersPerInstance;t++)this.runtime.queueEmitterPaused(e.handle.slot*this.emittersPerInstance+t,!1);return!0}setTimescale(e,t){if(!this.scheduler.setTimescale(e.handle,t))return!1;for(let s=0;s<this.emittersPerInstance;s++)this.runtime.queueEmitterTimescale(e.handle.slot*this.emittersPerInstance+s,t);return!0}setInput(e,t,s){if(null==this.scheduler.getInstance(e.handle))return!1;let i=!1;for(const r of this.inputBindings){if(r.inputId!==t)continue;const n=e.handle.slot*this.emittersPerInstance+r.emitterIndex;i=this.runtime.setEmitterBoundValue(n,r,s)||i}return i&&this.scheduler.setDuration(e.handle,this.calculateInstanceDuration(e.handle.slot)),i}calculateInstanceDuration(e){let t=0;for(let s=0;s<this.emittersPerInstance;s++){const i=this.runtime.emitters[e*this.emittersPerInstance+s],r="continuous"===i.rate.type?i.rate.duration<0?Number.POSITIVE_INFINITY:i.rate.delay+i.rate.duration+i.life:i.rate.delay+i.life;t=Math.max(t,r)}return t}restart(e){if(!this.scheduler.restart(e.handle))return!1;this.stoppingDeadlines[e.handle.slot]=Number.POSITIVE_INFINITY;for(let t=0;t<this.emittersPerInstance;t++){const s=e.handle.slot*this.emittersPerInstance+t;this.runtime.queueEmitterState(s,this.runtime.emitters[s].position,!0,!0)}return!0}stop(e,t){const s=this.scheduler.getInstance(e.handle);if(null==s||!this.scheduler.stop(e.handle))return!1;const i=null==t?this.maximumParticleLife:Math.max(0,t);this.stoppingDeadlines[e.handle.slot]=s.elapsedTime+i;for(let s=0;s<this.emittersPerInstance;s++)this.runtime.queueEmitterStop(e.handle.slot*this.emittersPerInstance+s,t);return!0}update(e){this.scheduler.update(e),this.runtime.update(e);for(const e of this.activeBySlot){if(null==e)continue;const t=this.scheduler.getInstance(e.handle);null!=t&&((!1===t.playing&&t.elapsedTime>=this.instanceDuration||t.stopping&&t.elapsedTime>=this.stoppingDeadlines[e.handle.slot])&&this.destroy(e))}this.flushActivePages()}flushActivePages(){this.activePagesDirty&&(this.runtime.setActivePages(this.activePages),this.activePagesDirty=!1)}getStats(){return{scheduler:this.scheduler.getStats(),particles:this.runtime.getStats()}}dispose(){this.runtime.dispose();for(const e of this.activeBySlot)null!=e&&this.scheduler.destroyInstance(e.handle);this.activeBySlot.fill(null)}}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,4 +1,4 @@
1
- import*as e from"three";import{calculateGpuSpriteOptionalStateLayout as t,GPU_SPRITE_BASE_COMMAND_BYTES as s,GPU_SPRITE_EMITTER_BYTES as i,GPU_SPRITE_TRANSFORM_COMMAND_BYTES as r,GpuSpriteRuntime as n}from"./gpu-sprite-runtime.js";import{GpuSpriteTemplateCache as l,instantiateGpuSpriteTemplate as a}from"./gpu-sprite-template.js";import{GpuVfxScheduler as o}from"./gpu-vfx-scheduler.js";export class GpuSpriteWorldRuntime{constructor(t,s,i){this.pools=i,this.activeByHandleSlot=[],this.activePages=new Set,this.positionScratch=new e.Vector3,this.activePagesDirty=!1,this.runtime=t,this.scheduler=s,this.templateCount=i.length;for(let e=0;e<t.emitters.length;e++)t.setEmitterActive(e,!1);t.setActivePages([])}static async create(h){if(0===h.templates.length)return null;const c=h.templateCache??new l,u=await Promise.all(h.templates.map(e=>c.resolve(e.asset,{assets:h.assets,renderClassCache:h.renderClassCache,resolveCustomMaterial:h.resolveCustomMaterial,revision:e.revision})));if(u.some(e=>null==e.template))return null;const m=u.map(e=>e.template),p=Math.max(1,Math.floor(h.particlePageSize??256)),d=[],f=new Map,g=[],S=[];let I=0;for(let t=0;t<m.length;t++){const s=m[t],i=h.templates[t],r=Math.max(1,Math.floor(i.maximumInstances)),n=s.renderClasses.map(e=>{let t=f.get(e);return null==t&&(t=d.length,f.set(e,t),d.push(e)),t}),l=g.length,o=new e.Vector3,c=a(s,new Array(r).fill(o));for(const e of c)e.renderClass=n[e.renderClass??0]??0,null!=e.parentEmitter&&(e.parentEmitter+=l),g.push(e);S.push({template:s,baseEmitterIndex:l,maximumInstances:r,freeSlots:Array.from({length:r},(e,t)=>r-t-1),emitterCapacities:s.emitters.map(e=>e.capacity),emitterIndexScratch:new Array(s.emitters.length).fill(0),emitterPositionOffsets:s.emitters.map(e=>e.position.clone()),maximumParticleLife:s.emitters.reduce((e,t)=>Math.max(e,t.life),0)}),I+=Math.ceil(s.particleCapacity/p)*p*r}const y=g.reduce((e,t)=>e+t.capacity,0),v=d.some(e=>null!=e.meshVertices),x=d.some(e=>!0===e.localSpace&&null==e.trail),E=g.some(e=>!0===e.localSpace&&null!=d[e.renderClass??0]?.trail),P=g.length*(E?r:s),C=v||g.some(e=>1!==e.meshScaleStart.x||1!==e.meshScaleStart.y||1!==e.meshScaleStart.z||1!==e.meshScaleEnd.x||1!==e.meshScaleEnd.y||1!==e.meshScaleEnd.z),T=g.reduce((e,t)=>{const s=d[t.renderClass??0]?.trail;return e+(null==s?0:t.capacity*(s.historyLength+1))},0),b=t({capacity:I,particleTransforms:C,vortex:g.some(e=>e.hasVortex),disperse:g.some(e=>e.hasDisperse),collisionEvents:g.some(e=>2===e.childSpawnEvent),trailHistoryEntries:T});if(16*I*4+4*y+4*I+4*I*4+g.length*i+Math.max(s,P)+160+16*d.length*2+d.reduce((e,t)=>e+(t.meshVertices?.byteLength??0),0)+b.bytes+(v||x?16*g.length*4:0)>(h.maximumStorageBytes??Number.POSITIVE_INFINITY))return null;if(null!=h.device){const e=h.device.limits.maxStorageBufferBindingSize;if([16*I*4,4*g.reduce((e,t)=>e+t.capacity,0),4*I,4*I*4,g.length*i,Math.max(s,P),...v||x?[16*g.length*4]:[],...b.bytes>0?[b.bytes]:[]].some(t=>t>e))return null;if(7+(b.bytes>0?1:0)>h.device.limits.maxStorageBuffersPerShaderStage)return null}const B=new n(g,d,void 0,{pageSize:p,capacity:I,aliveCountReadback:h.aliveCountReadback});return new GpuSpriteWorldRuntime(B,new o({pageSize:p,maximumParticles:I}),S)}spawn(e,t){const s=this.pools[e],i=s?.freeSlots.pop();if(null==s||null==i)return null;const r=this.scheduler.createInstance({particleCapacity:s.template.particleCapacity,duration:s.template.duration});if(null==r)return s.freeSlots.push(i),null;const n=this.scheduler.arena.get(r).pages,l={handle:r,templateIndex:e,pages:n,logicalSlot:i,stoppingDeadline:Number.POSITIVE_INFINITY};this.activeByHandleSlot[r.slot]=l;for(const e of n)this.activePages.add(e);this.activePagesDirty=!0;const a=s.template.emitters.length;for(let e=0;e<a;e++){const r=s.baseEmitterIndex+i*a+e;s.emitterIndexScratch[e]=r;const n=this.runtime.emitters[r];this.positionScratch.copy(s.emitterPositionOffsets[e]),!0!==n.localSpace&&null==n.parentEmitter&&this.positionScratch.add(t),this.runtime.queueEmitterState(r,this.positionScratch,!0,!0)}return this.runtime.mapParticlePages(n,s.emitterIndexScratch,s.emitterCapacities),this.scheduler.play(r),l}destroy(e){const t=this.activeByHandleSlot[e.handle.slot];if(null==t||t.handle.generation!==e.handle.generation)return!1;const s=this.pools[t.templateIndex],i=s.template.emitters.length;for(let e=0;e<i;e++){const r=s.baseEmitterIndex+t.logicalSlot*i+e;this.runtime.queueEmitterState(r,this.runtime.emitters[r].position,!1)}for(const e of t.pages)this.activePages.delete(e);return this.activePagesDirty=!0,s.freeSlots.push(t.logicalSlot),this.activeByHandleSlot[e.handle.slot]=null,this.scheduler.destroyInstance(e.handle)}setPosition(e,t){const s=this.resolve(e);if(null==s)return!1;const i=this.pools[s.templateIndex];for(let e=0;e<i.template.emitters.length;e++){const r=this.emitterIndex(s,i,e);!0!==this.runtime.emitters[r].localSpace&&null==this.runtime.emitters[r].parentEmitter&&(this.positionScratch.copy(t).add(i.emitterPositionOffsets[e]),this.runtime.queueEmitterState(r,this.positionScratch,!0))}return!0}setTransform(e,t){const s=this.resolve(e);if(null==s)return!1;const i=this.pools[s.templateIndex];for(let e=0;e<i.template.emitters.length;e++)this.runtime.setEmitterTransform(this.emitterIndex(s,i,e),t);return!0}pause(e){const t=this.resolve(e);return!(null==t||!this.scheduler.pause(t.handle))&&(this.forEachEmitter(t,e=>this.runtime.queueEmitterPaused(e,!0)),!0)}play(e){const t=this.resolve(e);return!(null==t||!this.scheduler.play(t.handle))&&(this.forEachEmitter(t,e=>this.runtime.queueEmitterPaused(e,!1)),!0)}restart(e){const t=this.resolve(e);return!(null==t||!this.scheduler.restart(t.handle))&&(t.stoppingDeadline=Number.POSITIVE_INFINITY,this.forEachEmitter(t,e=>{this.runtime.queueEmitterState(e,this.runtime.emitters[e].position,!0,!0)}),!0)}stop(e,t){const s=this.resolve(e),i=null==s?null:this.scheduler.getInstance(s.handle);if(null==s||null==i||!this.scheduler.stop(s.handle))return!1;const r=this.pools[s.templateIndex];return s.stoppingDeadline=i.elapsedTime+(null==t?r.maximumParticleLife:Math.max(0,t)),this.forEachEmitter(s,e=>this.runtime.queueEmitterStop(e,t)),!0}setTimescale(e,t){const s=this.resolve(e);return!(null==s||!this.scheduler.setTimescale(s.handle,t))&&(this.forEachEmitter(s,e=>this.runtime.queueEmitterTimescale(e,t)),!0)}setInput(e,t,s){const i=this.resolve(e);if(null==i)return!1;const r=this.pools[i.templateIndex];let n=!1;for(const e of r.template.inputBindings)e.inputId===t&&(n=this.runtime.setEmitterBoundValue(this.emitterIndex(i,r,e.emitterIndex),e,s)||n);return n&&this.scheduler.setDuration(i.handle,this.calculateInstanceDuration(i,r)),n}has(e){return null!=this.resolve(e)}update(e){this.scheduler.update(e),this.runtime.update(e);for(const e of this.activeByHandleSlot){if(null==e)continue;const t=this.scheduler.getInstance(e.handle);if(null==t)continue;const s=this.pools[e.templateIndex];(!1===t.playing&&t.elapsedTime>=s.template.duration||t.stopping&&t.elapsedTime>=e.stoppingDeadline)&&this.destroy(e)}this.flushActivePages()}flushActivePages(){this.activePagesDirty&&(this.runtime.setActivePages(this.activePages),this.activePagesDirty=!1)}dispose(){this.runtime.dispose();for(const e of this.activeByHandleSlot)null!=e&&this.scheduler.destroyInstance(e.handle);this.activeByHandleSlot.length=0}resolve(e){const t=this.activeByHandleSlot[e.handle.slot];return null!=t&&t.handle.generation===e.handle.generation&&null!=this.scheduler.getInstance(t.handle)?t:null}emitterIndex(e,t,s){return t.baseEmitterIndex+e.logicalSlot*t.template.emitters.length+s}forEachEmitter(e,t){const s=this.pools[e.templateIndex];for(let i=0;i<s.template.emitters.length;i++)t(this.emitterIndex(e,s,i))}calculateInstanceDuration(e,t){let s=0;for(let i=0;i<t.template.emitters.length;i++){const r=this.runtime.emitters[this.emitterIndex(e,t,i)],n="continuous"===r.rate.type?r.rate.duration<0?Number.POSITIVE_INFINITY:r.rate.delay+r.rate.duration+r.life:r.rate.delay+r.life;s=Math.max(s,n)}return s}}/*
1
+ import*as e from"three";import{calculateGpuSpriteOptionalStateLayout as t,GPU_SPRITE_BASE_COMMAND_BYTES as s,GPU_SPRITE_EMITTER_BYTES as i,GPU_SPRITE_TRANSFORM_COMMAND_BYTES as r,GpuSpriteRuntime as n}from"./gpu-sprite-runtime.js";import{GpuSpriteTemplateCache as l,instantiateGpuSpriteTemplate as a}from"./gpu-sprite-template.js";import{GpuVfxScheduler as o}from"./gpu-vfx-scheduler.js";export class GpuSpriteWorldRuntime{constructor(t,s,i){this.pools=i,this.activeByHandleSlot=[],this.activePages=new Set,this.positionScratch=new e.Vector3,this.activePagesDirty=!1,this.runtime=t,this.scheduler=s,this.templateCount=i.length;for(let e=0;e<t.emitters.length;e++)t.setEmitterActive(e,!1);t.setActivePages([])}static async create(h){if(0===h.templates.length)return null;const c=h.templateCache??new l,m=await Promise.all(h.templates.map(e=>c.resolve(e.asset,{assets:h.assets,renderClassCache:h.renderClassCache,resolveCustomMaterial:h.resolveCustomMaterial,revision:e.revision})));if(m.some(e=>null==e.template))return null;const u=m.map(e=>e.template),p=Math.max(1,Math.floor(h.particlePageSize??256)),d=[],f=new Map,g=[],S=[];let I=0;for(let t=0;t<u.length;t++){const s=u[t],i=h.templates[t],r=Math.max(1,Math.floor(i.maximumInstances)),n=s.renderClasses.map(e=>{let t=f.get(e);return null==t&&(t=d.length,f.set(e,t),d.push(e)),t}),l=g.length,o=new e.Vector3,c=a(s,new Array(r).fill(o));for(const e of c)e.renderClass=n[e.renderClass??0]??0,null!=e.parentEmitter&&(e.parentEmitter+=l),g.push(e);S.push({template:s,baseEmitterIndex:l,maximumInstances:r,freeSlots:Array.from({length:r},(e,t)=>r-t-1),emitterCapacities:s.emitters.map(e=>e.capacity),emitterIndexScratch:new Array(s.emitters.length).fill(0),emitterPositionOffsets:s.emitters.map(e=>e.position.clone()),maximumParticleLife:s.emitters.reduce((e,t)=>Math.max(e,t.life),0)}),I+=Math.ceil(s.particleCapacity/p)*p*r}const y=g.reduce((e,t)=>e+t.capacity,0),v=d.some(e=>null!=e.meshVertices),x=d.some(e=>!0===e.localSpace&&null==e.trail),E=g.some(e=>!0===e.localSpace&&null!=d[e.renderClass??0]?.trail),P=g.length*(E?r:s),C=v||g.some(e=>1!==e.meshScaleStart.x||1!==e.meshScaleStart.y||1!==e.meshScaleStart.z||1!==e.meshScaleEnd.x||1!==e.meshScaleEnd.y||1!==e.meshScaleEnd.z),T=g.reduce((e,t)=>{const s=d[t.renderClass??0]?.trail;return e+(null==s?0:t.capacity*(s.historyLength+1))},0),b=t({capacity:I,particleTransforms:C,vortex:g.some(e=>e.hasVortex),disperse:g.some(e=>e.hasDisperse),collisionEvents:g.some(e=>2===e.childSpawnEvent),trailHistoryEntries:T});if(16*I*4+4*y+4*I+4*I*4+g.length*i+Math.max(s,P)+160+16*d.length*2+d.reduce((e,t)=>e+(t.meshVertices?.byteLength??0),0)+b.bytes+(v||x?16*g.length*4:0)>(h.maximumStorageBytes??Number.POSITIVE_INFINITY))return null;if(null!=h.device){const e=h.device.limits.maxStorageBufferBindingSize;if([16*I*4,4*g.reduce((e,t)=>e+t.capacity,0),4*I,4*I*4,g.length*i,Math.max(s,P),...v||x?[16*g.length*4]:[],...b.bytes>0?[b.bytes]:[]].some(t=>t>e))return null;if(7+(b.bytes>0?1:0)>h.device.limits.maxStorageBuffersPerShaderStage)return null}const B=new n(g,d,void 0,{pageSize:p,capacity:I,aliveCountReadback:h.aliveCountReadback});return new GpuSpriteWorldRuntime(B,new o({pageSize:p,maximumParticles:I}),S)}spawn(e,t){const s=this.pools[e],i=s?.freeSlots.pop();if(null==s||null==i)return null;const r=this.scheduler.createInstance({particleCapacity:s.template.particleCapacity,duration:s.template.duration});if(null==r)return s.freeSlots.push(i),null;const n=this.scheduler.arena.get(r).pages,l={handle:r,templateIndex:e,pages:n,logicalSlot:i,stoppingDeadline:Number.POSITIVE_INFINITY};this.activeByHandleSlot[r.slot]=l;for(const e of n)this.activePages.add(e);this.activePagesDirty=!0;const a=s.template.emitters.length;for(let e=0;e<a;e++){const r=s.baseEmitterIndex+i*a+e;s.emitterIndexScratch[e]=r;const n=this.runtime.emitters[r];this.positionScratch.copy(s.emitterPositionOffsets[e]),!0!==n.localSpace&&null==n.parentEmitter&&this.positionScratch.add(t),this.runtime.queueEmitterState(r,this.positionScratch,!0,!0)}return this.runtime.mapParticlePages(n,s.emitterIndexScratch,s.emitterCapacities),this.scheduler.play(r),l}destroy(e){const t=this.activeByHandleSlot[e.handle.slot];if(null==t||t.handle.generation!==e.handle.generation)return!1;const s=this.pools[t.templateIndex],i=s.template.emitters.length;for(let e=0;e<i;e++){const r=s.baseEmitterIndex+t.logicalSlot*i+e;this.runtime.queueEmitterState(r,this.runtime.emitters[r].position,!1)}for(const e of t.pages)this.activePages.delete(e);return this.activePagesDirty=!0,s.freeSlots.push(t.logicalSlot),this.activeByHandleSlot[e.handle.slot]=null,this.scheduler.destroyInstance(e.handle)}setPosition(e,t){const s=this.resolve(e);if(null==s)return!1;const i=this.pools[s.templateIndex];for(let e=0;e<i.template.emitters.length;e++){const r=this.emitterIndex(s,i,e);!0!==this.runtime.emitters[r].localSpace&&null==this.runtime.emitters[r].parentEmitter&&(this.positionScratch.copy(t).add(i.emitterPositionOffsets[e]),this.runtime.queueEmitterState(r,this.positionScratch,!0))}return!0}setTransform(e,t){const s=this.resolve(e);if(null==s)return!1;const i=this.pools[s.templateIndex];for(let e=0;e<i.template.emitters.length;e++){const r=this.emitterIndex(s,i,e),n=this.runtime.emitters[r];this.runtime.setEmitterTransform(r,t),!0!==n.localSpace&&null==n.parentEmitter&&(this.positionScratch.copy(i.emitterPositionOffsets[e]).applyMatrix4(t),this.runtime.queueEmitterState(r,this.positionScratch,!0))}return!0}pause(e){const t=this.resolve(e);return!(null==t||!this.scheduler.pause(t.handle))&&(this.forEachEmitter(t,e=>this.runtime.queueEmitterPaused(e,!0)),!0)}play(e){const t=this.resolve(e);return!(null==t||!this.scheduler.play(t.handle))&&(this.forEachEmitter(t,e=>this.runtime.queueEmitterPaused(e,!1)),!0)}restart(e){const t=this.resolve(e);return!(null==t||!this.scheduler.restart(t.handle))&&(t.stoppingDeadline=Number.POSITIVE_INFINITY,this.forEachEmitter(t,e=>{this.runtime.queueEmitterState(e,this.runtime.emitters[e].position,!0,!0)}),!0)}stop(e,t){const s=this.resolve(e),i=null==s?null:this.scheduler.getInstance(s.handle);if(null==s||null==i||!this.scheduler.stop(s.handle))return!1;const r=this.pools[s.templateIndex];return s.stoppingDeadline=i.elapsedTime+(null==t?r.maximumParticleLife:Math.max(0,t)),this.forEachEmitter(s,e=>this.runtime.queueEmitterStop(e,t)),!0}setTimescale(e,t){const s=this.resolve(e);return!(null==s||!this.scheduler.setTimescale(s.handle,t))&&(this.forEachEmitter(s,e=>this.runtime.queueEmitterTimescale(e,t)),!0)}setInput(e,t,s){const i=this.resolve(e);if(null==i)return!1;const r=this.pools[i.templateIndex];let n=!1;for(const e of r.template.inputBindings)e.inputId===t&&(n=this.runtime.setEmitterBoundValue(this.emitterIndex(i,r,e.emitterIndex),e,s)||n);return n&&this.scheduler.setDuration(i.handle,this.calculateInstanceDuration(i,r)),n}has(e){return null!=this.resolve(e)}update(e){this.scheduler.update(e),this.runtime.update(e);for(const e of this.activeByHandleSlot){if(null==e)continue;const t=this.scheduler.getInstance(e.handle);if(null==t)continue;const s=this.pools[e.templateIndex];(!1===t.playing&&t.elapsedTime>=s.template.duration||t.stopping&&t.elapsedTime>=e.stoppingDeadline)&&this.destroy(e)}this.flushActivePages()}flushActivePages(){this.activePagesDirty&&(this.runtime.setActivePages(this.activePages),this.activePagesDirty=!1)}dispose(){this.runtime.dispose();for(const e of this.activeByHandleSlot)null!=e&&this.scheduler.destroyInstance(e.handle);this.activeByHandleSlot.length=0}resolve(e){const t=this.activeByHandleSlot[e.handle.slot];return null!=t&&t.handle.generation===e.handle.generation&&null!=this.scheduler.getInstance(t.handle)?t:null}emitterIndex(e,t,s){return t.baseEmitterIndex+e.logicalSlot*t.template.emitters.length+s}forEachEmitter(e,t){const s=this.pools[e.templateIndex];for(let i=0;i<s.template.emitters.length;i++)t(this.emitterIndex(e,s,i))}calculateInstanceDuration(e,t){let s=0;for(let i=0;i<t.template.emitters.length;i++){const r=this.runtime.emitters[this.emitterIndex(e,t,i)],n="continuous"===r.rate.type?r.rate.duration<0?Number.POSITIVE_INFINITY:r.rate.delay+r.rate.duration+r.life:r.rate.delay+r.life;s=Math.max(s,n)}return s}}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -5,10 +5,16 @@ export declare class DefaultInitializer extends Initializer {
5
5
  init(emitter: Emitter, particle: Particle): void;
6
6
  initialize(target: Emitter | Particle): void;
7
7
  }
8
- export declare class WorldSpaceEmitterRotationInitializer extends Initializer {
8
+ export declare class WorldSpaceEmitterTransformInitializer extends Initializer {
9
+ private readonly composeParticleRotation;
10
+ constructor(composeParticleRotation: boolean);
9
11
  init(emitter: Emitter, particle: Particle): void;
10
12
  initialize(target: Emitter | Particle): void;
11
13
  }
14
+ /** @deprecated Use WorldSpaceEmitterTransformInitializer. */
15
+ export declare class WorldSpaceEmitterRotationInitializer extends WorldSpaceEmitterTransformInitializer {
16
+ constructor();
17
+ }
12
18
  export declare class Rotation extends Initializer {
13
19
  private rotation;
14
20
  constructor(rotation: Vector3);
@@ -1,4 +1,4 @@
1
- import{Vector3 as t,Quaternion as e,Euler as i,Color as s}from"three";import{Span as o,Initializer as n}from"@hology/nebula";export class DefaultInitializer extends n{init(t,e){e.parent=t}initialize(t){}}export class WorldSpaceEmitterRotationInitializer extends n{init(t,e){"number"!=typeof e.rotation&&(a.setFromEuler(c.set(t.rotation.x,t.rotation.y,t.rotation.z)),r.setFromEuler(c.set(e.rotation.x,e.rotation.y,e.rotation.z)),a.multiply(r),c.setFromQuaternion(a),e.rotation.set(c.x,c.y,c.z))}initialize(t){}}export class Rotation extends n{constructor(t){super(),this.rotation=t}setRotation(t){this.rotation=t.clone()}initialize(t){"number"!=typeof t.rotation&&t.rotation.copy(this.rotation)}}export const randomRotationAxis=["XYZ","X","Y","Z"];export class RandomRotation extends n{constructor(t){super(),this.axis=t}initialize(t){switch(this.axis){case"XYZ":t.rotation.set(this.randomAngle(),this.randomAngle(),this.randomAngle());break;case"X":t.rotation.x=this.randomAngle();break;case"Y":t.rotation.y=this.randomAngle();break;case"Z":t.rotation.z=this.randomAngle()}}randomAngle(){return 2*Math.PI*Math.random()}}export class InitialScale extends n{constructor(t){super(),this.scale=t}setScale(t){this.scale=t}initialize(t){t.scale=this.scale}}export class RandomScale extends n{constructor(t,e){super(),this.min=t,this.max=e}setRange(t,e){this.min=t,this.max=e}initialize(t){t.scale=h(this.min,this.max)}}export class RandomColor extends n{constructor(t,e){super(),this.min=new s,this.max=new s,this.setRange(t,e)}setRange(t,e){this.min.set(t),this.max.set(e)}initialize(t){const e=Math.random();t.color.r=h(this.min.r,this.max.r,e),t.color.g=h(this.min.g,this.max.g,e),t.color.b=h(this.min.b,this.max.b,e),t.useColor=!0}}export class InitialScaleComponents extends n{constructor(t){super(),this.scale=t}setScaleComponents(t){this.scale=t.clone()}initialize(t){t.transform.initialScale=this.scale.clone()}}export class AdditiveVelocity extends n{constructor(t,e){super(),this.min=t,this.max=e}initialize(t){const e=m(this.min),i=null!=this.max?m(this.max):void 0;t.velocity.x+=null!=i?h(e.x,i.x):e.x,t.velocity.y+=null!=i?h(e.y,i.y):e.y,t.velocity.z+=null!=i?h(e.z,i.z):e.z}}export class RandomDirection extends n{constructor(t){super(),this.speed=t}setSpeed(t){this.speed=t}initialize(t){l.set(2*Math.random()-1,2*Math.random()-1,2*Math.random()-1).normalize().multiplyScalar(this.speed),t.velocity.x+=l.x,t.velocity.y+=l.y,t.velocity.z+=l.z}}export class RandomVelocity extends n{constructor(t,e){super(),this.min=t,this.max=e,this.x=new o(this.min.x,this.max.x),this.y=new o(this.min.y,this.max.y),this.z=new o(this.min.z,this.max.z)}initialize(t){t.velocity.x+=this.x.getValue(),t.velocity.y+=this.y.getValue(),t.velocity.z+=this.z.getValue()}}export const alignRotationAxes=["+X","-X","+Y","-Y","+Z","-Z"];export const alignRotationModes=["AwayFromCenter","TowardsCenter","AlongVelocity"];export class AlignRotation extends n{constructor(e,i,s=new t,o=new t){super(),this.axis=e,this.mode=i,this.offset=s,this.center=o,this.axisVec=new t(0,1,0),this.setAxis(e)}setAxis(t){switch(t){case"+X":this.axisVec.set(1,0,0);break;case"-X":this.axisVec.set(-1,0,0);break;case"+Y":this.axisVec.set(0,1,0);break;case"-Y":this.axisVec.set(0,-1,0);break;case"+Z":this.axisVec.set(0,0,1);break;case"-Z":this.axisVec.set(0,0,-1)}}initialize(t){if("number"!=typeof t.rotation){switch(this.mode){case"AwayFromCenter":l.copy(t.position).sub(this.center).normalize();break;case"TowardsCenter":l.copy(t.position).sub(this.center).normalize().multiplyScalar(-1);break;case"AlongVelocity":l.copy(t.velocity).normalize()}l.lengthSq()<1e-4&&l.set(0,1,0),a.setFromUnitVectors(this.axisVec,l),this.offset.lengthSq()>0&&(r.setFromEuler(c.set(this.offset.x,this.offset.y,this.offset.z)),a.multiply(r)),c.setFromQuaternion(a),t.rotation.x=c.x,t.rotation.y=c.y,t.rotation.z=c.z}}}const a=new e,r=new e,c=new i,l=new t;function h(t,e,i=Math.random()){return i*(e-t)+t}function m(t){return"function"==typeof t?t():t}/*
1
+ import{Vector3 as t,Quaternion as e,Euler as i,Color as s}from"three";import{Span as o,Initializer as n}from"@hology/nebula";export class DefaultInitializer extends n{init(t,e){e.parent=t}initialize(t){}}export class WorldSpaceEmitterTransformInitializer extends n{constructor(t){super(),this.composeParticleRotation=t}init(t,e){a.setFromEuler(c.set(t.rotation.x,t.rotation.y,t.rotation.z)),e.position.applyQuaternion(a),this.composeParticleRotation&&"number"!=typeof e.rotation&&(r.setFromEuler(c.set(e.rotation.x,e.rotation.y,e.rotation.z)),a.multiply(r),c.setFromQuaternion(a),e.rotation.set(c.x,c.y,c.z))}initialize(t){}}export class WorldSpaceEmitterRotationInitializer extends WorldSpaceEmitterTransformInitializer{constructor(){super(!0)}}export class Rotation extends n{constructor(t){super(),this.rotation=t}setRotation(t){this.rotation=t.clone()}initialize(t){"number"!=typeof t.rotation&&t.rotation.copy(this.rotation)}}export const randomRotationAxis=["XYZ","X","Y","Z"];export class RandomRotation extends n{constructor(t){super(),this.axis=t}initialize(t){switch(this.axis){case"XYZ":t.rotation.set(this.randomAngle(),this.randomAngle(),this.randomAngle());break;case"X":t.rotation.x=this.randomAngle();break;case"Y":t.rotation.y=this.randomAngle();break;case"Z":t.rotation.z=this.randomAngle()}}randomAngle(){return 2*Math.PI*Math.random()}}export class InitialScale extends n{constructor(t){super(),this.scale=t}setScale(t){this.scale=t}initialize(t){t.scale=this.scale}}export class RandomScale extends n{constructor(t,e){super(),this.min=t,this.max=e}setRange(t,e){this.min=t,this.max=e}initialize(t){t.scale=h(this.min,this.max)}}export class RandomColor extends n{constructor(t,e){super(),this.min=new s,this.max=new s,this.setRange(t,e)}setRange(t,e){this.min.set(t),this.max.set(e)}initialize(t){const e=Math.random();t.color.r=h(this.min.r,this.max.r,e),t.color.g=h(this.min.g,this.max.g,e),t.color.b=h(this.min.b,this.max.b,e),t.useColor=!0}}export class InitialScaleComponents extends n{constructor(t){super(),this.scale=t}setScaleComponents(t){this.scale=t.clone()}initialize(t){t.transform.initialScale=this.scale.clone()}}export class AdditiveVelocity extends n{constructor(t,e){super(),this.min=t,this.max=e}initialize(t){const e=m(this.min),i=null!=this.max?m(this.max):void 0;t.velocity.x+=null!=i?h(e.x,i.x):e.x,t.velocity.y+=null!=i?h(e.y,i.y):e.y,t.velocity.z+=null!=i?h(e.z,i.z):e.z}}export class RandomDirection extends n{constructor(t){super(),this.speed=t}setSpeed(t){this.speed=t}initialize(t){l.set(2*Math.random()-1,2*Math.random()-1,2*Math.random()-1).normalize().multiplyScalar(this.speed),t.velocity.x+=l.x,t.velocity.y+=l.y,t.velocity.z+=l.z}}export class RandomVelocity extends n{constructor(t,e){super(),this.min=t,this.max=e,this.x=new o(this.min.x,this.max.x),this.y=new o(this.min.y,this.max.y),this.z=new o(this.min.z,this.max.z)}initialize(t){t.velocity.x+=this.x.getValue(),t.velocity.y+=this.y.getValue(),t.velocity.z+=this.z.getValue()}}export const alignRotationAxes=["+X","-X","+Y","-Y","+Z","-Z"];export const alignRotationModes=["AwayFromCenter","TowardsCenter","AlongVelocity"];export class AlignRotation extends n{constructor(e,i,s=new t,o=new t){super(),this.axis=e,this.mode=i,this.offset=s,this.center=o,this.axisVec=new t(0,1,0),this.setAxis(e)}setAxis(t){switch(t){case"+X":this.axisVec.set(1,0,0);break;case"-X":this.axisVec.set(-1,0,0);break;case"+Y":this.axisVec.set(0,1,0);break;case"-Y":this.axisVec.set(0,-1,0);break;case"+Z":this.axisVec.set(0,0,1);break;case"-Z":this.axisVec.set(0,0,-1)}}initialize(t){if("number"!=typeof t.rotation){switch(this.mode){case"AwayFromCenter":l.copy(t.position).sub(this.center).normalize();break;case"TowardsCenter":l.copy(t.position).sub(this.center).normalize().multiplyScalar(-1);break;case"AlongVelocity":l.copy(t.velocity).normalize()}l.lengthSq()<1e-4&&l.set(0,1,0),a.setFromUnitVectors(this.axisVec,l),this.offset.lengthSq()>0&&(r.setFromEuler(c.set(this.offset.x,this.offset.y,this.offset.z)),a.multiply(r)),c.setFromQuaternion(a),t.rotation.x=c.x,t.rotation.y=c.y,t.rotation.z=c.z}}}const a=new e,r=new e,c=new i,l=new t;function h(t,e,i=Math.random()){return i*(e-t)+t}function m(t){return"function"==typeof t?t():t}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,4 +1,4 @@
1
- import e,{Behaviour as t,Body as a,Emitter as r,Rate as s}from"@hology/nebula";import*as i from"three";import{Object3D as n}from"three";import{AttributeVec3Node as l,AttributeVec4Node as o,NodeShaderMaterial as c,RgbNode as p,UniformFloatNode as u,UniformVec3Node as h,Vec3ExpressionNode as d,attributeVec3 as m,attributeVec4 as f,attributes as y,clamp as w,cross as g,float as b,lambertMaterial as v,length as M,log as A,normalize as E,pow as x,rgb as S,rgba as I,smoothstep as T,standardMaterial as P,textureSampler2d as C,uniforms as R,varying as G,varyingAttributes as B,varyingVec3 as k,varyingVec4 as j,vec2 as D,vec3 as F,vec4 as V}from"three-shader-graph";import{prepareClassParameters as L,prepareShaderGraphParameters as O,prepareShapeParameters as W}from"../../scene/materializer.js";import{SerializedParamType as U}from"../../scene/model.js";import{ShapeLibrary as Q}from"../../scene/objects/shapes.js";import{fragmentLinearEyeDepth as H,linearEyeDepth as N}from"../../shader-nodes/depth.js";import{particleEnergyUniformName as q,particleTimeUniformName as z,particleUniforms as J,particleVelcoityUniformName as X}from"../../shader-nodes/particle.js";import{sampleFlipbook as _}from"../../shader-nodes/texture-sequence.js";import{DefaultInitializer as K,WorldSpaceEmitterRotationInitializer as Y}from"./initializsers.js";import{DelayRate as Z,OnceRate as $}from"./rates.js";import{StretchedSprite as ee}from"./stretched-sprite.js";import{ThreeBlendingMode as te}from"./vfx-asset.js";import{VfxBehaviourLibrary as ae,VfxInitializserLibrary as re}from"./vfx-defs.js";import{MultiRenderer as se}from"./vfx-renderers.js";import{WorldCollisionBehaviour as ie}from"./vfx-collision-behaviour.js";import{getSpritePosition as ne,SpriteNodeShader as le,SpriteNodeShaderMaterial as oe}from"../../shader/sprite-shader.js";import{DecalUnlitShader as ce}from"../../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as pe}from"../../shader/builtin/decal-standard-shader.js";import{createBoundBehaviour as ue,createBoundInitializer as he}from"./vfx-binding-runtime.js";import{buildShaderGraphMaterial as de}from"../../shader/graph/index.js";import{markMaterialUniformValuesNeedUpdate as me,setMaterialUniformValuesAutoUpdate as fe}from"../../rendering/node-material-webgpu-resolver.js";import{applyMeshWorldTransformToGeometry as ye}from"./vfx-mesh-transform.js";export async function materializeVfx(t,a,r,s,l,o,c,p,u){let h=a;for(;null!=h.parent;)h=h.parent;const d=new n;d.name="particle system local",a.add(d);const m=new n;m.name="particle system world";const f=new se(m,d,i,s),y=new e;return(await Promise.all(t.vfx.emitters.slice().sort((e,t)=>(t.output.renderOrder??0)-(e.output.renderOrder??0)).map(async e=>{const t=await we(e,r,c,p,y,l,o,u,a);return t.setParentRecursive(y),t.emit()}))).forEach(e=>y.addEmitter(e)),y.addRenderer(f).emit({onEnd:()=>{}}),{container:m,system:y,dispose:()=>{m.removeFromParent(),d.removeFromParent(),f.dispose()}}}async function we(e,t,r,p,x,S,P,D,F){const L=function(e){let t;switch(e.rate.type){case"continuous":t=new Z(e.rate.delay??0,e.rate.count,e.rate.time,e.rate.duration);break;case"once":t=new $(e.rate.delay??0,e.rate.count);break;default:console.warn(`Failed to configure rate for emitter: ${JSON.stringify(e)}`),t=new s(0,1/0)}return t}(e);let O;switch(e.output.type){case"decal":O=new a(await async function(e,t,a,r,s){if("shaderGraph"===be(e)){const t=await createShaderGraphMaterial(e,"decal",a,r,s);if(null!=t){const a=new i.Mesh(new i.BoxGeometry(1,1,1),t);return Ae(a,e),a}}const n=!1!==e.unlit?new ce:new pe;n.color=new i.Color(e.color),n instanceof ce?n.intensity=e.intensity??1:n.emissiveIntensity=e.intensity??1;if(e.colorMap){const a=await t.getTexture(e.colorMap);n.colorMap=a}if(e.alphaMap){const a=await t.getTexture(e.alphaMap);n.alphaMap=a}const l=n.build();l.blending=te[e.blendingMode]??i.NormalBlending,l.transparent=!0,l.side=i.BackSide,l.depthTest=!1,null!=l&&!0===e.bloom&&(l.userData.hasBloom=!0);l.defines.IS_PARTICLE="";const o=new i.BoxGeometry(1,1,1),c=new i.Mesh(o,l);return Ae(c,e),c}(e.output,t,r,p,P));break;case"sprite":O=new a(await async function(e,t,a,r,s){let n=null;const l=be(e);"shaderGraph"===l&&(n=await createShaderGraphMaterial(e,"sprite",a,r,s));null==n&&"shader"===l&&null!=e.shader&&(n=await createShaderMaterial(e,t,s));null==n&&(n=await async function(e,t){const a=null!=e.texture?await t.getTexture(e.texture):ge,r=C(a);let s=r.sample(B.uv);e.flipbook?.enabled&&(s=_(r,y.uv,e.flipbook.columns,e.flipbook.rows,J.time,e.flipbook.fps,e.flipbook.mode));const n=new u("rotation",0),l=new h("color").rgb,o=k(new d("instanceColor")).rgb,c=N.subtract(H).divide(N);let p=J.opacity;switch(e.opacityChannel??"red"){case"none":break;case"red":p=p.multiply(s.r);break;case"alpha":p=p.multiply(s.a)}if("number"==typeof e.softness&&e.softness>0){const t=w(c,0,1e3);p=p.multiply(T(0,.2*e.softness,t))}const m=ne(n,void 0,void 0,!0),f=I(l.multiply(o).multiply(s.rgb).multiplyScalar(e.intensity??1),p);var g=new oe({color:f,emissive:f.rgb.multiplyScalar(p),transparent:!0,position:m,alphaTest:1e-4,uniforms:{color:{value:new i.Color(e.color)}}});g.alphaHash=!0,null!=g&&!0===e.bloom&&(g.userData.hasBloom=!0);return g.blending=te[e.blendingMode]??i.NormalBlending,g}(e,t));n.depthWrite=!1,Me(n,e);const o=new i.Mesh(new i.PlaneGeometry(1,1),n);return o.name="sprite",Ae(o,e),o}(e.output,t,r,p,P));break;case"stretchedSprite":O=new a(await async function(e,t){"shaderGraph"===be(e)&&console.warn("Shader graph materials are not supported for stretched sprite VFX outputs yet. Falling back to the default stretched sprite material.");const a=null!=e.texture?await t.getTexture(e.texture):ge,r=C(a).sample(B.uv),s=j(new o("particleColor")),n=s.rgb.multiply(r.rgb);let l=s.w;switch(e.opacityChannel??"red"){case"none":break;case"red":l=l.multiply(r.r);break;case"alpha":l=l.multiply(r.a)}if("number"==typeof e.softness&&e.softness>0){const t=N.subtract(H).divide(A(N)),a=w(t,0,1e3);l=l.multiply(T(0,.2*e.softness,a))}const c=m("offset"),p=f("velocity"),u=m("size"),h=p.w,d=u.x.add(u.y).multiply(.5),v=R.modelViewMatrix.multiplyVec(V(c,1)),x=R.normalMatrix.multiplyVec(p.xyz),S=E(g(v.xyz,x)).multiplyScalar(y.position.y.multiply(d)),P=x.multiplyScalar(y.position.x.add(.5).multiply(b(1).add(h.divide(M(x)))).multiply(d)),G=R.projectionMatrix.multiplyVec(V(v.xyz.add(S).subtract(P),v.w));var k=new oe({color:I(n.multiplyScalar(e.intensity??1),l),alphaTest:.1,transparent:!0,position:G,uniforms:{color:{value:new i.Color(e.color)}}});null!=k&&!0===e.bloom&&(k.userData.hasBloom=!0);k.blending=te[e.blendingMode]??i.NormalBlending;const D=new ee(new i.PlaneGeometry(1,1),k);return D.scaleFactor=e.scale,Ae(D,e),D}(e.output,t));break;case"shape":O=new a(await async function(e,t,a,r,s){if(null==e.shape)return console.log("Shape is null"),new n;const o=Q[e.shape];if(null==o)return console.error(`No shape with type ${e.shape}`),new n;const p=W(e.params??{}),u=o.geometry(p);let h=null;const m=be(e);"shaderGraph"===m&&(h=await createShaderGraphMaterial(e,"surface",a,r,s));null==h&&"shader"===m&&null!=e.shader&&(h=await createShaderMaterial(e,t,s));null==h&&(h="material"===m&&null!=e.material?Ee(await t.getMaterial(e.material)):function(){const e=G(new d("instanceColor")).rgb,t=G(new l("particleData")).x;return new c({color:v({color:e}).rgb.rgba(t),opacity:t,transparent:!0})}());Me(h,e);const f=new i.Mesh(u,h);return Ae(f,e),f}(e.output,t,r,p,P));break;case"mesh":O=new a(await async function(e,t,a,r,s){if(null==e.assetId)return console.warn("Can't use mesh as particle without asset id"),new n;const l=await t.getMesh(e.assetId),o=await t.getAsset(e.assetId),c=be(e);if("shaderGraph"===c||"shader"===c&&null!=e.shader||"material"===c&&null!=e.material){let n;"shaderGraph"===c?n=await createShaderGraphMaterial(e,"surface",a,r,s):"shader"===c&&null!=e.shader?n=await createShaderMaterial(e,t,s):"material"===c&&null!=e.material&&(n=Ee(await t.getMaterial(e.material))),n?.transparent&&(n.depthWrite=!1),null!=n&&Me(n,e),l.traverse(e=>{e instanceof i.Mesh&&null!=n&&(e.material=n)})}else{const e=[];if(null!=o.materialAssignments)for(const a of o.materialAssignments)null!=a.materialId&&l.traverse(r=>{r instanceof i.Mesh&&r.material instanceof i.Material&&r.material.color instanceof i.Color&&(r.material.name!=a.name&&null!=a.name||"#"+r.material.color.getHexString()!==a.color||e.push(t.getMaterial(a.materialId).then(e=>r.material=e)))});await Promise.all(e)}const p=[];if(l.traverse(e=>{e instanceof i.Mesh&&p.push(e)}),Ae(l,e),1===p.length){const t=p[0];return!0!==e.useLegacyTransform&&function(e){e.geometry=e.geometry.clone(),ye(e,e.geometry),e.position.set(0,0,0),e.quaternion.identity(),e.scale.set(1,1,1),e.updateMatrix(),e.matrixWorld.identity()}(t),t.removeFromParent(),t}return l}(e.output,t,r,p,P));break;case"trail":{const s="shaderGraph"===be(e.output)?await createShaderGraphMaterial(e.output,"trail",r,p,P,{trailBillboard:e.output.billboard??!1}):null;O=new a({type:"trail",taper:e.output.taper,headGeometry:null,material:s instanceof i.ShaderMaterial?s:void 0,dragTexture:!1,texture:null!=e.output.texture?await t.getTexture(e.output.texture):null,opacityChannel:e.output.opacityChannel,color:e.output.color,colorEnd:e.output.colorEnd,intensity:e.output.intensity??1,intensityEnd:e.output.intensityEnd??1,length:e.output.length,opacityStart:e.output.opacityStart,opacityEnd:e.output.opacityEnd,bloom:e.output.bloom,scrollSpeed:e.output.scrollSpeed,width:e.output.width,billboard:e.output.billboard??!1,renderOrder:e.output.renderOrder});break}default:console.error("Failed to create particly system body: "+JSON.stringify(e))}const q=new Se(F);q.parent=x,q.setRate(L),q._space=e.output.space;const z=await Promise.all(e.initializers.filter(e=>!1!==e.enabled).filter(e=>null!=re[e.type]).map(async e=>{const t=re[e.type],a=await W(e.params??{});return he(t,e.params??{},a,D)}));"world"!==e.output.space||"shape"!==e.output.type&&"mesh"!==e.output.type||z.unshift(new Y),z.push(O,new K),q.addInitializers(z);const X=await Promise.all(e.behaviours.filter(e=>!1!==e.enabled).filter(e=>null!=ae[e.type]).map(async e=>{const t=ae[e.type];for(const[a,r]of Object.entries(e.params))t.parameters&&null!=t.parameters[a]&&"curve"===t.parameters[a].type&&r.type!==U.Curve&&(r.type=U.Curve);const a=await W(e.params??{},r,p);return ue(t,e.params??{},a,D)}).sort((e,t)=>e instanceof ie?1:0));X.push(new xe);for(const e of X)e instanceof ie&&(e.physics=S);q.addBehaviours(X);for(const a of e.children??[]){const e=await we(a,t,r,p,x,S,P,D,F),s=new EmitterPool(()=>{const t=e.clone();return t.onExpired=()=>{const e=q.childEmitters.findIndex(e=>e.id===t.id);-1!=e&&q.childEmitters.splice(e,1),null!=t.parentParticle&&(n.delete(t.parentParticle.id),t.parentParticle=null),s.release(t)},t}),i=q.eventDispatcher,n=new Map;q.bindEmitterEvent=!0,i.addEventListener("PARTICLE_DEAD",e=>{const t=n.get(e.id);null!=t&&(q.detachChildEmitterFromParticle(t,e),n.delete(e.id))});let l="PARTICLE_CREATED";if("spawnEvent"in a)switch(a.spawnEvent){case"collision":l="PARTICLE_COLLISION";break;case"start":l="PARTICLE_CREATED"}i.addEventListener(l,e=>{const t=s.get();t.age=0,t.totalEmitTimes=-1,t.particles.length=0,t.currentEmitTime=0,t.cID=0,t.eventDispatcher.removeAllEventListeners(),q.childEmitters.push(t),n.set(e.id,t),t.parentParticle=e,t.system=q.system,t.emit()})}return q}const ge=(new i.TextureLoader).load("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJkSURBVHjaxJeJbusgEEW94S1L//83X18M2MSuLd2pbqc4wZGqRLrKBsyZhQHny7Jk73xVL8xpVhWrcmiB5lX+6GJ5YgQ2owbAm8oIwH1VgKZUmGcRqKGGPgtEQQAzGR8hQ59fAmhJHSAagigJ4E7GPWRXOYC6owAd1JM6wDQPADyMWUqZRMqmAojHp1Vn6EQQEgUNMJLnUjMyJsM49wygBkAPw9dVFwXRkncCIIW3GRgoTQUZn6HxCMAFEFd8TwEQ78X4rHbILoAUmeT+RFG4UhQ6MiIAE4W/UsYFjuVjAIa2nIY4q1R0GFtQWG3E84lqw2GO2QOoCKBVu0BAPgDSU0eUDjjQenNkV/AW/pWChhpMTelo1a64AOKM30vk18GzTHXCNtI/Knz3DFBgsUqBGIjTInXRY1yA9xkVoqW5tVq3pDR9A0hfF5BSARmVnh7RMDCaIdcNgbPBkgzn1Bu+SfIEFSpSBmkxyrMicb0fAEuCZrWnN89veA/4XcakrPcjBWzkTuLjlbfTQPOlBhz+HwkqqPXmPQDdrQItxE1moGof1S74j/8txk8EHhTQrAE8qlwfqS5yukm1x/rAJ9Jiaa6nyATqD78aUVBhFo8b1V4DdTXdCW+IxA1zB4JhiOhZMEWO1HqnvdoHZ4FAMIhV9REF8FiUm0jsYPEJx/Fm/N8OhH90HI9YRHesWbXXZwAShU8qThe7H8YAuJmw5yOd989uRINKRTJAhoF8jbqrHKfeCYdIISZfSq26bk/K+yO3YvfKrVgiwQBHnwt8ynPB25+M8hceTt/ybPhnryJ78+tLgAEAuCFyiQgQB30AAAAASUVORK5CYII=");export async function createShaderMaterial(e,t,a){const r=a.get(e.shader);if(null==r)return console.error("No shader exists with name "+e.shader),new i.Material;const s=new r.type;"sprite"===e.type&&s instanceof le&&(s.instanced=!0);const n=await L(e.shaderParams??{},r.type,t,{getTexture:e=>t.getTexture(e.id),getMaterial:e=>t.getMaterial(e.id),getMesh:e=>t.getMesh(e.id)},void 0,void 0,void 0,void 0,void 0,s);return Object.assign(s,n),s.build()}export async function createShaderGraphMaterial(e,t,a,r,s,i={}){const n=e.shaderGraph;if("asset"!==n?.source||null==n.assetId)return console.warn(`Missing shader graph asset reference for ${e.type} VFX output`),null;const l=await a.getAsset(n.assetId),o=l?.shaderGraph;if(null==o)return console.warn(`Missing shader graph asset "${n.assetId}" for ${e.type} VFX output`),null;if(o.target!==t)return console.warn(`Shader graph "${l.name}" targets "${o.target}" but ${e.type} VFX output expects "${t}"`),null;try{const t=await O(e.shaderGraphParams??{},o,a,r,void 0,s.shaders),l=de(o,{parameters:t,trailBillboard:i.trailBillboard});return l.userData.customShaderName=`shaderGraph:${n.assetId}`,Me(l,e),l}catch(e){return console.log("Shader graph VFX runtime error: "+e,e),null}}export function createGpuSpriteShaderGraphResolver(e,t,a,r){return async s=>{const n=be(s);let l=null;if("shaderGraph"===n)l=await createShaderGraphMaterial(s,"sprite"===s.type?"sprite":"decal"===s.type?"decal":"trail"===s.type?"trail":"surface",e,t,a,"trail"===s.type?{trailBillboard:s.billboard??!1}:void 0);else if("shader"===n&&"decal"!==s.type&&null!=r)l=await createShaderMaterial(s,r,a);else if("material"!==n||"mesh"!==s.type&&"shape"!==s.type||null==s.material||null==r){if("default"===n&&"mesh"===s.type&&null!=s.assetId&&null!=r){const e=await r.getAsset(s.assetId),t=e.materialAssignments?.find(e=>null!=e.materialId);null!=t&&(l=await ve(t.materialId,r))}else if("default"===n&&"decal"===s.type&&null!=r){const e=!1!==s.unlit?new ce:new pe;e.color=new i.Color(s.color),e instanceof ce?e.intensity=s.intensity??1:e.emissiveIntensity=s.intensity??1,s.colorMap&&(e.colorMap=await r.getTexture(s.colorMap)),s.alphaMap&&(e.alphaMap=await r.getTexture(s.alphaMap)),l=e.build(),l.transparent=!0}}else l="mesh"===s.type?await ve(s.material,r):Ee(await r.getMaterial(s.material));return null==l?null:("mesh"!==s.type&&"shape"!==s.type||!l.transparent||(l.depthWrite=!1),l instanceof c?l:(console.warn(`GPU ${s.type} materials must compile to NodeShaderMaterial; using CPU fallback`),null))}}function be(e){return null!=e.materialSource?("material"!==e.materialSource||"mesh"!==e.type&&"shape"!==e.type||null!=e.material)&&("shaderGraph"!==e.materialSource||"asset"===e.shaderGraph?.source&&null!=e.shaderGraph.assetId)&&("shader"!==e.materialSource||"shader"in e&&null!=e.shader)?e.materialSource:"default":"asset"===e.shaderGraph?.source?"shaderGraph":"shader"in e&&null!=e.shader?"shader":"mesh"!==e.type&&"shape"!==e.type||null==e.material?"default":"material"}async function ve(e,t){const a=(await t.getAsset(e)).material,r=a?.shaderParams??{},s=a?.params??{},n=r.color?.value??s.color??"#ffffff",l=r.opacity?.value??s.opacity??1,o=r.intensity?.value??s.intensity??1,p=r.map?.value??s.map,u=r.alphaMap?.value??s.alphaMap;let h=J.color.rgb.multiply(S(new i.Color(n))).multiplyScalar(b(o)),d=J.opacity.multiply(b(l));if(null!=p){const e=C(await t.getTexture(p)).sample(B.uv);h=h.multiply(e.rgb),d=d.multiply(e.a)}null!=u&&(d=d.multiply(C(await t.getTexture(u)).sample(B.uv).r));const m=new c({color:h.rgba(d),opacity:d,transparent:!0===a?.transparent||l<1||null!=u});return m.blending=te[a?.blending]??i.NormalBlending,m.alphaTest=a?.alphaTest??0,m.side=a?.side??i.FrontSide,m.transparent&&(m.depthWrite=!1),m}function Me(e,t){null!=e&&(fe(e,!1),"bloom"in t&&!0===t.bloom&&(e.userData.hasBloom=!0),"sprite"===t.type?(e.blending=te[t.blendingMode]??i.NormalBlending,!0===t.lockY&&e instanceof i.ShaderMaterial&&(e.defines??(e.defines={}),e.defines.LOCK_Y_AXIS="")):"decal"===t.type?(e.blending=te[t.blendingMode]??i.NormalBlending,e.transparent=!0,e.side=i.BackSide,e.depthTest=!1,e instanceof i.ShaderMaterial&&(e.defines??(e.defines={}),e.defines.IS_PARTICLE="")):"shape"!==t.type&&"mesh"!==t.type||e instanceof i.ShaderMaterial&&(e.defines??(e.defines={}),e.defines.IS_PARTICLE=""))}function Ae(e,t){const a=t.renderOrder;null!=a&&e.traverse(e=>e.renderOrder=a)}function Ee(e){const t=G(new d("instanceColor")).rgb;let a,r=G(new l("particleData")).x;if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial){let s=t.multiply(S(e.color));null!=e.map&&(s=s.multiply(C(e.map).sample(B.uv).rgb)),null!=e.alphaMap&&(r=r.multiply(C(e.alphaMap).sample(B.uv).r)),e instanceof i.MeshStandardMaterial?a=new c({color:P({color:s,emissive:S(e.emissive),emissiveIntensity:b(e.emissiveIntensity),roughness:e.roughness,metalness:e.metalness}).rgb.rgba(r),emissive:S(e.emissive).multiplyScalar(e.emissiveIntensity),transparent:e.transparent,opacity:r,alphaTest:e.alphaTest}):e instanceof i.MeshLambertMaterial?a=new c({color:v({color:s}).rgb.rgba(r),emissive:S(e.emissive).multiplyScalar(e.emissiveIntensity),transparent:e.transparent,opacity:r,alphaTest:e.alphaTest}):e instanceof i.MeshBasicMaterial&&(a=new c({color:s.rgb.rgba(r),emissive:s.rgb,transparent:e.transparent,opacity:r,alphaTest:e.alphaTest}))}else e instanceof c&&(a=e.clone(),a.defines.IS_PARTICLE="");return null!=a&&(!0===e.userData?.hasBloom&&null!=a&&(a.userData.hasBloom=!0),a.side=e.side,a.transparent=e.transparent),a??e}class xe extends t{initialize(e){e.body instanceof i.Object3D&&e.body.traverse(e=>{if(e instanceof i.Mesh){const t=e.material;t instanceof c&&(null!=t.uniforms[q]||null!=t.uniforms[z]||t.uniforms[X])}})}mutate(e,t,a){this.energize(e,t),e.target instanceof n&&e.target.traverse(t=>{if(t instanceof i.Mesh){const a=t.material;if(a instanceof c){let t=!1;null!=a.uniforms[q]&&(a.uniforms[q].value=this.energy,t=!0),null!=a.uniforms[z]&&(a.uniforms[z].value=e.age,t=!0),null!=a.uniforms[X]&&(a.uniforms[X].value=e.velocity,t=!0),t&&me(a)}}})}}class Se extends r{constructor(e){super(),this.transformRoot=e,this.childEmitters=[],this.bindEmitterEvent=!1,this.onExpired=()=>{}}clearParticlesRecursive(){let e=this.childEmitters.length;for(;e--;){const t=this.childEmitters[e];t.stopEmit(),t.clearParticlesRecursive(),t.onExpired()}this.childEmitters.length=0;let t=this.particles.length;for(;t--;){const e=this.particles[t];this.system?.dispatch("PARTICLE_DEAD",e),this.bindEmitterEvent&&this.dispatch("PARTICLE_DEAD",e),null!=this.system?this.system.pool.expire(e.reset()):e.reset()}this.particles.length=0}detachChildEmitterFromParticle(e,t){this.copyPositionToChildSpace(e,t.position),e.parentParticle=null,e.stopEmit()}update(e){if(!this.isEmitting&&0===this.particles.length&&0===this.childEmitters.length)return;this.age+=e,(this.dead||this.age>=this.life)&&this.destroy(),this.isEmitting&&this.generate(e),this.integrate(e);let t=this.particles.length;for(;t--;){const e=this.particles[t];e.dead&&(this.system&&this.system.dispatch("PARTICLE_DEAD",e),this.bindEmitterEvent&&this.dispatch("PARTICLE_DEAD",e),this.system.pool.expire(e.reset()),this.particles.splice(t,1))}this.updateEmitterBehaviours(e),this.updateChildren(e),this.isEmitting||0!==this.particles.length||0!==this.childEmitters.length||this.onExpired()}updateChildren(e){for(const t of this.childEmitters)null!=t.parentParticle&&this.copyPositionToChildSpace(t,t.parentParticle.position),t.update(e)}copyPositionToChildSpace(e,t){const a=this._space??"world",r=e._space??"world";a!==r&&null!=this.transformRoot?(Ie.copy(t),"local"===a&&"world"===r?Ie.applyMatrix4(this.transformRoot.matrixWorld):"world"===a&&"local"===r&&(Te.copy(this.transformRoot.matrixWorld).invert(),Ie.applyMatrix4(Te)),e.position.copy(Ie)):e.position.copy(t)}clone(){const e=new Se(this.transformRoot);return e.setRate(this.rate.clone()),e.behaviours=this.behaviours,e.initializers=this.initializers,e._space=this._space,e.body=this.body,e.parent=this.parent,e.system=this.system,e}setParentRecursive(e){this.system=e,this.childEmitters.forEach(t=>t.setParentRecursive(e))}}const Ie=new i.Vector3,Te=new i.Matrix4;export class EmitterPool{constructor(e){this.creator=e,this.instances=[]}get(){0==this.instances.length&&this.instances.push(this.creator());return this.instances.pop()}release(e){this.instances.push(e)}dispose(){this.instances.length=0}}/*
1
+ import e,{Behaviour as t,Body as a,Emitter as r,Rate as s}from"@hology/nebula";import*as i from"three";import{Object3D as n}from"three";import{AttributeVec3Node as l,AttributeVec4Node as o,NodeShaderMaterial as c,RgbNode as p,UniformFloatNode as u,UniformVec3Node as h,Vec3ExpressionNode as d,attributeVec3 as m,attributeVec4 as f,attributes as y,clamp as w,cross as g,float as b,lambertMaterial as v,length as M,log as A,normalize as E,pow as x,rgb as S,rgba as I,smoothstep as T,standardMaterial as P,textureSampler2d as C,uniforms as R,varying as G,varyingAttributes as B,varyingVec3 as k,varyingVec4 as j,vec2 as D,vec3 as F,vec4 as V}from"three-shader-graph";import{prepareClassParameters as L,prepareShaderGraphParameters as O,prepareShapeParameters as W}from"../../scene/materializer.js";import{SerializedParamType as U}from"../../scene/model.js";import{ShapeLibrary as Q}from"../../scene/objects/shapes.js";import{fragmentLinearEyeDepth as H,linearEyeDepth as N}from"../../shader-nodes/depth.js";import{particleEnergyUniformName as q,particleTimeUniformName as z,particleUniforms as J,particleVelcoityUniformName as X}from"../../shader-nodes/particle.js";import{sampleFlipbook as _}from"../../shader-nodes/texture-sequence.js";import{DefaultInitializer as K,WorldSpaceEmitterTransformInitializer as Y}from"./initializsers.js";import{DelayRate as Z,OnceRate as $}from"./rates.js";import{StretchedSprite as ee}from"./stretched-sprite.js";import{ThreeBlendingMode as te}from"./vfx-asset.js";import{VfxBehaviourLibrary as ae,VfxInitializserLibrary as re}from"./vfx-defs.js";import{MultiRenderer as se}from"./vfx-renderers.js";import{WorldCollisionBehaviour as ie}from"./vfx-collision-behaviour.js";import{getSpritePosition as ne,SpriteNodeShader as le,SpriteNodeShaderMaterial as oe}from"../../shader/sprite-shader.js";import{DecalUnlitShader as ce}from"../../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as pe}from"../../shader/builtin/decal-standard-shader.js";import{createBoundBehaviour as ue,createBoundInitializer as he}from"./vfx-binding-runtime.js";import{buildShaderGraphMaterial as de}from"../../shader/graph/index.js";import{markMaterialUniformValuesNeedUpdate as me,setMaterialUniformValuesAutoUpdate as fe}from"../../rendering/node-material-webgpu-resolver.js";import{applyMeshWorldTransformToGeometry as ye}from"./vfx-mesh-transform.js";export async function materializeVfx(t,a,r,s,l,o,c,p,u){let h=a;for(;null!=h.parent;)h=h.parent;const d=new n;d.name="particle system local",a.add(d);const m=new n;m.name="particle system world";const f=new se(m,d,i,s),y=new e;return(await Promise.all(t.vfx.emitters.slice().sort((e,t)=>(t.output.renderOrder??0)-(e.output.renderOrder??0)).map(async e=>{const t=await we(e,r,c,p,y,l,o,u,a);return t.setParentRecursive(y),t.emit()}))).forEach(e=>y.addEmitter(e)),y.addRenderer(f).emit({onEnd:()=>{}}),{container:m,system:y,dispose:()=>{m.removeFromParent(),d.removeFromParent(),f.dispose()}}}async function we(e,t,r,p,x,S,P,D,F){const L=function(e){let t;switch(e.rate.type){case"continuous":t=new Z(e.rate.delay??0,e.rate.count,e.rate.time,e.rate.duration);break;case"once":t=new $(e.rate.delay??0,e.rate.count);break;default:console.warn(`Failed to configure rate for emitter: ${JSON.stringify(e)}`),t=new s(0,1/0)}return t}(e);let O;switch(e.output.type){case"decal":O=new a(await async function(e,t,a,r,s){if("shaderGraph"===be(e)){const t=await createShaderGraphMaterial(e,"decal",a,r,s);if(null!=t){const a=new i.Mesh(new i.BoxGeometry(1,1,1),t);return Ae(a,e),a}}const n=!1!==e.unlit?new ce:new pe;n.color=new i.Color(e.color),n instanceof ce?n.intensity=e.intensity??1:n.emissiveIntensity=e.intensity??1;if(e.colorMap){const a=await t.getTexture(e.colorMap);n.colorMap=a}if(e.alphaMap){const a=await t.getTexture(e.alphaMap);n.alphaMap=a}const l=n.build();l.blending=te[e.blendingMode]??i.NormalBlending,l.transparent=!0,l.side=i.BackSide,l.depthTest=!1,null!=l&&!0===e.bloom&&(l.userData.hasBloom=!0);l.defines.IS_PARTICLE="";const o=new i.BoxGeometry(1,1,1),c=new i.Mesh(o,l);return Ae(c,e),c}(e.output,t,r,p,P));break;case"sprite":O=new a(await async function(e,t,a,r,s){let n=null;const l=be(e);"shaderGraph"===l&&(n=await createShaderGraphMaterial(e,"sprite",a,r,s));null==n&&"shader"===l&&null!=e.shader&&(n=await createShaderMaterial(e,t,s));null==n&&(n=await async function(e,t){const a=null!=e.texture?await t.getTexture(e.texture):ge,r=C(a);let s=r.sample(B.uv);e.flipbook?.enabled&&(s=_(r,y.uv,e.flipbook.columns,e.flipbook.rows,J.time,e.flipbook.fps,e.flipbook.mode));const n=new u("rotation",0),l=new h("color").rgb,o=k(new d("instanceColor")).rgb,c=N.subtract(H).divide(N);let p=J.opacity;switch(e.opacityChannel??"red"){case"none":break;case"red":p=p.multiply(s.r);break;case"alpha":p=p.multiply(s.a)}if("number"==typeof e.softness&&e.softness>0){const t=w(c,0,1e3);p=p.multiply(T(0,.2*e.softness,t))}const m=ne(n,void 0,void 0,!0),f=I(l.multiply(o).multiply(s.rgb).multiplyScalar(e.intensity??1),p);var g=new oe({color:f,emissive:f.rgb.multiplyScalar(p),transparent:!0,position:m,alphaTest:1e-4,uniforms:{color:{value:new i.Color(e.color)}}});g.alphaHash=!0,null!=g&&!0===e.bloom&&(g.userData.hasBloom=!0);return g.blending=te[e.blendingMode]??i.NormalBlending,g}(e,t));n.depthWrite=!1,Me(n,e);const o=new i.Mesh(new i.PlaneGeometry(1,1),n);return o.name="sprite",Ae(o,e),o}(e.output,t,r,p,P));break;case"stretchedSprite":O=new a(await async function(e,t){"shaderGraph"===be(e)&&console.warn("Shader graph materials are not supported for stretched sprite VFX outputs yet. Falling back to the default stretched sprite material.");const a=null!=e.texture?await t.getTexture(e.texture):ge,r=C(a).sample(B.uv),s=j(new o("particleColor")),n=s.rgb.multiply(r.rgb);let l=s.w;switch(e.opacityChannel??"red"){case"none":break;case"red":l=l.multiply(r.r);break;case"alpha":l=l.multiply(r.a)}if("number"==typeof e.softness&&e.softness>0){const t=N.subtract(H).divide(A(N)),a=w(t,0,1e3);l=l.multiply(T(0,.2*e.softness,a))}const c=m("offset"),p=f("velocity"),u=m("size"),h=p.w,d=u.x.add(u.y).multiply(.5),v=R.modelViewMatrix.multiplyVec(V(c,1)),x=R.normalMatrix.multiplyVec(p.xyz),S=E(g(v.xyz,x)).multiplyScalar(y.position.y.multiply(d)),P=x.multiplyScalar(y.position.x.add(.5).multiply(b(1).add(h.divide(M(x)))).multiply(d)),G=R.projectionMatrix.multiplyVec(V(v.xyz.add(S).subtract(P),v.w));var k=new oe({color:I(n.multiplyScalar(e.intensity??1),l),alphaTest:.1,transparent:!0,position:G,uniforms:{color:{value:new i.Color(e.color)}}});null!=k&&!0===e.bloom&&(k.userData.hasBloom=!0);k.blending=te[e.blendingMode]??i.NormalBlending;const D=new ee(new i.PlaneGeometry(1,1),k);return D.scaleFactor=e.scale,Ae(D,e),D}(e.output,t));break;case"shape":O=new a(await async function(e,t,a,r,s){if(null==e.shape)return console.log("Shape is null"),new n;const o=Q[e.shape];if(null==o)return console.error(`No shape with type ${e.shape}`),new n;const p=W(e.params??{}),u=o.geometry(p);let h=null;const m=be(e);"shaderGraph"===m&&(h=await createShaderGraphMaterial(e,"surface",a,r,s));null==h&&"shader"===m&&null!=e.shader&&(h=await createShaderMaterial(e,t,s));null==h&&(h="material"===m&&null!=e.material?Ee(await t.getMaterial(e.material)):function(){const e=G(new d("instanceColor")).rgb,t=G(new l("particleData")).x;return new c({color:v({color:e}).rgb.rgba(t),opacity:t,transparent:!0})}());Me(h,e);const f=new i.Mesh(u,h);return Ae(f,e),f}(e.output,t,r,p,P));break;case"mesh":O=new a(await async function(e,t,a,r,s){if(null==e.assetId)return console.warn("Can't use mesh as particle without asset id"),new n;const l=await t.getMesh(e.assetId),o=await t.getAsset(e.assetId),c=be(e);if("shaderGraph"===c||"shader"===c&&null!=e.shader||"material"===c&&null!=e.material){let n;"shaderGraph"===c?n=await createShaderGraphMaterial(e,"surface",a,r,s):"shader"===c&&null!=e.shader?n=await createShaderMaterial(e,t,s):"material"===c&&null!=e.material&&(n=Ee(await t.getMaterial(e.material))),n?.transparent&&(n.depthWrite=!1),null!=n&&Me(n,e),l.traverse(e=>{e instanceof i.Mesh&&null!=n&&(e.material=n)})}else{const e=[];if(null!=o.materialAssignments)for(const a of o.materialAssignments)null!=a.materialId&&l.traverse(r=>{r instanceof i.Mesh&&r.material instanceof i.Material&&r.material.color instanceof i.Color&&(r.material.name!=a.name&&null!=a.name||"#"+r.material.color.getHexString()!==a.color||e.push(t.getMaterial(a.materialId).then(e=>r.material=e)))});await Promise.all(e)}const p=[];if(l.traverse(e=>{e instanceof i.Mesh&&p.push(e)}),Ae(l,e),1===p.length){const t=p[0];return!0!==e.useLegacyTransform&&function(e){e.geometry=e.geometry.clone(),ye(e,e.geometry),e.position.set(0,0,0),e.quaternion.identity(),e.scale.set(1,1,1),e.updateMatrix(),e.matrixWorld.identity()}(t),t.removeFromParent(),t}return l}(e.output,t,r,p,P));break;case"trail":{const s="shaderGraph"===be(e.output)?await createShaderGraphMaterial(e.output,"trail",r,p,P,{trailBillboard:e.output.billboard??!1}):null;O=new a({type:"trail",taper:e.output.taper,headGeometry:null,material:s instanceof i.ShaderMaterial?s:void 0,dragTexture:!1,texture:null!=e.output.texture?await t.getTexture(e.output.texture):null,opacityChannel:e.output.opacityChannel,color:e.output.color,colorEnd:e.output.colorEnd,intensity:e.output.intensity??1,intensityEnd:e.output.intensityEnd??1,length:e.output.length,opacityStart:e.output.opacityStart,opacityEnd:e.output.opacityEnd,bloom:e.output.bloom,scrollSpeed:e.output.scrollSpeed,width:e.output.width,billboard:e.output.billboard??!1,renderOrder:e.output.renderOrder});break}default:console.error("Failed to create particly system body: "+JSON.stringify(e))}const q=new Se(F);q.parent=x,q.setRate(L),q._space=e.output.space;const z=await Promise.all(e.initializers.filter(e=>!1!==e.enabled).filter(e=>null!=re[e.type]).map(async e=>{const t=re[e.type],a=await W(e.params??{});return he(t,e.params??{},a,D)}));"world"===e.output.space&&z.push(new Y("shape"===e.output.type||"mesh"===e.output.type)),z.push(O,new K),q.addInitializers(z);const X=await Promise.all(e.behaviours.filter(e=>!1!==e.enabled).filter(e=>null!=ae[e.type]).map(async e=>{const t=ae[e.type];for(const[a,r]of Object.entries(e.params))t.parameters&&null!=t.parameters[a]&&"curve"===t.parameters[a].type&&r.type!==U.Curve&&(r.type=U.Curve);const a=await W(e.params??{},r,p);return ue(t,e.params??{},a,D)}).sort((e,t)=>e instanceof ie?1:0));X.push(new xe);for(const e of X)e instanceof ie&&(e.physics=S);q.addBehaviours(X);for(const a of e.children??[]){const e=await we(a,t,r,p,x,S,P,D,F),s=new EmitterPool(()=>{const t=e.clone();return t.onExpired=()=>{const e=q.childEmitters.findIndex(e=>e.id===t.id);-1!=e&&q.childEmitters.splice(e,1),null!=t.parentParticle&&(n.delete(t.parentParticle.id),t.parentParticle=null),s.release(t)},t}),i=q.eventDispatcher,n=new Map;q.bindEmitterEvent=!0,i.addEventListener("PARTICLE_DEAD",e=>{const t=n.get(e.id);null!=t&&(q.detachChildEmitterFromParticle(t,e),n.delete(e.id))});let l="PARTICLE_CREATED";if("spawnEvent"in a)switch(a.spawnEvent){case"collision":l="PARTICLE_COLLISION";break;case"start":l="PARTICLE_CREATED"}i.addEventListener(l,e=>{const t=s.get();t.age=0,t.totalEmitTimes=-1,t.particles.length=0,t.currentEmitTime=0,t.cID=0,t.eventDispatcher.removeAllEventListeners(),q.childEmitters.push(t),n.set(e.id,t),t.parentParticle=e,t.system=q.system,t.emit()})}return q}const ge=(new i.TextureLoader).load("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJkSURBVHjaxJeJbusgEEW94S1L//83X18M2MSuLd2pbqc4wZGqRLrKBsyZhQHny7Jk73xVL8xpVhWrcmiB5lX+6GJ5YgQ2owbAm8oIwH1VgKZUmGcRqKGGPgtEQQAzGR8hQ59fAmhJHSAagigJ4E7GPWRXOYC6owAd1JM6wDQPADyMWUqZRMqmAojHp1Vn6EQQEgUNMJLnUjMyJsM49wygBkAPw9dVFwXRkncCIIW3GRgoTQUZn6HxCMAFEFd8TwEQ78X4rHbILoAUmeT+RFG4UhQ6MiIAE4W/UsYFjuVjAIa2nIY4q1R0GFtQWG3E84lqw2GO2QOoCKBVu0BAPgDSU0eUDjjQenNkV/AW/pWChhpMTelo1a64AOKM30vk18GzTHXCNtI/Knz3DFBgsUqBGIjTInXRY1yA9xkVoqW5tVq3pDR9A0hfF5BSARmVnh7RMDCaIdcNgbPBkgzn1Bu+SfIEFSpSBmkxyrMicb0fAEuCZrWnN89veA/4XcakrPcjBWzkTuLjlbfTQPOlBhz+HwkqqPXmPQDdrQItxE1moGof1S74j/8txk8EHhTQrAE8qlwfqS5yukm1x/rAJ9Jiaa6nyATqD78aUVBhFo8b1V4DdTXdCW+IxA1zB4JhiOhZMEWO1HqnvdoHZ4FAMIhV9REF8FiUm0jsYPEJx/Fm/N8OhH90HI9YRHesWbXXZwAShU8qThe7H8YAuJmw5yOd989uRINKRTJAhoF8jbqrHKfeCYdIISZfSq26bk/K+yO3YvfKrVgiwQBHnwt8ynPB25+M8hceTt/ybPhnryJ78+tLgAEAuCFyiQgQB30AAAAASUVORK5CYII=");export async function createShaderMaterial(e,t,a){const r=a.get(e.shader);if(null==r)return console.error("No shader exists with name "+e.shader),new i.Material;const s=new r.type;"sprite"===e.type&&s instanceof le&&(s.instanced=!0);const n=await L(e.shaderParams??{},r.type,t,{getTexture:e=>t.getTexture(e.id),getMaterial:e=>t.getMaterial(e.id),getMesh:e=>t.getMesh(e.id)},void 0,void 0,void 0,void 0,void 0,s);return Object.assign(s,n),s.build()}export async function createShaderGraphMaterial(e,t,a,r,s,i={}){const n=e.shaderGraph;if("asset"!==n?.source||null==n.assetId)return console.warn(`Missing shader graph asset reference for ${e.type} VFX output`),null;const l=await a.getAsset(n.assetId),o=l?.shaderGraph;if(null==o)return console.warn(`Missing shader graph asset "${n.assetId}" for ${e.type} VFX output`),null;if(o.target!==t)return console.warn(`Shader graph "${l.name}" targets "${o.target}" but ${e.type} VFX output expects "${t}"`),null;try{const t=await O(e.shaderGraphParams??{},o,a,r,void 0,s.shaders),l=de(o,{parameters:t,trailBillboard:i.trailBillboard});return l.userData.customShaderName=`shaderGraph:${n.assetId}`,Me(l,e),l}catch(e){return console.log("Shader graph VFX runtime error: "+e,e),null}}export function createGpuSpriteShaderGraphResolver(e,t,a,r){return async s=>{const n=be(s);let l=null;if("shaderGraph"===n)l=await createShaderGraphMaterial(s,"sprite"===s.type?"sprite":"decal"===s.type?"decal":"trail"===s.type?"trail":"surface",e,t,a,"trail"===s.type?{trailBillboard:s.billboard??!1}:void 0);else if("shader"===n&&"decal"!==s.type&&null!=r)l=await createShaderMaterial(s,r,a);else if("material"!==n||"mesh"!==s.type&&"shape"!==s.type||null==s.material||null==r){if("default"===n&&"mesh"===s.type&&null!=s.assetId&&null!=r){const e=await r.getAsset(s.assetId),t=e.materialAssignments?.find(e=>null!=e.materialId);null!=t&&(l=await ve(t.materialId,r))}else if("default"===n&&"decal"===s.type&&null!=r){const e=!1!==s.unlit?new ce:new pe;e.color=new i.Color(s.color),e instanceof ce?e.intensity=s.intensity??1:e.emissiveIntensity=s.intensity??1,s.colorMap&&(e.colorMap=await r.getTexture(s.colorMap)),s.alphaMap&&(e.alphaMap=await r.getTexture(s.alphaMap)),l=e.build(),l.transparent=!0}}else l="mesh"===s.type?await ve(s.material,r):Ee(await r.getMaterial(s.material));return null==l?null:("mesh"!==s.type&&"shape"!==s.type||!l.transparent||(l.depthWrite=!1),l instanceof c?l:(console.warn(`GPU ${s.type} materials must compile to NodeShaderMaterial; using CPU fallback`),null))}}function be(e){return null!=e.materialSource?("material"!==e.materialSource||"mesh"!==e.type&&"shape"!==e.type||null!=e.material)&&("shaderGraph"!==e.materialSource||"asset"===e.shaderGraph?.source&&null!=e.shaderGraph.assetId)&&("shader"!==e.materialSource||"shader"in e&&null!=e.shader)?e.materialSource:"default":"asset"===e.shaderGraph?.source?"shaderGraph":"shader"in e&&null!=e.shader?"shader":"mesh"!==e.type&&"shape"!==e.type||null==e.material?"default":"material"}async function ve(e,t){const a=(await t.getAsset(e)).material,r=a?.shaderParams??{},s=a?.params??{},n=r.color?.value??s.color??"#ffffff",l=r.opacity?.value??s.opacity??1,o=r.intensity?.value??s.intensity??1,p=r.map?.value??s.map,u=r.alphaMap?.value??s.alphaMap;let h=J.color.rgb.multiply(S(new i.Color(n))).multiplyScalar(b(o)),d=J.opacity.multiply(b(l));if(null!=p){const e=C(await t.getTexture(p)).sample(B.uv);h=h.multiply(e.rgb),d=d.multiply(e.a)}null!=u&&(d=d.multiply(C(await t.getTexture(u)).sample(B.uv).r));const m=new c({color:h.rgba(d),opacity:d,transparent:!0===a?.transparent||l<1||null!=u});return m.blending=te[a?.blending]??i.NormalBlending,m.alphaTest=a?.alphaTest??0,m.side=a?.side??i.FrontSide,m.transparent&&(m.depthWrite=!1),m}function Me(e,t){null!=e&&(fe(e,!1),"bloom"in t&&!0===t.bloom&&(e.userData.hasBloom=!0),"sprite"===t.type?(e.blending=te[t.blendingMode]??i.NormalBlending,!0===t.lockY&&e instanceof i.ShaderMaterial&&(e.defines??(e.defines={}),e.defines.LOCK_Y_AXIS="")):"decal"===t.type?(e.blending=te[t.blendingMode]??i.NormalBlending,e.transparent=!0,e.side=i.BackSide,e.depthTest=!1,e instanceof i.ShaderMaterial&&(e.defines??(e.defines={}),e.defines.IS_PARTICLE="")):"shape"!==t.type&&"mesh"!==t.type||e instanceof i.ShaderMaterial&&(e.defines??(e.defines={}),e.defines.IS_PARTICLE=""))}function Ae(e,t){const a=t.renderOrder;null!=a&&e.traverse(e=>e.renderOrder=a)}function Ee(e){const t=G(new d("instanceColor")).rgb;let a,r=G(new l("particleData")).x;if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial){let s=t.multiply(S(e.color));null!=e.map&&(s=s.multiply(C(e.map).sample(B.uv).rgb)),null!=e.alphaMap&&(r=r.multiply(C(e.alphaMap).sample(B.uv).r)),e instanceof i.MeshStandardMaterial?a=new c({color:P({color:s,emissive:S(e.emissive),emissiveIntensity:b(e.emissiveIntensity),roughness:e.roughness,metalness:e.metalness}).rgb.rgba(r),emissive:S(e.emissive).multiplyScalar(e.emissiveIntensity),transparent:e.transparent,opacity:r,alphaTest:e.alphaTest}):e instanceof i.MeshLambertMaterial?a=new c({color:v({color:s}).rgb.rgba(r),emissive:S(e.emissive).multiplyScalar(e.emissiveIntensity),transparent:e.transparent,opacity:r,alphaTest:e.alphaTest}):e instanceof i.MeshBasicMaterial&&(a=new c({color:s.rgb.rgba(r),emissive:s.rgb,transparent:e.transparent,opacity:r,alphaTest:e.alphaTest}))}else e instanceof c&&(a=e.clone(),a.defines.IS_PARTICLE="");return null!=a&&(!0===e.userData?.hasBloom&&null!=a&&(a.userData.hasBloom=!0),a.side=e.side,a.transparent=e.transparent),a??e}class xe extends t{initialize(e){e.body instanceof i.Object3D&&e.body.traverse(e=>{if(e instanceof i.Mesh){const t=e.material;t instanceof c&&(null!=t.uniforms[q]||null!=t.uniforms[z]||t.uniforms[X])}})}mutate(e,t,a){this.energize(e,t),e.target instanceof n&&e.target.traverse(t=>{if(t instanceof i.Mesh){const a=t.material;if(a instanceof c){let t=!1;null!=a.uniforms[q]&&(a.uniforms[q].value=this.energy,t=!0),null!=a.uniforms[z]&&(a.uniforms[z].value=e.age,t=!0),null!=a.uniforms[X]&&(a.uniforms[X].value=e.velocity,t=!0),t&&me(a)}}})}}class Se extends r{constructor(e){super(),this.transformRoot=e,this.childEmitters=[],this.bindEmitterEvent=!1,this.onExpired=()=>{}}clearParticlesRecursive(){let e=this.childEmitters.length;for(;e--;){const t=this.childEmitters[e];t.stopEmit(),t.clearParticlesRecursive(),t.onExpired()}this.childEmitters.length=0;let t=this.particles.length;for(;t--;){const e=this.particles[t];this.system?.dispatch("PARTICLE_DEAD",e),this.bindEmitterEvent&&this.dispatch("PARTICLE_DEAD",e),null!=this.system?this.system.pool.expire(e.reset()):e.reset()}this.particles.length=0}detachChildEmitterFromParticle(e,t){this.copyPositionToChildSpace(e,t.position),e.parentParticle=null,e.stopEmit()}update(e){if(!this.isEmitting&&0===this.particles.length&&0===this.childEmitters.length)return;this.age+=e,(this.dead||this.age>=this.life)&&this.destroy(),this.isEmitting&&this.generate(e),this.integrate(e);let t=this.particles.length;for(;t--;){const e=this.particles[t];e.dead&&(this.system&&this.system.dispatch("PARTICLE_DEAD",e),this.bindEmitterEvent&&this.dispatch("PARTICLE_DEAD",e),this.system.pool.expire(e.reset()),this.particles.splice(t,1))}this.updateEmitterBehaviours(e),this.updateChildren(e),this.isEmitting||0!==this.particles.length||0!==this.childEmitters.length||this.onExpired()}updateChildren(e){for(const t of this.childEmitters)null!=t.parentParticle&&this.copyPositionToChildSpace(t,t.parentParticle.position),t.update(e)}copyPositionToChildSpace(e,t){const a=this._space??"world",r=e._space??"world";a!==r&&null!=this.transformRoot?(Ie.copy(t),"local"===a&&"world"===r?Ie.applyMatrix4(this.transformRoot.matrixWorld):"world"===a&&"local"===r&&(Te.copy(this.transformRoot.matrixWorld).invert(),Ie.applyMatrix4(Te)),e.position.copy(Ie)):e.position.copy(t)}clone(){const e=new Se(this.transformRoot);return e.setRate(this.rate.clone()),e.behaviours=this.behaviours,e.initializers=this.initializers,e._space=this._space,e.body=this.body,e.parent=this.parent,e.system=this.system,e}setParentRecursive(e){this.system=e,this.childEmitters.forEach(t=>t.setParentRecursive(e))}}const Ie=new i.Vector3,Te=new i.Matrix4;export class EmitterPool{constructor(e){this.creator=e,this.instances=[]}get(){0==this.instances.length&&this.instances.push(this.creator());return this.instances.pop()}release(e){this.instances.push(e)}dispose(){this.instances.length=0}}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,6 +1,6 @@
1
1
  import * as THREE from 'three';
2
- import type { Vec4Node, Vec3Node } from 'three-shader-graph';
3
- import { NodeShaderMaterial, type CompiledNodeWebGpuFullscreen, type WebGpuMaterialUniform, type WebGpuMaterialUniformValue, type WebGpuMaterialVertexAttribute, type WgslGraphTextureBinding } from 'three-shader-graph';
2
+ import type { Vec4Node } from 'three-shader-graph';
3
+ import { NodeShaderMaterial, type CompiledNodeWebGpuFullscreen, type WebGpuMaterialUniform, type WebGpuMaterialUniformValue, type WebGpuMaterialVertexAttribute, type WgslGraphTextureBinding, Vec3Node } from 'three-shader-graph';
4
4
  type ResolvedWebGpuMaterial = THREE.Material & {
5
5
  readonly vertexShader: string;
6
6
  readonly fragmentShader: string;
@@ -51,7 +51,7 @@ export interface ResolvedWorldEnvironment {
51
51
  * material only while the experimental backend is drawing.
52
52
  */
53
53
  export declare function createNodeMaterialSignature(material: NodeShaderMaterial): string;
54
- export type NodeMaterialWebGpuDrawStage = 'opaque' | 'late';
54
+ export type NodeMaterialWebGpuDrawStage = 'opaque' | 'late' | 'outline';
55
55
  type MRTOutputsResolverFn = (mat: NodeShaderMaterial, drawStage?: NodeMaterialWebGpuDrawStage) => (Vec3Node | Vec4Node)[] | undefined;
56
56
  export declare class NodeMaterialWebGpuResolver {
57
57
  private readonly webGpu;
@@ -61,6 +61,7 @@ export declare class NodeMaterialWebGpuResolver {
61
61
  private readonly mappedMaterialsCache;
62
62
  private readonly mappedMaterialsSignatures;
63
63
  private readonly observedNodeMaterials;
64
+ private readonly outlineMaterials;
64
65
  private readonly worldEnvironmentMaterials;
65
66
  private worldEnvironment;
66
67
  private worldEnvironmentTexture;
@@ -69,6 +70,7 @@ export declare class NodeMaterialWebGpuResolver {
69
70
  constructor(webGpu: NodeMaterialWebGpuModule, mrtResolver?: MRTOutputsResolverFn);
70
71
  setWorldEnvironment(environment: ResolvedWorldEnvironment | null): void;
71
72
  resolve(material: THREE.Material, drawStage?: NodeMaterialWebGpuDrawStage): ResolvedWebGpuMaterial | undefined;
73
+ private getOrCreateOutlineMaterial;
72
74
  compileFullscreen(material: NodeShaderMaterial): CompiledNodeWebGpuFullscreen;
73
75
  private getOrCreateMappedNodeMaterial;
74
76
  /**
@@ -1,4 +1,4 @@
1
- import*as e from"three";import{compileNodeWebGpuFullscreen as a,compileNodeShaderMaterialForWebGpu as t,NodeShaderMaterial as n,webGpuRendererBindings as i,textureSampler2d as s}from"three-shader-graph";import{StandardShader as o}from"../shader/builtin/standard-shader.js";import{LambertShader as r}from"../shader/builtin/lambert-shader.js";import{ToonShader as l}from"../shader/builtin/toon-shader.js";import{UnlitShader as u}from"../shader/builtin/unlit-shader.js";import{SpriteShader as p}from"../shader/sprite-shader.js";import{elapsedTimeUniformName as m}from"../shader-nodes/time.js";import{depthUniformName as c,farUniformName as h,nearUniformName as d,resolutionUniformName as f,sceneNormalUniformName as M}from"../shader-nodes/depth.js";import{sceneMapUniformName as v}from"../shader-nodes/scene-sample.js";const y={...i,uniformExpressions:{...i.uniformExpressions,[m]:{type:"float",expression:"rendererElapsedTime()"},[d]:{type:"float",expression:"rendererCameraNear()"},[h]:{type:"float",expression:"rendererCameraFar()"},[f]:{type:"vec2",expression:"rendererViewportSize()"}},sceneTextures:{[v]:{semantic:"sceneColor",sampleType:"float"},[c]:{semantic:"sceneDepth",sampleType:"depth"}},attributes:{material:{shaderLocation:6,format:"float32x4",defaultValue:[0,0,0,0]},material2:{shaderLocation:7,format:"float32x4",defaultValue:[0,0,0,0]},hole:{shaderLocation:8,format:"float32",defaultValue:[0]},offset:{shaderLocation:9,format:"float32x3",stepMode:"instance",defaultValue:[0,0,0]},velocity:{shaderLocation:10,format:"float32x4",stepMode:"instance",defaultValue:[0,0,0,0]},size:{shaderLocation:11,format:"float32x3",stepMode:"instance",defaultValue:[0,0,0]},rotation:{shaderLocation:12,format:"float32",stepMode:"instance",defaultValue:[0]},particleData:{shaderLocation:13,format:"float32x3",stepMode:"instance",defaultValue:[1,1,0]},particleColor:{shaderLocation:14,format:"float32x4",stepMode:"instance",defaultValue:[1,1,1,1]}}};export function setMaterialUniformValuesAutoUpdate(e,a){e.uniformValuesAutoUpdate=a}export function markMaterialUniformValuesNeedUpdate(e){const a=e;"uniformValuesNeedsUpdate"in a?a.uniformValuesNeedsUpdate=!0:a.uniformValuesAutoVersion=(a.uniformValuesAutoVersion??0)+1}function g(e){return!1!==e.uniformValuesAutoUpdate}function V(e){return e.uniformValuesAutoVersion??0}export function withThreeDefaultVertexAttributeValues(e){return e.map(e=>"uv1"===e.name&&null==e.defaultValue?{...e,defaultValue:[0,0]}:e)}const w=new WeakMap,I=new WeakMap;export function createNodeMaterialSignature(e){const a=I.get(e);if(null!=a)return a;const t=JSON.stringify({version:e.version,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader,alphaTest:e.alphaTest,alphaToCoverage:e.alphaToCoverage,blending:e.blending,colorWrite:e.colorWrite,depthFunc:e.depthFunc,depthTest:e.depthTest,depthWrite:e.depthWrite,polygonOffset:e.polygonOffset,polygonOffsetFactor:e.polygonOffsetFactor,polygonOffsetUnits:e.polygonOffsetUnits,premultipliedAlpha:e.premultipliedAlpha,side:e.side,stencilWrite:e.stencilWrite,transparent:e.transparent,wireframe:e.wireframe});return I.set(e,t),t}export class NodeMaterialWebGpuResolver{constructor(e,a){this.webGpu=e,this.mrtResolver=a,this.cache=new WeakMap,this.failedSignatures=new WeakMap,this.mappedMaterialsCache=new WeakMap,this.mappedMaterialsSignatures=new WeakMap,this.observedNodeMaterials=new Map,this.worldEnvironmentMaterials=new WeakSet,this.worldEnvironment=null,this.worldEnvironmentTexture=null,this.worldEnvironmentIntensity=0,this.worldEnvironmentRevision=0,this.cacheValues=new Set}setWorldEnvironment(e){const a=e?.texture??null,t=e?.intensity??0;if(this.worldEnvironmentTexture!==a||this.worldEnvironmentIntensity!==t){if(this.worldEnvironmentTexture!==a)this.worldEnvironmentRevision++;else if(null!=e)for(const e of this.cacheValues)e.inheritsWorldEnvironment&&null!=e.material.uniforms.envMapIntensity&&(e.material.uniforms.envMapIntensity.value=t,e.material.uniformValuesNeedsUpdate=!0);this.worldEnvironment=e,this.worldEnvironmentTexture=a,this.worldEnvironmentIntensity=t}}resolve(e,a=void 0){let i,s=!1;if(e instanceof n)i=e,this.observeNodeMaterial(i);else{const a=this.getOrCreateMappedNodeMaterial(e);if(null==a)return;i=a,s=!0}i.visible=e.visible,s&&(i.userData.receiveDecals=e.userData.receiveDecals);const o=a??"default",r=this.cache.get(i),l=r?.get(o);if(s&&null!=l&&l.sourceVersion===e.version&&l.worldEnvironmentRevision===this.worldEnvironmentRevision){const a=g(e),t=V(e);return l.material.uniformValuesAutoUpdate=a,this.syncInheritedWorldEnvironmentSource(i,l),a||l.sourceUniformValuesAutoVersion!==t?(W(e,i),l.compiled.syncLiveUniforms(l.material.uniforms),x(i,l.material.uniforms),T(i,l.material),l.sourceUniformValuesAutoVersion=t,a||(l.material.uniformValuesNeedsUpdate=!0),l.material):l.material}if(!s&&null!=l&&l.sourceVersion===e.version&&l.worldEnvironmentRevision===this.worldEnvironmentRevision&&E(i,l.compiled))return this.syncInheritedWorldEnvironmentSource(i,l),S(i,l),l.material;s&&W(e,i);const u=this.prepareWorldEnvironment(i),p=this.getNodeMaterialSignature(i,u);if(l?.signature===p&&E(i,l.compiled))return s?(l.material.uniformValuesAutoUpdate=g(e),l.compiled.syncLiveUniforms(l.material.uniforms),x(i,l.material.uniforms),T(i,l.material),l.sourceUniformValuesAutoVersion=V(e),l.material.uniformValuesAutoUpdate||(l.material.uniformValuesNeedsUpdate=!0)):S(i,l,!0),l.sourceVersion=e.version,l.worldEnvironmentRevision=this.worldEnvironmentRevision,l.material;try{const n=this.mrtResolver?.(i,a),m=t(i,y,n),c=new this.webGpu.WGSLShaderMaterial({vertexShader:m.vertexShader,fragmentShader:m.fragmentShader,depthVertexShader:m.depthVertexShader,depthFragmentShader:m.depthFragmentShader,pointShadowVertexShader:m.pointShadowVertexShader,pointShadowFragmentShader:m.pointShadowFragmentShader,uniforms:m.uniforms,textures:m.textures,sceneTextures:m.sceneTextures,graphTextures:m.graphTextures,vertexAttributes:withThreeDefaultVertexAttributeValues(m.vertexAttributes),uniformValuesAutoUpdate:s?g(e):i.uniformValuesAutoUpdate,transparent:m.renderState?.transparent,alphaTest:m.renderState?.alphaTest,depthTest:m.renderState?.depthTest,depthWrite:m.renderState?.depthWrite,side:m.renderState?.side,wireframe:i.wireframe});c.uniformValuesAutoUpdate=s?g(e):i.uniformValuesAutoUpdate,function(e,a){if(null==e)return;Object.assign(a,e)}(m.renderState,c),null!=l&&(l.material.dispose(),this.cacheValues.delete(l));const h={signature:p,compiled:m,material:c,inheritsWorldEnvironment:u,sourceVersion:e.version,sourceUniformValuesAutoVersion:s?V(e):i.uniformValuesAutoVersion,worldEnvironmentRevision:this.worldEnvironmentRevision},d=r??new Map;return d.set(o,h),this.cache.set(i,d),this.cacheValues.add(h),x(i,c.uniforms),T(i,c),c}catch(e){let a=this.failedSignatures.get(i);if(null==a&&(a=new Map,this.failedSignatures.set(i,a)),a.get(o)!==p){a.set(o,p);const t=e instanceof Error?e.message:String(e),n=i.name||i.uuid;console.warn(`[Hology WebGPU experiment] Falling back for NodeShaderMaterial "${n}": ${t}`,{material:i,error:e})}return}}compileFullscreen(e){const t=a({color:e.outputColor,wgslBindings:{...y,uniformExpressions:{},graphTextures:{...y.graphTextures,[M]:{resource:"hologyNormalRoughness",dimension:"2d",sampleType:"float",sampler:"filtering"}}}}),n=t.syncLiveUniforms;return{...t,syncLiveUniforms(a){n(a),x(e,a)}}}getOrCreateMappedNodeMaterial(a){const t=function(a){const t=[a.vertexColors,a.transparent,a.alphaTest,a.side,a.depthTest,a.depthWrite,a.wireframe??!1];a instanceof e.MeshStandardMaterial||a instanceof e.MeshPhysicalMaterial?t.push(a.map?a.map.uuid:null,a.normalMap?a.normalMap.uuid:null,a.roughnessMap?a.roughnessMap.uuid:null,a.metalnessMap?a.metalnessMap.uuid:null,a.aoMap?a.aoMap.uuid:null,a.emissiveMap?a.emissiveMap.uuid:null,a.lightMap?a.lightMap.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.envMap?a.envMap.uuid:null):a instanceof e.MeshLambertMaterial?t.push(a.map?a.map.uuid:null,a.normalMap?a.normalMap.uuid:null,a.aoMap?a.aoMap.uuid:null,a.emissiveMap?a.emissiveMap.uuid:null,a.lightMap?a.lightMap.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.envMap?a.envMap.uuid:null):a instanceof e.MeshToonMaterial?t.push(a.map?a.map.uuid:null,a.normalMap?a.normalMap.uuid:null,a.aoMap?a.aoMap.uuid:null,a.emissiveMap?a.emissiveMap.uuid:null,a.lightMap?a.lightMap.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.gradientMap?a.gradientMap.uuid:null):a instanceof e.MeshBasicMaterial?t.push(a.map?a.map.uuid:null,a.aoMap?a.aoMap.uuid:null,a.lightMap?a.lightMap.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.envMap?a.envMap.uuid:null):a instanceof e.MeshPhongMaterial?t.push(a.map?a.map.uuid:null,a.normalMap?a.normalMap.uuid:null,a.aoMap?a.aoMap.uuid:null,a.emissiveMap?a.emissiveMap.uuid:null,a.lightMap?a.lightMap.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.envMap?a.envMap.uuid:null):a instanceof e.SpriteMaterial&&t.push(a.map?a.map.uuid:null,a.alphaMap?a.alphaMap.uuid:null,a.sizeAttenuation);return t.join(",")}(a),n=this.mappedMaterialsCache.get(a),i=this.mappedMaterialsSignatures.get(a);if(null!=n&&i===t)return n;if(null!=n){n.dispose();const e=this.cache.get(n);if(null!=e){for(const a of e.values())a.material.dispose(),this.cacheValues.delete(a);this.cache.delete(n)}}const m=function(a){if(a instanceof e.SpriteMaterial){const e=new p;e.color=a.color,e.opacity=a.opacity,e.rotation=a.rotation,e.screenSpaceSize=a.sizeAttenuation?0:1,e.alphaTest=a.alphaTest,a.map&&(e.map=a.map),a.alphaMap&&(e.alphaMap=a.alphaMap);const t=e.build();return t.transparent=a.transparent,t.side=a.side,t.depthTest=a.depthTest,t.depthWrite=a.depthWrite,t}if(a instanceof e.MeshStandardMaterial||a instanceof e.MeshPhysicalMaterial){const e=new o;e.color=a.color,e.opacity=a.opacity,e.roughness=a.roughness,e.metalness=a.metalness,e.vertexColor=a.vertexColors,a.map&&(e.map=s(a.map)),a.normalMap&&(e.normalMap=s(a.normalMap),e.normalScale=a.normalScale),a.roughnessMap&&(e.roughnessMap=s(a.roughnessMap)),a.metalnessMap&&(e.metalnessMap=s(a.metalnessMap)),a.aoMap&&(e.aoMap=s(a.aoMap),e.aoMapIntensity=a.aoMapIntensity),a.emissiveMap&&(e.emissiveMap=s(a.emissiveMap)),a.lightMap&&(e.lightMap=s(a.lightMap),e.lightMapIntensity=a.lightMapIntensity),a.alphaMap&&(e.alphaMap=s(a.alphaMap)),e.emissive=a.emissive,e.emissiveIntensity=a.emissiveIntensity,e.envMap=a.envMap,e.envMapIntensity=a.envMapIntensity,e.alphaTest=a.alphaTest;const t=e.build();return t.transparent=a.transparent,t.side=a.side,t.depthTest=a.depthTest,t.depthWrite=a.depthWrite,t.wireframe=a.wireframe,t}if(a instanceof e.MeshLambertMaterial){const e=new r;e.color=a.color,e.opacity=a.opacity,e.vertexColor=a.vertexColors,a.map&&(e.map=s(a.map)),a.normalMap&&(e.normalMap=s(a.normalMap),e.normalScale=a.normalScale),a.aoMap&&(e.aoMap=s(a.aoMap),e.aoMapIntensity=a.aoMapIntensity),a.emissiveMap&&(e.emissiveMap=s(a.emissiveMap)),a.lightMap&&(e.lightMap=s(a.lightMap),e.lightMapIntensity=a.lightMapIntensity),a.alphaMap&&(e.alphaMap=s(a.alphaMap)),e.emissive=a.emissive,e.emissiveIntensity=a.emissiveIntensity,e.envMap=a.envMap,e.alphaTest=a.alphaTest;const t=e.build();return t.transparent=a.transparent,t.side=a.side,t.depthTest=a.depthTest,t.depthWrite=a.depthWrite,t.wireframe=a.wireframe,t}if(a instanceof e.MeshToonMaterial){const e=new l;e.color=a.color,e.opacity=a.opacity,e.vertexColor=a.vertexColors,a.map&&(e.map=s(a.map)),a.normalMap&&(e.normalMap=s(a.normalMap),e.normalScale=a.normalScale),a.aoMap&&(e.aoMap=s(a.aoMap),e.aoMapIntensity=a.aoMapIntensity),a.emissiveMap&&(e.emissiveMap=s(a.emissiveMap)),a.lightMap&&(e.lightMap=s(a.lightMap),e.lightMapIntensity=a.lightMapIntensity),a.alphaMap&&(e.alphaMap=s(a.alphaMap)),e.emissive=a.emissive,e.emissiveIntensity=a.emissiveIntensity,e.alphaTest=a.alphaTest;const t=e.build();return t.transparent=a.transparent,t.side=a.side,t.depthTest=a.depthTest,t.depthWrite=a.depthWrite,t.wireframe=a.wireframe,t}if(a instanceof e.MeshBasicMaterial||a instanceof e.LineBasicMaterial){const t=new u;t.color=a.color,t.opacity=a.opacity,t.vertexColor=a.vertexColors,a instanceof e.MeshBasicMaterial&&(a.map&&(t.map=s(a.map)),a.aoMap&&(t.aoMap=s(a.aoMap),t.aoMapIntensity=a.aoMapIntensity),a.lightMap&&(t.lightMap=s(a.lightMap),t.lightMapIntensity=a.lightMapIntensity),a.alphaMap&&(t.alphaMap=s(a.alphaMap)),t.envMap=a.envMap),t.alphaTest=a.alphaTest;const n=t.build();return n.transparent=a.transparent,n.side=a.side,n.depthTest=a.depthTest,n.depthWrite=a.depthWrite,n.wireframe=a instanceof e.MeshBasicMaterial&&a.wireframe,n}if(a instanceof e.MeshPhongMaterial){const e=new o;e.color=a.color,e.opacity=a.opacity,e.roughness=Math.max(0,1-a.shininess/100),e.metalness=0,e.vertexColor=a.vertexColors,a.map&&(e.map=s(a.map)),a.normalMap&&(e.normalMap=s(a.normalMap),e.normalScale=a.normalScale),a.aoMap&&(e.aoMap=s(a.aoMap),e.aoMapIntensity=a.aoMapIntensity),a.emissiveMap&&(e.emissiveMap=s(a.emissiveMap)),a.lightMap&&(e.lightMap=s(a.lightMap),e.lightMapIntensity=a.lightMapIntensity),a.alphaMap&&(e.alphaMap=s(a.alphaMap)),e.emissive=a.emissive,e.emissiveIntensity=a.emissiveIntensity,e.envMap=a.envMap,e.alphaTest=a.alphaTest;const t=e.build();return t.transparent=a.transparent,t.side=a.side,t.depthTest=a.depthTest,t.depthWrite=a.depthWrite,t.wireframe=a.wireframe,t}return null}(a);return null==m?null:(m.wireframe=a.wireframe??!1,this.mappedMaterialsCache.set(a,m),this.mappedMaterialsSignatures.set(a,t),a.addEventListener("dispose",()=>{const e=this.mappedMaterialsCache.get(a);if(null!=e){e.dispose(),this.mappedMaterialsCache.delete(a),this.mappedMaterialsSignatures.delete(a);const t=this.cache.get(e);if(null!=t){for(const e of t.values())e.material.dispose(),this.cacheValues.delete(e);this.cache.delete(e)}}}),m)}canResolve(e){return null!=this.resolve(e)}dispose(){for(const[e,a]of this.observedNodeMaterials)e.removeEventListener("dispose",a);this.observedNodeMaterials.clear();for(const e of this.cacheValues)e.material.dispose();this.cacheValues.clear()}syncInheritedWorldEnvironmentSource(e,a){a.inheritsWorldEnvironment&&null!=this.worldEnvironment&&(e.uniforms.envMap.value=this.worldEnvironment.texture,e.uniforms.envMapIntensity.value=this.worldEnvironment.intensity)}getNodeMaterialSignature(e,a){const t=`${createNodeMaterialSignature(e)}|receiveDecals:${!1!==e.userData.receiveDecals}`;return a?`${t}|worldEnvironment:${this.worldEnvironmentRevision}`:t}prepareWorldEnvironment(a){var t,n,i;return null!=a.envMap?(this.worldEnvironmentMaterials.has(a)&&(a.uniforms.envMap={value:a.envMap},a.uniforms.envMapIntensity={value:1},a.uniforms.envMapRotation={value:new e.Matrix3},this.worldEnvironmentMaterials.delete(a)),!1):null==this.worldEnvironment?(this.worldEnvironmentMaterials.has(a)&&(delete a.uniforms.envMap,delete a.uniforms.envMapIntensity,delete a.uniforms.envMapRotation,this.worldEnvironmentMaterials.delete(a)),!1):((t=a.uniforms).envMap??(t.envMap={value:this.worldEnvironment.texture}),a.uniforms.envMap.value=this.worldEnvironment.texture,(n=a.uniforms).envMapIntensity??(n.envMapIntensity={value:this.worldEnvironment.intensity}),a.uniforms.envMapIntensity.value=this.worldEnvironment.intensity,(i=a.uniforms).envMapRotation??(i.envMapRotation={value:new e.Matrix3}),this.worldEnvironmentMaterials.add(a),!0)}observeNodeMaterial(e){if(this.observedNodeMaterials.has(e))return;const a=()=>{e.removeEventListener("dispose",a),this.observedNodeMaterials.delete(e);const t=this.cache.get(e);if(null!=t){for(const e of t.values())e.material.dispose(),this.cacheValues.delete(e);this.cache.delete(e)}this.failedSignatures.delete(e),I.delete(e)};this.observedNodeMaterials.set(e,a),e.addEventListener("dispose",a)}}function S(e,a,t=!1){const n=a.material;n.uniformValuesAutoUpdate=e.uniformValuesAutoUpdate,(t||e.uniformValuesAutoUpdate||a.sourceUniformValuesAutoVersion!==e.uniformValuesAutoVersion)&&(a.compiled.syncLiveUniforms(n.uniforms),x(e,n.uniforms),T(e,n),a.sourceUniformValuesAutoVersion=e.uniformValuesAutoVersion,n.uniformValuesAutoUpdate||(n.uniformValuesNeedsUpdate=!0))}function x(e,a){let t=w.get(a);if(null==t){t=[];for(const e in a){const n=a[e],i=n.value,s=!0===i?.isVector2?2:!0===i?.isVector3?3:!0===i?.isVector4?4:!0===i?.isColor?5:0;t.push({name:e,target:n,copyKind:s})}w.set(a,t)}const n=e.uniforms;for(let e=0;e<t.length;e++){const a=t[e],i=n[a.name];if(null==i)continue;const s=i.value,o=a.target.value;if(s!==o){if(0!==a.copyKind){const e=s,t=o;if((2===a.copyKind?!0===e?.isVector2:3===a.copyKind?!0===e?.isVector3:4===a.copyKind?!0===e?.isVector4:!0===e?.isColor)&&"function"==typeof t?.copy){t.copy(s);continue}}a.target.value=s}}}function T(a,t){const n=a.uniforms.envMapIntensity,i=t.uniforms.envMapIntensity;null!=n&&null!=i&&(i.value=n.value);const s=a.uniforms.envMapRotation?.value,o=t.uniforms.envMapRotation?.value;s instanceof e.Matrix3&&o instanceof e.Matrix3&&o.copy(s)}function E(e,a){for(const t in a.textures){const n=a.textures[t],i=e.uniforms[t]?.value;if(C(i)&&i!==n)return!1}return!0}function C(e){return!0===e?.isTexture}function W(a,t){if(a instanceof e.SpriteMaterial){const n=t;t.uniforms.color&&(t.uniforms.color.value instanceof e.Vector3?t.uniforms.color.value.setFromColor(a.color):t.uniforms.color.value instanceof e.Color&&t.uniforms.color.value.copy(a.color)),t.uniforms.opacity&&(t.uniforms.opacity.value=a.opacity),n.rotation=a.rotation,n.screenSpaceSize=a.sizeAttenuation?0:1}else a instanceof e.MeshStandardMaterial||a instanceof e.MeshPhysicalMaterial?(t.uniforms.color&&(t.uniforms.color.value instanceof e.Vector3?t.uniforms.color.value.setFromColor(a.color):t.uniforms.color.value instanceof e.Color&&t.uniforms.color.value.copy(a.color)),t.uniforms.opacity&&(t.uniforms.opacity.value=a.opacity),t.uniforms.roughness&&(t.uniforms.roughness.value=a.roughness),t.uniforms.metalness&&(t.uniforms.metalness.value=a.metalness),t.uniforms.emissive&&(t.uniforms.emissive.value instanceof e.Vector3?t.uniforms.emissive.value.setFromColor(a.emissive):t.uniforms.emissive.value instanceof e.Color&&t.uniforms.emissive.value.copy(a.emissive)),t.uniforms.emissiveIntensity&&(t.uniforms.emissiveIntensity.value=a.emissiveIntensity),t.uniforms.normalScale&&a.normalScale&&(t.uniforms.normalScale.value=a.normalScale.x),t.uniforms.aoMapIntensity&&(t.uniforms.aoMapIntensity.value=a.aoMapIntensity),t.uniforms.lightMapIntensity&&(t.uniforms.lightMapIntensity.value=a.lightMapIntensity),t.uniforms.envMapIntensity&&(t.uniforms.envMapIntensity.value=a.envMapIntensity)):a instanceof e.MeshLambertMaterial||a instanceof e.MeshToonMaterial?(t.uniforms.color&&(t.uniforms.color.value instanceof e.Vector3?t.uniforms.color.value.setFromColor(a.color):t.uniforms.color.value instanceof e.Color&&t.uniforms.color.value.copy(a.color)),t.uniforms.opacity&&(t.uniforms.opacity.value=a.opacity),t.uniforms.emissive&&(t.uniforms.emissive.value instanceof e.Vector3?t.uniforms.emissive.value.setFromColor(a.emissive):t.uniforms.emissive.value instanceof e.Color&&t.uniforms.emissive.value.copy(a.emissive)),t.uniforms.emissiveIntensity&&(t.uniforms.emissiveIntensity.value=a.emissiveIntensity),t.uniforms.normalScale&&a.normalScale&&(t.uniforms.normalScale.value=a.normalScale.x),t.uniforms.aoMapIntensity&&(t.uniforms.aoMapIntensity.value=a.aoMapIntensity),t.uniforms.lightMapIntensity&&(t.uniforms.lightMapIntensity.value=a.lightMapIntensity)):a instanceof e.MeshBasicMaterial||a instanceof e.LineBasicMaterial?(t.uniforms.color&&(t.uniforms.color.value instanceof e.Vector3?t.uniforms.color.value.setFromColor(a.color):t.uniforms.color.value instanceof e.Color&&t.uniforms.color.value.copy(a.color)),t.uniforms.opacity&&(t.uniforms.opacity.value=a.opacity),a instanceof e.MeshBasicMaterial&&(t.uniforms.aoMapIntensity&&(t.uniforms.aoMapIntensity.value=a.aoMapIntensity),t.uniforms.lightMapIntensity&&(t.uniforms.lightMapIntensity.value=a.lightMapIntensity))):a instanceof e.MeshPhongMaterial&&(t.uniforms.color&&(t.uniforms.color.value instanceof e.Vector3?t.uniforms.color.value.setFromColor(a.color):t.uniforms.color.value instanceof e.Color&&t.uniforms.color.value.copy(a.color)),t.uniforms.opacity&&(t.uniforms.opacity.value=a.opacity),t.uniforms.roughness&&(t.uniforms.roughness.value=Math.max(0,1-a.shininess/100)),t.uniforms.emissive&&(t.uniforms.emissive.value instanceof e.Vector3?t.uniforms.emissive.value.setFromColor(a.emissive):t.uniforms.emissive.value instanceof e.Color&&t.uniforms.emissive.value.copy(a.emissive)),t.uniforms.emissiveIntensity&&(t.uniforms.emissiveIntensity.value=a.emissiveIntensity),t.uniforms.normalScale&&a.normalScale&&(t.uniforms.normalScale.value=a.normalScale.x),t.uniforms.aoMapIntensity&&(t.uniforms.aoMapIntensity.value=a.aoMapIntensity),t.uniforms.lightMapIntensity&&(t.uniforms.lightMapIntensity.value=a.lightMapIntensity))}/*
1
+ import*as e from"three";import{compileNodeWebGpuFullscreen as t,compileNodeShaderMaterialForWebGpu as a,NodeShaderMaterial as i,webGpuRendererBindings as n,textureSampler2d as s,float as o,length as r,max as l,rgba as u,isWgslCompiler as p,isWgslFragmentCompiler as m,sqrt as c,normalize as d,transformed as h,uniformFloat as f,uniforms as M,vec4 as v,Vec3Node as y}from"three-shader-graph";import{StandardShader as g}from"../shader/builtin/standard-shader.js";import{LambertShader as V}from"../shader/builtin/lambert-shader.js";import{ToonShader as w}from"../shader/builtin/toon-shader.js";import{UnlitShader as S}from"../shader/builtin/unlit-shader.js";import{SpriteShader as I}from"../shader/sprite-shader.js";import{elapsedTimeUniformName as x}from"../shader-nodes/time.js";import{depthUniformName as T,farUniformName as E,nearUniformName as b,resolutionUniformName as C,sceneNormalUniformName as W}from"../shader-nodes/depth.js";import{sceneMapUniformName as U}from"../shader-nodes/scene-sample.js";const A={...n,uniformExpressions:{...n.uniformExpressions,ambientLightColor:{type:"vec3",expression:"rendererAmbientLight()"},[x]:{type:"float",expression:"rendererElapsedTime()"},[b]:{type:"float",expression:"rendererCameraNear()"},[E]:{type:"float",expression:"rendererCameraFar()"},[C]:{type:"vec2",expression:"rendererViewportSize()"}},sceneTextures:{[U]:{semantic:"sceneColor",sampleType:"float"},[T]:{semantic:"sceneDepth",sampleType:"depth"}},attributes:{material:{shaderLocation:6,format:"float32x4",defaultValue:[0,0,0,0]},material2:{shaderLocation:7,format:"float32x4",defaultValue:[0,0,0,0]},hole:{shaderLocation:8,format:"float32",defaultValue:[0]},offset:{shaderLocation:9,format:"float32x3",stepMode:"instance",defaultValue:[0,0,0]},velocity:{shaderLocation:10,format:"float32x4",stepMode:"instance",defaultValue:[0,0,0,0]},size:{shaderLocation:11,format:"float32x3",stepMode:"instance",defaultValue:[0,0,0]},rotation:{shaderLocation:12,format:"float32",stepMode:"instance",defaultValue:[0]},particleData:{shaderLocation:13,format:"float32x3",stepMode:"instance",defaultValue:[1,1,0]},particleColor:{shaderLocation:14,format:"float32x4",stepMode:"instance",defaultValue:[1,1,1,1]}}};class N extends y{constructor(e){super(),this.fallback=e}compile(e){if(!p(e))return{out:e.get(this.fallback)};if(m(e))throw new Error("OutlineLocalPositionNode can only be used in the vertex stage");const t=`outline_local_position_${e.variable()}`;return{chunk:`\n#ifdef USE_SKINNING\n let ${t} = rendererSkinPosition(input.position, input.skinIndex, input.skinWeight).xyz;\n#else\n let ${t} = input.position;\n#endif`,out:t}}}class k extends y{constructor(e){super(),this.fallback=e}compile(e){if(!p(e))return{out:e.get(this.fallback)};if(m(e))throw new Error("OutlineLocalNormalNode can only be used in the vertex stage");const t=`outline_local_normal_${e.variable()}`;return{chunk:`\n#ifdef USE_SKINNING\n let ${t} = rendererSkinNormal(input.normal, input.skinIndex, input.skinWeight);\n#else\n let ${t} = input.normal;\n#endif`,out:t}}}export function setMaterialUniformValuesAutoUpdate(e,t){e.uniformValuesAutoUpdate=t}export function markMaterialUniformValuesNeedUpdate(e){const t=e;"uniformValuesNeedsUpdate"in t?t.uniformValuesNeedsUpdate=!0:t.uniformValuesAutoVersion=(t.uniformValuesAutoVersion??0)+1}function L(e){return!1!==e.uniformValuesAutoUpdate}function R(e){return e.uniformValuesAutoVersion??0}export function withThreeDefaultVertexAttributeValues(e){return e.map(e=>"uv1"===e.name&&null==e.defaultValue?{...e,defaultValue:[0,0]}:e)}const F=new WeakMap,D=new WeakMap;export function createNodeMaterialSignature(e){const t=D.get(e);if(null!=t)return t;const a=JSON.stringify({version:e.version,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader,alphaTest:e.alphaTest,alphaToCoverage:e.alphaToCoverage,blending:e.blending,colorWrite:e.colorWrite,depthFunc:e.depthFunc,depthTest:e.depthTest,depthWrite:e.depthWrite,polygonOffset:e.polygonOffset,polygonOffsetFactor:e.polygonOffsetFactor,polygonOffsetUnits:e.polygonOffsetUnits,premultipliedAlpha:e.premultipliedAlpha,side:e.side,stencilWrite:e.stencilWrite,transparent:e.transparent,wireframe:e.wireframe});return D.set(e,a),a}export class NodeMaterialWebGpuResolver{constructor(e,t){this.webGpu=e,this.mrtResolver=t,this.cache=new WeakMap,this.failedSignatures=new WeakMap,this.mappedMaterialsCache=new WeakMap,this.mappedMaterialsSignatures=new WeakMap,this.observedNodeMaterials=new Map,this.outlineMaterials=new WeakMap,this.worldEnvironmentMaterials=new WeakSet,this.worldEnvironment=null,this.worldEnvironmentTexture=null,this.worldEnvironmentIntensity=0,this.worldEnvironmentRevision=0,this.cacheValues=new Set}setWorldEnvironment(e){const t=e?.texture??null,a=e?.intensity??0;if(this.worldEnvironmentTexture!==t||this.worldEnvironmentIntensity!==a){if(this.worldEnvironmentTexture!==t)this.worldEnvironmentRevision++;else if(null!=e)for(const e of this.cacheValues)e.inheritsWorldEnvironment&&null!=e.material.uniforms.envMapIntensity&&(e.material.uniforms.envMapIntensity.value=a,e.material.uniformValuesNeedsUpdate=!0);this.worldEnvironment=e,this.worldEnvironmentTexture=t,this.worldEnvironmentIntensity=a}}resolve(e,t=void 0){let n,s=!1;if(e instanceof i)n=e,this.observeNodeMaterial(n);else{const t=this.getOrCreateMappedNodeMaterial(e);if(null==t)return;n=t,s=!0}if("outline"===t){if(null==n.outputAlbedo)return;s&&B(e,n),n.userData.outlineParameters=e.userData?.outlineParameters,n=this.getOrCreateOutlineMaterial(n),s=!1}n.visible=e.visible,s&&(n.userData.receiveDecals=e.userData.receiveDecals);const o=t??"default",r=this.cache.get(n),l=r?.get(o);if(s&&null!=l&&l.sourceVersion===e.version&&l.worldEnvironmentRevision===this.worldEnvironmentRevision){const t=L(e),a=R(e);return l.material.uniformValuesAutoUpdate=t,this.syncInheritedWorldEnvironmentSource(n,l),t||l.sourceUniformValuesAutoVersion!==a?(B(e,n),l.compiled.syncLiveUniforms(l.material.uniforms),j(n,l.material.uniforms),P(n,l.material),l.sourceUniformValuesAutoVersion=a,t||(l.material.uniformValuesNeedsUpdate=!0),l.material):l.material}if(!s&&null!=l&&l.sourceVersion===e.version&&l.worldEnvironmentRevision===this.worldEnvironmentRevision&&$(n,l.compiled))return this.syncInheritedWorldEnvironmentSource(n,l),O(n,l),l.material;s&&B(e,n);const u=this.prepareWorldEnvironment(n),p=this.getNodeMaterialSignature(n,u);if(l?.signature===p&&$(n,l.compiled))return s?(l.material.uniformValuesAutoUpdate=L(e),l.compiled.syncLiveUniforms(l.material.uniforms),j(n,l.material.uniforms),P(n,l.material),l.sourceUniformValuesAutoVersion=R(e),l.material.uniformValuesAutoUpdate||(l.material.uniformValuesNeedsUpdate=!0)):O(n,l,!0),l.sourceVersion=e.version,l.worldEnvironmentRevision=this.worldEnvironmentRevision,l.material;try{const i=this.mrtResolver?.(n,t),m=a(n,A,i),c=new this.webGpu.WGSLShaderMaterial({vertexShader:m.vertexShader,fragmentShader:m.fragmentShader,depthVertexShader:m.depthVertexShader,depthFragmentShader:m.depthFragmentShader,pointShadowVertexShader:m.pointShadowVertexShader,pointShadowFragmentShader:m.pointShadowFragmentShader,uniforms:m.uniforms,textures:m.textures,sceneTextures:m.sceneTextures,graphTextures:m.graphTextures,vertexAttributes:withThreeDefaultVertexAttributeValues(m.vertexAttributes),uniformValuesAutoUpdate:s?L(e):n.uniformValuesAutoUpdate,transparent:m.renderState?.transparent,alphaTest:m.renderState?.alphaTest,depthTest:m.renderState?.depthTest,depthWrite:m.renderState?.depthWrite,side:m.renderState?.side,wireframe:n.wireframe});c.uniformValuesAutoUpdate=s?L(e):n.uniformValuesAutoUpdate,function(e,t){if(null==e)return;Object.assign(t,e)}(m.renderState,c),null!=l&&(l.material.dispose(),this.cacheValues.delete(l));const d={signature:p,compiled:m,material:c,inheritsWorldEnvironment:u,sourceVersion:e.version,sourceUniformValuesAutoVersion:s?R(e):n.uniformValuesAutoVersion,worldEnvironmentRevision:this.worldEnvironmentRevision},h=r??new Map;return h.set(o,d),this.cache.set(n,h),this.cacheValues.add(d),j(n,c.uniforms),P(n,c),c}catch(e){let t=this.failedSignatures.get(n);if(null==t&&(t=new Map,this.failedSignatures.set(n,t)),t.get(o)!==p){t.set(o,p);const a=e instanceof Error?e.message:String(e),i=n.name||n.uuid;console.warn(`[Hology WebGPU experiment] Falling back for NodeShaderMaterial "${i}": ${a}`,{material:n,error:e})}return}}getOrCreateOutlineMaterial(t){let a=this.outlineMaterials.get(t);if(null==a){const n=t.nodeMaterialDefinition,s=t.outputAlbedo;if(null==s)throw new Error("Cannot derive an outline material without an albedo output");const p=f("outlineThickness",.003),m=f("outlineDarkening",.65),y=f("outlineAlpha",1),g=new N(h.position.xyz),V=new k(h.normal),w=n.transform?.multiplyVec(v(g,1))??v(g,1),S=M.modelViewMatrix.multiplyVec(w),I=d(M.normalMatrix.multiplyVec(V)),x=c(l(r(S.xyz),o(1e-4))).multiply(.5),T=S.xyz.add(I.multiplyScalar(p.multiply(x))),E=M.projectionMatrix.multiplyVec(S),b=M.projectionMatrix.multiplyVec(v(T,1)),C=(n.position??E).add(b.subtract(E)),W=u(s.multiplyScalar(o(1).subtract(m)),t.outputOpacity.multiply(y));a=new i({color:W,position:C,opacity:t.outputOpacity,discard:n.discard,alphaTest:t.alphaTest,transparent:!0,fog:!1,outputEncoding:n.outputEncoding,uniforms:n.uniforms,uniformNodes:n.uniformNodes}),a.side=e.BackSide,a.depthTest=!0,a.depthWrite=!0,this.outlineMaterials.set(t,a)}const n=t.userData?.outlineParameters;a.uniforms.outlineThickness.value=n?.thickness??.003,a.uniforms.outlineDarkening.value=e.MathUtils.clamp(n?.darkening??.65,0,1),a.uniforms.outlineAlpha.value=e.MathUtils.clamp(n?.alpha??t.opacity,0,1),a.userData.outlineSource=t;for(const e in t.uniforms)null!=a.uniforms[e]&&(a.uniforms[e].value=t.uniforms[e].value);return a}compileFullscreen(e){const a=t({color:e.outputColor,wgslBindings:{...A,uniformExpressions:{},graphTextures:{...A.graphTextures,[W]:{resource:"hologyNormalRoughness",dimension:"2d",sampleType:"float",sampler:"filtering"}}}}),i=a.syncLiveUniforms;return{...a,syncLiveUniforms(t){i(t),j(e,t)}}}getOrCreateMappedNodeMaterial(t){const a=function(t){const a=[t.vertexColors,t.transparent,t.alphaTest,t.side,t.depthTest,t.depthWrite,t.wireframe??!1];t instanceof e.MeshStandardMaterial||t instanceof e.MeshPhysicalMaterial?a.push(t.map?t.map.uuid:null,t.normalMap?t.normalMap.uuid:null,t.roughnessMap?t.roughnessMap.uuid:null,t.metalnessMap?t.metalnessMap.uuid:null,t.aoMap?t.aoMap.uuid:null,t.emissiveMap?t.emissiveMap.uuid:null,t.lightMap?t.lightMap.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.envMap?t.envMap.uuid:null):t instanceof e.MeshLambertMaterial?a.push(t.map?t.map.uuid:null,t.normalMap?t.normalMap.uuid:null,t.aoMap?t.aoMap.uuid:null,t.emissiveMap?t.emissiveMap.uuid:null,t.lightMap?t.lightMap.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.envMap?t.envMap.uuid:null):t instanceof e.MeshToonMaterial?a.push(t.map?t.map.uuid:null,t.normalMap?t.normalMap.uuid:null,t.aoMap?t.aoMap.uuid:null,t.emissiveMap?t.emissiveMap.uuid:null,t.lightMap?t.lightMap.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.gradientMap?t.gradientMap.uuid:null):t instanceof e.MeshBasicMaterial?a.push(t.map?t.map.uuid:null,t.aoMap?t.aoMap.uuid:null,t.lightMap?t.lightMap.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.envMap?t.envMap.uuid:null):t instanceof e.MeshPhongMaterial?a.push(t.map?t.map.uuid:null,t.normalMap?t.normalMap.uuid:null,t.aoMap?t.aoMap.uuid:null,t.emissiveMap?t.emissiveMap.uuid:null,t.lightMap?t.lightMap.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.envMap?t.envMap.uuid:null):t instanceof e.SpriteMaterial&&a.push(t.map?t.map.uuid:null,t.alphaMap?t.alphaMap.uuid:null,t.sizeAttenuation);return a.join(",")}(t),i=this.mappedMaterialsCache.get(t),n=this.mappedMaterialsSignatures.get(t);if(null!=i&&n===a)return i;if(null!=i){i.dispose();const e=this.cache.get(i);if(null!=e){for(const t of e.values())t.material.dispose(),this.cacheValues.delete(t);this.cache.delete(i)}}const o=function(t){if(t instanceof e.SpriteMaterial){const e=new I;e.color=t.color,e.opacity=t.opacity,e.rotation=t.rotation,e.screenSpaceSize=t.sizeAttenuation?0:1,e.alphaTest=t.alphaTest,t.map&&(e.map=t.map),t.alphaMap&&(e.alphaMap=t.alphaMap);const a=e.build();return a.transparent=t.transparent,a.side=t.side,a.depthTest=t.depthTest,a.depthWrite=t.depthWrite,a}if(t instanceof e.MeshStandardMaterial||t instanceof e.MeshPhysicalMaterial){const e=new g;e.color=t.color,e.opacity=t.opacity,e.roughness=t.roughness,e.metalness=t.metalness,e.vertexColor=t.vertexColors,t.map&&(e.map=s(t.map)),t.normalMap&&(e.normalMap=s(t.normalMap),e.normalScale=t.normalScale),t.roughnessMap&&(e.roughnessMap=s(t.roughnessMap)),t.metalnessMap&&(e.metalnessMap=s(t.metalnessMap)),t.aoMap&&(e.aoMap=s(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=s(t.emissiveMap)),t.lightMap&&(e.lightMap=s(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=s(t.alphaMap)),e.emissive=t.emissive,e.emissiveIntensity=t.emissiveIntensity,e.envMap=t.envMap,e.envMapIntensity=t.envMapIntensity,e.alphaTest=t.alphaTest;const a=e.build();return a.transparent=t.transparent,a.side=t.side,a.depthTest=t.depthTest,a.depthWrite=t.depthWrite,a.wireframe=t.wireframe,a}if(t instanceof e.MeshLambertMaterial){const e=new V;e.color=t.color,e.opacity=t.opacity,e.vertexColor=t.vertexColors,t.map&&(e.map=s(t.map)),t.normalMap&&(e.normalMap=s(t.normalMap),e.normalScale=t.normalScale),t.aoMap&&(e.aoMap=s(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=s(t.emissiveMap)),t.lightMap&&(e.lightMap=s(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=s(t.alphaMap)),e.emissive=t.emissive,e.emissiveIntensity=t.emissiveIntensity,e.envMap=t.envMap,e.alphaTest=t.alphaTest;const a=e.build();return a.transparent=t.transparent,a.side=t.side,a.depthTest=t.depthTest,a.depthWrite=t.depthWrite,a.wireframe=t.wireframe,a}if(t instanceof e.MeshToonMaterial){const e=new w;e.color=t.color,e.opacity=t.opacity,e.vertexColor=t.vertexColors,t.map&&(e.map=s(t.map)),t.normalMap&&(e.normalMap=s(t.normalMap),e.normalScale=t.normalScale),t.aoMap&&(e.aoMap=s(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=s(t.emissiveMap)),t.lightMap&&(e.lightMap=s(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=s(t.alphaMap)),e.emissive=t.emissive,e.emissiveIntensity=t.emissiveIntensity,e.alphaTest=t.alphaTest;const a=e.build();return a.transparent=t.transparent,a.side=t.side,a.depthTest=t.depthTest,a.depthWrite=t.depthWrite,a.wireframe=t.wireframe,a}if(t instanceof e.MeshBasicMaterial||t instanceof e.LineBasicMaterial){const a=new S;a.color=t.color,a.opacity=t.opacity,a.vertexColor=t.vertexColors,t instanceof e.MeshBasicMaterial&&(t.map&&(a.map=s(t.map)),t.aoMap&&(a.aoMap=s(t.aoMap),a.aoMapIntensity=t.aoMapIntensity),t.lightMap&&(a.lightMap=s(t.lightMap),a.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(a.alphaMap=s(t.alphaMap)),a.envMap=t.envMap),a.alphaTest=t.alphaTest;const i=a.build();return i.transparent=t.transparent,i.side=t.side,i.depthTest=t.depthTest,i.depthWrite=t.depthWrite,i.wireframe=t instanceof e.MeshBasicMaterial&&t.wireframe,i}if(t instanceof e.MeshPhongMaterial){const e=new g;e.color=t.color,e.opacity=t.opacity,e.roughness=Math.max(0,1-t.shininess/100),e.metalness=0,e.vertexColor=t.vertexColors,t.map&&(e.map=s(t.map)),t.normalMap&&(e.normalMap=s(t.normalMap),e.normalScale=t.normalScale),t.aoMap&&(e.aoMap=s(t.aoMap),e.aoMapIntensity=t.aoMapIntensity),t.emissiveMap&&(e.emissiveMap=s(t.emissiveMap)),t.lightMap&&(e.lightMap=s(t.lightMap),e.lightMapIntensity=t.lightMapIntensity),t.alphaMap&&(e.alphaMap=s(t.alphaMap)),e.emissive=t.emissive,e.emissiveIntensity=t.emissiveIntensity,e.envMap=t.envMap,e.alphaTest=t.alphaTest;const a=e.build();return a.transparent=t.transparent,a.side=t.side,a.depthTest=t.depthTest,a.depthWrite=t.depthWrite,a.wireframe=t.wireframe,a}return null}(t);return null==o?null:(o.wireframe=t.wireframe??!1,this.mappedMaterialsCache.set(t,o),this.mappedMaterialsSignatures.set(t,a),t.addEventListener("dispose",()=>{const e=this.mappedMaterialsCache.get(t);if(null!=e){e.dispose(),this.mappedMaterialsCache.delete(t),this.mappedMaterialsSignatures.delete(t);const a=this.cache.get(e);if(null!=a){for(const e of a.values())e.material.dispose(),this.cacheValues.delete(e);this.cache.delete(e)}}}),o)}canResolve(e){return null!=this.resolve(e)}dispose(){for(const[e,t]of this.observedNodeMaterials)e.removeEventListener("dispose",t);this.observedNodeMaterials.clear();for(const e of this.cacheValues)e.material.dispose();this.cacheValues.clear()}syncInheritedWorldEnvironmentSource(e,t){t.inheritsWorldEnvironment&&null!=this.worldEnvironment&&(e.uniforms.envMap.value=this.worldEnvironment.texture,e.uniforms.envMapIntensity.value=this.worldEnvironment.intensity)}getNodeMaterialSignature(e,t){const a=`${createNodeMaterialSignature(e)}|receiveDecals:${!1!==e.userData.receiveDecals}`;return t?`${a}|worldEnvironment:${this.worldEnvironmentRevision}`:a}prepareWorldEnvironment(t){var a,i,n;return null!=t.envMap?(this.worldEnvironmentMaterials.has(t)&&(t.uniforms.envMap={value:t.envMap},t.uniforms.envMapIntensity={value:1},t.uniforms.envMapRotation={value:new e.Matrix3},this.worldEnvironmentMaterials.delete(t)),!1):null==this.worldEnvironment?(this.worldEnvironmentMaterials.has(t)&&(delete t.uniforms.envMap,delete t.uniforms.envMapIntensity,delete t.uniforms.envMapRotation,this.worldEnvironmentMaterials.delete(t)),!1):((a=t.uniforms).envMap??(a.envMap={value:this.worldEnvironment.texture}),t.uniforms.envMap.value=this.worldEnvironment.texture,(i=t.uniforms).envMapIntensity??(i.envMapIntensity={value:this.worldEnvironment.intensity}),t.uniforms.envMapIntensity.value=this.worldEnvironment.intensity,(n=t.uniforms).envMapRotation??(n.envMapRotation={value:new e.Matrix3}),this.worldEnvironmentMaterials.add(t),!0)}observeNodeMaterial(e){if(this.observedNodeMaterials.has(e))return;const t=()=>{e.removeEventListener("dispose",t),this.observedNodeMaterials.delete(e);const a=this.cache.get(e);if(null!=a){for(const e of a.values())e.material.dispose(),this.cacheValues.delete(e);this.cache.delete(e)}const i=this.outlineMaterials.get(e);if(null!=i){const t=this.cache.get(i);if(null!=t){for(const e of t.values())e.material.dispose(),this.cacheValues.delete(e);this.cache.delete(i)}this.failedSignatures.delete(i),D.delete(i),i.dispose(),this.outlineMaterials.delete(e)}this.failedSignatures.delete(e),D.delete(e)};this.observedNodeMaterials.set(e,t),e.addEventListener("dispose",t)}}function O(e,t,a=!1){const i=t.material;i.uniformValuesAutoUpdate=e.uniformValuesAutoUpdate,(a||e.uniformValuesAutoUpdate||t.sourceUniformValuesAutoVersion!==e.uniformValuesAutoVersion)&&(t.compiled.syncLiveUniforms(i.uniforms),j(e,i.uniforms),P(e,i),t.sourceUniformValuesAutoVersion=e.uniformValuesAutoVersion,i.uniformValuesAutoUpdate||(i.uniformValuesNeedsUpdate=!0))}function j(e,t){let a=F.get(t);if(null==a){a=[];for(const e in t){const i=t[e],n=i.value,s=!0===n?.isVector2?2:!0===n?.isVector3?3:!0===n?.isVector4?4:!0===n?.isColor?5:0;a.push({name:e,target:i,copyKind:s})}F.set(t,a)}const i=e.uniforms;for(let e=0;e<a.length;e++){const t=a[e],n=i[t.name];if(null==n)continue;const s=n.value,o=t.target.value;if(s!==o){if(0!==t.copyKind){const e=s,a=o;if((2===t.copyKind?!0===e?.isVector2:3===t.copyKind?!0===e?.isVector3:4===t.copyKind?!0===e?.isVector4:!0===e?.isColor)&&"function"==typeof a?.copy){a.copy(s);continue}}t.target.value=s}}}function P(t,a){const i=t.uniforms.envMapIntensity,n=a.uniforms.envMapIntensity;null!=i&&null!=n&&(n.value=i.value);const s=t.uniforms.envMapRotation?.value,o=a.uniforms.envMapRotation?.value;s instanceof e.Matrix3&&o instanceof e.Matrix3&&o.copy(s)}function $(e,t){for(const a in t.textures){const i=t.textures[a],n=e.uniforms[a]?.value;if(z(n)&&n!==i)return!1}return!0}function z(e){return!0===e?.isTexture}function B(t,a){if(t instanceof e.SpriteMaterial){const i=a;a.uniforms.color&&(a.uniforms.color.value instanceof e.Vector3?a.uniforms.color.value.setFromColor(t.color):a.uniforms.color.value instanceof e.Color&&a.uniforms.color.value.copy(t.color)),a.uniforms.opacity&&(a.uniforms.opacity.value=t.opacity),i.rotation=t.rotation,i.screenSpaceSize=t.sizeAttenuation?0:1}else t instanceof e.MeshStandardMaterial||t instanceof e.MeshPhysicalMaterial?(a.uniforms.color&&(a.uniforms.color.value instanceof e.Vector3?a.uniforms.color.value.setFromColor(t.color):a.uniforms.color.value instanceof e.Color&&a.uniforms.color.value.copy(t.color)),a.uniforms.opacity&&(a.uniforms.opacity.value=t.opacity),a.uniforms.roughness&&(a.uniforms.roughness.value=t.roughness),a.uniforms.metalness&&(a.uniforms.metalness.value=t.metalness),a.uniforms.emissive&&(a.uniforms.emissive.value instanceof e.Vector3?a.uniforms.emissive.value.setFromColor(t.emissive):a.uniforms.emissive.value instanceof e.Color&&a.uniforms.emissive.value.copy(t.emissive)),a.uniforms.emissiveIntensity&&(a.uniforms.emissiveIntensity.value=t.emissiveIntensity),a.uniforms.normalScale&&t.normalScale&&(a.uniforms.normalScale.value=t.normalScale.x),a.uniforms.aoMapIntensity&&(a.uniforms.aoMapIntensity.value=t.aoMapIntensity),a.uniforms.lightMapIntensity&&(a.uniforms.lightMapIntensity.value=t.lightMapIntensity),a.uniforms.envMapIntensity&&(a.uniforms.envMapIntensity.value=t.envMapIntensity)):t instanceof e.MeshLambertMaterial||t instanceof e.MeshToonMaterial?(a.uniforms.color&&(a.uniforms.color.value instanceof e.Vector3?a.uniforms.color.value.setFromColor(t.color):a.uniforms.color.value instanceof e.Color&&a.uniforms.color.value.copy(t.color)),a.uniforms.opacity&&(a.uniforms.opacity.value=t.opacity),a.uniforms.emissive&&(a.uniforms.emissive.value instanceof e.Vector3?a.uniforms.emissive.value.setFromColor(t.emissive):a.uniforms.emissive.value instanceof e.Color&&a.uniforms.emissive.value.copy(t.emissive)),a.uniforms.emissiveIntensity&&(a.uniforms.emissiveIntensity.value=t.emissiveIntensity),a.uniforms.normalScale&&t.normalScale&&(a.uniforms.normalScale.value=t.normalScale.x),a.uniforms.aoMapIntensity&&(a.uniforms.aoMapIntensity.value=t.aoMapIntensity),a.uniforms.lightMapIntensity&&(a.uniforms.lightMapIntensity.value=t.lightMapIntensity)):t instanceof e.MeshBasicMaterial||t instanceof e.LineBasicMaterial?(a.uniforms.color&&(a.uniforms.color.value instanceof e.Vector3?a.uniforms.color.value.setFromColor(t.color):a.uniforms.color.value instanceof e.Color&&a.uniforms.color.value.copy(t.color)),a.uniforms.opacity&&(a.uniforms.opacity.value=t.opacity),t instanceof e.MeshBasicMaterial&&(a.uniforms.aoMapIntensity&&(a.uniforms.aoMapIntensity.value=t.aoMapIntensity),a.uniforms.lightMapIntensity&&(a.uniforms.lightMapIntensity.value=t.lightMapIntensity))):t instanceof e.MeshPhongMaterial&&(a.uniforms.color&&(a.uniforms.color.value instanceof e.Vector3?a.uniforms.color.value.setFromColor(t.color):a.uniforms.color.value instanceof e.Color&&a.uniforms.color.value.copy(t.color)),a.uniforms.opacity&&(a.uniforms.opacity.value=t.opacity),a.uniforms.roughness&&(a.uniforms.roughness.value=Math.max(0,1-t.shininess/100)),a.uniforms.emissive&&(a.uniforms.emissive.value instanceof e.Vector3?a.uniforms.emissive.value.setFromColor(t.emissive):a.uniforms.emissive.value instanceof e.Color&&a.uniforms.emissive.value.copy(t.emissive)),a.uniforms.emissiveIntensity&&(a.uniforms.emissiveIntensity.value=t.emissiveIntensity),a.uniforms.normalScale&&t.normalScale&&(a.uniforms.normalScale.value=t.normalScale.x),a.uniforms.aoMapIntensity&&(a.uniforms.aoMapIntensity.value=t.aoMapIntensity),a.uniforms.lightMapIntensity&&(a.uniforms.lightMapIntensity.value=t.lightMapIntensity))}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */