@hology/core 0.0.264 → 0.0.266

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.
Files changed (95) hide show
  1. package/dist/effects/sequence/sequence-player.js +1 -1
  2. package/dist/effects/vfx/gpu-material-uniforms.d.ts +23 -0
  3. package/dist/effects/vfx/gpu-material-uniforms.js +4 -0
  4. package/dist/effects/vfx/gpu-sprite-runtime.js +1 -1
  5. package/dist/effects/vfx/vfx-actor.d.ts +6 -0
  6. package/dist/effects/vfx/vfx-actor.js +1 -1
  7. package/dist/effects/vfx/vfx-materializer.d.ts +1 -0
  8. package/dist/effects/vfx/vfx-materializer.js +1 -1
  9. package/dist/effects/vfx/vfx-param.js +1 -1
  10. package/dist/effects/vfx/vfx-render-preparation.d.ts +8 -0
  11. package/dist/effects/vfx/vfx-render-preparation.js +4 -0
  12. package/dist/gameplay/actors/builtin/components/character/character-animation.d.ts +53 -0
  13. package/dist/gameplay/actors/builtin/components/character/character-animation.js +1 -1
  14. package/dist/gameplay/actors/builtin/components/character/character-movement.js +1 -1
  15. package/dist/gameplay/ai/behavior-tree/behavior-tree.d.ts +33 -0
  16. package/dist/gameplay/ai/behavior-tree/behavior-tree.js +4 -0
  17. package/dist/gameplay/ai/behavior-tree/behavior-tree.test.d.ts +2 -0
  18. package/dist/gameplay/ai/behavior-tree/behavior-tree.test.js +4 -0
  19. package/dist/gameplay/ai/behavior-tree/bt.d.ts +92 -70
  20. package/dist/gameplay/ai/behavior-tree/bt.js +1 -1
  21. package/dist/gameplay/ai/behavior-tree/bt.test.d.ts +2 -0
  22. package/dist/gameplay/ai/behavior-tree/bt.test.js +4 -0
  23. package/dist/gameplay/ai/behavior-tree/move.d.ts +1 -0
  24. package/dist/gameplay/ai/behavior-tree/move.js +1 -1
  25. package/dist/gameplay/ai/index.d.ts +1 -0
  26. package/dist/gameplay/ai/index.js +1 -1
  27. package/dist/gameplay/animation/foot-contact-baker.d.ts +23 -0
  28. package/dist/gameplay/animation/foot-contact-baker.js +4 -0
  29. package/dist/gameplay/animation/foot-contact.d.ts +27 -0
  30. package/dist/gameplay/animation/foot-contact.js +4 -0
  31. package/dist/gameplay/animation/locomotion-body.d.ts +62 -0
  32. package/dist/gameplay/animation/locomotion-body.js +4 -0
  33. package/dist/gameplay/animation/pose-inertialization.d.ts +46 -0
  34. package/dist/gameplay/animation/pose-inertialization.js +4 -0
  35. package/dist/gameplay/animation/root-motion.js +1 -1
  36. package/dist/gameplay/index.d.ts +4 -0
  37. package/dist/gameplay/index.js +1 -1
  38. package/dist/gameplay/initiate.js +1 -1
  39. package/dist/gameplay/input/input-service.d.ts +4 -0
  40. package/dist/gameplay/input/input-service.js +1 -1
  41. package/dist/gameplay/rendering-host.d.ts +2 -1
  42. package/dist/gameplay/rendering-host.js +1 -1
  43. package/dist/gameplay/services/physics/physics-system.d.ts +7 -0
  44. package/dist/gameplay/services/physics/physics-system.js +1 -1
  45. package/dist/gameplay/services/render.d.ts +2 -0
  46. package/dist/gameplay/services/render.js +1 -1
  47. package/dist/rendering/webgpu-experimental-backend.d.ts +1 -1
  48. package/dist/rendering/webgpu-experimental-backend.js +1 -1
  49. package/dist/rendering.d.ts +4 -2
  50. package/dist/rendering.js +1 -1
  51. package/dist/scene/animation-binary.d.ts +6 -0
  52. package/dist/scene/animation-binary.js +4 -0
  53. package/dist/scene/asset-resource-loader.d.ts +3 -1
  54. package/dist/scene/asset-resource-loader.js +1 -1
  55. package/dist/scene/landscape/landscape-manager.d.ts +4 -1
  56. package/dist/scene/landscape/landscape-manager.js +1 -1
  57. package/dist/scene/landscape/landscape-static-draw-sets.d.ts +18 -0
  58. package/dist/scene/landscape/landscape-static-draw-sets.js +4 -0
  59. package/dist/scene/materializer.d.ts +2 -0
  60. package/dist/scene/materializer.js +1 -1
  61. package/dist/shader/shader.d.ts +8 -0
  62. package/dist/test/animation-binary.test.d.ts +2 -0
  63. package/dist/test/animation-binary.test.js +4 -0
  64. package/dist/test/character-foot-contact.test.d.ts +2 -0
  65. package/dist/test/character-foot-contact.test.js +4 -0
  66. package/dist/test/character-inertialization.test.d.ts +2 -0
  67. package/dist/test/character-inertialization.test.js +4 -0
  68. package/dist/test/character-movement-solve.test.d.ts +2 -0
  69. package/dist/test/character-movement-solve.test.js +4 -0
  70. package/dist/test/foot-contact.test.d.ts +2 -0
  71. package/dist/test/foot-contact.test.js +4 -0
  72. package/dist/test/gpu-material-uniforms.test.d.ts +2 -0
  73. package/dist/test/gpu-material-uniforms.test.js +4 -0
  74. package/dist/test/gpu-sprite-pipeline-cache.test.d.ts +2 -0
  75. package/dist/test/gpu-sprite-pipeline-cache.test.js +4 -0
  76. package/dist/test/input.test.js +1 -1
  77. package/dist/test/landscape-static-draw-sets.test.d.ts +2 -0
  78. package/dist/test/landscape-static-draw-sets.test.js +4 -0
  79. package/dist/test/locomotion-body.test.d.ts +2 -0
  80. package/dist/test/locomotion-body.test.js +4 -0
  81. package/dist/test/physics-ray-object.test.d.ts +2 -0
  82. package/dist/test/physics-ray-object.test.js +4 -0
  83. package/dist/test/pose-inertialization.test.d.ts +2 -0
  84. package/dist/test/pose-inertialization.test.js +4 -0
  85. package/dist/test/renderer-loading.test.d.ts +2 -0
  86. package/dist/test/renderer-loading.test.js +4 -0
  87. package/dist/test/rendering-host.test.js +1 -1
  88. package/dist/test/sequence-property-parameters.test.js +1 -1
  89. package/dist/test/sequence-vfx.test.js +1 -1
  90. package/dist/test/vfx-render-preparation.test.d.ts +2 -0
  91. package/dist/test/vfx-render-preparation.test.js +4 -0
  92. package/dist/utils/structs.d.ts +4 -0
  93. package/dist/utils/structs.js +4 -0
  94. package/package.json +4 -2
  95. 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";export{createLatticeDeformation,latticePoint,isValidLattice,deformLatticeGeometry,LatticeGeometryCache}from"./lattice-deformation.js";import{ConvexPolyhedronCollisionShape as r}from"./collision/collision-shape.js";import{SpriteShader as i}from"../shader/sprite-shader.js";import{Observable as n,Subject as o}from"rxjs";import*as l from"three";import{BoxGeometry as c,BufferGeometry as u,Color as d,Euler as h,Fog as p,FogExp2 as f,Group as m,Material as g,Matrix4 as y,Mesh as w,MeshLambertMaterial as S,MeshPhongMaterial as b,MeshStandardMaterial as v,Matrix3 as M,Object3D as A,PointLight as x,Quaternion as j,Scene as I,Texture as P,Vector2 as D,Vector3 as O,Vector4 as C}from"three";import{attributes as E,batchingUniformFloat as k,batchingUniformVec2 as T,batchingUniformVec3 as B,batchingUniformVec4 as V,bool as z,BooleanExpression as N,BooleanNode as $,colorToNormal as U,float as F,deriveNodeShaderMaterial as W,FloatNode as R,ifDefApply as _,mix as G,NodeShaderMaterial as L,rgb as q,rgba as J,RgbNode as Y,select as Q,standardMaterial as H,Texture2dLookupNode as Z,textureSampler2d as X,textureSampler2dArray as K,UniformBoolNode as ee,UniformFloatNode as te,UniformSampler2dArraySlice as ae,UniformVec2Node as se,UniformVec3Node as re,UniformVec4Node as ie,varying as ne,varyingAttributes as oe,varyingTransformed as le,vec2 as ce,Vec2Node as ue,vec3 as de,Vec3Node as he,vec4 as pe,Vec4Node as fe}from"three-shader-graph";import{Service as me}from"typedi";import{VfxActor as ge}from"../effects/vfx/vfx-actor.js";import{VisualEffect as ye}from"../effects/vfx/vfx-param.js";import{Prefab as we,PrefabOf as Se}from"./objects/prefab.js";import{DataAssetRef as be}from"./objects/data-asset.js";import{SceneRef as ve}from"./scene-ref.js";import{ModelRef as Me}from"./model-ref.js";import{BaseActor as Ae,getActorOptions as xe}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 De}from"../gameplay/net/net-session.js";import{NetRole as Oe}from"../gameplay/net/service/net-actor-role.js";import{ThreeBlendingMode as Ce}from"../effects/vfx/vfx-asset.js";import{withInjectionContext as Ee}from"../gameplay/inject.js";import{RenderingView as ke}from"../rendering.js";import{markMaterialUniformValuesNeedUpdate as Te,setMaterialUniformValuesAutoUpdate as Be}from"../rendering/node-material-webgpu-resolver.js";import{curveSampler as Ve,oneMinus as ze,particleUniforms as Ne,Sampler2DNode as $e}from"../shader-nodes/index.js";import{LambertShader as Ue}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as Fe}from"../shader/builtin/landscape-composite-shader.js";import{LandscapeShader as We}from"../shader/builtin/landscape-shader.js";import{StandardShader as Re}from"../shader/builtin/standard-shader.js";import{UnlitShader as _e}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as Ge,getDataAssetDefinitionType as Le,getParameterDefinitionId as qe,getParameterDefinitionType as Je,isDataAssetDefinitionAbstract as Ye,isParameterDefinitionAbstract as Qe,isParameterDefinitionAssignableTo as He,isParameterDefinitionStructAssignableTo as Ze,shaderParameterUniformName as Xe}from"../shader/parameter.js";import{ArrayMap as Ke,DefaultMap as et,groupBy as tt}from"../utils/collections.js";import{iterateMaterials as at}from"../utils/materials.js";import{filterChildrenShallow as st,filterSceneShallow as rt,findFirstVisibleMesh as it,findFirstVisibleObject as nt,traverseAsync as ot}from"../utils/three/traverse.js";import{AssetMeshInstance as lt,AssetResourceLoader as ct}from"./asset-resource-loader.js";import{AssetsProvider as ut}from"./assets-provider.js";import{isCollisionMesh as dt}from"./collision/collision-shape-import.js";import{BoxCollisionShape as ht,PhysicalShapeMesh as pt}from"./collision/collision-shape.js";import{LandscapeManager as ft}from"./landscape/landscape-manager.js";import{initLandscape as mt}from"./landscape/landscape.js";import{SectionGrid as gt,smoothNormalsCrossMeshes as yt}from"./landscape/utils.js";import{createGrassFoliageMaterial as wt}from"./materials/grass-foliage.js";import{createGrassMaterial as St}from"./materials/grass.js";import{getMaterialAttribute as bt}from"./materials/utils/material-painting.js";import{PaintedScatterManager as vt}from"./scatter/painted-scatter-manager.js";import{SurfaceScatterManager as Mt}from"./scatter/surface-scatter-manager.js";import{createWaterMaterial as At}from"./materials/water.js";import{SerializedParamType as xt}from"./model.js";import{applyRuntimeParamTypeInference as jt,convertConfiguredParamsToRuntimeTypes as It,convertConfiguredParamValueToRuntimeType as Pt,inferRuntimeSerializedParamTypeHint as Dt}from"./custom-param-runtime-types.js";import{ShapeLibrary as Ot,ShapeLibraryKeys as Ct}from"./objects/shapes.js";import{ambientLightName as Et,createSky as kt,defaultSkyMaterial as Tt}from"./sky.js";import{Curve2 as Bt}from"../utils/curve.js";import{DecalUnlitShader as Vt}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as zt}from"../shader/builtin/decal-standard-shader.js";import{ClusterGenerator as Nt}from"../rendering/cluster-generator.js";import{ColorLayer as $t,defaultValueColorLayer as Ut,defaultValueMaskLayer as Ft,MaskLayer as Wt}from"../shader/color-layer.js";import{LayeredShader as Rt}from"../shader/builtin/layered-shader.js";import{isColorLayerSerialized as _t}from"../shader/color-layer.js";import{FogVolume as Gt}from"../rendering/fog/fog-volume-actor.js";import{UnscaledSprite as Lt}from"../utils/three/unscaled-sprite.js";import{ToonShader as qt}from"../shader/builtin/toon-shader.js";import{BatchedMesh2 as Jt}from"./batched-mesh-2.js";import{ParallaxStandardMaterial as Yt}from"../shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Qt}from"../shader-nodes/pom.js";import{traverseVisibleEvery as Ht}from"../utils/three/traverse.js";import{BufferGeometryUtils as Zt,RectAreaLightHelper as Xt}from"three/examples/jsm/Addons.js";import{createSequenceData as Kt,isSequenceData as ea,Sequence as ta}from"../effects/sequence/sequence-data.js";import{applyUvTiling as aa}from"./../shader/uv-nodes.js";import{buildShaderGraphMaterial as sa,shaderGraphMaterialSideToThree as ra}from"../shader/graph/index.js";import{hasExecutableEventGraphDocument as ia}from"../gameplay/event-graph/model.js";import{depthUniformName as na}from"../shader-nodes/depth.js";export{jt as applyRuntimeParamTypeInference,It as convertConfiguredParamsToRuntimeTypes,Pt as convertConfiguredParamValueToRuntimeType,Dt as inferRuntimeSerializedParamTypeHint};const oa={},la=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),ca=/^((?!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 ua(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}let ua=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,c,u,d=[]){this.scene=e,this.dataProvider=t,this.assetsService=s,this.assetManagerService=r,this.renderingView=i,this.shaders=n,this.actorTypes=c,this.actorProvider=u,this.componentTypes=d,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=De.none,this.updated$=new o,this.removed$=new o,this.prefabEventGraphAdded$=new o,this.prefabEventGraphRemoved$=new o,this.error$=new o,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.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 o,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.update(e).finally(()=>this.scheduleEditorStaticDrawSetRebuild()),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),t.onUpdate(e=>{this.prepareEditorStaticObjectForMutation(e),this.update(e).finally(()=>this.scheduleEditorStaticDrawSetRebuild(e)),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),t.onRemove(e=>{this.prepareEditorStaticObjectForMutation(e),this.remove(e),this.scheduleEditorStaticDrawSetRebuild(),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),this.createAssetSubscription=s.onCreate.subscribe(e=>{this.assets.set(e.id,e)}),this.updateSubscription=s.onUpdate.subscribe(async t=>{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 l.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=>zs(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 Ea(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 w)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 Ea(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 l.SpotLight&&"spot"===t.userData?.src?.light?.type&&t.userData.src.light.spot.mapTextureId===e.id&&s.push(t),t instanceof w&&(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 l.ShaderMaterial){for(const a of Object.values(e.uniforms))if(a.value instanceof l.Texture&&a.value.userData.assetId===t)return!0}else for(const a of Object.values(e))if(a instanceof l.Texture&&a.userData.assetId===t)return!0;return!1}replaceMaterialTextureReferences(e,t,a){let s=!1;if(e instanceof l.ShaderMaterial)for(const[r,i]of Object.entries(e.uniforms))i.value instanceof l.Texture&&i.value.userData.assetId===t&&(e.uniforms[r].value=a,s=!0);else for(const[r,i]of Object.entries(e))i instanceof l.Texture&&i.userData.assetId===t&&(e[r]=a,s=!0);s&&(e.needsUpdate=!0,Te(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===xt.Material&&s.value===a.id){t=!0;break}if(s.type===xt.Array&&"element"in s&&s.element===xt.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?Ka(e.material[s],i)||(e.material[s]=i):Ka(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===xt.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(),ha.clear(),pa.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)Aa(e,!1);this.editorMatrixWorldEditingObjects.clear();for(const t of e)this.editorMatrixWorldEditingObjects.add(t),Aa(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)Aa(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 m;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 m;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 m;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;(dt(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=va}0!==t.children.length&&(ba(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 w&&!dt(e)&&(t=!0,null!=e.geometry?.index&&null==e.customDepthMaterial&&ja(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=new Set,a=new Set,s=[],r=new I;for(const i of e){const e=i.asset;if(t.has(e.id))continue;t.add(e.id),Os(e,a);const n=await i.create(r);r.add(n.object);const o=n.particleSystemContainer;null!=o&&r.add(o),n.play(),n.onUpdate(.5),n.stop(),n.pause(),s.push(n)}await this.initVfxTextures(a);const i=this.renderingView.compileAsync(r);this.renderingView.initTextures(r),await i;for(const e of s)e.onEndPlay(),e.disposed.next(!0),e.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=>Ds(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,Ua(s.prefab.params)),null!=s.prefab.innerParams){const e=r.slice(t+1);for(const t of s.prefab.innerParams){const a=Ua(t.params);0!==Object.keys(a).length&&(n?c.push({path:Fa(t.path,e)?t.path.slice(e.length):t.path,params:a}):Fa(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!==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=>{!dt(e)&&e.isMesh&&s.push(e)});const r=1==s.length&&0==s[0].children.length,i=!ca,n=s.every(e=>!Array.isArray(e.material)||1===e.material.length),o=s.some(e=>e instanceof w&&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,ha.clear(),pa.clear();const e=[],t=new Ke,a=new Ke,s=new Ke;let r=0,i=0,n=0;const o=new Map,c=new et(()=>new Map),u="webgpu"===this.renderingView?.requestedBackend?new m:null,p=null!=u?new m:null;null!=u&&(u.name="Hology WebGPU static scene objects",p.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&&ja(e.material,!0)}(t)){((Array.isArray(t.material)?t.material:[t.material]).some(e=>e.transparent||Ia(e))?p:u).add(e)}else this.scene.add(e)};for(const l of this.dataProvider.getObjects())await Ea(l,async(l,u,h)=>{if(!this.shouldBeMaterialized(l))return;const p="asset_mesh"==l.type&&this.canObjectBeInstanced(l)&&await this.canAssetBeInstanced(l),f="shape_mesh"===l.type&&"landscape"!==l.shape&&l.physics?.type!==Pe.dynamic;if(p||f){if(u&&u.children?.length>0){const e=u.children.findIndex(e=>e.id===l.id);e>=0&&u.children.splice(e,1)}if(f){let e=l.shape+JSON.stringify(l.shapeParams??{})+l.castShadow+l.receiveShadow;const t=l.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===xt.Color&&null!=e.value&&(r=new d(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:{...l,parentTransform:h},color:r}),n++}else{const e=this.assets.get(l.assetId);null==e&&console.log("Can't find asset with id "+l.assetId);let s=o.get(l.assetId);if(null==s){const e=await this.createFromAsset(l,{assignMaterials:!1});if(null==e)return;if(s=o.get(l.assetId),null==s){s={useBatchedMesh:null!=it(e)&&Ht(e,e=>!(e instanceof w)||this.testCanBatch(e.material,e.geometry)),assetMesh:e},o.set(l.assetId,s)}}const n=_a(l.materialAssignments,e.materialAssignments);if(s.useBatchedMesh)await ot(s.assetMesh,async t=>{if(!(t instanceof w))return;const s=Array.isArray(t.material)?t.material[0]:t.material,i=await this.resolveMaterialForAssignments(s,n,e);if(null!=i){Be(i,!1),c.get(l.id).set(t.uuid,i);let s=ts(t,i);if(s+=cs(i),"webgpu"===this.renderingView?.requestedBackend){s+=`|castShadow:${l.castShadow??e.castShadow??!1?1:0}|receiveShadow:${l.receiveShadow??e.receiveShadow??!1?1:0}`}a.push(s,{...l,parentTransform:h,meshUUID:t.uuid}),r++}else console.warn("Can not materialize mesh because missing material",l)});else{const e=l.assetId+JSON.stringify(l.materialAssignments??[]);t.push(e,{...l,parentTransform:h}),i++}}}else null==u&&e.push({...l,parentTransform:h})});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,c,o);const a=this.assets.get(t[0].assetId);"webgl"===this.renderingView?.activeBackend?(e instanceof Jt&&e.perInstanceCastShadow||(e.castShadow=Ys(t,a?.castShadow??!1)),e.receiveShadow=Qs(t,a?.receiveShadow??!1)):(e.castShadow=!0,e.receiveShadow=!0);const s=new lt;s.add(e),s.userData.src=t[0],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 lt;r.add(t),r.userData.src=e[0],a instanceof lt&&(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=nt(a,e=>!dt(e)&&null!=e.geometry),r=Ha(s.material);null!=e[0].color&&null!=r.color&&(r.color=new d(16777215));const i=null==s.geometry.index?Zt.mergeVertices(s.geometry):s.geometry;let n,o;!(ca||r instanceof L)?(n=new l.BatchedMesh(e.length,i.getAttribute("position").count,i.index.count,r),n.perObjectFrustumCulled=!0,o=n.addGeometry(i)):n=new l.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 l.Matrix4).compose((new O).fromArray(a.object.position),(new j).setFromEuler((new h).fromArray(a.object.rotation)),(new O).fromArray(a.object.scale)),r=(new y).copy(a.object.parentTransform).multiply(s);let i;i=n instanceof l.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 lt;r.userData.src=e[0],a instanceof pt&&(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&&(ba(u),this.scene.add(u),this.experimentalStaticDrawSetDisposer=this.renderingView.registerExperimentalStaticDrawSet(u,"hology-materialized-static-scene")),null!=p&&p.children.length>0){ba(p),this.scene.add(p);const e=this.experimentalStaticDrawSetDisposer,t=this.renderingView.registerExperimentalStaticDrawSet(p,"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 Nt;e.initScene(this.scene),e.clusters.forEach(e=>{this.renderingView.addCluster(e)})}prepareCollisionShapesForInstanced(e){e instanceof lt&&e.collisionShapes.forEach(e=>{e instanceof r&&e.mesh instanceof w&&(e.mesh=e.mesh.geometry)})}setScene(e){this.scene=e}testCanBatch(e,t){return!ca&&(!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 Ke;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=nt(l.assetMesh,t=>t instanceof w&&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 c=["color","map","roughness","roughnessMap","metalness","metalnessMap","opacity","alphaMap","aoMap","aoMapIntensity","normalMap","normalScale","emissive","emissiveIntensity","emissiveMap"],u=new Map,h=new Map,p=[];let f=new l.MeshStandardMaterial({color:"white"});const m=t.get(e[0].id).get(e[0].meshUUID);if(null==m)throw"missing source material";if(m instanceof v&&!(m instanceof l.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 c){let r=e[t];r instanceof l.CompressedArrayTexture&&null!=r.userData.index&&(r=r.userData.index);const i=s.get(t);void 0===i||Ps(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=js(a.node,a.params.length-1)}else if(a instanceof C)t=V(s);else if(a instanceof O||a instanceof d)t=B(s);else if(a instanceof D)t=T(s);else if(a instanceof l.CompressedArrayTexture)s=e+"_i",t=k(s);else if(a instanceof P)continue;u.set(e,t),h.set(e,s)}let r=oe.uv;m instanceof Yt&&null!=m.heightMap&&(r=Qt(r,X(m.heightMap),F(m.heightScale)));let i=vs(u.get("opacity"),R)??F(m.opacity??1);if(null!=m.alphaMap){let e;if(m.alphaMap instanceof l.CompressedArrayTexture){const t=K(m.alphaMap),a=vs(u.get("alphaMap"),R)??F(m.alphaMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.alphaMap).sample(r);i=i.multiply(e.r)}let n=J(vs(u.get("color"),he)??m.color,i);if(null!=m.map){let e;if(m.map instanceof l.CompressedArrayTexture){const t=K(m.map),a=vs(u.get("map"),R)??F(m.map.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.map).sample(aa(r,m.map));n=n.multiply(e),i=i.multiply(e.a)}m.vertexColors&&(n=n.multiply(pe(ne(E.color.rgb),1)));let o=J(vs(u.get("emissive"),he)??m.emissive,i);if(null!=m.emissiveMap){let e;if(m.emissiveMap instanceof l.CompressedArrayTexture){const t=K(m.emissiveMap),a=vs(u.get("emissiveMap"),R)??F(m.emissiveMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.emissiveMap).sample(aa(r,m.emissiveMap));o=o.multiply(e)}const g=vs(u.get("emissiveIntensity"),R)??F(m.emissiveIntensity??1),y=vs(u.get("normalScale"),ue)??ce(m.normalScale??new D(1,1));let w=le.normal;if(null!=m.normalMap){let e;if(m.normalMap instanceof l.CompressedArrayTexture){const t=K(m.normalMap),a=vs(u.get("normalMap"),R)??F(m.normalMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.normalMap).sample(aa(r,m.normalMap));w=U(e.rgb,y.x)}let S=vs(u.get("roughness"),R)??F(m.roughness??1);if(null!=m.roughnessMap){let e;if(m.roughnessMap instanceof l.CompressedArrayTexture){const t=K(m.roughnessMap),a=vs(u.get("roughnessMap"),R)??F(m.roughnessMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.roughnessMap).sample(aa(r,m.roughnessMap));S=S.multiply(e.g)}let b=vs(u.get("metalness"),R)??F(m.metalness??0);if(null!=m.metalnessMap){let e;if(m.metalnessMap instanceof l.CompressedArrayTexture){const t=K(m.metalnessMap),a=vs(u.get("metalnessMap"),R)??F(m.metalnessMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.metalnessMap).sample(aa(r,m.metalnessMap));b=b.multiply(e.b)}let v=F(1);if(null!=m.aoMap){let e;if(m.aoMap instanceof l.CompressedArrayTexture){const t=K(m.aoMap),a=vs(u.get("aoMap"),R)??F(m.aoMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.aoMap).sample(aa(r,m.aoMap));v=v.multiply(e.r)}const M=vs(u.get("aoMapIntensity"),R)??F(m.aoMapIntensity??0);let A=w;!0!==m.userData.disableAO&&(A=_("DOUBLE_SIDED",A,e=>Q(new N("gl_FrontFacing"),e,e.multiplyScalar(-1))));const x=new L({color:H({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:xs(m.envMapRotation,m.envMap)}),x.envMap=m.envMap,x.side=m.side,f=x}else if(m instanceof L){const a=new Set,s=new Map,r=Object.keys(m.uniforms).filter(e=>!hs(e));for(const i of e){const e=t.get(i.id).get(i.meshUUID);if(!(e instanceof L))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||Ps(r,i)?s.set(t,r):fs(r)&&fs(i)&&ms(r)===ms(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=gs("vp"+p.length,i);s={name:t,params:[e],node:V(t)},p.push(s)}else s.params.push(e);a=s.name,t=js(s.node,s.params.length-1)}else if(s instanceof C)a=gs(e,i),t=V(a);else if(s instanceof O||s instanceof d)a=gs(e,i),t=B(a);else{if(!(s instanceof D))continue;a=gs(e,i),t=T(a)}u.set(e,t),h.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:ys(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 S=new Jt(n,i,r,f);for(const e of p)S.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 fe||t instanceof he?a=4:t instanceof ue&&(a=2),S.initUniform(h.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=S.addGeometry(as(i.geometry,m)),c=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=it(f.assetMesh)?.uuid===e,y=f.assetMesh instanceof lt&&g?f.assetMesh.collisionShapes:void 0,w=this.configureBatchedInstancedMesh(r,S,i,n,y);for(let e=0;e<w.length;e++){const a=r[e],s=w[e];"webgpu"!==this.renderingView?.requestedBackend&&S.setCastShadowAt(s,a.castShadow??c?.castShadow??!1);const i=t.get(a.id).get(a.meshUUID),n=i.userData.surface;null!=n&&(S.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=ps(i,e.params[a]);"number"==typeof s&&t.setComponent(a,s)}S.setUniformAt(e.name,s,t)}for(let e of u.keys()){if(p.some(t=>t.params.includes(e)))continue;const t=h.get(e)??e;let a=ps(i,e);if(a instanceof d&&(a=new O(a.r,a.g,a.b)),a instanceof l.CompressedArrayTexture)a=a.userData.index??0;else if(a instanceof P||null==a)continue;S.setUniformAt(t,s,a)}}}return S}async createInstancedMesh(e,t){const a=nt(t,e=>!dt(e)&&null!=e.geometry),s=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,_a(e[0].materialAssignments,s.materialAssignments),s),a.updateMatrix();const r=a.geometry.clone(),i=a.material;let n;if(n=new l.InstancedMesh(r,i,e.length),this.configureBatchedInstancedMesh(e,n,a),a.material instanceof g&&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 l.BatchedMesh&&(o=t.addInstance(s)),i.push(o);const c=(new l.Matrix4).compose((new O).fromArray(e[n].position),(new j).setFromEuler((new h).fromArray(e[n].rotation)),(new O).fromArray(e[n].scale)),u=(new y).copy(e[n].parentTransform).multiply(c),d=(new y).copy(u).multiply(a.matrixWorld);t.setMatrixAt(o,d),null==t.userData.hasCollision&&(t.userData.hasCollision=[]);const p=this.assets.get(e[n].assetId);t.userData.hasCollision[o]=!1!==e[n].collisionDetection||!1!==p?.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 rt(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(!Ja(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=Qa(a,n)),null!=a&&s.id!==a.id&&(r=r??qa(s),i=i??s.name,s=a);break}return s}unapplyMaterials(e){e.traverse(async e=>{if(e instanceof w)if(e.material instanceof Array)for(let t=0;t<e.material.length;t++)e.material[t]=this._originalMaterials.get(e.id+"#"+t)??e.material[t];else e.material=this._originalMaterials.get(e.id)??e.material})}updateActors(e){console.log("update actors"),this.actorTypes=e;const t=new Set(Object.values(je));rt(this.scene,e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&!t.has(e.userData.src.actor.type)).forEach(async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)})}updateComponents(e){this.componentTypes=e,rt(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 ha.entries())t.userData.customShaderName&&ha.delete(e);pa.clear(),this.landscapeManagers.forEach(t=>t.updateShaders(e)),rt(this.scene,e=>!0).forEach(e=>{e.traverse(async e=>{if(e instanceof w)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 w&&(e.material.wireframe=!0)}):t.traverse(e=>{e instanceof w&&(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);_a(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!==Pe.dynamic?Aa(t,!1):this.inEditor&&function(e){let t=!1;if(e.traverse(e=>{Ma.has(e)&&(t=!0)}),!t)return;e.updateWorldMatrix(!0,!0),e.traverse(e=>{Ma.has(e)&&(e.matrixWorldNeedsUpdate=!1)})}(t)),this.applyVertexMaterials(e,t),"light"==e.type){if("point"==e.light.type){const a=t;a.color=new d(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 d(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 d(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 Xt&&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 f?"density":"linear")!==e.fog.type;this.scene.fog=Pa(e.fog),t&&(a=this.scene).traverse(e=>{if(e instanceof w){const t=e.material;t instanceof L&&(a.fog instanceof p?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof f&&(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 Gt){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 pt&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}if("shape_mesh"===e.type&&"landscape"!==e.shape)da(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;da(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=Ba(e.prefab?.objects??[]),r=Ba(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=Na(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=Va(e.prefab?.objects??[]),i=Va(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=Ba(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=Na(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:st(t,t=>t.children?.some(t=>t.id===e.id),()=>!0))[0];return null==t?this.scene:null!=t?rt(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 d(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse(e=>{e instanceof w&&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=tt(e.vertexMaterials,e=>e.m);t.traverse(e=>{if(e instanceof w){if(null==e.geometry)return;if(es(bt(e,0,!1)),a>0){es(bt(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=bt(s,0,!0);es(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=bt(s,4,!0);es(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=Pa(e.fog),this.fixFogColor(),i=new m;break;case"sky":this.sky=kt(),this.updateSky(e),i=this.sky;break;case"world_env":this.updateWorldEnv(e),i=new m,this.worldEnvObj=i;break;case"actor":({object:i,actor:n}=await this.createFromActor(e,s));break;case"group":case"scatter":i=new m;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),this.applyTransform(e,i),a?i.userData._src=e:i.userData.src=e,null!=n&&(i.userData.actor=n),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(Da),i.getWorldQuaternion(Oa),i.getWorldScale(Ca),this.scene.add(i),i.position.copy(Da),i.quaternion.copy(Oa),i.scale.copy(Ca)),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)?Aa(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||ba(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 vt(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 Mt(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(l.NoToneMapping,1)}async updateSky(e){null!=this.sky&&(null==e?.sky?.materialId&&this.sky.material!==Tt?(this.sky.material=Tt,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=l.BackSide,(e instanceof v||e instanceof l.MeshBasicMaterial||e instanceof l.ShaderMaterial)&&(e.fog=!1),e.depthTest=!0,e.depthWrite=!1,e.transparent=!0}async createComponent(e,t,a,s){const r=new oa[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 O).fromArray(e.position),(new h).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===De.none)return;const t=xe(e.constructor);!0!==t?.replicate?this.netMode===De.client&&(e.netRole=Oe.none):e.netRole=this.netMode===De.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(ge,(new O).fromArray(e.position),(new h).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 w&&this._originalMaterials.set(e.id,e.material)});else{let s=new v({name:"Default",color:new d("#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 m;const a=mt(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new ft(e,this.renderingView,a,this.assetManagerService,this.assetsService,this.shaders,t=>{(e.materialAssignments??[]).filter(e=>null!=e.materialId).forEach(e=>this.applyMaterial(t,e))});return this.landscapeManagers.push(s),s.refreshGeometry(),a}applyHeightMaps(e,t,a=!1){const s=new gt(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(()=>yt(r),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&Ct.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 pt(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(_a(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,da(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 w&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()}),s.userData.assetId=e.assetId,s.traverse(e=>{if(e instanceof w)for(const t of at(e.material))Be(t,!1)}),"webgpu"===this.renderingView.requestedBackend){await this.renderingView.initializeBackend();const e=new Set;s.traverse(t=>{if(t instanceof w)for(const a of at(t.material))if(a instanceof l.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 m;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([...Ba(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&&ia(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 A}async createLight(e){if("point"===e.light.type){const t=new x(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 l.TextureLoader).load("assets/light-bulb-icon.webp"),a=new l.SpriteMaterial({map:e,alphaTest:.5}),s=new Lt(a);s.scale.multiplyScalar(.6),t.add(s)}return t}if("spot"===e.light.type){const t=new l.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 A,t.target.position.set(0,-1,0),t.add(t.target),this.inEditor){const e=(new l.TextureLoader).load("assets/light-bulb-icon.webp"),a=new l.SpriteMaterial({map:e,alphaTest:.5}),s=new Lt(a);s.scale.multiplyScalar(.6),t.add(s),t.add(new l.SpotLightHelper(t))}return t}if("rectArea"===e.light.type){const t=new l.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 l.TextureLoader).load("assets/light-bulb-icon.webp"),a=new l.SpriteMaterial({map:e,alphaTest:.5}),s=new Lt(a);s.scale.multiplyScalar(.6),t.add(s);const r=new Xt(t);t.add(r)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional,e),new m):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient,e),new m):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===Et);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){if(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(l.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}};ua=e([me(),t("design:paramtypes",[I,Object,ut,ct,ke,Array,Array,Object,Array])],ua);export{ua as SceneMaterializer};function da(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse(e=>{e.castShadow=t,e.receiveShadow=a})}const ha=new Map,pa=new Map,fa=new S({color:16711935}),ma=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),fa;const n=JSON.stringify(e.material)+t?._id,o=i&&!("shaderGraph"===e.material.type&&"asset"===e.material.shaderGraph?.source);if(o&&ha.has(n))return ha.get(n);if(o&&pa.has(n))return await pa.get(n);const l=_materialFromAsset(n,e,t,a,s,r,o);return o?pa.set(n,l).get(n):l}export async function _materialFromAsset(e,t,a,s,r,n,o=!0){const c={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 d(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&&(c.map=await r.getTexture(a))}let h,p,f;switch(t.material.type){case"phong":h=new b({...c,...u});break;case"water":h=At(c,a);break;case"grassFoliage":h=wt({color:c.color,map:c.map},a);break;case"grass":h=St({...c,colorTwo:new d(t.material.params.colorTwo),colorThree:new d(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),h=fa;break}"surface"===e.target&&null!=e.materialOptions?.side&&(p=ra(e.materialOptions.side)),"decal"===e.target?f=!1:null!=e.materialOptions?.transparent&&(f=e.materialOptions.transparent);try{const i=await prepareShaderGraphParameters(t.material?.shaderParams??{},e,s,r,a,n),o=t.shaderGraphPreviewNodeId,l=t.trailBillboard;h=sa(e,{parameters:i,previewNodeId:o,trailBillboard:l,alphaTest:t.material.alphaTest}),h.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),h=fa}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:la?Ue:Re,lambert:Ue,unlit:_e,toon:qt,layered:Rt,landscape:We,"landscape-composite":Fe,"decal-unlit":Vt,"decal-standard":zt,sprite:i}[t.material.type]??n.find(e=>e.name==t.material.shader)?.type;if(e){try{let i=new e;const o=await prepareClassParameters(t.material?.shaderParams??{},e,s,r,null,a,n,void 0,void 0,i);Object.assign(i,o),i.alphaTest=t.material.alphaTest??i.alphaTest,h=i.build()}catch(e){console.log("Shader runtime error: "+e,e),ma.has(t.material.shader)||ma.set(t.material.shader,fa.clone()),h=ma.get(t.material.shader)}h.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),h=fa;break;default:throw new Error("Unsupported material type "+t.material.type)}if(a?.csm.setupMaterial(h),h.side=p??t.material.side??h.side??l.FrontSide,h.transparent=(f??t.material.transparent??c.transparent??!1)||h.transparent,h.alphaTest=t.material.alphaTest??h.alphaTest??0,h.userData.receiveDecals=t.material.receiveDecals??!0,null!=t.material.blending&&(h.blending=Ce[t.material.blending]??l.NormalBlending),!0===t.material.transparent&&(h.depthWrite=!1),t.material.bloom&&(h.userData.hasBloom=!0),t.material.reflective&&(h.userData.reflective=!0),!0===t.material.outlines&&(h.userData.outlineParameters={},null!=t.material.outlineParams&&(null!=t.material.outlineParams.color&&(h.userData.outlineParameters.color=new d(t.material.outlineParams.color).toArray()),null!=t.material.outlineParams.thickness&&(h.userData.outlineParameters.thickness=t.material.outlineParams.thickness),null!=t.material.outlineParams.opacity&&(h.userData.outlineParameters.alpha=t.material.outlineParams.opacity),null!=t.material.outlineParams.colorMode&&(h.userData.outlineParameters.colorMode=t.material.outlineParams.colorMode),null!=t.material.outlineParams.darkening&&(h.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,n);null!=e&&(h.userData.surface=e.value)}return h.userData.assetId=t.id,o&&null!=a&&ha.set(e,h),o&&pa.delete(e),h}export function prepareCustomParamsFromShaderGraph(e,t={}){return Object.fromEntries((e.parameters??[]).map(e=>{const a=function(e){switch(e){case"float":return xt.FloatNode;case"boolean":return xt.BooleanNode;case"texture":return xt.Sampler2DNode;case"vec2":return xt.Vec2Node;case"vec3":return xt.Vec3Node;case"vec4":return xt.Vec4Node;case"color":return xt.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?Ra(i):s?.value??Ra(i);return[e.name,{type:a,value:n,override:r}]}))}export async function prepareShaderGraphParameters(e,t,a,s,r,i){const n={},o=prepareCustomParamsFromShaderGraph(t,e);for(const[e,t]of Object.entries(o)){const o=await ya(e,t,a,s,null,r,i);null!=o&&(n[e]=o)}return n}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:Ge,toSerializedParamType:toSerializedParamType});for(const e of h)console.warn(`Skipping stored parameter "${e.key}" because it could not be converted from ${xt[e.sourceType]} to ${xt[e.targetType]}`);for(const[e,t]of Object.entries(d)){if(!1===t.override)continue;const c=await ya(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 ya(r,i,t,a,null,void 0,void 0,void 0,void 0,void 0);null!=e&&(s[r]=e)}return s}const ga=new Map;async function ya(e,t,a,s,r,i,n,o,l=t.value,c=t.type,u,p=(t.type===xt.Struct?t.struct:void 0)){if(null==t||null==l||""===l)return null;switch(c){case xt.Array:if(Array.isArray(l)&&"element"in t)return await Promise.all(l.map(l=>ya(e,t,a,s,r,i,n,o,l,t.element,u,t.elementStruct)));break;case xt.Number:case xt.FloatNode:let f;if("string"==typeof l?f=parseFloat(l):"number"==typeof l&&(f=l),c===xt.FloatNode){if("object"==typeof l&&"a"in l&&"b"in l){const e=l;if(null==e.a)return null;const t="string"==typeof e.a?parseFloat(e.a):e.a;if(null==e.b)return t;const a="string"==typeof e.b?parseFloat(e.b):e.b,s=function(e){let t=ga.get(e);return null==t&&(t=Ve(Bt.decode(e)),ga.set(e,t)),t}(e.easing),r=s.sample(ze(Ne.energy));return G(F(t),F(a),r)}return new te(Xe(e),f,void 0,!1)}return f;case xt.Texture:let m=await s.getTexture(await a.getAsset(l));return"envmap"===e.toLowerCase()&&null!=i&&(m=i.getEnvTexture(m)),m;case xt.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 ae(null,t,new te(Xe(e)+"_i",a,void 0,!1))}const y=await s.getTexture(g);return y?X(y):null;case xt.Boolean:return l;case xt.BooleanNode:return new ee(Xe(e),l,void 0,!1);case xt.Vector2:case xt.Vec2Node:if("object"==typeof l){const t=l instanceof Array?(new D).fromArray(l):new D(l.x,l.y);return c===xt.Vec2Node?new se(Xe(e),t,void 0,!1):t}return null;case xt.Vector3:case xt.Vec3Node:if("object"==typeof l){const t=l instanceof Array?(new O).fromArray(l):new O(l.x,l.y,l.z);return c===xt.Vec3Node?new re(Xe(e),t,void 0,!1):t}return null;case xt.Vector4:case xt.Vec4Node:if("object"==typeof l){const t=l instanceof Array?(new C).fromArray(l):new C(l.x,l.y,l.z,l.w);return c===xt.Vec4Node?new ie(Xe(e),t,void 0,!1):t}return null;case xt.Color:case xt.RgbNode:const w=new d(l);return c===xt.RgbNode?new re(Xe(e),new O(w.r,w.g,w.b),void 0,!1).rgb:w;case xt.String:return l;case xt.Scene:return"string"==typeof l?new ve(l):"object"==typeof l&&null!=l&&"string"==typeof l.id?new ve(l.id,"string"==typeof l.name?l.name:void 0):null;case xt.ModelRef:return"string"==typeof l?new Me(l):null;case xt.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 xt.Euler:const b=l;return(new h).fromArray(b);case xt.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 xt.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=ha.get(t);if(null!=r)return r;const o=await prepareShaderGraphParameters({},e.shaderGraph,a,s,i,n),l=sa(e.shaderGraph,{parameters:o});return l.userData.assetId=e.id,ha.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 xt.AudioBuffer:return await s.getAudio(await a.getAsset(l));case xt.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 ye(o,v);console.error("Using a non-vfx asset for visual effect parameter");break;case xt.Prefab:{const e=await a.getAsset(l);return null==e?(console.error("Using a non-prefab asset for prefab parameter",l),null):new we(e)}case xt.PrefabActor:{const e=await a.getAsset(l);return null==e?(console.error("Using a non-prefab asset for prefab parameter",l),null):new Se(new we(e))}case xt.DataAsset:return materializeDataAssetRef(l,a,s,r,i,n,o,u);case xt.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 ta(e.sequence);console.error("Using a non-sequence asset for sequence parameter");break}case xt.SequenceData:return ea(l)?l:(console.warn("Invalid inline sequence data parameter value",l),null);case xt.Struct:return async function(e,t,a,s,r,i,n,o,l){const c=wa(e),u=c?.struct??t;if(null==u)return console.warn("Missing parameter definition id for struct parameter"),null;const d=Je(u);if(null==d)return console.warn(`Unknown parameter definition "${u}"`),null;if(Qe(u))return console.warn(`Can not instantiate abstract parameter definition "${u}"`),null;if(null!=t&&u!==t&&!Ze(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=wa(e);if(null!=t)return t.value;if(Sa(e))return e;if(null!=e&&"object"==typeof e&&Sa(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,p,a,s,r,i,n,o,u);case xt.Curve:return Bt.decode(l);case xt.ColorLayer:case xt.MaskLayer:if(_t(l)){const e=await $t.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 xt.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,o,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=Le(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,o,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 n(e=>{let n=0;const c=t.onUpdate.subscribe(c=>{if(c.id!==u.id||"data"!==c.type)return;const d=++n;materializeDataAssetRef(u.id,t,a,s,r,i,o,l).then(t=>{e.closed||d!==n||null==t||e.next(t)}).catch(e=>console.warn(`Failed to reload data asset "${u.id}"`,e))});return()=>c.unsubscribe()}):void 0;return new be(u,p,m)}function wa(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.struct&&Sa(e.value)?e:null}function Sa(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&Object.values(e).every(e=>null!=e&&"object"==typeof e&&"type"in e)}function ba(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 va(){}const Ma=new WeakMap;function Aa(e,t){if(t)return e.userData.hologyEditorMatrixWorldAutoUpdate=!0,void e.traverse(e=>{const t=Ma.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=>{Ma.has(e)&&s.push(e)}),0!==s.length||a||s.push(e);for(const e of s)xa(e);delete e.userData.hologyEditorMatrixWorldAutoUpdate}function xa(e){const t=Ma.get(e);if(e.updateMatrix(),e.updateWorldMatrix(!0,!0),null==t){const t=new Map;e.traverse(e=>{t.set(e,e.matrixAutoUpdate)}),Ma.set(e,{updateMatrixWorld:e.updateMatrixWorld,matrixAutoUpdate:t})}e.traverse(e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1}),e.updateMatrixWorld=va}function ja(e,t=!1){return Array.isArray(e)?e.every(e=>ja(e,t)):t||!e.transparent&&!Ia(e)}function Ia(e){return e instanceof L&&(null!=e.uniforms[na]||null!=e.uniforms.hology_scene_map)}function Pa(e){return"linear"===e.type?new p(new d(e.color),e.near??100,e.far??1e3):"density"===e.type?new f(e.color,e.density):void console.warn("Invalid fog type",e)}const Da=new O,Oa=new j,Ca=new O;new v({color:4229780});async function Ea(e,t,a,s){null==s&&(s=(new y).identity());const r=s.clone().multiply(ka(e,new l.Matrix4));if(null!=e.children&&e.children.length>0)for(let a=e.children.length-1;a>=0;a--)await Ea(e.children[a],t,e,r);await t(e,a,s)}function ka(e,t){return null==e.position||null==e.rotation||null==e.scale?t.identity():t.compose((new O).fromArray(e.position),(new j).setFromEuler((new h).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?xt.Number:t instanceof R||"function"==typeof e.prototype.isFloat?xt.FloatNode:t instanceof P||e===P||e.isTexture?xt.Texture:t instanceof $e||e===$e||e===Z||"function"==typeof e.prototype?.isSampler2D||!0===e.prototype?.isSampler2D?xt.Sampler2DNode:t instanceof Boolean||e===Boolean?xt.Boolean:t instanceof $?xt.BooleanNode:t instanceof d||e==d?xt.Color:t instanceof Y||"function"==typeof e.prototype.isRgb?xt.RgbNode:t instanceof D||e==D?xt.Vector2:t instanceof ue||"function"==typeof e.prototype.isVec2?xt.Vec2Node:t instanceof O||e==O?xt.Vector3:t instanceof he||"function"==typeof e.prototype.isVec3?xt.Vec3Node:t instanceof C||e==C?xt.Vector4:t instanceof fe||"function"==typeof e.prototype.isVec4?xt.Vec4Node:t instanceof String||e===String?xt.String:t instanceof ve||e===ve?xt.Scene:t instanceof Me||e===Me?xt.ModelRef:t instanceof Ae||e==Ae||e.prototype instanceof Ae||e.prototype==Ae?xt.BaseActor:t instanceof h||e==h?xt.Euler:t instanceof A||e==A?xt.Object3D:t instanceof g||e==g?xt.Material:t instanceof AudioBuffer||e==AudioBuffer?xt.AudioBuffer:t instanceof ye||e==ye?xt.VisualEffect:t instanceof we||e==we?xt.Prefab:t instanceof Se||e==Se?xt.PrefabActor:t instanceof be||e==be?xt.DataAsset:t instanceof Bt||e==Bt?xt.Curve:t instanceof $t||e==$t?xt.ColorLayer:t instanceof Wt||e==Wt?xt.MaskLayer:t instanceof l.AnimationClip||e==l.AnimationClip?xt.AnimationClip:t instanceof ta||e==ta?xt.Sequence:"SequenceData"===e.name||e.prototype&&"tracks"in e.prototype?xt.SequenceData:null!=qe(e)?xt.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===xt.Struct?qe(e.type):void 0;return!0===e.options.array?{type:xt.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=Ta(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 ea(e)?{type:xt.SequenceData}:void 0}(t);null!=a&&(e=a)}if(e.type!==xt.Struct)return{typeInfo:e,value:t};const a=wa(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===xt.Struct)return Qe(e.type)?{}:prepareCustomParamsFromType(e.type,{});return customParameterDefaultValueByType.get(a)}(e,a)),p=function(e,t){if(Ta(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!==xt.SequenceData||!ea(e))return;return{type:xt.SequenceData,value:e}}(n,h.typeInfo);i=function(e,t,a){if(e.type!==xt.Struct||a?.type!==xt.Struct||null==a.struct)return e;const s=t.struct??e.struct;if(null==s||a.struct===s||Ze(a.struct,s)||null==Je(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?Ra(t):[];return Ra(t)}(e,h.value,d):Ra(h.value),m=function(e,t,a){if(t.type===xt.Struct){if(null!=t.struct&&Qe(t.struct))return a;const s=null!=t.struct?Je(t.struct):e.type;return null!=s&&Sa(a)?prepareCustomParamsFromType(s,a):a}if(t.type!==xt.Array||t.element!==xt.Struct||!Array.isArray(a))return a;const s=null!=t.elementStruct?Je(t.elementStruct):e.type;return a.map(e=>{const a=wa(e),r=a?.struct??t.elementStruct;if(null!=r&&Qe(r))return e;const i=null!=a?Je(a.struct):s,n=a?.value??(Sa(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 Ta(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"number"==typeof e.type&&"value"in e}function Ba(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 Va(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??{},...Ua(e.params)}})}return{...e,params:{...e.params??{},...Ua(t.prefab.params)},innerParams:[...s.values()]}}function Na(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=$a(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:$a(e.params??{},t.params??{},a.params??{}),innerParams:n}}function $a(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 Ua(e){return null==e?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>function(e){return!0===e?.override}(e)))}function Fa(e,t){return e.length>=t.length&&t.every((t,a)=>e[a]===t)}export function prepareCustomParamsFromType(e,t,a=null,s={}){const r=Ge(e);if(0===r.length)return{};let i;null!=a?Ee(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 Ra(e){return null==e?e:Array.isArray(e)?e.map(e=>Ra(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 D:return t instanceof D?t.toArray():void a();case O:return t instanceof O?t.toArray():void a();case C:return t instanceof C?t.toArray():void a();case d:return t instanceof d?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new d(t).getHexString():void a();case String:return t;case h:return t instanceof h?t.toArray():void a();case we:return t instanceof we?t.asset?.id??null:void a();case be:return t instanceof be?t.id:"string"==typeof t?t:void a();case ve:return t instanceof ve?{id:t.id,...null!=t.name?{name:t.name}:{}}:void a();case Me:return t instanceof Me?t.id:"string"==typeof t?t:void a()}const s=qe(e);if(null!=s){const r=wa(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!=qe(a)&&He(a,e)?a:e}(e,t),n=qe(i),o=function(e,t){if(null==t)return null;if(Sa(t))return t;if(null!=t&&"object"==typeof t&&Sa(t.params))return t.params;if("object"!=typeof t)return;const a=Ge(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(ea(t))return t}function _a(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=>Ga(e.materialId)),(t??[]).filter(e=>Ga(e.materialId)),e=>e.name?`name:${e.name}`:`color:${e.color}`)}function Ga(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[xt.RgbNode,"#000000"],[xt.Color,"#000000"],[xt.String,""],[xt.Scene,null],[xt.ModelRef,null],[xt.Vector4,[0,0,0,0]],[xt.Vec4Node,[0,0,0,0]],[xt.Vector3,[0,0,0]],[xt.Vec3Node,[0,0,0]],[xt.Vector2,[0,0]],[xt.Vec2Node,[0,0]],[xt.Euler,[0,0,0,"XYZ"]],[xt.Array,[]],[xt.DataAsset,null],[xt.SequenceData,Kt()],[xt.ColorLayer,Ut],[xt.MaskLayer,Ft]]);let La=new d;new d;function qa(e){return null==e?.color?null:(La.set(e.color),"#"+La.getHexString())}function Ja(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=qa(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 w||e.isMesh||e instanceof l.SkinnedMesh||e.isSkinnedMesh)for(const t of at(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 d))continue;const o=qa(n),l=n.name;if(Ja(n,t,e.userData["originalColor_"+i],e.userData["originalMaterialName_"+i])){const n=Qa(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=qa(i),o=i.name;if(Ja(i,t,e.userData.originalColor,e.userData.originalMaterialName)){const i=Qa(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 Ya=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 Qa(e,t){if(null==e||null==t||!function(e,t){return function(e){const t=[];for(const[a,s]of Object.entries(e))Za(a,s)&&t.push(s);if(e instanceof l.ShaderMaterial)for(const[a,s]of Object.entries(e.uniforms))Za(a,s.value)&&t.push(s.value);return t}(e).some(e=>e.flipY!==t)}(e,t))return e;let a=Ya.get(e);null==a&&(a=new Map,Ya.set(e,a));const s=a.get(t);if(null!=s)return s;const r=Ha(e);if(function(e,t){for(const a of Object.keys(e)){const s=e[a];Za(a,s)&&(e[a]=Xa(s,t))}}(r,t),r instanceof l.ShaderMaterial){for(const[e,a]of Object.entries(r.uniforms))Za(e,a.value)&&(a.value=Xa(a.value,t));r.uniformsNeedUpdate=!0}return r.needsUpdate=!0,a.set(t,r),r}function Ha(e){const t=e.clone();return t.userData={...e.userData??{}},t}function Za(e,t){const a=t;return(t instanceof P||!0===a?.isTexture)&&!e.toLowerCase().includes("envmap")&&!0!==a.isCompressedTexture&&!0!==a.isCompressedArrayTexture}function Xa(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 Ka(e,t){if(e instanceof l.ShaderMaterial&&t instanceof l.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof l.ShaderMaterial&&t instanceof l.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 es(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}function ts(e,t){const a=it(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&&is(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 as(e,t){const a=Es(e,t);if(a.length===Object.keys(e.attributes).length)return e;const s=new u;s.name=e.name;const r=e.getIndex();null!=r&&s.setIndex(r);for(const t of a)s.setAttribute(t,rs(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 ss=new WeakMap;function rs(e,t){return e.getAttribute(t)??function(e,t){if("uv"===t)return function(e){let t=ss.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 l.Float32BufferAttribute(new Float32Array(2*a.count),2),ss.set(e,t));return t}(e);throw new Error(`Unsupported synthetic batching geometry attribute: ${t}`)}(e,t)}function is(e){return null!=e.getAttribute("position")}const ns=new WeakMap,os="hbat_",ls=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 cs(e){let t=ns.get(e);return null==t&&(t=function(e){let t=e.type;if(e instanceof L)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(hs(a))continue;const s=e.uniforms[a]?.value;fs(s)||(t+=`u:${a}:${bs(s)};`)}return t+=ds(e.vertexShader),t+=ds(e.fragmentShader),t}(e);else if(e instanceof l.MeshStandardMaterial&&!(e instanceof l.MeshPhysicalMaterial)||(t+=e.id+""),(e instanceof l.MeshBasicMaterial||e instanceof l.MeshLambertMaterial||e instanceof v||e instanceof b)&&(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 v&&(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 l.MeshPhysicalMaterial&&(null!=e.sheenColorMap&&(t+="sc"+e.sheenColorMap?.id),null!=e.sheenRoughnessMap&&(t+="sr"+e.sheenRoughnessMap?.id)),(e instanceof S||e instanceof b)&&null!=e.specularMap&&(t+="s"+e.specularMap?.id),e instanceof l.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 Yt&&null!=e.heightMap&&(t+="h"+e.heightMap?.id),e instanceof l.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),ns.set(e,t)),t}const us=new Map;function ds(e){return us.has(e)||us.set(e,`shader_${us.size}`),us.get(e)}function hs(e){return ls.has(e)||e.startsWith("hology_")}function ps(e,t){return e instanceof L?e.uniforms[t]?.value:e[t]}function fs(e){return"number"==typeof e||e instanceof D||e instanceof O||e instanceof C||e instanceof d}function ms(e){return"number"==typeof e?1:e instanceof D?2:4}function gs(e,t){const a=e.replace(/[^A-Za-z0-9_]/g,"_");let s=os+a;for(;t.has(s);)s=os+s;return t.add(s),s}function ys(e,t){const a={};for(const[s,r]of Object.entries(e.uniforms))t.has(s)||(a[s]={value:r.value});return a}const ws=new WeakMap;let Ss=1;function bs(e){if(null==e)return"null";if(e instanceof P||!0===e?.isTexture)return`texture:${e.id}`;if(e instanceof l.Matrix3||e instanceof l.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=ws.get(e);return null==t&&(t=Ss++,ws.set(e,t)),`object:${t}`}return String(e)}function vs(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 Ms=new y,As=new h;function xs(e,t){return As.copy(e),As.x*=-1,As.y*=-1,As.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(As.y*=-1,As.z*=-1),(new l.Matrix3).setFromMatrix4(Ms.makeRotationFromEuler(As))}function js(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 C;function Ps(e,t){return e===t||null==e==(null==t)&&("number"==typeof e&&"number"==typeof t?e===t||isNaN(e)&&isNaN(t):e instanceof l.Color&&t instanceof l.Color?e.r===t.r&&e.g===t.g&&e.b===t.b:e instanceof D&&t instanceof D?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 C&&t instanceof C&&(e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w))}function Ds(e){const t=[];for(const[a,s]of Object.entries(e))s instanceof ye?t.push(s):s instanceof Ie&&t.push(...Ds(s));return t}function Os(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)}const Cs=new WeakMap;function Es(e,t){const a=Object.keys(e.attributes).filter(a=>ks(e,t,a));return!e.hasAttribute("uv")&&is(e)&&ks(e,t,"uv")&&a.push("uv"),a}function ks(e,t,a){return"position"===a||("uv"===a?function(e){if(e instanceof L)return Bs(e,"uv");if(e instanceof l.ShaderMaterial)return Vs(e.vertexShader,"uv");if(e instanceof Yt&&null!=e.heightMap)return!0;return Ts.some(t=>e[t]?.isTexture)}(t):t instanceof L?Bs(t,a):t instanceof l.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=Cs.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 Cs.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 zs(e,t,a){if(t(e))return e;for(const s of e.children??[]){const e=zs(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=>zs(e,t,a));if(null!=e)return e}}return null}const Ns=new O,$s=new O,Us=new O,Fs=new C,Ws=new C,Rs=new y,_s=new y,Gs=new M;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 y).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++)Ns.fromBufferAttribute(r,t),e.applyBoneTransform(t,Ns),r.setXYZ(t,Ns.x,Ns.y,Ns.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 w(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),Ws.fromBufferAttribute(i,t),a.identity().multiplyScalar(0);for(let e=0;e<4;e++){const t=Ws.getComponent(e);if(0===t)continue;const s=Fs.getComponent(e);Rs.multiplyMatrices(n.bones[s].matrixWorld,n.boneInverses[s]);for(let e=0;e<16;e++)a.elements[e]+=Rs.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";export{createLatticeDeformation,latticePoint,isValidLattice,deformLatticeGeometry,LatticeGeometryCache}from"./lattice-deformation.js";import{ConvexPolyhedronCollisionShape as r}from"./collision/collision-shape.js";import{SpriteShader as i}from"../shader/sprite-shader.js";import{Observable as n,Subject as o}from"rxjs";import*as l from"three";import{BoxGeometry as c,BufferGeometry as u,Color as d,Euler as h,Fog as p,FogExp2 as f,Group as m,Material as g,Matrix4 as y,Mesh as w,MeshLambertMaterial as S,MeshPhongMaterial as b,MeshStandardMaterial as v,Matrix3 as M,Object3D as A,PointLight as x,Quaternion as I,Scene as j,Texture as P,Vector2 as D,Vector3 as O,Vector4 as E}from"three";import{attributes as C,batchingUniformFloat as k,batchingUniformVec2 as T,batchingUniformVec3 as B,batchingUniformVec4 as V,bool as z,BooleanExpression as N,BooleanNode as $,colorToNormal as U,float as F,deriveNodeShaderMaterial as W,FloatNode as R,ifDefApply as _,mix as G,NodeShaderMaterial as L,rgb as q,rgba as J,RgbNode as Y,select as Q,standardMaterial as H,Texture2dLookupNode as Z,textureSampler2d as X,textureSampler2dArray as K,UniformBoolNode as ee,UniformFloatNode as te,UniformSampler2dArraySlice as ae,UniformVec2Node as se,UniformVec3Node as re,UniformVec4Node as ie,varying as ne,varyingAttributes as oe,varyingTransformed as le,vec2 as ce,Vec2Node as ue,vec3 as de,Vec3Node as he,vec4 as pe,Vec4Node as fe}from"three-shader-graph";import{Service as me}from"typedi";import{VfxActor as ge}from"../effects/vfx/vfx-actor.js";import{VisualEffect as ye}from"../effects/vfx/vfx-param.js";import{Prefab as we,PrefabOf as Se}from"./objects/prefab.js";import{DataAssetRef as be}from"./objects/data-asset.js";import{SceneRef as ve}from"./scene-ref.js";import{ModelRef as Me}from"./model-ref.js";import{BaseActor as Ae,getActorOptions as xe}from"../gameplay/actors/actor.js";import Ie from"../gameplay/actors/builtin/index.js";import{ActorComponent as je}from"../gameplay/actors/component.js";import{PhysicsBodyType as Pe}from"../gameplay/services/physics/physics-system.js";import{NetMode as De}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 Ce}from"../gameplay/inject.js";import{RenderingView as ke}from"../rendering.js";import{markMaterialUniformValuesNeedUpdate as Te,setMaterialUniformValuesAutoUpdate as Be}from"../rendering/node-material-webgpu-resolver.js";import{curveSampler as Ve,oneMinus as ze,particleUniforms as Ne,Sampler2DNode as $e}from"../shader-nodes/index.js";import{LambertShader as Ue}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as Fe}from"../shader/builtin/landscape-composite-shader.js";import{LandscapeShader as We}from"../shader/builtin/landscape-shader.js";import{StandardShader as Re}from"../shader/builtin/standard-shader.js";import{UnlitShader as _e}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as Ge,getDataAssetDefinitionType as Le,getParameterDefinitionId as qe,getParameterDefinitionType as Je,isDataAssetDefinitionAbstract as Ye,isParameterDefinitionAbstract as Qe,isParameterDefinitionAssignableTo as He,isParameterDefinitionStructAssignableTo as Ze,shaderParameterUniformName as Xe}from"../shader/parameter.js";import{ArrayMap as Ke,DefaultMap as et,groupBy as tt}from"../utils/collections.js";import{iterateMaterials as at}from"../utils/materials.js";import{filterChildrenShallow as st,filterSceneShallow as rt,findFirstVisibleMesh as it,findFirstVisibleObject as nt,traverseAsync as ot}from"../utils/three/traverse.js";import{AssetMeshInstance as lt,AssetResourceLoader as ct}from"./asset-resource-loader.js";import{AssetsProvider as ut}from"./assets-provider.js";import{isCollisionMesh as dt}from"./collision/collision-shape-import.js";import{BoxCollisionShape as ht,PhysicalShapeMesh as pt}from"./collision/collision-shape.js";import{LandscapeManager as ft}from"./landscape/landscape-manager.js";import{initLandscape as mt}from"./landscape/landscape.js";import{SectionGrid as gt,smoothNormalsCrossMeshes as yt}from"./landscape/utils.js";import{createGrassFoliageMaterial as wt}from"./materials/grass-foliage.js";import{createGrassMaterial as St}from"./materials/grass.js";import{getMaterialAttribute as bt}from"./materials/utils/material-painting.js";import{PaintedScatterManager as vt}from"./scatter/painted-scatter-manager.js";import{SurfaceScatterManager as Mt}from"./scatter/surface-scatter-manager.js";import{createWaterMaterial as At}from"./materials/water.js";import{SerializedParamType as xt}from"./model.js";import{applyRuntimeParamTypeInference as It,convertConfiguredParamsToRuntimeTypes as jt,convertConfiguredParamValueToRuntimeType as Pt,inferRuntimeSerializedParamTypeHint as Dt}from"./custom-param-runtime-types.js";import{ShapeLibrary as Ot,ShapeLibraryKeys as Et}from"./objects/shapes.js";import{ambientLightName as Ct,createSky as kt,defaultSkyMaterial as Tt}from"./sky.js";import{Curve2 as Bt}from"../utils/curve.js";import{DecalUnlitShader as Vt}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as zt}from"../shader/builtin/decal-standard-shader.js";import{ClusterGenerator as Nt}from"../rendering/cluster-generator.js";import{ColorLayer as $t,defaultValueColorLayer as Ut,defaultValueMaskLayer as Ft,MaskLayer as Wt}from"../shader/color-layer.js";import{LayeredShader as Rt}from"../shader/builtin/layered-shader.js";import{isColorLayerSerialized as _t}from"../shader/color-layer.js";import{FogVolume as Gt}from"../rendering/fog/fog-volume-actor.js";import{UnscaledSprite as Lt}from"../utils/three/unscaled-sprite.js";import{ToonShader as qt}from"../shader/builtin/toon-shader.js";import{BatchedMesh2 as Jt}from"./batched-mesh-2.js";import{ParallaxStandardMaterial as Yt}from"../shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Qt}from"../shader-nodes/pom.js";import{traverseVisibleEvery as Ht}from"../utils/three/traverse.js";import{BufferGeometryUtils as Zt,RectAreaLightHelper as Xt}from"three/examples/jsm/Addons.js";import{createSequenceData as Kt,isSequenceData as ea,Sequence as ta}from"../effects/sequence/sequence-data.js";import{applyUvTiling as aa}from"./../shader/uv-nodes.js";import{buildShaderGraphMaterial as sa,shaderGraphMaterialSideToThree as ra}from"../shader/graph/index.js";import{hasExecutableEventGraphDocument as ia}from"../gameplay/event-graph/model.js";import{depthUniformName as na}from"../shader-nodes/depth.js";export{It as applyRuntimeParamTypeInference,jt as convertConfiguredParamsToRuntimeTypes,Pt as convertConfiguredParamValueToRuntimeType,Dt as inferRuntimeSerializedParamTypeHint};const oa={},la=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),ca=/^((?!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 ua(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}let ua=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,c,u,d=[]){this.scene=e,this.dataProvider=t,this.assetsService=s,this.assetManagerService=r,this.renderingView=i,this.shaders=n,this.actorTypes=c,this.actorProvider=u,this.componentTypes=d,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=De.none,this.updated$=new o,this.removed$=new o,this.prefabEventGraphAdded$=new o,this.prefabEventGraphRemoved$=new o,this.error$=new o,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.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 o,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.update(e).finally(()=>this.scheduleEditorStaticDrawSetRebuild()),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),t.onUpdate(e=>{this.prepareEditorStaticObjectForMutation(e),this.update(e).finally(()=>this.scheduleEditorStaticDrawSetRebuild(e)),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),t.onRemove(e=>{this.prepareEditorStaticObjectForMutation(e),this.remove(e),this.scheduleEditorStaticDrawSetRebuild(),this.handlePaintedScatterSceneMutation(e),this.handleSurfaceScatterSceneMutation(e)}),this.createAssetSubscription=s.onCreate.subscribe(e=>{this.assets.set(e.id,e)}),this.updateSubscription=s.onUpdate.subscribe(async t=>{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 l.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=>zs(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 Ca(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 w)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 Ca(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 l.SpotLight&&"spot"===t.userData?.src?.light?.type&&t.userData.src.light.spot.mapTextureId===e.id&&s.push(t),t instanceof w&&(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 l.ShaderMaterial){for(const a of Object.values(e.uniforms))if(a.value instanceof l.Texture&&a.value.userData.assetId===t)return!0}else for(const a of Object.values(e))if(a instanceof l.Texture&&a.userData.assetId===t)return!0;return!1}replaceMaterialTextureReferences(e,t,a){let s=!1;if(e instanceof l.ShaderMaterial)for(const[r,i]of Object.entries(e.uniforms))i.value instanceof l.Texture&&i.value.userData.assetId===t&&(e.uniforms[r].value=a,s=!0);else for(const[r,i]of Object.entries(e))i instanceof l.Texture&&i.userData.assetId===t&&(e[r]=a,s=!0);s&&(e.needsUpdate=!0,Te(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===xt.Material&&s.value===a.id){t=!0;break}if(s.type===xt.Array&&"element"in s&&s.element===xt.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?Ka(e.material[s],i)||(e.material[s]=i):Ka(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===xt.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(),ha.clear(),pa.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)Aa(e,!1);this.editorMatrixWorldEditingObjects.clear();for(const t of e)this.editorMatrixWorldEditingObjects.add(t),Aa(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)Aa(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 m;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 m;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 m;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;(dt(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=va}0!==t.children.length&&(ba(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 w&&!dt(e)&&(t=!0,null!=e.geometry?.index&&null==e.customDepthMaterial&&Ia(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=new Set,a=new Set,s=new j;for(const r of e){const e=r.asset;if(t.has(e.id))continue;t.add(e.id),Os(e,a);const i=await r.create(s);try{await i.prepareRendering()}finally{i.onEndPlay(),i.disposed.next(!0),i.object.removeFromParent()}}await this.initVfxTextures(a)}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=>Ds(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,Ua(s.prefab.params)),null!=s.prefab.innerParams){const e=r.slice(t+1);for(const t of s.prefab.innerParams){const a=Ua(t.params);0!==Object.keys(a).length&&(n?c.push({path:Fa(t.path,e)?t.path.slice(e.length):t.path,params:a}):Fa(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!==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=>{!dt(e)&&e.isMesh&&s.push(e)});const r=1==s.length&&0==s[0].children.length,i=!ca,n=s.every(e=>!Array.isArray(e.material)||1===e.material.length),o=s.some(e=>e instanceof w&&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,ha.clear(),pa.clear();const e=[],t=new Ke,a=new Ke,s=new Ke;let r=0,i=0,n=0;const o=new Map,c=new et(()=>new Map),u="webgpu"===this.renderingView?.requestedBackend?new m:null,p=null!=u?new m:null;null!=u&&(u.name="Hology WebGPU static scene objects",p.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&&Ia(e.material,!0)}(t)){((Array.isArray(t.material)?t.material:[t.material]).some(e=>e.transparent||ja(e))?p:u).add(e)}else this.scene.add(e)};for(const l of this.dataProvider.getObjects())await Ca(l,async(l,u,h)=>{if(!this.shouldBeMaterialized(l))return;const p="asset_mesh"==l.type&&this.canObjectBeInstanced(l)&&await this.canAssetBeInstanced(l),f="shape_mesh"===l.type&&"landscape"!==l.shape&&l.physics?.type!==Pe.dynamic;if(p||f){if(u&&u.children?.length>0){const e=u.children.findIndex(e=>e.id===l.id);e>=0&&u.children.splice(e,1)}if(f){let e=l.shape+JSON.stringify(l.shapeParams??{})+l.castShadow+l.receiveShadow;const t=l.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===xt.Color&&null!=e.value&&(r=new d(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:{...l,parentTransform:h},color:r}),n++}else{const e=this.assets.get(l.assetId);null==e&&console.log("Can't find asset with id "+l.assetId);let s=o.get(l.assetId);if(null==s){const e=await this.createFromAsset(l,{assignMaterials:!1});if(null==e)return;if(s=o.get(l.assetId),null==s){s={useBatchedMesh:null!=it(e)&&Ht(e,e=>!(e instanceof w)||this.testCanBatch(e.material,e.geometry)),assetMesh:e},o.set(l.assetId,s)}}const n=_a(l.materialAssignments,e.materialAssignments);if(s.useBatchedMesh)await ot(s.assetMesh,async t=>{if(!(t instanceof w))return;const s=Array.isArray(t.material)?t.material[0]:t.material,i=await this.resolveMaterialForAssignments(s,n,e);if(null!=i){Be(i,!1),c.get(l.id).set(t.uuid,i);let s=ts(t,i);if(s+=cs(i),"webgpu"===this.renderingView?.requestedBackend){s+=`|castShadow:${l.castShadow??e.castShadow??!1?1:0}|receiveShadow:${l.receiveShadow??e.receiveShadow??!1?1:0}`}a.push(s,{...l,parentTransform:h,meshUUID:t.uuid}),r++}else console.warn("Can not materialize mesh because missing material",l)});else{const e=l.assetId+JSON.stringify(l.materialAssignments??[]);t.push(e,{...l,parentTransform:h}),i++}}}else null==u&&e.push({...l,parentTransform:h})});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,c,o);const a=this.assets.get(t[0].assetId);"webgl"===this.renderingView?.activeBackend?(e instanceof Jt&&e.perInstanceCastShadow||(e.castShadow=Ys(t,a?.castShadow??!1)),e.receiveShadow=Qs(t,a?.receiveShadow??!1)):(e.castShadow=!0,e.receiveShadow=!0);const s=new lt;s.add(e),s.userData.src=t[0],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 lt;r.add(t),r.userData.src=e[0],a instanceof lt&&(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=nt(a,e=>!dt(e)&&null!=e.geometry),r=Ha(s.material);null!=e[0].color&&null!=r.color&&(r.color=new d(16777215));const i=null==s.geometry.index?Zt.mergeVertices(s.geometry):s.geometry;let n,o;!(ca||r instanceof L)?(n=new l.BatchedMesh(e.length,i.getAttribute("position").count,i.index.count,r),n.perObjectFrustumCulled=!0,o=n.addGeometry(i)):n=new l.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 l.Matrix4).compose((new O).fromArray(a.object.position),(new I).setFromEuler((new h).fromArray(a.object.rotation)),(new O).fromArray(a.object.scale)),r=(new y).copy(a.object.parentTransform).multiply(s);let i;i=n instanceof l.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 lt;r.userData.src=e[0],a instanceof pt&&(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&&(ba(u),this.scene.add(u),this.experimentalStaticDrawSetDisposer=this.renderingView.registerExperimentalStaticDrawSet(u,"hology-materialized-static-scene")),null!=p&&p.children.length>0){ba(p),this.scene.add(p);const e=this.experimentalStaticDrawSetDisposer,t=this.renderingView.registerExperimentalStaticDrawSet(p,"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 Nt;e.initScene(this.scene),e.clusters.forEach(e=>{this.renderingView.addCluster(e)})}prepareCollisionShapesForInstanced(e){e instanceof lt&&e.collisionShapes.forEach(e=>{e instanceof r&&e.mesh instanceof w&&(e.mesh=e.mesh.geometry)})}setScene(e){this.scene=e}testCanBatch(e,t){return!ca&&(!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 Ke;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=nt(l.assetMesh,t=>t instanceof w&&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 c=["color","map","roughness","roughnessMap","metalness","metalnessMap","opacity","alphaMap","aoMap","aoMapIntensity","normalMap","normalScale","emissive","emissiveIntensity","emissiveMap"],u=new Map,h=new Map,p=[];let f=new l.MeshStandardMaterial({color:"white"});const m=t.get(e[0].id).get(e[0].meshUUID);if(null==m)throw"missing source material";if(m instanceof v&&!(m instanceof l.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 c){let r=e[t];r instanceof l.CompressedArrayTexture&&null!=r.userData.index&&(r=r.userData.index);const i=s.get(t);void 0===i||Ps(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=Is(a.node,a.params.length-1)}else if(a instanceof E)t=V(s);else if(a instanceof O||a instanceof d)t=B(s);else if(a instanceof D)t=T(s);else if(a instanceof l.CompressedArrayTexture)s=e+"_i",t=k(s);else if(a instanceof P)continue;u.set(e,t),h.set(e,s)}let r=oe.uv;m instanceof Yt&&null!=m.heightMap&&(r=Qt(r,X(m.heightMap),F(m.heightScale)));let i=vs(u.get("opacity"),R)??F(m.opacity??1);if(null!=m.alphaMap){let e;if(m.alphaMap instanceof l.CompressedArrayTexture){const t=K(m.alphaMap),a=vs(u.get("alphaMap"),R)??F(m.alphaMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.alphaMap).sample(r);i=i.multiply(e.r)}let n=J(vs(u.get("color"),he)??m.color,i);if(null!=m.map){let e;if(m.map instanceof l.CompressedArrayTexture){const t=K(m.map),a=vs(u.get("map"),R)??F(m.map.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.map).sample(aa(r,m.map));n=n.multiply(e),i=i.multiply(e.a)}m.vertexColors&&(n=n.multiply(pe(ne(C.color.rgb),1)));let o=J(vs(u.get("emissive"),he)??m.emissive,i);if(null!=m.emissiveMap){let e;if(m.emissiveMap instanceof l.CompressedArrayTexture){const t=K(m.emissiveMap),a=vs(u.get("emissiveMap"),R)??F(m.emissiveMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.emissiveMap).sample(aa(r,m.emissiveMap));o=o.multiply(e)}const g=vs(u.get("emissiveIntensity"),R)??F(m.emissiveIntensity??1),y=vs(u.get("normalScale"),ue)??ce(m.normalScale??new D(1,1));let w=le.normal;if(null!=m.normalMap){let e;if(m.normalMap instanceof l.CompressedArrayTexture){const t=K(m.normalMap),a=vs(u.get("normalMap"),R)??F(m.normalMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.normalMap).sample(aa(r,m.normalMap));w=U(e.rgb,y.x)}let S=vs(u.get("roughness"),R)??F(m.roughness??1);if(null!=m.roughnessMap){let e;if(m.roughnessMap instanceof l.CompressedArrayTexture){const t=K(m.roughnessMap),a=vs(u.get("roughnessMap"),R)??F(m.roughnessMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.roughnessMap).sample(aa(r,m.roughnessMap));S=S.multiply(e.g)}let b=vs(u.get("metalness"),R)??F(m.metalness??0);if(null!=m.metalnessMap){let e;if(m.metalnessMap instanceof l.CompressedArrayTexture){const t=K(m.metalnessMap),a=vs(u.get("metalnessMap"),R)??F(m.metalnessMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.metalnessMap).sample(aa(r,m.metalnessMap));b=b.multiply(e.b)}let v=F(1);if(null!=m.aoMap){let e;if(m.aoMap instanceof l.CompressedArrayTexture){const t=K(m.aoMap),a=vs(u.get("aoMap"),R)??F(m.aoMap.userData.index??0);e=t.sample(de(r.x,r.y,a))}else e=X(m.aoMap).sample(aa(r,m.aoMap));v=v.multiply(e.r)}const M=vs(u.get("aoMapIntensity"),R)??F(m.aoMapIntensity??0);let A=w;!0!==m.userData.disableAO&&(A=_("DOUBLE_SIDED",A,e=>Q(new N("gl_FrontFacing"),e,e.multiplyScalar(-1))));const x=new L({color:H({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:xs(m.envMapRotation,m.envMap)}),x.envMap=m.envMap,x.side=m.side,f=x}else if(m instanceof L){const a=new Set,s=new Map,r=Object.keys(m.uniforms).filter(e=>!hs(e));for(const i of e){const e=t.get(i.id).get(i.meshUUID);if(!(e instanceof L))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||Ps(r,i)?s.set(t,r):fs(r)&&fs(i)&&ms(r)===ms(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=gs("vp"+p.length,i);s={name:t,params:[e],node:V(t)},p.push(s)}else s.params.push(e);a=s.name,t=Is(s.node,s.params.length-1)}else if(s instanceof E)a=gs(e,i),t=V(a);else if(s instanceof O||s instanceof d)a=gs(e,i),t=B(a);else{if(!(s instanceof D))continue;a=gs(e,i),t=T(a)}u.set(e,t),h.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:ys(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 S=new Jt(n,i,r,f);for(const e of p)S.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 fe||t instanceof he?a=4:t instanceof ue&&(a=2),S.initUniform(h.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=S.addGeometry(as(i.geometry,m)),c=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=it(f.assetMesh)?.uuid===e,y=f.assetMesh instanceof lt&&g?f.assetMesh.collisionShapes:void 0,w=this.configureBatchedInstancedMesh(r,S,i,n,y);for(let e=0;e<w.length;e++){const a=r[e],s=w[e];"webgpu"!==this.renderingView?.requestedBackend&&S.setCastShadowAt(s,a.castShadow??c?.castShadow??!1);const i=t.get(a.id).get(a.meshUUID),n=i.userData.surface;null!=n&&(S.surfaceByInstance[s]=n);for(const e of p){let t=js.set(0,0,0,0);for(let a=0;a<e.params.length;a++){const s=ps(i,e.params[a]);"number"==typeof s&&t.setComponent(a,s)}S.setUniformAt(e.name,s,t)}for(let e of u.keys()){if(p.some(t=>t.params.includes(e)))continue;const t=h.get(e)??e;let a=ps(i,e);if(a instanceof d&&(a=new O(a.r,a.g,a.b)),a instanceof l.CompressedArrayTexture)a=a.userData.index??0;else if(a instanceof P||null==a)continue;S.setUniformAt(t,s,a)}}}return S}async createInstancedMesh(e,t){const a=nt(t,e=>!dt(e)&&null!=e.geometry),s=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,_a(e[0].materialAssignments,s.materialAssignments),s),a.updateMatrix();const r=a.geometry.clone(),i=a.material;let n;if(n=new l.InstancedMesh(r,i,e.length),this.configureBatchedInstancedMesh(e,n,a),a.material instanceof g&&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 l.BatchedMesh&&(o=t.addInstance(s)),i.push(o);const c=(new l.Matrix4).compose((new O).fromArray(e[n].position),(new I).setFromEuler((new h).fromArray(e[n].rotation)),(new O).fromArray(e[n].scale)),u=(new y).copy(e[n].parentTransform).multiply(c),d=(new y).copy(u).multiply(a.matrixWorld);t.setMatrixAt(o,d),null==t.userData.hasCollision&&(t.userData.hasCollision=[]);const p=this.assets.get(e[n].assetId);t.userData.hasCollision[o]=!1!==e[n].collisionDetection||!1!==p?.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 rt(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(!Ja(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=Qa(a,n)),null!=a&&s.id!==a.id&&(r=r??qa(s),i=i??s.name,s=a);break}return s}unapplyMaterials(e){e.traverse(async e=>{if(e instanceof w)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){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)??Ie[e])!==(a.get(e)??Ie[e])&&s.add(e);this.actorTypes=e,0!==s.size&&rt(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,rt(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 ha.entries())t.userData.customShaderName&&ha.delete(e);pa.clear(),this.landscapeManagers.forEach(t=>t.updateShaders(e)),rt(this.scene,e=>!0).forEach(e=>{e.traverse(async e=>{if(e instanceof w)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 w&&(e.material.wireframe=!0)}):t.traverse(e=>{e instanceof w&&(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);_a(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!==Pe.dynamic?Aa(t,!1):this.inEditor&&function(e){let t=!1;if(e.traverse(e=>{Ma.has(e)&&(t=!0)}),!t)return;e.updateWorldMatrix(!0,!0),e.traverse(e=>{Ma.has(e)&&(e.matrixWorldNeedsUpdate=!1)})}(t)),this.applyVertexMaterials(e,t),"light"==e.type){if("point"==e.light.type){const a=t;a.color=new d(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 d(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 d(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 Xt&&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 f?"density":"linear")!==e.fog.type;this.scene.fog=Pa(e.fog),t&&(a=this.scene).traverse(e=>{if(e instanceof w){const t=e.material;t instanceof L&&(a.fog instanceof p?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof f&&(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 Gt){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 pt&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}if("shape_mesh"===e.type&&"landscape"!==e.shape)da(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;da(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=Ba(e.prefab?.objects??[]),r=Ba(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=Na(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=Va(e.prefab?.objects??[]),i=Va(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=Ba(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=Na(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 je))return null;a=t}return a instanceof je?a:null}findParent(e){const t=this.dataProvider.getObjects().flatMap(t=>t.id===e.id?null:st(t,t=>t.children?.some(t=>t.id===e.id),()=>!0))[0];return null==t?this.scene:null!=t?rt(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 d(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse(e=>{e instanceof w&&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=tt(e.vertexMaterials,e=>e.m);t.traverse(e=>{if(e instanceof w){if(null==e.geometry)return;if(es(bt(e,0,!1)),a>0){es(bt(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=bt(s,0,!0);es(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=bt(s,4,!0);es(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=Pa(e.fog),this.fixFogColor(),i=new m;break;case"sky":this.sky=kt(),this.updateSky(e),i=this.sky;break;case"world_env":this.updateWorldEnv(e),i=new m,this.worldEnvObj=i;break;case"actor":({object:i,actor:n}=await this.createFromActor(e,s));break;case"group":case"scatter":i=new m;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),this.applyTransform(e,i),a?i.userData._src=e:i.userData.src=e,null!=n&&(i.userData.actor=n),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(Da),i.getWorldQuaternion(Oa),i.getWorldScale(Ea),this.scene.add(i),i.position.copy(Da),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!==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)?Aa(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||ba(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 vt(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 Mt(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(l.NoToneMapping,1)}async updateSky(e){null!=this.sky&&(null==e?.sky?.materialId&&this.sky.material!==Tt?(this.sky.material=Tt,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=l.BackSide,(e instanceof v||e instanceof l.MeshBasicMaterial||e instanceof l.ShaderMaterial)&&(e.fog=!1),e.depthTest=!0,e.depthWrite=!1,e.transparent=!0}async createComponent(e,t,a,s){const r=new oa[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??Ie[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 h).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===De.none)return;const t=xe(e.constructor);!0!==t?.replicate?this.netMode===De.client&&(e.netRole=Oe.none):e.netRole=this.netMode===De.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(ge,(new O).fromArray(e.position),(new h).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 w&&this._originalMaterials.set(e.id,e.material)});else{let s=new v({name:"Default",color:new d("#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 m;const a=mt(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new ft(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 gt(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(()=>yt(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 pt(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(_a(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,da(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 w&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()}),s.userData.assetId=e.assetId,s.traverse(e=>{if(e instanceof w)for(const t of at(e.material))Be(t,!1)}),"webgpu"===this.renderingView.requestedBackend){await this.renderingView.initializeBackend();const e=new Set;s.traverse(t=>{if(t instanceof w)for(const a of at(t.material))if(a instanceof l.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 m;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([...Ba(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&&ia(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 A}async createLight(e){if("point"===e.light.type){const t=new x(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 l.TextureLoader).load("assets/light-bulb-icon.webp"),a=new l.SpriteMaterial({map:e,alphaTest:.5}),s=new Lt(a);s.scale.multiplyScalar(.6),t.add(s)}return t}if("spot"===e.light.type){const t=new l.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 A,t.target.position.set(0,-1,0),t.add(t.target),this.inEditor){const e=(new l.TextureLoader).load("assets/light-bulb-icon.webp"),a=new l.SpriteMaterial({map:e,alphaTest:.5}),s=new Lt(a);s.scale.multiplyScalar(.6),t.add(s),t.add(new l.SpotLightHelper(t))}return t}if("rectArea"===e.light.type){const t=new l.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 l.TextureLoader).load("assets/light-bulb-icon.webp"),a=new l.SpriteMaterial({map:e,alphaTest:.5}),s=new Lt(a);s.scale.multiplyScalar(.6),t.add(s);const r=new Xt(t);t.add(r)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional,e),new m):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient,e),new m):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===Ct);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(l.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}};ua=e([me(),t("design:paramtypes",[j,Object,ut,ct,ke,Array,Array,Object,Array])],ua);export{ua as SceneMaterializer};function da(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse(e=>{e.castShadow=t,e.receiveShadow=a})}const ha=new Map,pa=new Map,fa=new S({color:16711935}),ma=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),fa;const n=JSON.stringify(e.material)+t?._id,o=i&&!("shaderGraph"===e.material.type&&"asset"===e.material.shaderGraph?.source);if(o&&ha.has(n))return ha.get(n);if(o&&pa.has(n))return await pa.get(n);const l=_materialFromAsset(n,e,t,a,s,r,o);return o?pa.set(n,l).get(n):l}export async function _materialFromAsset(e,t,a,s,r,n,o=!0){const c={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 d(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&&(c.map=await r.getTexture(a))}let h,p,f;switch(t.material.type){case"phong":h=new b({...c,...u});break;case"water":h=At(c,a);break;case"grassFoliage":h=wt({color:c.color,map:c.map},a);break;case"grass":h=St({...c,colorTwo:new d(t.material.params.colorTwo),colorThree:new d(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),h=fa;break}"surface"===e.target&&null!=e.materialOptions?.side&&(p=ra(e.materialOptions.side)),"decal"===e.target?f=!1:null!=e.materialOptions?.transparent&&(f=e.materialOptions.transparent);try{const i=await prepareShaderGraphParameters(t.material?.shaderParams??{},e,s,r,a,n),o=t.shaderGraphPreviewNodeId,l=t.trailBillboard;h=sa(e,{parameters:i,previewNodeId:o,trailBillboard:l,alphaTest:t.material.alphaTest}),h.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),h=fa}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:la?Ue:Re,lambert:Ue,unlit:_e,toon:qt,layered:Rt,landscape:We,"landscape-composite":Fe,"decal-unlit":Vt,"decal-standard":zt,sprite:i}[t.material.type]??n.find(e=>e.name==t.material.shader)?.type;if(e){try{let i=new e;const o=await prepareClassParameters(t.material?.shaderParams??{},e,s,r,null,a,n,void 0,void 0,i);Object.assign(i,o),i.alphaTest=t.material.alphaTest??i.alphaTest,h=i.build()}catch(e){console.log("Shader runtime error: "+e,e),ma.has(t.material.shader)||ma.set(t.material.shader,fa.clone()),h=ma.get(t.material.shader)}h.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),h=fa;break;default:throw new Error("Unsupported material type "+t.material.type)}if(a?.csm.setupMaterial(h),h.side=p??t.material.side??h.side??l.FrontSide,h.transparent=(f??t.material.transparent??c.transparent??!1)||h.transparent,h.alphaTest=t.material.alphaTest??h.alphaTest??0,h.userData.receiveDecals=t.material.receiveDecals??!0,null!=t.material.blending&&(h.blending=Ee[t.material.blending]??l.NormalBlending),!0===t.material.transparent&&(h.depthWrite=!1),t.material.bloom&&(h.userData.hasBloom=!0),t.material.reflective&&(h.userData.reflective=!0),!0===t.material.outlines&&(h.userData.outlineParameters={},null!=t.material.outlineParams&&(null!=t.material.outlineParams.color&&(h.userData.outlineParameters.color=new d(t.material.outlineParams.color).toArray()),null!=t.material.outlineParams.thickness&&(h.userData.outlineParameters.thickness=t.material.outlineParams.thickness),null!=t.material.outlineParams.opacity&&(h.userData.outlineParameters.alpha=t.material.outlineParams.opacity),null!=t.material.outlineParams.colorMode&&(h.userData.outlineParameters.colorMode=t.material.outlineParams.colorMode),null!=t.material.outlineParams.darkening&&(h.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,n);null!=e&&(h.userData.surface=e.value)}return h.userData.assetId=t.id,o&&null!=a&&ha.set(e,h),o&&pa.delete(e),h}export function prepareCustomParamsFromShaderGraph(e,t={}){return Object.fromEntries((e.parameters??[]).map(e=>{const a=function(e){switch(e){case"float":return xt.FloatNode;case"boolean":return xt.BooleanNode;case"texture":return xt.Sampler2DNode;case"vec2":return xt.Vec2Node;case"vec3":return xt.Vec3Node;case"vec4":return xt.Vec4Node;case"color":return xt.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?Ra(i):s?.value??Ra(i);return[e.name,{type:a,value:n,override:r}]}))}export async function prepareShaderGraphParameters(e,t,a,s,r,i){const n={},o=prepareCustomParamsFromShaderGraph(t,e);for(const[e,t]of Object.entries(o)){const o=await ya(e,t,a,s,null,r,i);null!=o&&(n[e]=o)}return n}export async function prepareClassParameters(e,t,a,s,r,i,n,o,l,c){const u={},{params:d,skipped:h}=jt(e,{parameterType:t,parameterTarget:c,extractPropertyParameters:Ge,toSerializedParamType:toSerializedParamType});for(const e of h)console.warn(`Skipping stored parameter "${e.key}" because it could not be converted from ${xt[e.sourceType]} to ${xt[e.targetType]}`);for(const[e,t]of Object.entries(d)){if(!1===t.override)continue;const c=await ya(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 ya(r,i,t,a,null,void 0,void 0,void 0,void 0,void 0);null!=e&&(s[r]=e)}return s}const ga=new Map;async function ya(e,t,a,s,r,i,n,o,l=t.value,c=t.type,u,p=(t.type===xt.Struct?t.struct:void 0)){if(null==t||null==l||""===l)return null;switch(c){case xt.Array:if(Array.isArray(l)&&"element"in t)return await Promise.all(l.map(l=>ya(e,t,a,s,r,i,n,o,l,t.element,u,t.elementStruct)));break;case xt.Number:case xt.FloatNode:let f;if("string"==typeof l?f=parseFloat(l):"number"==typeof l&&(f=l),c===xt.FloatNode){if("object"==typeof l&&"a"in l&&"b"in l){const e=l;if(null==e.a)return null;const t="string"==typeof e.a?parseFloat(e.a):e.a;if(null==e.b)return t;const a="string"==typeof e.b?parseFloat(e.b):e.b,s=function(e){let t=ga.get(e);return null==t&&(t=Ve(Bt.decode(e)),ga.set(e,t)),t}(e.easing),r=s.sample(ze(Ne.energy));return G(F(t),F(a),r)}return new te(Xe(e),f,void 0,!1)}return f;case xt.Texture:let m=await s.getTexture(await a.getAsset(l));return"envmap"===e.toLowerCase()&&null!=i&&(m=i.getEnvTexture(m)),m;case xt.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 ae(null,t,new te(Xe(e)+"_i",a,void 0,!1))}const y=await s.getTexture(g);return y?X(y):null;case xt.Boolean:return l;case xt.BooleanNode:return new ee(Xe(e),l,void 0,!1);case xt.Vector2:case xt.Vec2Node:if("object"==typeof l){const t=l instanceof Array?(new D).fromArray(l):new D(l.x,l.y);return c===xt.Vec2Node?new se(Xe(e),t,void 0,!1):t}return null;case xt.Vector3:case xt.Vec3Node:if("object"==typeof l){const t=l instanceof Array?(new O).fromArray(l):new O(l.x,l.y,l.z);return c===xt.Vec3Node?new re(Xe(e),t,void 0,!1):t}return null;case xt.Vector4:case xt.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===xt.Vec4Node?new ie(Xe(e),t,void 0,!1):t}return null;case xt.Color:case xt.RgbNode:const w=new d(l);return c===xt.RgbNode?new re(Xe(e),new O(w.r,w.g,w.b),void 0,!1).rgb:w;case xt.String:return l;case xt.Scene:return"string"==typeof l?new ve(l):"object"==typeof l&&null!=l&&"string"==typeof l.id?new ve(l.id,"string"==typeof l.name?l.name:void 0):null;case xt.ModelRef:return"string"==typeof l?new Me(l):null;case xt.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 xt.Euler:const b=l;return(new h).fromArray(b);case xt.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 xt.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=ha.get(t);if(null!=r)return r;const o=await prepareShaderGraphParameters({},e.shaderGraph,a,s,i,n),l=sa(e.shaderGraph,{parameters:o});return l.userData.assetId=e.id,ha.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 xt.AudioBuffer:return await s.getAudio(await a.getAsset(l));case xt.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 ye(o,v);console.error("Using a non-vfx asset for visual effect parameter");break;case xt.Prefab:{const e=await a.getAsset(l);return null==e?(console.error("Using a non-prefab asset for prefab parameter",l),null):new we(e)}case xt.PrefabActor:{const e=await a.getAsset(l);return null==e?(console.error("Using a non-prefab asset for prefab parameter",l),null):new Se(new we(e))}case xt.DataAsset:return materializeDataAssetRef(l,a,s,r,i,n,o,u);case xt.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 ta(e.sequence);console.error("Using a non-sequence asset for sequence parameter");break}case xt.SequenceData:return ea(l)?l:(console.warn("Invalid inline sequence data parameter value",l),null);case xt.Struct:return async function(e,t,a,s,r,i,n,o,l){const c=wa(e),u=c?.struct??t;if(null==u)return console.warn("Missing parameter definition id for struct parameter"),null;const d=Je(u);if(null==d)return console.warn(`Unknown parameter definition "${u}"`),null;if(Qe(u))return console.warn(`Can not instantiate abstract parameter definition "${u}"`),null;if(null!=t&&u!==t&&!Ze(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=wa(e);if(null!=t)return t.value;if(Sa(e))return e;if(null!=e&&"object"==typeof e&&Sa(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,p,a,s,r,i,n,o,u);case xt.Curve:return Bt.decode(l);case xt.ColorLayer:case xt.MaskLayer:if(_t(l)){const e=await $t.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 xt.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,o,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=Le(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,o,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 n(e=>{let n=0;const c=t.onUpdate.subscribe(c=>{if(c.id!==u.id||"data"!==c.type)return;const d=++n;materializeDataAssetRef(u.id,t,a,s,r,i,o,l).then(t=>{e.closed||d!==n||null==t||e.next(t)}).catch(e=>console.warn(`Failed to reload data asset "${u.id}"`,e))});return()=>c.unsubscribe()}):void 0;return new be(u,p,m)}function wa(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.struct&&Sa(e.value)?e:null}function Sa(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&Object.values(e).every(e=>null!=e&&"object"==typeof e&&"type"in e)}function ba(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 va(){}const Ma=new WeakMap;function Aa(e,t){if(t)return e.userData.hologyEditorMatrixWorldAutoUpdate=!0,void e.traverse(e=>{const t=Ma.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=>{Ma.has(e)&&s.push(e)}),0!==s.length||a||s.push(e);for(const e of s)xa(e);delete e.userData.hologyEditorMatrixWorldAutoUpdate}function xa(e){const t=Ma.get(e);if(e.updateMatrix(),e.updateWorldMatrix(!0,!0),null==t){const t=new Map;e.traverse(e=>{t.set(e,e.matrixAutoUpdate)}),Ma.set(e,{updateMatrixWorld:e.updateMatrixWorld,matrixAutoUpdate:t})}e.traverse(e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1}),e.updateMatrixWorld=va}function Ia(e,t=!1){return Array.isArray(e)?e.every(e=>Ia(e,t)):t||!e.transparent&&!ja(e)}function ja(e){return e instanceof L&&(null!=e.uniforms[na]||null!=e.uniforms.hology_scene_map)}function Pa(e){return"linear"===e.type?new p(new d(e.color),e.near??100,e.far??1e3):"density"===e.type?new f(e.color,e.density):void console.warn("Invalid fog type",e)}const Da=new O,Oa=new I,Ea=new O;new v({color:4229780});async function Ca(e,t,a,s){null==s&&(s=(new y).identity());const r=s.clone().multiply(ka(e,new l.Matrix4));if(null!=e.children&&e.children.length>0)for(let a=e.children.length-1;a>=0;a--)await Ca(e.children[a],t,e,r);await t(e,a,s)}function ka(e,t){return null==e.position||null==e.rotation||null==e.scale?t.identity():t.compose((new O).fromArray(e.position),(new I).setFromEuler((new h).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?xt.Number:t instanceof R||"function"==typeof e.prototype.isFloat?xt.FloatNode:t instanceof P||e===P||e.isTexture?xt.Texture:t instanceof $e||e===$e||e===Z||"function"==typeof e.prototype?.isSampler2D||!0===e.prototype?.isSampler2D?xt.Sampler2DNode:t instanceof Boolean||e===Boolean?xt.Boolean:t instanceof $?xt.BooleanNode:t instanceof d||e==d?xt.Color:t instanceof Y||"function"==typeof e.prototype.isRgb?xt.RgbNode:t instanceof D||e==D?xt.Vector2:t instanceof ue||"function"==typeof e.prototype.isVec2?xt.Vec2Node:t instanceof O||e==O?xt.Vector3:t instanceof he||"function"==typeof e.prototype.isVec3?xt.Vec3Node:t instanceof E||e==E?xt.Vector4:t instanceof fe||"function"==typeof e.prototype.isVec4?xt.Vec4Node:t instanceof String||e===String?xt.String:t instanceof ve||e===ve?xt.Scene:t instanceof Me||e===Me?xt.ModelRef:t instanceof Ae||e==Ae||e.prototype instanceof Ae||e.prototype==Ae?xt.BaseActor:t instanceof h||e==h?xt.Euler:t instanceof A||e==A?xt.Object3D:t instanceof g||e==g?xt.Material:t instanceof AudioBuffer||e==AudioBuffer?xt.AudioBuffer:t instanceof ye||e==ye?xt.VisualEffect:t instanceof we||e==we?xt.Prefab:t instanceof Se||e==Se?xt.PrefabActor:t instanceof be||e==be?xt.DataAsset:t instanceof Bt||e==Bt?xt.Curve:t instanceof $t||e==$t?xt.ColorLayer:t instanceof Wt||e==Wt?xt.MaskLayer:t instanceof l.AnimationClip||e==l.AnimationClip?xt.AnimationClip:t instanceof ta||e==ta?xt.Sequence:"SequenceData"===e.name||e.prototype&&"tracks"in e.prototype?xt.SequenceData:null!=qe(e)?xt.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===xt.Struct?qe(e.type):void 0;return!0===e.options.array?{type:xt.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=Ta(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 ea(e)?{type:xt.SequenceData}:void 0}(t);null!=a&&(e=a)}if(e.type!==xt.Struct)return{typeInfo:e,value:t};const a=wa(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===xt.Struct)return Qe(e.type)?{}:prepareCustomParamsFromType(e.type,{});return customParameterDefaultValueByType.get(a)}(e,a)),p=function(e,t){if(Ta(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!==xt.SequenceData||!ea(e))return;return{type:xt.SequenceData,value:e}}(n,h.typeInfo);i=function(e,t,a){if(e.type!==xt.Struct||a?.type!==xt.Struct||null==a.struct)return e;const s=t.struct??e.struct;if(null==s||a.struct===s||Ze(a.struct,s)||null==Je(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?Ra(t):[];return Ra(t)}(e,h.value,d):Ra(h.value),m=function(e,t,a){if(t.type===xt.Struct){if(null!=t.struct&&Qe(t.struct))return a;const s=null!=t.struct?Je(t.struct):e.type;return null!=s&&Sa(a)?prepareCustomParamsFromType(s,a):a}if(t.type!==xt.Array||t.element!==xt.Struct||!Array.isArray(a))return a;const s=null!=t.elementStruct?Je(t.elementStruct):e.type;return a.map(e=>{const a=wa(e),r=a?.struct??t.elementStruct;if(null!=r&&Qe(r))return e;const i=null!=a?Je(a.struct):s,n=a?.value??(Sa(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 Ta(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"number"==typeof e.type&&"value"in e}function Ba(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 Va(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??{},...Ua(e.params)}})}return{...e,params:{...e.params??{},...Ua(t.prefab.params)},innerParams:[...s.values()]}}function Na(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=$a(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:$a(e.params??{},t.params??{},a.params??{}),innerParams:n}}function $a(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 Ua(e){return null==e?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>function(e){return!0===e?.override}(e)))}function Fa(e,t){return e.length>=t.length&&t.every((t,a)=>e[a]===t)}export function prepareCustomParamsFromType(e,t,a=null,s={}){const r=Ge(e);if(0===r.length)return{};let i;null!=a?Ce(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 Ra(e){return null==e?e:Array.isArray(e)?e.map(e=>Ra(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 D:return t instanceof D?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 d:return t instanceof d?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new d(t).getHexString():void a();case String:return t;case h:return t instanceof h?t.toArray():void a();case we:return t instanceof we?t.asset?.id??null:void a();case be:return t instanceof be?t.id:"string"==typeof t?t:void a();case ve:return t instanceof ve?{id:t.id,...null!=t.name?{name:t.name}:{}}:void a();case Me:return t instanceof Me?t.id:"string"==typeof t?t:void a()}const s=qe(e);if(null!=s){const r=wa(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!=qe(a)&&He(a,e)?a:e}(e,t),n=qe(i),o=function(e,t){if(null==t)return null;if(Sa(t))return t;if(null!=t&&"object"==typeof t&&Sa(t.params))return t.params;if("object"!=typeof t)return;const a=Ge(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(ea(t))return t}function _a(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=>Ga(e.materialId)),(t??[]).filter(e=>Ga(e.materialId)),e=>e.name?`name:${e.name}`:`color:${e.color}`)}function Ga(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[xt.RgbNode,"#000000"],[xt.Color,"#000000"],[xt.String,""],[xt.Scene,null],[xt.ModelRef,null],[xt.Vector4,[0,0,0,0]],[xt.Vec4Node,[0,0,0,0]],[xt.Vector3,[0,0,0]],[xt.Vec3Node,[0,0,0]],[xt.Vector2,[0,0]],[xt.Vec2Node,[0,0]],[xt.Euler,[0,0,0,"XYZ"]],[xt.Array,[]],[xt.DataAsset,null],[xt.SequenceData,Kt()],[xt.ColorLayer,Ut],[xt.MaskLayer,Ft]]);let La=new d;new d;function qa(e){return null==e?.color?null:(La.set(e.color),"#"+La.getHexString())}function Ja(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=qa(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 w||e.isMesh||e instanceof l.SkinnedMesh||e.isSkinnedMesh)for(const t of at(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 d))continue;const o=qa(n),l=n.name;if(Ja(n,t,e.userData["originalColor_"+i],e.userData["originalMaterialName_"+i])){const n=Qa(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=qa(i),o=i.name;if(Ja(i,t,e.userData.originalColor,e.userData.originalMaterialName)){const i=Qa(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 Ya=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 Qa(e,t){if(null==e||null==t||!function(e,t){return function(e){const t=[];for(const[a,s]of Object.entries(e))Za(a,s)&&t.push(s);if(e instanceof l.ShaderMaterial)for(const[a,s]of Object.entries(e.uniforms))Za(a,s.value)&&t.push(s.value);return t}(e).some(e=>e.flipY!==t)}(e,t))return e;let a=Ya.get(e);null==a&&(a=new Map,Ya.set(e,a));const s=a.get(t);if(null!=s)return s;const r=Ha(e);if(function(e,t){for(const a of Object.keys(e)){const s=e[a];Za(a,s)&&(e[a]=Xa(s,t))}}(r,t),r instanceof l.ShaderMaterial){for(const[e,a]of Object.entries(r.uniforms))Za(e,a.value)&&(a.value=Xa(a.value,t));r.uniformsNeedUpdate=!0}return r.needsUpdate=!0,a.set(t,r),r}function Ha(e){const t=e.clone();return t.userData={...e.userData??{}},t}function Za(e,t){const a=t;return(t instanceof P||!0===a?.isTexture)&&!e.toLowerCase().includes("envmap")&&!0!==a.isCompressedTexture&&!0!==a.isCompressedArrayTexture}function Xa(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 Ka(e,t){if(e instanceof l.ShaderMaterial&&t instanceof l.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof l.ShaderMaterial&&t instanceof l.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 es(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}function ts(e,t){const a=it(e);return null==a?"":function(e,t){const a=Cs(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&&is(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 as(e,t){const a=Cs(e,t);if(a.length===Object.keys(e.attributes).length)return e;const s=new u;s.name=e.name;const r=e.getIndex();null!=r&&s.setIndex(r);for(const t of a)s.setAttribute(t,rs(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 ss=new WeakMap;function rs(e,t){return e.getAttribute(t)??function(e,t){if("uv"===t)return function(e){let t=ss.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 l.Float32BufferAttribute(new Float32Array(2*a.count),2),ss.set(e,t));return t}(e);throw new Error(`Unsupported synthetic batching geometry attribute: ${t}`)}(e,t)}function is(e){return null!=e.getAttribute("position")}const ns=new WeakMap,os="hbat_",ls=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 cs(e){let t=ns.get(e);return null==t&&(t=function(e){let t=e.type;if(e instanceof L)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(hs(a))continue;const s=e.uniforms[a]?.value;fs(s)||(t+=`u:${a}:${bs(s)};`)}return t+=ds(e.vertexShader),t+=ds(e.fragmentShader),t}(e);else if(e instanceof l.MeshStandardMaterial&&!(e instanceof l.MeshPhysicalMaterial)||(t+=e.id+""),(e instanceof l.MeshBasicMaterial||e instanceof l.MeshLambertMaterial||e instanceof v||e instanceof b)&&(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 v&&(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 l.MeshPhysicalMaterial&&(null!=e.sheenColorMap&&(t+="sc"+e.sheenColorMap?.id),null!=e.sheenRoughnessMap&&(t+="sr"+e.sheenRoughnessMap?.id)),(e instanceof S||e instanceof b)&&null!=e.specularMap&&(t+="s"+e.specularMap?.id),e instanceof l.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 Yt&&null!=e.heightMap&&(t+="h"+e.heightMap?.id),e instanceof l.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),ns.set(e,t)),t}const us=new Map;function ds(e){return us.has(e)||us.set(e,`shader_${us.size}`),us.get(e)}function hs(e){return ls.has(e)||e.startsWith("hology_")}function ps(e,t){return e instanceof L?e.uniforms[t]?.value:e[t]}function fs(e){return"number"==typeof e||e instanceof D||e instanceof O||e instanceof E||e instanceof d}function ms(e){return"number"==typeof e?1:e instanceof D?2:4}function gs(e,t){const a=e.replace(/[^A-Za-z0-9_]/g,"_");let s=os+a;for(;t.has(s);)s=os+s;return t.add(s),s}function ys(e,t){const a={};for(const[s,r]of Object.entries(e.uniforms))t.has(s)||(a[s]={value:r.value});return a}const ws=new WeakMap;let Ss=1;function bs(e){if(null==e)return"null";if(e instanceof P||!0===e?.isTexture)return`texture:${e.id}`;if(e instanceof l.Matrix3||e instanceof l.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=ws.get(e);return null==t&&(t=Ss++,ws.set(e,t)),`object:${t}`}return String(e)}function vs(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 Ms=new y,As=new h;function xs(e,t){return As.copy(e),As.x*=-1,As.y*=-1,As.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(As.y*=-1,As.z*=-1),(new l.Matrix3).setFromMatrix4(Ms.makeRotationFromEuler(As))}function Is(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 js=new E;function Ps(e,t){return e===t||null==e==(null==t)&&("number"==typeof e&&"number"==typeof t?e===t||isNaN(e)&&isNaN(t):e instanceof l.Color&&t instanceof l.Color?e.r===t.r&&e.g===t.g&&e.b===t.b:e instanceof D&&t instanceof D?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 Ds(e){const t=[];for(const[a,s]of Object.entries(e))s instanceof ye?t.push(s):s instanceof je&&t.push(...Ds(s));return t}function Os(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)}const Es=new WeakMap;function Cs(e,t){const a=Object.keys(e.attributes).filter(a=>ks(e,t,a));return!e.hasAttribute("uv")&&is(e)&&ks(e,t,"uv")&&a.push("uv"),a}function ks(e,t,a){return"position"===a||("uv"===a?function(e){if(e instanceof L)return Bs(e,"uv");if(e instanceof l.ShaderMaterial)return Vs(e.vertexShader,"uv");if(e instanceof Yt&&null!=e.heightMap)return!0;return Ts.some(t=>e[t]?.isTexture)}(t):t instanceof L?Bs(t,a):t instanceof l.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=Es.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 Es.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 zs(e,t,a){if(t(e))return e;for(const s of e.children??[]){const e=zs(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=>zs(e,t,a));if(null!=e)return e}}return null}const Ns=new O,$s=new O,Us=new O,Fs=new E,Ws=new E,Rs=new y,_s=new y,Gs=new M;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 y).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++)Ns.fromBufferAttribute(r,t),e.applyBoneTransform(t,Ns),r.setXYZ(t,Ns.x,Ns.y,Ns.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 w(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),Ws.fromBufferAttribute(i,t),a.identity().multiplyScalar(0);for(let e=0;e<4;e++){const t=Ws.getComponent(e);if(0===t)continue;const s=Fs.getComponent(e);Rs.multiplyMatrices(n.bones[s].matrixWorld,n.boneInverses[s]);for(let e=0;e<16;e++)a.elements[e]+=Rs.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}/*
2
2
  * Copyright (©) 2026 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */