@hology/core 0.0.272 → 0.0.274
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/effects/sequence/sequence-player.js +1 -1
- package/dist/effects/vfx/gpu-sprite-runtime.js +1 -1
- package/dist/effects/vfx/gpu-vfx-world-service.js +1 -1
- package/dist/effects/vfx/rates.d.ts +2 -0
- package/dist/effects/vfx/rates.js +1 -1
- package/dist/effects/vfx/vfx-actor.d.ts +2 -1
- package/dist/effects/vfx/vfx-actor.js +1 -1
- package/dist/effects/vfx/vfx-asset.d.ts +10 -1
- package/dist/effects/vfx/vfx-backend-partition.d.ts +8 -0
- package/dist/effects/vfx/vfx-backend-partition.js +4 -0
- package/dist/effects/vfx/vfx-materializer.js +1 -1
- package/dist/effects/vfx/vfx-render-preparation.js +1 -1
- package/dist/effects/vfx/vfx-renderers.d.ts +27 -2
- package/dist/effects/vfx/vfx-renderers.js +1 -1
- package/dist/gameplay/actors/builtin/components/character/character-animation.d.ts +2 -0
- package/dist/gameplay/actors/builtin/components/character/character-animation.js +1 -1
- package/dist/gameplay/actors/builtin/components/character/character-movement.d.ts +19 -0
- package/dist/gameplay/actors/builtin/components/character/character-movement.js +1 -1
- package/dist/gameplay/actors/builtin/water-spline-volume-actor.d.ts +10 -0
- package/dist/gameplay/actors/builtin/water-spline-volume-actor.js +1 -1
- package/dist/gameplay/actors/builtin/water-volume-actor.d.ts +3 -1
- package/dist/gameplay/actors/builtin/water-volume-actor.js +1 -1
- package/dist/gameplay/actors/camera/first-person-camera-component.js +1 -1
- package/dist/gameplay/actors/camera/third-person-camera-component.d.ts +7 -0
- package/dist/gameplay/actors/camera/third-person-camera-component.js +1 -1
- package/dist/gameplay/ai/behavior-tree/move.d.ts +5 -0
- package/dist/gameplay/ai/behavior-tree/move.js +1 -1
- package/dist/gameplay/ai/behavior-tree/move.test.d.ts +2 -0
- package/dist/gameplay/ai/behavior-tree/move.test.js +4 -0
- package/dist/gameplay/animation/root-motion.js +1 -1
- package/dist/gameplay/input/input-service.d.ts +9 -1
- package/dist/gameplay/input/input-service.js +1 -1
- package/dist/gameplay/services/physics/physics-system.d.ts +2 -0
- package/dist/gameplay/services/physics/physics-system.js +1 -1
- package/dist/gameplay/services/render.d.ts +4 -1
- package/dist/gameplay/services/render.js +1 -1
- package/dist/gameplay/services/world.d.ts +5 -0
- package/dist/rendering/node-material-webgpu-resolver.js +1 -1
- package/dist/rendering/webgpu-experimental-backend.d.ts +4 -2
- package/dist/rendering/webgpu-experimental-backend.js +1 -1
- package/dist/rendering.d.ts +17 -2
- package/dist/rendering.js +1 -1
- package/dist/scene/asset-resource-loader.d.ts +4 -0
- package/dist/scene/asset-resource-loader.js +1 -1
- package/dist/scene/collision/collision-shape-import.js +1 -1
- package/dist/scene/collision/rapier-shape.js +1 -1
- package/dist/scene/landscape/landscape-geometry.d.ts +24 -0
- package/dist/scene/landscape/landscape-geometry.js +4 -0
- package/dist/scene/landscape/landscape-manager.d.ts +1 -0
- package/dist/scene/landscape/landscape-manager.js +1 -1
- package/dist/scene/materializer.d.ts +7 -1
- package/dist/scene/materializer.js +1 -1
- package/dist/scene/scene-data-service.d.ts +2 -1
- package/dist/scene/scene-data-service.js +1 -1
- package/dist/scene/sky.d.ts +2 -0
- package/dist/scene/sky.js +1 -1
- package/dist/shader/graph/compiler.js +1 -1
- package/dist/shader/graph/registry.js +1 -1
- package/dist/shader/parameter.js +1 -1
- package/dist/shader/sprite-shader.js +1 -1
- package/dist/shader-nodes/depth.d.ts +6 -4
- package/dist/shader-nodes/depth.js +1 -1
- package/dist/shader-nodes/index.d.ts +2 -1
- package/dist/shader-nodes/index.js +1 -1
- package/dist/shader-nodes/surface-reflection.d.ts +9 -0
- package/dist/shader-nodes/surface-reflection.js +4 -0
- package/dist/shader-nodes/water-volume.d.ts +6 -2
- package/dist/shader-nodes/water-volume.js +1 -1
- package/dist/test/asset-resource-loader-texture-array.test.js +1 -1
- package/dist/test/character-movement-solve.test.js +1 -1
- package/dist/test/collision-shape-import.test.js +1 -1
- package/dist/test/first-person-camera-component.test.js +1 -1
- package/dist/test/frame-stats.test.js +1 -1
- package/dist/test/gpu-sprite-compiler.test.js +1 -1
- package/dist/test/input.test.js +1 -1
- package/dist/test/landscape-geometry.test.d.ts +2 -0
- package/dist/test/landscape-geometry.test.js +4 -0
- package/dist/test/material-assignment.test.js +1 -1
- package/dist/test/materializer-dynamic-transform.test.js +1 -1
- package/dist/test/materializer-prefetch.test.js +1 -1
- package/dist/test/net-character-movement.test.js +1 -1
- package/dist/test/node-material-webgpu-resolver.test.js +1 -1
- package/dist/test/parameter-definition.test.js +1 -1
- package/dist/test/physics-hitstop.test.d.ts +2 -0
- package/dist/test/physics-hitstop.test.js +4 -0
- package/dist/test/physics-ray-object.test.js +1 -1
- package/dist/test/post-process-effect.test.js +1 -1
- package/dist/test/rapier-trimesh.test.d.ts +2 -0
- package/dist/test/rapier-trimesh.test.js +4 -0
- package/dist/test/sequence-animation-retiming.test.js +1 -1
- package/dist/test/sequence-vfx.test.js +1 -1
- package/dist/test/surface-reflection.test.d.ts +2 -0
- package/dist/test/surface-reflection.test.js +4 -0
- package/dist/test/vfx-backend-partition.test.d.ts +2 -0
- package/dist/test/vfx-backend-partition.test.js +4 -0
- package/dist/test/vfx-playback-transform.test.js +1 -1
- package/dist/test/vfx-render-preparation.test.js +1 -1
- package/dist/test/water-spline-volume-actor.test.js +1 -1
- package/dist/utils/mesh.d.ts +1 -1
- package/dist/utils/mesh.js +1 -1
- package/dist/utils/three/frame-stats.d.ts +8 -0
- package/dist/utils/three/frame-stats.js +1 -1
- package/package.json +2 -2
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as e,__metadata as t}from"tslib";import{LatticeGeometryCache as a,setLatticeGeometrySourceIdentity as s}from"./lattice-deformation.js";import{particleParameter as r}from"../shader-nodes/particle-parameter.js";export{createLatticeDeformation,latticePoint,isValidLattice,deformLatticeGeometry,LatticeGeometryCache}from"./lattice-deformation.js";import{ConvexPolyhedronCollisionShape as i}from"./collision/collision-shape.js";import{SpriteShader as n}from"../shader/sprite-shader.js";import{Observable as o,Subject as l}from"rxjs";import*as c from"three";import{BoxGeometry as u,BufferGeometry as d,Color as h,Euler as p,Fog as f,FogExp2 as m,Group as g,Material as y,Matrix4 as w,Mesh as S,MeshLambertMaterial as b,MeshPhongMaterial as v,MeshStandardMaterial as M,Matrix3 as A,Object3D as x,PointLight as j,Quaternion as P,Scene as I,Texture as D,Vector2 as C,Vector3 as O,Vector4 as E}from"three";import{attributes as k,batchingUniformFloat as T,batchingUniformVec2 as B,batchingUniformVec3 as V,batchingUniformVec4 as N,bool as z,BooleanExpression as $,BooleanNode as U,colorToNormal as F,float as R,deriveNodeShaderMaterial as W,FloatNode as _,ifDefApply as G,mix as L,NodeShaderMaterial as q,rgb as J,rgba as Y,RgbNode as Q,select as H,standardMaterial as Z,Texture2dLookupNode as X,textureSampler2d as K,textureSampler2dArray as ee,UniformBoolNode as te,UniformFloatNode as ae,UniformSampler2dArraySlice as se,UniformVec2Node as re,UniformVec3Node as ie,UniformVec4Node as ne,varying as oe,varyingAttributes as le,varyingTransformed as ce,vec2 as ue,Vec2Node as de,vec3 as he,Vec3Node as pe,vec4 as fe,Vec4Node as me}from"three-shader-graph";import{Service as ge}from"typedi";import{VfxActor as ye}from"../effects/vfx/vfx-actor.js";import{VisualEffect as we}from"../effects/vfx/vfx-param.js";import{Prefab as Se,PrefabOf as be}from"./objects/prefab.js";import{DataAssetRef as ve}from"./objects/data-asset.js";import{SceneRef as Me}from"./scene-ref.js";import{ModelRef as Ae}from"./model-ref.js";import{BaseActor as xe,getActorOptions as je}from"../gameplay/actors/actor.js";import Pe from"../gameplay/actors/builtin/index.js";import{ActorComponent as Ie}from"../gameplay/actors/component.js";import{PhysicsBodyType as De}from"../gameplay/services/physics/physics-system.js";import{NetMode as Ce}from"../gameplay/net/net-session.js";import{NetRole as Oe}from"../gameplay/net/service/net-actor-role.js";import{ThreeBlendingMode as Ee}from"../effects/vfx/vfx-asset.js";import{withInjectionContext as ke}from"../gameplay/inject.js";import{RenderingView as Te}from"../rendering.js";import{markMaterialUniformValuesNeedUpdate as Be,setMaterialUniformValuesAutoUpdate as Ve}from"../rendering/node-material-webgpu-resolver.js";import{curveSampler as Ne,oneMinus as ze,particleUniforms as $e,Sampler2DNode as Ue}from"../shader-nodes/index.js";import{LambertShader as Fe}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as Re}from"../shader/builtin/landscape-composite-shader.js";import{LandscapeShader as We}from"../shader/builtin/landscape-shader.js";import{StandardShader as _e}from"../shader/builtin/standard-shader.js";import{UnlitShader as Ge}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as Le,getDataAssetDefinitionType as qe,getParameterDefinitionId as Je,getParameterDefinitionType as Ye,isDataAssetDefinitionAbstract as Qe,isParameterDefinitionAbstract as He,isParameterDefinitionAssignableTo as Ze,isParameterDefinitionStructAssignableTo as Xe,shaderParameterUniformName as Ke}from"../shader/parameter.js";import{ArrayMap as et,DefaultMap as tt,groupBy as at}from"../utils/collections.js";import{iterateMaterials as st}from"../utils/materials.js";import{filterChildrenShallow as rt,filterSceneShallow as it,findFirstVisibleMesh as nt,findFirstVisibleObject as ot,traverseAsync as lt}from"../utils/three/traverse.js";import{AssetMeshInstance as ct,AssetResourceLoader as ut}from"./asset-resource-loader.js";import{AssetsProvider as dt}from"./assets-provider.js";import{isCollisionMesh as ht}from"./collision/collision-shape-import.js";import{BoxCollisionShape as pt,PhysicalShapeMesh as ft}from"./collision/collision-shape.js";import{LandscapeManager as mt}from"./landscape/landscape-manager.js";import{initLandscape as gt}from"./landscape/landscape.js";import{SectionGrid as yt,smoothNormalsCrossMeshes as wt}from"./landscape/utils.js";import{createGrassFoliageMaterial as St}from"./materials/grass-foliage.js";import{createGrassMaterial as bt}from"./materials/grass.js";import{getMaterialAttribute as vt}from"./materials/utils/material-painting.js";import{PaintedScatterManager as Mt}from"./scatter/painted-scatter-manager.js";import{SurfaceScatterManager as At}from"./scatter/surface-scatter-manager.js";import{createWaterMaterial as xt}from"./materials/water.js";import{SerializedParamType as jt}from"./model.js";import{applyRuntimeParamTypeInference as Pt,convertConfiguredParamsToRuntimeTypes as It,convertConfiguredParamValueToRuntimeType as Dt,inferRuntimeSerializedParamTypeHint as Ct}from"./custom-param-runtime-types.js";import{ShapeLibrary as Ot,ShapeLibraryKeys as Et}from"./objects/shapes.js";import{ambientLightName as kt,createSky as Tt,defaultSkyMaterial as Bt}from"./sky.js";import{Curve2 as Vt}from"../utils/curve.js";import{DecalUnlitShader as Nt}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as zt}from"../shader/builtin/decal-standard-shader.js";import{ClusterGenerator as $t}from"../rendering/cluster-generator.js";import{ColorLayer as Ut,defaultValueColorLayer as Ft,defaultValueMaskLayer as Rt,MaskLayer as Wt}from"../shader/color-layer.js";import{LayeredShader as _t}from"../shader/builtin/layered-shader.js";import{isColorLayerSerialized as Gt}from"../shader/color-layer.js";import{FogVolume as Lt}from"../rendering/fog/fog-volume-actor.js";import{UnscaledSprite as qt}from"../utils/three/unscaled-sprite.js";import{ToonShader as Jt}from"../shader/builtin/toon-shader.js";import{BatchedMesh2 as Yt}from"./batched-mesh-2.js";import{ParallaxStandardMaterial as Qt}from"../shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Ht}from"../shader-nodes/pom.js";import{traverseVisibleEvery as Zt}from"../utils/three/traverse.js";import{BufferGeometryUtils as Xt,RectAreaLightHelper as Kt}from"three/examples/jsm/Addons.js";import{createSequenceData as ea,isSequenceData as ta,Sequence as aa}from"../effects/sequence/sequence-data.js";import{applyUvTiling as sa}from"./../shader/uv-nodes.js";import{buildShaderGraphMaterial as ra,shaderGraphMaterialSideToThree as ia}from"../shader/graph/index.js";import{hasExecutableEventGraphDocument as na}from"../gameplay/event-graph/model.js";import{depthUniformName as oa}from"../shader-nodes/depth.js";export{Pt as applyRuntimeParamTypeInference,It as convertConfiguredParamsToRuntimeTypes,Dt as convertConfiguredParamValueToRuntimeType,Ct as inferRuntimeSerializedParamTypeHint};const la={},ca=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),ua=/^((?!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 da(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}let da=class{async preparePersistence(e,t,a){this.persistence=e,this.persistenceSceneId=t;const s=async(e,t,a,r)=>{for(const i of e){const e=t+i.id;if(a.length&&this.authoredPersistenceParents.set(e,a[a.length-1]),i.children&&await s(i.children,t,[...a,e],r),"prefab"!==i.type||null==i.assetId||r.includes(i.assetId))continue;const n=await this.assetsService.getAsset(i.assetId);null!=n?.prefab&&(null!=n.prefab.mainActorId&&this.prefabInstanceExposedActorMap.set(e,e+"/"+n.prefab.mainActorId),await s(n.prefab.objects,e+"/",[...a,e],[...r,i.assetId]))}};await s(a,"",[],[]);for(const e of this.prefabInstanceExposedActorMap.keys()){const t=this.persistenceActorPath(e),a=this.authoredPersistenceTargets.get(t);(null==a||e.length<a.length)&&this.authoredPersistenceTargets.set(t,e)}const r=e=>e.filter(e=>!this.isPersistenceRemoved(e.id)).map(e=>null==e.children?e:{...e,children:r(e.children)});return r(a)}persistenceActorPath(e){const t=new Set;for(;this.prefabInstanceExposedActorMap.has(e)&&!t.has(e);)t.add(e),e=this.prefabInstanceExposedActorMap.get(e);return e}isPersistenceRemoved(e){if(null==this.persistence)return!1;for(let t=e;null!=t;t=this.authoredPersistenceParents.get(t))if(this.persistence.isRemoved({sceneId:this.persistenceSceneId,path:t}))return!0;return!1}registerPersistentActors(){const e=[];if(null==this.persistence)return e;for(const[t,a]of this.materializedActors){const s={sceneId:this.persistenceSceneId,path:t},r={sceneId:this.persistenceSceneId,path:this.authoredPersistenceTargets.get(t)??t};this.persistence.register(a,s,r)&&e.push(a)}return e}get prefabEventGraphInstances(){return[...this.materializedPrefabEventGraphs.values()]}resolveSceneActor(e){const t=this.persistenceActorPath(e);if(!this.isPersistenceRemoved(t))return this.materializedActors.get(t)}constructor(e,t,s,r,i,n,o,u,d=[]){this.scene=e,this.dataProvider=t,this.assetsService=s,this.assetManagerService=r,this.renderingView=i,this.shaders=n,this.actorTypes=o,this.actorProvider=u,this.componentTypes=d,this.navigationBakes={},this.navigationRevision=0,this.objectMap=new Map,this.sceneObjectMap=new Map,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.authoredPersistenceTargets=new Map,this.authoredPersistenceParents=new Map,this.idToSceneObject=new Map,this.inEditor=!0,this.netMode=Ce.none,this.updated$=new l,this.removed$=new l,this.prefabEventGraphAdded$=new l,this.prefabEventGraphRemoved$=new l,this.error$=new l,this.materializedPrefabEventGraphs=new Map,this.announcedPrefabEventGraphs=new Set,this.editorActorParamSnapshot=new Map,this.editorAttachedActorComponents=new WeakMap,this.livePrefabInstances=new Map,this.sceneSettingsActive=!1,this.assets=new Map,this.vfxPreloads=new WeakMap,this.latticeGeometries=new a,this._canBeInstancedCache=new Map,this.editorStaticDrawChunks=[],this.editorStaticChunkBySource=new WeakMap,this.editorStaticSnapshotBySource=new WeakMap,this.dirtyEditorStaticDrawChunks=new Set,this.editorStaticEditingObjects=new Set,this.editorMatrixWorldEditingObjects=new Set,this.editorStaticSelectedObjects=new Set,this.editorStaticDrawSetSuspended=!1,this.editorStaticDrawSetRebuildQueued=!1,this.editorStaticFullRebuildQueued=!1,this._editorStaticDrawSetsEnabled=!0,this.editorStaticInitialized=!1,this.editorStaticDisposed=!1,this.editorStaticObjectsToRebuild=new Map,this.editorStaticDrawSetUpdated$=new l,this._originalMaterials=new Map,this.worldEnvironmentRequest=0,this.prefabInstanceChain=[],this.prefabInstanceExposedActorMap=new Map,this.geometryCache=new Map,this.collisionShapeCache=new Map,this.modelImageBitmaps=new WeakMap,this.assetManagerService.materialProvider=async e=>materialFromAsset(this.assets.get(e)??await this.assetsService.getAsset(e),this.renderingView,this.assetsService,this.assetManagerService,this.shaders),this.originalFog=e.fog,null!=this.renderingView.csm&&(this.originalGlobalLight={direction:this.renderingView.csm.lightDirection.clone(),intensity:this.renderingView.csm.lightIntensity,lights:this.renderingView.csm.lights.map(e=>({intensity:e.intensity,color:e.color.clone(),castShadow:e.castShadow,src:e.userData.src,volumetricIntensity:e.userData.volumetricIntensity}))}),t.onCreate(e=>{this.navigationRevision++,this.update(e).finally(()=>this.scheduleEditorStaticDrawSetRebuild()),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),t.onUpdate(e=>{this.navigationRevision++,this.prepareEditorStaticObjectForMutation(e),this.update(e).finally(()=>this.scheduleEditorStaticDrawSetRebuild(e)),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),t.onRemove(e=>{this.navigationRevision++,this.prepareEditorStaticObjectForMutation(e),this.remove(e),this.scheduleEditorStaticDrawSetRebuild(),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),this.createAssetSubscription=s.onCreate.subscribe(e=>{this.navigationRevision++,this.assets.set(e.id,e)}),this.updateSubscription=s.onUpdate.subscribe(async t=>{this.navigationRevision++;const a=this.assets.get(t.id);if(this.assets.set(t.id,t),"material"==t.type){const a=[];e.traverse(e=>{if(e instanceof c.Mesh)if(Array.isArray(e.material))for(let s=0;s<e.material.length;s++)a.push(this.refreshMaterial(e,e.material[s],t,s));else a.push(this.refreshMaterial(e,e.material,t))}),await Promise.all(a)}else if("mesh"==t.type){this.findByAssetId(t.id).forEach(async e=>{this.remove(e.userData.src);const t=await this.materializeAndInitActor(e.userData.src);this.updated$.next({object:t,source:e.userData.src}),this.scheduleEditorStaticDrawSetRebuild()});for(const e of this.assets.values())if("prefab"==e.type){if(!e.prefab.objects.some(e=>Ns(e,e=>e.assetId==t.id,this.assets)))continue;this.findByAssetId(e.id).forEach(e=>{this.remove(e.userData.src),this.materializeAndInitActor(e.userData.src).finally(()=>this.scheduleEditorStaticDrawSetRebuild())})}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 O,!0)}),null!=this.surfaceScatterManager&&(this.surfaceScatterManager.usesSourceAsset(t.id)||this.surfaceScatterManager.usesScatterAsset(t.id))&&this.surfaceScatterManager.queueRefresh(!0),this.paintedScatterManager?.usesScatterAsset(t.id)&&this.paintedScatterManager.queueRefresh(!0)}else if("prefab"===t.type){if("prefab"===a?.type&&await this.applyLivePrefabParameterUpdate(a,t))return;if(!this.inEditor)return void console.warn(`Prefab ${t.name??t.id} changed in a way that cannot be applied to its running instances. Respawn or restart to use the saved data.`);this.findByAssetId(t.id).forEach(e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t).finally(()=>this.scheduleEditorStaticDrawSetRebuild())}),(this.surfaceScatterManager?.usesPrefabAsset(t.id)||this.sceneReferencesPrefabAsset(t.id)&&await this.prefabAssetContainsSurfaceScatter(t))&&await this.refreshSurfaceScatterPresence(!0),(this.paintedScatterManager?.usesPrefabAsset(t.id)||this.sceneReferencesPrefabAsset(t.id)&&await this.prefabAssetContainsPaintedScatter(t))&&await this.refreshPaintedScatterPresence(!0)}else if("vfx"===t.type)for(const e of this.dataProvider.getObjects())await ka(e,async e=>{"vfx"===e.type&&e.assetId===t.id&&(this.remove(e),await this.materializeAndInitActor(e))});else if("texture"===t.type)await this.refreshMaterialTextures(t);else if("shaderGraph"===t.type){this.scene.traverse(e=>{if(e instanceof S)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)});for(const e of this.dataProvider.getObjects())await ka(e,async e=>{if("vfx"===e.type&&null!=e.assetId){const a=this.assets.get(e.assetId);null!=a&&this.vfxAssetUsesShaderGraph(a,t.id)&&(this.remove(e),await this.materializeAndInitActor(e))}})}this.scheduleEditorStaticDrawSetRebuild()})}async refreshMaterialTextures(e){if("texture"!==e.type)return void console.error("Can not refresh material textures. Asset is not a texture",e);const t=new Set,a=new Set,s=[],r=s=>{t.has(s)||(t.add(s),this.materialUsesTexture(s,e.id)&&a.add(s))};if(this.scene.traverse(t=>{t instanceof c.SpotLight&&"spot"===t.userData?.src?.light?.type&&t.userData.src.light.spot.mapTextureId===e.id&&s.push(t),t instanceof S&&(Array.isArray(t.material)?t.material.forEach(r):r(t.material))}),0===a.size&&0===s.length)return;const i=await this.assetManagerService.getTexture(e);if(null!=i){for(const t of a)this.replaceMaterialTextureReferences(t,e.id,i);for(const e of s)e.map=i}else console.error("Can not refresh material textures. Texture not found",e)}materialUsesTexture(e,t){if(e instanceof c.ShaderMaterial){for(const a of Object.values(e.uniforms))if(a.value instanceof c.Texture&&a.value.userData.assetId===t)return!0}else for(const a of Object.values(e))if(a instanceof c.Texture&&a.userData.assetId===t)return!0;return!1}replaceMaterialTextureReferences(e,t,a){let s=!1;if(e instanceof c.ShaderMaterial)for(const[r,i]of Object.entries(e.uniforms))i.value instanceof c.Texture&&i.value.userData.assetId===t&&(e.uniforms[r].value=a,s=!0);else for(const[r,i]of Object.entries(e))i instanceof c.Texture&&i.userData.assetId===t&&(e[r]=a,s=!0);s&&(e.needsUpdate=!0,Be(e))}async getAsset(e){let t=this.assets.get(e);return null==t&&(t=await this.assetsService.getAsset(e),null!=t&&this.assets.set(e,t)),t}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&&("shaderGraph"===a.type&&"asset"===e.material?.shaderGraph?.source&&e.material.shaderGraph.assetId===a.id&&(t=!0),!t&&null!=e.material?.shaderParams))for(const s of Object.values(e.material.shaderParams)){if(s.type===jt.Material&&s.value===a.id){t=!0;break}if(s.type===jt.Array&&"element"in s&&s.element===jt.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,o=t.userData.receiveDecals!==n.receiveDecals;i.userData=t.userData,i.userData.hasBloom=n.hasBloom,i.userData.reflective=n.reflective,i.userData.outlineParameters=n.outlineParameters,i.userData.receiveDecals=n.receiveDecals,o&&(t.needsUpdate=!0),null!=s?es(e.material[s],i)||(e.material[s]=i):es(e.material,i)||(e.material=i,e===this.sky&&this.applySkySettings(e.material))}vfxAssetUsesShaderGraph(e,t){return null!=e.vfx&&e.vfx.emitters.some(e=>this.emitterUsesShaderGraph(e,t))}emitterUsesShaderGraph(e,t){const a=e.output;return"shaderGraph"===a.materialSource&&"asset"===a.shaderGraph?.source&&a.shaderGraph.assetId===t||!!e.children&&e.children.some(e=>this.emitterUsesShaderGraph(e,t))}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="webgpu"===this.renderingView?.requestedBackend,t=e?this.renderingView.initializeBackend().catch(e=>{console.warn("Could not prepare WebGPU texture uploads before compilation",e)}):void 0,a=new Map,s=new Map,r=[];for(const e of this.collectMaterialAssignments(this.dataProvider.getObjects())){const t=this.assets.get(e.materialId);if(null!=t?.material)for(const e of Object.values(t.material.shaderParams??{}))if(e.type===jt.Texture&&"string"==typeof e.value){const t=this.assets.get(e.value);if(null==t)continue;const r=t.texture?.textureArrayFileKey;null==r?a.set(t.id,t):s.set(r,t)}}const i=[...Array.from(a.values(),e=>({asset:e,array:!1})),...Array.from(s.values(),e=>({asset:e,array:!0}))];let n=0;if(await Promise.all(Array.from({length:Math.min(16,i.length)},async()=>{for(;n<i.length;){const{asset:a,array:s}=i[n++],o=s?(await this.assetManagerService.getTextureArray(a))?.texture:await this.assetManagerService.getTexture(a);null!=o&&(e&&(await t,this.renderingView.initTexture(o)),r.push(o))}})),0!==r.length&&this.renderingView&&"webgpu"!==this.renderingView.requestedBackend){console.log(`Initializing ${r.length} textures`),console.time("Init textures");for(const e of r)this.renderingView.initTexture(e);console.timeEnd("Init textures")}}async prefetchAssets(){this.texturePrefetch=this.initTextures().catch(e=>{console.warn("Could not prefetch scene textures",e)});const e=this.collectAssetMeshIds(this.dataProvider.getObjects());await Promise.all(Array.from(e).map(async e=>{const t=this.assets.get(e);if("mesh"===t?.type)return this.assetManagerService.getMesh(t,{mergeGeomtries:!0,clone:!1})}))}collectAssetMeshIds(e,t=[],a=new Set){for(const s of e??[])this.collectObjectAssetMeshIds(s,t,a);return a}collectObjectAssetMeshIds(e,t,a){if(this.shouldBeMaterialized(e)&&("asset_mesh"===e.type&&null!=e.assetId&&a.add(e.assetId),null!=e.children&&this.collectAssetMeshIds(e.children,t,a),"prefab"===e.type&&null!=e.assetId&&!t.includes(e.assetId))){const s=this.assets.get(e.assetId);null!=s?.prefab?.objects&&this.collectAssetMeshIds(s.prefab.objects,[...t,e.assetId],a)}}collectMaterialAssignments(e,t=[],a=[]){for(const s of e??[])this.collectObjectMaterialAssignments(s,t,a);return a}collectObjectMaterialAssignments(e,t,a){if(this.shouldBeMaterialized(e)&&("shape_mesh"!==e.type&&"asset_mesh"!==e.type||null==e.materialAssignments||a.push(...e.materialAssignments),null!=e.children&&this.collectMaterialAssignments(e.children,t,a),"prefab"===e.type&&null!=e.assetId&&!t.includes(e.assetId))){const s=this.assets.get(e.assetId);null!=s?.prefab?.objects&&this.collectMaterialAssignments(s.prefab.objects,[...t,e.assetId],a)}}async init(){await this.preInit(),pa.clear(),fa.clear(),await this.prefetchAssets(),await Promise.all(this.dataProvider.getObjects().map(e=>this.materialize(e))),await this.initActorsPostInit(),this.generateOcclusionClusters(),this.announcePrefabEventGraphs(),await this.refreshPaintedScatterPresence(!0),await this.refreshSurfaceScatterPresence(!0),this.editorStaticInitialized=!0,this.rebuildEditorStaticDrawSet(),"webgpu"===this.renderingView.requestedBackend&&await this.texturePrefetch}get editorStaticDrawSetsEnabled(){return this._editorStaticDrawSetsEnabled}set editorStaticDrawSetsEnabled(e){this._editorStaticDrawSetsEnabled!==e&&(this._editorStaticDrawSetsEnabled=e,this.editorStaticInitialized&&!this.editorStaticDisposed&&(e?this.rebuildEditorStaticDrawSet():(this.editorStaticDrawSetSuspended=!1,this.editorStaticEditingObjects.clear(),this.editorStaticFullRebuildQueued=!1,this.editorStaticObjectsToRebuild.clear(),this.disposeEditorStaticDrawSet(),this.editorStaticDrawSetUpdated$.next())))}beginEditorStaticSceneEdit(e=[]){for(const e of this.editorMatrixWorldEditingObjects)xa(e,!1);this.editorMatrixWorldEditingObjects.clear();for(const t of e)this.editorMatrixWorldEditingObjects.add(t),xa(t,!0);if(!this._editorStaticDrawSetsEnabled||!this.inEditor||this.editorStaticDrawSetSuspended)return;this.editorStaticDrawSetSuspended=!0,this.editorStaticEditingObjects.clear();const t=new Set;for(const a of e){this.editorStaticEditingObjects.add(a);const e=this.editorStaticChunkBySource.get(a);null!=e&&t.add(e)}for(const e of t)this.disposeEditorStaticDrawChunk(e),this.dirtyEditorStaticDrawChunks.add(e),this.buildEditorStaticDrawChunk(e);this.editorStaticDrawSetUpdated$.next()}setEditorStaticSelectedObjects(e){if(!this.inEditor)return;const t=new Set(e),a=new Set;for(const e of this.editorStaticSelectedObjects)if(!t.has(e)){const t=this.editorStaticChunkBySource.get(e);null!=t&&a.add(t)}for(const e of t)if(!this.editorStaticSelectedObjects.has(e)){const t=this.editorStaticChunkBySource.get(e);null!=t&&a.add(t)}this.editorStaticSelectedObjects.clear();for(const e of t)this.editorStaticSelectedObjects.add(e);if(!this.editorStaticDrawSetSuspended&&"webgpu"===this.renderingView?.requestedBackend){for(const e of a)this.disposeEditorStaticDrawChunk(e),this.buildEditorStaticDrawChunk(e);a.size>0&&this.editorStaticDrawSetUpdated$.next()}}endEditorStaticSceneEdit(){for(const e of this.editorMatrixWorldEditingObjects)xa(e,!1);if(this.editorMatrixWorldEditingObjects.clear(),this.editorStaticDrawSetSuspended){this.editorStaticDrawSetSuspended=!1,this.editorStaticEditingObjects.clear();for(const e of this.dirtyEditorStaticDrawChunks)this.disposeEditorStaticDrawChunk(e),this.buildEditorStaticDrawChunk(e);this.dirtyEditorStaticDrawChunks.clear(),this.editorStaticDrawSetUpdated$.next()}}getEditorRenderObject(e){const t=e.userData?.src,a=null!=t?.id?this.sceneObjectMap.get(t.id)??e:e;if(this.editorStaticEditingObjects.has(a)||this.editorStaticSelectedObjects.has(a))return a;const s=this.editorStaticSnapshotBySource.get(a);return!0===s?.chunk.active?s.object:e}scheduleEditorStaticDrawSetRebuild(e){!this.editorStaticDisposed&&this._editorStaticDrawSetsEnabled&&this.inEditor&&!this.editorStaticDrawSetSuspended&&"webgpu"===this.renderingView?.requestedBackend&&(null==e?(this.editorStaticFullRebuildQueued=!0,this.editorStaticObjectsToRebuild.clear()):this.editorStaticFullRebuildQueued||this.editorStaticObjectsToRebuild.set(e.id,e),this.editorStaticDrawSetRebuildQueued||(this.editorStaticDrawSetRebuildQueued=!0,queueMicrotask(()=>{if(this.editorStaticDrawSetRebuildQueued=!1,this.editorStaticDisposed||this.editorStaticDrawSetSuspended)return;if(this.editorStaticFullRebuildQueued)return this.editorStaticFullRebuildQueued=!1,void this.rebuildEditorStaticDrawSet();const e=new Set;for(const t of this.editorStaticObjectsToRebuild.values()){const a=this.sceneObjectMap.get(t.id),s=null==a?null:this.editorStaticChunkBySource.get(a);if(null==s){this.editorStaticFullRebuildQueued=!0;break}e.add(s)}if(this.editorStaticObjectsToRebuild.clear(),this.editorStaticFullRebuildQueued)return this.editorStaticFullRebuildQueued=!1,void this.rebuildEditorStaticDrawSet();for(const t of e)this.disposeEditorStaticDrawChunk(t),this.buildEditorStaticDrawChunk(t);this.editorStaticDrawSetUpdated$.next()})))}prepareEditorStaticObjectForMutation(e){const t=this.sceneObjectMap.get(e.id);if(null==t)return;const a=this.editorStaticChunkBySource.get(t);!0===a?.active&&this.disposeEditorStaticDrawChunk(a)}rebuildEditorStaticDrawSet(){if(this.disposeEditorStaticDrawSet(),!this._editorStaticDrawSetsEnabled||!this.inEditor||this.editorStaticDrawSetSuspended||"webgpu"!==this.renderingView?.requestedBackend)return;const e=[];for(const t of this.idToSceneObject.values()){if("asset_mesh"!==t.type||null!=t.latticeDeformation||!0===t.hidden||t.physics?.type===De.dynamic)continue;const a=this.sceneObjectMap.get(t.id);null!=a&&this.canUseEditorStaticDrawSet(a)&&e.push(a)}const t=new g;t.name="Hology WebGPU editor static authored objects",t.visible=!1,t.userData.hologyEditorStaticAuthoredRoot=!0,this.scene.add(t),this.editorStaticAuthoredRoot=t,e.sort((e,t)=>{const a=e.userData?.src,s=t.userData?.src,r="asset_mesh"===a?.type?`${a.assetId}:${JSON.stringify(a.materialAssignments??[])}`:"",i="asset_mesh"===s?.type?`${s.assetId}:${JSON.stringify(s.materialAssignments??[])}`:"";return r.localeCompare(i)});for(let t=0;t<e.length;t+=32){const a={sources:e.slice(t,t+32),sourceVisibility:new Map,sourceUpdateMatrixWorld:new Map,sourceParents:new Map,active:!1};this.editorStaticDrawChunks.push(a);for(const e of a.sources)this.editorStaticChunkBySource.set(e,a);this.buildEditorStaticDrawChunk(a)}this.editorStaticDrawSetUpdated$.next()}buildEditorStaticDrawChunk(e){const t=new g;t.name="Hology WebGPU editor static asset mesh chunk",t.userData.hologyEditorStaticSnapshotRoot=!0,e.sourceVisibility.clear(),e.sourceUpdateMatrixWorld.clear(),e.sourceParents.clear();for(const a of e.sources){if(this.editorStaticEditingObjects.has(a)||this.editorStaticSelectedObjects.has(a)){this.editorStaticSnapshotBySource.delete(a);continue}a.updateWorldMatrix(!0,!0);const s=new g;s.name=a.name;const r=a.userData?.src;for(const e of a.children){const t=e.clone(!0),a=[];t.traverse(e=>{const t=e.userData?.src;(ht(e)||null!=t?.id&&null!=r?.id&&t.id!==r.id)&&a.push(e)});for(const e of a)e.removeFromParent();a.includes(t)||s.add(t)}s.matrix.copy(a.matrixWorld),s.matrix.decompose(s.position,s.quaternion,s.scale),s.matrixAutoUpdate=!1,t.add(s),this.editorStaticSnapshotBySource.set(a,{object:s,chunk:e}),e.sourceVisibility.set(a,a.visible),e.sourceParents.set(a,a.parent),a.visible=!1,this.editorStaticAuthoredRoot?.attach(a),e.sourceUpdateMatrixWorld.set(a,a.updateMatrixWorld),a.updateMatrixWorld=Ma}0!==t.children.length&&(va(t),this.scene.add(t),e.root=t,e.disposer=this.renderingView.registerExperimentalStaticDrawSet(t,`hology-editor-static-asset-meshes-${this.editorStaticDrawChunks.indexOf(e)}`),e.active=!0)}canUseEditorStaticDrawSet(e){let t=!1,a=!0;return e.traverseVisible(e=>{e instanceof S&&!ht(e)&&(t=!0,null!=e.geometry?.index&&null==e.customDepthMaterial&&Pa(e.material)||(a=!1))}),t&&a}disposeEditorStaticDrawSet(){for(const e of this.editorStaticDrawChunks)this.disposeEditorStaticDrawChunk(e);this.editorStaticDrawChunks.length=0,this.dirtyEditorStaticDrawChunks.clear(),this.editorStaticChunkBySource=new WeakMap,this.editorStaticSnapshotBySource=new WeakMap,this.editorStaticAuthoredRoot?.removeFromParent(),this.editorStaticAuthoredRoot=void 0}disposeEditorStaticDrawChunk(e){e.disposer?.(),e.disposer=void 0,e.root?.removeFromParent(),e.root=void 0,e.active=!1;for(const[t,a]of e.sourceParents){const e=t.userData?.src,s=null==e?.id||this.sceneObjectMap.get(e.id)===t;(null!=a&&null==t.parent&&s||null!=a&&t.parent===this.editorStaticAuthoredRoot&&s)&&a.attach(t)}e.sourceParents.clear();for(const[t,a]of e.sourceVisibility)t.visible=a;e.sourceVisibility.clear();for(const[t,a]of e.sourceUpdateMatrixWorld)t.updateMatrixWorld=a;e.sourceUpdateMatrixWorld.clear()}async preloadVisualEffects(e){const t=[],a=new Set;for(const s of e){const e=s.asset;if(a.has(e))continue;a.add(e);let r=this.inEditor?void 0:this.vfxPreloads.get(e);null==r&&(r=this.preloadVisualEffect(s).catch(t=>{throw this.vfxPreloads.get(e)===r&&this.vfxPreloads.delete(e),t}),this.inEditor||this.vfxPreloads.set(e,r)),t.push(r)}await Promise.all(t)}async preloadVisualEffect(e){const t=new Set;!function(e,t){const a=e=>{const s=e.output;switch(s.type){case"sprite":case"stretchedSprite":t.add(s.texture);break;case"trail":null!=s.texture&&t.add(s.texture);break;case"decal":t.add(s.colorMap),t.add(s.alphaMap)}e.children?.forEach(a)};e.vfx.emitters.forEach(a)}(e.asset,t),await Promise.all([this.initVfxTextures(t),(async()=>{const t=await e.create(new I);try{await t.prepareRendering()}finally{t.onEndPlay(),t.disposed.next(!0),t.object.removeFromParent()}})()])}async initVfxTextures(e){const t=await Promise.all(Array.from(e,async e=>{const t=await this.assetsService.getAsset(e);return null==t?null:this.assetManagerService.getTexture(t)}));for(const e of t)null!=e&&this.renderingView.initTexture(e)}async initVfx(){await this.preloadVisualEffects(this.actorInstances.flatMap(e=>Cs(e)))}async initActorsPostInit(e=Array.from(this.materializedActors.entries())){const t=e.map(async([e,t])=>{if(t.__isInitialised)return;const a=t.object.userData.src??t.object.userData._src;if("vfx"===a.type)return Promise.resolve();const s="prefab"===a.type?await this.assetsService.getAsset(a.assetId):null,r=e.split("/"),i=r.slice(0,-1),n=i.join("/"),o=(r[r.length-1],new Map);for(const[e,t]of this.materializedActors)if(o.set(e,t),0===n.length)e.includes("/")||o.set(e,t);else if(e.startsWith(n+"/")){const a=e.slice(n.length+1);a.includes("/")||o.set(a,t)}const l={...s?.actor?.params??{},...a.actor?.params??{}},c=[...a.actor?.innerParams??[]];for(let t=i.length-1;t>=0;t--){const a=i.slice(0,t+1).join("/"),s=this.idToSceneObject.get(a);if("prefab"===s?.type&&null!=s.prefab){const i=await this.assetsService.getAsset(s.assetId);if(null!=i){let n=!1,o=a+"/"+i.prefab?.mainActorId;for(;null!=o;){if(o===e){n=!0;break}o=this.prefabInstanceExposedActorMap.get(o)}if(n&&null!=s.prefab.params&&Object.assign(l,Fa(s.prefab.params)),null!=s.prefab.innerParams){const e=r.slice(t+1);for(const t of s.prefab.innerParams){const a=Fa(t.params);0!==Object.keys(a).length&&(n?c.push({path:Ra(t.path,e)?t.path.slice(e.length):t.path,params:a}):Ra(t.path,e)&&c.push({path:t.path.slice(e.length),params:a}))}}}}}this.rememberLivePrefabActorSettings(e,{...a.actor,params:l,innerParams:c});for(const e of c)await this.applyActorComponentParams(t,e.path.slice(),e.params,o);await this.attachEditorComponents(t,a,o);const u=await prepareClassParameters(l,t.constructor,this.assetsService,this.assetManagerService,o,this.renderingView,this.shaders,this.actorProvider,e=>{const t=n.length>0?n+"/"+e:e;return this.prefabInstanceExposedActorMap.has(t)?this.persistenceActorPath(t):null},t);Object.assign(t,u);try{return await this.actorProvider.initActor(t)}catch(e){console.error(`Failed to initiate actor (name="${a.name}", id=${a.id})`,e)}});return Promise.all(t)}async attachEditorComponents(e,t,a){const s=t.actor?.components??[],r=new Array(s.length).fill(null);this.editorAttachedActorComponents.set(e,r);for(const[i,n]of s.entries()){const s=this.componentTypes.find(e=>e.name===n.type);if(null==s){console.warn(`Component type '${n.type}' not found for actor ${t.id}`);continue}const o=e.attach(s.type);if(r[i]=o,null!=n.params){const e=await prepareClassParameters(n.params,null,this.assetsService,this.assetManagerService,a,this.renderingView,this.shaders,this.actorProvider,e=>this.prefabInstanceExposedActorMap.get(e)??null,o);Object.assign(o,e)}for(const e of n.innerParams??[])await this.applyActorComponentParams(o,e.path.slice(),e.params,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,e=>this.prefabInstanceExposedActorMap.get(e)??null,e);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)}previewLatticeDeformation(e,t){this.latticeGeometries.apply(e,t,JSON.stringify(e.userData.src?.vertexMaterials??[]))}canObjectBeInstanced(e){return null==e.latticeDeformation&&e.physics?.type!==De.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=>{!ht(e)&&e.isMesh&&s.push(e)});const r=1==s.length&&0==s[0].children.length,i=!ua,n=s.every(e=>!Array.isArray(e.material)||1===e.material.length),o=s.some(e=>e instanceof S&&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)}),await this.preloadAssets()}async preloadAssets(){const e=await this.assetsService.getAssets();for(const t of e)this.assets.set(t.id,t)}shouldBeMaterialized(e){if(!1===e.enabled)return!1;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(){this.sceneSettingsActive=!0,await this.preInit(),await this.prefetchAssets(),this.experimentalStaticDrawSetDisposer?.(),this.experimentalStaticDrawSetDisposer=void 0,pa.clear(),fa.clear();const e=[],t=new et,a=new et,s=new et;let r=0,i=0,n=0;const o=new Map,l=new tt(()=>new Map),u="webgpu"===this.renderingView?.requestedBackend?new g:null,d=null!=u?new g:null;null!=u&&(u.name="Hology WebGPU static scene objects",d.name="Hology WebGPU unsorted late static scene objects");const f=(e,t)=>{if(null!=u&&function(e){return e.visible&&null!=e.geometry.index&&null==e.customDepthMaterial&&Pa(e.material,!0)}(t)){((Array.isArray(t.material)?t.material:[t.material]).some(e=>e.transparent||Ia(e))?d:u).add(e)}else this.scene.add(e)};for(const c of this.dataProvider.getObjects())await ka(c,async(c,u,d)=>{if(!this.shouldBeMaterialized(c))return;const p="asset_mesh"==c.type&&this.canObjectBeInstanced(c)&&await this.canAssetBeInstanced(c),f="shape_mesh"===c.type&&"landscape"!==c.shape&&c.physics?.type!==De.dynamic;if(p||f){if(u&&u.children?.length>0){const e=u.children.findIndex(e=>e.id===c.id);e>=0&&u.children.splice(e,1)}if(f){let e=c.shape+JSON.stringify(c.shapeParams??{})+c.castShadow+c.receiveShadow;const t=c.materialAssignments?.at(0)?.materialId,a=null!=t?this.assets.get(t):null;let r=null;if(!1&&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===jt.Color&&null!=e.value&&(r=new h(e.value))}}e+=a.material.outlines,null!=a.material.outlineParams&&(e+=JSON.stringify(a.material.outlineParams)),e+=a.material.reflective,e+=a.material.bloom,e+=a.material.side,e+=a.material.side,e+=a.material.transparent,e+=a.material.alphaTest}else e+=t;s.push(e,{object:{...c,parentTransform:d},color:r}),n++}else{const e=this.assets.get(c.assetId);null==e&&console.log("Can't find asset with id "+c.assetId);let s=o.get(c.assetId);if(null==s){const e=await this.createFromAsset(c,{assignMaterials:!1});if(null==e)return;if(s=o.get(c.assetId),null==s){s={useBatchedMesh:null!=nt(e)&&Zt(e,e=>!(e instanceof S)||this.testCanBatch(e.material,e.geometry)),assetMesh:e},o.set(c.assetId,s)}}const n=Ga(c.materialAssignments,e.materialAssignments);if(s.useBatchedMesh)await lt(s.assetMesh,async t=>{if(!(t instanceof S))return;const s=Array.isArray(t.material)?t.material[0]:t.material,i=await this.resolveMaterialForAssignments(s,n,e);if(null!=i){Ve(i,!1),l.get(c.id).set(t.uuid,i);let s=as(t,i);if(s+=us(i),"webgpu"===this.renderingView?.requestedBackend){const t=c.castShadow??e.castShadow??!1,a=c.receiveShadow??e.receiveShadow??!1;s+=`|detailCulling:${JSON.stringify(c.detailCulling??null)}`,s+=`|castShadow:${t?1:0}|receiveShadow:${a?1:0}`}a.push(s,{...c,parentTransform:d,meshUUID:t.uuid}),r++}else console.warn("Can not materialize mesh because missing material",c)});else{const e=c.assetId+JSON.stringify(c.materialAssignments??[]);t.push(e,{...c,parentTransform:d}),i++}}}else null==u&&e.push({...c,parentTransform:d})});console.log(`Scene init stats: \n Batched Assets: ${a.size} groups containing in total ${r} objects.\n Instanced Assets: ${t.size} groups containing in total ${i} objects.\n Shapes: ${s.size} batch groups containing in total ${n} objects. \n ${e.length} objects can not be batched. \n `),console.time("materialize batches");for(const[e,t]of a.entries()){if(0==t.length)continue;let e;o.get(t[0].assetId).assetMesh;e=this.createBatchedMesh(t,l,o);const a=this.assets.get(t[0].assetId);"webgl"===this.renderingView?.activeBackend?(e instanceof Yt&&e.perInstanceCastShadow||(e.castShadow=Ys(t,a?.castShadow??!1)),e.receiveShadow=Qs(t,a?.receiveShadow??!1)):(e.castShadow=t[0].castShadow??a?.castShadow??!1,e.receiveShadow=t[0].receiveShadow??a?.receiveShadow??!1);const s=new ct;s.add(e),s.userData.src=t[0],s.userData.detailCulling=t[0].detailCulling,s.castShadow=!1,s.receiveShadow=!1,f(s,e)}for(const e of t.values()){if(0==e.length)continue;let t;const a=o.get(e[0].assetId).assetMesh;t=await this.createInstancedMesh(e,a);const s=this.assets.get(e[0].assetId);t.castShadow=Ys(e,s?.castShadow??!1),t.receiveShadow=Qs(e,s?.receiveShadow??!1);const r=new ct;r.add(t),r.userData.src=e[0],r.userData.detailCulling=e[0].detailCulling,a instanceof ct&&(r.collisionShapes=a.collisionShapes),this.prepareCollisionShapesForInstanced(r),r.castShadow=!1,r.receiveShadow=!1,f(r,t)}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=ot(a,e=>!ht(e)&&null!=e.geometry),r=Za(s.material);null!=e[0].color&&null!=r.color&&(r.color=new h(16777215));const i=null==s.geometry.index?Xt.mergeVertices(s.geometry):s.geometry;let n,o;!(ua||r instanceof q)?(n=new c.BatchedMesh(e.length,i.getAttribute("position").count,i.index.count,r),n.perObjectFrustumCulled=!0,o=n.addGeometry(i)):n=new c.InstancedMesh(i,r,e.length),n.castShadow=a.castShadow??!0,n.receiveShadow=s.receiveShadow??!1;for(let t=0;t<e.length;t++){const a=e[t],s=(new c.Matrix4).compose((new O).fromArray(a.object.position),(new P).setFromEuler((new p).fromArray(a.object.rotation)),(new O).fromArray(a.object.scale)),r=(new w).copy(a.object.parentTransform).multiply(s);let i;i=n instanceof c.BatchedMesh?n.addInstance(o):t,n.setMatrixAt(i,r),a.color}for(let t=0;t<e.length;t++){const s=e[t],r=new ct;r.userData.src=e[0],r.userData.detailCulling=e[0].object.detailCulling,a instanceof ft&&(r.collisionShapes=[a.collisionShape]),r.castShadow=!0,r.receiveShadow=!0,f(r,n),r.add(n),null==n.userData.hasCollision&&(n.userData.hasCollision=[]),n.userData.hasCollision[t]=!1!==s.object.collisionDetection}}if(null!=u&&u.children.length>0&&(va(u),this.scene.add(u),this.experimentalStaticDrawSetDisposer=this.renderingView.registerExperimentalStaticDrawSet(u,"hology-materialized-static-scene")),null!=d&&d.children.length>0){va(d),this.scene.add(d);const e=this.experimentalStaticDrawSetDisposer,t=this.renderingView.registerExperimentalStaticDrawSet(d,"hology-materialized-unsorted-late-static-scene",!0);this.experimentalStaticDrawSetDisposer=()=>{e?.(),t()}}await Promise.all(e.map(e=>this.materialize(e))),await this.initActorsPostInit(),this.announcePrefabEventGraphs(),await this.initVfx(),this.generateOcclusionClusters(),await this.refreshPaintedScatterPresence(!0),await this.refreshSurfaceScatterPresence(!0),"webgpu"===this.renderingView.requestedBackend&&await this.texturePrefetch}generateOcclusionClusters(){const e=new $t;e.initScene(this.scene),e.clusters.forEach(e=>{this.renderingView.addCluster(e)})}prepareCollisionShapesForInstanced(e){e instanceof ct&&e.collisionShapes.forEach(e=>{e instanceof i&&e.mesh instanceof S&&(e.mesh=e.mesh.geometry)})}setScene(e){this.scene=e}testCanBatch(e,t){return!ua&&(!Array.isArray(e)||1==e.length)&&this.testCanBatchMaterial(e)}testCanBatchMaterial(e){return null!=(Array.isArray(e)?e[0]:e)}createBatchedMesh(e,t,a){const s=new et;for(const t of e)null!=t.meshUUID?s.push(t.meshUUID??t.assetId,t):console.warn("Missing mesh uuid for batching");let r=0,i=0,n=0;const o=new Map;for(const[e,t]of s.entries()){const s=t[0].assetId,l=a.get(s);if(null==l){console.warn("Missing batching info for asset id "+s);continue}const c=ot(l.assetMesh,t=>t instanceof S&&t.uuid===e);if(null==c){console.warn("Missing mesh in batched asset");continue}o.set(e,c);const u=c.geometry.getAttribute("position");null==u&&console.warn("Missing position attribute for batched mesh"),r+=c.geometry.index.count*t.length,i+=u.count*t.length,n+=t.length}const l=["color","map","roughness","roughnessMap","metalness","metalnessMap","opacity","alphaMap","aoMap","aoMapIntensity","normalMap","normalScale","emissive","emissiveIntensity","emissiveMap"],u=new Map,d=new Map,p=[];let f=new c.MeshStandardMaterial({color:"white"});const m=t.get(e[0].id).get(e[0].meshUUID);if(null==m)throw"missing source material";if(m instanceof M&&!(m instanceof c.MeshPhysicalMaterial)){const a=new Set,s=new Map;for(const r of e){const e=t.get(r.id).get(r.meshUUID);if(null==e)throw"missing mat";for(const t of l){let r=e[t];r instanceof c.CompressedArrayTexture&&null!=r.userData.index&&(r=r.userData.index);const i=s.get(t);void 0===i||Ds(r,i)?s.set(t,r):a.add(t)}}for(const e of a){let t;const a=m[e];let s=e;if("number"==typeof a){let a=p.find(e=>e.params.length<4);if(null==a){const t="vp"+p.length;a={name:t,params:[e],node:N(t)},p.push(a)}else a.params.push(e);s=a.name,t=Ps(a.node,a.params.length-1)}else if(a instanceof E)t=N(s);else if(a instanceof O||a instanceof h)t=V(s);else if(a instanceof C)t=B(s);else if(a instanceof c.CompressedArrayTexture)s=e+"_i",t=T(s);else if(a instanceof D)continue;u.set(e,t),d.set(e,s)}let r=le.uv;m instanceof Qt&&null!=m.heightMap&&(r=Ht(r,K(m.heightMap),R(m.heightScale)));let i=Ms(u.get("opacity"),_)??R(m.opacity??1);if(null!=m.alphaMap){let e;if(m.alphaMap instanceof c.CompressedArrayTexture){const t=ee(m.alphaMap),a=Ms(u.get("alphaMap"),_)??R(m.alphaMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=K(m.alphaMap).sample(r);i=i.multiply(e.r)}let n=Y(Ms(u.get("color"),pe)??m.color,i);if(null!=m.map){let e;if(m.map instanceof c.CompressedArrayTexture){const t=ee(m.map),a=Ms(u.get("map"),_)??R(m.map.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=K(m.map).sample(sa(r,m.map));n=n.multiply(e),i=i.multiply(e.a)}m.vertexColors&&(n=n.multiply(fe(oe(k.color.rgb),1)));let o=Y(Ms(u.get("emissive"),pe)??m.emissive,i);if(null!=m.emissiveMap){let e;if(m.emissiveMap instanceof c.CompressedArrayTexture){const t=ee(m.emissiveMap),a=Ms(u.get("emissiveMap"),_)??R(m.emissiveMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=K(m.emissiveMap).sample(sa(r,m.emissiveMap));o=o.multiply(e)}const g=Ms(u.get("emissiveIntensity"),_)??R(m.emissiveIntensity??1),y=Ms(u.get("normalScale"),de)??ue(m.normalScale??new C(1,1));let w=ce.normal;if(null!=m.normalMap){let e;if(m.normalMap instanceof c.CompressedArrayTexture){const t=ee(m.normalMap),a=Ms(u.get("normalMap"),_)??R(m.normalMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=K(m.normalMap).sample(sa(r,m.normalMap));w=F(e.rgb,y.x)}let S=Ms(u.get("roughness"),_)??R(m.roughness??1);if(null!=m.roughnessMap){let e;if(m.roughnessMap instanceof c.CompressedArrayTexture){const t=ee(m.roughnessMap),a=Ms(u.get("roughnessMap"),_)??R(m.roughnessMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=K(m.roughnessMap).sample(sa(r,m.roughnessMap));S=S.multiply(e.g)}let b=Ms(u.get("metalness"),_)??R(m.metalness??0);if(null!=m.metalnessMap){let e;if(m.metalnessMap instanceof c.CompressedArrayTexture){const t=ee(m.metalnessMap),a=Ms(u.get("metalnessMap"),_)??R(m.metalnessMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=K(m.metalnessMap).sample(sa(r,m.metalnessMap));b=b.multiply(e.b)}let v=R(1);if(null!=m.aoMap){let e;if(m.aoMap instanceof c.CompressedArrayTexture){const t=ee(m.aoMap),a=Ms(u.get("aoMap"),_)??R(m.aoMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=K(m.aoMap).sample(sa(r,m.aoMap));v=v.multiply(e.r)}const M=Ms(u.get("aoMapIntensity"),_)??R(m.aoMapIntensity??0);let A=w;!0!==m.userData.disableAO&&(A=G("DOUBLE_SIDED",A,e=>H(new $("gl_FrontFacing"),e,e.multiplyScalar(-1))));const x=new q({color:Z({color:n,roughness:S,metalness:b,ambientOcclusion:v,ambientOcclusionIntensity:M,emissive:o,emissiveIntensity:g,normal:A}),normal:w,roughness:S,emissive:o.rgb,transparent:m.transparent,alphaTest:m.alphaTest,envMap:m.envMap,opacity:i});null!=m.envMap&&(x.uniforms.envMapIntensity={value:m.envMapIntensity},x.uniforms.envMapRotation={value:js(m.envMapRotation,m.envMap)}),x.envMap=m.envMap,x.side=m.side,f=x}else if(m instanceof q){const a=new Set,s=new Map,r=Object.keys(m.uniforms).filter(e=>!ps(e));for(const i of e){const e=t.get(i.id).get(i.meshUUID);if(!(e instanceof q))throw new Error("Expected NodeShaderMaterial in node material batch");for(const t of r){const r=e.uniforms[t]?.value,i=s.get(t);void 0===i||Ds(r,i)?s.set(t,r):ms(r)&&ms(i)&&gs(r)===gs(i)&&a.add(t)}}const i=new Set(Object.keys(m.uniforms)),n={};for(const e of a){let t,a;const s=m.uniforms[e]?.value;if("number"==typeof s){let s=p.find(e=>e.params.length<4);if(null==s){const t=ys("vp"+p.length,i);s={name:t,params:[e],node:N(t)},p.push(s)}else s.params.push(e);a=s.name,t=Ps(s.node,s.params.length-1)}else if(s instanceof E)a=ys(e,i),t=N(a);else if(s instanceof O||s instanceof h)a=ys(e,i),t=V(a);else{if(!(s instanceof C))continue;a=ys(e,i),t=B(a)}u.set(e,t),d.set(e,a),n[e]=t}if(0===u.size)f=m;else{const e=W(m,{color:m.outputColor,transform:m.outputTransform??null,position:null==m.outputTransform?m.outputPosition:void 0,normal:m.outputNormal??null,roughness:m.outputRoughness??null,opacity:m.outputOpacity??null,emissive:m.outputEmissive??null,uniforms:ws(m,new Set(u.keys())),uniformNodes:n});e.uniformNodes=n,g=m,(y=e).name=g.name,y.side=g.side,y.blending=g.blending,y.depthWrite=g.depthWrite,y.depthTest=g.depthTest,y.colorWrite=g.colorWrite,y.toneMapped=g.toneMapped,y.visible=g.visible,y.opacity=g.opacity,y.forceSinglePass=g.forceSinglePass,y.premultipliedAlpha=g.premultipliedAlpha,y.polygonOffset=g.polygonOffset,y.polygonOffsetFactor=g.polygonOffsetFactor,y.polygonOffsetUnits=g.polygonOffsetUnits,y.shadowSide=g.shadowSide,Object.assign(y.defines,g.defines),Object.assign(y.userData,g.userData),y.needsUpdate=!0,f=e}}else{f=m;for(const a of e){const e=t.get(a.id).get(a.meshUUID);if(e!=f){console.error(`Different materials in group for object ${a.id} and mesh uuid ${a.meshUUID}`,{objectMaterial:e,sourceMaterial:m});break}}}var g,y;const w=new Yt(n,i,r,f);for(const e of p)w.initUniform(e.name,4);for(const[e,t]of u.entries()){if(p.some(t=>t.params.includes(e)))continue;let a=1;t instanceof me||t instanceof pe?a=4:t instanceof de&&(a=2),w.initUniform(d.get(e)??e,a,0)}for(const[e,r]of s.entries()){const s=r[0].assetId,i=o.get(e);if(null==i){console.error(`Missing single asset mesh for mesh uuid ${e} and asset id ${s}`);continue}if(null==i.geometry){console.error("Missing geometry on mesh mesh");continue}const n=w.addGeometry(ss(i.geometry,m)),l=this.assets.get(s),f=a.get(s);if(null==f){console.warn("Missing batching info when configuring for asset id "+s);continue}const g=nt(f.assetMesh)?.uuid===e,y=f.assetMesh instanceof ct&&g?f.assetMesh.collisionShapes:void 0,S=this.configureBatchedInstancedMesh(r,w,i,n,y);for(let e=0;e<S.length;e++){const a=r[e],s=S[e];"webgpu"!==this.renderingView?.requestedBackend&&w.setCastShadowAt(s,a.castShadow??l?.castShadow??!1);const i=t.get(a.id).get(a.meshUUID),n=i.userData.surface;null!=n&&(w.surfaceByInstance[s]=n);for(const e of p){let t=Is.set(0,0,0,0);for(let a=0;a<e.params.length;a++){const s=fs(i,e.params[a]);"number"==typeof s&&t.setComponent(a,s)}w.setUniformAt(e.name,s,t)}for(let e of u.keys()){if(p.some(t=>t.params.includes(e)))continue;const t=d.get(e)??e;let a=fs(i,e);if(a instanceof h&&(a=new O(a.r,a.g,a.b)),a instanceof c.CompressedArrayTexture)a=a.userData.index??0;else if(a instanceof D||null==a)continue;w.setUniformAt(t,s,a)}}}return w}async createInstancedMesh(e,t){const a=ot(t,e=>!ht(e)&&null!=e.geometry),s=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,Ga(e[0].materialAssignments,s.materialAssignments),s),a.updateMatrix();const r=a.geometry.clone(),i=a.material;let n;if(n=new c.InstancedMesh(r,i,e.length),this.configureBatchedInstancedMesh(e,n,a),a.material instanceof y&&n.castShadow&&n.receiveShadow&&Array.isArray(i))for(const e of i);return n}configureBatchedInstancedMesh(e,t,a,s,r){const i=[];a.updateWorldMatrix(!0,!0);for(let n=0;n<e.length;n++){let o=n;t instanceof c.BatchedMesh&&(o=t.addInstance(s)),i.push(o);const l=(new c.Matrix4).compose((new O).fromArray(e[n].position),(new P).setFromEuler((new p).fromArray(e[n].rotation)),(new O).fromArray(e[n].scale)),u=(new w).copy(e[n].parentTransform).multiply(l),d=(new w).copy(u).multiply(a.matrixWorld);t.setMatrixAt(o,d),null==t.userData.hasCollision&&(t.userData.hasCollision=[]);const h=this.assets.get(e[n].assetId);t.userData.hasCollision[o]=!1!==e[n].collisionDetection||!1!==h?.collisionDetection,null!=r&&(null==t.userData.collisionShapes&&(t.userData.collisionShapes=[]),t.userData.collisionShapes[o]=r,null==t.userData.collisionMatrices&&(t.userData.collisionMatrices=[]),t.userData.collisionMatrices[o]=u)}return i}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 if("prefab"===e.type){this.unregisterLivePrefabInstance(e.id);const t=new Set(this.removePrefabEventGraphs(e.id).flatMap(e=>e.actors));this.materializedActors.forEach((a,s)=>{(s===e.id||s.startsWith(e.id+"/"))&&(t.has(a)||(a.disposed.next(!0),a.onEndPlay()),this.materializedActors.delete(s))})}const t=this.sceneObjectMap.get(e.id);t&&this.latticeGeometries.release(t),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 it(this.scene,t=>t.userData.src?.assetId==e,e=>null!=e.userData.src)}applyMaterials(e,t,a){return null==t?Promise.resolve([]):Promise.all(t.filter(e=>"null"!==e.materialId).map(t=>this.applyMaterial(e,t,a)))}async applyMaterial(e,t,a){await applyMaterial(e,t,async e=>{const t=await this.getAsset(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)}else console.warn("Missing material with id "+e)},this._originalMaterials,{textureFlipY:getConvertedFbxToGlbAssignedMaterialTextureFlipY(a)})}async resolveMaterialForAssignments(e,t,a){let s=e,r=null,i=null;const n=getConvertedFbxToGlbAssignedMaterialTextureFlipY(a);for(const e of t??[]){if(!Ya(s,e,r,i))continue;const t=await this.getAsset(e.materialId);if(null==t){console.warn("Missing material with id "+e.materialId);continue}let a=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!0);null!=a&&(a=Ha(a,n)),null!=a&&s.id!==a.id&&(r=r??Ja(s),i=i??s.name,s=a);break}return s}unapplyMaterials(e){e.traverse(async e=>{if(e instanceof S)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){this.navigationRevision++;const t=new Map(this.actorTypes.map(e=>[e.name,e.type])),a=new Map(e.map(e=>[e.name,e.type])),s=new Set;for(const e of new Set([...t.keys(),...a.keys()]))(t.get(e)??Pe[e])!==(a.get(e)??Pe[e])&&s.add(e);this.actorTypes=e,0!==s.size&&it(this.scene,e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&s.has(e.userData.src.actor.type)).forEach(async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)})}updateComponents(e){this.componentTypes=e,it(this.scene,e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&(e.userData.src.actor?.components?.length??0)>0).forEach(async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)})}updateShaders(e){this.shaders=e;for(const[e,t]of pa.entries())t.userData.customShaderName&&pa.delete(e);fa.clear(),this.landscapeManagers.forEach(t=>t.updateShaders(e)),it(this.scene,e=>!0).forEach(e=>{e.traverse(async e=>{if(e instanceof S)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=e.material[t].userData.assetId,s=await this.getAsset(a);null!=s&&this.refreshMaterial(e,e.material[t],s,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=e.material.userData.assetId,a=await this.getAsset(t);null!=a&&this.refreshMaterial(e,e.material,a)}}})})}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 i=!1;if(t.traverseAncestors(e=>{"_hology_transform_group"===e.name&&(i=!0)}),!i){const a=this.findParent(e);null!=a&&a.uuid!=t.uuid?a.attach(t):console.error("Parent is wrong")}if(!("shape_mesh"!==e.type&&"asset_mesh"!==e.type||null==e.renderOrder&&0===t.renderOrder||e.renderOrder===t.renderOrder))return void(t.renderOrder=e.renderOrder??0);if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(t);this.inEditor&&e.hidden&&!1?t.traverse(e=>{e instanceof S&&(e.material.wireframe=!0)}):t.traverse(e=>{e instanceof S&&(e.material.wireframe=!1)})}if("asset_mesh"===e.type&&t.userData.assetId!==e.assetId){this.remove(e);const t=await this.materializeAndInitActor(e);return void this.updated$.next({object:t,source:e})}if("asset_mesh"===e.type&&this.latticeGeometries.apply(t,e.latticeDeformation,JSON.stringify(e.vertexMaterials??[])),"asset_mesh"===e.type){const a=this.assets.get(e.assetId);Ga(e.materialAssignments,a.materialAssignments).forEach(e=>this.applyMaterial(t,e,a))}else"shape_mesh"===e.type&&this.applyMaterials(t,e.materialAssignments);if(i||(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.inEditor&&("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&e.physics?.type!==De.dynamic?xa(t,!1):this.inEditor&&function(e){let t=!1;if(e.traverse(e=>{Aa.has(e)&&(t=!0)}),!t)return;e.updateWorldMatrix(!0,!0),e.traverse(e=>{Aa.has(e)&&(e.matrixWorldNeedsUpdate=!1)})}(t)),this.applyVertexMaterials(e,t),"light"==e.type){if("point"==e.light.type){const a=t;a.color=new h(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 h(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,a.map=await this.loadSpotLightMap(e.light.spot.mapTextureId)}else if("directional"===e.light.type)this.applyDirectionalLight(e.light.directional,e);else if("ambient"===e.light.type)this.applyDirectionalAmbientLight(t,e.light.ambient,e);else if("rectArea"===e.light.type){const a=t;a.color=new h(e.light.rectArea.color),a.intensity=e.light.rectArea.intensity,null!=e.scale&&(a.width=e.scale[0],a.height=e.scale[1]),a.children.forEach(e=>{e instanceof Kt&&e.update()})}}else if("landscape"===e.shape){const a=this.landscapeManagers.find(t=>t.source.id===e.id),i=null==a||(s=a.source.landscape.options,r=e.landscape.options,s.density!==r.density||s.sections.x!==r.sections.x||s.sections.y!==r.sections.y);if(this.inEditor&&i){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 m?"density":"linear")!==e.fog.type;this.scene.fog=Da(e.fog),t&&(a=this.scene).traverse(e=>{if(e instanceof S){const t=e.material;t instanceof q&&(a.fog instanceof f?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof m&&(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 Lt){const a=await prepareClassParameters(e.actor.params,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,[],this.actorProvider,e=>this.prefabInstanceExposedActorMap.get(e)??null,t);return void Object.assign(t,a)}const a=this.editorActorParamSnapshot.get(e.id);if((null==a||a!==JSON.stringify(e.actor))&&!i){if(null!=t&&null!=a&&await this.tryApplyLiveActorParameterUpdate(t,e,a))return void this.updated$.next({object:t.object,source:e});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 ft&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}if("shape_mesh"===e.type&&"landscape"!==e.shape)ha(t,e.castShadow,e.receiveShadow);else if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);if(null==a)return void console.error("Asset not found",e.assetId);const s=e.receiveShadow??!!a.receiveShadow,r=e.castShadow??!!a.castShadow;ha(t,r,s)}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,s,r;this.renderingView.invalidateShadows()}async materializeAndInitActor(e,t=this.findParent(e)){const a=await this.materialize(e,t),s=Array.from(this.materializedActors.entries()).filter(([t])=>t===e.id||t.startsWith(e.id+"/"));return await this.initActorsPostInit(s),this.announcePrefabEventGraphs(e.id),a}async tryApplyLiveActorParameterUpdate(e,t,a){let s;try{s=JSON.parse(a)}catch{return!1}const r=await this.tryApplyLiveActorSettingsUpdate(e,s,t.actor);return r&&this.editorActorParamSnapshot.set(t.id,JSON.stringify(t.actor)),r}async tryApplyLiveActorSettingsUpdate(e,t,a){const s=await this.applyLiveActorSettingsUpdate(e,t,a);return s.hasChanges&&!s.rejected}async applyLiveActorSettingsUpdate(e,t,a){const s=t?.components??[],r=a?.components??[];if(t?.type!==a?.type||s.length!==r.length||s.some((e,t)=>e.type!==r[t]?.type))return{applied:t,hasChanges:!0,rejected:!0};let i=!1,n=!1;const o=await this.tryApplyLiveParameterUpdate(e,t?.params??{},a?.params??{});!1===o&&(n=!0),i||(i=!0===o);const l=await this.applyLiveInnerParameterUpdates(e,t?.innerParams??[],a?.innerParams??[]);n||(n=l.rejected),i||(i=l.hasChanges);const c=this.editorAttachedActorComponents.get(e),u=[];for(let e=0;e<r.length;e++){const t=s[e],a=r[e];if(JSON.stringify(t)===JSON.stringify(a)){u.push(a);continue}const o=c?.[e];if(null==o){n=!0,u.push(t);continue}const l=await this.tryApplyLiveParameterUpdate(o,t?.params??{},a?.params??{});!1===l&&(n=!0),i||(i=!0===l);const d=await this.applyLiveInnerParameterUpdates(o,t?.innerParams??[],a?.innerParams??[]);n||(n=d.rejected),i||(i=d.hasChanges),u.push({...a,params:!1===l?t?.params:a?.params,innerParams:d.applied})}return{applied:{...a,params:!1===o?t?.params:a?.params,innerParams:l.applied,components:u},hasChanges:i,rejected:n}}async applyLivePrefabParameterUpdate(e,t){if(!this.assetsService.supportsLivePrefabParameters)return!1;const a=this.livePrefabInstances.get(t.id);if(null==a||0===a.size)return!0;const s=Va(e.prefab?.objects??[]),r=Va(t.prefab?.objects??[]);if(s.size!==r.size||[...s.keys()].some(e=>!r.has(e)))return!1;const i=[];await this.applyLiveNestedPrefabOverrideUpdates(e,t,a,i);for(const n of a.values())for(const[a,o]of s){const s=r.get(a),l=n.actorsById.get(a);if(null==s||null==l){i.push(`${n.prefix}/${a}`);continue}const c=n.actorSettingsById.get(a)??za(o,n.source,e.prefab?.mainActorId===a),u=za(o,n.source,e.prefab?.mainActorId===a),d=$a(u,za(s,n.source,t.prefab?.mainActorId===a),n.desiredActorSettingsById.get(a)??u);if(n.desiredActorSettingsById.set(a,d),JSON.stringify(c)===JSON.stringify(d))continue;const h=await this.applyLiveActorSettingsUpdate(l,c,d);n.actorSettingsById.set(a,h.applied),h.rejected&&i.push(`${n.prefix}/${a}`)}return i.length>0&&console.warn(`Some live parameters for prefab ${t.name??t.id} were not applied. The running instances were preserved: ${i.join(", ")}`),!0}async applyLiveNestedPrefabOverrideUpdates(e,t,a,s){const r=Na(e.prefab?.objects??[]),i=Na(t.prefab?.objects??[]);for(const[e,t]of r){const r=i.get(e);if(null==r||t.assetId!==r.assetId||JSON.stringify(t.prefab)===JSON.stringify(r.prefab))continue;const n=this.assets.get(r.assetId),o=this.livePrefabInstances.get(r.assetId);if("prefab"!==n?.type||null==n.prefab||null==o)continue;const l=Va(n.prefab.objects);for(const i of a.values()){const a=`${i.prefix}/${e}`,c=o.get(a);if(null!=c){for(const[e,i]of l){const o=c.actorsById.get(e);if(null==o){s.push(`${a}/${e}`);continue}const l=za(i,t,n.prefab.mainActorId===e),u=za(i,r,n.prefab.mainActorId===e),d=c.desiredActorSettingsById.get(e)??l,h=$a(l,u,d);c.desiredActorSettingsById.set(e,h);const p=c.actorSettingsById.get(e)??d;if(JSON.stringify(p)!==JSON.stringify(h)){const t=await this.applyLiveActorSettingsUpdate(o,p,h);c.actorSettingsById.set(e,t.applied),t.rejected&&s.push(`${a}/${e}`)}}c.source=r}}}}unregisterLivePrefabInstance(e){if(0!==e.length)for(const[t,a]of this.livePrefabInstances){for(const t of[...a.keys()])(t===e||t.startsWith(e+"/"))&&a.delete(t);0===a.size&&this.livePrefabInstances.delete(t)}}rememberLivePrefabActorSettings(e,t){if(this.assetsService.supportsLivePrefabParameters)for(const a of this.livePrefabInstances.values())for(const s of a.values()){if(!e.startsWith(s.prefix+"/"))continue;const a=e.slice(s.prefix.length+1);s.actorsById.has(a)&&(s.actorSettingsById.set(a,t),s.desiredActorSettingsById.set(a,t))}}async tryApplyLiveParameterUpdate(e,t,a){const s=new Set([...new Set([...Object.keys(t),...Object.keys(a)])].filter(e=>JSON.stringify(t[e])!==JSON.stringify(a[e])));if(0===s.size)return null;const r=await prepareClassParameters(a,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders,this.actorProvider,e=>this.prefabInstanceExposedActorMap.get(e)??null,e);return await e.applySceneParameters(r,s)}async applyLiveInnerParameterUpdates(e,t,a){const s=new Map(t.map(e=>[JSON.stringify(e.path),e])),r=new Map(a.map(e=>[JSON.stringify(e.path),e]));if(s.size!==t.length||r.size!==a.length)return{applied:t,hasChanges:!0,rejected:!0};let i=!1,n=!1;const o=[];for(const t of new Set([...s.keys(),...r.keys()])){const a=s.get(t),l=r.get(t);if(JSON.stringify(a?.params??{})===JSON.stringify(l?.params??{})){null!=l&&o.push(l);continue}const c=l?.path??a?.path,u=this.resolveActorComponent(e,c);if(null==u){n=!0,null!=a&&o.push(a);continue}!0===await this.tryApplyLiveParameterUpdate(u,a?.params??{},l?.params??{})?(null!=l&&o.push(l),i=!0):(n=!0,null!=a&&o.push(a))}return{applied:o,hasChanges:i,rejected:n}}resolveActorComponent(e,t){if(null==t||0===t.length)return null;let a=e;for(const e of t){const t=a[e];if(!(t instanceof Ie))return null;a=t}return a instanceof Ie?a:null}findParent(e){const t=this.dataProvider.getObjects().flatMap(t=>t.id===e.id?null:rt(t,t=>t.children?.some(t=>t.id===e.id),()=>!0))[0];return null==t?this.scene:null!=t?it(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 h(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse(e=>{e instanceof S&&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=at(e.vertexMaterials,e=>e.m);t.traverse(e=>{if(e instanceof S){if(null==e.geometry)return;if(ts(vt(e,0,!1)),a>0){ts(vt(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=vt(s,0,!0);ts(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=vt(s,4,!0);ts(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){const r=this.getNestedActorId(e.id,s);if(null!=this.persistence&&!0!==s?.runtimeSpawn){if(this.isPersistenceRemoved(r))return;if("actor"===e.type){const e=this.persistence.resolve({sceneId:this.persistenceSceneId,path:r});if(null!=e)return void this.materializedActors.set(r,e)}}if(this.idToSceneObject.set(r,e),!this.shouldBeMaterialized(e))return;let i,n;switch(e.type){case"asset_mesh":i=await this.createFromAsset(e),e.latticeDeformation||(i=freezeSkinnedMeshes(i));break;case"shape_mesh":i=await this.createFromShape(e);break;case"light":i=await this.createLight(e);break;case"particles":i=await this.createParticleSystem(e),e.collisionDetection=!1;break;case"global_fog":this.scene.fog=Da(e.fog),this.fixFogColor(),i=new g;break;case"sky":this.sky=Tt(),this.updateSky(e),i=this.sky;break;case"world_env":this.updateWorldEnv(e),i=new g,this.worldEnvObj=i;break;case"actor":({object:i,actor:n}=await this.createFromActor(e,s));break;case"group":case"scatter":i=new g;break;case"prefab":i=await this.createFromPrefab(e,s,t);break;case"vfx":i=await this.createFromVfx(e,s);break;default: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 or because of an error in the scene data. Scene object: id=${e.id}, name=${e.name}`)}if(null==i)return;e.name&&e.name.length>0&&(i.name=e.name),i.userData.detailCulling=e.detailCulling,this.applyTransform(e,i),a?i.userData._src=e:i.userData.src=e,null!=n&&(i.userData.actor=n,["NavMesh","NavMeshActor"].includes(e.actor?.type)&&(i.userData.navigationBake=this.navigationBakes[r]??this.navigationBakes[r.replace(/^\//,"")],this.inEditor&&(i.userData.navigationBakeSource=async()=>({objects:this.dataProvider.getObjects(),assets:await this.assetsService.getAssets(),loadCollisionShapes:async e=>(await this.assetManagerService.getMesh(e)).scene.collisionShapes??[]})),this.inEditor&&(i.userData.navigationBakeRevision=()=>this.navigationRevision))),this.inEditor,this.inEditor,this.objectMap.set(i.uuid,e),this.sceneObjectMap.set(e.id,i),e.physics?.type!==De.dynamic||null==t||this.inEditor?null==t?this.scene.add(i):null==t||"actor"!==e.type||this.inEditor?t?.add(i):(t.add(i),this.scene?.attach(i),console.log(i)):(t.add(i),i.getWorldPosition(Ca),i.getWorldQuaternion(Oa),i.getWorldScale(Ea),this.scene.add(i),i.position.copy(Ca),i.quaternion.copy(Oa),i.scale.copy(Ea)),null!=e.children&&await Promise.all(e.children?.map(e=>this.materialize(e,i,a,null==s?void 0:structuredClone(s))));const o=("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&e.physics?.type!==De.dynamic;if(this.inEditor&&o&&!function(e){for(let t=e;null!=t;t=t.parent)if(!0===t.userData.hologyEditorMatrixWorldAutoUpdate)return!0;return!1}(t)?xa(i,!1):this.inEditor||null!=t||"asset_mesh"!=e.type&&"shape_mesh"!==e.type&&"prefab"!==e.type&&"group"!==e.type||"landscape"===e.shape||null!=e.physics?.type&&e.physics.type==De.dynamic||va(i),null!=this.renderingView)return this.renderingView.invalidateShadows(),i;console.warn("RenderingView not found in materializer")}async handlePaintedScatterSceneMutation(e){const t=this.paintedScatterManager?.referencesSceneObject(e.id)??!1,a=await this.sceneObjectContainsPaintedScatter(e);(t||a)&&await this.refreshPaintedScatterPresence(!1)}async refreshPaintedScatterPresence(e=!1){return await this.sceneContainsPaintedScatter()?(null==this.paintedScatterManager&&(this.paintedScatterManager=new Mt(this.scene,this.dataProvider,this.renderingView,this.assetManagerService,this.assetsService)),this.paintedScatterManager.queueRefresh(e),!0):(this.disposePaintedScatterManager(),!1)}disposePaintedScatterManager(){null!=this.paintedScatterManager&&(this.paintedScatterManager.clear(),this.paintedScatterManager.stop(),this.paintedScatterManager=void 0)}async sceneContainsPaintedScatter(){return this.sceneObjectsContainPaintedScatter(this.dataProvider.getObjects())}async sceneObjectsContainPaintedScatter(e,t=[]){for(const a of e??[])if(await this.sceneObjectContainsPaintedScatter(a,t))return!0;return!1}async sceneObjectContainsPaintedScatter(e,t=[]){if("scatter"===e.type&&(e.paintedScatter?.cells?.some(e=>(e.instances?.length??0)>0)||(e.paintedScatter?.palette?.length??0)>0))return!0;if(null!=e.children&&await this.sceneObjectsContainPaintedScatter(e.children,t))return!0;if("prefab"===e.type&&null!=e.assetId){if(t.includes(e.assetId))return!1;const a=this.assets.get(e.assetId)??await this.assetsService.getAsset(e.assetId),s=a?.prefab?.objects;if(null!=s)return this.sceneObjectsContainPaintedScatter(s,[...t,e.assetId])}return!1}async handleSurfaceScatterSceneMutation(e){const t=this.surfaceScatterManager?.referencesSceneObject(e.id)??!1,a=await this.sceneObjectContainsSurfaceScatter(e);(t||a)&&await this.refreshSurfaceScatterPresence(!0)}async refreshSurfaceScatterPresence(e=!1){return await this.sceneContainsSurfaceScatter()?(null==this.surfaceScatterManager&&(this.surfaceScatterManager=new At(this.scene,this.dataProvider,this.renderingView,this.assetManagerService,this.assetsService)),this.surfaceScatterManager.queueRefresh(e),!0):(this.disposeSurfaceScatterManager(),!1)}disposeSurfaceScatterManager(){null!=this.surfaceScatterManager&&(this.surfaceScatterManager.clear(),this.surfaceScatterManager.stop(),this.surfaceScatterManager=void 0)}async sceneContainsSurfaceScatter(){return this.sceneObjectsContainSurfaceScatter(this.dataProvider.getObjects())}async sceneObjectsContainSurfaceScatter(e,t=[]){for(const a of e??[])if(await this.sceneObjectContainsSurfaceScatter(a,t))return!0;return!1}async sceneObjectContainsSurfaceScatter(e,t=[]){if("asset_mesh"===e.type&&(e.surfaceScatter?.meshes?.length??0)>0)return!0;if(null!=e.children&&await this.sceneObjectsContainSurfaceScatter(e.children,t))return!0;if("prefab"===e.type&&null!=e.assetId){if(t.includes(e.assetId))return!1;const a=this.assets.get(e.assetId)??await this.assetsService.getAsset(e.assetId),s=a?.prefab?.objects;if(null!=s)return this.sceneObjectsContainSurfaceScatter(s,[...t,e.assetId])}return!1}sceneReferencesPrefabAsset(e){const t=(a=[])=>{for(const s of a??[]){if("prefab"===s.type&&s.assetId===e)return!0;if(t(s.children))return!0}return!1};return t(this.dataProvider.getObjects())}async prefabAssetContainsSurfaceScatter(e){return"prefab"===e.type&&null!=e.prefab?.objects&&this.sceneObjectsContainSurfaceScatter(e.prefab.objects,[e.id])}async prefabAssetContainsPaintedScatter(e){return"prefab"===e.type&&null!=e.prefab?.objects&&this.sceneObjectsContainPaintedScatter(e.prefab.objects,[e.id])}applyTransform(e,t){null!=e.position&&t.position.fromArray(e.position),null!=e.scale&&t.scale.fromArray(e.scale),null!=e.rotation&&t.rotation.fromArray(e.rotation)}updateWorldEnv(e){this.renderingView.configureAmbientOcclusion(e.worldEnv.ao.enabled,e.worldEnv.ao.blendIntensity,e.worldEnv.ao);const t=e.worldEnv.toneMapping;null!=t&&this.renderingView.setBaseToneMapping(t.mapping??0,t.exposure??1);const a=e.worldEnv.environment,s=++this.worldEnvironmentRequest;null!=a&&null!=a.textureId?this.assetManagerService.getTexture(this.assets.get(a.textureId)).then(e=>{s===this.worldEnvironmentRequest&&(null!=e?this.renderingView.setWorldEnvironment({source:e,intensity:a.intensity??1}):console.error("Failed to load environment texture with id "+a.textureId))}):this.renderingView.setWorldEnvironment(null)}resetWorldEnv(){this.worldEnvironmentRequest++,this.renderingView.setWorldEnvironment(null),this.renderingView.configureAmbientOcclusion(!1),this.renderingView.setBaseToneMapping(c.NoToneMapping,1)}async updateSky(e){null!=this.sky&&(null==e?.sky?.materialId&&this.sky.material!==Bt?(this.sky.material=Bt,this.applySkySettings(this.sky.material)):this.sky.material.userData?.assetId!==e.sky.materialId&&this.updateSkyMaterial(e),null!=e.rotation&&this.sky.rotation.fromArray(e.rotation))}async updateSkyMaterial(e){const t=await this.assetsService.getAsset(e.sky.materialId);if(null==t)return void console.warn(`No material asset found for sky with id ${e.sky.materialId}`);const 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=c.BackSide,(e instanceof M||e instanceof c.MeshBasicMaterial||e instanceof c.ShaderMaterial)&&(e.fog=!1),e.depthTest=!0,e.depthWrite=!1,e.transparent=!0}async createComponent(e,t,a,s){const r=new la[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??Pe[e.actor?.type];if(null==a)return console.warn(`Failed to materialize actor. No actor class found for type '${e.actor?.type}'.`),{object:null,actor:null};this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const s=await this.actorProvider.create(a,(new O).fromArray(e.position),(new p).fromArray(e.rotation),!0),r=this.getNestedActorId(e.id,t);return s.__netSceneId=r,this.applyInitialMaterializedNetRole(s),this.materializedActors.set(r,s),{object:s?.object,actor:s}}applyInitialMaterializedNetRole(e){if(this.inEditor||this.netMode===Ce.none)return;const t=je(e.constructor);!0!==t?.replicate?this.netMode===Ce.client&&(e.netRole=Oe.none):e.netRole=this.netMode===Ce.client?Oe.simulatedProxy:Oe.authority}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(ye,(new O).fromArray(e.position),(new p).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 S&&this._originalMaterials.set(e.id,e.material)});else{let s=new M({name:"Default",color:new h("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});!0===e.collider&&(s.opacity=.3,s.color.set(2517460),s.transparent=!0);const r=await this.createMeshByShape(e.shape,s,e.shapeParams);r.castShadow=e.castShadow??!0,r.receiveShadow=e.receiveShadow??!1,!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 g;const a=gt(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new mt(e,this.renderingView,a,this.assetManagerService,this.assetsService,this.shaders,async t=>{await Promise.all((e.materialAssignments??[]).filter(e=>null!=e.materialId).map(e=>this.applyMaterial(t,e))),this.inEditor||this.applyVertexMaterials({...e,vertexMaterials:e.vertexMaterials?.filter(e=>e.m===t.name)},t)},!this.inEditor&&!1!==e.landscape.staticDrawSets);return this.landscapeManagers.push(s),s.refreshGeometry(),a}applyHeightMaps(e,t,a=!1){const s=new yt(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(()=>wt(r),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&Et.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);if(!this.geometryCache.has(r)){const t=Ot[e].geometry(s);(function(e){return null!=e.index&&e.hasAttribute("position")&&e.hasAttribute("normal")&&e.hasAttribute("uv")})(t)&&t.computeTangents(),this.geometryCache.set(r,t)}this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,Ot[e].collision(s));return new ft(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 decodeModelImage(e){const t=e.image;if("function"!=typeof createImageBitmap||"undefined"==typeof HTMLImageElement||!(t instanceof HTMLImageElement))return;const a=e.source;let s=this.modelImageBitmaps.get(a);if(null==s){const e=()=>createImageBitmap(t,{imageOrientation:"none",premultiplyAlpha:"none",colorSpaceConversion:"none"}),r=t.currentSrc||t.src,i=/^(blob:|data:)/.test(r)?this.assetManagerService.decodeImageBitmap(r):void 0;s=(i?.catch(t=>(console.warn("Worker model image decode failed; decoding locally",t),e()))??e()).then(e=>{a.data===t?a.data=e:e.close()}).catch(e=>{console.warn("Could not decode model image before upload",e)}),this.modelImageBitmaps.set(a,s)}await s,a.data!==t&&(e.needsUpdate=!0)}async createFromAsset(e,t){const a=this.assets.get(e.assetId)??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(e.latticeDeformation&&(s=freezeSkinnedMeshes(s,!0),this.latticeGeometries.apply(s,e.latticeDeformation,JSON.stringify(e.vertexMaterials??[]))),!1!==t?.assignMaterials)try{await Promise.all(Ga(e.materialAssignments,a.materialAssignments).map(e=>this.applyMaterial(s,e,a)))}catch(t){console.error("Failed to apply material"+t,e)}const r=e.receiveShadow??!!a.receiveShadow,i=e.castShadow??!!a.castShadow;if(s.receiveShadow=r,ha(s,i,r),!1!==e.collisionDetection&&!1!==a.collisionDetection||(s.collisionShapes=[]),null!=e.physics&&!0!==this.inEditor&&(s.physics=e.physics),this.applyVertexMaterials(e,s),s.traverse(e=>{e instanceof S&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()}),s.userData.assetId=e.assetId,s.traverse(e=>{if(e instanceof S)for(const t of st(e.material))Ve(t,!1)}),"webgpu"===this.renderingView.requestedBackend){await this.renderingView.initializeBackend();const e=new Set;s.traverse(t=>{if(t instanceof S)for(const a of st(t.material))if(a instanceof c.ShaderMaterial)for(const t of Object.values(a.uniforms)){const a=t.value;a instanceof D&&null!=a.image&&e.add(a)}else for(const t of Object.values(a))t instanceof D&&null!=t.image&&e.add(t)}),await Promise.all(Array.from(e,async e=>{await this.decodeModelImage(e),this.renderingView.initTexture(e)}))}return s}async createFromPrefab(e,t,a){const s=await this.assetsService.getAsset(e.assetId);if(null==s)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:r}=await this.createFromPrefabAsset(s,t,a,e);return t.sceneObjectChain.pop(),r}async createFromPrefabAsset(e,t,a,s,r=!0){this.assets.set(e.id,e);const i=new g;null!=s&&this.applyTransform(s,i),null!=a&&a.add(i),await Promise.all(e.prefab.objects.filter(e=>"global_fog"!==e.type&&"world_env"!==e.type).map(e=>this.materialize(e,i,!0,structuredClone(t))));const n=t.sceneObjectChain.join("/"),o=Array.from(this.materializedActors.entries()).filter(([e,t])=>e.startsWith(n+"/")&&!t.__isInitialised);o.forEach(e=>{});let l=null;if(null!=e.prefab?.mainActorId){const a=t.sceneObjectChain.join("/")+"/"+e.prefab.mainActorId;l=this.materializedActors.get(this.persistenceActorPath(a))??null}r||await this.initActorsPostInit(o);const c=Array.from(this.materializedActors.entries()).filter(([e])=>e.startsWith(n+"/")),u=c.map(([,e])=>e),d=new Map(c.map(([e,t])=>[e.slice(n.length+1),t]));if(this.assetsService.supportsLivePrefabParameters){let t=this.livePrefabInstances.get(e.id);null==t&&(t=new Map,this.livePrefabInstances.set(e.id,t));const a=new Map([...Va(e.prefab?.objects??[])].map(([t,a])=>[t,za(a,s,e.prefab?.mainActorId===t)]));t.set(n,{prefix:n,source:s,actorsById:d,actorSettingsById:a,desiredActorSettingsById:new Map(a)})}if(!this.inEditor&&!0!==t.runtimeSpawn&&na(e.prefab?.eventGraph)&&this.materializedPrefabEventGraphs.set(n,{id:n,graph:e.prefab.eventGraph,object:i,actors:u,actorsById:d,mainActor:l}),null!=e.prefab?.mainActorId&&null!=s){const a=t.sceneObjectChain.join("/"),s=a+"/"+e.prefab.mainActorId;this.prefabInstanceExposedActorMap.set(a,s)}return{object:i,actors:u,actorsById:d,mainActor:l,instanceId:n}}async createParticleSystem(e){await this.assetsService.getAsset(e.assetId);return new x}async createLight(e){if("point"===e.light.type){const t=new j(e.light.point.color,e.light.point.intensity,Math.max(e.light.point.distance,0),e.light.point.decay);if(t.castShadow=e.light.point.castShadow??!0,t.userData.volumetricIntensity=e.light.point.volumetricIntensity,this.inEditor){const e=(new c.TextureLoader).load("assets/light-bulb-icon.webp"),a=new c.SpriteMaterial({map:e,alphaTest:.5}),s=new qt(a);s.scale.multiplyScalar(.6),t.add(s)}return t}if("spot"===e.light.type){const t=new c.SpotLight(e.light.spot.color,e.light.spot.intensity,Math.max(e.light.spot.distance,0),e.light.spot.angle,e.light.spot.penumbra,e.light.spot.decay);if(t.castShadow=e.light.spot.castShadow??!0,t.userData.volumetricIntensity=e.light.spot.volumetricIntensity,t.map=await this.loadSpotLightMap(e.light.spot.mapTextureId),t.target=new x,t.target.position.set(0,-1,0),t.add(t.target),this.inEditor){const e=(new c.TextureLoader).load("assets/light-bulb-icon.webp"),a=new c.SpriteMaterial({map:e,alphaTest:.5}),s=new qt(a);s.scale.multiplyScalar(.6),t.add(s),t.add(new c.SpotLightHelper(t))}return t}if("rectArea"===e.light.type){const t=new c.RectAreaLight(e.light.rectArea.color,e.light.rectArea.intensity,e.scale?e.scale[0]:1,e.scale?e.scale[1]:1);if(this.inEditor){const e=(new c.TextureLoader).load("assets/light-bulb-icon.webp"),a=new c.SpriteMaterial({map:e,alphaTest:.5}),s=new qt(a);s.scale.multiplyScalar(.6),t.add(s);const r=new Kt(t);t.add(r)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional,e),new g):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient,e),new g):void 0}async loadSpotLightMap(e){if(null==e)return null;const t=this.assets.get(e);return null==t||"texture"!==t.type?null:await this.assetManagerService.getTexture(t)}applyDirectionalAmbientLight(e,t,a){const s=this.scene.children.find(e=>e.name===kt);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){this.renderingView.csm.lightIntensity=e.intensity;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(e){for(const e of this.landscapeManagers)e.stop();if(this.landscapeManagers.length=0,this.latticeGeometries.dispose(),this.editorStaticDisposed=!0,this.disposeEditorStaticDrawSet(),this.editorStaticEditingObjects.clear(),this.editorStaticSelectedObjects.clear(),this.editorStaticObjectsToRebuild.clear(),this.editorStaticDrawSetUpdated$.complete(),this.experimentalStaticDrawSetDisposer?.(),this.experimentalStaticDrawSetDisposer=void 0,this.removePrefabEventGraphs(),this.livePrefabInstances.clear(),this.updateSubscription.unsubscribe(),this.createAssetSubscription.unsubscribe(),this.disposePaintedScatterManager(),this.disposeSurfaceScatterManager(),this.sceneSettingsActive){this.worldEnvironmentRequest++,this.renderingView.setWorldEnvironment(null),this.renderingView.configureAmbientOcclusion(!1),this.renderingView.setBaseToneMapping(c.NoToneMapping,1),this.scene.fog=this.originalFog;const e=this.renderingView.csm,t=this.originalGlobalLight;if(null!=e&&null!=t){e.lightDirection.copy(t.direction),e.lightIntensity=t.intensity;for(let a=0;a<e.lights.length&&a<t.lights.length;a++){const s=e.lights[a],r=t.lights[a];s.intensity=r.intensity,s.color.copy(r.color),s.castShadow=r.castShadow,s.userData.src=r.src,s.userData.volumetricIntensity=r.volumetricIntensity}}this.sceneSettingsActive=!1}this.materializedActors.forEach(t=>{e?.has(t)||t.disposed.next(!0)}),this.materializedActors.clear()}announcePrefabEventGraphs(e){for(const[t,a]of this.materializedPrefabEventGraphs)(null==e||t===e||t.startsWith(e+"/"))&&(this.announcedPrefabEventGraphs.has(t)||(this.announcedPrefabEventGraphs.add(t),this.prefabEventGraphAdded$.next(a)))}removePrefabEventGraphs(e){const t=[];for(const[a,s]of[...this.materializedPrefabEventGraphs])(null==e||a===e||a.startsWith(e+"/"))&&(t.push(s),this.prefabEventGraphRemoved$.next(s),this.materializedPrefabEventGraphs.delete(a),this.announcedPrefabEventGraphs.delete(a));return t}};da=e([ge(),t("design:paramtypes",[I,Object,dt,ut,Te,Array,Array,Object,Array])],da);export{da as SceneMaterializer};function ha(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse(e=>{e.castShadow=t,e.receiveShadow=a})}const pa=new Map,fa=new Map,ma=new b({color:16711935}),ga=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){if(null==e||null==e.material)return console.error("Asset or asset material is null",e),ma;const n=JSON.stringify(e.material)+t?._id,o=i&&!("shaderGraph"===e.material.type&&"asset"===e.material.shaderGraph?.source);if(o&&pa.has(n))return pa.get(n);if(o&&fa.has(n))return await fa.get(n);const l=_materialFromAsset(n,e,t,a,s,r,o);return o?fa.set(n,l).get(n):l}export async function _materialFromAsset(e,t,a,s,r,i,o=!0){const l={opacity:t.material.params?.opacity??1,map:null,emissive:t.material.params?.emissive??null,metalness:t.material.params?.metalness??0,flatShading:t.material.params?.flatShading??!1,color:new h(t.material.params?.color),transparent:null!=t.material.params?.opacity&&t.material.params?.opacity<1},u={};if(null!=t.material.params?.map){const e=t.material.params.map,a=await s.getAsset(e);null!=a&&(l.map=await r.getTexture(a))}let d,p,f;switch(t.material.type){case"phong":d=new v({...l,...u});break;case"water":d=xt(l,a);break;case"grassFoliage":d=St({color:l.color,map:l.map},a);break;case"grass":d=bt({...l,colorTwo:new h(t.material.params.colorTwo),colorThree:new h(t.material.params.colorThree)},a);break;case"shaderGraph":{const e=await async function(e,t){const a=e.material?.shaderGraph;if("local"===a?.source)return a.graph;if("asset"===a?.source){const e=await t.getAsset(a.assetId);return e?.shaderGraph??null}return e.shaderGraph??null}(t,s);if(null==e){console.warn("Missing shader graph for material "+t.name),d=ma;break}"surface"===e.target&&null!=e.materialOptions?.side&&(p=ia(e.materialOptions.side)),"decal"===e.target?f=!1:null!=e.materialOptions?.transparent&&(f=e.materialOptions.transparent);try{const n=await prepareShaderGraphParameters(t.material?.shaderParams??{},e,s,r,a,i),o=t.shaderGraphPreviewNodeId,l=t.trailBillboard;d=ra(e,{parameters:n,previewNodeId:o,trailBillboard:l,alphaTest:t.material.alphaTest}),d.userData.customShaderName="asset"===t.material.shaderGraph?.source?`shaderGraph:${t.material.shaderGraph.assetId}`:`shaderGraph:${t.id}`}catch(e){console.warn("Shader graph runtime error: "+e,e),d=ma}break}case"standard":case"unlit":case"toon":case"layered":case"lambert":case"shader":case"landscape":case"landscape-composite":case"decal-unlit":case"decal-standard":case"sprite":const e={standard:ca?Fe:_e,lambert:Fe,unlit:Ge,toon:Jt,layered:_t,landscape:We,"landscape-composite":Re,"decal-unlit":Nt,"decal-standard":zt,sprite:n}[t.material.type]??i.find(e=>e.name==t.material.shader)?.type;if(e){try{let n=new e;const o=await prepareClassParameters(t.material?.shaderParams??{},e,s,r,null,a,i,void 0,void 0,n);Object.assign(n,o),n.alphaTest=t.material.alphaTest??n.alphaTest,d=n.build()}catch(e){console.log("Shader runtime error: "+e,e),ga.has(t.material.shader)||ga.set(t.material.shader,ma.clone()),d=ga.get(t.material.shader)}d.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),d=ma;break;default:throw new Error("Unsupported material type "+t.material.type)}if(a?.csm.setupMaterial(d),d.side=p??t.material.side??d.side??c.FrontSide,d.transparent=(f??t.material.transparent??l.transparent??!1)||d.transparent,d.alphaTest=t.material.alphaTest??d.alphaTest??0,d.userData.receiveDecals=t.material.receiveDecals??!0,null!=t.material.blending&&(d.blending=Ee[t.material.blending]??c.NormalBlending),!0===t.material.transparent&&(d.depthWrite=!1),t.material.bloom&&(d.userData.hasBloom=!0),t.material.reflective&&(d.userData.reflective=!0),!0===t.material.outlines&&(d.userData.outlineParameters={},null!=t.material.outlineParams&&(null!=t.material.outlineParams.color&&(d.userData.outlineParameters.color=new h(t.material.outlineParams.color).toArray()),null!=t.material.outlineParams.thickness&&(d.userData.outlineParameters.thickness=t.material.outlineParams.thickness),null!=t.material.outlineParams.opacity&&(d.userData.outlineParameters.alpha=t.material.outlineParams.opacity),null!=t.material.outlineParams.colorMode&&(d.userData.outlineParameters.colorMode=t.material.outlineParams.colorMode),null!=t.material.outlineParams.darkening&&(d.userData.outlineParameters.darkening=t.material.outlineParams.darkening))),null!=t.material.surfaceAssetId&&""!==t.material.surfaceAssetId){const e=await materializeDataAssetRef(t.material.surfaceAssetId,s,r,void 0,a,i);null!=e&&(d.userData.surface=e.value)}return d.userData.assetId=t.id,o&&null!=a&&pa.set(e,d),o&&fa.delete(e),d}export function prepareCustomParamsFromShaderGraph(e,t={}){return Object.fromEntries((e.parameters??[]).map(e=>{const a=function(e){switch(e){case"float":return jt.FloatNode;case"boolean":return jt.BooleanNode;case"texture":return jt.Sampler2DNode;case"vec2":return jt.Vec2Node;case"vec3":return jt.Vec3Node;case"vec4":return jt.Vec4Node;case"color":return jt.RgbNode}}(e.type),s=t[e.name],r=s?.override??null!=s,i=void 0!==e.defaultValue?e.defaultValue:customParameterDefaultValueByType.get(a),n=!1===r?_a(i):s?.value??_a(i);return[e.name,{type:a,value:n,override:r}]}))}export async function prepareShaderGraphParameters(e,t,a,s,i,n,o=!1){const l={},c=prepareCustomParamsFromShaderGraph(t,e),u=Object.entries(c),d=await Promise.all(u.map(([e,t])=>{if(o&&t.type===jt.FloatNode){const a=t.value,s=e=>"string"==typeof e?parseFloat(e):Number(e);if(null!=a&&"object"==typeof a&&"a"in a&&"b"in a)return null==a.a?null:r(e,s(a.a),null==a.b?void 0:s(a.b),"easing"in a?String(a.easing):void 0);if(null!=a&&""!==a)return r(e,s(a))}return wa(e,t,a,s,null,i,n)}));for(let e=0;e<u.length;e++){const[t]=u[e],a=d[e];null!=a&&(l[t]=a)}return l}export async function prepareClassParameters(e,t,a,s,r,i,n,o,l,c){const u={},{params:d,skipped:h}=It(e,{parameterType:t,parameterTarget:c,extractPropertyParameters:Le,toSerializedParamType:toSerializedParamType});for(const e of h)console.warn(`Skipping stored parameter "${e.key}" because it could not be converted from ${jt[e.sourceType]} to ${jt[e.targetType]}`);for(const[e,t]of Object.entries(d)){if(!1===t.override)continue;const c=await wa(e,t,a,s,r,i,n,o,void 0,void 0,l);null!=c&&(u[e]=c)}return u}export async function prepareShapeParameters(e,t,a){const s={};for(const[r,i]of Object.entries(e)){const e=await wa(r,i,t,a,null,void 0,void 0,void 0,void 0,void 0);null!=e&&(s[r]=e)}return s}const ya=new Map;async function wa(e,t,a,s,r,i,n,o,l=t.value,c=t.type,u,d=(t.type===jt.Struct?t.struct:void 0)){if(null==t||null==l||""===l)return null;switch(c){case jt.Array:if(Array.isArray(l)&&"element"in t)return await Promise.all(l.map(l=>wa(e,t,a,s,r,i,n,o,l,t.element,u,t.elementStruct)));break;case jt.Number:case jt.FloatNode:let f;if("string"==typeof l?f=parseFloat(l):"number"==typeof l&&(f=l),c===jt.FloatNode){if("object"==typeof l&&"a"in l&&"b"in l){const t=l;if(null==t.a)return null;const a="string"==typeof t.a?parseFloat(t.a):t.a;if(null==t.b)return a;const s="string"==typeof t.b?parseFloat(t.b):t.b,r=function(e){let t=ya.get(e);return null==t&&(t=Ne(Vt.decode(e)),ya.set(e,t)),t}(t.easing),i=r.sample(ze($e.energy)),n=new re(Ke(e)+"_curveEndpoints",new C(a,s),void 0,!1);return L(n.x,n.y,i)}return new ae(Ke(e),f,void 0,!1)}return f;case jt.Texture:let m=await s.getTexture(await a.getAsset(l));return"envmap"===e.toLowerCase()&&null!=i&&(m=i.getEnvTexture(m)),m;case jt.Sampler2DNode:const g=await a.getAsset(l);if(null!=g?.texture?.textureArrayFileKey){const{texture:t,layerIndex:a}=await s.getTextureArray(g);if(t&&null!=a)return new se(null,t,new ae(Ke(e)+"_i",a,void 0,!1))}const y=await s.getTexture(g);return y?K(y):null;case jt.Boolean:return l;case jt.BooleanNode:return new te(Ke(e),l,void 0,!1);case jt.Vector2:case jt.Vec2Node:if("object"==typeof l){const t=l instanceof Array?(new C).fromArray(l):new C(l.x,l.y);return c===jt.Vec2Node?new re(Ke(e),t,void 0,!1):t}return null;case jt.Vector3:case jt.Vec3Node:if("object"==typeof l){const t=l instanceof Array?(new O).fromArray(l):new O(l.x,l.y,l.z);return c===jt.Vec3Node?new ie(Ke(e),t,void 0,!1):t}return null;case jt.Vector4:case jt.Vec4Node:if("object"==typeof l){const t=l instanceof Array?(new E).fromArray(l):new E(l.x,l.y,l.z,l.w);return c===jt.Vec4Node?new ne(Ke(e),t,void 0,!1):t}return null;case jt.Color:case jt.RgbNode:const w=new h(l);return c===jt.RgbNode?new ie(Ke(e),new O(w.r,w.g,w.b),void 0,!1).rgb:w;case jt.String:return l;case jt.Scene:return"string"==typeof l?new Me(l):"object"==typeof l&&null!=l&&"string"==typeof l.id?new Me(l.id,"string"==typeof l.name?l.name:void 0):null;case jt.ModelRef:return"string"==typeof l?new Ae(l):null;case jt.BaseActor:const S=l;if(null==r&&console.warn("Class parameters can not be prepared as actors are not passed in"),null==S)return null;if("object"==typeof S&&null!=S.type&&null!=S.id){if("actor"===S.type)return r?.get(S.id)??null;if("prefab"===S.type){const e=u?u(S.id):null;if(null!=e)return r?.get(e)??null;const t=[];for(const[e,a]of r?.entries()??[])e.startsWith(S.id+"/")&&t.push(a);return 1===t.length?t[0]:null}}if("string"==typeof S){const e=r?.get(S);if(null!=e)return e;const t=u?u(S):null;if(null!=t)return r?.get(t)??null;const a=[];for(const[e,t]of r?.entries()??[])e.startsWith(S+"/")&&a.push(t);return 1===a.length?a[0]:null}return null;case jt.Euler:const b=l;return(new p).fromArray(b);case jt.Object3D:{const e=await a.getAsset(l),t=(await s.getMesh(e,{applyMaterials:!0,rescale:!0,mergeGeomtries:!0})).scene;return t.userData.vfxIncludeRootTransform=!0,t}case jt.Material:{if(null==l)return null;const e=await a.getAsset(l);if(null==e)return console.warn("Material asset not found for material parameter",l),null;if("shaderGraph"===e.type&&null!=e.shaderGraph){const t=`shaderGraphParameter:${e.id}:${JSON.stringify(e.shaderGraph)}:${i?._id??"none"}`,r=pa.get(t);if(null!=r)return r;const o=await prepareShaderGraphParameters({},e.shaderGraph,a,s,i,n),l=ra(e.shaderGraph,{parameters:o});return l.userData.assetId=e.id,l.userData.assetName=e.name,pa.set(t,l),l}return null==e.material?(console.warn("Using a non-material asset for material parameter"),null):await materialFromAsset(e,i,a,s,n)}case jt.AudioBuffer:return await s.getAudio(await a.getAsset(l));case jt.VisualEffect:const v=await a.getAsset(l);if(null==o){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in v)return new we(o,v);console.error("Using a non-vfx asset for visual effect parameter");break;case jt.Prefab:{const e=await a.getAsset(l);return null==e?(console.error("Using a non-prefab asset for prefab parameter",l),null):new Se(e)}case jt.PrefabActor:{const e=await a.getAsset(l);return null==e?(console.error("Using a non-prefab asset for prefab parameter",l),null):new be(new Se(e))}case jt.DataAsset:return materializeDataAssetRef(l,a,s,r,i,n,o,u);case jt.Sequence:{if("string"!=typeof l)return console.warn("Invalid sequence parameter value",l),null;const e=await a.getAsset(l);if("sequence"===e?.type&&"sequence"in e)return new aa(e.sequence);console.error("Using a non-sequence asset for sequence parameter");break}case jt.SequenceData:return ta(l)?l:(console.warn("Invalid inline sequence data parameter value",l),null);case jt.Struct:return async function(e,t,a,s,r,i,n,o,l){const c=Sa(e),u=c?.struct??t;if(null==u)return console.warn("Missing parameter definition id for struct parameter"),null;const d=Ye(u);if(null==d)return console.warn(`Unknown parameter definition "${u}"`),null;if(He(u))return console.warn(`Can not instantiate abstract parameter definition "${u}"`),null;if(null!=t&&u!==t&&!Xe(u,t))return console.warn(`Parameter definition "${u}" is not assignable to "${t}"`),null;let h;try{h=new d}catch(e){return console.warn(`Failed to instantiate parameter definition "${u}"`,e),null}const p=function(e){const t=Sa(e);if(null!=t)return t.value;if(ba(e))return e;if(null!=e&&"object"==typeof e&&ba(e.params))return e.params;return{}}(c?.value??e),f=await prepareClassParameters(p,null,a,s,r,i,n,o,l,h);return Object.assign(h,f),h}(l,d,a,s,r,i,n,o,u);case jt.Curve:return Vt.decode(l);case jt.ColorLayer:case jt.MaskLayer:if(Gt(l)){const e=await Ut.decode(l,async e=>await s.getTexture(await a.getAsset(e))),t=await prepareClassParameters(l.params,null,a,s,void 0,void 0,void 0,void 0,void 0,e);return Object.assign(e,t),e}return console.warn("Expecting color layer but got",l),null;case jt.AnimationClip:{const e="string"==typeof l?l:"object"==typeof l&&null!=l?l.assetId:null;if(null==e)return console.warn("Invalid animation clip asset id value",l),null;return await s.getAnimationClip(await a.getAsset(e))}}return null}export async function materializeDataAssetRef(e,t,a,s,r,i,n,l){const c="string"==typeof e?e:null!=e&&"object"==typeof e?e.assetId??e.id:null;if(null==c||""===c)return null;const u=await t.getAsset(c);if(null==u)return console.warn(`Data asset "${c}" was not found`),null;if("data"!==u.type||null==u.dataAsset)return console.warn("Using a non-data asset for data asset parameter",c),null;const d=u.dataAsset.definition;if(null==d||""===d)return console.warn(`Missing data asset definition id for asset "${u.id}"`),null;if(Qe(d))return console.warn(`Can not instantiate abstract data asset definition "${d}"`),null;const h=qe(d);if(null==h)return console.warn(`Unknown data asset definition "${d}"`),null;let p;try{p=new h}catch(e){return console.warn(`Failed to instantiate data asset definition "${d}"`,e),null}const f=u.dataAsset.params??{};if("object"!=typeof f||Array.isArray(f))return console.warn(`Invalid data asset params for asset "${u.id}"`),null;try{const e=await prepareClassParameters(f,null,t,a,s,r,i,n,l,p);Object.assign(p,e)}catch(e){return console.warn(`Failed to materialize data asset "${u.id}"`,e),null}const m=t.supportsLiveDataAssets?new o(e=>{let o=0;const c=t.onUpdate.subscribe(c=>{if(c.id!==u.id||"data"!==c.type)return;const d=++o;materializeDataAssetRef(u.id,t,a,s,r,i,n,l).then(t=>{e.closed||d!==o||null==t||e.next(t)}).catch(e=>console.warn(`Failed to reload data asset "${u.id}"`,e))});return()=>c.unsubscribe()}):void 0;return new ve(u,p,m)}function Sa(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.struct&&ba(e.value)?e:null}function ba(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&Object.values(e).every(e=>null!=e&&"object"==typeof e&&"type"in e)}function va(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 Ma(){}const Aa=new WeakMap;function xa(e,t){if(t)return e.userData.hologyEditorMatrixWorldAutoUpdate=!0,void e.traverse(e=>{const t=Aa.get(e);if(null!=t){e.updateMatrixWorld=t.updateMatrixWorld;for(const[e,a]of t.matrixAutoUpdate)e.matrixAutoUpdate=a}});const a=!0===e.userData.hologyEditorMatrixWorldAutoUpdate,s=[];e.traverse(e=>{Aa.has(e)&&s.push(e)}),0!==s.length||a||s.push(e);for(const e of s)ja(e);delete e.userData.hologyEditorMatrixWorldAutoUpdate}function ja(e){const t=Aa.get(e);if(e.updateMatrix(),e.updateWorldMatrix(!0,!0),null==t){const t=new Map;e.traverse(e=>{t.set(e,e.matrixAutoUpdate)}),Aa.set(e,{updateMatrixWorld:e.updateMatrixWorld,matrixAutoUpdate:t})}e.traverse(e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1}),e.updateMatrixWorld=Ma}function Pa(e,t=!1){return Array.isArray(e)?e.every(e=>Pa(e,t)):t||!e.transparent&&!Ia(e)}function Ia(e){return e instanceof q&&(null!=e.uniforms[oa]||null!=e.uniforms.hology_scene_map)}function Da(e){return"linear"===e.type?new f(new h(e.color),e.near??100,e.far??1e3):"density"===e.type?new m(e.color,e.density):void console.warn("Invalid fog type",e)}const Ca=new O,Oa=new P,Ea=new O;new M({color:4229780});async function ka(e,t,a,s){null==s&&(s=(new w).identity());const r=s.clone().multiply(Ta(e,new c.Matrix4));if(null!=e.children&&e.children.length>0)for(let a=e.children.length-1;a>=0;a--)await ka(e.children[a],t,e,r);await t(e,a,s)}function Ta(e,t){return null==e.position||null==e.rotation||null==e.scale?t.identity():t.compose((new O).fromArray(e.position),(new P).setFromEuler((new p).fromArray(e.rotation)),(new O).fromArray(e.scale))}export function toSerializedParamType(e){if(null==e)return;const t=e.constructor.prototype;return t instanceof Number||e===Number?jt.Number:t instanceof _||"function"==typeof e.prototype.isFloat?jt.FloatNode:t instanceof D||e===D||e.isTexture?jt.Texture:t instanceof Ue||e===Ue||e===X||"function"==typeof e.prototype?.isSampler2D||!0===e.prototype?.isSampler2D?jt.Sampler2DNode:t instanceof Boolean||e===Boolean?jt.Boolean:t instanceof U?jt.BooleanNode:t instanceof h||e==h?jt.Color:t instanceof Q||"function"==typeof e.prototype.isRgb?jt.RgbNode:t instanceof C||e==C?jt.Vector2:t instanceof de||"function"==typeof e.prototype.isVec2?jt.Vec2Node:t instanceof O||e==O?jt.Vector3:t instanceof pe||"function"==typeof e.prototype.isVec3?jt.Vec3Node:t instanceof E||e==E?jt.Vector4:t instanceof me||"function"==typeof e.prototype.isVec4?jt.Vec4Node:t instanceof String||e===String?jt.String:t instanceof Me||e===Me?jt.Scene:t instanceof Ae||e===Ae?jt.ModelRef:t instanceof xe||e==xe||e.prototype instanceof xe||e.prototype==xe?jt.BaseActor:t instanceof p||e==p?jt.Euler:t instanceof x||e==x?jt.Object3D:t instanceof y||e==y?jt.Material:t instanceof AudioBuffer||e==AudioBuffer?jt.AudioBuffer:t instanceof we||e==we?jt.VisualEffect:t instanceof Se||e==Se?jt.Prefab:t instanceof be||e==be?jt.PrefabActor:t instanceof ve||e==ve?jt.DataAsset:t instanceof Vt||e==Vt?jt.Curve:t instanceof Ut||e==Ut?jt.ColorLayer:t instanceof Wt||e==Wt?jt.MaskLayer:t instanceof c.AnimationClip||e==c.AnimationClip?jt.AnimationClip:t instanceof aa||e==aa?jt.Sequence:"SequenceData"===e.name||e.prototype&&"tracks"in e.prototype?jt.SequenceData:null!=Je(e)?jt.Struct:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function getCustomParamTypeInfo(e){const t=e.type===Object?void 0:toSerializedParamType(e.type),a=t===jt.Struct?Je(e.type):void 0;return!0===e.options.array?{type:jt.Array,element:t,...null!=a?{elementStruct:a}:{}}:{type:t,...null!=a?{struct:a}:{}}}export function prepareCustomParams(e,t,a={},s={}){return Object.fromEntries(e.map(e=>{const r=getCustomParamTypeInfo(e);let i=r;const n=t[e.name],o=Ba(n)?n:void 0,l=!0===s.treatAllAsOptional||!0===e.options.optional,c=s.missingOverrideDefaultsToOverride??!0;let u=o?.override;void 0===u&&null!=n&&l&&c&&(u=!0),void 0===u&&l&&(u=!1);const d=void 0!==a[e.name]||void 0!==e.options.defaultValue,h=function(e,t){if(null==e.type){const a=function(e){return ta(e)?{type:jt.SequenceData}:void 0}(t);null!=a&&(e=a)}if(e.type!==jt.Struct)return{typeInfo:e,value:t};const a=Sa(t);if(null==a)return{typeInfo:e,value:t};return{typeInfo:{...e,struct:a.struct},value:a.value}}(i,function(e,t){if(void 0!==t[e.name])return t[e.name];if(void 0!==e.options.defaultValue){const t=serializeCustomParameter(e.type,e.options.defaultValue);return void 0!==t?t:e.options.defaultValue}const a=toSerializedParamType(e.type);if(a===jt.Struct)return He(e.type)?{}:prepareCustomParamsFromType(e.type,{});return customParameterDefaultValueByType.get(a)}(e,a)),p=function(e,t){if(Ba(e))return e;if(null!=e&&"object"==typeof e&&!Array.isArray(e)&&"value"in e){const a=e;return{...t,value:a.value,..."boolean"==typeof a.override?{override:a.override}:{}}}if(t.type!==jt.SequenceData||!ta(e))return;return{type:jt.SequenceData,value:e}}(n,h.typeInfo);i=function(e,t,a){if(e.type!==jt.Struct||a?.type!==jt.Struct||null==a.struct)return e;const s=t.struct??e.struct;if(null==s||a.struct===s||Xe(a.struct,s)||null==Ye(a.struct))return{...e,struct:a.struct};return e}(h.typeInfo,r,p);const f=!1!==u||e.options.array?p?.value??function(e,t,a){if(!0===e.options.array)return a?_a(t):[];return _a(t)}(e,h.value,d):_a(h.value),m=function(e,t,a){if(t.type===jt.Struct){if(null!=t.struct&&He(t.struct))return a;const s=null!=t.struct?Ye(t.struct):e.type;return null!=s&&ba(a)?prepareCustomParamsFromType(s,a):a}if(t.type!==jt.Array||t.element!==jt.Struct||!Array.isArray(a))return a;const s=null!=t.elementStruct?Ye(t.elementStruct):e.type;return a.map(e=>{const a=Sa(e),r=a?.struct??t.elementStruct;if(null!=r&&He(r))return e;const i=null!=a?Ye(a.struct):s,n=a?.value??(ba(e)?e:null);if(null==i||null==n)return e;const o=prepareCustomParamsFromType(i,n);return null!=a?{struct:a.struct,value:o}:o})}(e,i,f);return[e.name,{...i,value:m,override:u}]}))}function Ba(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"number"==typeof e.type&&"value"in e}function Va(e){const t=new Map,a=e=>{for(const s of e)"actor"===s.type&&null!=s.actor&&t.set(s.id,s.actor),null!=s.children&&a(s.children)};return a(e),t}function Na(e){const t=new Map,a=e=>{for(const s of e)"prefab"===s.type&&t.set(s.id,s),null!=s.children&&a(s.children)};return a(e),t}function za(e,t,a){if(!a||"prefab"!==t?.type||null==t.prefab)return e;const s=new Map((e.innerParams??[]).map(e=>[JSON.stringify(e.path),{path:e.path,params:{...e.params}}]));for(const e of t.prefab.innerParams??[]){const t=JSON.stringify(e.path),a=s.get(t);s.set(t,{path:e.path,params:{...a?.params??{},...Fa(e.params)}})}return{...e,params:{...e.params??{},...Fa(t.prefab.params)},innerParams:[...s.values()]}}function $a(e,t,a){const s=new Map((e.innerParams??[]).map(e=>[JSON.stringify(e.path),e])),r=new Map((t.innerParams??[]).map(e=>[JSON.stringify(e.path),e])),i=new Map((a.innerParams??[]).map(e=>[JSON.stringify(e.path),e])),n=[];for(const e of new Set([...s.keys(),...r.keys(),...i.keys()])){const t=s.get(e),a=r.get(e),o=i.get(e),l=Ua(t?.params??{},a?.params??{},o?.params??{});Object.keys(l).length>0&&n.push({path:a?.path??o?.path??t.path,params:l})}return{...t,params:Ua(e.params??{},t.params??{},a.params??{}),innerParams:n}}function Ua(e,t,a){const s={};for(const r of new Set([...Object.keys(e),...Object.keys(t),...Object.keys(a)]))JSON.stringify(a[r])!==JSON.stringify(e[r])?null!=a[r]&&(s[r]=a[r]):null!=t[r]&&(s[r]=t[r]);return s}function Fa(e){return null==e?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>function(e){return!0===e?.override}(e)))}function Ra(e,t){return e.length>=t.length&&t.every((t,a)=>e[a]===t)}export function prepareCustomParamsFromType(e,t,a=null,s={}){const r=Le(e);if(0===r.length)return{};let i;null!=a?ke(a,()=>{i=a.get(e)}):i=new e;const n={};for(const e of r){const t=i[e.name];if(null!=t){const a=Wa(e,t);void 0!==a&&(n[e.name]=a)}}return prepareCustomParams(r,t,n,s)}function Wa(e,t){return!0===e.options.array?Array.isArray(t)?t.map(t=>serializeCustomParameter(e.type,t)??t):[]:serializeCustomParameter(e.type,t)}function _a(e){return null==e?e:Array.isArray(e)?e.map(e=>_a(e)):"object"==typeof e?"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e)):e}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 C:return t instanceof C?t.toArray():void a();case O:return t instanceof O?t.toArray():void a();case E:return t instanceof E?t.toArray():void a();case h:return t instanceof h?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new h(t).getHexString():void a();case String:return t;case p:return t instanceof p?t.toArray():void a();case Se:return t instanceof Se?t.asset?.id??null:void a();case ve:return t instanceof ve?t.id:"string"==typeof t?t:void a();case Me:return t instanceof Me?{id:t.id,...null!=t.name?{name:t.name}:{}}:void a();case Ae:return t instanceof Ae?t.id:"string"==typeof t?t:void a()}const s=Je(e);if(null!=s){const r=Sa(t);if(null!=r)return r.struct===s?r.value:r;const i=function(e,t){if(null==t||"object"!=typeof t)return e;const a=t.constructor;return null!=Je(a)&&Ze(a,e)?a:e}(e,t),n=Je(i),o=function(e,t){if(null==t)return null;if(ba(t))return t;if(null!=t&&"object"==typeof t&&ba(t.params))return t.params;if("object"!=typeof t)return;const a=Le(e),s={};for(const e of a){const a=t[e.name];if(void 0===a)continue;const r=Wa(e,a);void 0!==r&&(s[e.name]=r)}return prepareCustomParams(a,{},s)}(i,t);return void 0!==o?null!=o&&null!=n&&n!==s?{struct:n,value:o}:o:void a()}if(ta(t))return t}function Ga(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=>La(e.materialId)),(t??[]).filter(e=>La(e.materialId)),e=>e.name?`name:${e.name}`:`color:${e.color}`)}function La(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[jt.RgbNode,"#000000"],[jt.Color,"#000000"],[jt.String,""],[jt.Scene,null],[jt.ModelRef,null],[jt.Vector4,[0,0,0,0]],[jt.Vec4Node,[0,0,0,0]],[jt.Vector3,[0,0,0]],[jt.Vec3Node,[0,0,0]],[jt.Vector2,[0,0]],[jt.Vec2Node,[0,0]],[jt.Euler,[0,0,0,"XYZ"]],[jt.Array,[]],[jt.DataAsset,null],[jt.SequenceData,ea()],[jt.ColorLayer,Ft],[jt.MaskLayer,Rt]]);let qa=new h;new h;function Ja(e){return null==e?.color?null:(qa.set(e.color),"#"+qa.getHexString())}function Ya(e,t,a,s){const r="string"==typeof t.name&&""!==t.name?t.name:null;if(null!=r)return e.name===r||s===r;const i=Ja(e);return null!=i&&(i===t.color||a===t.color)}export function applyMaterial(e,t,a,s,r={}){const i=[];return e.traverse(async e=>{if(e instanceof S||e.isMesh||e instanceof c.SkinnedMesh||e.isSkinnedMesh)for(const t of st(e.material))t.hasOwnProperty("color")&&i.push(e)}),Promise.all(i.map(async e=>{if(e.material instanceof Array)for(let i=0;i<e.material.length;i++){const n=e.material[i];if(null==n.color||!(n.color instanceof h))continue;const o=Ja(n),l=n.name;if(Ya(n,t,e.userData["originalColor_"+i],e.userData["originalMaterialName_"+i])){const n=Ha(await a(t.materialId),r.textureFlipY),c=e.material[i];null!=n&&c.id!=n.id&&(e.material[i]=n,e.userData["originalColor_"+i]=e.userData["originalColor_"+i]??o,e.userData["originalMaterialName_"+i]=e.userData["originalMaterialName_"+i]??l,null!=s&&s.set(e.id+"#"+i,c))}}else if("color"in e.material){const i=e.material,n=Ja(i),o=i.name;if(Ya(i,t,e.userData.originalColor,e.userData.originalMaterialName)){const i=Ha(await a(t.materialId),r.textureFlipY),l=e.material;null!=i&&(e.material=i,e.userData.originalColor=e.userData.originalColor??n,e.userData.originalMaterialName=e.userData.originalMaterialName??o,null!=s&&(s.has(e.id)||s.set(e.id,l)))}}}))}const Qa=new WeakMap;export function getConvertedFbxToGlbAssignedMaterialTextureFlipY(e){const t=e?.mesh?.uvConversion;return"fbx2gltf"===t?.source?!0!==t.flipV&&void 0:!function(e){return"glb"===e?.fileFormat&&!0===e.originalFileKey?.toLowerCase().endsWith(".fbx")}(e)&&void 0}function Ha(e,t){if(null==e||null==t||!function(e,t){return function(e){const t=[];for(const[a,s]of Object.entries(e))Xa(a,s)&&t.push(s);if(e instanceof c.ShaderMaterial)for(const[a,s]of Object.entries(e.uniforms))Xa(a,s.value)&&t.push(s.value);return t}(e).some(e=>e.flipY!==t)}(e,t))return e;let a=Qa.get(e);null==a&&(a=new Map,Qa.set(e,a));const s=a.get(t);if(null!=s)return s;const r=Za(e);if(function(e,t){for(const a of Object.keys(e)){const s=e[a];Xa(a,s)&&(e[a]=Ka(s,t))}}(r,t),r instanceof c.ShaderMaterial){for(const[e,a]of Object.entries(r.uniforms))Xa(e,a.value)&&(a.value=Ka(a.value,t));r.uniformsNeedUpdate=!0}return r.needsUpdate=!0,a.set(t,r),r}function Za(e){const t=e.clone();return t.userData={...e.userData??{}},t}function Xa(e,t){const a=t;return(t instanceof D||!0===a?.isTexture)&&!e.toLowerCase().includes("envmap")&&!0!==a.isCompressedTexture&&!0!==a.isCompressedArrayTexture}function Ka(e,t){if(e.flipY===t)return e;const a=e.clone();return a.flipY=t,a.userData={...e.userData??{}},a.needsUpdate=!0,a}function es(e,t){if(e instanceof c.ShaderMaterial&&t instanceof c.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof c.ShaderMaterial&&t instanceof c.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 ts(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}function as(e,t){const a=nt(e);return null==a?"":function(e,t){const a=Es(e,t),s=a.sort().map(t=>{const a=e.getAttribute(t);if(null!=a){const e=a.array??a.data?.array,s=e?.constructor?.name??"";return`${t}:${a.itemSize}:${a.normalized?1:0}:${s}`}const s=function(e,t){if("uv"===t&&ns(e))return{itemSize:2,normalized:!1,arrayType:"Float32Array"};throw new Error(`Unsupported synthetic batching geometry attribute: ${t}`)}(e,t);return`${t}:${s.itemSize}:${s.normalized?1:0}:${s.arrayType}`}).join(",");return`${null!=e.index?"indexed":"nonindexed"}|${s}`}(a.geometry,t)}function ss(e,t){const a=Es(e,t);if(a.length===Object.keys(e.attributes).length)return e;const s=new d;s.name=e.name;const r=e.getIndex();null!=r&&s.setIndex(r);for(const t of a)s.setAttribute(t,is(e,t));for(const t of e.groups)s.addGroup(t.start,t.count,t.materialIndex);return s.setDrawRange(e.drawRange.start,e.drawRange.count),null!=e.boundingBox&&(s.boundingBox=e.boundingBox.clone()),null!=e.boundingSphere&&(s.boundingSphere=e.boundingSphere.clone()),s.userData=e.userData,s}const rs=new WeakMap;function is(e,t){return e.getAttribute(t)??function(e,t){if("uv"===t)return function(e){let t=rs.get(e);const a=e.getAttribute("position");if(null==a)throw new Error("Can not create synthetic batching UVs without a position attribute");null!=t&&t.count===a.count||(t=new c.Float32BufferAttribute(new Float32Array(2*a.count),2),rs.set(e,t));return t}(e);throw new Error(`Unsupported synthetic batching geometry attribute: ${t}`)}(e,t)}function ns(e){return null!=e.getAttribute("position")}const os=new WeakMap,ls="hbat_",cs=new Set(["ambientLightColor","cameraNear","directionalLightShadows","directionalLights","directionalShadowMap","directionalShadowMatrix","fogColor","fogDensity","fogFar","fogNear","hemisphereLights","lightProbe","ltc_1","ltc_2","pointLightShadows","pointLights","pointShadowMap","pointShadowMatrix","receiveShadow","rectAreaLights","shadowFar","spotLightMap","spotLightMatrix","spotLightShadows","spotLights","spotShadowMap"]);function us(e){let t=os.get(e);return null==t&&(t=function(e){let t=e.type;if(e instanceof q)t+=function(e){let t="nodeShader";t+=function(e){if(null==e)return"";let t="";for(const a of Object.keys(e).sort())t+=`${a}:${String(e[a])};`;return t}(e.defines),t+=e.lights?"lights":"",t+=e.fog?"fog":"";for(const a of Object.keys(e.uniforms).sort()){if(ps(a))continue;const s=e.uniforms[a]?.value;ms(s)||(t+=`u:${a}:${vs(s)};`)}return t+=hs(e.vertexShader),t+=hs(e.fragmentShader),t}(e);else if(e instanceof c.MeshStandardMaterial&&!(e instanceof c.MeshPhysicalMaterial)||(t+=e.id+""),(e instanceof c.MeshBasicMaterial||e instanceof c.MeshLambertMaterial||e instanceof M||e instanceof v)&&(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 M&&(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 c.MeshPhysicalMaterial&&(null!=e.sheenColorMap&&(t+="sc"+e.sheenColorMap?.id),null!=e.sheenRoughnessMap&&(t+="sr"+e.sheenRoughnessMap?.id)),(e instanceof b||e instanceof v)&&null!=e.specularMap&&(t+="s"+e.specularMap?.id),e instanceof c.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 Qt&&null!=e.heightMap&&(t+="h"+e.heightMap?.id),e instanceof c.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,t+=e.userData.outlineParameters.alpha,t+=e.userData.outlineParameters.colorMode,t+=e.userData.outlineParameters.darkening);return t+=`side:${e.side};shadowSide:${e.shadowSide??"auto"};`,t+=e.transparent?"t":"",t+=e.vertexColors?"vc":"",t+=e.depthWrite?"dw":"",t+=e.depthTest?"dt":"",t+=`alphaTest:${e.alphaTest>0};`,t}(e),os.set(e,t)),t}const ds=new Map;function hs(e){return ds.has(e)||ds.set(e,`shader_${ds.size}`),ds.get(e)}function ps(e){return cs.has(e)||e.startsWith("hology_")}function fs(e,t){return e instanceof q?e.uniforms[t]?.value:e[t]}function ms(e){return"number"==typeof e||e instanceof C||e instanceof O||e instanceof E||e instanceof h}function gs(e){return"number"==typeof e?1:e instanceof C?2:4}function ys(e,t){const a=e.replace(/[^A-Za-z0-9_]/g,"_");let s=ls+a;for(;t.has(s);)s=ls+s;return t.add(s),s}function ws(e,t){const a={};for(const[s,r]of Object.entries(e.uniforms))t.has(s)||(a[s]={value:r.value});return a}const Ss=new WeakMap;let bs=1;function vs(e){if(null==e)return"null";if(e instanceof D||!0===e?.isTexture)return`texture:${e.id}`;if(e instanceof c.Matrix3||e instanceof c.Matrix4)return e.toArray().join(",");if("boolean"==typeof e||"number"==typeof e||"string"==typeof e)return String(e);if(Array.isArray(e)&&e.every(e=>null==e||["boolean","number","string"].includes(typeof e)))return JSON.stringify(e);if("object"==typeof e){let t=Ss.get(e);return null==t&&(t=bs++,Ss.set(e,t)),`object:${t}`}return String(e)}function Ms(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 As=new w,xs=new p;function js(e,t){return xs.copy(e),xs.x*=-1,xs.y*=-1,xs.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(xs.y*=-1,xs.z*=-1),(new c.Matrix3).setFromMatrix4(As.makeRotationFromEuler(xs))}function Ps(e,t){switch(t){case 0:return e.x;case 1:return e.y;case 2:return e.z;case 3:return e.w}}const Is=new E;function Ds(e,t){return e===t||null==e==(null==t)&&("number"==typeof e&&"number"==typeof t?e===t||isNaN(e)&&isNaN(t):e instanceof c.Color&&t instanceof c.Color?e.r===t.r&&e.g===t.g&&e.b===t.b:e instanceof C&&t instanceof C?e.x===t.x&&e.y===t.y:e instanceof O&&t instanceof O?e.x===t.x&&e.y===t.y&&e.z===t.z:e instanceof E&&t instanceof E&&(e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w))}function Cs(e){const t=[];for(const[a,s]of Object.entries(e))s instanceof we?t.push(s):s instanceof Ie&&t.push(...Cs(s));return t}const Os=new WeakMap;function Es(e,t){const a=Object.keys(e.attributes).filter(a=>ks(e,t,a));return!e.hasAttribute("uv")&&ns(e)&&ks(e,t,"uv")&&a.push("uv"),a}function ks(e,t,a){return"position"===a||("uv"===a?function(e){if(e instanceof q)return Bs(e,"uv");if(e instanceof c.ShaderMaterial)return Vs(e.vertexShader,"uv");if(e instanceof Qt&&null!=e.heightMap)return!0;return Ts.some(t=>e[t]?.isTexture)}(t):t instanceof q?Bs(t,a):t instanceof c.ShaderMaterial?function(e,t){if("uv1"===t||"uv2"===t||"uv3"===t)return Vs(e.vertexShader,t);return!0}(t,a):"uv1"!==a&&(("color"!==a||!function(e){let t=Os.get(e);if(null!=t)return t;const a=e.getAttribute("color");if(null==a)t=!1;else{t=!0;for(let e=0;e<a.count;e++){for(let s=0;s<3;s++)if(1!==a.getComponent(e,s)){t=!1;break}if(!t)break}}return Os.set(e,t),t}(e))&&("uv2"!==a||(null!=t.lightMap||null!=t.aoMap))))}const Ts=["map","alphaMap","emissiveMap","normalMap","bumpMap","displacementMap","roughnessMap","metalnessMap","aoMap","specularMap","gradientMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","iridescenceMap","iridescenceThicknessMap","sheenColorMap","sheenRoughnessMap","transmissionMap","thicknessMap","anisotropyMap"];function Bs(e,t){return Vs(e.vertexShader,t)}function Vs(e,t){return new RegExp(`(^|[^A-Za-z0-9_])${a=t,a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}([^A-Za-z0-9_]|$)`).test(e);var a}function Ns(e,t,a){if(t(e))return e;for(const s of e.children??[]){const e=Ns(s,t,a);if(null!=e)return e}if(null!=a&&"prefab"===e.type){const s=a.get(e.assetId);if(null!=s){const e=s.prefab.objects.find(e=>Ns(e,t,a));if(null!=e)return e}}return null}const zs=new O,$s=new O,Us=new O,Fs=new E,Rs=new E,Ws=new w,_s=new w,Gs=new A;export function freezeSkinnedMeshes(e,t=!1){if(null==e)return e;e.updateWorldMatrix(!0,!0);const a=[];e.traverse(e=>{e.isSkinnedMesh&&a.push(e)});let s=e;for(const e of a){const a=Ls(e,t),r=e.parent;if(null==r){s=a;continue}const i=r.children.indexOf(e);e.removeFromParent(),r.add(a);const n=r.children.indexOf(a);i>=0&&n>=0&&n!==i&&(r.children.splice(n,1),r.children.splice(i,0,a))}return function(e){const t=[];e.traverse(e=>{e.isBone&&t.push(e)});for(const e of t)null!=e.parent&&!e.parent.isBone&&Js(e)&&e.removeFromParent()}(s),s}function Ls(e,t){e.updateWorldMatrix(!0,!1);const a=e.geometry.clone();t&&s(a,JSON.stringify([e.geometry.uuid,e.bindMatrix.elements,e.bindMatrixInverse.elements,e.skeleton.bones.map((t,a)=>(new w).multiplyMatrices(t.matrixWorld,e.skeleton.boneInverses[a]).elements)]));const r=a.getAttribute("position"),i=a.getAttribute("normal"),n=a.getAttribute("tangent");if(null!=r){for(let t=0;t<r.count;t++)zs.fromBufferAttribute(r,t),e.applyBoneTransform(t,zs),r.setXYZ(t,zs.x,zs.y,zs.z);r.needsUpdate=!0}if(null!=i||null!=n){const t=a.getAttribute("skinIndex"),s=a.getAttribute("skinWeight");if(null!=t&&null!=s){for(let a=0;a<t.count;a++)qs(e,a,_s),null!=i&&($s.fromBufferAttribute(i,a),Gs.getNormalMatrix(_s),$s.applyMatrix3(Gs).normalize(),i.setXYZ(a,$s.x,$s.y,$s.z)),null!=n&&(Us.fromBufferAttribute(n,a),Us.transformDirection(_s),n.setXYZ(a,Us.x,Us.y,Us.z));null!=i&&(i.needsUpdate=!0),null!=n&&(n.needsUpdate=!0)}}a.deleteAttribute("skinIndex"),a.deleteAttribute("skinWeight"),a.computeBoundingBox(),a.computeBoundingSphere();const o=new S(a,e.material);return o.copy(e,!1),o.geometry=a,o.material=e.material,o.userData={...e.userData},o}function qs(e,t,a){const s=e.geometry,r=s.getAttribute("skinIndex"),i=s.getAttribute("skinWeight"),n=e.skeleton;Fs.fromBufferAttribute(r,t),Rs.fromBufferAttribute(i,t),a.identity().multiplyScalar(0);for(let e=0;e<4;e++){const t=Rs.getComponent(e);if(0===t)continue;const s=Fs.getComponent(e);Ws.multiplyMatrices(n.bones[s].matrixWorld,n.boneInverses[s]);for(let e=0;e<16;e++)a.elements[e]+=Ws.elements[e]*t}return a.premultiply(e.bindMatrixInverse).multiply(e.bindMatrix),a}function Js(e){let t=!0;return e.traverse(a=>{a===e||a.isBone||(t=!1)}),t}function Ys(e,t){let a=t??!1,s=!0;for(const t of e)if(!1!==t.castShadow){s=!1;break}for(const t of e)if(!0===t.castShadow)return!0;return a&&!s}function Qs(e,t){let a=t??!1,s=!0;for(const t of e)if(!1!==t.receiveShadow){s=!1;break}if(s)return!1;for(const t of e)if(!0===t.receiveShadow)return!0;return a&&!s}/*
|
|
1
|
+
import{__decorate as e,__metadata as t}from"tslib";import{LatticeGeometryCache as a,setLatticeGeometrySourceIdentity as s}from"./lattice-deformation.js";import{particleParameter as r}from"../shader-nodes/particle-parameter.js";export{createLatticeDeformation,latticePoint,isValidLattice,deformLatticeGeometry,LatticeGeometryCache}from"./lattice-deformation.js";import{ConvexPolyhedronCollisionShape as i}from"./collision/collision-shape.js";import{SpriteShader as n}from"../shader/sprite-shader.js";import{Observable as o,Subject as l}from"rxjs";import*as c from"three";import{BoxGeometry as u,BufferGeometry as d,Color as h,Euler as p,Fog as f,FogExp2 as m,Group as g,Material as y,Matrix4 as w,Mesh as S,MeshLambertMaterial as b,MeshPhongMaterial as v,MeshStandardMaterial as M,Matrix3 as A,Object3D as x,PointLight as D,Quaternion as j,Scene as I,Texture as P,Vector2 as O,Vector3 as C,Vector4 as E}from"three";import{attributes as k,batchingUniformFloat as T,batchingUniformVec2 as B,batchingUniformVec3 as z,batchingUniformVec4 as V,bool as N,BooleanExpression as $,BooleanNode as U,colorToNormal as F,float as R,deriveNodeShaderMaterial as W,FloatNode as _,ifDefApply as G,mix as L,NodeShaderMaterial as q,rgb as J,rgba as Q,RgbNode as Y,select as H,standardMaterial as Z,Texture2dLookupNode as K,textureSampler2d as X,textureSampler2dArray as ee,UniformBoolNode as te,UniformFloatNode as ae,UniformSampler2dArraySlice as se,UniformVec2Node as re,UniformVec3Node as ie,UniformVec4Node as ne,varying as oe,varyingAttributes as le,varyingTransformed as ce,vec2 as ue,Vec2Node as de,vec3 as he,Vec3Node as pe,vec4 as fe,Vec4Node as me}from"three-shader-graph";import{Service as ge}from"typedi";import{VfxActor as ye}from"../effects/vfx/vfx-actor.js";import{VisualEffect as we}from"../effects/vfx/vfx-param.js";import{Prefab as Se,PrefabOf as be}from"./objects/prefab.js";import{DataAssetRef as ve}from"./objects/data-asset.js";import{SceneRef as Me}from"./scene-ref.js";import{ModelRef as Ae}from"./model-ref.js";import{BaseActor as xe,getActorOptions as De}from"../gameplay/actors/actor.js";import je from"../gameplay/actors/builtin/index.js";import{ActorComponent as Ie}from"../gameplay/actors/component.js";import{PhysicsBodyType as Pe}from"../gameplay/services/physics/physics-system.js";import{NetMode as Oe}from"../gameplay/net/net-session.js";import{NetRole as Ce}from"../gameplay/net/service/net-actor-role.js";import{ThreeBlendingMode as Ee}from"../effects/vfx/vfx-asset.js";import{withInjectionContext as ke}from"../gameplay/inject.js";import{RenderingView as Te}from"../rendering.js";import{markMaterialUniformValuesNeedUpdate as Be,setMaterialUniformValuesAutoUpdate as ze}from"../rendering/node-material-webgpu-resolver.js";import{curveSampler as Ve,oneMinus as Ne,particleUniforms as $e,Sampler2DNode as Ue}from"../shader-nodes/index.js";import{LambertShader as Fe}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as Re}from"../shader/builtin/landscape-composite-shader.js";import{LandscapeShader as We}from"../shader/builtin/landscape-shader.js";import{StandardShader as _e}from"../shader/builtin/standard-shader.js";import{UnlitShader as Ge}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as Le,getDataAssetDefinitionType as qe,getParameterDefinitionId as Je,getParameterDefinitionType as Qe,isDataAssetDefinitionAbstract as Ye,isParameterDefinitionAbstract as He,isParameterDefinitionAssignableTo as Ze,isParameterDefinitionStructAssignableTo as Ke,shaderParameterUniformName as Xe}from"../shader/parameter.js";import{ArrayMap as et,DefaultMap as tt,groupBy as at}from"../utils/collections.js";import{iterateMaterials as st}from"../utils/materials.js";import{filterChildrenShallow as rt,filterSceneShallow as it,findFirstVisibleMesh as nt,findFirstVisibleObject as ot,traverseAsync as lt}from"../utils/three/traverse.js";import{AssetMeshInstance as ct,AssetResourceLoader as ut}from"./asset-resource-loader.js";import{AssetsProvider as dt}from"./assets-provider.js";import{isCollisionMesh as ht}from"./collision/collision-shape-import.js";import{BoxCollisionShape as pt,PhysicalShapeMesh as ft}from"./collision/collision-shape.js";import{LandscapeManager as mt}from"./landscape/landscape-manager.js";import{initLandscape as gt}from"./landscape/landscape.js";import{SectionGrid as yt,smoothNormalsCrossMeshes as wt}from"./landscape/utils.js";import{createGrassFoliageMaterial as St}from"./materials/grass-foliage.js";import{createGrassMaterial as bt}from"./materials/grass.js";import{getMaterialAttribute as vt}from"./materials/utils/material-painting.js";import{PaintedScatterManager as Mt}from"./scatter/painted-scatter-manager.js";import{SurfaceScatterManager as At}from"./scatter/surface-scatter-manager.js";import{createWaterMaterial as xt}from"./materials/water.js";import{SerializedParamType as Dt}from"./model.js";import{applyRuntimeParamTypeInference as jt,convertConfiguredParamsToRuntimeTypes as It,convertConfiguredParamValueToRuntimeType as Pt,inferRuntimeSerializedParamTypeHint as Ot}from"./custom-param-runtime-types.js";import{ShapeLibrary as Ct,ShapeLibraryKeys as Et}from"./objects/shapes.js";import{ambientLightName as kt,applySkyMaterialSettings as Tt,createSky as Bt,defaultSkyMaterial as zt}from"./sky.js";import{Curve2 as Vt}from"../utils/curve.js";import{DecalUnlitShader as Nt}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as $t}from"../shader/builtin/decal-standard-shader.js";import{ClusterGenerator as Ut}from"../rendering/cluster-generator.js";import{ColorLayer as Ft,defaultValueColorLayer as Rt,defaultValueMaskLayer as Wt,MaskLayer as _t}from"../shader/color-layer.js";import{LayeredShader as Gt}from"../shader/builtin/layered-shader.js";import{isColorLayerSerialized as Lt}from"../shader/color-layer.js";import{FogVolume as qt}from"../rendering/fog/fog-volume-actor.js";import{UnscaledSprite as Jt}from"../utils/three/unscaled-sprite.js";import{ToonShader as Qt}from"../shader/builtin/toon-shader.js";import{BatchedMesh2 as Yt}from"./batched-mesh-2.js";import{ParallaxStandardMaterial as Ht}from"../shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Zt}from"../shader-nodes/pom.js";import{traverseVisibleEvery as Kt}from"../utils/three/traverse.js";import{BufferGeometryUtils as Xt,RectAreaLightHelper as ea}from"three/examples/jsm/Addons.js";import{createSequenceData as ta,isSequenceData as aa,Sequence as sa}from"../effects/sequence/sequence-data.js";import{applyUvTiling as ra}from"./../shader/uv-nodes.js";import{buildShaderGraphMaterial as ia,shaderGraphMaterialSideToThree as na}from"../shader/graph/index.js";import{hasExecutableEventGraphDocument as oa}from"../gameplay/event-graph/model.js";import{depthUniformName as la}from"../shader-nodes/depth.js";import{resolveDetailCulling as ca,setObjectDetailCulling as ua}from"@hology/webgpu-renderer";export{jt as applyRuntimeParamTypeInference,It as convertConfiguredParamsToRuntimeTypes,Pt as convertConfiguredParamValueToRuntimeType,Ot as inferRuntimeSerializedParamTypeHint};const da={},ha=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),pa=/^((?!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 fa(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}let fa=class{whenReplacementsComplete(){return this.replacementQueue}async preparePersistence(e,t,a){this.persistence=e,this.persistenceSceneId=t;const s=async(e,t,a,r)=>{for(const i of e){const e=t+i.id;if(a.length&&this.authoredPersistenceParents.set(e,a[a.length-1]),i.children&&await s(i.children,t,[...a,e],r),"prefab"!==i.type||null==i.assetId||r.includes(i.assetId))continue;const n=await this.assetsService.getAsset(i.assetId);null!=n?.prefab&&(null!=n.prefab.mainActorId&&this.prefabInstanceExposedActorMap.set(e,e+"/"+n.prefab.mainActorId),await s(n.prefab.objects,e+"/",[...a,e],[...r,i.assetId]))}};await s(a,"",[],[]);for(const e of this.prefabInstanceExposedActorMap.keys()){const t=this.persistenceActorPath(e),a=this.authoredPersistenceTargets.get(t);(null==a||e.length<a.length)&&this.authoredPersistenceTargets.set(t,e)}const r=e=>e.filter(e=>!this.isPersistenceRemoved(e.id)).map(e=>null==e.children?e:{...e,children:r(e.children)});return r(a)}persistenceActorPath(e){const t=new Set;for(;this.prefabInstanceExposedActorMap.has(e)&&!t.has(e);)t.add(e),e=this.prefabInstanceExposedActorMap.get(e);return e}isPersistenceRemoved(e){if(null==this.persistence)return!1;for(let t=e;null!=t;t=this.authoredPersistenceParents.get(t))if(this.persistence.isRemoved({sceneId:this.persistenceSceneId,path:t}))return!0;return!1}registerPersistentActors(){const e=[];if(null==this.persistence)return e;for(const[t,a]of this.materializedActors){const s={sceneId:this.persistenceSceneId,path:t},r={sceneId:this.persistenceSceneId,path:this.authoredPersistenceTargets.get(t)??t};this.persistence.register(a,s,r)&&e.push(a)}return e}get prefabEventGraphInstances(){return[...this.materializedPrefabEventGraphs.values()]}resolveSceneActor(e){const t=this.persistenceActorPath(e);if(!this.isPersistenceRemoved(t))return this.materializedActors.get(t)}constructor(e,t,s,r,i,n,o,u,d=[]){this.scene=e,this.dataProvider=t,this.assetsService=s,this.assetManagerService=r,this.renderingView=i,this.shaders=n,this.actorTypes=o,this.actorProvider=u,this.componentTypes=d,this.navigationBakes={},this.navigationRevision=0,this.objectMap=new Map,this.sceneObjectMap=new Map,this.materializedSourceKinds=new WeakMap,this.replacementQueue=Promise.resolve(),this.pendingReplacements=0,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.authoredPersistenceTargets=new Map,this.authoredPersistenceParents=new Map,this.idToSceneObject=new Map,this.inEditor=!0,this.staticSpatialDisposers=new Map,this.netMode=Oe.none,this.updated$=new l,this.removed$=new l,this.prefabEventGraphAdded$=new l,this.prefabEventGraphRemoved$=new l,this.error$=new l,this.materializedPrefabEventGraphs=new Map,this.announcedPrefabEventGraphs=new Set,this.editorActorParamSnapshot=new Map,this.editorAttachedActorComponents=new WeakMap,this.livePrefabInstances=new Map,this.sceneSettingsActive=!1,this.assets=new Map,this.vfxPreloads=new WeakMap,this.latticeGeometries=new a,this._canBeInstancedCache=new Map,this.editorStaticDrawChunks=[],this.editorStaticChunkBySource=new WeakMap,this.editorStaticSnapshotBySource=new WeakMap,this.dirtyEditorStaticDrawChunks=new Set,this.editorStaticEditingObjects=new Set,this.editorMatrixWorldEditingObjects=new Set,this.editorStaticSelectedObjects=new Set,this.editorStaticDrawSetSuspended=!1,this.editorStaticDrawSetRebuildQueued=!1,this.editorStaticFullRebuildQueued=!1,this._editorStaticDrawSetsEnabled=!0,this.editorStaticInitialized=!1,this.editorStaticDisposed=!1,this.editorStaticObjectsToRebuild=new Map,this.editorStaticDrawSetUpdated$=new l,this._originalMaterials=new Map,this.worldEnvironmentRequest=0,this.prefabInstanceChain=[],this.prefabInstanceExposedActorMap=new Map,this.geometryCache=new Map,this.collisionShapeCache=new Map,this.modelImageBitmaps=new WeakMap,this.assetManagerService.materialProvider=async e=>materialFromAsset(this.assets.get(e)??await this.assetsService.getAsset(e),this.renderingView,this.assetsService,this.assetManagerService,this.shaders),this.originalFog=e.fog,null!=this.renderingView.csm&&(this.originalGlobalLight={direction:this.renderingView.csm.lightDirection.clone(),intensity:this.renderingView.csm.lightIntensity,lights:this.renderingView.csm.lights.map(e=>({intensity:e.intensity,color:e.color.clone(),castShadow:e.castShadow,src:e.userData.src,volumetricIntensity:e.userData.volumetricIntensity}))}),t.onCreate(e=>{this.navigationRevision++,this.update(e).finally(()=>this.scheduleEditorStaticDrawSetRebuild()),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),t.onUpdate((e,t,a)=>{this.navigationRevision++,this.prepareEditorStaticObjectForMutation(e),a||this.pendingReplacements>0?(this.pendingReplacements++,this.replacementQueue=this.replacementQueue.catch(console.error).then(()=>{if(!this.editorStaticDisposed)return this.update(e,a)}).finally(()=>{this.pendingReplacements--,this.scheduleEditorStaticDrawSetRebuild(e)})):this.update(e).finally(()=>this.scheduleEditorStaticDrawSetRebuild(e)),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),t.onRemove(e=>{this.navigationRevision++,this.prepareEditorStaticObjectForMutation(e),this.remove(e),this.scheduleEditorStaticDrawSetRebuild(),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),this.createAssetSubscription=s.onCreate.subscribe(e=>{this.navigationRevision++,this.assets.set(e.id,e)}),this.updateSubscription=s.onUpdate.subscribe(async t=>{this.navigationRevision++;const a=this.assets.get(t.id);if(this.assets.set(t.id,t),"material"==t.type){const a=[];e.traverse(e=>{if(e instanceof c.Mesh)if(Array.isArray(e.material))for(let s=0;s<e.material.length;s++)a.push(this.refreshMaterial(e,e.material[s],t,s));else a.push(this.refreshMaterial(e,e.material,t))}),await Promise.all(a)}else if("mesh"==t.type){this.findByAssetId(t.id).forEach(async e=>{this.remove(e.userData.src);const t=await this.materializeAndInitActor(e.userData.src);this.updated$.next({object:t,source:e.userData.src}),this.scheduleEditorStaticDrawSetRebuild()});for(const e of this.assets.values())if("prefab"==e.type){if(!e.prefab.objects.some(e=>Us(e,e=>e.assetId==t.id,this.assets)))continue;this.findByAssetId(e.id).forEach(e=>{this.remove(e.userData.src),this.materializeAndInitActor(e.userData.src).finally(()=>this.scheduleEditorStaticDrawSetRebuild())})}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 C,!0)}),null!=this.surfaceScatterManager&&(this.surfaceScatterManager.usesSourceAsset(t.id)||this.surfaceScatterManager.usesScatterAsset(t.id))&&this.surfaceScatterManager.queueRefresh(!0),this.paintedScatterManager?.usesScatterAsset(t.id)&&this.paintedScatterManager.queueRefresh(!0)}else if("prefab"===t.type){if("prefab"===a?.type&&await this.applyLivePrefabParameterUpdate(a,t))return;if(!this.inEditor)return void console.warn(`Prefab ${t.name??t.id} changed in a way that cannot be applied to its running instances. Respawn or restart to use the saved data.`);this.findByAssetId(t.id).forEach(e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t).finally(()=>this.scheduleEditorStaticDrawSetRebuild())}),(this.surfaceScatterManager?.usesPrefabAsset(t.id)||this.sceneReferencesPrefabAsset(t.id)&&await this.prefabAssetContainsSurfaceScatter(t))&&await this.refreshSurfaceScatterPresence(!0),(this.paintedScatterManager?.usesPrefabAsset(t.id)||this.sceneReferencesPrefabAsset(t.id)&&await this.prefabAssetContainsPaintedScatter(t))&&await this.refreshPaintedScatterPresence(!0)}else if("vfx"===t.type)for(const e of this.dataProvider.getObjects())await za(e,async e=>{"vfx"===e.type&&e.assetId===t.id&&(this.remove(e),await this.materializeAndInitActor(e))});else if("texture"===t.type)await this.refreshMaterialTextures(t);else if("shaderGraph"===t.type){this.scene.traverse(e=>{if(e instanceof S)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)});for(const e of this.dataProvider.getObjects())await za(e,async e=>{if("vfx"===e.type&&null!=e.assetId){const a=this.assets.get(e.assetId);null!=a&&this.vfxAssetUsesShaderGraph(a,t.id)&&(this.remove(e),await this.materializeAndInitActor(e))}})}this.scheduleEditorStaticDrawSetRebuild()})}async refreshMaterialTextures(e){if("texture"!==e.type)return void console.error("Can not refresh material textures. Asset is not a texture",e);const t=new Set,a=new Set,s=[],r=s=>{t.has(s)||(t.add(s),this.materialUsesTexture(s,e.id)&&a.add(s))};if(this.scene.traverse(t=>{t instanceof c.SpotLight&&"spot"===t.userData?.src?.light?.type&&t.userData.src.light.spot.mapTextureId===e.id&&s.push(t),t instanceof S&&(Array.isArray(t.material)?t.material.forEach(r):r(t.material))}),0===a.size&&0===s.length)return;const i=await this.assetManagerService.getTexture(e);if(null!=i){for(const t of a)this.replaceMaterialTextureReferences(t,e.id,i);for(const e of s)e.map=i}else console.error("Can not refresh material textures. Texture not found",e)}materialUsesTexture(e,t){if(e instanceof c.ShaderMaterial){for(const a of Object.values(e.uniforms))if(a.value instanceof c.Texture&&a.value.userData.assetId===t)return!0}else for(const a of Object.values(e))if(a instanceof c.Texture&&a.userData.assetId===t)return!0;return!1}replaceMaterialTextureReferences(e,t,a){let s=!1;if(e instanceof c.ShaderMaterial)for(const[r,i]of Object.entries(e.uniforms))i.value instanceof c.Texture&&i.value.userData.assetId===t&&(e.uniforms[r].value=a,s=!0);else for(const[r,i]of Object.entries(e))i instanceof c.Texture&&i.userData.assetId===t&&(e[r]=a,s=!0);s&&(e.needsUpdate=!0,Be(e))}async getAsset(e){let t=this.assets.get(e);return null==t&&(t=await this.assetsService.getAsset(e),null!=t&&this.assets.set(e,t)),t}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&&("shaderGraph"===a.type&&"asset"===e.material?.shaderGraph?.source&&e.material.shaderGraph.assetId===a.id&&(t=!0),!t&&null!=e.material?.shaderParams))for(const s of Object.values(e.material.shaderParams)){if(s.type===Dt.Material&&s.value===a.id){t=!0;break}if(s.type===Dt.Array&&"element"in s&&s.element===Dt.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,o=t.userData.receiveDecals!==n.receiveDecals;i.userData=t.userData,i.userData.hasBloom=n.hasBloom,i.userData.reflective=n.reflective,i.userData.outlineParameters=n.outlineParameters,i.userData.receiveDecals=n.receiveDecals,o&&(t.needsUpdate=!0),null!=s?ss(e.material[s],i)||(e.material[s]=i):ss(e.material,i)||(e.material=i,e===this.sky&&this.applySkySettings(e.material))}vfxAssetUsesShaderGraph(e,t){return null!=e.vfx&&e.vfx.emitters.some(e=>this.emitterUsesShaderGraph(e,t))}emitterUsesShaderGraph(e,t){const a=e.output;return"shaderGraph"===a.materialSource&&"asset"===a.shaderGraph?.source&&a.shaderGraph.assetId===t||!!e.children&&e.children.some(e=>this.emitterUsesShaderGraph(e,t))}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="webgpu"===this.renderingView?.requestedBackend,t=e?this.renderingView.initializeBackend().catch(e=>{console.warn("Could not prepare WebGPU texture uploads before compilation",e)}):void 0,a=new Map,s=new Map,r=[];for(const e of this.collectMaterialAssignments(this.dataProvider.getObjects())){const t=this.assets.get(e.materialId);if(null!=t?.material)for(const e of Object.values(t.material.shaderParams??{}))if(e.type===Dt.Texture&&"string"==typeof e.value){const t=this.assets.get(e.value);if(null==t)continue;const r=t.texture?.textureArrayFileKey;null==r?a.set(t.id,t):s.set(r,t)}}const i=[...Array.from(a.values(),e=>({asset:e,array:!1})),...Array.from(s.values(),e=>({asset:e,array:!0}))];let n=0;if(await Promise.all(Array.from({length:Math.min(16,i.length)},async()=>{for(;n<i.length;){const{asset:a,array:s}=i[n++],o=s?(await this.assetManagerService.getTextureArray(a))?.texture:await this.assetManagerService.getTexture(a);null!=o&&(e&&(await t,this.renderingView.initTexture(o)),r.push(o))}})),0!==r.length&&this.renderingView&&"webgpu"!==this.renderingView.requestedBackend){console.log(`Initializing ${r.length} textures`),console.time("Init textures");for(const e of r)this.renderingView.initTexture(e);console.timeEnd("Init textures")}}async prefetchAssets(){this.texturePrefetch=this.initTextures().catch(e=>{console.warn("Could not prefetch scene textures",e)});const e=this.collectAssetMeshIds(this.dataProvider.getObjects());await Promise.all(Array.from(e).map(async e=>{const t=this.assets.get(e);if("mesh"===t?.type)return this.assetManagerService.getMesh(t,{mergeGeomtries:!0,clone:!1})}))}collectAssetMeshIds(e,t=[],a=new Set){for(const s of e??[])this.collectObjectAssetMeshIds(s,t,a);return a}collectObjectAssetMeshIds(e,t,a){if(this.shouldBeMaterialized(e)&&("asset_mesh"===e.type&&null!=e.assetId&&a.add(e.assetId),null!=e.children&&this.collectAssetMeshIds(e.children,t,a),"prefab"===e.type&&null!=e.assetId&&!t.includes(e.assetId))){const s=this.assets.get(e.assetId);null!=s?.prefab?.objects&&this.collectAssetMeshIds(s.prefab.objects,[...t,e.assetId],a)}}collectMaterialAssignments(e,t=[],a=[]){for(const s of e??[])this.collectObjectMaterialAssignments(s,t,a);return a}collectObjectMaterialAssignments(e,t,a){if(this.shouldBeMaterialized(e)&&("shape_mesh"!==e.type&&"asset_mesh"!==e.type||null==e.materialAssignments||a.push(...e.materialAssignments),null!=e.children&&this.collectMaterialAssignments(e.children,t,a),"prefab"===e.type&&null!=e.assetId&&!t.includes(e.assetId))){const s=this.assets.get(e.assetId);null!=s?.prefab?.objects&&this.collectMaterialAssignments(s.prefab.objects,[...t,e.assetId],a)}}async init(){await this.preInit(),ga.clear(),ya.clear();const e=this.prefetchAssets();await Promise.all([e,...this.dataProvider.getObjects().map(e=>this.materialize(e))]),await this.initActorsPostInit(),this.generateOcclusionClusters(),this.announcePrefabEventGraphs(),await this.refreshPaintedScatterPresence(!0),await this.refreshSurfaceScatterPresence(!0),this.editorStaticInitialized=!0,this.rebuildEditorStaticDrawSet(),"webgpu"===this.renderingView.requestedBackend&&await this.texturePrefetch}get editorStaticDrawSetsEnabled(){return this._editorStaticDrawSetsEnabled}set editorStaticDrawSetsEnabled(e){this._editorStaticDrawSetsEnabled!==e&&(this._editorStaticDrawSetsEnabled=e,this.editorStaticInitialized&&!this.editorStaticDisposed&&(e?this.rebuildEditorStaticDrawSet():(this.editorStaticDrawSetSuspended=!1,this.editorStaticEditingObjects.clear(),this.editorStaticFullRebuildQueued=!1,this.editorStaticObjectsToRebuild.clear(),this.disposeEditorStaticDrawSet(),this.editorStaticDrawSetUpdated$.next())))}beginEditorStaticSceneEdit(e=[]){for(const e of this.editorMatrixWorldEditingObjects)Ia(e,!1),this.renderingView?.refreshStaticSpatialObjects(e,!1);this.editorMatrixWorldEditingObjects.clear();for(const t of e)this.editorMatrixWorldEditingObjects.add(t),Ia(t,!0),this.renderingView?.refreshStaticSpatialObjects(t,!0);if(!this._editorStaticDrawSetsEnabled||!this.inEditor||this.editorStaticDrawSetSuspended)return;this.editorStaticDrawSetSuspended=!0,this.editorStaticEditingObjects.clear();const t=new Set;for(const a of e){this.editorStaticEditingObjects.add(a);const e=this.editorStaticChunkBySource.get(a);null!=e&&t.add(e)}for(const e of t)this.disposeEditorStaticDrawChunk(e),this.dirtyEditorStaticDrawChunks.add(e),this.buildEditorStaticDrawChunk(e);this.editorStaticDrawSetUpdated$.next()}setEditorStaticSelectedObjects(e){if(!this.inEditor)return;const t=new Set(e),a=new Set;for(const e of this.editorStaticSelectedObjects)if(!t.has(e)){const t=this.editorStaticChunkBySource.get(e);null!=t&&a.add(t)}for(const e of t)if(!this.editorStaticSelectedObjects.has(e)){const t=this.editorStaticChunkBySource.get(e);null!=t&&a.add(t)}this.editorStaticSelectedObjects.clear();for(const e of t)this.editorStaticSelectedObjects.add(e);if(!this.editorStaticDrawSetSuspended&&"webgpu"===this.renderingView?.requestedBackend){for(const e of a)this.disposeEditorStaticDrawChunk(e),this.buildEditorStaticDrawChunk(e);a.size>0&&this.editorStaticDrawSetUpdated$.next()}}endEditorStaticSceneEdit(){for(const e of this.editorMatrixWorldEditingObjects)Ia(e,!1),this.renderingView?.refreshStaticSpatialObjects(e,!1);if(this.editorMatrixWorldEditingObjects.clear(),this.editorStaticDrawSetSuspended){this.editorStaticDrawSetSuspended=!1,this.editorStaticEditingObjects.clear();for(const e of this.dirtyEditorStaticDrawChunks)this.disposeEditorStaticDrawChunk(e),this.buildEditorStaticDrawChunk(e);this.dirtyEditorStaticDrawChunks.clear(),this.editorStaticDrawSetUpdated$.next()}}getEditorRenderObject(e){const t=e.userData?.src,a=null!=t?.id?this.sceneObjectMap.get(t.id)??e:e;if(this.editorStaticEditingObjects.has(a)||this.editorStaticSelectedObjects.has(a))return a;const s=this.editorStaticSnapshotBySource.get(a);return!0===s?.chunk.active?s.object:e}scheduleEditorStaticDrawSetRebuild(e){!this.editorStaticDisposed&&this._editorStaticDrawSetsEnabled&&this.inEditor&&!this.editorStaticDrawSetSuspended&&"webgpu"===this.renderingView?.requestedBackend&&(null==e?(this.editorStaticFullRebuildQueued=!0,this.editorStaticObjectsToRebuild.clear()):this.editorStaticFullRebuildQueued||this.editorStaticObjectsToRebuild.set(e.id,e),this.editorStaticDrawSetRebuildQueued||(this.editorStaticDrawSetRebuildQueued=!0,queueMicrotask(()=>{if(this.editorStaticDrawSetRebuildQueued=!1,this.editorStaticDisposed||this.editorStaticDrawSetSuspended)return;if(this.editorStaticFullRebuildQueued)return this.editorStaticFullRebuildQueued=!1,void this.rebuildEditorStaticDrawSet();const e=new Set;for(const t of this.editorStaticObjectsToRebuild.values()){const a=this.sceneObjectMap.get(t.id),s=null==a?null:this.editorStaticChunkBySource.get(a);if(null==s){this.editorStaticFullRebuildQueued=!0;break}e.add(s)}if(this.editorStaticObjectsToRebuild.clear(),this.editorStaticFullRebuildQueued)return this.editorStaticFullRebuildQueued=!1,void this.rebuildEditorStaticDrawSet();for(const t of e)this.disposeEditorStaticDrawChunk(t),this.buildEditorStaticDrawChunk(t);this.editorStaticDrawSetUpdated$.next()})))}prepareEditorStaticObjectForMutation(e){const t=this.sceneObjectMap.get(e.id);if(null==t)return;const a=this.editorStaticChunkBySource.get(t);!0===a?.active&&this.disposeEditorStaticDrawChunk(a)}rebuildEditorStaticDrawSet(){if(this.disposeEditorStaticDrawSet(),!this._editorStaticDrawSetsEnabled||!this.inEditor||this.editorStaticDrawSetSuspended||"webgpu"!==this.renderingView?.requestedBackend)return;const e=[];for(const t of this.idToSceneObject.values()){if("asset_mesh"!==t.type||null!=t.latticeDeformation||!0===t.hidden||t.physics?.type===Pe.dynamic)continue;const a=this.sceneObjectMap.get(t.id);null!=a&&this.canUseEditorStaticDrawSet(a)&&e.push(a)}const t=new g;t.name="Hology WebGPU editor static authored objects",t.visible=!1,t.userData.hologyEditorStaticAuthoredRoot=!0,this.scene.add(t),this.editorStaticAuthoredRoot=t,e.sort((e,t)=>{const a=e.userData?.src,s=t.userData?.src,r="asset_mesh"===a?.type?`${a.assetId}:${JSON.stringify(a.materialAssignments??[])}`:"",i="asset_mesh"===s?.type?`${s.assetId}:${JSON.stringify(s.materialAssignments??[])}`:"";return r.localeCompare(i)});for(let t=0;t<e.length;t+=32){const a={sources:e.slice(t,t+32),sourceVisibility:new Map,sourceUpdateMatrixWorld:new Map,sourceParents:new Map,active:!1};this.editorStaticDrawChunks.push(a);for(const e of a.sources)this.editorStaticChunkBySource.set(e,a);this.buildEditorStaticDrawChunk(a)}this.editorStaticDrawSetUpdated$.next()}buildEditorStaticDrawChunk(e){const t=new g;t.name="Hology WebGPU editor static asset mesh chunk",t.userData.hologyEditorStaticSnapshotRoot=!0,e.sourceVisibility.clear(),e.sourceUpdateMatrixWorld.clear(),e.sourceParents.clear();for(const a of e.sources){if(this.editorStaticEditingObjects.has(a)||this.editorStaticSelectedObjects.has(a)){this.editorStaticSnapshotBySource.delete(a);continue}a.updateWorldMatrix(!0,!0);const s=new g;s.name=a.name;const r=ca(a);ua(s,{enabled:!0,minScreenSize:r.minScreenSize,maxDistance:r.maxDistance,shadow:{enabled:!0,minScreenSize:r.shadowMinScreenSize,maxDistance:r.shadowMaxDistance}});const i=a.userData?.src;for(const e of a.children){const t=e.clone(!0),a=[];t.traverse(e=>{const t=e.userData?.src;(ht(e)||null!=t?.id&&null!=i?.id&&t.id!==i.id)&&a.push(e)});for(const e of a)e.removeFromParent();a.includes(t)||s.add(t)}s.matrix.copy(a.matrixWorld),s.matrix.decompose(s.position,s.quaternion,s.scale),s.matrixAutoUpdate=!1,t.add(s),this.editorStaticSnapshotBySource.set(a,{object:s,chunk:e}),e.sourceVisibility.set(a,a.visible),e.sourceParents.set(a,a.parent),a.visible=!1,this.editorStaticAuthoredRoot?.attach(a),e.sourceUpdateMatrixWorld.set(a,a.updateMatrixWorld),a.updateMatrixWorld=Da}0!==t.children.length&&(xa(t),this.scene.add(t),e.root=t,e.disposer=this.renderingView.registerExperimentalStaticDrawSet(t,`hology-editor-static-asset-meshes-${this.editorStaticDrawChunks.indexOf(e)}`),e.active=!0)}canUseEditorStaticDrawSet(e){let t=!1,a=!0;return e.traverseVisible(e=>{e instanceof S&&!ht(e)&&(t=!0,null!=e.geometry?.index&&null==e.customDepthMaterial&&Oa(e.material)||(a=!1))}),t&&a}disposeEditorStaticDrawSet(){for(const e of this.editorStaticDrawChunks)this.disposeEditorStaticDrawChunk(e);this.editorStaticDrawChunks.length=0,this.dirtyEditorStaticDrawChunks.clear(),this.editorStaticChunkBySource=new WeakMap,this.editorStaticSnapshotBySource=new WeakMap,this.editorStaticAuthoredRoot?.removeFromParent(),this.editorStaticAuthoredRoot=void 0}disposeEditorStaticDrawChunk(e){e.disposer?.(),e.disposer=void 0,e.root?.removeFromParent(),e.root=void 0,e.active=!1;for(const[t,a]of e.sourceParents){const e=t.userData?.src,s=null==e?.id||this.sceneObjectMap.get(e.id)===t;(null!=a&&null==t.parent&&s||null!=a&&t.parent===this.editorStaticAuthoredRoot&&s)&&a.attach(t)}e.sourceParents.clear();for(const[t,a]of e.sourceVisibility)t.visible=a;e.sourceVisibility.clear();for(const[t,a]of e.sourceUpdateMatrixWorld)t.updateMatrixWorld=a;e.sourceUpdateMatrixWorld.clear()}async preloadVisualEffects(e){const t=[],a=new Set;for(const s of e){const e=s.asset;if(a.has(e))continue;a.add(e);let r=this.inEditor?void 0:this.vfxPreloads.get(e);null==r&&(r=this.preloadVisualEffect(s).catch(t=>{throw this.vfxPreloads.get(e)===r&&this.vfxPreloads.delete(e),t}),this.inEditor||this.vfxPreloads.set(e,r)),t.push(r)}await Promise.all(t)}async preloadVisualEffect(e){const t=new Set;!function(e,t){const a=e=>{const s=e.output;switch(s.type){case"sprite":case"stretchedSprite":t.add(s.texture);break;case"trail":null!=s.texture&&t.add(s.texture);break;case"decal":t.add(s.colorMap),t.add(s.alphaMap)}e.children?.forEach(a)};e.vfx.emitters.forEach(a)}(e.asset,t),await Promise.all([this.initVfxTextures(t),(async()=>{const t=await e.create(new I);try{await t.prepareRendering()}finally{t.onEndPlay(),t.disposed.next(!0),t.object.removeFromParent()}})()])}async initVfxTextures(e){const t=await Promise.all(Array.from(e,async e=>{const t=await this.assetsService.getAsset(e);return null==t?null:this.assetManagerService.getTexture(t)}));for(const e of t)null!=e&&this.renderingView.initTexture(e)}async initVfx(){await this.preloadVisualEffects(this.actorInstances.flatMap(e=>ks(e)))}async initActorsPostInit(e=Array.from(this.materializedActors.entries())){const t=e.map(async([e,t])=>{if(t.__isInitialised)return;const a=t.object.userData.src??t.object.userData._src;if("vfx"===a.type)return Promise.resolve();const s="prefab"===a.type?await this.assetsService.getAsset(a.assetId):null,r=e.split("/"),i=r.slice(0,-1),n=i.join("/"),o=(r[r.length-1],new Map);for(const[e,t]of this.materializedActors)if(o.set(e,t),0===n.length)e.includes("/")||o.set(e,t);else if(e.startsWith(n+"/")){const a=e.slice(n.length+1);a.includes("/")||o.set(a,t)}const l={...s?.actor?.params??{},...a.actor?.params??{}},c=[...a.actor?.innerParams??[]];for(let t=i.length-1;t>=0;t--){const a=i.slice(0,t+1).join("/"),s=this.idToSceneObject.get(a);if("prefab"===s?.type&&null!=s.prefab){const i=await this.assetsService.getAsset(s.assetId);if(null!=i){let n=!1,o=a+"/"+i.prefab?.mainActorId;for(;null!=o;){if(o===e){n=!0;break}o=this.prefabInstanceExposedActorMap.get(o)}if(n&&null!=s.prefab.params&&Object.assign(l,_a(s.prefab.params)),null!=s.prefab.innerParams){const e=r.slice(t+1);for(const t of s.prefab.innerParams){const a=_a(t.params);0!==Object.keys(a).length&&(n?c.push({path:Ga(t.path,e)?t.path.slice(e.length):t.path,params:a}):Ga(t.path,e)&&c.push({path:t.path.slice(e.length),params:a}))}}}}}this.rememberLivePrefabActorSettings(e,{...a.actor,params:l,innerParams:c});for(const e of c)await this.applyActorComponentParams(t,e.path.slice(),e.params,o);await this.attachEditorComponents(t,a,o);const u=await prepareClassParameters(l,t.constructor,this.assetsService,this.assetManagerService,o,this.renderingView,this.shaders,this.actorProvider,e=>{const t=n.length>0?n+"/"+e:e;return this.prefabInstanceExposedActorMap.has(t)?this.persistenceActorPath(t):null},t);Object.assign(t,u);try{return await this.actorProvider.initActor(t)}catch(e){console.error(`Failed to initiate actor (name="${a.name}", id=${a.id})`,e)}});return Promise.all(t)}async attachEditorComponents(e,t,a){const s=t.actor?.components??[],r=new Array(s.length).fill(null);this.editorAttachedActorComponents.set(e,r);for(const[i,n]of s.entries()){const s=this.componentTypes.find(e=>e.name===n.type);if(null==s){console.warn(`Component type '${n.type}' not found for actor ${t.id}`);continue}const o=e.attach(s.type);if(r[i]=o,null!=n.params){const e=await prepareClassParameters(n.params,null,this.assetsService,this.assetManagerService,a,this.renderingView,this.shaders,this.actorProvider,e=>this.prefabInstanceExposedActorMap.get(e)??null,o);Object.assign(o,e)}for(const e of n.innerParams??[])await this.applyActorComponentParams(o,e.path.slice(),e.params,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,e=>this.prefabInstanceExposedActorMap.get(e)??null,e);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)}previewLatticeDeformation(e,t){this.latticeGeometries.apply(e,t,JSON.stringify(e.userData.src?.vertexMaterials??[])),this.renderingView?.refreshStaticSpatialObjects(e)}canObjectBeInstanced(e){return null==e.latticeDeformation&&e.physics?.type!==Pe.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=>{!ht(e)&&e.isMesh&&s.push(e)});const r=1==s.length&&0==s[0].children.length,i=!pa,n=s.every(e=>!Array.isArray(e.material)||1===e.material.length),o=s.some(e=>e instanceof S&&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)}),await this.preloadAssets()}async preloadAssets(){const e=await this.assetsService.getAssets();for(const t of e)this.assets.set(t.id,t)}shouldBeMaterialized(e){if(!1===e.enabled)return!1;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(){this.sceneSettingsActive=!0,await this.preInit(),await this.prefetchAssets(),this.experimentalStaticDrawSetDisposer?.(),this.experimentalStaticDrawSetDisposer=void 0,ga.clear(),ya.clear();const e=[],t=new et,a=new et,s=new et;let r=0,i=0,n=0;const o=new Map,l=new tt(()=>new Map),u="webgpu"===this.renderingView?.requestedBackend?new g:null,d=null!=u?new g:null;null!=u&&(u.name="Hology WebGPU static scene objects",d.name="Hology WebGPU unsorted late static scene objects");const f=(e,t)=>{if(null!=u&&function(e){return e.visible&&null!=e.geometry.index&&null==e.customDepthMaterial&&Oa(e.material,!0)}(t)){((Array.isArray(t.material)?t.material:[t.material]).some(e=>e.transparent||Ca(e))?d:u).add(e)}else this.scene.add(e)};for(const c of this.dataProvider.getObjects())await za(c,async(c,u,d)=>{if(!this.shouldBeMaterialized(c))return;const p="asset_mesh"==c.type&&this.canObjectBeInstanced(c)&&await this.canAssetBeInstanced(c),f="shape_mesh"===c.type&&"landscape"!==c.shape&&c.physics?.type!==Pe.dynamic;if(p||f){if(u&&u.children?.length>0){const e=u.children.findIndex(e=>e.id===c.id);e>=0&&u.children.splice(e,1)}if(f){let e=c.shape+JSON.stringify(c.shapeParams??{})+c.castShadow+c.receiveShadow;const t=c.materialAssignments?.at(0)?.materialId,a=null!=t?this.assets.get(t):null;let r=null;if(!1&&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===Dt.Color&&null!=e.value&&(r=new h(e.value))}}e+=a.material.outlines,null!=a.material.outlineParams&&(e+=JSON.stringify(a.material.outlineParams)),e+=a.material.reflective,e+=a.material.bloom,e+=a.material.side,e+=a.material.side,e+=a.material.transparent,e+=a.material.alphaTest}else e+=t;s.push(e,{object:{...c,parentTransform:d},color:r}),n++}else{const e=this.assets.get(c.assetId);null==e&&console.log("Can't find asset with id "+c.assetId);let s=o.get(c.assetId);if(null==s){const e=await this.createFromAsset(c,{assignMaterials:!1});if(null==e)return;if(s=o.get(c.assetId),null==s){s={useBatchedMesh:null!=nt(e)&&Kt(e,e=>!(e instanceof S)||this.testCanBatch(e.material,e.geometry)),assetMesh:e},o.set(c.assetId,s)}}const n=Ja(c.materialAssignments,e.materialAssignments);if(s.useBatchedMesh)await lt(s.assetMesh,async t=>{if(!(t instanceof S))return;const s=Array.isArray(t.material)?t.material[0]:t.material,i=await this.resolveMaterialForAssignments(s,n,e);if(null!=i){ze(i,!1),l.get(c.id).set(t.uuid,i);let s=is(t,i);if(s+=ps(i),"webgpu"===this.renderingView?.requestedBackend){const t=c.castShadow??e.castShadow??!1,a=c.receiveShadow??e.receiveShadow??!1;s+=`|detailCulling:${JSON.stringify(c.detailCulling??null)}`,s+=`|castShadow:${t?1:0}|receiveShadow:${a?1:0}`}a.push(s,{...c,parentTransform:d,meshUUID:t.uuid}),r++}else console.warn("Can not materialize mesh because missing material",c)});else{const e=c.assetId+JSON.stringify(c.materialAssignments??[]);t.push(e,{...c,parentTransform:d}),i++}}}else null==u&&e.push({...c,parentTransform:d})});console.log(`Scene init stats: \n Batched Assets: ${a.size} groups containing in total ${r} objects.\n Instanced Assets: ${t.size} groups containing in total ${i} objects.\n Shapes: ${s.size} batch groups containing in total ${n} objects. \n ${e.length} objects can not be batched. \n `),console.time("materialize batches");for(const[e,t]of a.entries()){if(0==t.length)continue;let e;o.get(t[0].assetId).assetMesh;e=this.createBatchedMesh(t,l,o);const a=this.assets.get(t[0].assetId);"webgl"===this.renderingView?.activeBackend?(e instanceof Yt&&e.perInstanceCastShadow||(e.castShadow=Zs(t,a?.castShadow??!1)),e.receiveShadow=Ks(t,a?.receiveShadow??!1)):(e.castShadow=t[0].castShadow??a?.castShadow??!1,e.receiveShadow=t[0].receiveShadow??a?.receiveShadow??!1);const s=new ct;s.add(e),s.userData.src=t[0],s.userData.detailCulling=t[0].detailCulling,s.castShadow=!1,s.receiveShadow=!1,f(s,e)}for(const e of t.values()){if(0==e.length)continue;let t;const a=o.get(e[0].assetId).assetMesh;t=await this.createInstancedMesh(e,a);const s=this.assets.get(e[0].assetId);t.castShadow=Zs(e,s?.castShadow??!1),t.receiveShadow=Ks(e,s?.receiveShadow??!1);const r=new ct;r.add(t),r.userData.src=e[0],r.userData.detailCulling=e[0].detailCulling,a instanceof ct&&(r.collisionShapes=a.collisionShapes),this.prepareCollisionShapesForInstanced(r),r.castShadow=!1,r.receiveShadow=!1,f(r,t)}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=ot(a,e=>!ht(e)&&null!=e.geometry),r=es(s.material);null!=e[0].color&&null!=r.color&&(r.color=new h(16777215));const i=null==s.geometry.index?Xt.mergeVertices(s.geometry):s.geometry;let n,o;!(pa||r instanceof q)?(n=new c.BatchedMesh(e.length,i.getAttribute("position").count,i.index.count,r),n.perObjectFrustumCulled=!0,o=n.addGeometry(i)):n=new c.InstancedMesh(i,r,e.length),n.castShadow=a.castShadow??!0,n.receiveShadow=s.receiveShadow??!1;for(let t=0;t<e.length;t++){const a=e[t],s=(new c.Matrix4).compose((new C).fromArray(a.object.position),(new j).setFromEuler((new p).fromArray(a.object.rotation)),(new C).fromArray(a.object.scale)),r=(new w).copy(a.object.parentTransform).multiply(s);let i;i=n instanceof c.BatchedMesh?n.addInstance(o):t,n.setMatrixAt(i,r),a.color}for(let t=0;t<e.length;t++){const s=e[t],r=new ct;r.userData.src=e[0],r.userData.detailCulling=e[0].object.detailCulling,a instanceof ft&&(r.collisionShapes=[a.collisionShape]),r.castShadow=!0,r.receiveShadow=!0,f(r,n),r.add(n),null==n.userData.hasCollision&&(n.userData.hasCollision=[]),n.userData.hasCollision[t]=!1!==s.object.collisionDetection}}if(null!=u&&u.children.length>0&&(xa(u),this.scene.add(u),this.experimentalStaticDrawSetDisposer=this.renderingView.registerExperimentalStaticDrawSet(u,"hology-materialized-static-scene")),null!=d&&d.children.length>0){xa(d),this.scene.add(d);const e=this.experimentalStaticDrawSetDisposer,t=this.renderingView.registerExperimentalStaticDrawSet(d,"hology-materialized-unsorted-late-static-scene",!0);this.experimentalStaticDrawSetDisposer=()=>{e?.(),t()}}await Promise.all(e.map(e=>this.materialize(e))),await this.initActorsPostInit(),this.announcePrefabEventGraphs(),await this.initVfx(),this.generateOcclusionClusters(),await this.refreshPaintedScatterPresence(!0),await this.refreshSurfaceScatterPresence(!0),"webgpu"===this.renderingView.requestedBackend&&await this.texturePrefetch}generateOcclusionClusters(){const e=new Ut;e.initScene(this.scene),e.clusters.forEach(e=>{this.renderingView.addCluster(e)})}prepareCollisionShapesForInstanced(e){e instanceof ct&&e.collisionShapes.forEach(e=>{e instanceof i&&e.mesh instanceof S&&(e.mesh=e.mesh.geometry)})}setScene(e){this.scene=e}testCanBatch(e,t){return!pa&&(!Array.isArray(e)||1==e.length)&&this.testCanBatchMaterial(e)}testCanBatchMaterial(e){return null!=(Array.isArray(e)?e[0]:e)}createBatchedMesh(e,t,a){const s=new et;for(const t of e)null!=t.meshUUID?s.push(t.meshUUID??t.assetId,t):console.warn("Missing mesh uuid for batching");let r=0,i=0,n=0;const o=new Map;for(const[e,t]of s.entries()){const s=t[0].assetId,l=a.get(s);if(null==l){console.warn("Missing batching info for asset id "+s);continue}const c=ot(l.assetMesh,t=>t instanceof S&&t.uuid===e);if(null==c){console.warn("Missing mesh in batched asset");continue}o.set(e,c);const u=c.geometry.getAttribute("position");null==u&&console.warn("Missing position attribute for batched mesh"),r+=c.geometry.index.count*t.length,i+=u.count*t.length,n+=t.length}const l=["color","map","roughness","roughnessMap","metalness","metalnessMap","opacity","alphaMap","aoMap","aoMapIntensity","normalMap","normalScale","emissive","emissiveIntensity","emissiveMap"],u=new Map,d=new Map,p=[];let f=new c.MeshStandardMaterial({color:"white"});const m=t.get(e[0].id).get(e[0].meshUUID);if(null==m)throw"missing source material";if(m instanceof M&&!(m instanceof c.MeshPhysicalMaterial)){const a=new Set,s=new Map;for(const r of e){const e=t.get(r.id).get(r.meshUUID);if(null==e)throw"missing mat";for(const t of l){let r=e[t];r instanceof c.CompressedArrayTexture&&null!=r.userData.index&&(r=r.userData.index);const i=s.get(t);void 0===i||Es(r,i)?s.set(t,r):a.add(t)}}for(const e of a){let t;const a=m[e];let s=e;if("number"==typeof a){let a=p.find(e=>e.params.length<4);if(null==a){const t="vp"+p.length;a={name:t,params:[e],node:V(t)},p.push(a)}else a.params.push(e);s=a.name,t=Os(a.node,a.params.length-1)}else if(a instanceof E)t=V(s);else if(a instanceof C||a instanceof h)t=z(s);else if(a instanceof O)t=B(s);else if(a instanceof c.CompressedArrayTexture)s=e+"_i",t=T(s);else if(a instanceof P)continue;u.set(e,t),d.set(e,s)}let r=le.uv;m instanceof Ht&&null!=m.heightMap&&(r=Zt(r,X(m.heightMap),R(m.heightScale)));let i=Ds(u.get("opacity"),_)??R(m.opacity??1);if(null!=m.alphaMap){let e;if(m.alphaMap instanceof c.CompressedArrayTexture){const t=ee(m.alphaMap),a=Ds(u.get("alphaMap"),_)??R(m.alphaMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=X(m.alphaMap).sample(r);i=i.multiply(e.r)}let n=Q(Ds(u.get("color"),pe)??m.color,i);if(null!=m.map){let e;if(m.map instanceof c.CompressedArrayTexture){const t=ee(m.map),a=Ds(u.get("map"),_)??R(m.map.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=X(m.map).sample(ra(r,m.map));n=n.multiply(e),i=i.multiply(e.a)}m.vertexColors&&(n=n.multiply(fe(oe(k.color.rgb),1)));let o=Q(Ds(u.get("emissive"),pe)??m.emissive,i);if(null!=m.emissiveMap){let e;if(m.emissiveMap instanceof c.CompressedArrayTexture){const t=ee(m.emissiveMap),a=Ds(u.get("emissiveMap"),_)??R(m.emissiveMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=X(m.emissiveMap).sample(ra(r,m.emissiveMap));o=o.multiply(e)}const g=Ds(u.get("emissiveIntensity"),_)??R(m.emissiveIntensity??1),y=Ds(u.get("normalScale"),de)??ue(m.normalScale??new O(1,1));let w=ce.normal;if(null!=m.normalMap){let e;if(m.normalMap instanceof c.CompressedArrayTexture){const t=ee(m.normalMap),a=Ds(u.get("normalMap"),_)??R(m.normalMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=X(m.normalMap).sample(ra(r,m.normalMap));w=F(e.rgb,y.x)}let S=Ds(u.get("roughness"),_)??R(m.roughness??1);if(null!=m.roughnessMap){let e;if(m.roughnessMap instanceof c.CompressedArrayTexture){const t=ee(m.roughnessMap),a=Ds(u.get("roughnessMap"),_)??R(m.roughnessMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=X(m.roughnessMap).sample(ra(r,m.roughnessMap));S=S.multiply(e.g)}let b=Ds(u.get("metalness"),_)??R(m.metalness??0);if(null!=m.metalnessMap){let e;if(m.metalnessMap instanceof c.CompressedArrayTexture){const t=ee(m.metalnessMap),a=Ds(u.get("metalnessMap"),_)??R(m.metalnessMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=X(m.metalnessMap).sample(ra(r,m.metalnessMap));b=b.multiply(e.b)}let v=R(1);if(null!=m.aoMap){let e;if(m.aoMap instanceof c.CompressedArrayTexture){const t=ee(m.aoMap),a=Ds(u.get("aoMap"),_)??R(m.aoMap.userData.index??0);e=t.sample(he(r.x,r.y,a))}else e=X(m.aoMap).sample(ra(r,m.aoMap));v=v.multiply(e.r)}const M=Ds(u.get("aoMapIntensity"),_)??R(m.aoMapIntensity??0);let A=w;!0!==m.userData.disableAO&&(A=G("DOUBLE_SIDED",A,e=>H(new $("gl_FrontFacing"),e,e.multiplyScalar(-1))));const x=new q({color:Z({color:n,roughness:S,metalness:b,ambientOcclusion:v,ambientOcclusionIntensity:M,emissive:o,emissiveIntensity:g,normal:A}),normal:w,roughness:S,emissive:o.rgb,transparent:m.transparent,alphaTest:m.alphaTest,envMap:m.envMap,opacity:i});null!=m.envMap&&(x.uniforms.envMapIntensity={value:m.envMapIntensity},x.uniforms.envMapRotation={value:Ps(m.envMapRotation,m.envMap)}),x.envMap=m.envMap,x.side=m.side,f=x}else if(m instanceof q){const a=new Set,s=new Map,r=Object.keys(m.uniforms).filter(e=>!gs(e));for(const i of e){const e=t.get(i.id).get(i.meshUUID);if(!(e instanceof q))throw new Error("Expected NodeShaderMaterial in node material batch");for(const t of r){const r=e.uniforms[t]?.value,i=s.get(t);void 0===i||Es(r,i)?s.set(t,r):ws(r)&&ws(i)&&Ss(r)===Ss(i)&&a.add(t)}}const i=new Set(Object.keys(m.uniforms)),n={};for(const e of a){let t,a;const s=m.uniforms[e]?.value;if("number"==typeof s){let s=p.find(e=>e.params.length<4);if(null==s){const t=bs("vp"+p.length,i);s={name:t,params:[e],node:V(t)},p.push(s)}else s.params.push(e);a=s.name,t=Os(s.node,s.params.length-1)}else if(s instanceof E)a=bs(e,i),t=V(a);else if(s instanceof C||s instanceof h)a=bs(e,i),t=z(a);else{if(!(s instanceof O))continue;a=bs(e,i),t=B(a)}u.set(e,t),d.set(e,a),n[e]=t}if(0===u.size)f=m;else{const e=W(m,{color:m.outputColor,transform:m.outputTransform??null,position:null==m.outputTransform?m.outputPosition:void 0,normal:m.outputNormal??null,roughness:m.outputRoughness??null,opacity:m.outputOpacity??null,emissive:m.outputEmissive??null,uniforms:vs(m,new Set(u.keys())),uniformNodes:n});e.uniformNodes=n,g=m,(y=e).name=g.name,y.side=g.side,y.blending=g.blending,y.depthWrite=g.depthWrite,y.depthTest=g.depthTest,y.colorWrite=g.colorWrite,y.toneMapped=g.toneMapped,y.visible=g.visible,y.opacity=g.opacity,y.forceSinglePass=g.forceSinglePass,y.premultipliedAlpha=g.premultipliedAlpha,y.polygonOffset=g.polygonOffset,y.polygonOffsetFactor=g.polygonOffsetFactor,y.polygonOffsetUnits=g.polygonOffsetUnits,y.shadowSide=g.shadowSide,Object.assign(y.defines,g.defines),Object.assign(y.userData,g.userData),y.needsUpdate=!0,f=e}}else{f=m;for(const a of e){const e=t.get(a.id).get(a.meshUUID);if(e!=f){console.error(`Different materials in group for object ${a.id} and mesh uuid ${a.meshUUID}`,{objectMaterial:e,sourceMaterial:m});break}}}var g,y;const w=new Yt(n,i,r,f);for(const e of p)w.initUniform(e.name,4);for(const[e,t]of u.entries()){if(p.some(t=>t.params.includes(e)))continue;let a=1;t instanceof me||t instanceof pe?a=4:t instanceof de&&(a=2),w.initUniform(d.get(e)??e,a,0)}for(const[e,r]of s.entries()){const s=r[0].assetId,i=o.get(e);if(null==i){console.error(`Missing single asset mesh for mesh uuid ${e} and asset id ${s}`);continue}if(null==i.geometry){console.error("Missing geometry on mesh mesh");continue}const n=w.addGeometry(ns(i.geometry,m)),l=this.assets.get(s),f=a.get(s);if(null==f){console.warn("Missing batching info when configuring for asset id "+s);continue}const g=nt(f.assetMesh)?.uuid===e,y=f.assetMesh instanceof ct&&g?f.assetMesh.collisionShapes:void 0,S=this.configureBatchedInstancedMesh(r,w,i,n,y);for(let e=0;e<S.length;e++){const a=r[e],s=S[e];"webgpu"!==this.renderingView?.requestedBackend&&w.setCastShadowAt(s,a.castShadow??l?.castShadow??!1);const i=t.get(a.id).get(a.meshUUID),n=i.userData.surface;null!=n&&(w.surfaceByInstance[s]=n);for(const e of p){let t=Cs.set(0,0,0,0);for(let a=0;a<e.params.length;a++){const s=ys(i,e.params[a]);"number"==typeof s&&t.setComponent(a,s)}w.setUniformAt(e.name,s,t)}for(let e of u.keys()){if(p.some(t=>t.params.includes(e)))continue;const t=d.get(e)??e;let a=ys(i,e);if(a instanceof h&&(a=new C(a.r,a.g,a.b)),a instanceof c.CompressedArrayTexture)a=a.userData.index??0;else if(a instanceof P||null==a)continue;w.setUniformAt(t,s,a)}}}return w}async createInstancedMesh(e,t){const a=ot(t,e=>!ht(e)&&null!=e.geometry),s=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,Ja(e[0].materialAssignments,s.materialAssignments),s),a.updateMatrix();const r=a.geometry.clone(),i=a.material;let n;if(n=new c.InstancedMesh(r,i,e.length),this.configureBatchedInstancedMesh(e,n,a),a.material instanceof y&&n.castShadow&&n.receiveShadow&&Array.isArray(i))for(const e of i);return n}configureBatchedInstancedMesh(e,t,a,s,r){const i=[];a.updateWorldMatrix(!0,!0);for(let n=0;n<e.length;n++){let o=n;t instanceof c.BatchedMesh&&(o=t.addInstance(s)),i.push(o);const l=(new c.Matrix4).compose((new C).fromArray(e[n].position),(new j).setFromEuler((new p).fromArray(e[n].rotation)),(new C).fromArray(e[n].scale)),u=(new w).copy(e[n].parentTransform).multiply(l),d=(new w).copy(u).multiply(a.matrixWorld);t.setMatrixAt(o,d),null==t.userData.hasCollision&&(t.userData.hasCollision=[]);const h=this.assets.get(e[n].assetId);t.userData.hasCollision[o]=!1!==e[n].collisionDetection||!1!==h?.collisionDetection,null!=r&&(null==t.userData.collisionShapes&&(t.userData.collisionShapes=[]),t.userData.collisionShapes[o]=r,null==t.userData.collisionMatrices&&(t.userData.collisionMatrices=[]),t.userData.collisionMatrices[o]=u)}return i}remove(e){if(console.log("Remove scene object",e),"global_fog"==e.type)this.scene.fog=this.originalFog;else 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 if("prefab"===e.type){this.unregisterLivePrefabInstance(e.id);const t=new Set(this.removePrefabEventGraphs(e.id).flatMap(e=>e.actors));this.materializedActors.forEach((a,s)=>{(s===e.id||s.startsWith(e.id+"/"))&&(t.has(a)||(a.disposed.next(!0),a.onEndPlay()),this.materializedActors.delete(s))})}const t=this.sceneObjectMap.get(e.id);t?.traverse(e=>{this.staticSpatialDisposers.get(e)?.(),this.staticSpatialDisposers.delete(e)}),t&&this.latticeGeometries.release(t),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}),"actor"!==e.type&&"vfx"!==e.type||this.materializedActors.delete(e.id)}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 it(this.scene,t=>t.userData.src?.assetId==e,e=>null!=e.userData.src)}applyMaterials(e,t,a){return null==t?Promise.resolve([]):Promise.all(t.filter(e=>"null"!==e.materialId).map(t=>this.applyMaterial(e,t,a)))}async applyMaterial(e,t,a){await applyMaterial(e,t,async e=>{const t=await this.getAsset(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)}else console.warn("Missing material with id "+e)},this._originalMaterials,{textureFlipY:getConvertedFbxToGlbAssignedMaterialTextureFlipY(a)})}async resolveMaterialForAssignments(e,t,a){let s=e,r=null,i=null;const n=getConvertedFbxToGlbAssignedMaterialTextureFlipY(a);for(const e of t??[]){if(!Za(s,e,r,i))continue;const t=await this.getAsset(e.materialId);if(null==t){console.warn("Missing material with id "+e.materialId);continue}let a=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!0);null!=a&&(a=Xa(a,n)),null!=a&&s.id!==a.id&&(r=r??Ha(s),i=i??s.name,s=a);break}return s}unapplyMaterials(e){e.traverse(async e=>{if(e instanceof S)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){this.navigationRevision++;const t=new Map(this.actorTypes.map(e=>[e.name,e.type])),a=new Map(e.map(e=>[e.name,e.type])),s=new Set;for(const e of new Set([...t.keys(),...a.keys()]))(t.get(e)??je[e])!==(a.get(e)??je[e])&&s.add(e);this.actorTypes=e,0!==s.size&&it(this.scene,e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&s.has(e.userData.src.actor.type)).forEach(async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)})}updateComponents(e){this.componentTypes=e,it(this.scene,e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&(e.userData.src.actor?.components?.length??0)>0).forEach(async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)})}updateShaders(e){this.shaders=e;for(const[e,t]of ga.entries())t.userData.customShaderName&&ga.delete(e);ya.clear(),this.landscapeManagers.forEach(t=>t.updateShaders(e)),it(this.scene,e=>!0).forEach(e=>{e.traverse(async e=>{if(e instanceof S)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=e.material[t].userData.assetId,s=await this.getAsset(a);null!=s&&this.refreshMaterial(e,e.material[t],s,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=e.material.userData.assetId,a=await this.getAsset(t);null!=a&&this.refreshMaterial(e,e.material,a)}}})})}async update(e,t=!1){const a=this.sceneObjectMap.get(e.id),s=null==a?void 0:this.materializedSourceKinds.get(a);if(t||null!=s&&(s.type!==e.type||s.assetId!==e.assetId||s.actor?.type!==e.actor?.type)){const t=e=>{for(const a of e.children??[])t(a);const a=this.sceneObjectMap.get(e.id),s=null==a?void 0:this.materializedSourceKinds.get(a);this.remove(s??e)};t(e);const a=await this.materializeAndInitActor(e);return void this.updated$.next({object:a,source: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 r=this.sceneObjectMap.get(e.id);if(r){let t=!1;if(r.traverseAncestors(e=>{"_hology_transform_group"===e.name&&(t=!0)}),!t){const t=this.findParent(e);null!=t&&t.uuid!=r.uuid?t.attach(r):console.error("Parent is wrong")}if(!("shape_mesh"!==e.type&&"asset_mesh"!==e.type||null==e.renderOrder&&0===r.renderOrder||e.renderOrder===r.renderOrder))return void(r.renderOrder=e.renderOrder??0);if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(r);this.inEditor&&e.hidden&&!1?r.traverse(e=>{e instanceof S&&(e.material.wireframe=!0)}):r.traverse(e=>{e instanceof S&&(e.material.wireframe=!1)})}if("asset_mesh"===e.type&&r.userData.assetId!==e.assetId){this.remove(e);const t=await this.materializeAndInitActor(e);return void this.updated$.next({object:t,source:e})}if("asset_mesh"===e.type&&this.latticeGeometries.apply(r,e.latticeDeformation,JSON.stringify(e.vertexMaterials??[])),"asset_mesh"===e.type){const t=this.assets.get(e.assetId);Ja(e.materialAssignments,t.materialAssignments).forEach(e=>this.applyMaterial(r,e,t))}else"shape_mesh"===e.type&&this.applyMaterials(r,e.materialAssignments);if(t||(null!=e.position&&r.position.fromArray(e.position),null!=e.scale&&r.scale.fromArray(e.scale),null!=e.rotation&&r.rotation.fromArray(e.rotation),this.inEditor&&("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&e.physics?.type!==Pe.dynamic?Ia(r,!1):this.inEditor&&function(e){let t=!1;if(e.traverse(e=>{ja.has(e)&&(t=!0)}),!t)return;e.updateWorldMatrix(!0,!0),e.traverse(e=>{ja.has(e)&&(e.matrixWorldNeedsUpdate=!1)})}(r)),this.applyVertexMaterials(e,r),"light"==e.type){if("point"==e.light.type){const t=r;t.color=new h(e.light.point.color),t.intensity=e.light.point.intensity,t.decay=e.light.point.decay,t.castShadow=e.light.point.castShadow,t.distance=Math.max(e.light.point.distance,0),t.userData.volumetricIntensity=e.light.point.volumetricIntensity}else if("spot"==e.light.type){const t=r;t.color=new h(e.light.spot.color),t.intensity=e.light.spot.intensity,t.decay=e.light.spot.decay,t.angle=e.light.spot.angle,t.penumbra=e.light.spot.penumbra,t.castShadow=e.light.spot.castShadow,t.distance=Math.max(e.light.spot.distance,0),t.userData.volumetricIntensity=e.light.spot.volumetricIntensity,t.map=await this.loadSpotLightMap(e.light.spot.mapTextureId)}else if("directional"===e.light.type)this.applyDirectionalLight(e.light.directional,e);else if("ambient"===e.light.type)this.applyDirectionalAmbientLight(r,e.light.ambient,e);else if("rectArea"===e.light.type){const t=r;t.color=new h(e.light.rectArea.color),t.intensity=e.light.rectArea.intensity,null!=e.scale&&(t.width=e.scale[0],t.height=e.scale[1]),t.children.forEach(e=>{e instanceof ea&&e.update()})}}else if("landscape"===e.shape){const t=this.landscapeManagers.find(t=>t.source.id===e.id),a=null==t||function(e,t){return e.density!==t.density||e.sections.x!==t.sections.x||e.sections.y!==t.sections.y}(t.source.landscape.options,e.landscape.options);if(this.inEditor&&a){this.remove(e);const t=await this.materializeAndInitActor(e);return void this.updated$.next({object:t,source:e})}this.applyHeightMaps(r,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 m?"density":"linear")!==e.fog.type;this.scene.fog=Ea(e.fog),t&&(i=this.scene).traverse(e=>{if(e instanceof S){const t=e.material;t instanceof q&&(i.fog instanceof f?(t.uniforms.fogFar.value=i.fog.far,t.uniforms.fogNear.value=i.fog.near):i.fog instanceof m&&(t.uniforms.density={value:i.fog.density}),t.needsUpdate=!0,t.uniformsNeedUpdate=!0)}}),this.fixFogColor()}else if("actor"===e.type){if(this.materializedActors.has(e.id)){const a=this.materializedActors.get(e.id);if(a instanceof qt){const t=await prepareClassParameters(e.actor.params,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,[],this.actorProvider,e=>this.prefabInstanceExposedActorMap.get(e)??null,a);return void Object.assign(a,t)}const s=this.editorActorParamSnapshot.get(e.id);if((null==s||s!==JSON.stringify(e.actor))&&!t){if(null!=a&&null!=s&&await this.tryApplyLiveActorParameterUpdate(a,e,s))return void this.updated$.next({object:a.object,source:e});this.remove(e),await this.materializeAndInitActor(e)}}}else if("shape_mesh"===e.type){const t=await this.createMeshByShape(e.shape,r.material,e.shapeParams);r instanceof ft&&(r.geometry=t.geometry,r.collisionShape=t.collisionShape)}if("shape_mesh"===e.type&&"landscape"!==e.shape)ma(r,e.castShadow,e.receiveShadow);else if("asset_mesh"===e.type){const t=this.assets.get(e.assetId);if(null==t)return void console.error("Asset not found",e.assetId);const a=e.receiveShadow??!!t.receiveShadow,s=e.castShadow??!!t.castShadow;ma(r,s,a)}e.name&&e.name.length>0&&(r.name=e.name),r.userData.detailCulling=e.detailCulling,this.renderingView.refreshStaticSpatialObjects(r),this.updated$.next({object:r,source:e})}else{const t=await this.materializeAndInitActor(e);this.updated$.next({object:t,source:e})}var i;this.renderingView.invalidateShadows()}async materializeAndInitActor(e,t=this.findParent(e)){const a=await this.materialize(e,t),s=e.children?.length?new Set:void 0,r=e=>{s.add(e.id);for(const t of e.children??[])r(t)};null!=s&&r(e);const i=Array.from(this.materializedActors.entries()).filter(([t])=>{const a=t.indexOf("/");return t===e.id||t.startsWith(e.id+"/")||s?.has(-1===a?t:t.slice(0,a))});if(await this.initActorsPostInit(i),null!=s)for(const e of s)this.announcePrefabEventGraphs(e);else this.announcePrefabEventGraphs(e.id);return a}async tryApplyLiveActorParameterUpdate(e,t,a){let s;try{s=JSON.parse(a)}catch{return!1}const r=await this.tryApplyLiveActorSettingsUpdate(e,s,t.actor);return r&&this.editorActorParamSnapshot.set(t.id,JSON.stringify(t.actor)),r}async tryApplyLiveActorSettingsUpdate(e,t,a){const s=await this.applyLiveActorSettingsUpdate(e,t,a);return s.hasChanges&&!s.rejected}async applyLiveActorSettingsUpdate(e,t,a){const s=t?.components??[],r=a?.components??[];if(t?.type!==a?.type||s.length!==r.length||s.some((e,t)=>e.type!==r[t]?.type))return{applied:t,hasChanges:!0,rejected:!0};let i=!1,n=!1;const o=await this.tryApplyLiveParameterUpdate(e,t?.params??{},a?.params??{});!1===o&&(n=!0),i||(i=!0===o);const l=await this.applyLiveInnerParameterUpdates(e,t?.innerParams??[],a?.innerParams??[]);n||(n=l.rejected),i||(i=l.hasChanges);const c=this.editorAttachedActorComponents.get(e),u=[];for(let e=0;e<r.length;e++){const t=s[e],a=r[e];if(JSON.stringify(t)===JSON.stringify(a)){u.push(a);continue}const o=c?.[e];if(null==o){n=!0,u.push(t);continue}const l=await this.tryApplyLiveParameterUpdate(o,t?.params??{},a?.params??{});!1===l&&(n=!0),i||(i=!0===l);const d=await this.applyLiveInnerParameterUpdates(o,t?.innerParams??[],a?.innerParams??[]);n||(n=d.rejected),i||(i=d.hasChanges),u.push({...a,params:!1===l?t?.params:a?.params,innerParams:d.applied})}return{applied:{...a,params:!1===o?t?.params:a?.params,innerParams:l.applied,components:u},hasChanges:i,rejected:n}}async applyLivePrefabParameterUpdate(e,t){if(!this.assetsService.supportsLivePrefabParameters)return!1;const a=this.livePrefabInstances.get(t.id);if(null==a||0===a.size)return!0;const s=$a(e.prefab?.objects??[]),r=$a(t.prefab?.objects??[]);if(s.size!==r.size||[...s.keys()].some(e=>!r.has(e)))return!1;const i=[];await this.applyLiveNestedPrefabOverrideUpdates(e,t,a,i);for(const n of a.values())for(const[a,o]of s){const s=r.get(a),l=n.actorsById.get(a);if(null==s||null==l){i.push(`${n.prefix}/${a}`);continue}const c=n.actorSettingsById.get(a)??Fa(o,n.source,e.prefab?.mainActorId===a),u=Fa(o,n.source,e.prefab?.mainActorId===a),d=Ra(u,Fa(s,n.source,t.prefab?.mainActorId===a),n.desiredActorSettingsById.get(a)??u);if(n.desiredActorSettingsById.set(a,d),JSON.stringify(c)===JSON.stringify(d))continue;const h=await this.applyLiveActorSettingsUpdate(l,c,d);n.actorSettingsById.set(a,h.applied),h.rejected&&i.push(`${n.prefix}/${a}`)}return i.length>0&&console.warn(`Some live parameters for prefab ${t.name??t.id} were not applied. The running instances were preserved: ${i.join(", ")}`),!0}async applyLiveNestedPrefabOverrideUpdates(e,t,a,s){const r=Ua(e.prefab?.objects??[]),i=Ua(t.prefab?.objects??[]);for(const[e,t]of r){const r=i.get(e);if(null==r||t.assetId!==r.assetId||JSON.stringify(t.prefab)===JSON.stringify(r.prefab))continue;const n=this.assets.get(r.assetId),o=this.livePrefabInstances.get(r.assetId);if("prefab"!==n?.type||null==n.prefab||null==o)continue;const l=$a(n.prefab.objects);for(const i of a.values()){const a=`${i.prefix}/${e}`,c=o.get(a);if(null!=c){for(const[e,i]of l){const o=c.actorsById.get(e);if(null==o){s.push(`${a}/${e}`);continue}const l=Fa(i,t,n.prefab.mainActorId===e),u=Fa(i,r,n.prefab.mainActorId===e),d=c.desiredActorSettingsById.get(e)??l,h=Ra(l,u,d);c.desiredActorSettingsById.set(e,h);const p=c.actorSettingsById.get(e)??d;if(JSON.stringify(p)!==JSON.stringify(h)){const t=await this.applyLiveActorSettingsUpdate(o,p,h);c.actorSettingsById.set(e,t.applied),t.rejected&&s.push(`${a}/${e}`)}}c.source=r}}}}unregisterLivePrefabInstance(e){if(0!==e.length)for(const[t,a]of this.livePrefabInstances){for(const t of[...a.keys()])(t===e||t.startsWith(e+"/"))&&a.delete(t);0===a.size&&this.livePrefabInstances.delete(t)}}rememberLivePrefabActorSettings(e,t){if(this.assetsService.supportsLivePrefabParameters)for(const a of this.livePrefabInstances.values())for(const s of a.values()){if(!e.startsWith(s.prefix+"/"))continue;const a=e.slice(s.prefix.length+1);s.actorsById.has(a)&&(s.actorSettingsById.set(a,t),s.desiredActorSettingsById.set(a,t))}}async tryApplyLiveParameterUpdate(e,t,a){const s=new Set([...new Set([...Object.keys(t),...Object.keys(a)])].filter(e=>JSON.stringify(t[e])!==JSON.stringify(a[e])));if(0===s.size)return null;const r=await prepareClassParameters(a,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders,this.actorProvider,e=>this.prefabInstanceExposedActorMap.get(e)??null,e);return await e.applySceneParameters(r,s)}async applyLiveInnerParameterUpdates(e,t,a){const s=new Map(t.map(e=>[JSON.stringify(e.path),e])),r=new Map(a.map(e=>[JSON.stringify(e.path),e]));if(s.size!==t.length||r.size!==a.length)return{applied:t,hasChanges:!0,rejected:!0};let i=!1,n=!1;const o=[];for(const t of new Set([...s.keys(),...r.keys()])){const a=s.get(t),l=r.get(t);if(JSON.stringify(a?.params??{})===JSON.stringify(l?.params??{})){null!=l&&o.push(l);continue}const c=l?.path??a?.path,u=this.resolveActorComponent(e,c);if(null==u){n=!0,null!=a&&o.push(a);continue}!0===await this.tryApplyLiveParameterUpdate(u,a?.params??{},l?.params??{})?(null!=l&&o.push(l),i=!0):(n=!0,null!=a&&o.push(a))}return{applied:o,hasChanges:i,rejected:n}}resolveActorComponent(e,t){if(null==t||0===t.length)return null;let a=e;for(const e of t){const t=a[e];if(!(t instanceof Ie))return null;a=t}return a instanceof Ie?a:null}findParent(e){const t=this.dataProvider.getObjects().flatMap(t=>t.id===e.id?null:rt(t,t=>t.children?.some(t=>t.id===e.id),()=>!0))[0];return null==t?this.scene:null!=t?it(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 h(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse(e=>{e instanceof S&&e.geometry&&(t=e)}),t}applyVertexMaterials(e,t){const a=e.vertexMaterials??[];let s=1;for(const e of a)s=Math.max(e.w.length,s);const r=at(a,e=>e.m),i=new Set;t.traverse(e=>{if(e instanceof S){if(null==e.geometry)return;const t=e.geometry.getAttribute("material"),a=e.geometry.getAttribute("material2");null==t&&null==a||(rs(t),rs(a),i.add(e.name))}});for(const[e,a]of r.entries()){const r=null!=e?t.getObjectByName(e):this.findMeshWithGeometry(t);let n=!1;if(null==r||null==r.geometry)return void console.warn(`Failed to apply vertex materials on mesh with name "${e}"`);const o=vt(r,0,!0);rs(o);for(const e of a)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(s>0){const e=vt(r,4,!0);rs(e);for(const t of a)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&&i.add(e)}this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,e=>i.has(e.name)))}async materialize(e,t,a=!1,s){const r=this.getNestedActorId(e.id,s);if(null!=this.persistence&&!0!==s?.runtimeSpawn){if(this.isPersistenceRemoved(r))return;if("actor"===e.type){const e=this.persistence.resolve({sceneId:this.persistenceSceneId,path:r});if(null!=e)return void this.materializedActors.set(r,e)}}if(this.idToSceneObject.set(r,e),!this.shouldBeMaterialized(e))return;let i,n;switch(e.type){case"asset_mesh":i=await this.createFromAsset(e),e.latticeDeformation||(i=freezeSkinnedMeshes(i));break;case"shape_mesh":i=await this.createFromShape(e);break;case"light":i=await this.createLight(e);break;case"particles":i=await this.createParticleSystem(e),e.collisionDetection=!1;break;case"global_fog":this.scene.fog=Ea(e.fog),this.fixFogColor(),i=new g;break;case"sky":this.sky=Bt(),this.updateSky(e),i=this.sky;break;case"world_env":this.updateWorldEnv(e),i=new g,this.worldEnvObj=i;break;case"actor":({object:i,actor:n}=await this.createFromActor(e,s));break;case"group":case"scatter":i=new g;break;case"prefab":i=await this.createFromPrefab(e,s,t);break;case"vfx":i=await this.createFromVfx(e,s);break;default: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 or because of an error in the scene data. Scene object: id=${e.id}, name=${e.name}`)}if(null==i)return;e.name&&e.name.length>0&&(i.name=e.name),i.userData.detailCulling=e.detailCulling??i.userData.detailCulling,this.inEditor&&this.materializedSourceKinds.set(i,{id:e.id,name:e.name,type:e.type,assetId:e.assetId,actor:null==e.actor?void 0:{type:e.actor.type}}),this.applyTransform(e,i),a?i.userData._src=e:i.userData.src=e,null!=n&&(i.userData.actor=n,["NavMesh","NavMeshActor"].includes(e.actor?.type)&&(i.userData.navigationBake=this.navigationBakes[r]??this.navigationBakes[r.replace(/^\//,"")],this.inEditor&&(i.userData.navigationBakeSource=async()=>({objects:this.dataProvider.getObjects(),assets:await this.assetsService.getAssets(),loadCollisionShapes:async e=>(await this.assetManagerService.getMesh(e)).scene.collisionShapes??[]})),this.inEditor&&(i.userData.navigationBakeRevision=()=>this.navigationRevision))),this.inEditor,this.inEditor,this.objectMap.set(i.uuid,e),this.sceneObjectMap.set(e.id,i),e.physics?.type!==Pe.dynamic||null==t||this.inEditor?null==t?this.scene.add(i):null==t||"actor"!==e.type||this.inEditor?t?.add(i):(t.add(i),this.scene?.attach(i),console.log(i)):(t.add(i),i.getWorldPosition(ka),i.getWorldQuaternion(Ta),i.getWorldScale(Ba),this.scene.add(i),i.position.copy(ka),i.quaternion.copy(Ta),i.scale.copy(Ba)),null!=e.children&&await Promise.all(e.children?.map(e=>this.materialize(e,i,a,null==s?void 0:structuredClone(s))));const o=("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&e.physics?.type!==Pe.dynamic;if(this.inEditor&&o&&!function(e){for(let t=e;null!=t;t=t.parent)if(!0===t.userData.hologyEditorMatrixWorldAutoUpdate)return!0;return!1}(t)?Ia(i,!1):this.inEditor||null!=t||"asset_mesh"!=e.type&&"shape_mesh"!==e.type&&"prefab"!==e.type&&"group"!==e.type||"landscape"===e.shape||null!=e.physics?.type&&e.physics.type==Pe.dynamic||xa(i),null!=this.renderingView){if(o&&!e.children?.length){let e=!1;i.traverseAncestors(t=>{const a=t.userData.src;e||(e=null!=t.userData.actor||"actor"===a?.type||a?.physics?.type===Pe.dynamic)}),e||this.staticSpatialDisposers.set(i,this.renderingView.registerStaticSpatialObject(i))}return this.renderingView.invalidateShadows(),i}console.warn("RenderingView not found in materializer")}async handlePaintedScatterSceneMutation(e){const t=this.paintedScatterManager?.referencesSceneObject(e.id)??!1,a=await this.sceneObjectContainsPaintedScatter(e);(t||a)&&await this.refreshPaintedScatterPresence(!1)}async refreshPaintedScatterPresence(e=!1){return await this.sceneContainsPaintedScatter()?(null==this.paintedScatterManager&&(this.paintedScatterManager=new Mt(this.scene,this.dataProvider,this.renderingView,this.assetManagerService,this.assetsService)),this.paintedScatterManager.queueRefresh(e),!0):(this.disposePaintedScatterManager(),!1)}disposePaintedScatterManager(){null!=this.paintedScatterManager&&(this.paintedScatterManager.clear(),this.paintedScatterManager.stop(),this.paintedScatterManager=void 0)}async sceneContainsPaintedScatter(){return this.sceneObjectsContainPaintedScatter(this.dataProvider.getObjects())}async sceneObjectsContainPaintedScatter(e,t=[]){for(const a of e??[])if(await this.sceneObjectContainsPaintedScatter(a,t))return!0;return!1}async sceneObjectContainsPaintedScatter(e,t=[]){if("scatter"===e.type&&(e.paintedScatter?.cells?.some(e=>(e.instances?.length??0)>0)||(e.paintedScatter?.palette?.length??0)>0))return!0;if(null!=e.children&&await this.sceneObjectsContainPaintedScatter(e.children,t))return!0;if("prefab"===e.type&&null!=e.assetId){if(t.includes(e.assetId))return!1;const a=this.assets.get(e.assetId)??await this.assetsService.getAsset(e.assetId),s=a?.prefab?.objects;if(null!=s)return this.sceneObjectsContainPaintedScatter(s,[...t,e.assetId])}return!1}async handleSurfaceScatterSceneMutation(e){const t=this.surfaceScatterManager?.referencesSceneObject(e.id)??!1,a=await this.sceneObjectContainsSurfaceScatter(e);(t||a)&&await this.refreshSurfaceScatterPresence(!0)}async refreshSurfaceScatterPresence(e=!1){return await this.sceneContainsSurfaceScatter()?(null==this.surfaceScatterManager&&(this.surfaceScatterManager=new At(this.scene,this.dataProvider,this.renderingView,this.assetManagerService,this.assetsService)),this.surfaceScatterManager.queueRefresh(e),!0):(this.disposeSurfaceScatterManager(),!1)}disposeSurfaceScatterManager(){null!=this.surfaceScatterManager&&(this.surfaceScatterManager.clear(),this.surfaceScatterManager.stop(),this.surfaceScatterManager=void 0)}async sceneContainsSurfaceScatter(){return this.sceneObjectsContainSurfaceScatter(this.dataProvider.getObjects())}async sceneObjectsContainSurfaceScatter(e,t=[]){for(const a of e??[])if(await this.sceneObjectContainsSurfaceScatter(a,t))return!0;return!1}async sceneObjectContainsSurfaceScatter(e,t=[]){if("asset_mesh"===e.type&&(e.surfaceScatter?.meshes?.length??0)>0)return!0;if(null!=e.children&&await this.sceneObjectsContainSurfaceScatter(e.children,t))return!0;if("prefab"===e.type&&null!=e.assetId){if(t.includes(e.assetId))return!1;const a=this.assets.get(e.assetId)??await this.assetsService.getAsset(e.assetId),s=a?.prefab?.objects;if(null!=s)return this.sceneObjectsContainSurfaceScatter(s,[...t,e.assetId])}return!1}sceneReferencesPrefabAsset(e){const t=(a=[])=>{for(const s of a??[]){if("prefab"===s.type&&s.assetId===e)return!0;if(t(s.children))return!0}return!1};return t(this.dataProvider.getObjects())}async prefabAssetContainsSurfaceScatter(e){return"prefab"===e.type&&null!=e.prefab?.objects&&this.sceneObjectsContainSurfaceScatter(e.prefab.objects,[e.id])}async prefabAssetContainsPaintedScatter(e){return"prefab"===e.type&&null!=e.prefab?.objects&&this.sceneObjectsContainPaintedScatter(e.prefab.objects,[e.id])}applyTransform(e,t){null!=e.position&&t.position.fromArray(e.position),null!=e.scale&&t.scale.fromArray(e.scale),null!=e.rotation&&t.rotation.fromArray(e.rotation)}updateWorldEnv(e){this.renderingView.configureAmbientOcclusion(e.worldEnv.ao.enabled,e.worldEnv.ao.blendIntensity,e.worldEnv.ao);const t=e.worldEnv.toneMapping;null!=t&&this.renderingView.setBaseToneMapping(t.mapping??0,t.exposure??1);const a=e.worldEnv.environment,s=++this.worldEnvironmentRequest;null!=a&&null!=a.textureId?this.assetManagerService.getTexture(this.assets.get(a.textureId)).then(e=>{s===this.worldEnvironmentRequest&&(null!=e?this.renderingView.setWorldEnvironment({source:e,intensity:a.intensity??1}):console.error("Failed to load environment texture with id "+a.textureId))}):this.renderingView.setWorldEnvironment(null)}resetWorldEnv(){this.worldEnvironmentRequest++,this.renderingView.setWorldEnvironment(null),this.renderingView.configureAmbientOcclusion(!1),this.renderingView.setBaseToneMapping(c.NoToneMapping,1)}async updateSky(e){null!=this.sky&&(null==e?.sky?.materialId&&this.sky.material!==zt?(this.sky.material=zt,this.applySkySettings(this.sky.material)):null!=e?.sky?.materialId&&this.sky.material.userData?.assetId!==e.sky.materialId&&this.updateSkyMaterial(e),null!=e.rotation&&this.sky.rotation.fromArray(e.rotation))}async updateSkyMaterial(e){const t=await this.assetsService.getAsset(e.sky.materialId);if(null==t)return void console.warn(`No material asset found for sky with id ${e.sky.materialId}`);const 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){Tt(e,e===zt)}async createComponent(e,t,a,s){const r=new da[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??je[e.actor?.type];if(null==a)return console.warn(`Failed to materialize actor. No actor class found for type '${e.actor?.type}'.`),{object:null,actor:null};this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const s=await this.actorProvider.create(a,(new C).fromArray(e.position),(new p).fromArray(e.rotation),!0),r=this.getNestedActorId(e.id,t);return s.__netSceneId=r,this.applyInitialMaterializedNetRole(s),this.materializedActors.set(r,s),{object:s?.object,actor:s}}applyInitialMaterializedNetRole(e){if(this.inEditor||this.netMode===Oe.none)return;const t=De(e.constructor);!0!==t?.replicate?this.netMode===Oe.client&&(e.netRole=Ce.none):e.netRole=this.netMode===Oe.client?Ce.simulatedProxy:Ce.authority}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(ye,(new C).fromArray(e.position),(new p).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 S&&this._originalMaterials.set(e.id,e.material)});else{let s=new M({name:"Default",color:new h("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});!0===e.collider&&(s.opacity=.3,s.color.set(2517460),s.transparent=!0);const r=await this.createMeshByShape(e.shape,s,e.shapeParams);r.castShadow=e.castShadow??!0,r.receiveShadow=e.receiveShadow??!1,!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 g;const a=gt(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new mt(e,this.renderingView,a,this.assetManagerService,this.assetsService,this.shaders,async t=>{await Promise.all((e.materialAssignments??[]).filter(e=>null!=e.materialId).map(e=>this.applyMaterial(t,e))),this.inEditor||this.applyVertexMaterials({...e,vertexMaterials:e.vertexMaterials?.filter(e=>e.m===t.name)},t)},!this.inEditor&&!1!==e.landscape.staticDrawSets);return this.landscapeManagers.push(s),s.refreshGeometry(),a}applyHeightMaps(e,t,a=!1){const s=new yt(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(()=>wt(r),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&Et.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);if(!this.geometryCache.has(r)){const t=Ct[e].geometry(s);(function(e){return null!=e.index&&e.hasAttribute("position")&&e.hasAttribute("normal")&&e.hasAttribute("uv")})(t)&&t.computeTangents(),this.geometryCache.set(r,t)}this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,Ct[e].collision(s));return new ft(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 decodeModelImage(e){const t=e.image;if("function"!=typeof createImageBitmap||"undefined"==typeof HTMLImageElement||!(t instanceof HTMLImageElement))return;const a=e.source;let s=this.modelImageBitmaps.get(a);if(null==s){const e=()=>createImageBitmap(t,{imageOrientation:"none",premultiplyAlpha:"none",colorSpaceConversion:"none"}),r=t.currentSrc||t.src,i=/^(blob:|data:)/.test(r)?this.assetManagerService.decodeImageBitmap(r):void 0;s=(i?.catch(t=>(console.warn("Worker model image decode failed; decoding locally",t),e()))??e()).then(e=>{a.data===t?a.data=e:e.close()}).catch(e=>{console.warn("Could not decode model image before upload",e)}),this.modelImageBitmaps.set(a,s)}await s,a.data!==t&&(e.needsUpdate=!0)}async createFromAsset(e,t){const a=this.assets.get(e.assetId)??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(e.latticeDeformation&&(s=freezeSkinnedMeshes(s,!0),this.latticeGeometries.apply(s,e.latticeDeformation,JSON.stringify(e.vertexMaterials??[]))),!1!==t?.assignMaterials)try{await Promise.all(Ja(e.materialAssignments,a.materialAssignments).map(e=>this.applyMaterial(s,e,a)))}catch(t){console.error("Failed to apply material"+t,e)}const r=e.receiveShadow??!!a.receiveShadow,i=e.castShadow??!!a.castShadow;if(s.receiveShadow=r,ma(s,i,r),!1!==e.collisionDetection&&!1!==a.collisionDetection||(s.collisionShapes=[]),null!=e.physics&&!0!==this.inEditor&&(s.physics=e.physics),this.applyVertexMaterials(e,s),s.traverse(e=>{e instanceof S&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()}),s.userData.assetId=e.assetId,s.traverse(e=>{if(e instanceof S)for(const t of st(e.material))ze(t,!1)}),"webgpu"===this.renderingView.requestedBackend){await this.renderingView.initializeBackend();const e=new Set;s.traverse(t=>{if(t instanceof S)for(const a of st(t.material))if(a instanceof c.ShaderMaterial)for(const t of Object.values(a.uniforms)){const a=t.value;a instanceof P&&null!=a.image&&e.add(a)}else for(const t of Object.values(a))t instanceof P&&null!=t.image&&e.add(t)}),await Promise.all(Array.from(e,async e=>{await this.decodeModelImage(e),this.renderingView.initTexture(e)}))}return s}async createFromPrefab(e,t,a){const s=await this.assetsService.getAsset(e.assetId);if(null==s)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:r}=await this.createFromPrefabAsset(s,t,a,e);return t.sceneObjectChain.pop(),r}async createFromPrefabAsset(e,t,a,s,r=!0){this.assets.set(e.id,e);const i=new g;null!=s&&this.applyTransform(s,i),null!=a&&a.add(i),await Promise.all(e.prefab.objects.filter(e=>"global_fog"!==e.type&&"world_env"!==e.type).map(e=>this.materialize(e,i,!0,structuredClone(t))));const n=t.sceneObjectChain.join("/"),o=Array.from(this.materializedActors.entries()).filter(([e,t])=>e.startsWith(n+"/")&&!t.__isInitialised);o.forEach(e=>{});let l=null;if(null!=e.prefab?.mainActorId){const a=t.sceneObjectChain.join("/")+"/"+e.prefab.mainActorId;l=this.materializedActors.get(this.persistenceActorPath(a))??null}r||await this.initActorsPostInit(o);const c=Array.from(this.materializedActors.entries()).filter(([e])=>e.startsWith(n+"/")),u=c.map(([,e])=>e),d=new Map(c.map(([e,t])=>[e.slice(n.length+1),t]));if(this.assetsService.supportsLivePrefabParameters){let t=this.livePrefabInstances.get(e.id);null==t&&(t=new Map,this.livePrefabInstances.set(e.id,t));const a=new Map([...$a(e.prefab?.objects??[])].map(([t,a])=>[t,Fa(a,s,e.prefab?.mainActorId===t)]));t.set(n,{prefix:n,source:s,actorsById:d,actorSettingsById:a,desiredActorSettingsById:new Map(a)})}if(!this.inEditor&&!0!==t.runtimeSpawn&&oa(e.prefab?.eventGraph)&&this.materializedPrefabEventGraphs.set(n,{id:n,graph:e.prefab.eventGraph,object:i,actors:u,actorsById:d,mainActor:l}),null!=e.prefab?.mainActorId&&null!=s){const a=t.sceneObjectChain.join("/"),s=a+"/"+e.prefab.mainActorId;this.prefabInstanceExposedActorMap.set(a,s)}return{object:i,actors:u,actorsById:d,mainActor:l,instanceId:n}}async createParticleSystem(e){await this.assetsService.getAsset(e.assetId);return new x}async createLight(e){if("point"===e.light.type){const t=new D(e.light.point.color,e.light.point.intensity,Math.max(e.light.point.distance,0),e.light.point.decay);if(t.castShadow=e.light.point.castShadow??!0,t.userData.volumetricIntensity=e.light.point.volumetricIntensity,this.inEditor){const e=(new c.TextureLoader).load("assets/light-bulb-icon.webp"),a=new c.SpriteMaterial({map:e,alphaTest:.5}),s=new Jt(a);s.scale.multiplyScalar(.6),t.add(s)}return t}if("spot"===e.light.type){const t=new c.SpotLight(e.light.spot.color,e.light.spot.intensity,Math.max(e.light.spot.distance,0),e.light.spot.angle,e.light.spot.penumbra,e.light.spot.decay);if(t.castShadow=e.light.spot.castShadow??!0,t.userData.volumetricIntensity=e.light.spot.volumetricIntensity,t.map=await this.loadSpotLightMap(e.light.spot.mapTextureId),t.target=new x,t.target.position.set(0,-1,0),t.add(t.target),this.inEditor){const e=(new c.TextureLoader).load("assets/light-bulb-icon.webp"),a=new c.SpriteMaterial({map:e,alphaTest:.5}),s=new Jt(a);s.scale.multiplyScalar(.6),t.add(s),t.add(new c.SpotLightHelper(t))}return t}if("rectArea"===e.light.type){const t=new c.RectAreaLight(e.light.rectArea.color,e.light.rectArea.intensity,e.scale?e.scale[0]:1,e.scale?e.scale[1]:1);if(this.inEditor){const e=(new c.TextureLoader).load("assets/light-bulb-icon.webp"),a=new c.SpriteMaterial({map:e,alphaTest:.5}),s=new Jt(a);s.scale.multiplyScalar(.6),t.add(s);const r=new ea(t);t.add(r)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional,e),new g):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient,e),new g):void 0}async loadSpotLightMap(e){if(null==e)return null;const t=this.assets.get(e);return null==t||"texture"!==t.type?null:await this.assetManagerService.getTexture(t)}applyDirectionalAmbientLight(e,t,a){const s=this.scene.children.find(e=>e.name===kt);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){this.renderingView.csm.lightIntensity=e.intensity;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(e){for(const e of this.staticSpatialDisposers.values())e();this.staticSpatialDisposers.clear();for(const e of this.landscapeManagers)e.stop();if(this.landscapeManagers.length=0,this.latticeGeometries.dispose(),this.editorStaticDisposed=!0,this.disposeEditorStaticDrawSet(),this.editorStaticEditingObjects.clear(),this.editorStaticSelectedObjects.clear(),this.editorStaticObjectsToRebuild.clear(),this.editorStaticDrawSetUpdated$.complete(),this.experimentalStaticDrawSetDisposer?.(),this.experimentalStaticDrawSetDisposer=void 0,this.removePrefabEventGraphs(),this.livePrefabInstances.clear(),this.updateSubscription.unsubscribe(),this.createAssetSubscription.unsubscribe(),this.disposePaintedScatterManager(),this.disposeSurfaceScatterManager(),this.sceneSettingsActive){this.worldEnvironmentRequest++,this.renderingView.setWorldEnvironment(null),this.renderingView.configureAmbientOcclusion(!1),this.renderingView.setBaseToneMapping(c.NoToneMapping,1),this.scene.fog=this.originalFog;const e=this.renderingView.csm,t=this.originalGlobalLight;if(null!=e&&null!=t){e.lightDirection.copy(t.direction),e.lightIntensity=t.intensity;for(let a=0;a<e.lights.length&&a<t.lights.length;a++){const s=e.lights[a],r=t.lights[a];s.intensity=r.intensity,s.color.copy(r.color),s.castShadow=r.castShadow,s.userData.src=r.src,s.userData.volumetricIntensity=r.volumetricIntensity}}this.sceneSettingsActive=!1}this.materializedActors.forEach(t=>{e?.has(t)||t.disposed.next(!0)}),this.materializedActors.clear()}announcePrefabEventGraphs(e){for(const[t,a]of this.materializedPrefabEventGraphs)(null==e||t===e||t.startsWith(e+"/"))&&(this.announcedPrefabEventGraphs.has(t)||(this.announcedPrefabEventGraphs.add(t),this.prefabEventGraphAdded$.next(a)))}removePrefabEventGraphs(e){const t=[];for(const[a,s]of[...this.materializedPrefabEventGraphs])(null==e||a===e||a.startsWith(e+"/"))&&(t.push(s),this.prefabEventGraphRemoved$.next(s),this.materializedPrefabEventGraphs.delete(a),this.announcedPrefabEventGraphs.delete(a));return t}};fa=e([ge(),t("design:paramtypes",[I,Object,dt,ut,Te,Array,Array,Object,Array])],fa);export{fa as SceneMaterializer};function ma(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse(e=>{e.castShadow=t,e.receiveShadow=a})}const ga=new Map,ya=new Map,wa=new b({color:16711935}),Sa=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){if(null==e||null==e.material)return console.error("Asset or asset material is null",e),wa;const n=JSON.stringify(e.material)+t?._id,o=i&&!("shaderGraph"===e.material.type&&"asset"===e.material.shaderGraph?.source);if(o&&ga.has(n))return ga.get(n);if(o&&ya.has(n))return await ya.get(n);const l=_materialFromAsset(n,e,t,a,s,r,o);return o?ya.set(n,l).get(n):l}export async function _materialFromAsset(e,t,a,s,r,i,o=!0){const l={opacity:t.material.params?.opacity??1,map:null,emissive:t.material.params?.emissive??null,metalness:t.material.params?.metalness??0,flatShading:t.material.params?.flatShading??!1,color:new h(t.material.params?.color),transparent:null!=t.material.params?.opacity&&t.material.params?.opacity<1},u={};if(null!=t.material.params?.map){const e=t.material.params.map,a=await s.getAsset(e);null!=a&&(l.map=await r.getTexture(a))}let d,p,f;switch(t.material.type){case"phong":d=new v({...l,...u});break;case"water":d=xt(l,a);break;case"grassFoliage":d=St({color:l.color,map:l.map},a);break;case"grass":d=bt({...l,colorTwo:new h(t.material.params.colorTwo),colorThree:new h(t.material.params.colorThree)},a);break;case"shaderGraph":{const e=await async function(e,t){const a=e.material?.shaderGraph;if("local"===a?.source)return a.graph;if("asset"===a?.source){const e=await t.getAsset(a.assetId);return e?.shaderGraph??null}return e.shaderGraph??null}(t,s);if(null==e){console.warn("Missing shader graph for material "+t.name),d=wa;break}"surface"===e.target&&null!=e.materialOptions?.side&&(p=na(e.materialOptions.side)),"decal"===e.target?f=!1:null!=e.materialOptions?.transparent&&(f=e.materialOptions.transparent);try{const n=await prepareShaderGraphParameters(t.material?.shaderParams??{},e,s,r,a,i),o=t.shaderGraphPreviewNodeId,l=t.trailBillboard;d=ia(e,{parameters:n,previewNodeId:o,trailBillboard:l,alphaTest:t.material.alphaTest}),d.userData.customShaderName="asset"===t.material.shaderGraph?.source?`shaderGraph:${t.material.shaderGraph.assetId}`:`shaderGraph:${t.id}`}catch(e){console.warn("Shader graph runtime error: "+e,e),d=wa}break}case"standard":case"unlit":case"toon":case"layered":case"lambert":case"shader":case"landscape":case"landscape-composite":case"decal-unlit":case"decal-standard":case"sprite":const e={standard:ha?Fe:_e,lambert:Fe,unlit:Ge,toon:Qt,layered:Gt,landscape:We,"landscape-composite":Re,"decal-unlit":Nt,"decal-standard":$t,sprite:n}[t.material.type]??i.find(e=>e.name==t.material.shader)?.type;if(e){try{let n=new e;const o=await prepareClassParameters(t.material?.shaderParams??{},e,s,r,null,a,i,void 0,void 0,n);Object.assign(n,o),n.alphaTest=t.material.alphaTest??n.alphaTest,d=n.build()}catch(e){console.log("Shader runtime error: "+e,e),Sa.has(t.material.shader)||Sa.set(t.material.shader,wa.clone()),d=Sa.get(t.material.shader)}d.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),d=wa;break;default:throw new Error("Unsupported material type "+t.material.type)}if(a?.csm.setupMaterial(d),d.side=p??t.material.side??d.side??c.FrontSide,d.transparent=(f??t.material.transparent??l.transparent??!1)||d.transparent,d.alphaTest=t.material.alphaTest??d.alphaTest??0,d.userData.receiveDecals=t.material.receiveDecals??!0,null!=t.material.blending&&(d.blending=Ee[t.material.blending]??c.NormalBlending),!0===t.material.transparent&&(d.depthWrite=!1),t.material.bloom&&(d.userData.hasBloom=!0),t.material.reflective&&(d.userData.reflective=!0),!0===t.material.outlines&&(d.userData.outlineParameters={},null!=t.material.outlineParams&&(null!=t.material.outlineParams.color&&(d.userData.outlineParameters.color=new h(t.material.outlineParams.color).toArray()),null!=t.material.outlineParams.thickness&&(d.userData.outlineParameters.thickness=t.material.outlineParams.thickness),null!=t.material.outlineParams.opacity&&(d.userData.outlineParameters.alpha=t.material.outlineParams.opacity),null!=t.material.outlineParams.colorMode&&(d.userData.outlineParameters.colorMode=t.material.outlineParams.colorMode),null!=t.material.outlineParams.darkening&&(d.userData.outlineParameters.darkening=t.material.outlineParams.darkening))),null!=t.material.surfaceAssetId&&""!==t.material.surfaceAssetId){const e=await materializeDataAssetRef(t.material.surfaceAssetId,s,r,void 0,a,i);null!=e&&(d.userData.surface=e.value)}return d.userData.assetId=t.id,o&&null!=a&&ga.set(e,d),o&&ya.delete(e),d}export function prepareCustomParamsFromShaderGraph(e,t={}){return Object.fromEntries((e.parameters??[]).map(e=>{const a=function(e){switch(e){case"float":return Dt.FloatNode;case"boolean":return Dt.BooleanNode;case"texture":return Dt.Sampler2DNode;case"vec2":return Dt.Vec2Node;case"vec3":return Dt.Vec3Node;case"vec4":return Dt.Vec4Node;case"color":return Dt.RgbNode}}(e.type),s=t[e.name],r=s?.override??null!=s,i=void 0!==e.defaultValue?e.defaultValue:customParameterDefaultValueByType.get(a),n=!1===r?qa(i):s?.value??qa(i);return[e.name,{type:a,value:n,override:r}]}))}export async function prepareShaderGraphParameters(e,t,a,s,i,n,o=!1){const l={},c=prepareCustomParamsFromShaderGraph(t,e),u=Object.entries(c),d=await Promise.all(u.map(([e,t])=>{if(o&&t.type===Dt.FloatNode){const a=t.value,s=e=>"string"==typeof e?parseFloat(e):Number(e);if(null!=a&&"object"==typeof a&&"a"in a&&"b"in a)return null==a.a?null:r(e,s(a.a),null==a.b?void 0:s(a.b),"easing"in a?String(a.easing):void 0);if(null!=a&&""!==a)return r(e,s(a))}return va(e,t,a,s,null,i,n)}));for(let e=0;e<u.length;e++){const[t]=u[e],a=d[e];null!=a&&(l[t]=a)}return l}export async function prepareClassParameters(e,t,a,s,r,i,n,o,l,c){const u={},{params:d,skipped:h}=It(e,{parameterType:t,parameterTarget:c,extractPropertyParameters:Le,toSerializedParamType:toSerializedParamType});for(const e of h)console.warn(`Skipping stored parameter "${e.key}" because it could not be converted from ${Dt[e.sourceType]} to ${Dt[e.targetType]}`);for(const[e,t]of Object.entries(d)){if(!1===t.override)continue;const c=await va(e,t,a,s,r,i,n,o,void 0,void 0,l);null!=c&&(u[e]=c)}return u}export async function prepareShapeParameters(e,t,a){const s={};for(const[r,i]of Object.entries(e)){const e=await va(r,i,t,a,null,void 0,void 0,void 0,void 0,void 0);null!=e&&(s[r]=e)}return s}const ba=new Map;async function va(e,t,a,s,r,i,n,o,l=t.value,c=t.type,u,d=(t.type===Dt.Struct?t.struct:void 0)){if(null==t||null==l||""===l)return null;switch(c){case Dt.Array:if(Array.isArray(l)&&"element"in t)return await Promise.all(l.map(l=>va(e,t,a,s,r,i,n,o,l,t.element,u,t.elementStruct)));break;case Dt.Number:case Dt.FloatNode:let f;if("string"==typeof l?f=parseFloat(l):"number"==typeof l&&(f=l),c===Dt.FloatNode){if("object"==typeof l&&"a"in l&&"b"in l){const t=l;if(null==t.a)return null;const a="string"==typeof t.a?parseFloat(t.a):t.a;if(null==t.b)return a;const s="string"==typeof t.b?parseFloat(t.b):t.b,r=function(e){let t=ba.get(e);return null==t&&(t=Ve(Vt.decode(e)),ba.set(e,t)),t}(t.easing),i=r.sample(Ne($e.energy)),n=new re(Xe(e)+"_curveEndpoints",new O(a,s),void 0,!1);return L(n.x,n.y,i)}return new ae(Xe(e),f,void 0,!1)}return f;case Dt.Texture:let m=await s.getTexture(await a.getAsset(l));return"envmap"===e.toLowerCase()&&null!=i&&(m=i.getEnvTexture(m)),m;case Dt.Sampler2DNode:const g=await a.getAsset(l);if(null!=g?.texture?.textureArrayFileKey){const{texture:t,layerIndex:a}=await s.getTextureArray(g);if(t&&null!=a)return new se(null,t,new ae(Xe(e)+"_i",a,void 0,!1))}const y=await s.getTexture(g);return y?X(y):null;case Dt.Boolean:return l;case Dt.BooleanNode:return new te(Xe(e),l,void 0,!1);case Dt.Vector2:case Dt.Vec2Node:if("object"==typeof l){const t=l instanceof Array?(new O).fromArray(l):new O(l.x,l.y);return c===Dt.Vec2Node?new re(Xe(e),t,void 0,!1):t}return null;case Dt.Vector3:case Dt.Vec3Node:if("object"==typeof l){const t=l instanceof Array?(new C).fromArray(l):new C(l.x,l.y,l.z);return c===Dt.Vec3Node?new ie(Xe(e),t,void 0,!1):t}return null;case Dt.Vector4:case Dt.Vec4Node:if("object"==typeof l){const t=l instanceof Array?(new E).fromArray(l):new E(l.x,l.y,l.z,l.w);return c===Dt.Vec4Node?new ne(Xe(e),t,void 0,!1):t}return null;case Dt.Color:case Dt.RgbNode:const w=new h(l);return c===Dt.RgbNode?new ie(Xe(e),new C(w.r,w.g,w.b),void 0,!1).rgb:w;case Dt.String:return l;case Dt.Scene:return"string"==typeof l?new Me(l):"object"==typeof l&&null!=l&&"string"==typeof l.id?new Me(l.id,"string"==typeof l.name?l.name:void 0):null;case Dt.ModelRef:return"string"==typeof l?new Ae(l):null;case Dt.BaseActor:const S=l;if(null==r&&console.warn("Class parameters can not be prepared as actors are not passed in"),null==S)return null;if("object"==typeof S&&null!=S.type&&null!=S.id){if("actor"===S.type)return r?.get(S.id)??null;if("prefab"===S.type){const e=u?u(S.id):null;if(null!=e)return r?.get(e)??null;const t=[];for(const[e,a]of r?.entries()??[])e.startsWith(S.id+"/")&&t.push(a);return 1===t.length?t[0]:null}}if("string"==typeof S){const e=r?.get(S);if(null!=e)return e;const t=u?u(S):null;if(null!=t)return r?.get(t)??null;const a=[];for(const[e,t]of r?.entries()??[])e.startsWith(S+"/")&&a.push(t);return 1===a.length?a[0]:null}return null;case Dt.Euler:const b=l;return(new p).fromArray(b);case Dt.Object3D:{const e=await a.getAsset(l),t=(await s.getMesh(e,{applyMaterials:!0,rescale:!0,mergeGeomtries:!0})).scene;return t.userData.vfxIncludeRootTransform=!0,t}case Dt.Material:{if(null==l)return null;const e=await a.getAsset(l);if(null==e)return console.warn("Material asset not found for material parameter",l),null;if("shaderGraph"===e.type&&null!=e.shaderGraph){const t=`shaderGraphParameter:${e.id}:${JSON.stringify(e.shaderGraph)}:${i?._id??"none"}`,r=ga.get(t);if(null!=r)return r;const o=await prepareShaderGraphParameters({},e.shaderGraph,a,s,i,n),l=ia(e.shaderGraph,{parameters:o});return l.userData.assetId=e.id,l.userData.assetName=e.name,ga.set(t,l),l}return null==e.material?(console.warn("Using a non-material asset for material parameter"),null):await materialFromAsset(e,i,a,s,n)}case Dt.AudioBuffer:return await s.getAudio(await a.getAsset(l));case Dt.VisualEffect:const v=await a.getAsset(l);if(null==o){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in v)return new we(o,v);console.error("Using a non-vfx asset for visual effect parameter");break;case Dt.Prefab:{const e=await a.getAsset(l);return null==e?(console.error("Using a non-prefab asset for prefab parameter",l),null):new Se(e)}case Dt.PrefabActor:{const e=await a.getAsset(l);return null==e?(console.error("Using a non-prefab asset for prefab parameter",l),null):new be(new Se(e))}case Dt.DataAsset:return materializeDataAssetRef(l,a,s,r,i,n,o,u);case Dt.Sequence:{if("string"!=typeof l)return console.warn("Invalid sequence parameter value",l),null;const e=await a.getAsset(l);if("sequence"===e?.type&&"sequence"in e)return new sa(e.sequence);console.error("Using a non-sequence asset for sequence parameter");break}case Dt.SequenceData:return aa(l)?l:(console.warn("Invalid inline sequence data parameter value",l),null);case Dt.Struct:return async function(e,t,a,s,r,i,n,o,l){const c=Ma(e),u=c?.struct??t;if(null==u)return console.warn("Missing parameter definition id for struct parameter"),null;const d=Qe(u);if(null==d)return console.warn(`Unknown parameter definition "${u}"`),null;if(He(u))return console.warn(`Can not instantiate abstract parameter definition "${u}"`),null;if(null!=t&&u!==t&&!Ke(u,t))return console.warn(`Parameter definition "${u}" is not assignable to "${t}"`),null;let h;try{h=new d}catch(e){return console.warn(`Failed to instantiate parameter definition "${u}"`,e),null}const p=function(e){const t=Ma(e);if(null!=t)return t.value;if(Aa(e))return e;if(null!=e&&"object"==typeof e&&Aa(e.params))return e.params;return{}}(c?.value??e),f=await prepareClassParameters(p,null,a,s,r,i,n,o,l,h);return Object.assign(h,f),h}(l,d,a,s,r,i,n,o,u);case Dt.Curve:return Vt.decode(l);case Dt.ColorLayer:case Dt.MaskLayer:if(Lt(l)){const e=await Ft.decode(l,async e=>await s.getTexture(await a.getAsset(e))),t=await prepareClassParameters(l.params,null,a,s,void 0,void 0,void 0,void 0,void 0,e);return Object.assign(e,t),e}return console.warn("Expecting color layer but got",l),null;case Dt.AnimationClip:{const e="string"==typeof l?l:"object"==typeof l&&null!=l?l.assetId:null;if(null==e)return console.warn("Invalid animation clip asset id value",l),null;return await s.getAnimationClip(await a.getAsset(e))}}return null}export async function materializeDataAssetRef(e,t,a,s,r,i,n,l){const c="string"==typeof e?e:null!=e&&"object"==typeof e?e.assetId??e.id:null;if(null==c||""===c)return null;const u=await t.getAsset(c);if(null==u)return console.warn(`Data asset "${c}" was not found`),null;if("data"!==u.type||null==u.dataAsset)return console.warn("Using a non-data asset for data asset parameter",c),null;const d=u.dataAsset.definition;if(null==d||""===d)return console.warn(`Missing data asset definition id for asset "${u.id}"`),null;if(Ye(d))return console.warn(`Can not instantiate abstract data asset definition "${d}"`),null;const h=qe(d);if(null==h)return console.warn(`Unknown data asset definition "${d}"`),null;let p;try{p=new h}catch(e){return console.warn(`Failed to instantiate data asset definition "${d}"`,e),null}const f=u.dataAsset.params??{};if("object"!=typeof f||Array.isArray(f))return console.warn(`Invalid data asset params for asset "${u.id}"`),null;try{const e=await prepareClassParameters(f,null,t,a,s,r,i,n,l,p);Object.assign(p,e)}catch(e){return console.warn(`Failed to materialize data asset "${u.id}"`,e),null}const m=t.supportsLiveDataAssets?new o(e=>{let o=0;const c=t.onUpdate.subscribe(c=>{if(c.id!==u.id||"data"!==c.type)return;const d=++o;materializeDataAssetRef(u.id,t,a,s,r,i,n,l).then(t=>{e.closed||d!==o||null==t||e.next(t)}).catch(e=>console.warn(`Failed to reload data asset "${u.id}"`,e))});return()=>c.unsubscribe()}):void 0;return new ve(u,p,m)}function Ma(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.struct&&Aa(e.value)?e:null}function Aa(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&Object.values(e).every(e=>null!=e&&"object"==typeof e&&"type"in e)}function xa(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 Da(){}const ja=new WeakMap;function Ia(e,t){if(t)return e.userData.hologyEditorMatrixWorldAutoUpdate=!0,void e.traverse(e=>{const t=ja.get(e);if(null!=t){e.updateMatrixWorld=t.updateMatrixWorld;for(const[e,a]of t.matrixAutoUpdate)e.matrixAutoUpdate=a}});const a=!0===e.userData.hologyEditorMatrixWorldAutoUpdate,s=[];e.traverse(e=>{ja.has(e)&&s.push(e)}),0!==s.length||a||s.push(e);for(const e of s)Pa(e);delete e.userData.hologyEditorMatrixWorldAutoUpdate}function Pa(e){const t=ja.get(e);if(e.updateMatrix(),e.updateWorldMatrix(!0,!0),null==t){const t=new Map;e.traverse(e=>{t.set(e,e.matrixAutoUpdate)}),ja.set(e,{updateMatrixWorld:e.updateMatrixWorld,matrixAutoUpdate:t})}e.traverse(e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1}),e.updateMatrixWorld=Da}function Oa(e,t=!1){return Array.isArray(e)?e.every(e=>Oa(e,t)):t||!e.transparent&&!Ca(e)}function Ca(e){return e instanceof q&&(null!=e.uniforms[la]||null!=e.uniforms.hology_scene_map)}function Ea(e){return"linear"===e.type?new f(new h(e.color),e.near??100,e.far??1e3):"density"===e.type?new m(e.color,e.density):void console.warn("Invalid fog type",e)}const ka=new C,Ta=new j,Ba=new C;new M({color:4229780});async function za(e,t,a,s){null==s&&(s=(new w).identity());const r=s.clone().multiply(Va(e,new c.Matrix4));if(null!=e.children&&e.children.length>0)for(let a=e.children.length-1;a>=0;a--)await za(e.children[a],t,e,r);await t(e,a,s)}function Va(e,t){return null==e.position||null==e.rotation||null==e.scale?t.identity():t.compose((new C).fromArray(e.position),(new j).setFromEuler((new p).fromArray(e.rotation)),(new C).fromArray(e.scale))}export function toSerializedParamType(e){if(null==e)return;if("function"!=typeof e||null==e.prototype)return void console.warn("Failed to map parameter type to serialized version",{type:e});const t=e.constructor.prototype;return t instanceof Number||e===Number?Dt.Number:t instanceof _||"function"==typeof e.prototype.isFloat?Dt.FloatNode:t instanceof P||e===P||e.isTexture?Dt.Texture:t instanceof Ue||e===Ue||e===K||"function"==typeof e.prototype?.isSampler2D||!0===e.prototype?.isSampler2D?Dt.Sampler2DNode:t instanceof Boolean||e===Boolean?Dt.Boolean:t instanceof U?Dt.BooleanNode:t instanceof h||e==h?Dt.Color:t instanceof Y||"function"==typeof e.prototype.isRgb?Dt.RgbNode:t instanceof O||e==O?Dt.Vector2:t instanceof de||"function"==typeof e.prototype.isVec2?Dt.Vec2Node:t instanceof C||e==C?Dt.Vector3:t instanceof pe||"function"==typeof e.prototype.isVec3?Dt.Vec3Node:t instanceof E||e==E?Dt.Vector4:t instanceof me||"function"==typeof e.prototype.isVec4?Dt.Vec4Node:t instanceof String||e===String?Dt.String:t instanceof Me||e===Me?Dt.Scene:t instanceof Ae||e===Ae?Dt.ModelRef:t instanceof xe||e==xe||e.prototype instanceof xe||e.prototype==xe?Dt.BaseActor:t instanceof p||e==p?Dt.Euler:t instanceof x||e==x?Dt.Object3D:t instanceof y||e==y?Dt.Material:t instanceof AudioBuffer||e==AudioBuffer?Dt.AudioBuffer:t instanceof we||e==we?Dt.VisualEffect:t instanceof Se||e==Se?Dt.Prefab:t instanceof be||e==be?Dt.PrefabActor:t instanceof ve||e==ve?Dt.DataAsset:t instanceof Vt||e==Vt?Dt.Curve:t instanceof Ft||e==Ft?Dt.ColorLayer:t instanceof _t||e==_t?Dt.MaskLayer:t instanceof c.AnimationClip||e==c.AnimationClip?Dt.AnimationClip:t instanceof sa||e==sa?Dt.Sequence:"SequenceData"===e.name||e.prototype&&"tracks"in e.prototype?Dt.SequenceData:null!=Je(e)?Dt.Struct:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function getCustomParamTypeInfo(e){const t=e.type===Object?void 0:toSerializedParamType(e.type),a=t===Dt.Struct?Je(e.type):void 0;return!0===e.options.array?{type:Dt.Array,element:t,...null!=a?{elementStruct:a}:{}}:{type:t,...null!=a?{struct:a}:{}}}export function prepareCustomParams(e,t,a={},s={}){return Object.fromEntries(e.map(e=>{const r=getCustomParamTypeInfo(e);let i=r;const n=t[e.name],o=Na(n)?n:void 0,l=!0===s.treatAllAsOptional||!0===e.options.optional,c=s.missingOverrideDefaultsToOverride??!0;let u=o?.override;void 0===u&&null!=n&&l&&c&&(u=!0),void 0===u&&l&&(u=!1);const d=void 0!==a[e.name]||void 0!==e.options.defaultValue,h=function(e,t){if(null==e.type){const a=function(e){return aa(e)?{type:Dt.SequenceData}:void 0}(t);null!=a&&(e=a)}if(e.type!==Dt.Struct)return{typeInfo:e,value:t};const a=Ma(t);if(null==a)return{typeInfo:e,value:t};return{typeInfo:{...e,struct:a.struct},value:a.value}}(i,function(e,t){if(void 0!==t[e.name])return t[e.name];if(void 0!==e.options.defaultValue){const t=serializeCustomParameter(e.type,e.options.defaultValue);return void 0!==t?t:e.options.defaultValue}const a=toSerializedParamType(e.type);if(a===Dt.Struct)return He(e.type)?{}:prepareCustomParamsFromType(e.type,{});return customParameterDefaultValueByType.get(a)}(e,a)),p=function(e,t){if(Na(e))return e;if(null!=e&&"object"==typeof e&&!Array.isArray(e)&&"value"in e){const a=e;return{...t,value:a.value,..."boolean"==typeof a.override?{override:a.override}:{}}}if(t.type!==Dt.SequenceData||!aa(e))return;return{type:Dt.SequenceData,value:e}}(n,h.typeInfo);i=function(e,t,a){if(e.type!==Dt.Struct||a?.type!==Dt.Struct||null==a.struct)return e;const s=t.struct??e.struct;if(null==s||a.struct===s||Ke(a.struct,s)||null==Qe(a.struct))return{...e,struct:a.struct};return e}(h.typeInfo,r,p);const f=!1!==u||e.options.array?p?.value??function(e,t,a){if(!0===e.options.array)return a?qa(t):[];return qa(t)}(e,h.value,d):qa(h.value),m=function(e,t,a){if(t.type===Dt.Struct){if(null!=t.struct&&He(t.struct))return a;const s=null!=t.struct?Qe(t.struct):e.type;return null!=s&&Aa(a)?prepareCustomParamsFromType(s,a):a}if(t.type!==Dt.Array||t.element!==Dt.Struct||!Array.isArray(a))return a;const s=null!=t.elementStruct?Qe(t.elementStruct):e.type;return a.map(e=>{const a=Ma(e),r=a?.struct??t.elementStruct;if(null!=r&&He(r))return e;const i=null!=a?Qe(a.struct):s,n=a?.value??(Aa(e)?e:null);if(null==i||null==n)return e;const o=prepareCustomParamsFromType(i,n);return null!=a?{struct:a.struct,value:o}:o})}(e,i,f);return[e.name,{...i,value:m,override:u}]}))}function Na(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"number"==typeof e.type&&"value"in e}function $a(e){const t=new Map,a=e=>{for(const s of e)"actor"===s.type&&null!=s.actor&&t.set(s.id,s.actor),null!=s.children&&a(s.children)};return a(e),t}function Ua(e){const t=new Map,a=e=>{for(const s of e)"prefab"===s.type&&t.set(s.id,s),null!=s.children&&a(s.children)};return a(e),t}function Fa(e,t,a){if(!a||"prefab"!==t?.type||null==t.prefab)return e;const s=new Map((e.innerParams??[]).map(e=>[JSON.stringify(e.path),{path:e.path,params:{...e.params}}]));for(const e of t.prefab.innerParams??[]){const t=JSON.stringify(e.path),a=s.get(t);s.set(t,{path:e.path,params:{...a?.params??{},..._a(e.params)}})}return{...e,params:{...e.params??{},..._a(t.prefab.params)},innerParams:[...s.values()]}}function Ra(e,t,a){const s=new Map((e.innerParams??[]).map(e=>[JSON.stringify(e.path),e])),r=new Map((t.innerParams??[]).map(e=>[JSON.stringify(e.path),e])),i=new Map((a.innerParams??[]).map(e=>[JSON.stringify(e.path),e])),n=[];for(const e of new Set([...s.keys(),...r.keys(),...i.keys()])){const t=s.get(e),a=r.get(e),o=i.get(e),l=Wa(t?.params??{},a?.params??{},o?.params??{});Object.keys(l).length>0&&n.push({path:a?.path??o?.path??t.path,params:l})}return{...t,params:Wa(e.params??{},t.params??{},a.params??{}),innerParams:n}}function Wa(e,t,a){const s={};for(const r of new Set([...Object.keys(e),...Object.keys(t),...Object.keys(a)]))JSON.stringify(a[r])!==JSON.stringify(e[r])?null!=a[r]&&(s[r]=a[r]):null!=t[r]&&(s[r]=t[r]);return s}function _a(e){return null==e?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>function(e){return!0===e?.override}(e)))}function Ga(e,t){return e.length>=t.length&&t.every((t,a)=>e[a]===t)}export function prepareCustomParamsFromType(e,t,a=null,s={}){const r=Le(e);if(0===r.length)return{};let i;null!=a?ke(a,()=>{i=a.get(e)}):i=new e;const n={};for(const e of r){const t=i[e.name];if(null!=t){const a=La(e,t);void 0!==a&&(n[e.name]=a)}}return prepareCustomParams(r,t,n,s)}function La(e,t){return!0===e.options.array?Array.isArray(t)?t.map(t=>serializeCustomParameter(e.type,t)??t):[]:serializeCustomParameter(e.type,t)}function qa(e){return null==e?e:Array.isArray(e)?e.map(e=>qa(e)):"object"==typeof e?"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e)):e}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 O:return t instanceof O?t.toArray():void a();case C:return t instanceof C?t.toArray():void a();case E:return t instanceof E?t.toArray():void a();case h:return t instanceof h?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new h(t).getHexString():void a();case String:return t;case p:return t instanceof p?t.toArray():void a();case Se:return t instanceof Se?t.asset?.id??null:void a();case ve:return t instanceof ve?t.id:"string"==typeof t?t:void a();case Me:return t instanceof Me?{id:t.id,...null!=t.name?{name:t.name}:{}}:void a();case Ae:return t instanceof Ae?t.id:"string"==typeof t?t:void a()}const s=Je(e);if(null!=s){const r=Ma(t);if(null!=r)return r.struct===s?r.value:r;const i=function(e,t){if(null==t||"object"!=typeof t)return e;const a=t.constructor;return null!=Je(a)&&Ze(a,e)?a:e}(e,t),n=Je(i),o=function(e,t){if(null==t)return null;if(Aa(t))return t;if(null!=t&&"object"==typeof t&&Aa(t.params))return t.params;if("object"!=typeof t)return;const a=Le(e),s={};for(const e of a){const a=t[e.name];if(void 0===a)continue;const r=La(e,a);void 0!==r&&(s[e.name]=r)}return prepareCustomParams(a,{},s)}(i,t);return void 0!==o?null!=o&&null!=n&&n!==s?{struct:n,value:o}:o:void a()}if(aa(t))return t}function Ja(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=>Qa(e.materialId)),(t??[]).filter(e=>Qa(e.materialId)),e=>e.name?`name:${e.name}`:`color:${e.color}`)}function Qa(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[Dt.RgbNode,"#000000"],[Dt.Color,"#000000"],[Dt.String,""],[Dt.Scene,null],[Dt.ModelRef,null],[Dt.Vector4,[0,0,0,0]],[Dt.Vec4Node,[0,0,0,0]],[Dt.Vector3,[0,0,0]],[Dt.Vec3Node,[0,0,0]],[Dt.Vector2,[0,0]],[Dt.Vec2Node,[0,0]],[Dt.Euler,[0,0,0,"XYZ"]],[Dt.Array,[]],[Dt.DataAsset,null],[Dt.SequenceData,ta()],[Dt.ColorLayer,Rt],[Dt.MaskLayer,Wt]]);let Ya=new h;new h;function Ha(e){return null==e?.color?null:(Ya.set(e.color),"#"+Ya.getHexString())}function Za(e,t,a,s){const r="string"==typeof t.name&&""!==t.name?t.name:null;if(null!=r)return e.name===r||s===r;const i=Ha(e);return null!=i&&i===t.color||null!=a&&a===t.color}export function applyMaterial(e,t,a,s,r={}){const i=[];return e.traverse(e=>{(e instanceof S||e.isMesh||e instanceof c.SkinnedMesh||e.isSkinnedMesh)&&i.push(e)}),Promise.all(i.map(async e=>{if(e.material instanceof Array)for(let i=0;i<e.material.length;i++){const n=e.material[i];if(null==n)continue;const o=Ha(n),l=n.name;if(Za(n,t,e.userData["originalColor_"+i],e.userData["originalMaterialName_"+i])){const n=Xa(await a(t.materialId),r.textureFlipY),c=e.material[i];if(null!=n&&c.id!=n.id&&(e.material[i]=n,e.userData["originalColor_"+i]=e.userData["originalColor_"+i]??o,e.userData["originalMaterialName_"+i]=e.userData["originalMaterialName_"+i]??l,null!=s)){const t=e.id+"#"+i;s.has(t)||s.set(t,c)}}}else if(null!=e.material){const i=e.material,n=Ha(i),o=i.name;if(Za(i,t,e.userData.originalColor,e.userData.originalMaterialName)){const i=Xa(await a(t.materialId),r.textureFlipY),l=e.material;null!=i&&(e.material=i,e.userData.originalColor=e.userData.originalColor??n,e.userData.originalMaterialName=e.userData.originalMaterialName??o,null!=s&&(s.has(e.id)||s.set(e.id,l)))}}}))}const Ka=new WeakMap;export function getConvertedFbxToGlbAssignedMaterialTextureFlipY(e){const t=e?.mesh?.uvConversion;return"fbx2gltf"===t?.source?!0!==t.flipV&&void 0:!function(e){return"glb"===e?.fileFormat&&!0===e.originalFileKey?.toLowerCase().endsWith(".fbx")}(e)&&void 0}function Xa(e,t){if(null==e||null==t||!function(e,t){return function(e){const t=[];for(const[a,s]of Object.entries(e))ts(a,s)&&t.push(s);if(e instanceof c.ShaderMaterial)for(const[a,s]of Object.entries(e.uniforms))ts(a,s.value)&&t.push(s.value);return t}(e).some(e=>e.flipY!==t)}(e,t))return e;let a=Ka.get(e);null==a&&(a=new Map,Ka.set(e,a));const s=a.get(t);if(null!=s)return s;const r=es(e);if(function(e,t){for(const a of Object.keys(e)){const s=e[a];ts(a,s)&&(e[a]=as(s,t))}}(r,t),r instanceof c.ShaderMaterial){for(const[e,a]of Object.entries(r.uniforms))ts(e,a.value)&&(a.value=as(a.value,t));r.uniformsNeedUpdate=!0}return r.needsUpdate=!0,a.set(t,r),r}function es(e){const t=e.clone();return t.userData={...e.userData??{}},t}function ts(e,t){const a=t;return(t instanceof P||!0===a?.isTexture)&&!e.toLowerCase().includes("envmap")&&!0!==a.isCompressedTexture&&!0!==a.isCompressedArrayTexture}function as(e,t){if(e.flipY===t)return e;const a=e.clone();return a.flipY=t,a.userData={...e.userData??{}},a.needsUpdate=!0,a}function ss(e,t){if(e instanceof c.ShaderMaterial&&t instanceof c.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof c.ShaderMaterial&&t instanceof c.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 rs(e){null!=e&&(e.array.fill(0),e.needsUpdate=!0)}function is(e,t){const a=nt(e);return null==a?"":function(e,t){const a=Bs(e,t),s=a.sort().map(t=>{const a=e.getAttribute(t);if(null!=a){const e=a.array??a.data?.array,s=e?.constructor?.name??"";return`${t}:${a.itemSize}:${a.normalized?1:0}:${s}`}const s=function(e,t){if("uv"===t&&cs(e))return{itemSize:2,normalized:!1,arrayType:"Float32Array"};throw new Error(`Unsupported synthetic batching geometry attribute: ${t}`)}(e,t);return`${t}:${s.itemSize}:${s.normalized?1:0}:${s.arrayType}`}).join(",");return`${null!=e.index?"indexed":"nonindexed"}|${s}`}(a.geometry,t)}function ns(e,t){const a=Bs(e,t);if(a.length===Object.keys(e.attributes).length)return e;const s=new d;s.name=e.name;const r=e.getIndex();null!=r&&s.setIndex(r);for(const t of a)s.setAttribute(t,ls(e,t));for(const t of e.groups)s.addGroup(t.start,t.count,t.materialIndex);return s.setDrawRange(e.drawRange.start,e.drawRange.count),null!=e.boundingBox&&(s.boundingBox=e.boundingBox.clone()),null!=e.boundingSphere&&(s.boundingSphere=e.boundingSphere.clone()),s.userData=e.userData,s}const os=new WeakMap;function ls(e,t){return e.getAttribute(t)??function(e,t){if("uv"===t)return function(e){let t=os.get(e);const a=e.getAttribute("position");if(null==a)throw new Error("Can not create synthetic batching UVs without a position attribute");null!=t&&t.count===a.count||(t=new c.Float32BufferAttribute(new Float32Array(2*a.count),2),os.set(e,t));return t}(e);throw new Error(`Unsupported synthetic batching geometry attribute: ${t}`)}(e,t)}function cs(e){return null!=e.getAttribute("position")}const us=new WeakMap,ds="hbat_",hs=new Set(["ambientLightColor","cameraNear","directionalLightShadows","directionalLights","directionalShadowMap","directionalShadowMatrix","fogColor","fogDensity","fogFar","fogNear","hemisphereLights","lightProbe","ltc_1","ltc_2","pointLightShadows","pointLights","pointShadowMap","pointShadowMatrix","receiveShadow","rectAreaLights","shadowFar","spotLightMap","spotLightMatrix","spotLightShadows","spotLights","spotShadowMap"]);function ps(e){let t=us.get(e);return null==t&&(t=function(e){let t=e.type;if(e instanceof q)t+=function(e){let t="nodeShader";t+=function(e){if(null==e)return"";let t="";for(const a of Object.keys(e).sort())t+=`${a}:${String(e[a])};`;return t}(e.defines),t+=e.lights?"lights":"",t+=e.fog?"fog":"";for(const a of Object.keys(e.uniforms).sort()){if(gs(a))continue;const s=e.uniforms[a]?.value;ws(s)||(t+=`u:${a}:${xs(s)};`)}return t+=ms(e.vertexShader),t+=ms(e.fragmentShader),t}(e);else if(e instanceof c.MeshStandardMaterial&&!(e instanceof c.MeshPhysicalMaterial)||(t+=e.id+""),(e instanceof c.MeshBasicMaterial||e instanceof c.MeshLambertMaterial||e instanceof M||e instanceof v)&&(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 M&&(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 c.MeshPhysicalMaterial&&(null!=e.sheenColorMap&&(t+="sc"+e.sheenColorMap?.id),null!=e.sheenRoughnessMap&&(t+="sr"+e.sheenRoughnessMap?.id)),(e instanceof b||e instanceof v)&&null!=e.specularMap&&(t+="s"+e.specularMap?.id),e instanceof c.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 Ht&&null!=e.heightMap&&(t+="h"+e.heightMap?.id),e instanceof c.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,t+=e.userData.outlineParameters.alpha,t+=e.userData.outlineParameters.colorMode,t+=e.userData.outlineParameters.darkening);return t+=`side:${e.side};shadowSide:${e.shadowSide??"auto"};`,t+=e.transparent?"t":"",t+=e.vertexColors?"vc":"",t+=e.depthWrite?"dw":"",t+=e.depthTest?"dt":"",t+=`alphaTest:${e.alphaTest>0};`,t}(e),us.set(e,t)),t}const fs=new Map;function ms(e){return fs.has(e)||fs.set(e,`shader_${fs.size}`),fs.get(e)}function gs(e){return hs.has(e)||e.startsWith("hology_")}function ys(e,t){return e instanceof q?e.uniforms[t]?.value:e[t]}function ws(e){return"number"==typeof e||e instanceof O||e instanceof C||e instanceof E||e instanceof h}function Ss(e){return"number"==typeof e?1:e instanceof O?2:4}function bs(e,t){const a=e.replace(/[^A-Za-z0-9_]/g,"_");let s=ds+a;for(;t.has(s);)s=ds+s;return t.add(s),s}function vs(e,t){const a={};for(const[s,r]of Object.entries(e.uniforms))t.has(s)||(a[s]={value:r.value});return a}const Ms=new WeakMap;let As=1;function xs(e){if(null==e)return"null";if(e instanceof P||!0===e?.isTexture)return`texture:${e.id}`;if(e instanceof c.Matrix3||e instanceof c.Matrix4)return e.toArray().join(",");if("boolean"==typeof e||"number"==typeof e||"string"==typeof e)return String(e);if(Array.isArray(e)&&e.every(e=>null==e||["boolean","number","string"].includes(typeof e)))return JSON.stringify(e);if("object"==typeof e){let t=Ms.get(e);return null==t&&(t=As++,Ms.set(e,t)),`object:${t}`}return String(e)}function Ds(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 js=new w,Is=new p;function Ps(e,t){return Is.copy(e),Is.x*=-1,Is.y*=-1,Is.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(Is.y*=-1,Is.z*=-1),(new c.Matrix3).setFromMatrix4(js.makeRotationFromEuler(Is))}function Os(e,t){switch(t){case 0:return e.x;case 1:return e.y;case 2:return e.z;case 3:return e.w}}const Cs=new E;function Es(e,t){return e===t||null==e==(null==t)&&("number"==typeof e&&"number"==typeof t?e===t||isNaN(e)&&isNaN(t):e instanceof c.Color&&t instanceof c.Color?e.r===t.r&&e.g===t.g&&e.b===t.b:e instanceof O&&t instanceof O?e.x===t.x&&e.y===t.y:e instanceof C&&t instanceof C?e.x===t.x&&e.y===t.y&&e.z===t.z:e instanceof E&&t instanceof E&&(e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w))}function ks(e){const t=[];for(const[a,s]of Object.entries(e))s instanceof we?t.push(s):s instanceof Ie&&t.push(...ks(s));return t}const Ts=new WeakMap;function Bs(e,t){const a=Object.keys(e.attributes).filter(a=>zs(e,t,a));return!e.hasAttribute("uv")&&cs(e)&&zs(e,t,"uv")&&a.push("uv"),a}function zs(e,t,a){return"position"===a||("uv"===a?function(e){if(e instanceof q)return Ns(e,"uv");if(e instanceof c.ShaderMaterial)return $s(e.vertexShader,"uv");if(e instanceof Ht&&null!=e.heightMap)return!0;return Vs.some(t=>e[t]?.isTexture)}(t):t instanceof q?Ns(t,a):t instanceof c.ShaderMaterial?function(e,t){if("uv1"===t||"uv2"===t||"uv3"===t)return $s(e.vertexShader,t);return!0}(t,a):"uv1"!==a&&(("color"!==a||!function(e){let t=Ts.get(e);if(null!=t)return t;const a=e.getAttribute("color");if(null==a)t=!1;else{t=!0;for(let e=0;e<a.count;e++){for(let s=0;s<3;s++)if(1!==a.getComponent(e,s)){t=!1;break}if(!t)break}}return Ts.set(e,t),t}(e))&&("uv2"!==a||(null!=t.lightMap||null!=t.aoMap))))}const Vs=["map","alphaMap","emissiveMap","normalMap","bumpMap","displacementMap","roughnessMap","metalnessMap","aoMap","specularMap","gradientMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","iridescenceMap","iridescenceThicknessMap","sheenColorMap","sheenRoughnessMap","transmissionMap","thicknessMap","anisotropyMap"];function Ns(e,t){return $s(e.vertexShader,t)}function $s(e,t){return new RegExp(`(^|[^A-Za-z0-9_])${a=t,a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}([^A-Za-z0-9_]|$)`).test(e);var a}function Us(e,t,a){if(t(e))return e;for(const s of e.children??[]){const e=Us(s,t,a);if(null!=e)return e}if(null!=a&&"prefab"===e.type){const s=a.get(e.assetId);if(null!=s){const e=s.prefab.objects.find(e=>Us(e,t,a));if(null!=e)return e}}return null}const Fs=new C,Rs=new C,Ws=new C,_s=new E,Gs=new E,Ls=new w,qs=new w,Js=new A;export function freezeSkinnedMeshes(e,t=!1){if(null==e)return e;e.updateWorldMatrix(!0,!0);const a=[];e.traverse(e=>{e.isSkinnedMesh&&a.push(e)});let s=e;for(const e of a){const a=Qs(e,t),r=e.parent;if(null==r){s=a;continue}const i=r.children.indexOf(e);e.removeFromParent(),r.add(a);const n=r.children.indexOf(a);i>=0&&n>=0&&n!==i&&(r.children.splice(n,1),r.children.splice(i,0,a))}return function(e){const t=[];e.traverse(e=>{e.isBone&&t.push(e)});for(const e of t)null!=e.parent&&!e.parent.isBone&&Hs(e)&&e.removeFromParent()}(s),s}function Qs(e,t){e.updateWorldMatrix(!0,!1);const a=e.geometry.clone();t&&s(a,JSON.stringify([e.geometry.uuid,e.bindMatrix.elements,e.bindMatrixInverse.elements,e.skeleton.bones.map((t,a)=>(new w).multiplyMatrices(t.matrixWorld,e.skeleton.boneInverses[a]).elements)]));const r=a.getAttribute("position"),i=a.getAttribute("normal"),n=a.getAttribute("tangent");if(null!=r){for(let t=0;t<r.count;t++)Fs.fromBufferAttribute(r,t),e.applyBoneTransform(t,Fs),r.setXYZ(t,Fs.x,Fs.y,Fs.z);r.needsUpdate=!0}if(null!=i||null!=n){const t=a.getAttribute("skinIndex"),s=a.getAttribute("skinWeight");if(null!=t&&null!=s){for(let a=0;a<t.count;a++)Ys(e,a,qs),null!=i&&(Rs.fromBufferAttribute(i,a),Js.getNormalMatrix(qs),Rs.applyMatrix3(Js).normalize(),i.setXYZ(a,Rs.x,Rs.y,Rs.z)),null!=n&&(Ws.fromBufferAttribute(n,a),Ws.transformDirection(qs),n.setXYZ(a,Ws.x,Ws.y,Ws.z));null!=i&&(i.needsUpdate=!0),null!=n&&(n.needsUpdate=!0)}}a.deleteAttribute("skinIndex"),a.deleteAttribute("skinWeight"),a.computeBoundingBox(),a.computeBoundingSphere();const o=new S(a,e.material);return o.copy(e,!1),o.geometry=a,o.material=e.material,o.userData={...e.userData},o}function Ys(e,t,a){const s=e.geometry,r=s.getAttribute("skinIndex"),i=s.getAttribute("skinWeight"),n=e.skeleton;_s.fromBufferAttribute(r,t),Gs.fromBufferAttribute(i,t),a.identity().multiplyScalar(0);for(let e=0;e<4;e++){const t=Gs.getComponent(e);if(0===t)continue;const s=_s.getComponent(e);Ls.multiplyMatrices(n.bones[s].matrixWorld,n.boneInverses[s]);for(let e=0;e<16;e++)a.elements[e]+=Ls.elements[e]*t}return a.premultiply(e.bindMatrixInverse).multiply(e.bindMatrix),a}function Hs(e){let t=!0;return e.traverse(a=>{a===e||a.isBone||(t=!1)}),t}function Zs(e,t){let a=t??!1,s=!0;for(const t of e)if(!1!==t.castShadow){s=!1;break}for(const t of e)if(!0===t.castShadow)return!0;return a&&!s}function Ks(e,t){let a=t??!1,s=!0;for(const t of e)if(!1!==t.receiveShadow){s=!1;break}if(s)return!1;for(const t of e)if(!0===t.receiveShadow)return!0;return a&&!s}/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|