@hology/core 0.0.161 → 0.0.162

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{BackSide as e,Color as t,ShaderMaterial as i,UniformsLib as n,UniformsUtils as a,Object3D as l,Mesh as o,InstancedMesh as r,BatchedMesh as s,Vector3 as c}from"three";import{glslFunction as p,NodeShaderMaterial as u,Vec4Node as d,uniforms as m,transformed as v,neg as f,uniformFloat as h,uniformVec3 as _,vec3 as g,rgba as x,vec4 as k,negVec3 as A,ifDefApply as b,BooleanExpression as y,select as w,attributes as M}from"three-shader-graph";export class OutlineEffect{constructor(i,n={}){this.applied=new WeakSet,this.enabled=!0;const a=void 0!==n.defaultThickness?n.defaultThickness:.003,l=((new t).fromArray(void 0!==n.defaultColor?n.defaultColor:[0,0,0]),void 0!==n.defaultAlpha?n.defaultAlpha:1),o=void 0!==n.defaultKeepAlive&&n.defaultKeepAlive,r={},s={};["#include <common>","#include <uv_pars_vertex>","#include <displacementmap_pars_vertex>","#include <fog_pars_vertex>","#include <morphtarget_pars_vertex>","#include <skinning_pars_vertex>","#include <logdepthbuf_pars_vertex>","#include <clipping_planes_pars_vertex>","uniform float outlineThickness;","vec4 calculateOutline( vec4 pos, vec3 normal, vec4 skinned ) {","\tfloat thickness = outlineThickness;","\tconst float ratio = 1.0;","\tvec4 pos2 = projectionMatrix * modelViewMatrix * vec4( skinned.xyz + normal, 1.0 );"," float viewDistance = length((modelViewMatrix * vec4(skinned.xyz, 1.0)).xyz);"," float scale = pow(viewDistance, 0.5); // sqrt, or any exponent","\tvec4 norm = normalize( pos - pos2 );","\treturn pos + norm * thickness * scale * ratio;","}","void main() {","\t#include <uv_vertex>","\t#include <beginnormal_vertex>","\t#include <morphnormal_vertex>","\t#include <skinbase_vertex>","\t#include <skinnormal_vertex>","\t#include <begin_vertex>","\t#include <morphtarget_vertex>","\t#include <skinning_vertex>","\t#include <displacementmap_vertex>","\t#include <project_vertex>","\tvec3 outlineNormal = - objectNormal;","\tgl_Position = calculateOutline( gl_Position, outlineNormal, vec4( transformed, 1.0 ) );","\t#include <logdepthbuf_vertex>","\t#include <clipping_planes_vertex>","\t#include <fog_vertex>","}"].join("\n"),["#include <common>","#include <fog_pars_fragment>","#include <logdepthbuf_pars_fragment>","#include <clipping_planes_pars_fragment>","uniform vec3 outlineColor;","uniform float outlineAlpha;","void main() {","\t#include <clipping_planes_fragment>","\t#include <logdepthbuf_fragment>","\tgl_FragColor = vec4( outlineColor, outlineAlpha );","\t#include <tonemapping_fragment>","\t#include <colorspace_fragment>","\t#include <fog_fragment>","\t#include <premultiplied_alpha_fragment>","}"].join("\n");function f(t){const i=m.projectionMatrix.multiply(m.modelViewMatrix).multiplyVec(v.position);let n=A(M.normal);n=b("DOUBLE_SIDED",n,e=>w(new y("gl_FrontFacing"),e,e.multiplyScalar(-1)));const o=h("outlineThickness",a),r=_("outlineColor",new c(0,0,0)),s=h("outlineAlpha",l),f=p(d,{pos:i,normal:n,skinned:v.position,outlineThickness:o},"\n\t\t\t\t\tfloat thickness = outlineThickness;\n\t\t\t\t\tconst float ratio = 1.0; // TODO: support outline thickness ratio for each vertex\n\t\t\t\t\tvec4 pos2 = projectionMatrix * modelViewMatrix * vec4( skinned.xyz + normal, 1.0 );\n\t\t\t\t\tfloat viewDistance = length((modelViewMatrix * vec4(skinned.xyz, 1.0)).xyz);\n\t\t\t\t\tfloat scale = pow(viewDistance, 0.5); // sqrt, or any exponent\n\t\t\t\t\t// NOTE: subtract pos2 from pos because BackSide objectNormal is negative\n\t\t\t\t\tvec4 norm = normalize( pos - pos2 );\n\t\t\t\t\treturn pos + norm * thickness * scale * ratio;\n\t\t\t"),g=x(r,s),D=[g,k(0),k(0)],T="number"==typeof t.userData.mrtOutputs&&t.userData.mrtOutputs>1,O=new u({position:f,outputs:T?D:void 0,color:T?void 0:g});return O.side=e,O.depthTest=!0,O.depthWrite=!0,O.transparent=!0,O}this.createMaterial=f,this.getOutlineMaterial=function(e){const t=function(e){let t=r[e.uuid];return void 0===t&&(t={material:f(e),used:!0,keepAlive:o,count:0},r[e.uuid]=t),t.used=!0,t.material}(e);return s[t.uuid]=e,function(e,t){Array.isArray(t)&&(t=t[0]);if("invisible"===e.name)return;const i=t.userData.outlineParameters;e.fog=t.fog,e.toneMapped=t.toneMapped,e.premultipliedAlpha=t.premultipliedAlpha,e.displacementMap=t.displacementMap,void 0!==i?(!1===t.visible?e.visible=!1:e.visible=void 0===i.visible||i.visible,e.transparent=void 0!==i.alpha&&i.alpha<1||t.transparent,void 0!==i.keepAlive&&(r[t.uuid].keepAlive=i.keepAlive)):(e.transparent=t.transparent,e.visible=t.visible);!0!==t.wireframe&&!1!==t.depthTest||(e.visible=!1);t.clippingPlanes&&(e.clipping=!0,e.clippingPlanes=t.clippingPlanes,e.clipIntersection=t.clipIntersection,e.clipShadows=t.clipShadows);e.version=t.version}(t,e),t},this.updateUniforms=function(e,t){const i=t.userData.outlineParameters;e.uniforms.outlineAlpha.value=t.opacity,void 0!==i&&(void 0!==i.thickness&&(e.uniforms.outlineThickness.value=i.thickness),void 0!==i.color&&e.uniforms.outlineColor.value.fromArray(i.color),void 0!==i.alpha&&(e.uniforms.outlineAlpha.value=i.alpha)),t.displacementMap&&(e.uniforms.displacementMap.value=t.displacementMap,e.uniforms.displacementScale.value=t.displacementScale,e.uniforms.displacementBias.value=t.displacementBias)}}apply(e){if(!(e instanceof o)||e instanceof s||e instanceof r)return;if(this.applied.has(e))return;this.applied.add(e);const t=e.onAfterRender;e.onAfterRender=(i,n,a,l,o,r)=>{t(i,n,a,l,o);let s=!1;if(Array.isArray(o)?s=o.some(e=>e&&e.userData&&e.userData.outlineParameters):o&&o.userData&&o.userData.outlineParameters&&(s=!0),!s)return;const c=e.material,p=this.getOutlineMaterial(c);e.material=p,this.updateUniforms(p,o),i.renderBufferDirect(a,n,l,p,e,r),e.material=c}}}/*
1
+ import{BackSide as e,Color as t,ShaderMaterial as i,UniformsLib as n,UniformsUtils as a,Object3D as l,Mesh as r,InstancedMesh as o,BatchedMesh as s,Vector3 as c}from"three";import{glslFunction as p,NodeShaderMaterial as u,Vec4Node as d,uniforms as m,transformed as v,neg as f,uniformFloat as h,uniformVec3 as _,vec3 as g,rgba as x,vec4 as k,negVec3 as A,ifDefApply as b,BooleanExpression as y,select as w,attributes as M}from"three-shader-graph";export class OutlineEffect{constructor(i,n={}){this.applied=new WeakSet,this.enabled=!0;const a=void 0!==n.defaultThickness?n.defaultThickness:.003,l=((new t).fromArray(void 0!==n.defaultColor?n.defaultColor:[0,0,0]),void 0!==n.defaultAlpha?n.defaultAlpha:1),r=void 0!==n.defaultKeepAlive&&n.defaultKeepAlive,o={},s={};["#include <common>","#include <uv_pars_vertex>","#include <displacementmap_pars_vertex>","#include <fog_pars_vertex>","#include <morphtarget_pars_vertex>","#include <skinning_pars_vertex>","#include <logdepthbuf_pars_vertex>","#include <clipping_planes_pars_vertex>","uniform float outlineThickness;","vec4 calculateOutline( vec4 pos, vec3 normal, vec4 skinned ) {","\tfloat thickness = outlineThickness;","\tconst float ratio = 1.0;","\tvec4 pos2 = projectionMatrix * modelViewMatrix * vec4( skinned.xyz + normal, 1.0 );"," float viewDistance = length((modelViewMatrix * vec4(skinned.xyz, 1.0)).xyz);"," float scale = pow(viewDistance, 0.5); // sqrt, or any exponent","\tvec4 norm = normalize( pos - pos2 );","\treturn pos + norm * thickness * scale * ratio;","}","void main() {","\t#include <uv_vertex>","\t#include <beginnormal_vertex>","\t#include <morphnormal_vertex>","\t#include <skinbase_vertex>","\t#include <skinnormal_vertex>","\t#include <begin_vertex>","\t#include <morphtarget_vertex>","\t#include <skinning_vertex>","\t#include <displacementmap_vertex>","\t#include <project_vertex>","\tvec3 outlineNormal = - objectNormal;","\tgl_Position = calculateOutline( gl_Position, outlineNormal, vec4( transformed, 1.0 ) );","\t#include <logdepthbuf_vertex>","\t#include <clipping_planes_vertex>","\t#include <fog_vertex>","}"].join("\n"),["#include <common>","#include <fog_pars_fragment>","#include <logdepthbuf_pars_fragment>","#include <clipping_planes_pars_fragment>","uniform vec3 outlineColor;","uniform float outlineAlpha;","void main() {","\t#include <clipping_planes_fragment>","\t#include <logdepthbuf_fragment>","\tgl_FragColor = vec4( outlineColor, outlineAlpha );","\t#include <tonemapping_fragment>","\t#include <colorspace_fragment>","\t#include <fog_fragment>","\t#include <premultiplied_alpha_fragment>","}"].join("\n");function f(t){Array.isArray(t)&&(t=t[0]);const i=m.projectionMatrix.multiply(m.modelViewMatrix).multiplyVec(v.position);let n=A(M.normal);n=b("DOUBLE_SIDED",n,e=>w(new y("gl_FrontFacing"),e,e.multiplyScalar(-1)));const r=h("outlineThickness",a),o=_("outlineColor",new c(0,0,0)),s=h("outlineAlpha",l),f=p(d,{pos:i,normal:n,skinned:v.position,outlineThickness:r},"\n\t\t\t\t\tfloat thickness = outlineThickness;\n\t\t\t\t\tconst float ratio = 1.0; // TODO: support outline thickness ratio for each vertex\n\t\t\t\t\tvec4 pos2 = projectionMatrix * modelViewMatrix * vec4( skinned.xyz + normal, 1.0 );\n\t\t\t\t\tfloat viewDistance = length((modelViewMatrix * vec4(skinned.xyz, 1.0)).xyz);\n\t\t\t\t\tfloat scale = pow(viewDistance, 0.5); // sqrt, or any exponent\n\t\t\t\t\t// NOTE: subtract pos2 from pos because BackSide objectNormal is negative\n\t\t\t\t\tvec4 norm = normalize( pos - pos2 );\n\t\t\t\t\treturn pos + norm * thickness * scale * ratio;\n\t\t\t"),g=x(o,s),D=[g,k(0),k(0)],T="number"==typeof t.userData.mrtOutputs&&t.userData.mrtOutputs>1,O=new u({position:f,outputs:T?D:void 0,color:T?void 0:g});return O.side=e,O.depthTest=!0,O.depthWrite=!0,O.transparent=!0,O}this.createMaterial=f,this.getOutlineMaterial=function(e){const t=function(e){let t=o[e.uuid];return void 0===t&&(t={material:f(e),used:!0,keepAlive:r,count:0},o[e.uuid]=t),t.used=!0,t.material}(e);return s[t.uuid]=e,function(e,t){Array.isArray(t)&&(t=t[0]);if("invisible"===e.name)return;const i=t.userData.outlineParameters;e.fog=t.fog,e.toneMapped=t.toneMapped,e.premultipliedAlpha=t.premultipliedAlpha,e.displacementMap=t.displacementMap,void 0!==i?(!1===t.visible?e.visible=!1:e.visible=void 0===i.visible||i.visible,e.transparent=void 0!==i.alpha&&i.alpha<1||t.transparent,void 0!==i.keepAlive&&(o[t.uuid].keepAlive=i.keepAlive)):(e.transparent=t.transparent,e.visible=t.visible);!0!==t.wireframe&&!1!==t.depthTest||(e.visible=!1);t.clippingPlanes&&(e.clipping=!0,e.clippingPlanes=t.clippingPlanes,e.clipIntersection=t.clipIntersection,e.clipShadows=t.clipShadows);e.version=t.version}(t,e),t},this.updateUniforms=function(e,t){const i=t.userData.outlineParameters;e.uniforms.outlineAlpha.value=t.opacity,void 0!==i&&(void 0!==i.thickness&&(e.uniforms.outlineThickness.value=i.thickness),void 0!==i.color&&e.uniforms.outlineColor.value.fromArray(i.color),void 0!==i.alpha&&(e.uniforms.outlineAlpha.value=i.alpha)),t.displacementMap&&(e.uniforms.displacementMap.value=t.displacementMap,e.uniforms.displacementScale.value=t.displacementScale,e.uniforms.displacementBias.value=t.displacementBias)}}apply(e){if(!(e instanceof r)||e instanceof s||e instanceof o)return;if(this.applied.has(e))return;this.applied.add(e);const t=e.onAfterRender;e.onAfterRender=(i,n,a,l,r,o)=>{t(i,n,a,l,r);let s=!1;if(Array.isArray(r)?s=r.some(e=>e&&e.userData&&e.userData.outlineParameters):r&&r.userData&&r.userData.outlineParameters&&(s=!0),!s)return;const c=e.material,p=this.getOutlineMaterial(c);e.material=p,this.updateUniforms(p,r),i.renderBufferDirect(a,n,l,p,e,o),e.material=c}}}/*
2
2
  * Copyright (©) 2025 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
package/dist/rendering.js CHANGED
@@ -1,4 +1,4 @@
1
- var e;import{__decorate as t,__metadata as s}from"tslib";import*as i from"three";import{Color as r,Material as a,Matrix4 as n,Mesh as o,PerspectiveCamera as l,ShaderChunk as h,ShaderMaterial as d,WebGLRenderTarget as u,Texture as c,Euler as p}from"three";import{CopyShader as m,EffectComposer as f,FXAAShader as g,GammaCorrectionShader as v,LUTPass as M,RenderPass as T,ShaderPass as b,VRButton as x}from"three-stdlib";import{CSMShader as P,CSMUtil as y}from"./csm.js";import{bool as w,colorToNormal as S,float as R,NodeShaderMaterial as C,standardMaterial as A,uniformFloat as F,uniformVec3 as U,toonMaterial as E,lambertMaterial as O,normalize as I,rgb as B,rgba as D,textureSampler2d as W,transformed as L,varying as j,varyingAttributes as V,varyingTransformed as _,vec4 as G,BooleanExpression as q,select as k,ifDefApply as N,uniformSampler2d as H,RgbaNode as z}from"three-shader-graph";import{Reflector as $}from"three-stdlib";import{BokehPass as X,OutputPass as Y}from"three/examples/jsm/Addons.js";import{CSM as Q}from"three/examples/jsm/csm/CSM.js";import K from"three/examples/jsm/libs/stats.module.js";import{GTAOPass as J}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as Z}from"typedi";import{depthUniformName as ee,farUniformName as te,nearUniformName as se,resolutionUniformName as ie,sceneNormalUniformName as re,screenUV as ae,supportsDepthTextureExtension as ne}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as oe}from"./shader-nodes/time.js";import{aoMapUniformName as le,sceneMapUniformName as he}from"./shader-nodes/scene-sample.js";import{DepthPass as de}from"./utils/three/depth-pass.js";import{GPUStatsPanel as ue}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as ce}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as pe,traverseVisibleStop as me}from"./utils/three/traverse.js";import{clamp as fe}from"./utils/math.js";import{ColorPass as ge}from"./rendering/color-pass.js";import{SSRPass as ve}from"./rendering/ssr/SSRPass.js";import{SSRShader as Me}from"./rendering/ssr/SSRShader.js";import{VolumetricFogPass as Te}from"./rendering/fog/volumetric-fog-pass.js";import{OutlineEffect as be}from"./rendering/outline-effect.js";import{UnrealBloomPass as xe}from"./rendering/bloom/UnrealBloomPass.js";import{highPrecisionEyeDepth as Pe}from"./shader-nodes/depth";import{packDepthToRGBA as ye}from"three-shader-graph";import{FogVolumeObject as we}from"./rendering/fog/fog-volume-object";import{ParallaxStandardMaterial as Se}from"./shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Re}from"./shader-nodes/pom.js";import{FullScreenQuad as Ce}from"three-stdlib";import{edgeDepthEffect as Ae}from"./shader-nodes/effects";import{decalDiscard as Fe}from"./shader-nodes/decal.js";import{Pass as Ue}from"three/examples/jsm/Addons.js";y.patchSetupMaterial();const Ee=document.createElement("div");Ee.style.position="absolute",Ee.style.left="50%",Ee.style.top="50%",Ee.style.color="black",Ee.style.zIndex="999";(new i.Layers).set(9);const Oe=new i.MeshBasicMaterial({color:"black"}),Ie=new i.MeshDepthMaterial;var Be;Ie.depthPacking=i.RGBADepthPacking,Ie.blending=i.NoBlending,Ie.side=i.DoubleSide,function(e){e[e.opaque=0]="opaque",e[e.transparent=1]="transparent"}(Be||(Be={}));const De=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let We=e=class{setPaused(e){this.paused=e}resizeRender(){const e=this.container.clientWidth,t=this.container.clientHeight;this.previousClientWith===e&&this.previousClientHeight===t||0!==e&&0!==t&&(this.previousClientWith=e,this.previousClientHeight=t,this.camera instanceof l&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(e,t),this.composer.setSize(e*this.resolutionScale,t*this.resolutionScale),this.dofPass.setSize(e*this.resolutionScale,t*this.resolutionScale),this.fxaaPass.setSize(e*this.renderer.getPixelRatio(),t*this.renderer.getPixelRatio()),this.fxaaPass.uniforms.resolution.value.set(1/(e*this.renderer.getPixelRatio()),1/(t*this.renderer.getPixelRatio())),this.createGRenderTarget(),this.phasedRenderPass.gRenderTarget=this.gRenderTarget,this.bloomPass.emissiveTexture=this.gRenderTarget.textures[1],this.ssrPass.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),this.aoPass.setSize(e*this.resolutionScale,t*this.resolutionScale),this.aoPass.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),this.sceneColorRenderTarget.dispose(),this.sceneColorRenderTarget=this.createSceneColorRenderTarget(this.renderer,this.container),this.copyPass.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass.material.uniformsNeedUpdate=!0)}addPostProcessVolume(e){if(0===this.postProcessVolumes.length)this.postProcessVolumes.push(e);else{let t=!1;for(let s=0;s<this.postProcessVolumes.length;s++)if(e.priority<this.postProcessVolumes[s].priority){this.postProcessVolumes.splice(s,0,e),t=!0;break}t||this.postProcessVolumes.push(e)}}removePostProcessVolume(e){const t=this.postProcessVolumes.indexOf(e);t>-1&&this.postProcessVolumes.splice(t,1)}constructor(t,s={}){this.container=t,this.options=s,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.postProcessVolumes=[],this.postProcessSettings={},this.fquadCopy=new Ce(new d(m)),this.fquadCopyOpaque=new Ce(new C({outputs:[H("tSceneColor",new c).sample(ae),G(H("tDepthTexture",new i.DepthTexture(1,1)).sample(ae).r)]})),this.fquadBlendAO=(()=>{const e=G(1),t=new C({outputs:[H("tAO",new c).sample(ae),e,e],transparent:!0});t.depthWrite=!1,t.depthTest=!1,t.blending=i.MultiplyBlending;return new Ce(t)})(),this.resolutionScale=1,this.maxPixelRatio=De?1:window.devicePixelRatio,this.onResize=()=>{if(this.resizeRender(),!this.paused)try{this.render()}catch(e){}},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!0,this.onLoopCallbacks=[],this.stats=new K,this._showStats=!0,this.gbufferMaterialCache=new Map,this.tbufferMaterialCache=new Map,this.pmremGeneratorResults=new WeakMap,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new r,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],this._customDepthMaterialCache=new WeakMap,null!=s.maxPixelRatio&&(this.maxPixelRatio=s.maxPixelRatio),window.renderer=this.renderer=new i.WebGLRenderer({antialias:!1,powerPreference:"high-performance"});new i.MeshStandardMaterial({color:"#ccc"});this.scene=new i.Scene,this.scene.matrixWorldAutoUpdate=!0,this.scene.updateMatrixWorld=function(e){const t=this.children;for(let s=0,i=t.length;s<i;s++){t[s].updateMatrixWorld(e)}}.bind(this.scene),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(x.createButton(this.renderer));const a=new be(this.renderer,{defaultThickness:.005,defaultColor:[0,0,0],defaultAlpha:1,defaultKeepAlive:!0});this.outlineEffect=a,this.createGRenderTarget(),this.composer=new f(this.renderer);var n=(t.clientWidth||1)/(t.clientHeight||1);const o=new i.PerspectiveCamera(45,n,.5,800);o.layers.enable(19),this.setCamera(o),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=i.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=s.shadows?.autoUpdate??!1,this.renderer.outputColorSpace=i.SRGBColorSpace,this.renderer.toneMapping=i.NoToneMapping,this.renderer.toneMappingExposure=1,this.renderer.gammaFactor=1.4,y.renderingView=this,this.isDepthTextureExtensionSupported=ne(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container),this.sceneColorRenderTarget=this.createSceneColorRenderTarget(this.renderer,this.container);const l=new i.Vector2(t.clientWidth,t.clientHeight),h=(new T(this.scene,this.camera),new b(m,"prevtexture"));h.enabled=!0,h.needsSwap=!0,h.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass=h;const u=new xe(l,1.5,.4,.85);u.threshold=1,u.strength=.9,u.radius=.5,this.bloomPass=u;const p=new J(this.scene,this.camera,t.clientWidth,t.clientWidth,{});p.normalRenderTarget?.dispose(),p.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),p.output=J.OUTPUT.Off,p.enabled=!1,this.aoPass=p,this.fquadBlendAO.material.uniforms.tAO.value=p.pdRenderTarget.texture,Me.fragmentShader=Me.fragmentShader.replace("if(metalness==0.) return;","if(metalness<0.1) return;");const P=new ve({renderer:this.renderer,scene:this.scene,camera:this.camera,groundReflector:null,selects:[],normalTexture:this.gRenderTarget.textures[2],depthTexture:this.gRenderTarget.depthTexture});P.output=ve.OUTPUT.Default,P.blur=!0,P.fresnel=!1,P.distanceAttenuation=!0,P.maxDistance=50,P.selective=!0,P.bouncing=!1,P.opacity=.4,P.enabled=!1!==this.options?.reflection?.enabled,this.ssrPass=P,!1!==this.options.ao?.enabled&&this.composer.addPass(p);const w=new Ze((e,t,s,i,r)=>{this.aoPass.enabled&&(this.initResolutionUniform(this.fquadBlendAO.material),this.renderer.setRenderTarget(this.gRenderTarget),this.fquadBlendAO.render(this.renderer),this.renderer.setRenderTarget(null))});this.composer.addPass(w);const S=new Ze((e,t,s,i,r)=>{this.renderer.setRenderTarget(this.gRenderTarget),this.renderScene(Be.transparent),this.renderer.setRenderTarget(null)});this.composer.addPass(S),this.composer.addPass(h),this.composer.addPass(P),this.phasedRenderPass=new Je(this.scene,this.camera,this.gRenderTarget),this.composer.addPass(this.phasedRenderPass),this.composer.addPass(u),u.emissiveTexture=this.gRenderTarget.textures[1],this.renderer.info.autoReset=!1,this.volumetricFogPass=new Te(l),this.composer.addPass(this.volumetricFogPass),this.volumetricFogPass.enabled=!0,this.dofPass=new X(this.scene,this.camera,{focus:1,aperture:.025,maxblur:.01}),this.dofPass.enabled=!1,this.composer.addPass(this.dofPass);const R=new ge;this.composer.addPass(R),this.colorPass=R,R.vignetteEnabled=!1,this.outlinePass=new ce(new i.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.outlinePass.enabled=!1,this.composer.addPass(this.outlinePass);const A=new b(g);A.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(A),this.fxaaPass=A,this.fxaaPass.enabled=!1,!0===s.enableOutlines&&this.setEnableOutlines(!0),new b(v).clear=!1,this.fixStatsStyle(),this.lutPass=new M({}),this.lutPass.enabled=!1,this.composer.addPass(this.lutPass);const F=new b(m,"prevtexture");F.enabled=!0,F.needsSwap=!1,F.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[1],F.renderToScreen=!0;const U=new Y;this.composer.addPass(U)}fixStatsStyle(){const e=this.stats.dom;e.style.position="absolute";const t=e.getElementsByTagName("canvas");for(let e=0;e<t.length;e++)t.item(e).style.display="inline-block"}setEnableOutlines(e){this.outlinePass.enabled=e,this.fxaaPass.enabled=e}setCamera(e){this.camera=e,this.composer.passes.forEach(t=>{t instanceof T?t.camera=e:t instanceof ce?t.renderCamera=e:(t instanceof de||t instanceof J)&&(t.camera=e)}),this.ssrPass&&(this.ssrPass.camera=e),this.aoPass&&(this.aoPass.camera=e),this.phasedRenderPass&&(this.phasedRenderPass.camera=e),null==this.csm?(this.csm=new Q({maxFar:100,lightFar:250,lightMargin:20,cascades:De?2:4,shadowMapSize:2048*(De?.5:1),lightDirection:new i.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene,mode:"practical"}),this.csm&&Array.isArray(this.csm.lights),this.csm.fade=!0,h.lights_fragment_begin=P.lights_fragment_begin):(this.csm.camera=this.camera,this.camera),this.csm.updateFrustums()}setSelectedObjects(e){if(null==this.outlinePass)return;const t=new Map;for(const s of e)t.set(s.uuid,s);for(const s of e)s.traverse(e=>{e.uuid!==s.uuid&&t.has(e.uuid)&&t.delete(e.uuid)});this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t,s){const r=new i.WebGLRenderTarget(t.clientWidth*s,t.clientHeight*s);return r.texture.minFilter=i.NearestFilter,r.texture.magFilter=i.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,r.depthTexture=new i.DepthTexture(128,128),r.depthTexture.type=i.UnsignedShortType,r.depthTexture.minFilter=i.NearestFilter,r.depthTexture.magFilter=i.NearestFilter,r}static createAOMaskDepthRenderTarget(e,t){const s=new i.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio(),{type:i.HalfFloatType});return s.texture.minFilter=i.NearestFilter,s.texture.magFilter=i.NearestFilter,s.texture.generateMipmaps=!1,s.stencilBuffer=!1,s.depthTexture=new i.DepthTexture(128,128),s.depthTexture.type=i.UnsignedInt248Type,s.depthTexture.minFilter=i.NearestFilter,s.depthTexture.magFilter=i.NearestFilter,s}createSceneColorRenderTarget(e,t){const s=new i.WebGLRenderTarget(t.clientWidth*this.renderer.getPixelRatio(),t.clientHeight*this.renderer.getPixelRatio(),{count:2,type:i.FloatType,format:i.RGBAFormat,colorSpace:i.SRGBColorSpace,depthBuffer:!1,stencilBuffer:!1});return s.texture.minFilter=i.LinearFilter,s.texture.magFilter=i.LinearFilter,s.texture.generateMipmaps=!1,s}createGRenderTarget(){const e=this.container;null!=this.gRenderTarget&&this.gRenderTarget.dispose(),this.gRenderTarget=new u(e.clientWidth*this.renderer.getPixelRatio(),e.clientHeight*this.renderer.getPixelRatio(),{count:3,minFilter:i.NearestFilter,magFilter:i.NearestFilter,type:i.HalfFloatType,format:i.RGBAFormat}),this.gRenderTarget.depthTexture=new i.DepthTexture(e.clientWidth,e.clientHeight),this.gRenderTarget.depthTexture.type=i.UnsignedIntType,this.gRenderTarget.depthTexture.minFilter=i.NearestFilter,this.gRenderTarget.depthTexture.magFilter=i.NearestFilter,this.gRenderTarget.texture.generateMipmaps=!1,this.gRenderTarget.stencilBuffer=!1}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(){this.running=!1,window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],this.renderer.dispose(),this.gRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.sceneColorRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren(),this.volumetricFogPass.dispose(),y.clearSceneCache(this.scene)}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.container.contains(this.stats.dom)?this.container.appendChild(this.stats.dom):!this._showStats&&this.container.contains(this.stats.dom)&&this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}applyEnvMap(e){if(null!=this.scene.environment&&(e instanceof C&&(null==e.envMap||e.userData.useSceneEnv)&&(e.userData.useSceneEnv=!0,null==e.uniforms.envMap&&(e.uniforms.envMap={value:this.scene.environment},e.uniformsNeedUpdate=!0,e.uniforms.envMapRotation={value:He(this.scene.environmentRotation,this.scene.environment,new i.Matrix3)}),null==e.uniforms.envMapIntensity&&(e.uniforms.envMapIntensity={value:1},e.uniformsNeedUpdate=!0),e.uniforms.envMap.value=this.scene.environment,e.uniforms.envMapIntensity.value=this.scene.environmentIntensity,e.envMap=this.scene.environment),e instanceof C||e instanceof i.MeshStandardMaterial)){const t=this.gbufferMaterialCache.get(e);null==t||this.gbufferMaterialCache.has(t)||this.applyEnvMap(t)}}setupCsm(e){if(e instanceof i.Mesh||e instanceof i.SkinnedMesh)if(e.material instanceof Array)for(const t of e.material)this.csm.setupMaterial(t);else this.csm.setupMaterial(e.material)}updateUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s){const t=i[e],r=s[e].value;null!=t&&t.value!==r&&(t.value=r)}}updateLightUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e of et){const t=i[e],r=s[e];null!=r&&null!=t&&(t.value=r.value)}}createGBufferMaterial(e,t){const s=t===Be.opaque?this.gbufferMaterialCache:this.tbufferMaterialCache;let r=s.get(e);if(null==r){let o=V.uv;e instanceof Se&&null!=e.heightMap&&(o=Re(o,W(e.heightMap),R(e.heightScale??1)));let l=_.normal;e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial?null!=e.normalMap&&(l=S(W(e.normalMap).sample(o),e.normalScale.x??1)):e instanceof C&&null!=e.outputNormal&&(l=e.outputNormal),!0!==e.userData.disableAO&&(l=N("DOUBLE_SIDED",l,e=>k(new q("gl_FrontFacing"),e,e.multiplyScalar(-1))));let h=e.userData?.reflective?R(0):R(1);if(e instanceof i.MeshStandardMaterial){const t=F("roughness",e.roughness??1);h=null!=e.roughnessMap?W(e.roughnessMap).sample(o).g.multiply(t):t}else e instanceof C&&null!=e.outputRoughness&&(h=e.outputRoughness);let u=null;(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial)&&null!=e.lightMap&&(u=W(e.lightMap).sample(o).rgb.multiplyScalar(e.lightMapIntensity));let c,p=R(0);if(e instanceof i.MeshStandardMaterial){const t=F("metalness",e.metalness??0);p=null!=e.metalnessMap?W(e.metalnessMap).sample(o).b.multiply(t):t}else e instanceof C&&e.outputRoughness;let m=R(1);e instanceof i.MeshStandardMaterial?null!=e.aoMap&&(c=W(e.aoMap).sample(o).r,m=F("aoMapIntensity",e.aoMapIntensity)):e instanceof C&&e.outputRoughness;const f=F("opacity",e.opacity??1);let g=R(1);e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial?(null!=e.alphaMap&&(g=W(e.alphaMap).sample(o).r),g=g.multiply(f)):e instanceof C&&null!=e.outputOpacity&&(g=e.outputOpacity);let v=D(0,1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial){const t=U("color",(new i.Vector3).setFromColor(e.color));null!=e.map?(v=W(e.map).sample(o).multiply(D(t,1)),g=g.multiply(v.w)):v=D(t,1)}const M=!0===e.userData.hasBloom;let T=B(0);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=U("emissive",(new i.Vector3).setFromColor(e.emissive));T=null!=e.emissiveMap?W(e.emissiveMap).sample(o).rgb.multiply(t):t,T=T.multiplyScalar(e.emissiveIntensity)}else e instanceof C&&null!=e.outputEmissive&&(T=e.outputEmissive);const b=e instanceof d&&null!=e.uniforms[ee],x=e instanceof d&&null!=e.uniforms[he],P=e instanceof d&&null!=e.uniforms[le],y=e.transparent&&e.alphaTest<=.01||e.blending===i.AdditiveBlending,L=F("alphaTest",e.alphaTest);let j,H=e.alphaTest>0?g.lt(L):y&&t===Be.opaque?g.lt(.8):w(!1);!0===e.userData.isDecal&&(H=H.or(Fe)),j=y?G(0,0,0,0):(n=l,I(n).multiplyScalar(.5).addScalar(.5)).rgba(h);let z,$=e instanceof C?e.outputPosition:void 0,X=D("black",1);if(e instanceof C&&null!=e.outputColor)X=e.outputColor;else if(e instanceof i.MeshStandardMaterial)X=A({color:v,metalness:p,roughness:h,emissive:T.rgb,normal:l,ambientOcclusion:c,ambientOcclusionIntensity:m,bakedLight:u});else if(e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)X=O({color:v.rgb});else if(e instanceof i.MeshBasicMaterial){let e=v.rgb,t=u??B("white");null!=c&&(t=t.multiplyScalar(c.subtract(1).multiply(m).add(1))),e=e.multiply(t),X=e.rgba(g)}else e instanceof i.MeshToonMaterial&&(X=E({color:v,emissive:T.rgb,normal:l,ambientOcclusion:c,ambientOcclusionIntensity:m,bakedLight:u}));(e instanceof C||e instanceof i.MeshStandardMaterial)&&(z=e.envMap),r=new C({position:$,outputs:[(a=D(X.rgb,g),new FogNode(a)),T.rgba(t===Be.opaque?L:M?1:0),j],opacity:g,outputEncoding:!1,fog:!0,transparent:e.transparent,lights:!0,envMap:z,discard:H}),e instanceof i.MeshStandardMaterial&&null!=e.envMap&&null!=r.uniforms.envMapIntensity&&(r.uniforms.envMapIntensity.value=e.envMapIntensity),(e instanceof C||e instanceof i.MeshStandardMaterial)&&this.applyEnvMap(r),e instanceof C&&Object.assign(r.defines,e.defines),r.userData.mrtOutputs=3,r.forceSinglePass=e.forceSinglePass,r.side=e.side,r.blending=e.blending,y?(r.depthWrite=!e.transparent,r.depthTest=e.depthTest,r.colorWrite=t===Be.transparent):(r.depthWrite=e.depthWrite,r.depthTest=e.depthTest),r.visible=e.visible,r.alphaTest=e.alphaTest,r.alphaHash=e.alphaHash,t===Be.opaque?(r.visible&&(r.visible=!b&&!x&&!P),r.visible&&(r.visible=!y)):t===Be.transparent&&r.visible&&(r.visible=y||b||x||P),Object.assign(r.userData,e.userData),r.visible&&(this.csm.setupMaterial(r),e instanceof d&&Object.assign(r.uniforms,e.uniforms)),s.set(e,r)}var a,n;return r.visible&&e instanceof d&&this.updateUniformValues(e,r),r}loop(e,t=!1){const s=this.stats,r=s.addPanel(new K.Panel("Calls","#83f","#002")),a=s.addPanel(new K.Panel("Triangles","#c32","#002"));let l;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(l=new ue(this.renderer.getContext()),s.addPanel(l)),this.showStats=t;let h=10,d=1e3;const u=()=>{const e=this.renderer.info.render.calls;e>h&&(h=e,setTimeout(()=>h=10,5e3)),r.update(e,h);const t=this.renderer.info.render.triangles;t>d&&(d=t,setTimeout(()=>d=1e3,5e3)),a.update(t,d)};performance.now();i.Ray.prototype.intersectTriangle;this.resizeRender();const c=[],p=[],m=[];let f=0;const g=new n,v=new n;let M=0;let T=this.paused;const b=t=>{const r=this.renderer.getContext();if(this.paused&&this.running&&r.drawingBufferHeight>1)return setTimeout(()=>b(t),500),void(T=!0);this.renderer.clear(),this.applyPostProcessSettings(),this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,s.begin(),this.showStats&&l?.startQuery(),this.ssrPass.gpuPanel=l;let a=(t*=.001)-f;if(f=t,T&&(a=.016,T=!1),g.copy(this.camera.matrixWorld),a>1){let t=a;for(;t>.05;)e(Le),t-=Le;e(t)}else e(a);this.onLoopCallbacks.forEach(e=>e(a)),this.camera?.updateMatrixWorld(),v.copy(this.camera.matrixWorld),t-M>.08&&!v.equals(g)&&(this.renderer.shadowMap.needsUpdate=!0,M=t),this.csm.update();let n=!1;c.length=0,p.length=0,m.length=0;const h=Ve;Ge.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),h.setFromProjectionMatrix(Ge);let d=!1,x=!1,P=!1;this.scene.traverseVisible(e=>{if(this.setupCsm(e),this.outlineEffect.apply(e),e instanceof we&&(d=!0),e instanceof o&&this.initCustomDepthMaterial(e),(e instanceof o||e instanceof i.Sprite)&&(this.initResolutionUniform(e.material),this.initNormalUniform(e.material),this.initShadowUniform(e,e.material),null!=this.scene.environment&&function(e,t){if(Array.isArray(e.material))for(const s of e.material)t(s);else null!=e.material&&t(e.material)}(e,e=>this.applyEnvMap(e)),!0===e.material?.userData?.hasBloom&&(n=!0)),(e instanceof o||e instanceof i.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[ee])&&isObjectInFrustum(e,h)?(this.initDepthUniform(e.material),x=!0):e instanceof $&&(e.visible=!1,p.push(e)),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[le]&&isObjectInFrustum(e,h)&&e.material instanceof C&&this.initAoUniform(e.material),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[he]&&isObjectInFrustum(e,h)&&(m.push(e),e.material.uniforms[he].value=this.sceneColorRenderTarget.texture,P=!0),e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[oe])e.material.uniforms[oe].value=t;else if(e instanceof o&&Array.isArray(e.material))for(const s of e.material)s.uniforms&&null!=s.uniforms[oe]&&(s.uniforms[oe].value=t)}),this.bloomPass.enabled=n,this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clear(),this.renderScene(Be.opaque),this.aoPass.output=J.OUTPUT.Off,(x||P)&&(this.fquadCopyOpaque.material.uniforms.tSceneColor.value=this.gRenderTarget.textures[0],this.fquadCopyOpaque.material.uniforms.tDepthTexture.value=this.gRenderTarget.depthTexture,this.initResolutionUniform(this.fquadCopyOpaque.material),this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.renderer.clear(),this.fquadCopyOpaque.render(this.renderer),this.renderer.setRenderTarget(this.gRenderTarget)),m.length,c.forEach(e=>e.visible=!0),p.forEach(e=>e.visible=!0),m.forEach(e=>e.visible=!0),this.aoPass.enabled,this.ssrPass&&(this.ssrPass.elapsedTime=t),this.volumetricFogPass&&d&&this.volumetricFogPass.update(this.camera,this.gRenderTarget,this.csm,this.scene);try{!this.paused&&this.running&&(this.render(a),this.showStats&&l?.endQuery(),this.showStats&&u(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}s.end(),this.csm?.update(),this.running&&!0!==this.options.enableXR&&(this.fpsCap?setTimeout(()=>{requestAnimationFrame(b)},1e3/this.fpsCap):requestAnimationFrame(b))};!0===this.options.enableXR?this.renderer.setAnimationLoop(b):requestAnimationFrame(b)}renderScene(e){Xe.clear(),Ye.length=0;me(this.scene,t=>{if(Qe(t))return Ye.push(t),t.visible=!1,!1;if(t instanceof o){Xe.set(t,t.material);let s=!1;if(Array.isArray(t.material)){t.material=t.material.slice();for(let i=0;i<t.material.length;i++)t.material[i]=this.createGBufferMaterial(t.material[i],e),s||(s=t.material[i].visible)}else t.material=this.createGBufferMaterial(t.material,e),s||(s=t.material.visible);s?t.visible=!0:null!=t.children&&0!=t.children.length||(Ye.push(t),t.visible=!1)}});const t=this.scene.matrixWorldAutoUpdate,s=this.scene.matrixAutoUpdate,i=this.renderer.shadowMap.autoUpdate;e!==Be.opaque&&(this.renderer.shadowMap.autoUpdate=!1,this.scene.matrixWorldAutoUpdate=!1,this.scene.matrixAutoUpdate=!1);try{this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Render failed",e)}e===Be.opaque&&Xe.forEach((e,t)=>{!Array.isArray(e)&&!Array.isArray(t.material)&&e instanceof d&&this.updateLightUniformValues(t.material,e)}),Xe.forEach((e,t)=>{t.material=e}),Ye.forEach((e,t)=>{e.visible=!0,e.updateMatrixWorld(!0)}),this.renderer.shadowMap.autoUpdate=i,this.scene.matrixWorldAutoUpdate=t,this.scene.matrixAutoUpdate=s}getEnvTexture(e){null==this.pmremGenerator&&(this.pmremGenerator=new i.PMREMGenerator(this.renderer),this.pmremGenerator.compileEquirectangularShader());let t=this.pmremGeneratorResults.get(e);return null==t&&(t=this.pmremGenerator.fromEquirectangular(e).texture,this.pmremGeneratorResults.set(e,t)),t.colorSpace=i.SRGBColorSpace,t}applyPostProcessSettings(){if(0==this.postProcessVolumes.length)return this.lutPass.enabled=!1,void(this.colorPass.enabled=!1);var e;(e=this.postProcessSettings).tonemapMapping=void 0,e.tonemapExposure=1,e.envIntensity=1,e.envTexture=void 0,e.vignetteIntensity=0,e.colorTint=new i.Color("white"),e.colorTintIntensity=0,e.depthFocus=void 0,e.depthAperture=void 0,e.depthMaxBlur=void 0,e.temperature=6500,e.temperatureTint=0,e.lut=void 0,e.lutIntensity=0;const t=this.postProcessSettings;let s,r=!1,a=!1,n=!1,o=!1;if(null==this.camera)return;const h=this.camera.getWorldPosition(qe);let d=[];for(const e of this.postProcessVolumes){if(!je(e.object))continue;let l=e.blendWeight??1;const u=e.distanceToPoint(h);u>e.blendRadius||(e.blendRadius>0&&(l*=fe(1-u/e.blendRadius,0,1)),l>1&&(l=1),l>0&&(d.push(e),void 0!==e.settings.tonemapMapping&&(t.tonemapMapping=e.settings.tonemapMapping),void 0!==e.settings.tonemapExposure&&(t.tonemapExposure=i.MathUtils.lerp(t.tonemapExposure,e.settings.tonemapExposure,l)),void 0!==e.settings.envTexture&&(t.envTexture=e.settings.envTexture),void 0!==e.settings.envIntensity&&(t.envIntensity=i.MathUtils.lerp(t.envIntensity,e.settings.envIntensity,l)),void 0!==e.settings.vignetteIntensity&&(t.vignetteIntensity=i.MathUtils.lerp(t.vignetteIntensity,e.settings.vignetteIntensity,l),a=!0),void 0!==e.settings.colorTint&&void 0!==e.settings.colorTintIntensity&&e.settings.colorTintIntensity>0&&(t.colorTint=t.colorTint.lerp(e.settings.colorTint,l),o=!0),void 0!==e.settings.colorTintIntensity&&(t.colorTintIntensity=i.MathUtils.lerp(t.colorTintIntensity,e.settings.colorTintIntensity,l)),void 0!==e.settings.depthFocus&&(r=!0,t.depthFocus=void 0!==t.depthFocus?i.MathUtils.lerp(t.depthFocus,e.settings.depthFocus,l):e.settings.depthFocus),void 0!==e.settings.depthAperture&&(r=!0,t.depthAperture=void 0!==t.depthAperture?i.MathUtils.lerp(t.depthAperture,e.settings.depthAperture,l):e.settings.depthAperture),void 0!==e.settings.depthMaxBlur&&(r=!0,t.depthMaxBlur=void 0!==t.depthMaxBlur?i.MathUtils.lerp(t.depthMaxBlur,e.settings.depthMaxBlur,l):e.settings.depthMaxBlur),void 0!==e.settings.temperature&&(t.temperature=i.MathUtils.lerp(t.temperature,e.settings.temperature,l)),void 0!==e.settings.temperatureTint&&(t.temperatureTint=i.MathUtils.lerp(t.temperatureTint,e.settings.temperatureTint,l)),void 0!==e.settings.lut&&(s=e.settings.lut,n=!0),void 0!==e.settings.lutIntensity&&(t.lutIntensity=i.MathUtils.lerp(t.lutIntensity,e.settings.lutIntensity,l),n=!0)))}this.renderer.toneMapping=t.tonemapMapping??i.NoToneMapping,this.renderer.toneMappingExposure=t.tonemapExposure,null!=t.envTexture&&(this.scene.environment=this.getEnvTexture(t.envTexture)),this.scene.environmentIntensity=t.envIntensity,this.colorPass.vignetteIntensity=t.vignetteIntensity,this.colorPass.vignetteEnabled=a,this.colorPass.colorTint=t.colorTint,this.colorPass.colorTintIntensity=t.colorTintIntensity,this.colorPass.enabled=a||o,r&&this.camera instanceof l?(this.dofPass.enabled=!0,void 0!==t.depthFocus&&(this.dofPass.uniforms.focus.value=t.depthFocus),void 0!==t.depthAperture&&(this.dofPass.uniforms.aperture.value=t.depthAperture),void 0!==t.depthMaxBlur&&(this.dofPass.uniforms.maxblur.value=t.depthMaxBlur)):this.dofPass.enabled=!1,this.colorPass.temperature=t.temperature,this.colorPass.temperatureTint=t.temperatureTint,this.lutPass.enabled=n,n&&(null!=s&&(s.flipY=!0,s.generateMipmaps=!1),this.lutPass.lut=s,this.lutPass.intensity=t.lutIntensity)}renderOverlay(){if(0===this.overlayCameras.size)return;const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.previousClientWith/2,s=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let i=0;i<e.length;i++)this.renderer.clearDepth(),this.renderer.setViewport(t-s/2+this.insetWidth*i+this.insetMargin*i,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[i])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){if(0===this.composer.renderTarget1.width||0===this.composer.renderTarget1.height)return;if(0===this.composer.renderTarget2.width||0===this.composer.renderTarget2.height)return;let t=!1;if(this.ssrPass.enabled&&!1!==this.options?.reflection?.enabled){const e=this.ssrPass.selects??[];e.length=0,this.scene.traverseVisible(t=>{t instanceof o&&!0===t.material.userData?.reflective&&isObjectInFrustum(t,Ve)&&e.push(t)}),this.ssrPass.selects=e,0==e.length&&(this.ssrPass.enabled=!1),t=!0}this.options.bloom,this.composer.render(e),this.scene.matrixWorldAutoUpdate=!0,this.scene.matrixAutoUpdate=!0,t&&(this.ssrPass.enabled=!0)}hasBloom(){return null!=pe(this.scene,e=>e instanceof o&&!0===e.material?.userData?.hasBloom)}darkenNonBloomed(e){if((e instanceof o||e instanceof i.Sprite||e instanceof i.Line)&&e.visible&&(null==e.material.userData||!0!==e.material.userData.hasBloom)){if(e.material?.id===Oe.id)return;this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=Oe:(e.visible=!1,this.bloomHidden.push(e))}else"TransformControlsPlane"!==e.type&&"TransformControlsGizmo"!==e.type||(e.visible=!1,this.bloomHidden.push(e))}restoreMaterial(e){this.bloomStoredMaterials[e.uuid]&&(e.material=this.bloomStoredMaterials[e.uuid],delete this.bloomStoredMaterials[e.uuid],e.visible=!0)}initDepthUniform(e){e instanceof d&&(e.uniforms[ee].value=this.sceneColorRenderTarget.textures[1],this.camera instanceof l&&(null!=e.uniforms[se]&&(e.uniforms[se].value=this.camera.near),null!=e.uniforms[te]&&(e.uniforms[te].value=this.camera.far)))}initNormalUniform(e){e instanceof d&&null!=e.uniforms[re]&&(e.uniforms[re].value=this.gRenderTarget.textures[2])}initShadowUniform(e,t){t instanceof C&&t.uniforms.receiveShadow&&(t.uniforms.receiveShadow.value=e.receiveShadow)}initResolutionUniform(e){if(e instanceof d&&null!=e.uniforms[ie]){const t=this.previousClientWith,s=this.previousClientHeight;e.uniforms[ie].value.set(t*this.renderer.getPixelRatio(),s*this.renderer.getPixelRatio())}}initAoUniform(e){if(this.aoPass.enabled){e.uniforms[le].value=this.aoPass.pdRenderTarget.texture,null==e.defines.USE_SSAO_MAP&&(e.defines.USE_SSAO_MAP="",e.needsUpdate=!0),e.defines.USE_SSAO_MAP="";const t=this.tbufferMaterialCache.get(e);null!=t&&this.initAoUniform(t)}else if(null!=e.defines.USE_SSAO_MAP){delete e.defines.USE_SSAO_MAP,e.needsUpdate=!0;const t=this.tbufferMaterialCache.get(e);null!=t&&this.initAoUniform(t)}}initCustomDepthMaterial(e){if(null!=e.customDepthMaterial||!e.castShadow)return;const t=e.material;if(t instanceof C&&!t.transparent&&t.depthWrite){let s=this._customDepthMaterialCache.get(t);if(null==s){const e=ye(Pe);let i;null!=t.alphaTest&&t.alphaTest>0&&null!=t.outputOpacity&&(i=t.outputOpacity.lt(t.alphaTest)),s=new C({color:e,discard:i}),this._customDepthMaterialCache.set(t,s)}e.customDepthMaterial=s}}};We=e=t([Z(),s("design:paramtypes",[HTMLElement,Object])],We);export{We as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const Le=.05;function je(e){let t=e;for(;t;){if(!1===t.visible)return!1;t=t.parent}return!0}J.prototype.overrideVisibility=function(){const e=this.scene,t=this._visibilityCache;e.traverse(function(e){if(t.set(e,e.visible),(e.isPoints||e.isLine||e.isTransformControls||e.isSprite)&&(e.visible=!1),null!=e.material){let t=!1,s=!1;if(Array.isArray(e.material)){for(const s of e.material)if(null!=s.alphaTest&&s.alphaTest>0){t=!0;break}}else null!=e.material.alphaTest&&e.material.alphaTest>0?t=!0:!0===e.material.userData.isDecal&&(s=!0);s&&(e.visible=!1)}})};const Ve=new i.Frustum,_e=new i.Box3,Ge=new i.Matrix4;export function isObjectInFrustum(e,t){const s=_e.setFromObject(e);return t.intersectsBox(s)}const qe=new i.Vector3;const ke=new n,Ne=new p;function He(e,t,s=new i.Matrix3){return Ne.copy(e),Ne.x*=-1,Ne.y*=-1,Ne.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(Ne.y*=-1,Ne.z*=-1),s.setFromMatrix4(ke.makeRotationFromEuler(Ne))}const ze=new C({outputs:[G(0,0,0,0),G(0,0,0,0),D(B("white"),Ae(4))],transparent:!0}),$e=new i.MeshBasicMaterial({color:"blue",transparent:!0,opacity:.5});ze.depthWrite=!1;new o(new i.BoxGeometry(4,4,4),$e);const Xe=new Map,Ye=[];function Qe(e){return e instanceof i.Sprite||e.isPoints||e.isLine||e.isTransformControls||e.isTransformControlsGizmo||e instanceof o&&Ke(e,e.material)}function Ke(e,t){return null==t||(Array.isArray(t)?t.some(t=>Ke(e,t)):t instanceof i.RawShaderMaterial||t instanceof i.ShaderMaterial&&!(t instanceof C))}class Je extends Ue{constructor(e,t,s){super(),this.scene=e,this.camera=t,this.gRenderTarget=s,this.needsSwap=!1}render(e,t,s,i,r){const a=e.autoClear;e.autoClear=!1;const n=this.scene.matrixWorldAutoUpdate,l=this.scene.matrixAutoUpdate,h=e.shadowMap.autoUpdate;this.scene.matrixAutoUpdate=!1,e.shadowMap.autoUpdate=!1;const d=s.depthTexture;s.depthTexture=this.gRenderTarget.depthTexture,e.setRenderTarget(s),Ye.length=0;let u=0;this.scene.traverseVisible(e=>{const t=Qe(e);e instanceof o&&!t?(Ye.push(e),e.visible=!1):t&&u++}),u>0&&e.render(this.scene,this.camera),Ye.forEach((e,t)=>{e.visible=!0}),e.setRenderTarget(null),e.autoClear=a,s.depthTexture=d,this.scene.matrixWorldAutoUpdate=n,this.scene.matrixAutoUpdate=l,e.shadowMap.autoUpdate=h}}class Ze extends Ue{constructor(e){super(),this.fn=e}render(e,t,s,i,r){this.fn(e,t,s,i,r)}}const et=["ambientLightColor","cameraNear","directionalLightShadows","directionalLights","directionalShadowMap","directionalShadowMatrix","fogColor","fogDensity","fogFar","fogNear","hemisphereLights","lightProbe","ltc_1","ltc_2","pointLightShadows","pointLights","pointShadowMap","pointShadowMatrix","rectAreaLights","shadowFar","spotLightMap","spotLightMatrix","spotLightShadows","spotLights","spotShadowMap"],tt=U("fogColor");export class FogNode extends z{constructor(e,t=tt){super(),this.source=e,this.fogColor=t}compile(e){const t=e.variable(),s=e.get(this.source.rgb),i=e.get(this.source.a),r=e.get(this.fogColor),a=e.get(F("fogFar")),n=e.get(F("fogNear")),o=e.get(F("fogDensity")),l=e.get(j(L.mvPosition.z));return{pars:"\n ",chunk:`\n #ifdef FOG_EXP2\n float fogFactor_${t} = 1.0 - exp( - ${o} * ${o} * ${l} * ${l} );\n #else\n float fogFactor_${t} = smoothstep( ${n}, ${a}, ${l} );\n #endif\n vec4 color_vec4_${t} = vec4(mix(${s}, ${r}, fogFactor_${t}), ${i});\n `,out:`color_vec4_${t}`}}}/*
1
+ var e;import{__decorate as t,__metadata as s}from"tslib";import*as i from"three";import{Color as r,Material as a,Matrix4 as n,Mesh as o,PerspectiveCamera as l,ShaderChunk as h,ShaderMaterial as d,WebGLRenderTarget as u,Texture as c,Euler as p,MeshStandardMaterial as m}from"three";import{CopyShader as f,EffectComposer as g,FXAAShader as v,GammaCorrectionShader as M,LUTPass as T,RenderPass as b,ShaderPass as x,VRButton as P}from"three-stdlib";import{CSMShader as y,CSMUtil as w}from"./csm.js";import{bool as S,colorToNormal as R,float as C,NodeShaderMaterial as A,standardMaterial as F,uniformFloat as U,uniformVec3 as E,toonMaterial as O,lambertMaterial as B,normalize as I,rgb as D,rgba as W,textureSampler2d as L,transformed as j,varying as V,varyingAttributes as _,varyingTransformed as G,vec4 as q,BooleanExpression as k,select as N,ifDefApply as H,uniformSampler2d as z,RgbaNode as $}from"three-shader-graph";import{Reflector as X}from"three-stdlib";import{BokehPass as Y,OutputPass as Q}from"three/examples/jsm/Addons.js";import{CSM as K}from"three/examples/jsm/csm/CSM.js";import J from"three/examples/jsm/libs/stats.module.js";import{GTAOPass as Z}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as ee}from"typedi";import{depthUniformName as te,farUniformName as se,nearUniformName as ie,resolutionUniformName as re,sceneNormalUniformName as ae,screenUV as ne,supportsDepthTextureExtension as oe}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as le}from"./shader-nodes/time.js";import{aoMapUniformName as he,sceneMapUniformName as de}from"./shader-nodes/scene-sample.js";import{DepthPass as ue}from"./utils/three/depth-pass.js";import{GPUStatsPanel as ce}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as pe}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as me,traverseVisibleStop as fe}from"./utils/three/traverse.js";import{clamp as ge}from"./utils/math.js";import{ColorPass as ve}from"./rendering/color-pass.js";import{SSRPass as Me}from"./rendering/ssr/SSRPass.js";import{SSRShader as Te}from"./rendering/ssr/SSRShader.js";import{VolumetricFogPass as be}from"./rendering/fog/volumetric-fog-pass.js";import{OutlineEffect as xe}from"./rendering/outline-effect.js";import{UnrealBloomPass as Pe}from"./rendering/bloom/UnrealBloomPass.js";import{highPrecisionEyeDepth as ye}from"./shader-nodes/depth";import{packDepthToRGBA as we}from"three-shader-graph";import{FogVolumeObject as Se}from"./rendering/fog/fog-volume-object";import{ParallaxStandardMaterial as Re}from"./shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Ce}from"./shader-nodes/pom.js";import{FullScreenQuad as Ae}from"three-stdlib";import{edgeDepthEffect as Fe}from"./shader-nodes/effects";import{decalDiscard as Ue}from"./shader-nodes/decal.js";import{Pass as Ee}from"three/examples/jsm/Addons.js";w.patchSetupMaterial();const Oe=document.createElement("div");Oe.style.position="absolute",Oe.style.left="50%",Oe.style.top="50%",Oe.style.color="black",Oe.style.zIndex="999";(new i.Layers).set(9);const Be=new i.MeshBasicMaterial({color:"black"}),Ie=new i.MeshDepthMaterial;var De;Ie.depthPacking=i.RGBADepthPacking,Ie.blending=i.NoBlending,Ie.side=i.DoubleSide,function(e){e[e.opaque=0]="opaque",e[e.transparent=1]="transparent"}(De||(De={}));const We=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let Le=e=class{setPaused(e){this.paused=e}resizeRender(){const e=this.container.clientWidth,t=this.container.clientHeight;this.previousClientWith===e&&this.previousClientHeight===t||0!==e&&0!==t&&(this.previousClientWith=e,this.previousClientHeight=t,this.camera instanceof l&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(e,t),this.composer.setSize(e*this.resolutionScale,t*this.resolutionScale),this.dofPass.setSize(e*this.resolutionScale,t*this.resolutionScale),this.fxaaPass.setSize(e*this.renderer.getPixelRatio(),t*this.renderer.getPixelRatio()),this.fxaaPass.uniforms.resolution.value.set(1/(e*this.renderer.getPixelRatio()),1/(t*this.renderer.getPixelRatio())),this.createGRenderTarget(),this.phasedRenderPass.gRenderTarget=this.gRenderTarget,this.bloomPass.emissiveTexture=this.gRenderTarget.textures[1],this.ssrPass.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),this.aoPass.setSize(e*this.resolutionScale,t*this.resolutionScale),this.aoPass.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),this.sceneColorRenderTarget.dispose(),this.sceneColorRenderTarget=this.createSceneColorRenderTarget(this.renderer,this.container),this.copyPass.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass.material.uniformsNeedUpdate=!0)}addPostProcessVolume(e){if(0===this.postProcessVolumes.length)this.postProcessVolumes.push(e);else{let t=!1;for(let s=0;s<this.postProcessVolumes.length;s++)if(e.priority<this.postProcessVolumes[s].priority){this.postProcessVolumes.splice(s,0,e),t=!0;break}t||this.postProcessVolumes.push(e)}}removePostProcessVolume(e){const t=this.postProcessVolumes.indexOf(e);t>-1&&this.postProcessVolumes.splice(t,1)}constructor(t,s={}){this.container=t,this.options=s,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.postProcessVolumes=[],this.postProcessSettings={},this.fquadCopy=new Ae(new d(f)),this.fquadCopyOpaque=new Ae(new A({outputs:[z("tSceneColor",new c).sample(ne),q(z("tDepthTexture",new i.DepthTexture(1,1)).sample(ne).r)]})),this.fquadBlendAO=(()=>{const e=q(1),t=new A({outputs:[z("tAO",new c).sample(ne),e,e],transparent:!0});t.depthWrite=!1,t.depthTest=!1,t.blending=i.MultiplyBlending;return new Ae(t)})(),this.resolutionScale=1,this.maxPixelRatio=We?1:window.devicePixelRatio,this.onResize=()=>{if(this.resizeRender(),!this.paused)try{this.render()}catch(e){}},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!0,this.onLoopCallbacks=[],this.stats=new J,this._showStats=!0,this.gbufferMaterialCache=new Map,this.tbufferMaterialCache=new Map,this.pmremGeneratorResults=new WeakMap,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new r,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],this._customDepthMaterialCache=new WeakMap,null!=s.maxPixelRatio&&(this.maxPixelRatio=s.maxPixelRatio),window.renderer=this.renderer=new i.WebGLRenderer({antialias:!1,powerPreference:"high-performance"});new i.MeshStandardMaterial({color:"#ccc"});this.scene=new i.Scene,this.scene.matrixWorldAutoUpdate=!0,this.scene.updateMatrixWorld=function(e){const t=this.children;for(let s=0,i=t.length;s<i;s++){t[s].updateMatrixWorld(e)}}.bind(this.scene),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(P.createButton(this.renderer));const a=new xe(this.renderer,{defaultThickness:.005,defaultColor:[0,0,0],defaultAlpha:1,defaultKeepAlive:!0});this.outlineEffect=a,this.createGRenderTarget(),this.composer=new g(this.renderer);var n=(t.clientWidth||1)/(t.clientHeight||1);const o=new i.PerspectiveCamera(45,n,.5,800);o.layers.enable(19),this.setCamera(o),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=i.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=s.shadows?.autoUpdate??!1,this.renderer.outputColorSpace=i.SRGBColorSpace,this.renderer.toneMapping=i.NoToneMapping,this.renderer.toneMappingExposure=1,this.renderer.gammaFactor=1.4,w.renderingView=this,this.isDepthTextureExtensionSupported=oe(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container),this.sceneColorRenderTarget=this.createSceneColorRenderTarget(this.renderer,this.container);const l=new i.Vector2(t.clientWidth,t.clientHeight),h=(new b(this.scene,this.camera),new x(f,"prevtexture"));h.enabled=!0,h.needsSwap=!0,h.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass=h;const u=new Pe(l,1.5,.4,.85);u.threshold=1,u.strength=.9,u.radius=.5,this.bloomPass=u;const p=new Z(this.scene,this.camera,t.clientWidth,t.clientWidth,{});p.normalRenderTarget?.dispose(),p.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),p.output=Z.OUTPUT.Off,p.enabled=!1,this.aoPass=p,this.fquadBlendAO.material.uniforms.tAO.value=p.pdRenderTarget.texture,Te.fragmentShader=Te.fragmentShader.replace("if(metalness==0.) return;","if(metalness<0.1) return;");const m=new Me({renderer:this.renderer,scene:this.scene,camera:this.camera,groundReflector:null,selects:[],normalTexture:this.gRenderTarget.textures[2],depthTexture:this.gRenderTarget.depthTexture});m.output=Me.OUTPUT.Default,m.blur=!0,m.fresnel=!1,m.distanceAttenuation=!0,m.maxDistance=50,m.selective=!0,m.bouncing=!1,m.opacity=.4,m.enabled=!1!==this.options?.reflection?.enabled,this.ssrPass=m,!1!==this.options.ao?.enabled&&this.composer.addPass(p);const y=new et((e,t,s,i,r)=>{this.aoPass.enabled&&(this.initResolutionUniform(this.fquadBlendAO.material),this.renderer.setRenderTarget(this.gRenderTarget),this.fquadBlendAO.render(this.renderer),this.renderer.setRenderTarget(null))});this.composer.addPass(y);const S=new et((e,t,s,i,r)=>{this.renderer.setRenderTarget(this.gRenderTarget),this.renderScene(De.transparent),this.renderer.setRenderTarget(null)});this.composer.addPass(S),this.composer.addPass(h),this.composer.addPass(m),this.phasedRenderPass=new Ze(this.scene,this.camera,this.gRenderTarget),this.composer.addPass(this.phasedRenderPass),this.composer.addPass(u),u.emissiveTexture=this.gRenderTarget.textures[1],this.renderer.info.autoReset=!1,this.volumetricFogPass=new be(l),this.composer.addPass(this.volumetricFogPass),this.volumetricFogPass.enabled=!0,this.dofPass=new Y(this.scene,this.camera,{focus:1,aperture:.025,maxblur:.01}),this.dofPass.enabled=!1,this.composer.addPass(this.dofPass);const R=new ve;this.composer.addPass(R),this.colorPass=R,R.vignetteEnabled=!1,this.outlinePass=new pe(new i.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.outlinePass.enabled=!1,this.composer.addPass(this.outlinePass);const C=new x(v);C.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(C),this.fxaaPass=C,this.fxaaPass.enabled=!1,!0===s.enableOutlines&&this.setEnableOutlines(!0),new x(M).clear=!1,this.fixStatsStyle(),this.lutPass=new T({}),this.lutPass.enabled=!1,this.composer.addPass(this.lutPass);const F=new x(f,"prevtexture");F.enabled=!0,F.needsSwap=!1,F.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[1],F.renderToScreen=!0;const U=new Q;this.composer.addPass(U)}fixStatsStyle(){const e=this.stats.dom;e.style.position="absolute";const t=e.getElementsByTagName("canvas");for(let e=0;e<t.length;e++)t.item(e).style.display="inline-block"}setEnableOutlines(e){this.outlinePass.enabled=e,this.fxaaPass.enabled=e}setCamera(e){this.camera=e,this.composer.passes.forEach(t=>{t instanceof b?t.camera=e:t instanceof pe?t.renderCamera=e:(t instanceof ue||t instanceof Z)&&(t.camera=e)}),this.ssrPass&&(this.ssrPass.camera=e),this.aoPass&&(this.aoPass.camera=e),this.phasedRenderPass&&(this.phasedRenderPass.camera=e),null==this.csm?(this.csm=new K({maxFar:100,lightFar:250,lightMargin:20,cascades:We?2:4,shadowMapSize:2048*(We?.5:1),lightDirection:new i.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene,mode:"practical"}),this.csm&&Array.isArray(this.csm.lights),this.csm.fade=!0,h.lights_fragment_begin=y.lights_fragment_begin):(this.csm.camera=this.camera,this.camera),this.csm.updateFrustums()}setSelectedObjects(e){if(null==this.outlinePass)return;const t=new Map;for(const s of e)t.set(s.uuid,s);for(const s of e)s.traverse(e=>{e.uuid!==s.uuid&&t.has(e.uuid)&&t.delete(e.uuid)});this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t,s){const r=new i.WebGLRenderTarget(t.clientWidth*s,t.clientHeight*s);return r.texture.minFilter=i.NearestFilter,r.texture.magFilter=i.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,r.depthTexture=new i.DepthTexture(128,128),r.depthTexture.type=i.UnsignedShortType,r.depthTexture.minFilter=i.NearestFilter,r.depthTexture.magFilter=i.NearestFilter,r}static createAOMaskDepthRenderTarget(e,t){const s=new i.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio(),{type:i.HalfFloatType});return s.texture.minFilter=i.NearestFilter,s.texture.magFilter=i.NearestFilter,s.texture.generateMipmaps=!1,s.stencilBuffer=!1,s.depthTexture=new i.DepthTexture(128,128),s.depthTexture.type=i.UnsignedInt248Type,s.depthTexture.minFilter=i.NearestFilter,s.depthTexture.magFilter=i.NearestFilter,s}createSceneColorRenderTarget(e,t){const s=new i.WebGLRenderTarget(t.clientWidth*this.renderer.getPixelRatio(),t.clientHeight*this.renderer.getPixelRatio(),{count:2,type:i.FloatType,format:i.RGBAFormat,colorSpace:i.SRGBColorSpace,depthBuffer:!1,stencilBuffer:!1});return s.texture.minFilter=i.LinearFilter,s.texture.magFilter=i.LinearFilter,s.texture.generateMipmaps=!1,s}createGRenderTarget(){const e=this.container;null!=this.gRenderTarget&&this.gRenderTarget.dispose(),this.gRenderTarget=new u(e.clientWidth*this.renderer.getPixelRatio(),e.clientHeight*this.renderer.getPixelRatio(),{count:3,minFilter:i.NearestFilter,magFilter:i.NearestFilter,type:i.HalfFloatType,format:i.RGBAFormat}),this.gRenderTarget.depthTexture=new i.DepthTexture(e.clientWidth,e.clientHeight),this.gRenderTarget.depthTexture.type=i.UnsignedIntType,this.gRenderTarget.depthTexture.minFilter=i.NearestFilter,this.gRenderTarget.depthTexture.magFilter=i.NearestFilter,this.gRenderTarget.texture.generateMipmaps=!1,this.gRenderTarget.stencilBuffer=!1}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(){this.running=!1,window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],this.renderer.dispose(),this.gRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.sceneColorRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren(),this.volumetricFogPass.dispose(),w.clearSceneCache(this.scene)}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.container.contains(this.stats.dom)?this.container.appendChild(this.stats.dom):!this._showStats&&this.container.contains(this.stats.dom)&&this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}applyEnvMap(e){if(null!=this.scene.environment&&(e instanceof A&&(null==e.envMap||e.userData.useSceneEnv)&&(e.userData.useSceneEnv=!0,null==e.uniforms.envMap&&(e.uniforms.envMap={value:this.scene.environment},e.uniformsNeedUpdate=!0,e.uniforms.envMapRotation={value:ze(this.scene.environmentRotation,this.scene.environment,new i.Matrix3)}),null==e.uniforms.envMapIntensity&&(e.uniforms.envMapIntensity={value:1},e.uniformsNeedUpdate=!0),e.uniforms.envMap.value=this.scene.environment,e.uniforms.envMapIntensity.value=this.scene.environmentIntensity,e.envMap=this.scene.environment),e instanceof A||e instanceof i.MeshStandardMaterial)){const t=this.gbufferMaterialCache.get(e);null==t||this.gbufferMaterialCache.has(t)||this.applyEnvMap(t)}}setupCsm(e){if(e instanceof i.Mesh||e instanceof i.SkinnedMesh)if(e.material instanceof Array)for(const t of e.material)this.csm.setupMaterial(t);else this.csm.setupMaterial(e.material)}updateUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s){const t=i[e],r=s[e].value;null!=t&&t.value!==r&&(t.value=r)}}updateLightUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e of tt){const t=i[e],r=s[e];null!=r&&null!=t&&(t.value=r.value)}}createGBufferMaterial(e,t){const s=t===De.opaque?this.gbufferMaterialCache:this.tbufferMaterialCache;let r=s.get(e);if(null==r){let n=_.uv;e instanceof Re&&null!=e.heightMap&&(n=Ce(n,L(e.heightMap),C(e.heightScale??1)));let o=G.normal;e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial?null!=e.normalMap&&(o=R(L(e.normalMap).sample(n),e.normalScale.x??1)):e instanceof A&&null!=e.outputNormal&&(o=e.outputNormal),!0!==e.userData.disableAO&&(o=H("DOUBLE_SIDED",o,e=>N(new k("gl_FrontFacing"),e,e.multiplyScalar(-1))));let l=e.userData?.reflective?C(0):C(1);if(e instanceof i.MeshStandardMaterial){const t=U("roughness",e.roughness??1);l=null!=e.roughnessMap?L(e.roughnessMap).sample(n).g.multiply(t):t}else e instanceof A&&null!=e.outputRoughness&&(l=e.outputRoughness);let h=null;(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial)&&null!=e.lightMap&&(h=L(e.lightMap).sample(n).rgb.multiplyScalar(e.lightMapIntensity));let u,c=C(0);if(e instanceof i.MeshStandardMaterial){const t=U("metalness",e.metalness??0);c=null!=e.metalnessMap?L(e.metalnessMap).sample(n).b.multiply(t):t}else e instanceof A&&e.outputRoughness;let p=C(1);e instanceof i.MeshStandardMaterial?null!=e.aoMap&&(u=L(e.aoMap).sample(n).r,p=U("aoMapIntensity",e.aoMapIntensity)):e instanceof A&&e.outputRoughness;const f=U("opacity",e.opacity??1);let g=C(1);e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial?(null!=e.alphaMap&&(g=L(e.alphaMap).sample(n).r),g=g.multiply(f)):e instanceof A&&null!=e.outputOpacity&&(g=e.outputOpacity);let v=W(0,1);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial||e instanceof i.MeshBasicMaterial){const t=E("color",(new i.Vector3).setFromColor(e.color));null!=e.map?(v=L(e.map).sample(n).multiply(W(t,1)),g=g.multiply(v.w)):v=W(t,1)}const M=!0===e.userData.hasBloom;let T=D(0);if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial){const t=E("emissive",(new i.Vector3).setFromColor(e.emissive));T=null!=e.emissiveMap?L(e.emissiveMap).sample(n).rgb.multiply(t):t,T=T.multiplyScalar(e.emissiveIntensity)}else e instanceof A&&null!=e.outputEmissive&&(T=e.outputEmissive);const b=e instanceof d&&null!=e.uniforms[te],x=e instanceof d&&null!=e.uniforms[de],P=e instanceof d&&null!=e.uniforms[he],y=e.transparent&&e.alphaTest<=.01||e.blending===i.AdditiveBlending,w=U("alphaTest",e.alphaTest);let j,V=e.alphaTest>0?g.lt(w):y&&t===De.opaque?g.lt(.8):S(!1);!0===e.userData.isDecal&&(V=V.or(Ue)),j=y?q(0,0,0,0):(a=o,I(a).multiplyScalar(.5).addScalar(.5)).rgba(l);const z=e instanceof A?e.outputPosition:void 0,$=e instanceof A?e.outputTransform:void 0;let X,Y=W("black",1);if(e instanceof A&&null!=e.outputColor)Y=e.outputColor;else if(e instanceof i.MeshStandardMaterial)Y=F({color:v,metalness:c,roughness:l,emissive:T.rgb,normal:o,ambientOcclusion:u,ambientOcclusionIntensity:p,bakedLight:h});else if(e instanceof i.MeshLambertMaterial||e instanceof i.MeshPhongMaterial)Y=B({color:v.rgb});else if(e instanceof i.MeshBasicMaterial){let e=v.rgb,t=h??D("white");null!=u&&(t=t.multiplyScalar(u.subtract(1).multiply(p).add(1))),e=e.multiply(t),Y=e.rgba(g)}else e instanceof i.MeshToonMaterial&&(Y=O({color:v,emissive:T.rgb,normal:o,ambientOcclusion:u,ambientOcclusionIntensity:p,bakedLight:h}));(e instanceof A||e instanceof i.MeshStandardMaterial)&&(X=e.envMap);let Q=!0;(e instanceof m||e instanceof i.MeshBasicMaterial||e instanceof i.ShaderMaterial)&&(Q=e.fog);let K=W(Y.rgb,g);Q&&(K=new FogNode(K)),r=new A({transform:$,position:null==$?z:void 0,outputs:[K,T.rgba(t===De.opaque?w:M?1:0),j],opacity:g,outputEncoding:!1,fog:Q,transparent:e.transparent,lights:!0,envMap:X,discard:V}),e instanceof i.MeshStandardMaterial&&null!=e.envMap&&null!=r.uniforms.envMapIntensity&&(r.uniforms.envMapIntensity.value=e.envMapIntensity),(e instanceof A||e instanceof i.MeshStandardMaterial)&&this.applyEnvMap(r),e instanceof A&&Object.assign(r.defines,e.defines),r.userData.mrtOutputs=3,r.forceSinglePass=e.forceSinglePass,r.side=e.side,r.blending=e.blending,y?(r.depthWrite=!e.transparent,r.depthTest=e.depthTest,r.colorWrite=t===De.transparent):(r.depthWrite=e.depthWrite,r.depthTest=e.depthTest),r.visible=e.visible,r.alphaTest=e.alphaTest,r.alphaHash=e.alphaHash,t===De.opaque?(r.visible&&(r.visible=!b&&!x&&!P),r.visible&&(r.visible=!y)):t===De.transparent&&r.visible&&(r.visible=y||b||x||P),Object.assign(r.userData,e.userData),r.visible&&(this.csm.setupMaterial(r),e instanceof d&&Object.assign(r.uniforms,e.uniforms)),s.set(e,r)}var a;return r.visible&&e instanceof d&&this.updateUniformValues(e,r),r}loop(e,t=!1){const s=this.stats,r=s.addPanel(new J.Panel("Calls","#83f","#002")),a=s.addPanel(new J.Panel("Triangles","#c32","#002"));let l;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(l=new ce(this.renderer.getContext()),s.addPanel(l)),this.showStats=t;let h=10,d=1e3;const u=()=>{const e=this.renderer.info.render.calls;e>h&&(h=e,setTimeout(()=>h=10,5e3)),r.update(e,h);const t=this.renderer.info.render.triangles;t>d&&(d=t,setTimeout(()=>d=1e3,5e3)),a.update(t,d)};performance.now();i.Ray.prototype.intersectTriangle;this.resizeRender();const c=[],p=[],m=[];let f=0;const g=new n,v=new n;let M=0;let T=this.paused;const b=t=>{const r=this.renderer.getContext();if(this.paused&&this.running&&r.drawingBufferHeight>1)return setTimeout(()=>b(t),500),void(T=!0);this.renderer.clear(),this.applyPostProcessSettings(),this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,s.begin(),this.showStats&&l?.startQuery(),this.ssrPass.gpuPanel=l;let a=(t*=.001)-f;if(f=t,T&&(a=.016,T=!1),g.copy(this.camera.matrixWorld),a>1){let t=a;for(;t>.05;)e(je),t-=je;e(t)}else e(a);this.onLoopCallbacks.forEach(e=>e(a)),this.camera?.updateMatrixWorld(),v.copy(this.camera.matrixWorld),t-M>.08&&!v.equals(g)&&(this.renderer.shadowMap.needsUpdate=!0,M=t),this.csm.update();let n=!1;c.length=0,p.length=0,m.length=0;const h=_e;qe.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),h.setFromProjectionMatrix(qe);let d=!1,x=!1,P=!1;this.scene.traverseVisible(e=>{if(this.setupCsm(e),this.outlineEffect.apply(e),e instanceof Se&&(d=!0),e instanceof o&&this.initCustomDepthMaterial(e),(e instanceof o||e instanceof i.Sprite)&&(this.initResolutionUniform(e.material),this.initNormalUniform(e.material),this.initShadowUniform(e,e.material),null!=this.scene.environment&&function(e,t){if(Array.isArray(e.material))for(const s of e.material)t(s);else null!=e.material&&t(e.material)}(e,e=>this.applyEnvMap(e)),!0===e.material?.userData?.hasBloom&&(n=!0)),(e instanceof o||e instanceof i.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[te])&&isObjectInFrustum(e,h)?(this.initDepthUniform(e.material),x=!0):e instanceof X&&(e.visible=!1,p.push(e)),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[he]&&isObjectInFrustum(e,h)&&e.material instanceof A&&this.initAoUniform(e.material),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[de]&&isObjectInFrustum(e,h)&&(m.push(e),e.material.uniforms[de].value=this.sceneColorRenderTarget.texture,P=!0),e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[le])e.material.uniforms[le].value=t;else if(e instanceof o&&Array.isArray(e.material))for(const s of e.material)s.uniforms&&null!=s.uniforms[le]&&(s.uniforms[le].value=t)}),this.bloomPass.enabled=n,this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clear(),this.renderScene(De.opaque),this.aoPass.output=Z.OUTPUT.Off,(x||P)&&(this.fquadCopyOpaque.material.uniforms.tSceneColor.value=this.gRenderTarget.textures[0],this.fquadCopyOpaque.material.uniforms.tDepthTexture.value=this.gRenderTarget.depthTexture,this.initResolutionUniform(this.fquadCopyOpaque.material),this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.renderer.clear(),this.fquadCopyOpaque.render(this.renderer),this.renderer.setRenderTarget(this.gRenderTarget)),m.length,c.forEach(e=>e.visible=!0),p.forEach(e=>e.visible=!0),m.forEach(e=>e.visible=!0),this.aoPass.enabled,this.ssrPass&&(this.ssrPass.elapsedTime=t),this.volumetricFogPass&&d&&this.volumetricFogPass.update(this.camera,this.gRenderTarget,this.csm,this.scene);try{!this.paused&&this.running&&(this.render(a),this.showStats&&l?.endQuery(),this.showStats&&u(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}s.end(),this.csm?.update(),this.running&&!0!==this.options.enableXR&&(this.fpsCap?setTimeout(()=>{requestAnimationFrame(b)},1e3/this.fpsCap):requestAnimationFrame(b))};!0===this.options.enableXR?this.renderer.setAnimationLoop(b):requestAnimationFrame(b)}renderScene(e){Ye.clear(),Qe.length=0;fe(this.scene,t=>{if(Ke(t))return Qe.push(t),t.visible=!1,!1;if(t instanceof o){Ye.set(t,t.material);let s=!1;if(Array.isArray(t.material)){t.material=t.material.slice();for(let i=0;i<t.material.length;i++)t.material[i]=this.createGBufferMaterial(t.material[i],e),s||(s=t.material[i].visible)}else t.material=this.createGBufferMaterial(t.material,e),s||(s=t.material.visible);s?t.visible=!0:null!=t.children&&0!=t.children.length||(Qe.push(t),t.visible=!1)}});const t=this.scene.matrixWorldAutoUpdate,s=this.scene.matrixAutoUpdate,i=this.renderer.shadowMap.autoUpdate;e!==De.opaque&&(this.renderer.shadowMap.autoUpdate=!1,this.scene.matrixWorldAutoUpdate=!1,this.scene.matrixAutoUpdate=!1);try{this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Render failed",e)}e===De.opaque&&Ye.forEach((e,t)=>{!Array.isArray(e)&&!Array.isArray(t.material)&&e instanceof d&&this.updateLightUniformValues(t.material,e)}),Ye.forEach((e,t)=>{t.material=e}),Qe.forEach((e,t)=>{e.visible=!0,e.updateMatrixWorld(!0)}),this.renderer.shadowMap.autoUpdate=i,this.scene.matrixWorldAutoUpdate=t,this.scene.matrixAutoUpdate=s}getEnvTexture(e){null==this.pmremGenerator&&(this.pmremGenerator=new i.PMREMGenerator(this.renderer),this.pmremGenerator.compileEquirectangularShader());let t=this.pmremGeneratorResults.get(e);return null==t&&(t=this.pmremGenerator.fromEquirectangular(e).texture,this.pmremGeneratorResults.set(e,t)),t.colorSpace=i.SRGBColorSpace,t}applyPostProcessSettings(){if(0==this.postProcessVolumes.length)return this.lutPass.enabled=!1,void(this.colorPass.enabled=!1);var e;(e=this.postProcessSettings).tonemapMapping=void 0,e.tonemapExposure=1,e.envIntensity=1,e.envTexture=void 0,e.vignetteIntensity=0,e.colorTint=new i.Color("white"),e.colorTintIntensity=0,e.depthFocus=void 0,e.depthAperture=void 0,e.depthMaxBlur=void 0,e.temperature=6500,e.temperatureTint=0,e.lut=void 0,e.lutIntensity=0;const t=this.postProcessSettings;let s,r=!1,a=!1,n=!1,o=!1;if(null==this.camera)return;const h=this.camera.getWorldPosition(ke);let d=[];for(const e of this.postProcessVolumes){if(!Ve(e.object))continue;let l=e.blendWeight??1;const u=e.distanceToPoint(h);u>e.blendRadius||(e.blendRadius>0&&(l*=ge(1-u/e.blendRadius,0,1)),l>1&&(l=1),l>0&&(d.push(e),void 0!==e.settings.tonemapMapping&&(t.tonemapMapping=e.settings.tonemapMapping),void 0!==e.settings.tonemapExposure&&(t.tonemapExposure=i.MathUtils.lerp(t.tonemapExposure,e.settings.tonemapExposure,l)),void 0!==e.settings.envTexture&&(t.envTexture=e.settings.envTexture),void 0!==e.settings.envIntensity&&(t.envIntensity=i.MathUtils.lerp(t.envIntensity,e.settings.envIntensity,l)),void 0!==e.settings.vignetteIntensity&&(t.vignetteIntensity=i.MathUtils.lerp(t.vignetteIntensity,e.settings.vignetteIntensity,l),a=!0),void 0!==e.settings.colorTint&&void 0!==e.settings.colorTintIntensity&&e.settings.colorTintIntensity>0&&(t.colorTint=t.colorTint.lerp(e.settings.colorTint,l),o=!0),void 0!==e.settings.colorTintIntensity&&(t.colorTintIntensity=i.MathUtils.lerp(t.colorTintIntensity,e.settings.colorTintIntensity,l)),void 0!==e.settings.depthFocus&&(r=!0,t.depthFocus=void 0!==t.depthFocus?i.MathUtils.lerp(t.depthFocus,e.settings.depthFocus,l):e.settings.depthFocus),void 0!==e.settings.depthAperture&&(r=!0,t.depthAperture=void 0!==t.depthAperture?i.MathUtils.lerp(t.depthAperture,e.settings.depthAperture,l):e.settings.depthAperture),void 0!==e.settings.depthMaxBlur&&(r=!0,t.depthMaxBlur=void 0!==t.depthMaxBlur?i.MathUtils.lerp(t.depthMaxBlur,e.settings.depthMaxBlur,l):e.settings.depthMaxBlur),void 0!==e.settings.temperature&&(t.temperature=i.MathUtils.lerp(t.temperature,e.settings.temperature,l)),void 0!==e.settings.temperatureTint&&(t.temperatureTint=i.MathUtils.lerp(t.temperatureTint,e.settings.temperatureTint,l)),void 0!==e.settings.lut&&(s=e.settings.lut,n=!0),void 0!==e.settings.lutIntensity&&(t.lutIntensity=i.MathUtils.lerp(t.lutIntensity,e.settings.lutIntensity,l),n=!0)))}this.renderer.toneMapping=t.tonemapMapping??i.NoToneMapping,this.renderer.toneMappingExposure=t.tonemapExposure,null!=t.envTexture&&(this.scene.environment=this.getEnvTexture(t.envTexture)),this.scene.environmentIntensity=t.envIntensity,this.colorPass.vignetteIntensity=t.vignetteIntensity,this.colorPass.vignetteEnabled=a,this.colorPass.colorTint=t.colorTint,this.colorPass.colorTintIntensity=t.colorTintIntensity,this.colorPass.enabled=a||o,r&&this.camera instanceof l?(this.dofPass.enabled=!0,void 0!==t.depthFocus&&(this.dofPass.uniforms.focus.value=t.depthFocus),void 0!==t.depthAperture&&(this.dofPass.uniforms.aperture.value=t.depthAperture),void 0!==t.depthMaxBlur&&(this.dofPass.uniforms.maxblur.value=t.depthMaxBlur)):this.dofPass.enabled=!1,this.colorPass.temperature=t.temperature,this.colorPass.temperatureTint=t.temperatureTint,this.lutPass.enabled=n,n&&(null!=s&&(s.flipY=!0,s.generateMipmaps=!1),this.lutPass.lut=s,this.lutPass.intensity=t.lutIntensity)}renderOverlay(){if(0===this.overlayCameras.size)return;const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.previousClientWith/2,s=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let i=0;i<e.length;i++)this.renderer.clearDepth(),this.renderer.setViewport(t-s/2+this.insetWidth*i+this.insetMargin*i,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[i])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){if(0===this.composer.renderTarget1.width||0===this.composer.renderTarget1.height)return;if(0===this.composer.renderTarget2.width||0===this.composer.renderTarget2.height)return;let t=!1;if(this.ssrPass.enabled&&!1!==this.options?.reflection?.enabled){const e=this.ssrPass.selects??[];e.length=0,this.scene.traverseVisible(t=>{t instanceof o&&!0===t.material.userData?.reflective&&isObjectInFrustum(t,_e)&&e.push(t)}),this.ssrPass.selects=e,0==e.length&&(this.ssrPass.enabled=!1),t=!0}this.options.bloom,this.composer.render(e),this.scene.matrixWorldAutoUpdate=!0,this.scene.matrixAutoUpdate=!0,t&&(this.ssrPass.enabled=!0)}hasBloom(){return null!=me(this.scene,e=>e instanceof o&&!0===e.material?.userData?.hasBloom)}darkenNonBloomed(e){if((e instanceof o||e instanceof i.Sprite||e instanceof i.Line)&&e.visible&&(null==e.material.userData||!0!==e.material.userData.hasBloom)){if(e.material?.id===Be.id)return;this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=Be:(e.visible=!1,this.bloomHidden.push(e))}else"TransformControlsPlane"!==e.type&&"TransformControlsGizmo"!==e.type||(e.visible=!1,this.bloomHidden.push(e))}restoreMaterial(e){this.bloomStoredMaterials[e.uuid]&&(e.material=this.bloomStoredMaterials[e.uuid],delete this.bloomStoredMaterials[e.uuid],e.visible=!0)}initDepthUniform(e){e instanceof d&&(e.uniforms[te].value=this.sceneColorRenderTarget.textures[1],this.camera instanceof l&&(null!=e.uniforms[ie]&&(e.uniforms[ie].value=this.camera.near),null!=e.uniforms[se]&&(e.uniforms[se].value=this.camera.far)))}initNormalUniform(e){e instanceof d&&null!=e.uniforms[ae]&&(e.uniforms[ae].value=this.gRenderTarget.textures[2])}initShadowUniform(e,t){t instanceof A&&t.uniforms.receiveShadow&&(t.uniforms.receiveShadow.value=e.receiveShadow)}initResolutionUniform(e){if(e instanceof d&&null!=e.uniforms[re]){const t=this.previousClientWith,s=this.previousClientHeight;e.uniforms[re].value.set(t*this.renderer.getPixelRatio(),s*this.renderer.getPixelRatio())}}initAoUniform(e){if(this.aoPass.enabled){e.uniforms[he].value=this.aoPass.pdRenderTarget.texture,null==e.defines.USE_SSAO_MAP&&(e.defines.USE_SSAO_MAP="",e.needsUpdate=!0),e.defines.USE_SSAO_MAP="";const t=this.tbufferMaterialCache.get(e);null!=t&&this.initAoUniform(t)}else if(null!=e.defines.USE_SSAO_MAP){delete e.defines.USE_SSAO_MAP,e.needsUpdate=!0;const t=this.tbufferMaterialCache.get(e);null!=t&&this.initAoUniform(t)}}initCustomDepthMaterial(e){if(null!=e.customDepthMaterial||!e.castShadow)return;const t=e.material;if(t instanceof A&&!t.transparent&&t.depthWrite){let s=this._customDepthMaterialCache.get(t);if(null==s){const e=we(ye);let i;null!=t.alphaTest&&t.alphaTest>0&&null!=t.outputOpacity&&(i=t.outputOpacity.lt(t.alphaTest)),s=new A({color:e,discard:i}),this._customDepthMaterialCache.set(t,s)}e.customDepthMaterial=s}}};Le=e=t([ee(),s("design:paramtypes",[HTMLElement,Object])],Le);export{Le as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const je=.05;function Ve(e){let t=e;for(;t;){if(!1===t.visible)return!1;t=t.parent}return!0}Z.prototype.overrideVisibility=function(){const e=this.scene,t=this._visibilityCache;e.traverse(function(e){if(t.set(e,e.visible),(e.isPoints||e.isLine||e.isTransformControls||e.isSprite)&&(e.visible=!1),null!=e.material){let t=!1,s=!1;if(Array.isArray(e.material)){for(const s of e.material)if(null!=s.alphaTest&&s.alphaTest>0){t=!0;break}}else null!=e.material.alphaTest&&e.material.alphaTest>0?t=!0:!0===e.material.userData.isDecal&&(s=!0);s&&(e.visible=!1)}})};const _e=new i.Frustum,Ge=new i.Box3,qe=new i.Matrix4;export function isObjectInFrustum(e,t){const s=Ge.setFromObject(e);return t.intersectsBox(s)}const ke=new i.Vector3;const Ne=new n,He=new p;function ze(e,t,s=new i.Matrix3){return He.copy(e),He.x*=-1,He.y*=-1,He.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(He.y*=-1,He.z*=-1),s.setFromMatrix4(Ne.makeRotationFromEuler(He))}const $e=new A({outputs:[q(0,0,0,0),q(0,0,0,0),W(D("white"),Fe(4))],transparent:!0}),Xe=new i.MeshBasicMaterial({color:"blue",transparent:!0,opacity:.5});$e.depthWrite=!1;new o(new i.BoxGeometry(4,4,4),Xe);const Ye=new Map,Qe=[];function Ke(e){return e instanceof i.Sprite||e.isPoints||e.isLine||e.isTransformControls||e.isTransformControlsGizmo||e instanceof o&&Je(e,e.material)}function Je(e,t){return null==t||(Array.isArray(t)?t.some(t=>Je(e,t)):t instanceof i.RawShaderMaterial||t instanceof i.ShaderMaterial&&!(t instanceof A))}class Ze extends Ee{constructor(e,t,s){super(),this.scene=e,this.camera=t,this.gRenderTarget=s,this.needsSwap=!1}render(e,t,s,i,r){const a=e.autoClear;e.autoClear=!1;const n=this.scene.matrixWorldAutoUpdate,l=this.scene.matrixAutoUpdate,h=e.shadowMap.autoUpdate;this.scene.matrixAutoUpdate=!1,e.shadowMap.autoUpdate=!1;const d=s.depthTexture;s.depthTexture=this.gRenderTarget.depthTexture,e.setRenderTarget(s),Qe.length=0;let u=0;this.scene.traverseVisible(e=>{const t=Ke(e);e instanceof o&&!t?(Qe.push(e),e.visible=!1):t&&u++}),u>0&&e.render(this.scene,this.camera),Qe.forEach((e,t)=>{e.visible=!0}),e.setRenderTarget(null),e.autoClear=a,s.depthTexture=d,this.scene.matrixWorldAutoUpdate=n,this.scene.matrixAutoUpdate=l,e.shadowMap.autoUpdate=h}}class et extends Ee{constructor(e){super(),this.fn=e}render(e,t,s,i,r){this.fn(e,t,s,i,r)}}const tt=["ambientLightColor","cameraNear","directionalLightShadows","directionalLights","directionalShadowMap","directionalShadowMatrix","fogColor","fogDensity","fogFar","fogNear","hemisphereLights","lightProbe","ltc_1","ltc_2","pointLightShadows","pointLights","pointShadowMap","pointShadowMatrix","rectAreaLights","shadowFar","spotLightMap","spotLightMatrix","spotLightShadows","spotLights","spotShadowMap"],st=E("fogColor");export class FogNode extends ${constructor(e,t=st){super(),this.source=e,this.fogColor=t}compile(e){const t=e.variable(),s=e.get(this.source.rgb),i=e.get(this.source.a),r=e.get(this.fogColor),a=e.get(U("fogFar")),n=e.get(U("fogNear")),o=e.get(U("fogDensity")),l=e.get(V(j.mvPosition.z));return{pars:"\n ",chunk:`\n #ifdef FOG_EXP2\n float fogFactor_${t} = 1.0 - exp( - ${o} * ${o} * ${l} * ${l} );\n #else\n float fogFactor_${t} = smoothstep( ${n}, ${a}, ${l} );\n #endif\n vec4 color_vec4_${t} = vec4(mix(${s}, ${r}, fogFactor_${t}), ${i});\n `,out:`color_vec4_${t}`}}}/*
2
2
  * Copyright (©) 2025 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,4 +1,4 @@
1
- import{__decorate as e,__metadata as t}from"tslib";import{ConvexPolyhedronCollisionShape as a}from"@hology/core";import{Subject as s}from"rxjs";import*as r from"three";import{BoxGeometry as i,Color as n,Euler as o,Fog as l,FogExp2 as c,Group as h,Material as p,Matrix4 as m,Mesh as d,MeshLambertMaterial as u,MeshPhongMaterial as f,MeshStandardMaterial as g,Object3D as y,PointLight as w,Quaternion as M,Scene as v,Texture as b,Vector2 as A,Vector3 as S,Vector4 as x}from"three";import j,{SpriteRenderer as I}from"@hology/nebula";import{batchingUniformFloat as D,batchingUniformVec2 as P,batchingUniformVec3 as C,batchingUniformVec4 as E,bool as T,BooleanExpression as V,BooleanNode as O,colorToNormal as k,float as z,FloatNode as F,ifDefApply as B,mix as N,NodeShaderMaterial as _,rgb as U,rgba as $,RgbNode as W,select as L,standardMaterial as R,Texture2dLookupNode as G,textureSampler2d as H,textureSampler2dArray as J,varyingAttributes as q,varyingTransformed as X,vec2 as Y,Vec2Node as Z,vec3 as K,Vec3Node as Q,vec4 as ee,Vec4Node as te}from"three-shader-graph";import{Service as ae}from"typedi";import{VfxActor as se}from"../effects/vfx/vfx-actor.js";import{VisualEffect as re}from"../effects/vfx/vfx-param.js";import{Prefab as ie}from"./objects/prefab.js";import{BaseActor as ne}from"../gameplay/actors/actor.js";import oe from"../gameplay/actors/builtin/index.js";import{PhysicsBodyType as le,ThreeBlendingMode as ce,withInjectionContext as he}from"../gameplay/index.js";import{RenderingView as pe}from"../rendering.js";import{curveSampler as me,oneMinus as de,particleUniforms as ue,Sampler2DNode as fe}from"../shader-nodes/index.js";import{LambertShader as ge}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as ye}from"../shader/builtin/landscape-composite-shader";import{LandscapeShader as we}from"../shader/builtin/landscape-shader.js";import{StandardShader as Me}from"../shader/builtin/standard-shader.js";import{UnlitShader as ve}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as be}from"../shader/parameter.js";import{ArrayMap as Ae,DefaultMap as Se,groupBy as xe}from"../utils/collections.js";import{iterateMaterials as je}from"../utils/materials.js";import{filterChildrenShallow as Ie,filterSceneShallow as De,findFirstVisibleMesh as Pe,findFirstVisibleObject as Ce,traverseAsync as Ee}from"../utils/three/traverse.js";import{AssetMeshInstance as Te,AssetResourceLoader as Ve}from"./asset-resource-loader.js";import{isCollisionMesh as Oe}from"./collision/collision-shape-import.js";import{BoxCollisionShape as ke,PhysicalShapeMesh as ze}from"./collision/collision-shape.js";import{LandscapeManager as Fe}from"./landscape/landscape-manager.js";import{initLandscape as Be}from"./landscape/landscape.js";import{SectionGrid as Ne,smoothNormalsCrossMeshes as _e}from"./landscape/utils.js";import{createGrassFoliageMaterial as Ue}from"./materials/grass-foliage.js";import{createGrassMaterial as $e}from"./materials/grass.js";import{getMaterialAttribute as We}from"./materials/utils/material-painting.js";import{createWaterMaterial as Le}from"./materials/water.js";import{SerializedParamType as Re}from"./model.js";import{ShapeLibrary as Ge,ShapeLibraryKeys as He}from"./objects/shapes.js";import{ambientLightName as Je,createSky as qe,defaultSkyMaterial as Xe}from"./sky.js";import{Curve2 as Ye}from"../utils/curve.js";import{DecalUnlitShader as Ze}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as Ke}from"../shader/builtin/decal-standard-shader.js";import{ColorLayer as Qe,defaultValueColorLayer as et,defaultValueMaskLayer as tt,MaskLayer as at}from"../shader/color-layer.js";import{LayeredShader as st}from"../shader/builtin/layered-shader";import{isColorLayerSerialized as rt}from"../shader/color-layer";import{FogVolume as it}from"../rendering/fog/fog-volume-actor.js";import{UnscaledSprite as nt}from"../utils/three/unscaled-sprite.js";import{ToonShader as ot}from"../shader/builtin/toon-shader.js";import{BatchedMesh2 as lt}from"./batched-mesh-2.js";import{ParallaxStandardMaterial as ct}from"../shader/builtin/standard-shader";import{parallaxOcclusionMapping as ht}from"../shader-nodes/pom.js";import{traverseVisibleEvery as pt}from"../utils/three/traverse";const mt={},dt=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),ut=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||(navigator.userAgent.includes("iPhone")||navigator.userAgent.includes("iPad"))&&!!navigator.userAgent.match(/AppleWebKit/)&&!navigator.userAgent.match(/CriOS/);export const shapeDefaultColor="#aaaaaa";export class SceneMaterializerLoader{constructor(e,t,a){this.dataProvider=e,this.assetsService=t,this.assetManagerService=a}get(e,t){return new ft(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}let ft=class{constructor(e,t,a,i,n,o,l,c){this.scene=e,this.dataProvider=t,this.assetsService=a,this.assetManagerService=i,this.renderingView=n,this.shaders=o,this.actorTypes=l,this.actorProvider=c,this.objectMap=new Map,this.sceneObjectMap=new Map,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.inEditor=!0,this.updated$=new s,this.removed$=new s,this.error$=new s,this.editorActorParamSnapshot=new Map,this.assets=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,this.pmremGeneratorResults=new WeakMap,this.prefabInstanceChain=[],this.geometryCache=new Map,this.collisionShapeCache=new Map,this.originalFog=null,t.onCreate(e=>this.update(e)),t.onUpdate(e=>this.update(e)),t.onRemove(e=>this.remove(e)),this.createAssetSubscription=a.onCreate.subscribe(e=>{this.assets.set(e.id,e)}),this.updateSubscription=a.onUpdate.subscribe(async t=>{this.assets.set(t.id,t),"material"==t.type?e.traverse(e=>{if(e instanceof r.Mesh)if(Array.isArray(e.material))for(let a=0;a<e.material.length;a++)this.refreshMaterial(e,e.material[a],t,a);else this.refreshMaterial(e,e.material,t)}):"mesh"==t.type?(this.findByAssetId(t.id).forEach(e=>{this.remove(e.userData.src),this.materializeAndInitActor(e.userData.src)}),this.landscapeManagers.forEach(e=>{const a=e.source?.grass?.layers?.some(e=>e.meshes.some(e=>e.assetId===t.id));a&&e.queueRefreshScatter(this.renderingView?.camera.position??new S,!0)})):"prefab"===t.type?this.findByAssetId(t.id).forEach(e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t)}):"vfx"===t.type&&this.dataProvider.getObjects().forEach(e=>{It(e,(e,a)=>{"vfx"===e.type&&e.assetId===t.id&&(this.remove(e),this.materializeAndInitActor(e))})})})}async refreshMaterial(e,t,a,s){const r=t?.userData?.assetId;if(r!==a.id){const e=this.assets.get(r);let t=!1;if(null!=e)for(const s of Object.values(e.material.shaderParams)){if(s.type===Re.Material&&s.value===a.id){t=!0;break}if(s.type===Re.Array&&"element"in s&&s.element===Re.Material&&s.value.includes(a.id)){t=!0;break}}if(!t)return}const i=await materialFromAsset(this.assets.get(r),this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1),n=i.userData;i.userData=t.userData,i.userData.hasBloom=n.hasBloom,i.userData.reflective=n.reflective,i.userData.outlineParameters=n.outlineParameters,null!=s?Ot(e.material[s],i)||(e.material[s]=i):Ot(e.material,i)||(e.material=i,e===this.sky&&this.applySkySettings(e.material))}getTopLevelActors(){return Array.from(this.materializedActors.entries()).filter(([e,t])=>!e.includes("/")).map(([,e])=>e)}get actorInstances(){return Array.from(this.materializedActors.values())}async initTextures(){const e=[];if(await Promise.all(this.dataProvider.getObjects().filter(e=>"shape_mesh"===e.type||"asset_mesh"===e.type).filter(e=>null!=e.materialAssignments).flatMap(e=>e.materialAssignments).map(async t=>{const a=this.assets.get(t.materialId);if(null!=a)for(const t of Object.values(a.material.shaderParams))if(t.type===Re.Texture&&"string"==typeof t.value){const a=this.assets.get(t.value),s=await this.assetManagerService.getTexture(a);null!=s&&e.push(s)}})),0!==e.length&&this.renderingView){console.log(`Initializing ${e.length} textures`),console.time("Init textures");for(const t of e)this.renderingView.renderer.initTexture(t);console.timeEnd("Init textures")}}async prefetchAssets(){const e=Array.from(new Set(this.dataProvider.getObjects().filter(e=>null!=e.assetId&&"asset_mesh"==e.type).filter(e=>e.assetId)));await Promise.all(e.map(e=>this.assetsService.getAsset(e.assetId).then(e=>{if(null!=e)return this.assetManagerService.getMesh(e)}))),this.initTextures()}async init(){await this.preInit(),yt.clear(),wt.clear(),await this.prefetchAssets(),await Promise.all(this.dataProvider.getObjects().map(e=>this.materialize(e))),await this.initActorsPostInit()}initActorsPostInit(e=this.getTopLevelActors(),t){const a=e.map(async e=>{const a=e.object.userData.src??e.object.userData._src;if("vfx"===a.type)return Promise.resolve();const s=await this.assetsService.getAsset(a.assetId),r={...s?.actor?.params??{},...a.actor?.params??{}},i=null!=t?new Map(Array.from(this.materializedActors.entries()).filter(([e,a])=>e.startsWith(t.sceneObjectChain.join("/"))&&e.split("/").length-1===t.sceneObjectChain.length).map(([e,t])=>[e.split("/").pop(),t])):this.materializedActors;for(const t of a.actor.innerParams??[])await this.applyActorComponentParams(e,t.path.slice(),t.params,i);const n=await prepareClassParameters(r,e.constructor,this.assetsService,this.assetManagerService,i,this.renderingView,this.shaders,this.actorProvider);Object.assign(e,n);try{return await this.actorProvider.initActor(e)}catch(e){console.error(`Failed to initiate actor (name="${a.name}", id=${a.id})`,e)}});return Promise.all(a)}addVfxChildActors(e,t=e){}async applyActorComponentParams(e,t,a,s){const r=t.length,i=t.shift();if(0==r){const t=await prepareClassParameters(a,null,this.assetsService,this.assetManagerService,s,this.renderingView,this.shaders,this.actorProvider);for(const[a,s]of Object.entries(t))null!=s&&(e[a]=s)}else null!=e[i]&&await this.applyActorComponentParams(e[i],t,a,s)}canObjectBeInstanced(e){return e.physics?.type!==le.dynamic&&"sky"!==e.type&&"global_fog"!==e.type&&"world_env"!==e.type}async canAssetBeInstanced(e){let t=this._canBeInstancedCache.get(e.assetId);if(null==t){const a=await this.createFromAsset(e);if(null==a)return!1;const s=[];a.traverse(e=>{!Oe(e)&&e.isMesh&&s.push(e)});const r=1==s.length&&0==s[0].children.length,i=!ut,n=s.every(e=>!Array.isArray(e.material)||1===e.material.length),o=s.some(e=>e instanceof d&&null!=e.geometry.morphAttributes&&Object.keys(e.geometry.morphAttributes).length>0),l=!0;t=s.length>0&&(r||n&&i)&&l&&!o,this._canBeInstancedCache.set(e.assetId,t)}return t}async preInit(){this.renderingView?.onLoop(()=>{null!=this.sky&&this.renderingView.camera.getWorldPosition(this.sky.position)}),this.assetsService.getAssets().then(e=>{for(const t of e)this.assets.set(t.id,t)})}shouldBeMaterialized(e){if(null!=this.detailTier&&"asset_mesh"===e.type&&null!=e.assetId){const t=this.assets.get(e.assetId);if(null!=t){const e=t.mesh?.detailTier;if(null!=e)return e<=this.detailTier}}return!0}async initWithInstancing(){await this.preInit(),await this.prefetchAssets(),yt.clear(),wt.clear();const e=[],t=new Ae,a=new Ae,s=new Ae;let i=0,l=0,c=0;const h=new Map,p=new Se(()=>new Map);for(const r of this.dataProvider.getObjects())await It(r,async(r,o,m)=>{if(!this.shouldBeMaterialized(r))return;const u="asset_mesh"==r.type&&this.canObjectBeInstanced(r)&&await this.canAssetBeInstanced(r),f="shape_mesh"===r.type&&"landscape"!==r.shape&&r.physics?.type!==le.dynamic;if(u||f){if(o&&o.children?.length>0){const e=o.children.findIndex(e=>e.id===r.id);e>=0&&o.children.splice(e,1)}if(f){let e=r.shape+JSON.stringify(r.shapeParams??{})+r.castShadow+r.receiveShadow;const t=r.materialAssignments?.at(0)?.materialId,a=null!=t?this.assets.get(t):null;let i=null;if(null!=a&&"shader"!==a.material.type){if(e+=a.material.type+a.material.shader,null!=a.material.shaderParams){if(e+=Object.entries(a.material.shaderParams).filter(([e,t])=>"color"!=e).map(e=>JSON.stringify(e)).join(),null!=a.material.shaderParams.color){const e=a.material.shaderParams.color;e.type===Re.Color&&null!=e.value&&(i=new n(e.value))}}}else e+=t;s.push(e,{object:{...r,parentTransform:m},color:i}),c++}else{const e=this.assets.get(r.assetId);let s=h.get(r.assetId);if(null==s){const e=await this.createFromAsset(r,{assignMaterials:!1});if(null==e)return;if(s=h.get(r.assetId),null==s){s={useBatchedMesh:null!=Pe(e)&&pt(e,e=>!(e instanceof d)||this.testCanBatch(e.material,e.geometry)),assetMesh:e},h.set(r.assetId,s)}}const n=Pt(r.materialAssignments,e.materialAssignments);if(s.useBatchedMesh)await Ee(s.assetMesh,async e=>{if(!(e instanceof d))return;const t=Array.isArray(e.material)?e.material[0]:e.material,s=n.find(e=>null!=t.color&&Vt(e.color,t.color)&&(null==e.name||t.name===e.name))?.materialId;let o=t;if(null!=s){const e=this.assets.get(s);o=await materialFromAsset(e,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!0)}if(null!=o){p.get(r.id).set(e.uuid,o);let t=Nt(o);t+=Ft(e),a.push(t,{...r,parentTransform:m,meshUUID:e.uuid}),i++}else console.warn("Can not materialize mesh because missing material",r)});else{const e=r.assetId+JSON.stringify(r.materialAssignments??[]);t.push(e,{...r,parentTransform:m}),l++}}}else null==o&&e.push({...r,parentTransform:m})});console.log(`Scene init stats: \n Batched Assets: ${a.size} groups containing in total ${i} objects.\n Instanced Assets: ${t.size} groups containing in total ${l} objects.\n Shapes: ${s.size} batch groups containing in total ${c} objects. \n ${e.length} objects can not be batched. \n `);for(const e of h.values())this.prepareCollisionShapesForInstanced(e.assetMesh);console.time("materialize batches");for(const e of a.values()){if(0==e.length)continue;let t;const a=h.get(e[0].assetId).assetMesh;t=this.createBatchedMesh(e,p,h);const s=this.assets.get(e[0].assetId);t.castShadow=e[0].castShadow??s.castShadow??!0,t.receiveShadow=e[0].receiveShadow??s.receiveShadow??!0;const r=new Te;r.add(t),r.userData.src=e[0],a instanceof Te&&(r.collisionShapes=a.collisionShapes),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r)}for(const e of t.values()){if(0==e.length)continue;let t;const a=h.get(e[0].assetId).assetMesh;t=await this.createInstancedMesh(e,a);const s=this.assets.get(e[0].assetId);t.castShadow=e[0].castShadow??s.castShadow??!0,t.receiveShadow=e[0].receiveShadow??s.receiveShadow??!0;const r=new Te;r.add(t),r.userData.src=e[0],a instanceof Te&&(r.collisionShapes=a.collisionShapes),this.prepareCollisionShapesForInstanced(r),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r)}console.timeEnd("materialize batches");for(const e of s.values()){if(0==e.length)continue;const t=e[0].object,a=await this.createFromShape(t),s=Ce(a,e=>!Oe(e)&&null!=e.geometry),i=s.material.clone();null!=e[0].color&&null!=i.color&&(i.color=new n(16777215));const l=s.geometry;let c,h;!(ut||i instanceof _||null==l.index)?(c=new r.BatchedMesh(e.length,l.getAttribute("position").count,l.index.count,i),c.perObjectFrustumCulled=!0,h=c.addGeometry(l)):c=new r.InstancedMesh(l,i,e.length),c.castShadow=a.castShadow??!0,c.receiveShadow=s.receiveShadow??!0;for(let t=0;t<e.length;t++){const a=e[t],s=(new r.Matrix4).compose((new S).fromArray(a.object.position),(new M).setFromEuler((new o).fromArray(a.object.rotation)),(new S).fromArray(a.object.scale)),i=(new m).copy(a.object.parentTransform).multiply(s);let n;n=c instanceof r.BatchedMesh?c.addInstance(h):t,c.setMatrixAt(n,i),null!=a.color&&c.setColorAt(n,a.color)}for(let t=0;t<e.length;t++){const s=e[t],r=new Te;r.userData.src=e[0],a instanceof ze&&(r.collisionShapes=[a.collisionShape]),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r),r.add(c),null==c.userData.hasCollision&&(c.userData.hasCollision=[]),c.userData.hasCollision[t]=!!s.object.collisionDetection}}await Promise.all(e.map(e=>this.materialize(e))),await this.initActorsPostInit()}prepareCollisionShapesForInstanced(e){e instanceof Te&&e.collisionShapes.forEach(e=>{e instanceof a&&e.mesh instanceof d&&(e.mesh=e.mesh.geometry)})}testCanBatch(e,t){return!ut&&t.groups.length<2&&(!Array.isArray(e)||1==e.length)&&this.testCanBatchMaterial(e)}testCanBatchMaterial(e){const t=Array.isArray(e)?e[0]:e;return null!=t&&(!(t instanceof g)||null==t.bumpMap&&null==t.lightMap&&null==t.displacementMap)}createBatchedMesh(e,t,a){const s=new Ae;for(const t of e)null!=t.meshUUID?s.push(t.meshUUID??t.assetId,t):console.warn("Missing mesh uuid for batching");let i=0,o=0,l=0;const c=new Map;for(const[e,t]of s.entries()){const s=t[0].assetId,r=a.get(s);if(null==r){console.warn("Missing batching info for asset id "+s);continue}const n=Ce(r.assetMesh,t=>t instanceof d&&t.uuid===e);if(null==n){console.warn("Missing mesh in batched asset");continue}c.set(e,n);const h=n.geometry.getAttribute("position");null==h&&console.warn("Missing position attribute for batched mesh"),i+=n.geometry.index.count*t.length,o+=h.count*t.length,l+=t.length}const h=["color","map","roughness","roughnessMap","metalness","metalnessMap","opacity","alphaMap","aoMap","aoMapIntensity","normalMap","normalScale","emissive","emissiveIntensity","emissiveMap"];let p=new Map,m=new r.MeshStandardMaterial({color:"white"});const u=t.get(e[0].id).get(e[0].meshUUID);if(null==u)throw"missing source material";if(u instanceof g){const a=new Set,s=new Map;for(const i of e){const e=t.get(i.id).get(i.meshUUID);if(null==e)throw"missing mat";for(const t of h){let i=e[t];i instanceof r.CompressedArrayTexture&&null!=i.userData.index&&(i=i.userData.index);const n=s.get(t);void 0===n||Lt(i,n)?s.set(t,i):a.add(t)}}for(const e of a){let t;const a=u[e];if("number"==typeof a)t=D(e);else if(a instanceof x)t=E(e);else if(a instanceof S||a instanceof n)t=C(e);else if(a instanceof A)t=P(e);else if(a instanceof r.CompressedArrayTexture)t=D(e+"_i");else if(a instanceof b)continue;p.set(e,t)}let i=q.uv;u instanceof ct&&null!=u.heightMap&&(i=ht(i,H(u.heightMap),z(u.heightScale)));let o=_t(p.get("opacity"),F)??z(u.opacity??1);if(null!=u.alphaMap){let e;if(u.alphaMap instanceof r.CompressedArrayTexture){const t=J(u.alphaMap),a=_t(p.get("alphaMap"),F)??z(u.alphaMap.userData.index??0);e=t.sample(K(i.x,i.y,a))}else e=H(u.alphaMap).sample(i);o=o.multiply(e.r)}let l=$(_t(p.get("color"),Q)??u.color,o);if(null!=u.map){let e;if(u.map instanceof r.CompressedArrayTexture){const t=J(u.map),a=_t(p.get("map"),F)??z(u.map.userData.index??0);e=t.sample(K(i.x,i.y,a))}else e=H(u.map).sample(i);l=l.multiply(e)}let c=$(_t(p.get("emissive"),Q)??u.emissive,o);if(null!=u.emissiveMap){let e;if(u.emissiveMap instanceof r.CompressedArrayTexture){const t=J(u.emissiveMap),a=_t(p.get("emissiveMap"),F)??z(u.emissiveMap.userData.index??0);e=t.sample(K(i.x,i.y,a))}else e=H(u.emissiveMap).sample(i);c=c.multiply(e)}const d=_t(p.get("emissiveIntensity"),F)??z(u.emissiveIntensity??1),f=_t(p.get("normalScale"),Z)??Y(u.normalScale??new A(1,1));let g=X.normal;if(null!=u.normalMap){let e;if(u.normalMap instanceof r.CompressedArrayTexture){const t=J(u.normalMap),a=_t(p.get("normalMap"),F)??z(u.normalMap.userData.index??0);e=t.sample(K(i.x,i.y,a))}else e=H(u.normalMap).sample(i);g=k(e.rgb,f.x)}let y=_t(p.get("roughness"),F)??z(u.roughness??1);if(null!=u.roughnessMap){let e;if(u.roughnessMap instanceof r.CompressedArrayTexture){const t=J(u.roughnessMap),a=_t(p.get("roughnessMap"),F)??z(u.roughnessMap.userData.index??0);e=t.sample(K(i.x,i.y,a))}else e=H(u.roughnessMap).sample(i);y=y.multiply(e.g)}let w=_t(p.get("metalness"),F)??z(u.metalness??0);if(null!=u.metalnessMap){let e;if(u.metalnessMap instanceof r.CompressedArrayTexture){const t=J(u.metalnessMap),a=_t(p.get("metalnessMap"),F)??z(u.metalnessMap.userData.index??0);e=t.sample(K(i.x,i.y,a))}else e=H(u.metalnessMap).sample(i);w=w.multiply(e.b)}let M=z(1);if(null!=u.aoMap){let e;if(u.aoMap instanceof r.CompressedArrayTexture){const t=J(u.aoMap),a=_t(p.get("aoMap"),F)??z(u.aoMap.userData.index??0);e=t.sample(K(i.x,i.y,a))}else e=H(u.aoMap).sample(i);M=M.multiply(e.r)}const v=_t(p.get("aoMapIntensity"),F)??z(u.aoMapIntensity??0);let j=g;!0!==u.userData.disableAO&&(j=B("DOUBLE_SIDED",j,e=>L(new V("gl_FrontFacing"),e,e.multiplyScalar(-1))));const I=new _({color:R({color:l,roughness:y,metalness:w,ambientOcclusion:M,ambientOcclusionIntensity:v,emissive:c,emissiveIntensity:d,normal:j}),normal:g,roughness:y,emissive:c.rgb,transparent:u.transparent,alphaTest:u.alphaTest,envMap:u.envMap});null!=u.envMap&&(I.uniforms.envMapIntensity={value:u.envMapIntensity},I.uniforms.envMapRotation={value:Wt(u.envMapRotation,u.envMap)}),I.envMap=u.envMap,I.side=u.side,m=I}else{m=u;for(const a of e){const e=t.get(a.id).get(a.meshUUID);if(e!=m){console.error(`Different materials in group for object ${a.id} and mesh uuid ${a.meshUUID}`,{objectMaterial:e,sourceMaterial:u});break}}}const f=new lt(l,o,i,m);for(const[e,t]of p.entries()){let a=1;t instanceof te||t instanceof Q?a=4:t instanceof Z&&(a=2),f.initUniform(e,a,0)}for(const[e,i]of s.entries()){const s=i[0].assetId,o=c.get(e);if(null==o){console.error(`Missing single asset mesh for mesh uuid ${e} and asset id ${s}`);continue}if(null==o.geometry){console.error("Missing geometry on mesh mesh");continue}const l=f.addGeometry(o.geometry),h=a.get(s);if(null==h){console.warn("Missing batching info when configuring for asset id "+s);continue}const m=Pe(h.assetMesh)?.uuid===e,d=h.assetMesh instanceof Te&&m?h.assetMesh.collisionShapes:void 0,u=this.configureBatchedInstancedMesh(i,f,o,l,d);for(let e=0;e<u.length;e++){const a=i[e],s=u[e],o=t.get(a.id).get(a.meshUUID);for(let e of p.keys()){let t=o[e];if(t instanceof n&&(t=new S(t.r,t.g,t.b)),t instanceof r.CompressedArrayTexture)t=t.userData.index??0,e+="_i";else if(t instanceof b||null==t)continue;f.setUniformAt(e,s,t)}}}return f}async createInstancedMesh(e,t){const a=Ce(t,e=>!Oe(e)&&null!=e.geometry),s=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,Pt(e[0].materialAssignments,s.materialAssignments)),a.updateMatrix();const i=a.geometry.clone(),n=a.material;let o;if(o=new r.InstancedMesh(i,n,e.length),this.configureBatchedInstancedMesh(e,o,a),a.material instanceof p&&o.castShadow&&o.receiveShadow&&Array.isArray(n))for(const e of n);return o}configureBatchedInstancedMesh(e,t,a,s,i){const n=[];for(let l=0;l<e.length;l++){let c=l;t instanceof r.BatchedMesh&&(c=t.addInstance(s)),n.push(c);const h=(new r.Matrix4).compose((new S).fromArray(e[l].position),(new M).setFromEuler((new o).fromArray(e[l].rotation)),(new S).fromArray(e[l].scale)),p=(new m).copy(e[l].parentTransform).multiply(h).multiply(a.matrixWorld);t.setMatrixAt(c,p),null==t.userData.hasCollision&&(t.userData.hasCollision=[]),t.userData.hasCollision[c]=!!e[l].collisionDetection,null!=i&&(null==t.userData.collisionShapes&&(t.userData.collisionShapes=[]),t.userData.collisionShapes[c]=i)}return n}remove(e){if(console.log("Remove scene object",e),"global_fog"==e.type)return void(this.scene.fog=this.originalFog);if("world_env"===e.type)this.resetWorldEnv(),this.worldEnvObj=null;else if("actor"==e.type||"vfx"===e.type){const t=this.materializedActors.get(e.id);null!=t?(t.disposed.next(!0),t.onEndPlay()):console.warn("Failed to remove actor",e)}else"prefab"===e.type&&this.materializedActors.forEach((t,a)=>{a.startsWith(e.id)&&(t.disposed.next(!0),t.onEndPlay()),this.materializedActors.delete(a)});const t=this.sceneObjectMap.get(e.id);t?.parent.remove(t),this.sceneObjectMap.delete(e.id),this.components.filter(t=>t.object.userData.src?.id===e.id).forEach(e=>this.components.splice(this.components.indexOf(e,1))),this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>{e.clear(),e.stop(),this.landscapeManagers.splice(this.landscapeManagers.indexOf(e,1))}),this.removed$.next({object:t,source:e})}deleteSceneObject(e){const t=this.sceneObjectMap.get(e.id);if(this.scene.remove(t),"landscape"==e.type){const t=this.landscapeManagers.findIndex(t=>t.source.id===e.id);if(t>-1){const e=this.landscapeManagers.splice(t,1)[0];e.clear(),e.stop()}}}findByAssetId(e){return De(this.scene,t=>t.userData.src?.assetId==e,e=>null!=e.userData.src)}applyMaterials(e,t){return null==t?Promise.resolve([]):Promise.all(t.filter(e=>"null"!==e.materialId).map(t=>this.applyMaterial(e,t)))}async applyMaterial(e,t){await applyMaterial(e,t,e=>{const t=this.assets.get(e);if(null!=t)try{return materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders)}catch(e){console.error("Failed to apply material",e)}},this._originalMaterials)}unapplyMaterials(e){e.traverse(async e=>{if(e instanceof d)if(e.material instanceof Array)for(let t=0;t<e.material.length;t++)e.material[t]=this._originalMaterials.get(e.id+"#"+t)??e.material[t];else e.material=this._originalMaterials.get(e.id)??e.material})}updateActors(e){console.log("update actors"),this.actorTypes=e;const t=new Set(Object.values(oe));De(this.scene,e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&!t.has(e.userData.src.actor.type)).forEach(async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)})}updateShaders(e){this.shaders=e;for(const[e,t]of yt.entries())t.userData.customShaderName&&yt.delete(e);this.landscapeManagers.forEach(t=>t.updateShaders(e)),De(this.scene,e=>!0).forEach(e=>{e.traverse(async e=>{if(e instanceof d)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++){const a=e.material[t].userData?.customShaderName;if(null!=a){const a=this.assets.get(e.material[t].userData.assetId);this.refreshMaterial(e,e.material[t],a,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=this.assets.get(e.material.userData.assetId);this.refreshMaterial(e,e.material,t)}}})})}async update(e){if("sky"===e.type&&null!=this.sky&&null!=this.sky.parent)return void this.updateSky(e);if("world_env"===e.type&&null!=this.worldEnvObj)return void this.updateWorldEnv(e);const t=this.sceneObjectMap.get(e.id);if(t){let s=!1;if(t.traverseAncestors(e=>{"_hology_transform_group"===e.name&&(s=!0)}),!s){const a=this.findParent(e);null!=a&&a.uuid!=t.uuid?a.attach(t):console.error("Parent is wrong")}if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(t);this.inEditor&&e.hidden&&!1?t.traverse(e=>{e instanceof d&&(e.material.wireframe=!0)}):t.traverse(e=>{e instanceof d&&(e.material.wireframe=!1)})}if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);Pt(e.materialAssignments,a.materialAssignments).forEach(e=>this.applyMaterial(t,e))}else"shape_mesh"===e.type&&this.applyMaterials(t,e.materialAssignments);if(s||(null!=e.position&&t.position.fromArray(e.position),null!=e.scale&&t.scale.fromArray(e.scale),null!=e.rotation&&t.rotation.fromArray(e.rotation)),this.applyVertexMaterials(e,t),"light"==e.type)if("point"==e.light.type){const a=t;a.color=new n(e.light.point.color),a.intensity=e.light.point.intensity,a.decay=e.light.point.decay,a.castShadow=e.light.point.castShadow,a.distance=Math.max(e.light.point.distance,0),a.userData.volumetricIntensity=e.light.point.volumetricIntensity}else if("spot"==e.light.type){const a=t;a.color=new n(e.light.spot.color),a.intensity=e.light.spot.intensity,a.decay=e.light.spot.decay,a.angle=e.light.spot.angle,a.penumbra=e.light.spot.penumbra,a.castShadow=e.light.spot.castShadow,a.distance=Math.max(e.light.spot.distance,0),a.userData.volumetricIntensity=e.light.spot.volumetricIntensity}else"directional"===e.light.type?this.applyDirectionalLight(e.light.directional,e):"ambient"===e.light.type&&this.applyDirectionalAmbientLight(t,e.light.ambient,e);else if("landscape"===e.shape){const a=this.landscapeManagers.find(t=>t.source.id===e.id).source.landscape.options.density!==e.landscape.options.density;if(this.inEditor&&a){this.remove(e);const t=await this.materializeAndInitActor(e);return void this.updated$.next({object:t,source:e})}this.applyHeightMaps(t,e.landscape.heightMaps),this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(t=>{t.updateSource(e),t.queueRefreshScatter(this.renderingView.camera.position,!0,e=>!0)})}else if("global_fog"===e.type){const t=(this.scene.fog instanceof c?"density":"linear")!==e.fog.type;this.scene.fog=xt(e.fog),t&&(a=this.scene).traverse(e=>{if(e instanceof d){const t=e.material;t instanceof _&&(a.fog instanceof l?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof c&&(t.uniforms.density={value:a.fog.density}),t.needsUpdate=!0,t.uniformsNeedUpdate=!0)}}),this.fixFogColor()}else if("actor"===e.type){if(this.materializedActors.has(e.id)){const t=this.materializedActors.get(e.id);if(t instanceof it){const a=await prepareClassParameters(e.actor.params,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,[],this.actorProvider);return void Object.assign(t,a)}const a=this.editorActorParamSnapshot.get(e.id);null!=a&&a===JSON.stringify(e.actor)||s||(this.remove(e),await this.materializeAndInitActor(e))}}else if("shape_mesh"===e.type){const a=await this.createMeshByShape(e.shape,t.material,e.shapeParams);t instanceof ze&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&gt(t,e.castShadow,e.receiveShadow),e.name&&e.name.length>0&&(t.name=e.name),this.updated$.next({object:t,source:e})}else{const t=await this.materializeAndInitActor(e);this.updated$.next({object:t,source:e})}var a;this.renderingView.renderer.shadowMap.needsUpdate=!0}async materializeAndInitActor(e,t=this.findParent(e)){const a=await this.materialize(e,t);return It(e,async e=>{if("actor"===e.type){const t=this.materializedActors.get(e.id);null!=t?await this.initActorsPostInit([t]):console.error(`Something went wrong when creating actor ${e.id}`)}}),a}findParent(e){const t=this.dataProvider.getObjects().flatMap(t=>t.id===e.id?null:Ie(t,t=>t.children?.some(t=>t.id===e.id),()=>!0))[0];return null==t?this.scene:null!=t?De(this.scene,e=>e.userData?.src?.id===t.id,e=>null!=e.userData?.src)[0]:void 0}fixFogColor(){!0===this.renderingView.options.enableOutlines&&(this.scene.fog.color=new n(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse(e=>{e instanceof d&&e.geometry&&(t=e)}),t}applyVertexMaterials(e,t){if(null==e.vertexMaterials||0===e.vertexMaterials.length)return;let a=1;for(const t of e.vertexMaterials)a=Math.max(t.w.length,a);const s=xe(e.vertexMaterials,e=>e.m);t.traverse(e=>{if(e instanceof d){if(null==e.geometry)return;if(kt(We(e,0,!1)),a>0){kt(We(e,0,!1))}}});const r=new Set;for(const[e,i]of s.entries()){const s=null!=e?t.getObjectByName(e):this.findMeshWithGeometry(t);let n=!1;if(null==s||null==s.geometry)return void console.warn(`Failed to apply vertex materials on mesh with name "${e}"`);const o=We(s,0,!0);kt(o);for(const e of i)o.setX(e.i,e.w[0]??0),o.setY(e.i,e.w[1]??0),o.setZ(e.i,e.w[2]??0),o.setW(e.i,e.w[3]??0),n=!0;if(a>0){const e=We(s,4,!0);kt(e);for(const t of i)e.setX(t.i,t.w[4]??0),e.setY(t.i,t.w[5]??0),e.setZ(t.i,t.w[6]??0),e.setW(t.i,t.w[7]??0),e.needsUpdate=!0,n=!0}n&&r.add(e)}this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,e=>r.has(e.name)))}async materialize(e,t,a=!1,s){if(!this.shouldBeMaterialized(e))return;let r,n;switch(e.type){case"asset_mesh":r=await this.createFromAsset(e);break;case"shape_mesh":r=await this.createFromShape(e);break;case"light":r=await this.createLight(e);break;case"particles":r=await this.createParticleSystem(e),e.collisionDetection=!1;break;case"global_fog":this.scene.fog=xt(e.fog),this.fixFogColor(),r=new h;break;case"sky":this.sky=qe(),this.updateSky(e),r=this.sky;break;case"world_env":this.updateWorldEnv(e),r=new h,this.worldEnvObj=r;break;case"actor":({object:r,actor:n}=await this.createFromActor(e,s));break;case"group":r=new h;break;case"prefab":r=await this.createFromPrefab(e,s);break;case"vfx":r=await this.createFromVfx(e,s);break;default:if(this.inEditor)throw new Error("unknown type "+e.type);console.warn(`Failed to materialize object. Unknown type '${e.type}'. This might be because the hology/core library is not compatible with the editor version.`)}if(null!=r){if(e.name&&e.name.length>0&&(r.name=e.name),null!=e.position&&r.position.fromArray(e.position),null!=e.scale&&r.scale.fromArray(e.scale),null!=e.rotation&&r.rotation.fromArray(e.rotation),a?r.userData._src=e:r.userData.src=e,null!=n&&(r.userData.actor=n),this.inEditor,this.inEditor){let e=null;r instanceof ze&&(e=function(e){if(e instanceof ke)return new d(new i(...e.offset.toArray()),jt);return null}(r.collisionShape)),null!=e&&(e.layers.disable(0),e.layers.enable(18),e.scale.multiplyScalar(1.1),r.add(e))}if(this.objectMap.set(r.uuid,e),this.sceneObjectMap.set(e.id,r),e.physics?.type!==le.dynamic||null==t||this.inEditor?null==t?this.scene.add(r):t?.add(r):(t.add(r),r.getWorldPosition(r.position),r.getWorldQuaternion(r.quaternion),r.getWorldScale(r.scale),this.scene?.attach(r)),null!=e.children&&await Promise.all(e.children?.map(e=>this.materialize(e,r,a))),this.inEditor||"asset_mesh"!=e.type&&"shape_mesh"!==e.type||"landscape"===e.shape||null!=e.physics?.type&&e.physics.type==le.dynamic||St(r),null!=this.renderingView)return this.renderingView.renderer.shadowMap.needsUpdate=!0,r;console.warn("RenderingView not found in materializer. No idea what called this")}}updateWorldEnv(e){this.renderingView.aoPass.enabled=e.worldEnv.ao.enabled,this.renderingView.aoPass.blendIntensity=e.worldEnv.ao.blendIntensity,this.renderingView.aoPass.updateGtaoMaterial(e.worldEnv.ao);const t=e.worldEnv.toneMapping;null!=t&&(this.renderingView.renderer.toneMapping=t.mapping??0,this.renderingView.renderer.toneMappingExposure=t.exposure??1);const a=e.worldEnv.environment;null!=a&&null!=a.textureId?this.assetManagerService.getTexture(this.assets.get(a.textureId)).then(e=>{null==this.pmremGenerator&&(this.pmremGenerator=new r.PMREMGenerator(this.renderingView.renderer),this.pmremGenerator.compileEquirectangularShader()),this.pmremGeneratorResults.has(e)||this.pmremGeneratorResults.set(e,this.pmremGenerator.fromEquirectangular(e).texture);const t=this.pmremGeneratorResults.get(e);this.renderingView.scene.environment=t,this.renderingView.scene.environmentIntensity=a.intensity??1}):this.renderingView.scene.environment=null}resetWorldEnv(){this.renderingView.aoPass.enabled=!1,this.renderingView.aoPass.blendIntensity=1,this.renderingView.aoPass.output=0,this.renderingView.renderer.toneMapping=0,this.renderingView.renderer.toneMappingExposure=1}async updateSky(e){if(null==e?.sky?.materialId)return void(this.sky.material=Xe);const t=await this.assetsService.getAsset(e.sky.materialId),a=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);this.applySkySettings(a),null!=this.sky?this.sky.material=a:console.warn("No sky has been created")}applySkySettings(e){e.side=r.BackSide,(e instanceof g||e instanceof r.MeshBasicMaterial||e instanceof r.ShaderMaterial)&&(e.fog=!1),e.depthTest=!1}async createComponent(e,t,a,s){const r=new mt[a.path+"/"+a.className],i=t.id+s;r.id=i,r.object=e;for(const e of a.params)null!=e.value&&(r[e.name]=e.value);return this.components.push(r),i}async createFromActor(e,t){const a=this.actorTypes.find(t=>t.name===e.actor?.type)?.type??oe[e.actor?.type];if(null==a)return{object:null,actor:null};this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const s=await this.actorProvider.create(a,(new S).fromArray(e.position),(new o).fromArray(e.rotation),!0);return this.materializedActors.set(this.getNestedActorId(e.id,t),s),{object:s?.object,actor:s}}getNestedActorId(e,t){return null!=t?t.sceneObjectChain.join("/")+"/"+e:e}async createFromVfx(e,t){const a=await this.assetsService.getAsset(e.assetId);null==a&&console.error("Could not find asset",e);const s=await this.actorProvider.create(se,(new S).fromArray(e.position),(new o).fromArray(e.rotation),!1);try{await s.fromAsset(a)}catch(e){return console.error("Failed to create VFX asset",e),null}return s.play(),this.materializedActors.set(this.getNestedActorId(e.id,t),s),null!=s&&(s.object.userData.actor=s),s?.object}async createFromShape(e){const t=this.inEditor&&e.hidden;let a;if("landscape"==e.shape)a=this.createLandscape(e),a.traverse(e=>{e instanceof d&&this._originalMaterials.set(e.id,e.material)});else{let s=new g({name:"Default",color:new n("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});const r=await this.createMeshByShape(e.shape,s,e.shapeParams);r.castShadow=e.castShadow??!0,r.receiveShadow=e.castShadow??!1,e.collisionDetection||(r.collisionShape=null),r.physics=e.physics,a=r,this._originalMaterials.set(a.id,r.material),a.traverse(e=>{})}return t||(await Promise.all((e.materialAssignments??[]).filter(e=>null!=e.materialId).map(e=>this.applyMaterial(a,e))),this.applyVertexMaterials(e,a)),a}createLandscape(e){const t=e.landscape?.options;if(null==t)return console.error(`No landscape options exist on scene object ${e.id} ${e.name}`),new h;const a=Be(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new Fe(e,this.renderingView,a,this.assetManagerService,this.assetsService,this.shaders,t=>{(e.materialAssignments??[]).filter(e=>null!=e.materialId).forEach(e=>this.applyMaterial(t,e))});return this.landscapeManagers.push(s),s.refreshGeometry(),a}applyHeightMaps(e,t,a=!1){const s=new Ne(e.sections);for(const e of t??[]){const t=s.find(e.x,e.y);if(!t)return;const a=t.geometry.getAttribute("position");for(const t of e.points)a.setY(t.i,t.y);a.needsUpdate=!0}const r=e.sections;r.forEach(e=>{e.geometry.computeBoundsTree(),e.geometry.computeVertexNormals()}),this.inEditor&&!a||setTimeout(()=>_e(r),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&He.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);if(!this.geometryCache.has(r)){const t=Ge[e].geometry(s);t.computeTangents(),this.geometryCache.set(r,t)}this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,Ge[e].collision(s));return new ze(this.geometryCache.get(r),t,this.collisionShapeCache.get(r))}if(this.inEditor)throw new Error(`Unsupported shape '${e}'`);console.warn(`Failed to create shape. Unsupported shape '${e}'. This might be because the hology/core library is not compatible with the editor version.`)}async createFromAsset(e,t){const a=await this.assetsService.getAsset(e.assetId);if(null==a)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);let{scene:s}=await this.assetManagerService.getMesh(a,{mergeGeomtries:!0});if(!1!==t?.assignMaterials)try{await Promise.all(Pt(e.materialAssignments,a.materialAssignments).map(e=>this.applyMaterial(s,e)))}catch(t){console.error("Failed to apply material"+t,e)}const r=e.receiveShadow??!!a.receiveShadow??!0,i=e.castShadow??!!a.castShadow??!1;return s.receiveShadow=r,gt(s,i,r),e.collisionDetection||(s.collisionShapes=[]),null!=e.physics&&!0!==this.inEditor&&(s.physics=e.physics),this.applyVertexMaterials(e,s),s.traverse(e=>{e instanceof d&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()}),s}async createFromPrefab(e,t){const a=await this.assetsService.getAsset(e.assetId);if(null==a)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);null==t&&(t={sceneObjectChain:[]}),t.sceneObjectChain.push(e.id);const{object:s}=await this.createFromPrefabAsset(a,t);return t.sceneObjectChain.pop(),s}async createFromPrefabAsset(e,t){const a=new h;await Promise.all(e.prefab.objects.filter(e=>"global_fog"!==e.type&&"world_env"!==e.type).map(e=>this.materialize(e,a,!0,structuredClone(t))));const s=t.sceneObjectChain.join("/"),r=Array.from(this.materializedActors.entries()).filter(([e,a])=>e.startsWith(s)&&e.split("/").length-1===t.sceneObjectChain.length).map(([,e])=>e);r.forEach(e=>{a.add(e.object)}),this.initActorsPostInit(r,structuredClone(t));const i=Array.from(this.materializedActors.entries()).filter(([e,t])=>e.startsWith(s)).map(([,e])=>e);return{object:a,actors:i}}async createParticleSystem(e){const t=await this.assetsService.getAsset(e.assetId),a=new y;return await j.fromJSONAsync(t.particleSystem,r).then(e=>{const t=new I(a,r);e.addRenderer(t),this.renderingView.onLoop(t=>e.update())}),a}async createLight(e){if("point"===e.light.type){const t=new w(e.light.point.color,e.light.point.intensity,e.light.point.distance,e.light.point.decay);if(t.castShadow=e.light.point.castShadow??!0,this.inEditor){const e=(new r.TextureLoader).load("assets/light-bulb-icon.webp"),a=new r.SpriteMaterial({map:e,alphaTest:.5}),s=new nt(a);s.scale.multiplyScalar(.6),t.add(s)}return t}if("spot"===e.light.type){const t=new r.SpotLight(e.light.spot.color,e.light.spot.intensity,e.light.spot.distance,e.light.spot.angle,e.light.spot.penumbra,e.light.spot.decay);if(t.castShadow=e.light.spot.castShadow??!0,t.target=new y,t.target.position.set(0,-1,0),t.add(t.target),this.inEditor){const e=(new r.TextureLoader).load("assets/light-bulb-icon.webp"),a=new r.SpriteMaterial({map:e,alphaTest:.5}),s=new nt(a);s.scale.multiplyScalar(.6),t.add(s),t.add(new r.SpotLightHelper(t))}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional,e),new h):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient,e),new h):void 0}applyDirectionalAmbientLight(e,t,a){const s=this.scene.children.find(e=>e.name===Je);null!=s?(s.intensity=t.intensity,s.color.set(t.color),s.groundColor.set(t.color),s.userData.src=a,s.userData.volumetricIntensity=t.volumetricIntensity):console.warn("Couldn't find ambient light")}applyDirectionalLight(e,t){for(const a of this.renderingView.csm.lights)a.intensity=e.intensity,a.color.set(e.color),a.castShadow=e.castShadow,a.userData.src=t,a.userData.volumetricIntensity=e.volumetricIntensity;this.renderingView.csm.lightDirection.fromArray(e.direction).normalize()}dispose(){this.updateSubscription.unsubscribe(),this.createAssetSubscription.unsubscribe(),this.materializedActors.forEach(e=>e.disposed.next(!0)),this.materializedActors.clear()}};ft=e([ae(),t("design:paramtypes",[v,Object,Object,Ve,pe,Array,Array,Object])],ft);export{ft as SceneMaterializer};function gt(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse(e=>{e.castShadow=t,e.receiveShadow=a})}const yt=new Map,wt=new Map,Mt=new u({color:16711935}),vt=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){const n=JSON.stringify(e.material);return i&&yt.has(n)?yt.get(n):i&&wt.has(n)?await wt.get(n):wt.set(n,_materialFromAsset(n,e,t,a,s,r,i)).get(n)}export async function _materialFromAsset(e,t,a,s,i,o,l=!0){const c={opacity:t.material.params.opacity,map:null,emissive:t.material.params.emissive??null,metalness:t.material.params.metalness??0,flatShading:t.material.params.flatShading??!1,color:new n(t.material.params.color),transparent:null!=t.material.params.opacity&&t.material.params.opacity<1},h={};if(null!=t.material.params.map){const e=t.material.params.map,a=await s.getAsset(e);null!=a&&(c.map=await i.getTexture(a))}let p;switch(t.material.type){case"phong":p=new f({...c,...h});break;case"water":p=Le(c,a);break;case"grassFoliage":p=Ue({color:c.color,map:c.map},a);break;case"grass":p=$e({...c,colorTwo:new n(t.material.params.colorTwo),colorThree:new n(t.material.params.colorThree)},a);break;case"standard":case"unlit":case"toon":case"layered":case"lambert":case"shader":case"landscape":case"landscape-composite":case"decal-unlit":case"decal-standard":const e={standard:dt?ge:Me,lambert:ge,unlit:ve,toon:ot,layered:st,landscape:we,"landscape-composite":ye,"decal-unlit":Ze,"decal-standard":Ke}[t.material.type]??o.find(e=>e.name==t.material.shader)?.type;if(e){try{let r=new e;const n=await prepareClassParameters(t.material?.shaderParams??{},e,s,i,null,a,o);Object.assign(r,n),p=r.build()}catch(e){console.log("Shader runtime error: "+e),vt.has(t.material.shader)||vt.set(t.material.shader,Mt.clone()),p=vt.get(t.material.shader)}p.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),p=Mt;break;default:throw new Error("Unsupported material type"+t.material.type)}return a?.csm.setupMaterial(p),null!=a&&yt.set(e,p),p.side=t.material.side??p.side??r.FrontSide,p.transparent=(t.material.transparent??c.transparent??!1)||p.transparent,p.alphaTest=t.material.alphaTest??p.alphaTest??0,null!=t.material.blending&&(p.blending=ce[t.material.blending]??r.NormalBlending),t.material.bloom&&(p.userData.hasBloom=!0),t.material.reflective&&(p.userData.reflective=!0),!0===t.material.outlines&&(p.userData.outlineParameters={},null!=t.material.outlineParams&&(null!=t.material.outlineParams.color&&(p.userData.outlineParameters.color=new n(t.material.outlineParams.color).toArray()),null!=t.material.outlineParams.thickness&&(p.userData.outlineParameters.thickness=t.material.outlineParams.thickness))),p.userData.assetId=t.id,wt.delete(e),p}export async function prepareClassParameters(e,t,a,s,r,i,n,o){const l={};for(const[t,c]of Object.entries(e)){const e=await At(t,c,a,s,r,i,n,o);null!=e&&(l[t]=e)}return l}export async function prepareShapeParameters(e){const t={};for(const[a,s]of Object.entries(e)){const e=await At(a,s,null,null,null);null!=e&&(t[a]=e)}return t}const bt=new Map;async function At(e,t,a,s,r,i,l,c,h=t.value,p=t.type){if(null==t||null==h||""===h)return null;switch(p){case Re.Array:if(Array.isArray(h)&&"element"in t)return await Promise.all(h.map(n=>At(e,t,a,s,r,i,l,c,n,t.element)));break;case Re.Number:case Re.FloatNode:let p;if("string"==typeof h?p=parseFloat(h):"number"==typeof h&&(p=h),t.type===Re.FloatNode){if("object"==typeof h&&"a"in h&&"b"in h){const e=h;if(null==e.a)return null;const t="string"==typeof e.a?parseFloat(e.a):e.a;if(null==e.b)return t;const a="string"==typeof e.b?parseFloat(e.b):e.b,s=function(e){let t=bt.get(e);return null==t&&(t=me(Ye.decode(e)),bt.set(e,t)),t}(e.easing),r=s.sample(de(ue.energy));return N(z(t),z(a),r)}return z(p)}return p;case Re.Texture:let m=await s.getTexture(await a.getAsset(h));return"envmap"===e.toLowerCase()&&null!=i&&(m=i.getEnvTexture(m)),m;case Re.Sampler2DNode:return H(await s.getTexture(await a.getAsset(h)));case Re.Boolean:return h;case Re.BooleanNode:return T(h);case Re.Vector2:case Re.Vec2Node:if("object"==typeof h){const e=h instanceof Array?(new A).fromArray(h):new A(h.x,h.y);return t.type===Re.Vec2Node?Y(e):e}return null;case Re.Vector3:case Re.Vec3Node:if("object"==typeof h){const e=h instanceof Array?(new S).fromArray(h):new S(h.x,h.y,h.z);return t.type===Re.Vec3Node?K(e):e}return null;case Re.Color:case Re.RgbNode:const d=new n(h);return t.type===Re.RgbNode?U(d):d;case Re.String:return h;case Re.BaseActor:const u=h;return null==r&&console.warn("Class parameters can not be prepared as actors are not passed in"),r?.get(u);case Re.Euler:const f=h;return(new o).fromArray(f);case Re.Object3D:return(await s.getMesh(await a.getAsset(h))).scene;case Re.Material:return await materialFromAsset(await a.getAsset(h),i,a,s,l);case Re.AudioBuffer:return await s.getAudio(await a.getAsset(h));case Re.VisualEffect:const g=await a.getAsset(h);if(null==c){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in g)return new re(c,g);console.error("Using a non-vfx asset for visual effect parameter");break;case Re.Prefab:{const e=await a.getAsset(h);return null==e?(console.error("Using a non-prefab asset for prefab parameter",h),null):new ie(e)}case Re.Curve:return Ye.decode(h);case Re.ColorLayer:case Re.MaskLayer:if(rt(h)){const e=await Qe.decode(h,async e=>await s.getTexture(await a.getAsset(e))),t=await prepareClassParameters(h.params,null,a,s);return Object.assign(e,t),e}return console.warn("Expecting color layer but got",h),null}return null}function St(e){e.updateWorldMatrix(!0,!0),e.updateMatrix(),e.traverse(e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1});const t=e.updateMatrixWorld;e.updateMatrixWorld=function(){t.apply(e),e.updateMatrixWorld=function(){}}}function xt(e){return"linear"===e.type?new l(new n(e.color),e.near??100,e.far??1e3):"density"===e.type?new c(e.color,e.density):void console.warn("Invalid fog type",e)}const jt=new g({color:4229780});async function It(e,t,a,s){null==s&&(s=(new m).identity());const i=s.clone().multiply(Dt(e,new r.Matrix4));if(null!=e.children&&e.children.length>0)for(let a=e.children.length-1;a>=0;a--)await It(e.children[a],t,e,i);await t(e,a,s)}function Dt(e,t){return null==e.position||null==e.rotation||null==e.scale?t.identity():t.compose((new S).fromArray(e.position),(new M).setFromEuler((new o).fromArray(e.rotation)),(new S).fromArray(e.scale))}export function toSerializedParamType(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?Re.Number:t instanceof F||"function"==typeof e.prototype.isFloat?Re.FloatNode:t instanceof b||e===b||e.isTexture?Re.Texture:t instanceof fe||e===G?Re.Sampler2DNode:t instanceof Boolean||e===Boolean?Re.Boolean:t instanceof O?Re.BooleanNode:t instanceof n||e==n?Re.Color:t instanceof W||"function"==typeof e.prototype.isRgb?Re.RgbNode:t instanceof A||e==A?Re.Vector2:t instanceof Z||"function"==typeof e.prototype.isVec2?Re.Vec2Node:t instanceof S||e==S?Re.Vector3:t instanceof Q||"function"==typeof e.prototype.isVec3?Re.Vec3Node:t instanceof String||e===String?Re.String:t instanceof ne||e==ne||e.prototype instanceof ne||e.prototype==ne?Re.BaseActor:t instanceof o||e==o?Re.Euler:t instanceof y||e==y?Re.Object3D:t instanceof p||e==p?Re.Material:t instanceof AudioBuffer||e==AudioBuffer?Re.AudioBuffer:t instanceof re||e==re?Re.VisualEffect:t instanceof ie||e==ie?Re.Prefab:t instanceof Ye||e==Ye?Re.Curve:t instanceof Qe||e==Qe?Re.ColorLayer:t instanceof at||e==at?Re.MaskLayer:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function prepareCustomParams(e,t,a={}){return Object.fromEntries(e.map(e=>[e.name,{type:e.options.array?Re.Array:toSerializedParamType(e.type),...e.options.array?{element:toSerializedParamType(e.type)}:{},value:t[e.name]?.value??(!0!==e.options.array?a[e.name]??customParameterDefaultValueByType.get(toSerializedParamType(e.type)):[])}]))}export function prepareCustomParamsFromType(e,t,a=null){const s=be(e);if(0===s.length)return{};let r;null!=a?he(a,()=>{r=a.get(e)}):r=new e;const i={};for(const e of s){const t=r[e.name];if(null!=t&&!0!==e.options.array){const a=serializeCustomParameter(e.type,t);null!=a&&(i[e.name]=a)}}return prepareCustomParams(s,t,i)}export function serializeCustomParameter(e,t){function a(){console.error("Failed to serialize value",{type:e,value:t})}switch(e){case Number:case Boolean:return t;case A:return t instanceof A?t.toArray():void a();case S:return t instanceof S?t.toArray():void a();case x:return t instanceof x?t.toArray():void a();case n:return t instanceof n?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new n(t).getHexString():void a();case String:return t;case o:return t instanceof o?t.toArray():void a();case ie:return t instanceof ie?t.asset?.id??null:void a()}}function Pt(e,t){return function(e,t,a){const s=[],r=new Set;for(const i of[...e??[],...t??[]]){const e=a(i);r.has(e)||(r.add(e),s.push(i))}return s}((e??[]).filter(e=>Ct(e.materialId)),(t??[]).filter(e=>Ct(e.materialId)),e=>e.color+e.name)}function Ct(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[Re.RgbNode,"#000000"],[Re.Color,"#000000"],[Re.Vector4,[0,0,0,0]],[Re.Vec4Node,[0,0,0,0]],[Re.Vector3,[0,0,0]],[Re.Vec3Node,[0,0,0]],[Re.Vector2,[0,0]],[Re.Vec2Node,[0,0]],[Re.Euler,[0,0,0,"XYZ"]],[Re.Array,[]],[Re.ColorLayer,et],[Re.MaskLayer,tt]]);let Et=new n,Tt=new n;function Vt(e,t){return Et.set(e),Tt.set(t),Et.getHexString()==Tt.getHexString()}export function applyMaterial(e,t,a,s){const i=[];return e.traverse(async e=>{if(e instanceof d||e.isMesh||e instanceof r.SkinnedMesh||e.isSkinnedMesh)for(const t of je(e.material))t.hasOwnProperty("color")&&i.push(e)}),Promise.all(i.map(async e=>{if(e.material instanceof Array)for(let r=0;r<e.material.length;r++){const i=e.material[r];if(null==i.color||!(i.color instanceof n))continue;const o="#"+i.color.getHexString(),l=i.name;if(o===t.color&&(i.name===t.name||null==t.name)||e.userData["originalColor_"+r]===t.color&&e.userData["originalMaterialName_"+r]===t.name){const i=await a(t.materialId),n=e.material[r];null!=i&&n.id!=i.id&&(e.material[r]=i,e.userData["originalColor_"+r]=e.userData["originalColor_"+r]??o,e.userData["originalMaterialName_"+r]=e.userData["originalMaterialName_"+r]??l,null!=s&&s.set(e.id+"#"+r,n))}}else if("color"in e.material){const r="#"+e.material.color.getHexString(),i=e.material.name;if(r===t.color&&(e.material.name===t.name||null==t.name)||e.userData.originalColor===t.color&&e.userData.originalName===t.name){const n=await a(t.materialId),o=e.material;null!=n&&(e.material=n,e.userData.originalColor=e.userData.originalColor??r,e.userData.originalMaterialName=e.userData.originalMaterialName??i,null!=s&&(s.has(e.id)||s.set(e.id,o)))}}}))}function Ot(e,t){if(e instanceof r.ShaderMaterial&&t instanceof r.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof r.ShaderMaterial&&t instanceof r.ShaderMaterial){for(const a in e.uniforms){if(null==t.uniforms[a])return!1;if(t.uniforms[a].value!==e.uniforms[a].value)return!1}return!0}return!1}(e,t)}return!1}function kt(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}const zt=new WeakMap;function Ft(e){let t=zt.get(e);return null==t&&(t=function(e){const t=Pe(e);if(null==t)return"";return Object.keys(t.geometry.attributes).sort().join(",")}(e),zt.set(e,t)),t}const Bt=new WeakMap;function Nt(e){let t=Bt.get(e);return null==t&&(t=function(e){let t=e.type;e instanceof r.MeshStandardMaterial||(t+=e.id+"");(e instanceof r.MeshBasicMaterial||e instanceof r.MeshLambertMaterial||e instanceof g||e instanceof f)&&(null!=e.map&&(t+="c"+e.map?.id),null!=e.aoMap&&(t+="o"+e.aoMap?.id),null!=e.lightMap&&(t+="l"+e.lightMap?.id),null!=e.envMap&&(t+="v"+e.envMap?.id),null!=e.alphaMap&&(t+="a"+e.alphaMap?.id));e instanceof g&&(null!=e.normalMap&&(t+="n"+e.normalMap?.id),null!=e.roughnessMap&&(t+="r"+e.roughnessMap?.id),null!=e.metalnessMap&&(t+="m"+e.metalnessMap?.id),null!=e.emissiveMap&&(t+="e"+e.emissiveMap?.id));(e instanceof u||e instanceof f)&&null!=e.specularMap&&(t+="s"+e.specularMap?.id);e instanceof r.MeshToonMaterial&&(null!=e.map&&(t+="c"+e.map?.id),null!=e.aoMap&&(t+="o"+e.aoMap?.id),null!=e.lightMap&&(t+="l"+e.lightMap?.id),null!=e.alphaMap&&(t+="a"+e.alphaMap?.id));e instanceof ct&&null!=e.heightMap&&(t+="h"+e.heightMap?.id);if(e instanceof r.ShaderMaterial){t+=e.vertexShader,t+=e.fragmentShader;for(const a in e.uniforms){const s=e.uniforms[a];s&&s.value&&s.value.isTexture&&null!=s.value.id&&(t+="t:"+a+":"+s.value.id)}}null!=e.userData.outlineParameters&&(t+=e.userData.outlineParameters.color,t+=e.userData.outlineParameters.thickness);return t+=e.side,t+=e.transparent?"t":"",t+=e.depthWrite?"dw":"",t+=e.depthTest?"dt":"",t+=e.alphaTest,t}(e),Bt.set(e,t)),t}function _t(e,t){if(null==e)return null;if(!(e instanceof t))throw new Error(`Value is not an instance of ${t.name}`);return e}const Ut=new m,$t=new o;function Wt(e,t){return $t.copy(e),$t.x*=-1,$t.y*=-1,$t.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&($t.y*=-1,$t.z*=-1),(new r.Matrix3).setFromMatrix4(Ut.makeRotationFromEuler($t))}new x;function Lt(e,t){return e===t||null==e==(null==t)&&("number"==typeof e&&"number"==typeof t?e===t||isNaN(e)&&isNaN(t):e instanceof r.Color&&t instanceof r.Color?e.r===t.r&&e.g===t.g&&e.b===t.b:e instanceof A&&t instanceof A?e.x===t.x&&e.y===t.y:e instanceof S&&t instanceof S?e.x===t.x&&e.y===t.y&&e.z===t.z:e instanceof x&&t instanceof x&&(e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w))}/*
1
+ import{__decorate as e,__metadata as t}from"tslib";import{ConvexPolyhedronCollisionShape as a}from"@hology/core";import{Subject as s}from"rxjs";import*as r from"three";import{BoxGeometry as i,Color as n,Euler as o,Fog as l,FogExp2 as c,Group as h,Material as p,Matrix4 as m,Mesh as d,MeshLambertMaterial as u,MeshPhongMaterial as f,MeshStandardMaterial as g,Object3D as y,PointLight as w,Quaternion as M,Scene as v,Texture as b,Vector2 as A,Vector3 as S,Vector4 as x}from"three";import j,{SpriteRenderer as I}from"@hology/nebula";import{batchingUniformFloat as D,batchingUniformVec2 as P,batchingUniformVec3 as C,batchingUniformVec4 as E,bool as T,BooleanExpression as V,BooleanNode as O,colorToNormal as k,float as z,FloatNode as F,ifDefApply as B,mix as N,NodeShaderMaterial as _,rgb as U,rgba as $,RgbNode as W,select as L,standardMaterial as R,Texture2dLookupNode as G,textureSampler2d as H,textureSampler2dArray as J,varyingAttributes as q,varyingTransformed as X,vec2 as Y,Vec2Node as Z,vec3 as K,Vec3Node as Q,vec4 as ee,Vec4Node as te}from"three-shader-graph";import{Service as ae}from"typedi";import{VfxActor as se}from"../effects/vfx/vfx-actor.js";import{VisualEffect as re}from"../effects/vfx/vfx-param.js";import{Prefab as ie}from"./objects/prefab.js";import{BaseActor as ne}from"../gameplay/actors/actor.js";import oe from"../gameplay/actors/builtin/index.js";import{PhysicsBodyType as le,ThreeBlendingMode as ce,withInjectionContext as he}from"../gameplay/index.js";import{RenderingView as pe}from"../rendering.js";import{curveSampler as me,oneMinus as de,particleUniforms as ue,Sampler2DNode as fe}from"../shader-nodes/index.js";import{LambertShader as ge}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as ye}from"../shader/builtin/landscape-composite-shader";import{LandscapeShader as we}from"../shader/builtin/landscape-shader.js";import{StandardShader as Me}from"../shader/builtin/standard-shader.js";import{UnlitShader as ve}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as be}from"../shader/parameter.js";import{ArrayMap as Ae,DefaultMap as Se,groupBy as xe}from"../utils/collections.js";import{iterateMaterials as je}from"../utils/materials.js";import{filterChildrenShallow as Ie,filterSceneShallow as De,findFirstVisibleMesh as Pe,findFirstVisibleObject as Ce,traverseAsync as Ee}from"../utils/three/traverse.js";import{AssetMeshInstance as Te,AssetResourceLoader as Ve}from"./asset-resource-loader.js";import{isCollisionMesh as Oe}from"./collision/collision-shape-import.js";import{BoxCollisionShape as ke,PhysicalShapeMesh as ze}from"./collision/collision-shape.js";import{LandscapeManager as Fe}from"./landscape/landscape-manager.js";import{initLandscape as Be}from"./landscape/landscape.js";import{SectionGrid as Ne,smoothNormalsCrossMeshes as _e}from"./landscape/utils.js";import{createGrassFoliageMaterial as Ue}from"./materials/grass-foliage.js";import{createGrassMaterial as $e}from"./materials/grass.js";import{getMaterialAttribute as We}from"./materials/utils/material-painting.js";import{createWaterMaterial as Le}from"./materials/water.js";import{SerializedParamType as Re}from"./model.js";import{ShapeLibrary as Ge,ShapeLibraryKeys as He}from"./objects/shapes.js";import{ambientLightName as Je,createSky as qe,defaultSkyMaterial as Xe}from"./sky.js";import{Curve2 as Ye}from"../utils/curve.js";import{DecalUnlitShader as Ze}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as Ke}from"../shader/builtin/decal-standard-shader.js";import{ColorLayer as Qe,defaultValueColorLayer as et,defaultValueMaskLayer as tt,MaskLayer as at}from"../shader/color-layer.js";import{LayeredShader as st}from"../shader/builtin/layered-shader";import{isColorLayerSerialized as rt}from"../shader/color-layer";import{FogVolume as it}from"../rendering/fog/fog-volume-actor.js";import{UnscaledSprite as nt}from"../utils/three/unscaled-sprite.js";import{ToonShader as ot}from"../shader/builtin/toon-shader.js";import{BatchedMesh2 as lt}from"./batched-mesh-2.js";import{ParallaxStandardMaterial as ct}from"../shader/builtin/standard-shader";import{parallaxOcclusionMapping as ht}from"../shader-nodes/pom.js";import{traverseVisibleEvery as pt}from"../utils/three/traverse";const mt={},dt=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),ut=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||(navigator.userAgent.includes("iPhone")||navigator.userAgent.includes("iPad"))&&!!navigator.userAgent.match(/AppleWebKit/)&&!navigator.userAgent.match(/CriOS/);export const shapeDefaultColor="#aaaaaa";export class SceneMaterializerLoader{constructor(e,t,a){this.dataProvider=e,this.assetsService=t,this.assetManagerService=a}get(e,t){return new ft(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}let ft=class{constructor(e,t,a,i,n,o,l,c){this.scene=e,this.dataProvider=t,this.assetsService=a,this.assetManagerService=i,this.renderingView=n,this.shaders=o,this.actorTypes=l,this.actorProvider=c,this.objectMap=new Map,this.sceneObjectMap=new Map,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.inEditor=!0,this.updated$=new s,this.removed$=new s,this.error$=new s,this.editorActorParamSnapshot=new Map,this.assets=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,this.pmremGeneratorResults=new WeakMap,this.prefabInstanceChain=[],this.geometryCache=new Map,this.collisionShapeCache=new Map,this.originalFog=null,t.onCreate(e=>this.update(e)),t.onUpdate(e=>this.update(e)),t.onRemove(e=>this.remove(e)),this.createAssetSubscription=a.onCreate.subscribe(e=>{this.assets.set(e.id,e)}),this.updateSubscription=a.onUpdate.subscribe(async t=>{this.assets.set(t.id,t),"material"==t.type?e.traverse(e=>{if(e instanceof r.Mesh)if(Array.isArray(e.material))for(let a=0;a<e.material.length;a++)this.refreshMaterial(e,e.material[a],t,a);else this.refreshMaterial(e,e.material,t)}):"mesh"==t.type?(this.findByAssetId(t.id).forEach(e=>{this.remove(e.userData.src),this.materializeAndInitActor(e.userData.src)}),this.landscapeManagers.forEach(e=>{const a=e.source?.grass?.layers?.some(e=>e.meshes.some(e=>e.assetId===t.id));a&&e.queueRefreshScatter(this.renderingView?.camera.position??new S,!0)})):"prefab"===t.type?this.findByAssetId(t.id).forEach(e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t)}):"vfx"===t.type&&this.dataProvider.getObjects().forEach(e=>{It(e,(e,a)=>{"vfx"===e.type&&e.assetId===t.id&&(this.remove(e),this.materializeAndInitActor(e))})})})}async refreshMaterial(e,t,a,s){const r=t?.userData?.assetId;if(r!==a.id){const e=this.assets.get(r);let t=!1;if(null!=e)for(const s of Object.values(e.material.shaderParams)){if(s.type===Re.Material&&s.value===a.id){t=!0;break}if(s.type===Re.Array&&"element"in s&&s.element===Re.Material&&s.value.includes(a.id)){t=!0;break}}if(!t)return}const i=await materialFromAsset(this.assets.get(r),this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1),n=i.userData;i.userData=t.userData,i.userData.hasBloom=n.hasBloom,i.userData.reflective=n.reflective,i.userData.outlineParameters=n.outlineParameters,null!=s?Ot(e.material[s],i)||(e.material[s]=i):Ot(e.material,i)||(e.material=i,e===this.sky&&this.applySkySettings(e.material))}getTopLevelActors(){return Array.from(this.materializedActors.entries()).filter(([e,t])=>!e.includes("/")).map(([,e])=>e)}get actorInstances(){return Array.from(this.materializedActors.values())}async initTextures(){const e=[];if(await Promise.all(this.dataProvider.getObjects().filter(e=>"shape_mesh"===e.type||"asset_mesh"===e.type).filter(e=>null!=e.materialAssignments).flatMap(e=>e.materialAssignments).map(async t=>{const a=this.assets.get(t.materialId);if(null!=a)for(const t of Object.values(a.material.shaderParams))if(t.type===Re.Texture&&"string"==typeof t.value){const a=this.assets.get(t.value),s=await this.assetManagerService.getTexture(a);null!=s&&e.push(s)}})),0!==e.length&&this.renderingView){console.log(`Initializing ${e.length} textures`),console.time("Init textures");for(const t of e)this.renderingView.renderer.initTexture(t);console.timeEnd("Init textures")}}async prefetchAssets(){const e=Array.from(new Set(this.dataProvider.getObjects().filter(e=>null!=e.assetId&&"asset_mesh"==e.type).filter(e=>e.assetId)));await Promise.all(e.map(e=>this.assetsService.getAsset(e.assetId).then(e=>{if(null!=e)return this.assetManagerService.getMesh(e)}))),this.initTextures()}async init(){await this.preInit(),yt.clear(),wt.clear(),await this.prefetchAssets(),await Promise.all(this.dataProvider.getObjects().map(e=>this.materialize(e))),await this.initActorsPostInit()}initActorsPostInit(e=this.getTopLevelActors(),t){const a=e.map(async e=>{const a=e.object.userData.src??e.object.userData._src;if("vfx"===a.type)return Promise.resolve();const s=await this.assetsService.getAsset(a.assetId),r={...s?.actor?.params??{},...a.actor?.params??{}},i=null!=t?new Map(Array.from(this.materializedActors.entries()).filter(([e,a])=>e.startsWith(t.sceneObjectChain.join("/"))&&e.split("/").length-1===t.sceneObjectChain.length).map(([e,t])=>[e.split("/").pop(),t])):this.materializedActors;for(const t of a.actor.innerParams??[])await this.applyActorComponentParams(e,t.path.slice(),t.params,i);const n=await prepareClassParameters(r,e.constructor,this.assetsService,this.assetManagerService,i,this.renderingView,this.shaders,this.actorProvider);Object.assign(e,n);try{return await this.actorProvider.initActor(e)}catch(e){console.error(`Failed to initiate actor (name="${a.name}", id=${a.id})`,e)}});return Promise.all(a)}addVfxChildActors(e,t=e){}async applyActorComponentParams(e,t,a,s){const r=t.length,i=t.shift();if(0==r){const t=await prepareClassParameters(a,null,this.assetsService,this.assetManagerService,s,this.renderingView,this.shaders,this.actorProvider);for(const[a,s]of Object.entries(t))null!=s&&(e[a]=s)}else null!=e[i]&&await this.applyActorComponentParams(e[i],t,a,s)}canObjectBeInstanced(e){return e.physics?.type!==le.dynamic&&"sky"!==e.type&&"global_fog"!==e.type&&"world_env"!==e.type}async canAssetBeInstanced(e){let t=this._canBeInstancedCache.get(e.assetId);if(null==t){const a=await this.createFromAsset(e);if(null==a)return!1;const s=[];a.traverse(e=>{!Oe(e)&&e.isMesh&&s.push(e)});const r=1==s.length&&0==s[0].children.length,i=!ut,n=s.every(e=>!Array.isArray(e.material)||1===e.material.length),o=s.some(e=>e instanceof d&&null!=e.geometry.morphAttributes&&Object.keys(e.geometry.morphAttributes).length>0),l=!0;t=s.length>0&&(r||n&&i)&&l&&!o,this._canBeInstancedCache.set(e.assetId,t)}return t}async preInit(){this.renderingView?.onLoop(()=>{null!=this.sky&&this.renderingView.camera.getWorldPosition(this.sky.position)}),this.assetsService.getAssets().then(e=>{for(const t of e)this.assets.set(t.id,t)})}shouldBeMaterialized(e){if(null!=this.detailTier&&"asset_mesh"===e.type&&null!=e.assetId){const t=this.assets.get(e.assetId);if(null!=t){const e=t.mesh?.detailTier;if(null!=e)return e<=this.detailTier}}return!0}async initWithInstancing(){await this.preInit(),await this.prefetchAssets(),yt.clear(),wt.clear();const e=[],t=new Ae,a=new Ae,s=new Ae;let i=0,l=0,c=0;const h=new Map,p=new Se(()=>new Map);for(const r of this.dataProvider.getObjects())await It(r,async(r,o,m)=>{if(!this.shouldBeMaterialized(r))return;const u="asset_mesh"==r.type&&this.canObjectBeInstanced(r)&&await this.canAssetBeInstanced(r),f="shape_mesh"===r.type&&"landscape"!==r.shape&&r.physics?.type!==le.dynamic;if(u||f){if(o&&o.children?.length>0){const e=o.children.findIndex(e=>e.id===r.id);e>=0&&o.children.splice(e,1)}if(f){let e=r.shape+JSON.stringify(r.shapeParams??{})+r.castShadow+r.receiveShadow;const t=r.materialAssignments?.at(0)?.materialId,a=null!=t?this.assets.get(t):null;let i=null;if(null!=a&&"shader"!==a.material.type){if(e+=a.material.type+a.material.shader,null!=a.material.shaderParams){if(e+=Object.entries(a.material.shaderParams).filter(([e,t])=>"color"!=e).map(e=>JSON.stringify(e)).join(),null!=a.material.shaderParams.color){const e=a.material.shaderParams.color;e.type===Re.Color&&null!=e.value&&(i=new n(e.value))}}}else e+=t;s.push(e,{object:{...r,parentTransform:m},color:i}),c++}else{const e=this.assets.get(r.assetId);let s=h.get(r.assetId);if(null==s){const e=await this.createFromAsset(r,{assignMaterials:!1});if(null==e)return;if(s=h.get(r.assetId),null==s){s={useBatchedMesh:null!=Pe(e)&&pt(e,e=>!(e instanceof d)||this.testCanBatch(e.material,e.geometry)),assetMesh:e},h.set(r.assetId,s)}}const n=Pt(r.materialAssignments,e.materialAssignments);if(s.useBatchedMesh)await Ee(s.assetMesh,async e=>{if(!(e instanceof d))return;const t=Array.isArray(e.material)?e.material[0]:e.material,s=n.find(e=>null!=t.color&&Vt(e.color,t.color)&&(null==e.name||t.name===e.name))?.materialId;let o=t;if(null!=s){const e=this.assets.get(s);o=await materialFromAsset(e,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!0)}if(null!=o){p.get(r.id).set(e.uuid,o);let t=Nt(o);t+=Ft(e),a.push(t,{...r,parentTransform:m,meshUUID:e.uuid}),i++}else console.warn("Can not materialize mesh because missing material",r)});else{const e=r.assetId+JSON.stringify(r.materialAssignments??[]);t.push(e,{...r,parentTransform:m}),l++}}}else null==o&&e.push({...r,parentTransform:m})});console.log(`Scene init stats: \n Batched Assets: ${a.size} groups containing in total ${i} objects.\n Instanced Assets: ${t.size} groups containing in total ${l} objects.\n Shapes: ${s.size} batch groups containing in total ${c} objects. \n ${e.length} objects can not be batched. \n `);for(const e of h.values())this.prepareCollisionShapesForInstanced(e.assetMesh);console.time("materialize batches");for(const e of a.values()){if(0==e.length)continue;let t;const a=h.get(e[0].assetId).assetMesh;t=this.createBatchedMesh(e,p,h);const s=this.assets.get(e[0].assetId);t.castShadow=e[0].castShadow??s.castShadow??!0,t.receiveShadow=e[0].receiveShadow??s.receiveShadow??!0;const r=new Te;r.add(t),r.userData.src=e[0],a instanceof Te&&(r.collisionShapes=a.collisionShapes),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r)}for(const e of t.values()){if(0==e.length)continue;let t;const a=h.get(e[0].assetId).assetMesh;t=await this.createInstancedMesh(e,a);const s=this.assets.get(e[0].assetId);t.castShadow=e[0].castShadow??s.castShadow??!0,t.receiveShadow=e[0].receiveShadow??s.receiveShadow??!0;const r=new Te;r.add(t),r.userData.src=e[0],a instanceof Te&&(r.collisionShapes=a.collisionShapes),this.prepareCollisionShapesForInstanced(r),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r)}console.timeEnd("materialize batches");for(const e of s.values()){if(0==e.length)continue;const t=e[0].object,a=await this.createFromShape(t),s=Ce(a,e=>!Oe(e)&&null!=e.geometry),i=s.material.clone();null!=e[0].color&&null!=i.color&&(i.color=new n(16777215));const l=s.geometry;let c,h;!(ut||i instanceof _||null==l.index)?(c=new r.BatchedMesh(e.length,l.getAttribute("position").count,l.index.count,i),c.perObjectFrustumCulled=!0,h=c.addGeometry(l)):c=new r.InstancedMesh(l,i,e.length),c.castShadow=a.castShadow??!0,c.receiveShadow=s.receiveShadow??!0;for(let t=0;t<e.length;t++){const a=e[t],s=(new r.Matrix4).compose((new S).fromArray(a.object.position),(new M).setFromEuler((new o).fromArray(a.object.rotation)),(new S).fromArray(a.object.scale)),i=(new m).copy(a.object.parentTransform).multiply(s);let n;n=c instanceof r.BatchedMesh?c.addInstance(h):t,c.setMatrixAt(n,i),null!=a.color&&c.setColorAt(n,a.color)}for(let t=0;t<e.length;t++){const s=e[t],r=new Te;r.userData.src=e[0],a instanceof ze&&(r.collisionShapes=[a.collisionShape]),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r),r.add(c),null==c.userData.hasCollision&&(c.userData.hasCollision=[]),c.userData.hasCollision[t]=!!s.object.collisionDetection}}await Promise.all(e.map(e=>this.materialize(e))),await this.initActorsPostInit()}prepareCollisionShapesForInstanced(e){e instanceof Te&&e.collisionShapes.forEach(e=>{e instanceof a&&e.mesh instanceof d&&(e.mesh=e.mesh.geometry)})}testCanBatch(e,t){return!ut&&t.groups.length<2&&(!Array.isArray(e)||1==e.length)&&this.testCanBatchMaterial(e)}testCanBatchMaterial(e){const t=Array.isArray(e)?e[0]:e;return null!=t&&(!(t instanceof g)||null==t.bumpMap&&null==t.lightMap&&null==t.displacementMap)}createBatchedMesh(e,t,a){const s=new Ae;for(const t of e)null!=t.meshUUID?s.push(t.meshUUID??t.assetId,t):console.warn("Missing mesh uuid for batching");let i=0,o=0,l=0;const c=new Map;for(const[e,t]of s.entries()){const s=t[0].assetId,r=a.get(s);if(null==r){console.warn("Missing batching info for asset id "+s);continue}const n=Ce(r.assetMesh,t=>t instanceof d&&t.uuid===e);if(null==n){console.warn("Missing mesh in batched asset");continue}c.set(e,n);const h=n.geometry.getAttribute("position");null==h&&console.warn("Missing position attribute for batched mesh"),i+=n.geometry.index.count*t.length,o+=h.count*t.length,l+=t.length}const h=["color","map","roughness","roughnessMap","metalness","metalnessMap","opacity","alphaMap","aoMap","aoMapIntensity","normalMap","normalScale","emissive","emissiveIntensity","emissiveMap"];let p=new Map,m=new r.MeshStandardMaterial({color:"white"});const u=t.get(e[0].id).get(e[0].meshUUID);if(null==u)throw"missing source material";if(u instanceof g){const a=new Set,s=new Map;for(const i of e){const e=t.get(i.id).get(i.meshUUID);if(null==e)throw"missing mat";for(const t of h){let i=e[t];i instanceof r.CompressedArrayTexture&&null!=i.userData.index&&(i=i.userData.index);const n=s.get(t);void 0===n||Lt(i,n)?s.set(t,i):a.add(t)}}for(const e of a){let t;const a=u[e];if("number"==typeof a)t=D(e);else if(a instanceof x)t=E(e);else if(a instanceof S||a instanceof n)t=C(e);else if(a instanceof A)t=P(e);else if(a instanceof r.CompressedArrayTexture)t=D(e+"_i");else if(a instanceof b)continue;p.set(e,t)}let i=q.uv;u instanceof ct&&null!=u.heightMap&&(i=ht(i,H(u.heightMap),z(u.heightScale)));let o=_t(p.get("opacity"),F)??z(u.opacity??1);if(null!=u.alphaMap){let e;if(u.alphaMap instanceof r.CompressedArrayTexture){const t=J(u.alphaMap),a=_t(p.get("alphaMap"),F)??z(u.alphaMap.userData.index??0);e=t.sample(K(i.x,i.y,a))}else e=H(u.alphaMap).sample(i);o=o.multiply(e.r)}let l=$(_t(p.get("color"),Q)??u.color,o);if(null!=u.map){let e;if(u.map instanceof r.CompressedArrayTexture){const t=J(u.map),a=_t(p.get("map"),F)??z(u.map.userData.index??0);e=t.sample(K(i.x,i.y,a))}else e=H(u.map).sample(i);l=l.multiply(e)}let c=$(_t(p.get("emissive"),Q)??u.emissive,o);if(null!=u.emissiveMap){let e;if(u.emissiveMap instanceof r.CompressedArrayTexture){const t=J(u.emissiveMap),a=_t(p.get("emissiveMap"),F)??z(u.emissiveMap.userData.index??0);e=t.sample(K(i.x,i.y,a))}else e=H(u.emissiveMap).sample(i);c=c.multiply(e)}const d=_t(p.get("emissiveIntensity"),F)??z(u.emissiveIntensity??1),f=_t(p.get("normalScale"),Z)??Y(u.normalScale??new A(1,1));let g=X.normal;if(null!=u.normalMap){let e;if(u.normalMap instanceof r.CompressedArrayTexture){const t=J(u.normalMap),a=_t(p.get("normalMap"),F)??z(u.normalMap.userData.index??0);e=t.sample(K(i.x,i.y,a))}else e=H(u.normalMap).sample(i);g=k(e.rgb,f.x)}let y=_t(p.get("roughness"),F)??z(u.roughness??1);if(null!=u.roughnessMap){let e;if(u.roughnessMap instanceof r.CompressedArrayTexture){const t=J(u.roughnessMap),a=_t(p.get("roughnessMap"),F)??z(u.roughnessMap.userData.index??0);e=t.sample(K(i.x,i.y,a))}else e=H(u.roughnessMap).sample(i);y=y.multiply(e.g)}let w=_t(p.get("metalness"),F)??z(u.metalness??0);if(null!=u.metalnessMap){let e;if(u.metalnessMap instanceof r.CompressedArrayTexture){const t=J(u.metalnessMap),a=_t(p.get("metalnessMap"),F)??z(u.metalnessMap.userData.index??0);e=t.sample(K(i.x,i.y,a))}else e=H(u.metalnessMap).sample(i);w=w.multiply(e.b)}let M=z(1);if(null!=u.aoMap){let e;if(u.aoMap instanceof r.CompressedArrayTexture){const t=J(u.aoMap),a=_t(p.get("aoMap"),F)??z(u.aoMap.userData.index??0);e=t.sample(K(i.x,i.y,a))}else e=H(u.aoMap).sample(i);M=M.multiply(e.r)}const v=_t(p.get("aoMapIntensity"),F)??z(u.aoMapIntensity??0);let j=g;!0!==u.userData.disableAO&&(j=B("DOUBLE_SIDED",j,e=>L(new V("gl_FrontFacing"),e,e.multiplyScalar(-1))));const I=new _({color:R({color:l,roughness:y,metalness:w,ambientOcclusion:M,ambientOcclusionIntensity:v,emissive:c,emissiveIntensity:d,normal:j}),normal:g,roughness:y,emissive:c.rgb,transparent:u.transparent,alphaTest:u.alphaTest,envMap:u.envMap});null!=u.envMap&&(I.uniforms.envMapIntensity={value:u.envMapIntensity},I.uniforms.envMapRotation={value:Wt(u.envMapRotation,u.envMap)}),I.envMap=u.envMap,I.side=u.side,m=I}else{m=u;for(const a of e){const e=t.get(a.id).get(a.meshUUID);if(e!=m){console.error(`Different materials in group for object ${a.id} and mesh uuid ${a.meshUUID}`,{objectMaterial:e,sourceMaterial:u});break}}}const f=new lt(l,o,i,m);for(const[e,t]of p.entries()){let a=1;t instanceof te||t instanceof Q?a=4:t instanceof Z&&(a=2),f.initUniform(e,a,0)}for(const[e,i]of s.entries()){const s=i[0].assetId,o=c.get(e);if(null==o){console.error(`Missing single asset mesh for mesh uuid ${e} and asset id ${s}`);continue}if(null==o.geometry){console.error("Missing geometry on mesh mesh");continue}const l=f.addGeometry(o.geometry),h=a.get(s);if(null==h){console.warn("Missing batching info when configuring for asset id "+s);continue}const m=Pe(h.assetMesh)?.uuid===e,d=h.assetMesh instanceof Te&&m?h.assetMesh.collisionShapes:void 0,u=this.configureBatchedInstancedMesh(i,f,o,l,d);for(let e=0;e<u.length;e++){const a=i[e],s=u[e],o=t.get(a.id).get(a.meshUUID);for(let e of p.keys()){let t=o[e];if(t instanceof n&&(t=new S(t.r,t.g,t.b)),t instanceof r.CompressedArrayTexture)t=t.userData.index??0,e+="_i";else if(t instanceof b||null==t)continue;f.setUniformAt(e,s,t)}}}return f}async createInstancedMesh(e,t){const a=Ce(t,e=>!Oe(e)&&null!=e.geometry),s=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,Pt(e[0].materialAssignments,s.materialAssignments)),a.updateMatrix();const i=a.geometry.clone(),n=a.material;let o;if(o=new r.InstancedMesh(i,n,e.length),this.configureBatchedInstancedMesh(e,o,a),a.material instanceof p&&o.castShadow&&o.receiveShadow&&Array.isArray(n))for(const e of n);return o}configureBatchedInstancedMesh(e,t,a,s,i){const n=[];for(let l=0;l<e.length;l++){let c=l;t instanceof r.BatchedMesh&&(c=t.addInstance(s)),n.push(c);const h=(new r.Matrix4).compose((new S).fromArray(e[l].position),(new M).setFromEuler((new o).fromArray(e[l].rotation)),(new S).fromArray(e[l].scale)),p=(new m).copy(e[l].parentTransform).multiply(h).multiply(a.matrixWorld);t.setMatrixAt(c,p),null==t.userData.hasCollision&&(t.userData.hasCollision=[]),t.userData.hasCollision[c]=!!e[l].collisionDetection,null!=i&&(null==t.userData.collisionShapes&&(t.userData.collisionShapes=[]),t.userData.collisionShapes[c]=i)}return n}remove(e){if(console.log("Remove scene object",e),"global_fog"==e.type)return void(this.scene.fog=this.originalFog);if("world_env"===e.type)this.resetWorldEnv(),this.worldEnvObj=null;else if("actor"==e.type||"vfx"===e.type){const t=this.materializedActors.get(e.id);null!=t?(t.disposed.next(!0),t.onEndPlay()):console.warn("Failed to remove actor",e)}else"prefab"===e.type&&this.materializedActors.forEach((t,a)=>{a.startsWith(e.id)&&(t.disposed.next(!0),t.onEndPlay()),this.materializedActors.delete(a)});const t=this.sceneObjectMap.get(e.id);t?.parent.remove(t),this.sceneObjectMap.delete(e.id),this.components.filter(t=>t.object.userData.src?.id===e.id).forEach(e=>this.components.splice(this.components.indexOf(e,1))),this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>{e.clear(),e.stop(),this.landscapeManagers.splice(this.landscapeManagers.indexOf(e,1))}),this.removed$.next({object:t,source:e})}deleteSceneObject(e){const t=this.sceneObjectMap.get(e.id);if(this.scene.remove(t),"landscape"==e.type){const t=this.landscapeManagers.findIndex(t=>t.source.id===e.id);if(t>-1){const e=this.landscapeManagers.splice(t,1)[0];e.clear(),e.stop()}}}findByAssetId(e){return De(this.scene,t=>t.userData.src?.assetId==e,e=>null!=e.userData.src)}applyMaterials(e,t){return null==t?Promise.resolve([]):Promise.all(t.filter(e=>"null"!==e.materialId).map(t=>this.applyMaterial(e,t)))}async applyMaterial(e,t){await applyMaterial(e,t,e=>{const t=this.assets.get(e);if(null!=t)try{return materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders)}catch(e){console.error("Failed to apply material",e)}},this._originalMaterials)}unapplyMaterials(e){e.traverse(async e=>{if(e instanceof d)if(e.material instanceof Array)for(let t=0;t<e.material.length;t++)e.material[t]=this._originalMaterials.get(e.id+"#"+t)??e.material[t];else e.material=this._originalMaterials.get(e.id)??e.material})}updateActors(e){console.log("update actors"),this.actorTypes=e;const t=new Set(Object.values(oe));De(this.scene,e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&!t.has(e.userData.src.actor.type)).forEach(async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)})}updateShaders(e){this.shaders=e;for(const[e,t]of yt.entries())t.userData.customShaderName&&yt.delete(e);this.landscapeManagers.forEach(t=>t.updateShaders(e)),De(this.scene,e=>!0).forEach(e=>{e.traverse(async e=>{if(e instanceof d)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++){const a=e.material[t].userData?.customShaderName;if(null!=a){const a=this.assets.get(e.material[t].userData.assetId);this.refreshMaterial(e,e.material[t],a,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=this.assets.get(e.material.userData.assetId);this.refreshMaterial(e,e.material,t)}}})})}async update(e){if("sky"===e.type&&null!=this.sky&&null!=this.sky.parent)return void this.updateSky(e);if("world_env"===e.type&&null!=this.worldEnvObj)return void this.updateWorldEnv(e);const t=this.sceneObjectMap.get(e.id);if(t){let s=!1;if(t.traverseAncestors(e=>{"_hology_transform_group"===e.name&&(s=!0)}),!s){const a=this.findParent(e);null!=a&&a.uuid!=t.uuid?a.attach(t):console.error("Parent is wrong")}if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(t);this.inEditor&&e.hidden&&!1?t.traverse(e=>{e instanceof d&&(e.material.wireframe=!0)}):t.traverse(e=>{e instanceof d&&(e.material.wireframe=!1)})}if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);Pt(e.materialAssignments,a.materialAssignments).forEach(e=>this.applyMaterial(t,e))}else"shape_mesh"===e.type&&this.applyMaterials(t,e.materialAssignments);if(s||(null!=e.position&&t.position.fromArray(e.position),null!=e.scale&&t.scale.fromArray(e.scale),null!=e.rotation&&t.rotation.fromArray(e.rotation)),this.applyVertexMaterials(e,t),"light"==e.type)if("point"==e.light.type){const a=t;a.color=new n(e.light.point.color),a.intensity=e.light.point.intensity,a.decay=e.light.point.decay,a.castShadow=e.light.point.castShadow,a.distance=Math.max(e.light.point.distance,0),a.userData.volumetricIntensity=e.light.point.volumetricIntensity}else if("spot"==e.light.type){const a=t;a.color=new n(e.light.spot.color),a.intensity=e.light.spot.intensity,a.decay=e.light.spot.decay,a.angle=e.light.spot.angle,a.penumbra=e.light.spot.penumbra,a.castShadow=e.light.spot.castShadow,a.distance=Math.max(e.light.spot.distance,0),a.userData.volumetricIntensity=e.light.spot.volumetricIntensity}else"directional"===e.light.type?this.applyDirectionalLight(e.light.directional,e):"ambient"===e.light.type&&this.applyDirectionalAmbientLight(t,e.light.ambient,e);else if("landscape"===e.shape){const a=this.landscapeManagers.find(t=>t.source.id===e.id).source.landscape.options.density!==e.landscape.options.density;if(this.inEditor&&a){this.remove(e);const t=await this.materializeAndInitActor(e);return void this.updated$.next({object:t,source:e})}this.applyHeightMaps(t,e.landscape.heightMaps),this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(t=>{t.updateSource(e),t.queueRefreshScatter(this.renderingView.camera.position,!0,e=>!0)})}else if("global_fog"===e.type){const t=(this.scene.fog instanceof c?"density":"linear")!==e.fog.type;this.scene.fog=xt(e.fog),t&&(a=this.scene).traverse(e=>{if(e instanceof d){const t=e.material;t instanceof _&&(a.fog instanceof l?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof c&&(t.uniforms.density={value:a.fog.density}),t.needsUpdate=!0,t.uniformsNeedUpdate=!0)}}),this.fixFogColor()}else if("actor"===e.type){if(this.materializedActors.has(e.id)){const t=this.materializedActors.get(e.id);if(t instanceof it){const a=await prepareClassParameters(e.actor.params,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,[],this.actorProvider);return void Object.assign(t,a)}const a=this.editorActorParamSnapshot.get(e.id);null!=a&&a===JSON.stringify(e.actor)||s||(this.remove(e),await this.materializeAndInitActor(e))}}else if("shape_mesh"===e.type){const a=await this.createMeshByShape(e.shape,t.material,e.shapeParams);t instanceof ze&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&gt(t,e.castShadow,e.receiveShadow),e.name&&e.name.length>0&&(t.name=e.name),this.updated$.next({object:t,source:e})}else{const t=await this.materializeAndInitActor(e);this.updated$.next({object:t,source:e})}var a;this.renderingView.renderer.shadowMap.needsUpdate=!0}async materializeAndInitActor(e,t=this.findParent(e)){const a=await this.materialize(e,t);return It(e,async e=>{if("actor"===e.type){const t=this.materializedActors.get(e.id);null!=t?await this.initActorsPostInit([t]):console.error(`Something went wrong when creating actor ${e.id}`)}}),a}findParent(e){const t=this.dataProvider.getObjects().flatMap(t=>t.id===e.id?null:Ie(t,t=>t.children?.some(t=>t.id===e.id),()=>!0))[0];return null==t?this.scene:null!=t?De(this.scene,e=>e.userData?.src?.id===t.id,e=>null!=e.userData?.src)[0]:void 0}fixFogColor(){!0===this.renderingView.options.enableOutlines&&(this.scene.fog.color=new n(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse(e=>{e instanceof d&&e.geometry&&(t=e)}),t}applyVertexMaterials(e,t){if(null==e.vertexMaterials||0===e.vertexMaterials.length)return;let a=1;for(const t of e.vertexMaterials)a=Math.max(t.w.length,a);const s=xe(e.vertexMaterials,e=>e.m);t.traverse(e=>{if(e instanceof d){if(null==e.geometry)return;if(kt(We(e,0,!1)),a>0){kt(We(e,0,!1))}}});const r=new Set;for(const[e,i]of s.entries()){const s=null!=e?t.getObjectByName(e):this.findMeshWithGeometry(t);let n=!1;if(null==s||null==s.geometry)return void console.warn(`Failed to apply vertex materials on mesh with name "${e}"`);const o=We(s,0,!0);kt(o);for(const e of i)o.setX(e.i,e.w[0]??0),o.setY(e.i,e.w[1]??0),o.setZ(e.i,e.w[2]??0),o.setW(e.i,e.w[3]??0),n=!0;if(a>0){const e=We(s,4,!0);kt(e);for(const t of i)e.setX(t.i,t.w[4]??0),e.setY(t.i,t.w[5]??0),e.setZ(t.i,t.w[6]??0),e.setW(t.i,t.w[7]??0),e.needsUpdate=!0,n=!0}n&&r.add(e)}this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,e=>r.has(e.name)))}async materialize(e,t,a=!1,s){if(!this.shouldBeMaterialized(e))return;let r,n;switch(e.type){case"asset_mesh":r=await this.createFromAsset(e);break;case"shape_mesh":r=await this.createFromShape(e);break;case"light":r=await this.createLight(e);break;case"particles":r=await this.createParticleSystem(e),e.collisionDetection=!1;break;case"global_fog":this.scene.fog=xt(e.fog),this.fixFogColor(),r=new h;break;case"sky":this.sky=qe(),this.updateSky(e),r=this.sky;break;case"world_env":this.updateWorldEnv(e),r=new h,this.worldEnvObj=r;break;case"actor":({object:r,actor:n}=await this.createFromActor(e,s));break;case"group":r=new h;break;case"prefab":r=await this.createFromPrefab(e,s);break;case"vfx":r=await this.createFromVfx(e,s);break;default:if(this.inEditor)throw new Error("unknown type "+e.type);console.warn(`Failed to materialize object. Unknown type '${e.type}'. This might be because the hology/core library is not compatible with the editor version.`)}if(null!=r){if(e.name&&e.name.length>0&&(r.name=e.name),null!=e.position&&r.position.fromArray(e.position),null!=e.scale&&r.scale.fromArray(e.scale),null!=e.rotation&&r.rotation.fromArray(e.rotation),a?r.userData._src=e:r.userData.src=e,null!=n&&(r.userData.actor=n),this.inEditor,this.inEditor){let e=null;r instanceof ze&&(e=function(e){if(e instanceof ke)return new d(new i(...e.offset.toArray()),jt);return null}(r.collisionShape)),null!=e&&(e.layers.disable(0),e.layers.enable(18),e.scale.multiplyScalar(1.1),r.add(e))}if(this.objectMap.set(r.uuid,e),this.sceneObjectMap.set(e.id,r),e.physics?.type!==le.dynamic||null==t||this.inEditor?null==t?this.scene.add(r):t?.add(r):(t.add(r),r.getWorldPosition(r.position),r.getWorldQuaternion(r.quaternion),r.getWorldScale(r.scale),this.scene?.attach(r)),null!=e.children&&await Promise.all(e.children?.map(e=>this.materialize(e,r,a))),this.inEditor||"asset_mesh"!=e.type&&"shape_mesh"!==e.type||"landscape"===e.shape||null!=e.physics?.type&&e.physics.type==le.dynamic||St(r),null!=this.renderingView)return this.renderingView.renderer.shadowMap.needsUpdate=!0,r;console.warn("RenderingView not found in materializer")}}updateWorldEnv(e){this.renderingView.aoPass.enabled=e.worldEnv.ao.enabled,this.renderingView.aoPass.blendIntensity=e.worldEnv.ao.blendIntensity,this.renderingView.aoPass.updateGtaoMaterial(e.worldEnv.ao);const t=e.worldEnv.toneMapping;null!=t&&(this.renderingView.renderer.toneMapping=t.mapping??0,this.renderingView.renderer.toneMappingExposure=t.exposure??1);const a=e.worldEnv.environment;null!=a&&null!=a.textureId?this.assetManagerService.getTexture(this.assets.get(a.textureId)).then(e=>{null==this.pmremGenerator&&(this.pmremGenerator=new r.PMREMGenerator(this.renderingView.renderer),this.pmremGenerator.compileEquirectangularShader()),this.pmremGeneratorResults.has(e)||this.pmremGeneratorResults.set(e,this.pmremGenerator.fromEquirectangular(e).texture);const t=this.pmremGeneratorResults.get(e);this.renderingView.scene.environment=t,this.renderingView.scene.environmentIntensity=a.intensity??1}):this.renderingView.scene.environment=null}resetWorldEnv(){this.renderingView.aoPass.enabled=!1,this.renderingView.aoPass.blendIntensity=1,this.renderingView.aoPass.output=0,this.renderingView.renderer.toneMapping=0,this.renderingView.renderer.toneMappingExposure=1}async updateSky(e){if(null==e?.sky?.materialId)return void(this.sky.material=Xe);const t=await this.assetsService.getAsset(e.sky.materialId),a=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);this.applySkySettings(a),null!=this.sky?this.sky.material=a:console.warn("No sky has been created")}applySkySettings(e){e.side=r.BackSide,(e instanceof g||e instanceof r.MeshBasicMaterial||e instanceof r.ShaderMaterial)&&(e.fog=!1),e.depthTest=!1}async createComponent(e,t,a,s){const r=new mt[a.path+"/"+a.className],i=t.id+s;r.id=i,r.object=e;for(const e of a.params)null!=e.value&&(r[e.name]=e.value);return this.components.push(r),i}async createFromActor(e,t){const a=this.actorTypes.find(t=>t.name===e.actor?.type)?.type??oe[e.actor?.type];if(null==a)return{object:null,actor:null};this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const s=await this.actorProvider.create(a,(new S).fromArray(e.position),(new o).fromArray(e.rotation),!0);return this.materializedActors.set(this.getNestedActorId(e.id,t),s),{object:s?.object,actor:s}}getNestedActorId(e,t){return null!=t?t.sceneObjectChain.join("/")+"/"+e:e}async createFromVfx(e,t){const a=await this.assetsService.getAsset(e.assetId);null==a&&console.error("Could not find asset",e);const s=await this.actorProvider.create(se,(new S).fromArray(e.position),(new o).fromArray(e.rotation),!1);try{await s.fromAsset(a)}catch(e){return console.error("Failed to create VFX asset",e),null}return s.play(),this.materializedActors.set(this.getNestedActorId(e.id,t),s),null!=s&&(s.object.userData.actor=s),s?.object}async createFromShape(e){const t=this.inEditor&&e.hidden;let a;if("landscape"==e.shape)a=this.createLandscape(e),a.traverse(e=>{e instanceof d&&this._originalMaterials.set(e.id,e.material)});else{let s=new g({name:"Default",color:new n("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});const r=await this.createMeshByShape(e.shape,s,e.shapeParams);r.castShadow=e.castShadow??!0,r.receiveShadow=e.castShadow??!1,e.collisionDetection||(r.collisionShape=null),r.physics=e.physics,a=r,this._originalMaterials.set(a.id,r.material),a.traverse(e=>{})}return t||(await Promise.all((e.materialAssignments??[]).filter(e=>null!=e.materialId).map(e=>this.applyMaterial(a,e))),this.applyVertexMaterials(e,a)),a}createLandscape(e){const t=e.landscape?.options;if(null==t)return console.error(`No landscape options exist on scene object ${e.id} ${e.name}`),new h;const a=Be(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new Fe(e,this.renderingView,a,this.assetManagerService,this.assetsService,this.shaders,t=>{(e.materialAssignments??[]).filter(e=>null!=e.materialId).forEach(e=>this.applyMaterial(t,e))});return this.landscapeManagers.push(s),s.refreshGeometry(),a}applyHeightMaps(e,t,a=!1){const s=new Ne(e.sections);for(const e of t??[]){const t=s.find(e.x,e.y);if(!t)return;const a=t.geometry.getAttribute("position");for(const t of e.points)a.setY(t.i,t.y);a.needsUpdate=!0}const r=e.sections;r.forEach(e=>{e.geometry.computeBoundsTree(),e.geometry.computeVertexNormals()}),this.inEditor&&!a||setTimeout(()=>_e(r),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&He.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);if(!this.geometryCache.has(r)){const t=Ge[e].geometry(s);t.computeTangents(),this.geometryCache.set(r,t)}this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,Ge[e].collision(s));return new ze(this.geometryCache.get(r),t,this.collisionShapeCache.get(r))}if(this.inEditor)throw new Error(`Unsupported shape '${e}'`);console.warn(`Failed to create shape. Unsupported shape '${e}'. This might be because the hology/core library is not compatible with the editor version.`)}async createFromAsset(e,t){const a=await this.assetsService.getAsset(e.assetId);if(null==a)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);let{scene:s}=await this.assetManagerService.getMesh(a,{mergeGeomtries:!0});if(!1!==t?.assignMaterials)try{await Promise.all(Pt(e.materialAssignments,a.materialAssignments).map(e=>this.applyMaterial(s,e)))}catch(t){console.error("Failed to apply material"+t,e)}const r=e.receiveShadow??!!a.receiveShadow??!0,i=e.castShadow??!!a.castShadow??!1;return s.receiveShadow=r,gt(s,i,r),e.collisionDetection||(s.collisionShapes=[]),null!=e.physics&&!0!==this.inEditor&&(s.physics=e.physics),this.applyVertexMaterials(e,s),s.traverse(e=>{e instanceof d&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()}),s}async createFromPrefab(e,t){const a=await this.assetsService.getAsset(e.assetId);if(null==a)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);null==t&&(t={sceneObjectChain:[]}),t.sceneObjectChain.push(e.id);const{object:s}=await this.createFromPrefabAsset(a,t);return t.sceneObjectChain.pop(),s}async createFromPrefabAsset(e,t){const a=new h;await Promise.all(e.prefab.objects.filter(e=>"global_fog"!==e.type&&"world_env"!==e.type).map(e=>this.materialize(e,a,!0,structuredClone(t))));const s=t.sceneObjectChain.join("/"),r=Array.from(this.materializedActors.entries()).filter(([e,a])=>e.startsWith(s)&&e.split("/").length-1===t.sceneObjectChain.length).map(([,e])=>e);r.forEach(e=>{a.add(e.object)}),this.initActorsPostInit(r,structuredClone(t));const i=Array.from(this.materializedActors.entries()).filter(([e,t])=>e.startsWith(s)).map(([,e])=>e);return{object:a,actors:i}}async createParticleSystem(e){const t=await this.assetsService.getAsset(e.assetId),a=new y;return await j.fromJSONAsync(t.particleSystem,r).then(e=>{const t=new I(a,r);e.addRenderer(t),this.renderingView.onLoop(t=>e.update())}),a}async createLight(e){if("point"===e.light.type){const t=new w(e.light.point.color,e.light.point.intensity,e.light.point.distance,e.light.point.decay);if(t.castShadow=e.light.point.castShadow??!0,this.inEditor){const e=(new r.TextureLoader).load("assets/light-bulb-icon.webp"),a=new r.SpriteMaterial({map:e,alphaTest:.5}),s=new nt(a);s.scale.multiplyScalar(.6),t.add(s)}return t}if("spot"===e.light.type){const t=new r.SpotLight(e.light.spot.color,e.light.spot.intensity,e.light.spot.distance,e.light.spot.angle,e.light.spot.penumbra,e.light.spot.decay);if(t.castShadow=e.light.spot.castShadow??!0,t.target=new y,t.target.position.set(0,-1,0),t.add(t.target),this.inEditor){const e=(new r.TextureLoader).load("assets/light-bulb-icon.webp"),a=new r.SpriteMaterial({map:e,alphaTest:.5}),s=new nt(a);s.scale.multiplyScalar(.6),t.add(s),t.add(new r.SpotLightHelper(t))}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional,e),new h):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient,e),new h):void 0}applyDirectionalAmbientLight(e,t,a){const s=this.scene.children.find(e=>e.name===Je);null!=s?(s.intensity=t.intensity,s.color.set(t.color),s.groundColor.set(t.color),s.userData.src=a,s.userData.volumetricIntensity=t.volumetricIntensity):console.warn("Couldn't find ambient light")}applyDirectionalLight(e,t){for(const a of this.renderingView.csm.lights)a.intensity=e.intensity,a.color.set(e.color),a.castShadow=e.castShadow,a.userData.src=t,a.userData.volumetricIntensity=e.volumetricIntensity;this.renderingView.csm.lightDirection.fromArray(e.direction).normalize()}dispose(){this.updateSubscription.unsubscribe(),this.createAssetSubscription.unsubscribe(),this.materializedActors.forEach(e=>e.disposed.next(!0)),this.materializedActors.clear()}};ft=e([ae(),t("design:paramtypes",[v,Object,Object,Ve,pe,Array,Array,Object])],ft);export{ft as SceneMaterializer};function gt(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse(e=>{e.castShadow=t,e.receiveShadow=a})}const yt=new Map,wt=new Map,Mt=new u({color:16711935}),vt=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){const n=JSON.stringify(e.material);return i&&yt.has(n)?yt.get(n):i&&wt.has(n)?await wt.get(n):wt.set(n,_materialFromAsset(n,e,t,a,s,r,i)).get(n)}export async function _materialFromAsset(e,t,a,s,i,o,l=!0){const c={opacity:t.material.params.opacity,map:null,emissive:t.material.params.emissive??null,metalness:t.material.params.metalness??0,flatShading:t.material.params.flatShading??!1,color:new n(t.material.params.color),transparent:null!=t.material.params.opacity&&t.material.params.opacity<1},h={};if(null!=t.material.params.map){const e=t.material.params.map,a=await s.getAsset(e);null!=a&&(c.map=await i.getTexture(a))}let p;switch(t.material.type){case"phong":p=new f({...c,...h});break;case"water":p=Le(c,a);break;case"grassFoliage":p=Ue({color:c.color,map:c.map},a);break;case"grass":p=$e({...c,colorTwo:new n(t.material.params.colorTwo),colorThree:new n(t.material.params.colorThree)},a);break;case"standard":case"unlit":case"toon":case"layered":case"lambert":case"shader":case"landscape":case"landscape-composite":case"decal-unlit":case"decal-standard":const e={standard:dt?ge:Me,lambert:ge,unlit:ve,toon:ot,layered:st,landscape:we,"landscape-composite":ye,"decal-unlit":Ze,"decal-standard":Ke}[t.material.type]??o.find(e=>e.name==t.material.shader)?.type;if(e){try{let r=new e;const n=await prepareClassParameters(t.material?.shaderParams??{},e,s,i,null,a,o);Object.assign(r,n),p=r.build()}catch(e){console.log("Shader runtime error: "+e),vt.has(t.material.shader)||vt.set(t.material.shader,Mt.clone()),p=vt.get(t.material.shader)}p.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),p=Mt;break;default:throw new Error("Unsupported material type"+t.material.type)}return a?.csm.setupMaterial(p),null!=a&&yt.set(e,p),p.side=t.material.side??p.side??r.FrontSide,p.transparent=(t.material.transparent??c.transparent??!1)||p.transparent,p.alphaTest=t.material.alphaTest??p.alphaTest??0,null!=t.material.blending&&(p.blending=ce[t.material.blending]??r.NormalBlending),t.material.bloom&&(p.userData.hasBloom=!0),t.material.reflective&&(p.userData.reflective=!0),!0===t.material.outlines&&(p.userData.outlineParameters={},null!=t.material.outlineParams&&(null!=t.material.outlineParams.color&&(p.userData.outlineParameters.color=new n(t.material.outlineParams.color).toArray()),null!=t.material.outlineParams.thickness&&(p.userData.outlineParameters.thickness=t.material.outlineParams.thickness))),p.userData.assetId=t.id,wt.delete(e),p}export async function prepareClassParameters(e,t,a,s,r,i,n,o){const l={};for(const[t,c]of Object.entries(e)){const e=await At(t,c,a,s,r,i,n,o);null!=e&&(l[t]=e)}return l}export async function prepareShapeParameters(e){const t={};for(const[a,s]of Object.entries(e)){const e=await At(a,s,null,null,null);null!=e&&(t[a]=e)}return t}const bt=new Map;async function At(e,t,a,s,r,i,l,c,h=t.value,p=t.type){if(null==t||null==h||""===h)return null;switch(p){case Re.Array:if(Array.isArray(h)&&"element"in t)return await Promise.all(h.map(n=>At(e,t,a,s,r,i,l,c,n,t.element)));break;case Re.Number:case Re.FloatNode:let p;if("string"==typeof h?p=parseFloat(h):"number"==typeof h&&(p=h),t.type===Re.FloatNode){if("object"==typeof h&&"a"in h&&"b"in h){const e=h;if(null==e.a)return null;const t="string"==typeof e.a?parseFloat(e.a):e.a;if(null==e.b)return t;const a="string"==typeof e.b?parseFloat(e.b):e.b,s=function(e){let t=bt.get(e);return null==t&&(t=me(Ye.decode(e)),bt.set(e,t)),t}(e.easing),r=s.sample(de(ue.energy));return N(z(t),z(a),r)}return z(p)}return p;case Re.Texture:let m=await s.getTexture(await a.getAsset(h));return"envmap"===e.toLowerCase()&&null!=i&&(m=i.getEnvTexture(m)),m;case Re.Sampler2DNode:return H(await s.getTexture(await a.getAsset(h)));case Re.Boolean:return h;case Re.BooleanNode:return T(h);case Re.Vector2:case Re.Vec2Node:if("object"==typeof h){const e=h instanceof Array?(new A).fromArray(h):new A(h.x,h.y);return t.type===Re.Vec2Node?Y(e):e}return null;case Re.Vector3:case Re.Vec3Node:if("object"==typeof h){const e=h instanceof Array?(new S).fromArray(h):new S(h.x,h.y,h.z);return t.type===Re.Vec3Node?K(e):e}return null;case Re.Color:case Re.RgbNode:const d=new n(h);return t.type===Re.RgbNode?U(d):d;case Re.String:return h;case Re.BaseActor:const u=h;return null==r&&console.warn("Class parameters can not be prepared as actors are not passed in"),r?.get(u);case Re.Euler:const f=h;return(new o).fromArray(f);case Re.Object3D:return(await s.getMesh(await a.getAsset(h))).scene;case Re.Material:return await materialFromAsset(await a.getAsset(h),i,a,s,l);case Re.AudioBuffer:return await s.getAudio(await a.getAsset(h));case Re.VisualEffect:const g=await a.getAsset(h);if(null==c){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in g)return new re(c,g);console.error("Using a non-vfx asset for visual effect parameter");break;case Re.Prefab:{const e=await a.getAsset(h);return null==e?(console.error("Using a non-prefab asset for prefab parameter",h),null):new ie(e)}case Re.Curve:return Ye.decode(h);case Re.ColorLayer:case Re.MaskLayer:if(rt(h)){const e=await Qe.decode(h,async e=>await s.getTexture(await a.getAsset(e))),t=await prepareClassParameters(h.params,null,a,s);return Object.assign(e,t),e}return console.warn("Expecting color layer but got",h),null}return null}function St(e){e.updateWorldMatrix(!0,!0),e.updateMatrix(),e.traverse(e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1});const t=e.updateMatrixWorld;e.updateMatrixWorld=function(){t.apply(e),e.updateMatrixWorld=function(){}}}function xt(e){return"linear"===e.type?new l(new n(e.color),e.near??100,e.far??1e3):"density"===e.type?new c(e.color,e.density):void console.warn("Invalid fog type",e)}const jt=new g({color:4229780});async function It(e,t,a,s){null==s&&(s=(new m).identity());const i=s.clone().multiply(Dt(e,new r.Matrix4));if(null!=e.children&&e.children.length>0)for(let a=e.children.length-1;a>=0;a--)await It(e.children[a],t,e,i);await t(e,a,s)}function Dt(e,t){return null==e.position||null==e.rotation||null==e.scale?t.identity():t.compose((new S).fromArray(e.position),(new M).setFromEuler((new o).fromArray(e.rotation)),(new S).fromArray(e.scale))}export function toSerializedParamType(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?Re.Number:t instanceof F||"function"==typeof e.prototype.isFloat?Re.FloatNode:t instanceof b||e===b||e.isTexture?Re.Texture:t instanceof fe||e===G?Re.Sampler2DNode:t instanceof Boolean||e===Boolean?Re.Boolean:t instanceof O?Re.BooleanNode:t instanceof n||e==n?Re.Color:t instanceof W||"function"==typeof e.prototype.isRgb?Re.RgbNode:t instanceof A||e==A?Re.Vector2:t instanceof Z||"function"==typeof e.prototype.isVec2?Re.Vec2Node:t instanceof S||e==S?Re.Vector3:t instanceof Q||"function"==typeof e.prototype.isVec3?Re.Vec3Node:t instanceof String||e===String?Re.String:t instanceof ne||e==ne||e.prototype instanceof ne||e.prototype==ne?Re.BaseActor:t instanceof o||e==o?Re.Euler:t instanceof y||e==y?Re.Object3D:t instanceof p||e==p?Re.Material:t instanceof AudioBuffer||e==AudioBuffer?Re.AudioBuffer:t instanceof re||e==re?Re.VisualEffect:t instanceof ie||e==ie?Re.Prefab:t instanceof Ye||e==Ye?Re.Curve:t instanceof Qe||e==Qe?Re.ColorLayer:t instanceof at||e==at?Re.MaskLayer:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function prepareCustomParams(e,t,a={}){return Object.fromEntries(e.map(e=>[e.name,{type:e.options.array?Re.Array:toSerializedParamType(e.type),...e.options.array?{element:toSerializedParamType(e.type)}:{},value:t[e.name]?.value??(!0!==e.options.array?a[e.name]??customParameterDefaultValueByType.get(toSerializedParamType(e.type)):[])}]))}export function prepareCustomParamsFromType(e,t,a=null){const s=be(e);if(0===s.length)return{};let r;null!=a?he(a,()=>{r=a.get(e)}):r=new e;const i={};for(const e of s){const t=r[e.name];if(null!=t&&!0!==e.options.array){const a=serializeCustomParameter(e.type,t);null!=a&&(i[e.name]=a)}}return prepareCustomParams(s,t,i)}export function serializeCustomParameter(e,t){function a(){console.error("Failed to serialize value",{type:e,value:t})}switch(e){case Number:case Boolean:return t;case A:return t instanceof A?t.toArray():void a();case S:return t instanceof S?t.toArray():void a();case x:return t instanceof x?t.toArray():void a();case n:return t instanceof n?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new n(t).getHexString():void a();case String:return t;case o:return t instanceof o?t.toArray():void a();case ie:return t instanceof ie?t.asset?.id??null:void a()}}function Pt(e,t){return function(e,t,a){const s=[],r=new Set;for(const i of[...e??[],...t??[]]){const e=a(i);r.has(e)||(r.add(e),s.push(i))}return s}((e??[]).filter(e=>Ct(e.materialId)),(t??[]).filter(e=>Ct(e.materialId)),e=>e.color+e.name)}function Ct(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[Re.RgbNode,"#000000"],[Re.Color,"#000000"],[Re.Vector4,[0,0,0,0]],[Re.Vec4Node,[0,0,0,0]],[Re.Vector3,[0,0,0]],[Re.Vec3Node,[0,0,0]],[Re.Vector2,[0,0]],[Re.Vec2Node,[0,0]],[Re.Euler,[0,0,0,"XYZ"]],[Re.Array,[]],[Re.ColorLayer,et],[Re.MaskLayer,tt]]);let Et=new n,Tt=new n;function Vt(e,t){return Et.set(e),Tt.set(t),Et.getHexString()==Tt.getHexString()}export function applyMaterial(e,t,a,s){const i=[];return e.traverse(async e=>{if(e instanceof d||e.isMesh||e instanceof r.SkinnedMesh||e.isSkinnedMesh)for(const t of je(e.material))t.hasOwnProperty("color")&&i.push(e)}),Promise.all(i.map(async e=>{if(e.material instanceof Array)for(let r=0;r<e.material.length;r++){const i=e.material[r];if(null==i.color||!(i.color instanceof n))continue;const o="#"+i.color.getHexString(),l=i.name;if(o===t.color&&(i.name===t.name||null==t.name)||e.userData["originalColor_"+r]===t.color&&e.userData["originalMaterialName_"+r]===t.name){const i=await a(t.materialId),n=e.material[r];null!=i&&n.id!=i.id&&(e.material[r]=i,e.userData["originalColor_"+r]=e.userData["originalColor_"+r]??o,e.userData["originalMaterialName_"+r]=e.userData["originalMaterialName_"+r]??l,null!=s&&s.set(e.id+"#"+r,n))}}else if("color"in e.material){const r="#"+e.material.color.getHexString(),i=e.material.name;if(r===t.color&&(e.material.name===t.name||null==t.name)||e.userData.originalColor===t.color&&e.userData.originalName===t.name){const n=await a(t.materialId),o=e.material;null!=n&&(e.material=n,e.userData.originalColor=e.userData.originalColor??r,e.userData.originalMaterialName=e.userData.originalMaterialName??i,null!=s&&(s.has(e.id)||s.set(e.id,o)))}}}))}function Ot(e,t){if(e instanceof r.ShaderMaterial&&t instanceof r.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof r.ShaderMaterial&&t instanceof r.ShaderMaterial){for(const a in e.uniforms){if(null==t.uniforms[a])return!1;if(t.uniforms[a].value!==e.uniforms[a].value)return!1}return!0}return!1}(e,t)}return!1}function kt(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}const zt=new WeakMap;function Ft(e){let t=zt.get(e);return null==t&&(t=function(e){const t=Pe(e);if(null==t)return"";return Object.keys(t.geometry.attributes).sort().join(",")}(e),zt.set(e,t)),t}const Bt=new WeakMap;function Nt(e){let t=Bt.get(e);return null==t&&(t=function(e){let t=e.type;e instanceof r.MeshStandardMaterial||(t+=e.id+"");(e instanceof r.MeshBasicMaterial||e instanceof r.MeshLambertMaterial||e instanceof g||e instanceof f)&&(null!=e.map&&(t+="c"+e.map?.id),null!=e.aoMap&&(t+="o"+e.aoMap?.id),null!=e.lightMap&&(t+="l"+e.lightMap?.id),null!=e.envMap&&(t+="v"+e.envMap?.id),null!=e.alphaMap&&(t+="a"+e.alphaMap?.id));e instanceof g&&(null!=e.normalMap&&(t+="n"+e.normalMap?.id),null!=e.roughnessMap&&(t+="r"+e.roughnessMap?.id),null!=e.metalnessMap&&(t+="m"+e.metalnessMap?.id),null!=e.emissiveMap&&(t+="e"+e.emissiveMap?.id));(e instanceof u||e instanceof f)&&null!=e.specularMap&&(t+="s"+e.specularMap?.id);e instanceof r.MeshToonMaterial&&(null!=e.map&&(t+="c"+e.map?.id),null!=e.aoMap&&(t+="o"+e.aoMap?.id),null!=e.lightMap&&(t+="l"+e.lightMap?.id),null!=e.alphaMap&&(t+="a"+e.alphaMap?.id));e instanceof ct&&null!=e.heightMap&&(t+="h"+e.heightMap?.id);if(e instanceof r.ShaderMaterial){t+=e.vertexShader,t+=e.fragmentShader;for(const a in e.uniforms){const s=e.uniforms[a];s&&s.value&&s.value.isTexture&&null!=s.value.id&&(t+="t:"+a+":"+s.value.id)}}null!=e.userData.outlineParameters&&(t+=e.userData.outlineParameters.color,t+=e.userData.outlineParameters.thickness);return t+=e.side,t+=e.transparent?"t":"",t+=e.depthWrite?"dw":"",t+=e.depthTest?"dt":"",t+=e.alphaTest,t}(e),Bt.set(e,t)),t}function _t(e,t){if(null==e)return null;if(!(e instanceof t))throw new Error(`Value is not an instance of ${t.name}`);return e}const Ut=new m,$t=new o;function Wt(e,t){return $t.copy(e),$t.x*=-1,$t.y*=-1,$t.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&($t.y*=-1,$t.z*=-1),(new r.Matrix3).setFromMatrix4(Ut.makeRotationFromEuler($t))}new x;function Lt(e,t){return e===t||null==e==(null==t)&&("number"==typeof e&&"number"==typeof t?e===t||isNaN(e)&&isNaN(t):e instanceof r.Color&&t instanceof r.Color?e.r===t.r&&e.g===t.g&&e.b===t.b:e instanceof A&&t instanceof A?e.x===t.x&&e.y===t.y:e instanceof S&&t instanceof S?e.x===t.x&&e.y===t.y&&e.z===t.z:e instanceof x&&t instanceof x&&(e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w))}/*
2
2
  * Copyright (©) 2025 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -10,6 +10,7 @@ export declare class DecalUnlitShader extends DecalNodeShader {
10
10
  atlasTile: number;
11
11
  output(): {
12
12
  color: import("three-shader-graph").RgbaNode;
13
+ emissive: import("three-shader-graph").RgbNode;
13
14
  };
14
15
  build(): Material;
15
16
  }
@@ -1,4 +1,4 @@
1
- import{__decorate as t,__metadata as e}from"tslib";import{Color as i,Texture as a,Vector2 as r,BackSide as o}from"three";import{Parameter as l}from"../parameter.js";import{DecalNodeShader as s}from"../decal-shader.js";import{rgb as p,rgba as n,textureSampler2d as d,float as h,AttributeVec3Node as c,varying as m,ifDefApply as y,Vec3ExpressionNode as u}from"three-shader-graph";import{decalAlpha as S,decalUV as g}from"../../shader-nodes/decal.js";import{tileUv as D}from"./decal-standard-shader";export class DecalUnlitShader extends s{constructor(){super(...arguments),this.color=new i("#FFFFFF"),this.opacity=1,this.intensity=1,this.atlasSize=new r(1,1),this.atlasTile=1}output(){let t=D(g,this.atlasSize,this.atlasTile);const e=m(new c("particleData"));let i=y("IS_PARTICLE",h(this.opacity),()=>e.x);null!=this.alphaMap&&(i=i.multiply(d(this.alphaMap).sample(t).r)),i=i.multiply(S);const a=m(y("IS_PARTICLE",p(this.color),()=>new u("instanceColor")));let r=y("IS_PARTICLE",p(this.color),()=>a.rgb),o=n(r,i);return null!=this.colorMap&&(o=o.multiply(d(this.colorMap).sample(t))),o=n(o.rgb.multiplyScalar(this.intensity),o.a),{color:o}}build(){const t=super.build();return t.depthTest=!0,t.depthWrite=!1,t.userData.isDecal=!0,t.side=o,t}}t([l(),e("design:type",i)],DecalUnlitShader.prototype,"color",void 0),t([l({range:[0,1]}),e("design:type",Number)],DecalUnlitShader.prototype,"opacity",void 0),t([l({range:[0,10]}),e("design:type",Number)],DecalUnlitShader.prototype,"intensity",void 0),t([l(),e("design:type",a)],DecalUnlitShader.prototype,"colorMap",void 0),t([l(),e("design:type",a)],DecalUnlitShader.prototype,"alphaMap",void 0),t([l(),e("design:type",r)],DecalUnlitShader.prototype,"atlasSize",void 0),t([l({range:[1,64],precision:0}),e("design:type",Number)],DecalUnlitShader.prototype,"atlasTile",void 0);/*
1
+ import{__decorate as t,__metadata as e}from"tslib";import{Color as i,Texture as r,Vector2 as a,BackSide as o}from"three";import{Parameter as l}from"../parameter.js";import{DecalNodeShader as s}from"../decal-shader.js";import{rgb as p,rgba as n,textureSampler2d as d,float as h,AttributeVec3Node as c,varying as m,ifDefApply as y,Vec3ExpressionNode as u}from"three-shader-graph";import{decalAlpha as S,decalUV as g}from"../../shader-nodes/decal.js";import{tileUv as D}from"./decal-standard-shader";export class DecalUnlitShader extends s{constructor(){super(...arguments),this.color=new i("#FFFFFF"),this.opacity=1,this.intensity=1,this.atlasSize=new a(1,1),this.atlasTile=1}output(){let t=D(g,this.atlasSize,this.atlasTile);const e=m(new c("particleData"));let i=y("IS_PARTICLE",h(this.opacity),()=>e.x);null!=this.alphaMap&&(i=i.multiply(d(this.alphaMap).sample(t).r)),i=i.multiply(S);const r=m(y("IS_PARTICLE",p(this.color),()=>new u("instanceColor")));let a=y("IS_PARTICLE",p(this.color),()=>r.rgb),o=n(a,i);return null!=this.colorMap&&(o=o.multiply(d(this.colorMap).sample(t))),o=n(o.rgb.multiplyScalar(this.intensity),o.a),{color:o,emissive:o.rgb}}build(){const t=super.build();return t.depthTest=!0,t.depthWrite=!1,t.userData.isDecal=!0,t.side=o,t}}t([l(),e("design:type",i)],DecalUnlitShader.prototype,"color",void 0),t([l({range:[0,1]}),e("design:type",Number)],DecalUnlitShader.prototype,"opacity",void 0),t([l({range:[0,10]}),e("design:type",Number)],DecalUnlitShader.prototype,"intensity",void 0),t([l(),e("design:type",r)],DecalUnlitShader.prototype,"colorMap",void 0),t([l(),e("design:type",r)],DecalUnlitShader.prototype,"alphaMap",void 0),t([l(),e("design:type",a)],DecalUnlitShader.prototype,"atlasSize",void 0),t([l({range:[1,64],precision:0}),e("design:type",Number)],DecalUnlitShader.prototype,"atlasTile",void 0);/*
2
2
  * Copyright (©) 2025 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,4 +1,4 @@
1
- import{__decorate as t,__metadata as e}from"tslib";import{AddOperation as i,MultiplyOperation as p,MixOperation as o,Color as a,MeshBasicMaterial as r,Texture as n}from"three";import{Shader as s}from"../shader.js";import{Parameter as d}from"../parameter.js";import{removeObjectUndefined as l}from"../../utils/collections.js";export class UnlitShader extends s{constructor(){super(...arguments),this.color=new a("#FFFFFF"),this.opacity=1,this.intensity=1}build(){return new r(l({color:this.color.multiplyScalar(this.intensity),opacity:this.opacity,map:this.map,lightMap:this.lightMap,lightMapIntensity:this.lightMapIntensity,aoMap:this.aoMap,aoMapIntensity:this.aoMapIntensity,specularMap:this.specularMap,alphaMap:this.alphaMap,envMap:this.envMap,combine:this.combine,reflectivity:this.reflectivity,refractionRatio:this.refractionRatio}))}}t([d(),e("design:type",a)],UnlitShader.prototype,"color",void 0),t([d({range:[0,1]}),e("design:type",Number)],UnlitShader.prototype,"opacity",void 0),t([d({range:[0,10]}),e("design:type",Number)],UnlitShader.prototype,"intensity",void 0),t([d(),e("design:type",n)],UnlitShader.prototype,"map",void 0),t([d(),e("design:type",n)],UnlitShader.prototype,"lightMap",void 0),t([d(),e("design:type",Number)],UnlitShader.prototype,"lightMapIntensity",void 0),t([d(),e("design:type",n)],UnlitShader.prototype,"aoMap",void 0),t([d(),e("design:type",Number)],UnlitShader.prototype,"aoMapIntensity",void 0),t([d(),e("design:type",n)],UnlitShader.prototype,"specularMap",void 0),t([d(),e("design:type",n)],UnlitShader.prototype,"alphaMap",void 0),t([d(),e("design:type",n)],UnlitShader.prototype,"envMap",void 0),t([d({options:[{name:"Mix",value:o},{name:"Multiply",value:p},{name:"Add",value:i}]}),e("design:type",Number)],UnlitShader.prototype,"combine",void 0),t([d({range:[0,1]}),e("design:type",Number)],UnlitShader.prototype,"reflectivity",void 0),t([d({range:[0,1]}),e("design:type",Number)],UnlitShader.prototype,"refractionRatio",void 0);/*
1
+ import{__decorate as t,__metadata as e}from"tslib";import{AddOperation as i,MultiplyOperation as o,MixOperation as p,Color as a,MeshBasicMaterial as r,Texture as n}from"three";import{Shader as s}from"../shader.js";import{Parameter as l}from"../parameter.js";import{removeObjectUndefined as d}from"../../utils/collections.js";export class UnlitShader extends s{constructor(){super(...arguments),this.color=new a("#FFFFFF"),this.opacity=1,this.intensity=1}build(){return new r(d({color:this.color.multiplyScalar(this.intensity),emissive:this.color.multiplyScalar(this.intensity),opacity:this.opacity,map:this.map,lightMap:this.lightMap,lightMapIntensity:this.lightMapIntensity,aoMap:this.aoMap,aoMapIntensity:this.aoMapIntensity,specularMap:this.specularMap,alphaMap:this.alphaMap,envMap:this.envMap,combine:this.combine,reflectivity:this.reflectivity,refractionRatio:this.refractionRatio}))}}t([l(),e("design:type",a)],UnlitShader.prototype,"color",void 0),t([l({range:[0,1]}),e("design:type",Number)],UnlitShader.prototype,"opacity",void 0),t([l({range:[0,10]}),e("design:type",Number)],UnlitShader.prototype,"intensity",void 0),t([l(),e("design:type",n)],UnlitShader.prototype,"map",void 0),t([l(),e("design:type",n)],UnlitShader.prototype,"lightMap",void 0),t([l(),e("design:type",Number)],UnlitShader.prototype,"lightMapIntensity",void 0),t([l(),e("design:type",n)],UnlitShader.prototype,"aoMap",void 0),t([l(),e("design:type",Number)],UnlitShader.prototype,"aoMapIntensity",void 0),t([l(),e("design:type",n)],UnlitShader.prototype,"specularMap",void 0),t([l(),e("design:type",n)],UnlitShader.prototype,"alphaMap",void 0),t([l(),e("design:type",n)],UnlitShader.prototype,"envMap",void 0),t([l({options:[{name:"Mix",value:p},{name:"Multiply",value:o},{name:"Add",value:i}]}),e("design:type",Number)],UnlitShader.prototype,"combine",void 0),t([l({range:[0,1]}),e("design:type",Number)],UnlitShader.prototype,"reflectivity",void 0),t([l({range:[0,1]}),e("design:type",Number)],UnlitShader.prototype,"refractionRatio",void 0);/*
2
2
  * Copyright (©) 2025 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,4 +1,4 @@
1
- import{Vec3ExpressionNode as t,attributes as r,dot as e,float as o,ifDefApply as i,normalize as m,pow as n,saturate as p,transformed as a,uniforms as c,varyingAttributes as f,varyingVec3 as l,vec4 as s}from"three-shader-graph";import{fragmentLinearEyeDepth as u,linearEyeDepth as d}from"./depth.js";import{oneMinus as h}from"./math.js";c.modelMatrix.multiplyVec(s(r.position,1));export function fresnelEffect(t=1){const r=i("FLIP_SIDED",a.normal,()=>a.normal.multiplyScalar(-1));return n(h(p(e(a.viewDir,r))),o(t))}const D=o(1).subtract(d.subtract(u).divide(d));export function edgeDepthEffect(t=1){return n(D,o(t))}/*
1
+ import{attributes as t,dot as r,float as e,ifDefApply as o,normalize as i,pow as m,saturate as n,transformed as p,uniforms as a,varying as c,varyingAttributes as f,vec4 as l}from"three-shader-graph";import{fragmentLinearEyeDepth as s,linearEyeDepth as u}from"./depth.js";import{oneMinus as d}from"./math.js";a.modelMatrix.multiplyVec(l(t.position,1));export function fresnelEffect(t=1){const i=o("FLIP_SIDED",p.normal,()=>p.normal.multiplyScalar(-1));return m(d(n(r(p.viewDir,i))),e(t))}const h=e(1).subtract(u.subtract(s).divide(u));export function edgeDepthEffect(t=1){return m(h,e(t))}/*
2
2
  * Copyright (©) 2025 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hology/core",
3
- "version": "0.0.161",
3
+ "version": "0.0.162",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -174,7 +174,7 @@
174
174
  "recast-navigation": "0.39.0",
175
175
  "rxjs": "7.8.1",
176
176
  "three-mesh-bvh": "^0.7.5",
177
- "three-shader-graph": "^0.2.27",
177
+ "three-shader-graph": "^0.2.32",
178
178
  "three-stdlib": "2.34.0",
179
179
  "ts-key-enum": "^2.0.12",
180
180
  "typedi": "^0.10.0"