@hology/core 0.0.261 → 0.0.262
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gameplay/index.d.ts +1 -0
- package/dist/gameplay/index.js +1 -1
- package/dist/gameplay/initiate.js +1 -1
- package/dist/gameplay/inject.d.ts +8 -0
- package/dist/gameplay/inject.js +1 -1
- package/dist/gameplay/services/asset-loader.d.ts +3 -0
- package/dist/gameplay/services/asset-loader.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/rendering/graphics-runtime.d.ts +1 -1
- package/dist/rendering/graphics-runtime.js +1 -1
- package/dist/rendering/node-material-webgpu-resolver.js +1 -1
- package/dist/rendering.d.ts +6 -1
- package/dist/rendering.js +1 -1
- package/dist/scene/asset-resource-loader.d.ts +3 -0
- package/dist/scene/asset-resource-loader.js +1 -1
- package/dist/scene/custom-param-deserialize.js +1 -1
- package/dist/scene/custom-param-runtime-types.js +1 -1
- package/dist/scene/lattice-deformation.d.ts +28 -0
- package/dist/scene/lattice-deformation.js +4 -0
- package/dist/scene/materializer.d.ts +12 -3
- package/dist/scene/materializer.js +1 -1
- package/dist/scene/model-ref.d.ts +7 -0
- package/dist/scene/model-ref.js +4 -0
- package/dist/scene/model.d.ts +2 -1
- package/dist/scene/model.js +1 -1
- package/dist/shader/parameter.d.ts +2 -1
- package/dist/test/graphics-runtime.test.js +1 -1
- package/dist/test/lattice-deformation.test.d.ts +2 -0
- package/dist/test/lattice-deformation.test.js +4 -0
- package/dist/test/materializer-prefetch.test.js +1 -1
- package/docs/actor-persistence.md +87 -87
- package/package.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as e,__metadata as t}from"tslib";import{ConvexPolyhedronCollisionShape as a}from"./collision/collision-shape.js";import{SpriteShader as s}from"../shader/sprite-shader.js";import{Subject as r}from"rxjs";import*as i from"three";import{BoxGeometry as n,BufferGeometry as o,Color as l,Euler as c,Fog as u,FogExp2 as d,Group as h,Material as p,Matrix4 as f,Mesh as m,MeshLambertMaterial as g,MeshPhongMaterial as y,MeshStandardMaterial as S,Matrix3 as w,Object3D as b,PointLight as v,Quaternion as M,Scene as A,Texture as x,Vector2 as j,Vector3 as I,Vector4 as P}from"three";import{attributes as D,batchingUniformFloat as O,batchingUniformVec2 as E,batchingUniformVec3 as C,batchingUniformVec4 as k,bool as T,BooleanExpression as B,BooleanNode as V,colorToNormal as z,float as N,deriveNodeShaderMaterial as $,FloatNode as U,ifDefApply as F,mix as W,NodeShaderMaterial as R,rgb as _,rgba as G,RgbNode as L,select as q,standardMaterial as J,Texture2dLookupNode as Y,textureSampler2d as Q,textureSampler2dArray as H,UniformBoolNode as Z,UniformFloatNode as X,UniformSampler2dArraySlice as K,UniformVec2Node as ee,UniformVec3Node as te,UniformVec4Node as ae,varying as se,varyingAttributes as re,varyingTransformed as ie,vec2 as ne,Vec2Node as oe,vec3 as le,Vec3Node as ce,vec4 as ue,Vec4Node as de}from"three-shader-graph";import{Service as he}from"typedi";import{VfxActor as pe}from"../effects/vfx/vfx-actor.js";import{VisualEffect as fe}from"../effects/vfx/vfx-param.js";import{Prefab as me,PrefabOf as ge}from"./objects/prefab.js";import{DataAssetRef as ye}from"./objects/data-asset.js";import{SceneRef as Se}from"./scene-ref.js";import{BaseActor as we,getActorOptions as be}from"../gameplay/actors/actor.js";import ve from"../gameplay/actors/builtin/index.js";import{ActorComponent as Me}from"../gameplay/actors/component.js";import{PhysicsBodyType as Ae}from"../gameplay/services/physics/physics-system.js";import{NetMode as xe}from"../gameplay/net/net-session.js";import{NetRole as je}from"../gameplay/net/service/net-actor-role.js";import{ThreeBlendingMode as Ie}from"../effects/vfx/vfx-asset.js";import{withInjectionContext as Pe}from"../gameplay/inject.js";import{RenderingView as De}from"../rendering.js";import{markMaterialUniformValuesNeedUpdate as Oe,setMaterialUniformValuesAutoUpdate as Ee}from"../rendering/node-material-webgpu-resolver.js";import{curveSampler as Ce,oneMinus as ke,particleUniforms as Te,Sampler2DNode as Be}from"../shader-nodes/index.js";import{LambertShader as Ve}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as ze}from"../shader/builtin/landscape-composite-shader.js";import{LandscapeShader as Ne}from"../shader/builtin/landscape-shader.js";import{StandardShader as $e}from"../shader/builtin/standard-shader.js";import{UnlitShader as Ue}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as Fe,getDataAssetDefinitionType as We,getParameterDefinitionId as Re,getParameterDefinitionType as _e,isDataAssetDefinitionAbstract as Ge,isParameterDefinitionAbstract as Le,isParameterDefinitionAssignableTo as qe,isParameterDefinitionStructAssignableTo as Je,shaderParameterUniformName as Ye}from"../shader/parameter.js";import{ArrayMap as Qe,DefaultMap as He,groupBy as Ze}from"../utils/collections.js";import{iterateMaterials as Xe}from"../utils/materials.js";import{filterChildrenShallow as Ke,filterSceneShallow as et,findFirstVisibleMesh as tt,findFirstVisibleObject as at,traverseAsync as st}from"../utils/three/traverse.js";import{AssetMeshInstance as rt,AssetResourceLoader as it}from"./asset-resource-loader.js";import{AssetsProvider as nt}from"./assets-provider.js";import{isCollisionMesh as ot}from"./collision/collision-shape-import.js";import{BoxCollisionShape as lt,PhysicalShapeMesh as ct}from"./collision/collision-shape.js";import{LandscapeManager as ut}from"./landscape/landscape-manager.js";import{initLandscape as dt}from"./landscape/landscape.js";import{SectionGrid as ht,smoothNormalsCrossMeshes as pt}from"./landscape/utils.js";import{createGrassFoliageMaterial as ft}from"./materials/grass-foliage.js";import{createGrassMaterial as mt}from"./materials/grass.js";import{getMaterialAttribute as gt}from"./materials/utils/material-painting.js";import{PaintedScatterManager as yt}from"./scatter/painted-scatter-manager.js";import{SurfaceScatterManager as St}from"./scatter/surface-scatter-manager.js";import{createWaterMaterial as wt}from"./materials/water.js";import{SerializedParamType as bt}from"./model.js";import{applyRuntimeParamTypeInference as vt,convertConfiguredParamsToRuntimeTypes as Mt,convertConfiguredParamValueToRuntimeType as At,inferRuntimeSerializedParamTypeHint as xt}from"./custom-param-runtime-types.js";import{ShapeLibrary as jt,ShapeLibraryKeys as It}from"./objects/shapes.js";import{ambientLightName as Pt,createSky as Dt,defaultSkyMaterial as Ot}from"./sky.js";import{Curve2 as Et}from"../utils/curve.js";import{DecalUnlitShader as Ct}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as kt}from"../shader/builtin/decal-standard-shader.js";import{ClusterGenerator as Tt}from"../rendering/cluster-generator.js";import{ColorLayer as Bt,defaultValueColorLayer as Vt,defaultValueMaskLayer as zt,MaskLayer as Nt}from"../shader/color-layer.js";import{LayeredShader as $t}from"../shader/builtin/layered-shader.js";import{isColorLayerSerialized as Ut}from"../shader/color-layer.js";import{FogVolume as Ft}from"../rendering/fog/fog-volume-actor.js";import{UnscaledSprite as Wt}from"../utils/three/unscaled-sprite.js";import{ToonShader as Rt}from"../shader/builtin/toon-shader.js";import{BatchedMesh2 as _t}from"./batched-mesh-2.js";import{ParallaxStandardMaterial as Gt}from"../shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Lt}from"../shader-nodes/pom.js";import{traverseVisibleEvery as qt}from"../utils/three/traverse.js";import{BufferGeometryUtils as Jt,RectAreaLightHelper as Yt}from"three/examples/jsm/Addons.js";import{createSequenceData as Qt,isSequenceData as Ht,Sequence as Zt}from"../effects/sequence/sequence-data.js";import{applyUvTiling as Xt}from"./../shader/uv-nodes.js";import{buildShaderGraphMaterial as Kt,shaderGraphMaterialSideToThree as ea}from"../shader/graph/index.js";import{hasExecutableEventGraphDocument as ta}from"../gameplay/event-graph/model.js";import{depthUniformName as aa}from"../shader-nodes/depth.js";export{vt as applyRuntimeParamTypeInference,Mt as convertConfiguredParamsToRuntimeTypes,At as convertConfiguredParamValueToRuntimeType,xt as inferRuntimeSerializedParamTypeHint};const sa={},ra=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),ia=/^((?!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 na(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}let na=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,a,s,n,o,l,c,u=[]){this.scene=e,this.dataProvider=t,this.assetsService=a,this.assetManagerService=s,this.renderingView=n,this.shaders=o,this.actorTypes=l,this.actorProvider=c,this.componentTypes=u,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=xe.none,this.updated$=new r,this.removed$=new r,this.prefabEventGraphAdded$=new r,this.prefabEventGraphRemoved$=new r,this.error$=new r,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._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 r,this._originalMaterials=new Map,this.worldEnvironmentRequest=0,this.prefabInstanceChain=[],this.prefabInstanceExposedActorMap=new Map,this.geometryCache=new Map,this.collisionShapeCache=new Map,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=a.onCreate.subscribe(e=>{this.assets.set(e.id,e)}),this.updateSubscription=a.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 i.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=>ks(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 I,!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 Pa(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 m)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 Pa(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 i.SpotLight&&"spot"===t.userData?.src?.light?.type&&t.userData.src.light.spot.mapTextureId===e.id&&s.push(t),t instanceof m&&(Array.isArray(t.material)?t.material.forEach(r):r(t.material))}),0===a.size&&0===s.length)return;const n=await this.assetManagerService.getTexture(e);if(null!=n){for(const t of a)this.replaceMaterialTextureReferences(t,e.id,n);for(const e of s)e.map=n}else console.error("Can not refresh material textures. Texture not found",e)}materialUsesTexture(e,t){if(e instanceof i.ShaderMaterial){for(const a of Object.values(e.uniforms))if(a.value instanceof i.Texture&&a.value.userData.assetId===t)return!0}else for(const a of Object.values(e))if(a instanceof i.Texture&&a.userData.assetId===t)return!0;return!1}replaceMaterialTextureReferences(e,t,a){let s=!1;if(e instanceof i.ShaderMaterial)for(const[r,n]of Object.entries(e.uniforms))n.value instanceof i.Texture&&n.value.userData.assetId===t&&(e.uniforms[r].value=a,s=!0);else for(const[r,n]of Object.entries(e))n instanceof i.Texture&&n.userData.assetId===t&&(e[r]=a,s=!0);s&&(e.needsUpdate=!0,Oe(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===bt.Material&&s.value===a.id){t=!0;break}if(s.type===bt.Array&&"element"in s&&s.element===bt.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?Qa(e.material[s],i)||(e.material[s]=i):Qa(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=new Map,t=new Map,a=[];for(const a of this.collectMaterialAssignments(this.dataProvider.getObjects())){const s=this.assets.get(a.materialId);if(null!=s?.material)for(const a of Object.values(s.material.shaderParams??{}))if(a.type===bt.Texture&&"string"==typeof a.value){const s=this.assets.get(a.value);if(null==s)continue;const r=s.texture?.textureArrayFileKey;null==r?e.set(s.id,s):t.set(r,s)}}const s=[...Array.from(e.values(),e=>({asset:e,array:!1})),...Array.from(t.values(),e=>({asset:e,array:!0}))];let r=0;if(await Promise.all(Array.from({length:Math.min(16,s.length)},async()=>{for(;r<s.length;){const{asset:e,array:t}=s[r++],i=t?(await this.assetManagerService.getTextureArray(e))?.texture:await this.assetManagerService.getTexture(e);null!=i&&a.push(i)}})),0!==a.length&&this.renderingView&&"webgpu"!==this.renderingView.requestedBackend){console.log(`Initializing ${a.length} textures`),console.time("Init textures");for(const e of a)this.renderingView.initTexture(e);console.timeEnd("Init textures")}}async prefetchAssets(){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})})),this.initTextures()}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(),la.clear(),ca.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()}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)wa(e,!1);this.editorMatrixWorldEditingObjects.clear();for(const t of e)this.editorMatrixWorldEditingObjects.add(t),wa(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)wa(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||!0===t.hidden||t.physics?.type===Ae.dynamic)continue;const a=this.sceneObjectMap.get(t.id);null!=a&&this.canUseEditorStaticDrawSet(a)&&e.push(a)}const t=new h;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 h;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 h;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;(ot(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=ya}0!==t.children.length&&(ga(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 m&&!ot(e)&&(t=!0,null!=e.geometry?.index&&null==e.customDepthMaterial&&va(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 A;for(const i of e){const e=i.asset;if(t.has(e.id))continue;t.add(e.id),js(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=>xs(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,Va(s.prefab.params)),null!=s.prefab.innerParams){const e=r.slice(t+1);for(const t of s.prefab.innerParams){const a=Va(t.params);0!==Object.keys(a).length&&(n?c.push({path:za(t.path,e)?t.path.slice(e.length):t.path,params:a}):za(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)}canObjectBeInstanced(e){return e.physics?.type!==Ae.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=>{!ot(e)&&e.isMesh&&s.push(e)});const r=1==s.length&&0==s[0].children.length,i=!ia,n=s.every(e=>!Array.isArray(e.material)||1===e.material.length),o=s.some(e=>e instanceof m&&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,la.clear(),ca.clear();const e=[],t=new Qe,a=new Qe,s=new Qe;let r=0,n=0,o=0;const u=new Map,d=new He(()=>new Map),p="webgpu"===this.renderingView?.requestedBackend?new h:null,g=null!=p?new h:null;null!=p&&(p.name="Hology WebGPU static scene objects",g.name="Hology WebGPU unsorted late static scene objects");const y=(e,t)=>{if(null!=p&&function(e){return e.visible&&null!=e.geometry.index&&null==e.customDepthMaterial&&va(e.material,!0)}(t)){((Array.isArray(t.material)?t.material:[t.material]).some(e=>e.transparent||Ma(e))?g:p).add(e)}else this.scene.add(e)};for(const i of this.dataProvider.getObjects())await Pa(i,async(i,c,h)=>{if(!this.shouldBeMaterialized(i))return;const p="asset_mesh"==i.type&&this.canObjectBeInstanced(i)&&await this.canAssetBeInstanced(i),f="shape_mesh"===i.type&&"landscape"!==i.shape&&i.physics?.type!==Ae.dynamic;if(p||f){if(c&&c.children?.length>0){const e=c.children.findIndex(e=>e.id===i.id);e>=0&&c.children.splice(e,1)}if(f){let e=i.shape+JSON.stringify(i.shapeParams??{})+i.castShadow+i.receiveShadow;const t=i.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===bt.Color&&null!=e.value&&(r=new l(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:{...i,parentTransform:h},color:r}),o++}else{const e=this.assets.get(i.assetId);null==e&&console.log("Can't find asset with id "+i.assetId);let s=u.get(i.assetId);if(null==s){const e=await this.createFromAsset(i,{assignMaterials:!1});if(null==e)return;if(s=u.get(i.assetId),null==s){s={useBatchedMesh:null!=tt(e)&&qt(e,e=>!(e instanceof m)||this.testCanBatch(e.material,e.geometry)),assetMesh:e},u.set(i.assetId,s)}}const o=Ua(i.materialAssignments,e.materialAssignments);if(s.useBatchedMesh)await st(s.assetMesh,async t=>{if(!(t instanceof m))return;const s=Array.isArray(t.material)?t.material[0]:t.material,n=await this.resolveMaterialForAssignments(s,o,e);if(null!=n){Ee(n,!1),d.get(i.id).set(t.uuid,n);let s=Za(t,n);if(s+=is(n),"webgpu"===this.renderingView?.requestedBackend){s+=`|castShadow:${i.castShadow??e.castShadow??!1?1:0}|receiveShadow:${i.receiveShadow??e.receiveShadow??!1?1:0}`}a.push(s,{...i,parentTransform:h,meshUUID:t.uuid}),r++}else console.warn("Can not materialize mesh because missing material",i)});else{const e=i.assetId+JSON.stringify(i.materialAssignments??[]);t.push(e,{...i,parentTransform:h}),n++}}}else null==c&&e.push({...i,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 ${n} objects.\n Shapes: ${s.size} batch groups containing in total ${o} 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;u.get(t[0].assetId).assetMesh;e=this.createBatchedMesh(t,d,u);const a=this.assets.get(t[0].assetId);"webgl"===this.renderingView?.activeBackend?(e instanceof _t&&e.perInstanceCastShadow||(e.castShadow=Gs(t,a?.castShadow??!1)),e.receiveShadow=Ls(t,a?.receiveShadow??!1)):(e.castShadow=!0,e.receiveShadow=!0);const s=new rt;s.add(e),s.userData.src=t[0],s.castShadow=!1,s.receiveShadow=!1,y(s,e)}for(const e of t.values()){if(0==e.length)continue;let t;const a=u.get(e[0].assetId).assetMesh;t=await this.createInstancedMesh(e,a);const s=this.assets.get(e[0].assetId);t.castShadow=Gs(e,s?.castShadow??!1),t.receiveShadow=Ls(e,s?.receiveShadow??!1);const r=new rt;r.add(t),r.userData.src=e[0],a instanceof rt&&(r.collisionShapes=a.collisionShapes),this.prepareCollisionShapesForInstanced(r),r.castShadow=!1,r.receiveShadow=!1,y(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=at(a,e=>!ot(e)&&null!=e.geometry),r=qa(s.material);null!=e[0].color&&null!=r.color&&(r.color=new l(16777215));const n=null==s.geometry.index?Jt.mergeVertices(s.geometry):s.geometry;let o,u;!(ia||r instanceof R)?(o=new i.BatchedMesh(e.length,n.getAttribute("position").count,n.index.count,r),o.perObjectFrustumCulled=!0,u=o.addGeometry(n)):o=new i.InstancedMesh(n,r,e.length),o.castShadow=a.castShadow??!0,o.receiveShadow=s.receiveShadow??!1;for(let t=0;t<e.length;t++){const a=e[t],s=(new i.Matrix4).compose((new I).fromArray(a.object.position),(new M).setFromEuler((new c).fromArray(a.object.rotation)),(new I).fromArray(a.object.scale)),r=(new f).copy(a.object.parentTransform).multiply(s);let n;n=o instanceof i.BatchedMesh?o.addInstance(u):t,o.setMatrixAt(n,r),a.color}for(let t=0;t<e.length;t++){const s=e[t],r=new rt;r.userData.src=e[0],a instanceof ct&&(r.collisionShapes=[a.collisionShape]),r.castShadow=!0,r.receiveShadow=!0,y(r,o),r.add(o),null==o.userData.hasCollision&&(o.userData.hasCollision=[]),o.userData.hasCollision[t]=!1!==s.object.collisionDetection}}if(null!=p&&p.children.length>0&&(ga(p),this.scene.add(p),this.experimentalStaticDrawSetDisposer=this.renderingView.registerExperimentalStaticDrawSet(p,"hology-materialized-static-scene")),null!=g&&g.children.length>0){ga(g),this.scene.add(g);const e=this.experimentalStaticDrawSetDisposer,t=this.renderingView.registerExperimentalStaticDrawSet(g,"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)}generateOcclusionClusters(){const e=new Tt;e.initScene(this.scene),e.clusters.forEach(e=>{this.renderingView.addCluster(e)})}prepareCollisionShapesForInstanced(e){e instanceof rt&&e.collisionShapes.forEach(e=>{e instanceof a&&e.mesh instanceof m&&(e.mesh=e.mesh.geometry)})}setScene(e){this.scene=e}testCanBatch(e,t){return!ia&&(!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 Qe;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,n=0,o=0;const c=new Map;for(const[e,t]of s.entries()){const s=t[0].assetId,i=a.get(s);if(null==i){console.warn("Missing batching info for asset id "+s);continue}const l=at(i.assetMesh,t=>t instanceof m&&t.uuid===e);if(null==l){console.warn("Missing mesh in batched asset");continue}c.set(e,l);const u=l.geometry.getAttribute("position");null==u&&console.warn("Missing position attribute for batched mesh"),r+=l.geometry.index.count*t.length,n+=u.count*t.length,o+=t.length}const u=["color","map","roughness","roughnessMap","metalness","metalnessMap","opacity","alphaMap","aoMap","aoMapIntensity","normalMap","normalScale","emissive","emissiveIntensity","emissiveMap"],d=new Map,h=new Map,p=[];let f=new i.MeshStandardMaterial({color:"white"});const g=t.get(e[0].id).get(e[0].meshUUID);if(null==g)throw"missing source material";if(g instanceof S&&!(g instanceof i.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 u){let r=e[t];r instanceof i.CompressedArrayTexture&&null!=r.userData.index&&(r=r.userData.index);const n=s.get(t);void 0===n||As(r,n)?s.set(t,r):a.add(t)}}for(const e of a){let t;const a=g[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:k(t)},p.push(a)}else a.params.push(e);s=a.name,t=vs(a.node,a.params.length-1)}else if(a instanceof P)t=k(s);else if(a instanceof I||a instanceof l)t=C(s);else if(a instanceof j)t=E(s);else if(a instanceof i.CompressedArrayTexture)s=e+"_i",t=O(s);else if(a instanceof x)continue;d.set(e,t),h.set(e,s)}let r=re.uv;g instanceof Gt&&null!=g.heightMap&&(r=Lt(r,Q(g.heightMap),N(g.heightScale)));let n=ys(d.get("opacity"),U)??N(g.opacity??1);if(null!=g.alphaMap){let e;if(g.alphaMap instanceof i.CompressedArrayTexture){const t=H(g.alphaMap),a=ys(d.get("alphaMap"),U)??N(g.alphaMap.userData.index??0);e=t.sample(le(r.x,r.y,a))}else e=Q(g.alphaMap).sample(r);n=n.multiply(e.r)}let o=G(ys(d.get("color"),ce)??g.color,n);if(null!=g.map){let e;if(g.map instanceof i.CompressedArrayTexture){const t=H(g.map),a=ys(d.get("map"),U)??N(g.map.userData.index??0);e=t.sample(le(r.x,r.y,a))}else e=Q(g.map).sample(Xt(r,g.map));o=o.multiply(e),n=n.multiply(e.a)}g.vertexColors&&(o=o.multiply(ue(se(D.color.rgb),1)));let c=G(ys(d.get("emissive"),ce)??g.emissive,n);if(null!=g.emissiveMap){let e;if(g.emissiveMap instanceof i.CompressedArrayTexture){const t=H(g.emissiveMap),a=ys(d.get("emissiveMap"),U)??N(g.emissiveMap.userData.index??0);e=t.sample(le(r.x,r.y,a))}else e=Q(g.emissiveMap).sample(Xt(r,g.emissiveMap));c=c.multiply(e)}const m=ys(d.get("emissiveIntensity"),U)??N(g.emissiveIntensity??1),y=ys(d.get("normalScale"),oe)??ne(g.normalScale??new j(1,1));let S=ie.normal;if(null!=g.normalMap){let e;if(g.normalMap instanceof i.CompressedArrayTexture){const t=H(g.normalMap),a=ys(d.get("normalMap"),U)??N(g.normalMap.userData.index??0);e=t.sample(le(r.x,r.y,a))}else e=Q(g.normalMap).sample(Xt(r,g.normalMap));S=z(e.rgb,y.x)}let w=ys(d.get("roughness"),U)??N(g.roughness??1);if(null!=g.roughnessMap){let e;if(g.roughnessMap instanceof i.CompressedArrayTexture){const t=H(g.roughnessMap),a=ys(d.get("roughnessMap"),U)??N(g.roughnessMap.userData.index??0);e=t.sample(le(r.x,r.y,a))}else e=Q(g.roughnessMap).sample(Xt(r,g.roughnessMap));w=w.multiply(e.g)}let b=ys(d.get("metalness"),U)??N(g.metalness??0);if(null!=g.metalnessMap){let e;if(g.metalnessMap instanceof i.CompressedArrayTexture){const t=H(g.metalnessMap),a=ys(d.get("metalnessMap"),U)??N(g.metalnessMap.userData.index??0);e=t.sample(le(r.x,r.y,a))}else e=Q(g.metalnessMap).sample(Xt(r,g.metalnessMap));b=b.multiply(e.b)}let v=N(1);if(null!=g.aoMap){let e;if(g.aoMap instanceof i.CompressedArrayTexture){const t=H(g.aoMap),a=ys(d.get("aoMap"),U)??N(g.aoMap.userData.index??0);e=t.sample(le(r.x,r.y,a))}else e=Q(g.aoMap).sample(Xt(r,g.aoMap));v=v.multiply(e.r)}const M=ys(d.get("aoMapIntensity"),U)??N(g.aoMapIntensity??0);let A=S;!0!==g.userData.disableAO&&(A=F("DOUBLE_SIDED",A,e=>q(new B("gl_FrontFacing"),e,e.multiplyScalar(-1))));const T=new R({color:J({color:o,roughness:w,metalness:b,ambientOcclusion:v,ambientOcclusionIntensity:M,emissive:c,emissiveIntensity:m,normal:A}),normal:S,roughness:w,emissive:c.rgb,transparent:g.transparent,alphaTest:g.alphaTest,envMap:g.envMap,opacity:n});null!=g.envMap&&(T.uniforms.envMapIntensity={value:g.envMapIntensity},T.uniforms.envMapRotation={value:bs(g.envMapRotation,g.envMap)}),T.envMap=g.envMap,T.side=g.side,f=T}else if(g instanceof R){const a=new Set,s=new Map,r=Object.keys(g.uniforms).filter(e=>!ls(e));for(const i of e){const e=t.get(i.id).get(i.meshUUID);if(!(e instanceof R))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||As(r,i)?s.set(t,r):us(r)&&us(i)&&ds(r)===ds(i)&&a.add(t)}}const i=new Set(Object.keys(g.uniforms)),n={};for(const e of a){let t,a;const s=g.uniforms[e]?.value;if("number"==typeof s){let s=p.find(e=>e.params.length<4);if(null==s){const t=hs("vp"+p.length,i);s={name:t,params:[e],node:k(t)},p.push(s)}else s.params.push(e);a=s.name,t=vs(s.node,s.params.length-1)}else if(s instanceof P)a=hs(e,i),t=k(a);else if(s instanceof I||s instanceof l)a=hs(e,i),t=C(a);else{if(!(s instanceof j))continue;a=hs(e,i),t=E(a)}d.set(e,t),h.set(e,a),n[e]=t}if(0===d.size)f=g;else{const e=$(g,{color:g.outputColor,transform:g.outputTransform??null,position:null==g.outputTransform?g.outputPosition:void 0,normal:g.outputNormal??null,roughness:g.outputRoughness??null,opacity:g.outputOpacity??null,emissive:g.outputEmissive??null,uniforms:ps(g,new Set(d.keys())),uniformNodes:n});e.uniformNodes=n,y=g,(w=e).name=y.name,w.side=y.side,w.blending=y.blending,w.depthWrite=y.depthWrite,w.depthTest=y.depthTest,w.colorWrite=y.colorWrite,w.toneMapped=y.toneMapped,w.visible=y.visible,w.opacity=y.opacity,w.forceSinglePass=y.forceSinglePass,w.premultipliedAlpha=y.premultipliedAlpha,w.polygonOffset=y.polygonOffset,w.polygonOffsetFactor=y.polygonOffsetFactor,w.polygonOffsetUnits=y.polygonOffsetUnits,w.shadowSide=y.shadowSide,Object.assign(w.defines,y.defines),Object.assign(w.userData,y.userData),w.needsUpdate=!0,f=e}}else{f=g;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:g});break}}}var y,w;const b=new _t(o,n,r,f);for(const e of p)b.initUniform(e.name,4);for(const[e,t]of d.entries()){if(p.some(t=>t.params.includes(e)))continue;let a=1;t instanceof de||t instanceof ce?a=4:t instanceof oe&&(a=2),b.initUniform(h.get(e)??e,a,0)}for(const[e,r]of s.entries()){const s=r[0].assetId,n=c.get(e);if(null==n){console.error(`Missing single asset mesh for mesh uuid ${e} and asset id ${s}`);continue}if(null==n.geometry){console.error("Missing geometry on mesh mesh");continue}const o=b.addGeometry(Xa(n.geometry,g)),u=this.assets.get(s),f=a.get(s);if(null==f){console.warn("Missing batching info when configuring for asset id "+s);continue}const m=tt(f.assetMesh)?.uuid===e,y=f.assetMesh instanceof rt&&m?f.assetMesh.collisionShapes:void 0,S=this.configureBatchedInstancedMesh(r,b,n,o,y);for(let e=0;e<S.length;e++){const a=r[e],s=S[e];"webgpu"!==this.renderingView?.requestedBackend&&b.setCastShadowAt(s,a.castShadow??u?.castShadow??!1);const n=t.get(a.id).get(a.meshUUID),o=n.userData.surface;null!=o&&(b.surfaceByInstance[s]=o);for(const e of p){let t=Ms.set(0,0,0,0);for(let a=0;a<e.params.length;a++){const s=cs(n,e.params[a]);"number"==typeof s&&t.setComponent(a,s)}b.setUniformAt(e.name,s,t)}for(let e of d.keys()){if(p.some(t=>t.params.includes(e)))continue;const t=h.get(e)??e;let a=cs(n,e);if(a instanceof l&&(a=new I(a.r,a.g,a.b)),a instanceof i.CompressedArrayTexture)a=a.userData.index??0;else if(a instanceof x||null==a)continue;b.setUniformAt(t,s,a)}}}return b}async createInstancedMesh(e,t){const a=at(t,e=>!ot(e)&&null!=e.geometry),s=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,Ua(e[0].materialAssignments,s.materialAssignments),s),a.updateMatrix();const r=a.geometry.clone(),n=a.material;let o;if(o=new i.InstancedMesh(r,n,e.length),this.configureBatchedInstancedMesh(e,o,a),a.material instanceof p&&o.castShadow&&o.receiveShadow&&Array.isArray(n))for(const e of n);return o}configureBatchedInstancedMesh(e,t,a,s,r){const n=[];a.updateWorldMatrix(!0,!0);for(let o=0;o<e.length;o++){let l=o;t instanceof i.BatchedMesh&&(l=t.addInstance(s)),n.push(l);const u=(new i.Matrix4).compose((new I).fromArray(e[o].position),(new M).setFromEuler((new c).fromArray(e[o].rotation)),(new I).fromArray(e[o].scale)),d=(new f).copy(e[o].parentTransform).multiply(u),h=(new f).copy(d).multiply(a.matrixWorld);t.setMatrixAt(l,h),null==t.userData.hasCollision&&(t.userData.hasCollision=[]);const p=this.assets.get(e[o].assetId);t.userData.hasCollision[l]=!1!==e[o].collisionDetection||!1!==p?.collisionDetection,null!=r&&(null==t.userData.collisionShapes&&(t.userData.collisionShapes=[]),t.userData.collisionShapes[l]=r,null==t.userData.collisionMatrices&&(t.userData.collisionMatrices=[]),t.userData.collisionMatrices[l]=d)}return n}remove(e){if(console.log("Remove scene object",e),"global_fog"==e.type)return void(this.scene.fog=this.originalFog);if("world_env"===e.type)this.resetWorldEnv(),this.worldEnvObj=null;else if("actor"==e.type||"vfx"===e.type){const t=this.materializedActors.get(e.id);null!=t?(t.disposed.next(!0),t.onEndPlay()):console.warn("Failed to remove actor",e)}else 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?.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 et(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(!_a(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=La(a,n)),null!=a&&s.id!==a.id&&(r=r??Ra(s),i=i??s.name,s=a);break}return s}unapplyMaterials(e){e.traverse(async e=>{if(e instanceof m)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(ve));et(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,et(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 la.entries())t.userData.customShaderName&&la.delete(e);ca.clear(),this.landscapeManagers.forEach(t=>t.updateShaders(e)),et(this.scene,e=>!0).forEach(e=>{e.traverse(async e=>{if(e instanceof m)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 m&&(e.material.wireframe=!0)}):t.traverse(e=>{e instanceof m&&(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){const a=this.assets.get(e.assetId);Ua(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!==Ae.dynamic?wa(t,!1):this.inEditor&&function(e){let t=!1;if(e.traverse(e=>{Sa.has(e)&&(t=!0)}),!t)return;e.updateWorldMatrix(!0,!0),e.traverse(e=>{Sa.has(e)&&(e.matrixWorldNeedsUpdate=!1)})}(t)),this.applyVertexMaterials(e,t),"light"==e.type){if("point"==e.light.type){const a=t;a.color=new l(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 l(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 l(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 Yt&&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 d?"density":"linear")!==e.fog.type;this.scene.fog=Aa(e.fog),t&&(a=this.scene).traverse(e=>{if(e instanceof m){const t=e.material;t instanceof R&&(a.fog instanceof u?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof d&&(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 Ft){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 ct&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}if("shape_mesh"===e.type&&"landscape"!==e.shape)oa(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;oa(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=Ea(e.prefab?.objects??[]),r=Ea(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)??ka(o,n.source,e.prefab?.mainActorId===a),u=ka(o,n.source,e.prefab?.mainActorId===a),d=Ta(u,ka(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=Ca(e.prefab?.objects??[]),i=Ca(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=Ea(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=ka(i,t,n.prefab.mainActorId===e),u=ka(i,r,n.prefab.mainActorId===e),d=c.desiredActorSettingsById.get(e)??l,h=Ta(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 Me))return null;a=t}return a instanceof Me?a:null}findParent(e){const t=this.dataProvider.getObjects().flatMap(t=>t.id===e.id?null:Ke(t,t=>t.children?.some(t=>t.id===e.id),()=>!0))[0];return null==t?this.scene:null!=t?et(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 l(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse(e=>{e instanceof m&&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=Ze(e.vertexMaterials,e=>e.m);t.traverse(e=>{if(e instanceof m){if(null==e.geometry)return;if(Ha(gt(e,0,!1)),a>0){Ha(gt(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=gt(s,0,!0);Ha(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=gt(s,4,!0);Ha(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),i=function(e){if(null==e)return e;e.updateWorldMatrix(!0,!0);const t=[];e.traverse(e=>{e.isSkinnedMesh&&t.push(e)});let a=e;for(const e of t){const t=Ws(e),s=e.parent;if(null==s){a=t;continue}const r=s.children.indexOf(e);e.removeFromParent(),s.add(t);const i=s.children.indexOf(t);r>=0&&i>=0&&i!==r&&(s.children.splice(i,1),s.children.splice(r,0,t))}return function(e){const t=[];e.traverse(e=>{e.isBone&&t.push(e)});for(const e of t)null!=e.parent&&!e.parent.isBone&&_s(e)&&e.removeFromParent()}(a),a}(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=Aa(e.fog),this.fixFogColor(),i=new h;break;case"sky":this.sky=Dt(),this.updateSky(e),i=this.sky;break;case"world_env":this.updateWorldEnv(e),i=new h,this.worldEnvObj=i;break;case"actor":({object:i,actor:n}=await this.createFromActor(e,s));break;case"group":case"scatter":i=new h;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!==Ae.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(xa),i.getWorldQuaternion(ja),i.getWorldScale(Ia),this.scene.add(i),i.position.copy(xa),i.quaternion.copy(ja),i.scale.copy(Ia)),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!==Ae.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)?wa(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==Ae.dynamic||ga(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 yt(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 St(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(i.NoToneMapping,1)}async updateSky(e){null!=this.sky&&(null==e?.sky?.materialId&&this.sky.material!==Ot?(this.sky.material=Ot,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=i.BackSide,(e instanceof S||e instanceof i.MeshBasicMaterial||e instanceof i.ShaderMaterial)&&(e.fog=!1),e.depthTest=!0,e.depthWrite=!1,e.transparent=!0}async createComponent(e,t,a,s){const r=new sa[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??ve[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 I).fromArray(e.position),(new c).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===xe.none)return;const t=be(e.constructor);!0!==t?.replicate?this.netMode===xe.client&&(e.netRole=je.none):e.netRole=this.netMode===xe.client?je.simulatedProxy:je.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(pe,(new I).fromArray(e.position),(new c).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 m&&this._originalMaterials.set(e.id,e.material)});else{let s=new S({name:"Default",color:new l("#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 h;const a=dt(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new ut(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 ht(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(()=>pt(r),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&It.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);if(!this.geometryCache.has(r)){const t=jt[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,jt[e].collision(s));return new ct(this.geometryCache.get(r),t,this.collisionShapeCache.get(r))}if(this.inEditor)throw new Error(`Unsupported shape '${e}'`);console.warn(`Failed to create shape. Unsupported shape '${e}'. This might be because the hology/core library is not compatible with the editor version.`)}async createFromAsset(e,t){const a=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(!1!==t?.assignMaterials)try{await Promise.all(Ua(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;return s.receiveShadow=r,oa(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 m&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()}),s.userData.assetId=e.assetId,s.traverse(e=>{if(e instanceof m)for(const t of Xe(e.material))Ee(t,!1)}),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 h;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([...Ea(e.prefab?.objects??[])].map(([t,a])=>[t,ka(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&&ta(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 b}async createLight(e){if("point"===e.light.type){const t=new v(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 i.TextureLoader).load("assets/light-bulb-icon.webp"),a=new i.SpriteMaterial({map:e,alphaTest:.5}),s=new Wt(a);s.scale.multiplyScalar(.6),t.add(s)}return t}if("spot"===e.light.type){const t=new i.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 b,t.target.position.set(0,-1,0),t.add(t.target),this.inEditor){const e=(new i.TextureLoader).load("assets/light-bulb-icon.webp"),a=new i.SpriteMaterial({map:e,alphaTest:.5}),s=new Wt(a);s.scale.multiplyScalar(.6),t.add(s),t.add(new i.SpotLightHelper(t))}return t}if("rectArea"===e.light.type){const t=new i.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 i.TextureLoader).load("assets/light-bulb-icon.webp"),a=new i.SpriteMaterial({map:e,alphaTest:.5}),s=new Wt(a);s.scale.multiplyScalar(.6),t.add(s);const r=new Yt(t);t.add(r)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional,e),new h):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient,e),new h):void 0}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===Pt);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.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(i.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}};na=e([he(),t("design:paramtypes",[A,Object,nt,it,De,Array,Array,Object,Array])],na);export{na as SceneMaterializer};function oa(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse(e=>{e.castShadow=t,e.receiveShadow=a})}const la=new Map,ca=new Map,ua=new g({color:16711935}),da=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),ua;const n=JSON.stringify(e.material)+t?._id,o=i&&!("shaderGraph"===e.material.type&&"asset"===e.material.shaderGraph?.source);if(o&&la.has(n))return la.get(n);if(o&&ca.has(n))return await ca.get(n);const l=_materialFromAsset(n,e,t,a,s,r,o);return o?ca.set(n,l).get(n):l}export async function _materialFromAsset(e,t,a,r,n,o,c=!0){const u={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 l(t.material.params?.color),transparent:null!=t.material.params?.opacity&&t.material.params?.opacity<1},d={};if(null!=t.material.params?.map){const e=t.material.params.map,a=await r.getAsset(e);null!=a&&(u.map=await n.getTexture(a))}let h,p,f;switch(t.material.type){case"phong":h=new y({...u,...d});break;case"water":h=wt(u,a);break;case"grassFoliage":h=ft({color:u.color,map:u.map},a);break;case"grass":h=mt({...u,colorTwo:new l(t.material.params.colorTwo),colorThree:new l(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,r);if(null==e){console.warn("Missing shader graph for material "+t.name),h=ua;break}"surface"===e.target&&null!=e.materialOptions?.side&&(p=ea(e.materialOptions.side)),"decal"===e.target?f=!1:null!=e.materialOptions?.transparent&&(f=e.materialOptions.transparent);try{const s=await prepareShaderGraphParameters(t.material?.shaderParams??{},e,r,n,a,o),i=t.shaderGraphPreviewNodeId,l=t.trailBillboard;h=Kt(e,{parameters:s,previewNodeId:i,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=ua}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:ra?Ve:$e,lambert:Ve,unlit:Ue,toon:Rt,layered:$t,landscape:Ne,"landscape-composite":ze,"decal-unlit":Ct,"decal-standard":kt,sprite:s}[t.material.type]??o.find(e=>e.name==t.material.shader)?.type;if(e){try{let s=new e;const i=await prepareClassParameters(t.material?.shaderParams??{},e,r,n,null,a,o,void 0,void 0,s);Object.assign(s,i),s.alphaTest=t.material.alphaTest??s.alphaTest,h=s.build()}catch(e){console.log("Shader runtime error: "+e,e),da.has(t.material.shader)||da.set(t.material.shader,ua.clone()),h=da.get(t.material.shader)}h.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),h=ua;break;default:throw new Error("Unsupported material type "+t.material.type)}if(a?.csm.setupMaterial(h),h.side=p??t.material.side??h.side??i.FrontSide,h.transparent=(f??t.material.transparent??u.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=Ie[t.material.blending]??i.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 l(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,r,n,void 0,a,o);null!=e&&(h.userData.surface=e.value)}return h.userData.assetId=t.id,c&&null!=a&&la.set(e,h),c&&ca.delete(e),h}export function prepareCustomParamsFromShaderGraph(e,t={}){return Object.fromEntries((e.parameters??[]).map(e=>{const a=function(e){switch(e){case"float":return bt.FloatNode;case"boolean":return bt.BooleanNode;case"texture":return bt.Sampler2DNode;case"vec2":return bt.Vec2Node;case"vec3":return bt.Vec3Node;case"vec4":return bt.Vec4Node;case"color":return bt.RgbNode}}(e.type),s=t[e.name],r=s?.override??null!=s,i=void 0!==e.defaultValue?e.defaultValue:customParameterDefaultValueByType.get(a),n=!1===r?$a(i):s?.value??$a(i);return[e.name,{type:a,value:n,override:r}]}))}export async function prepareShaderGraphParameters(e,t,a,s,r,i){const n={},o=prepareCustomParamsFromShaderGraph(t,e);for(const[e,t]of Object.entries(o)){const o=await pa(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}=Mt(e,{parameterType:t,parameterTarget:c,extractPropertyParameters:Fe,toSerializedParamType:toSerializedParamType});for(const e of h)console.warn(`Skipping stored parameter "${e.key}" because it could not be converted from ${bt[e.sourceType]} to ${bt[e.targetType]}`);for(const[e,t]of Object.entries(d)){if(!1===t.override)continue;const c=await pa(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 pa(r,i,t,a,null,void 0,void 0,void 0,void 0,void 0);null!=e&&(s[r]=e)}return s}const ha=new Map;async function pa(e,t,a,s,r,i,n,o,u=t.value,d=t.type,h,p=(t.type===bt.Struct?t.struct:void 0)){if(null==t||null==u||""===u)return null;switch(d){case bt.Array:if(Array.isArray(u)&&"element"in t)return await Promise.all(u.map(l=>pa(e,t,a,s,r,i,n,o,l,t.element,h,t.elementStruct)));break;case bt.Number:case bt.FloatNode:let f;if("string"==typeof u?f=parseFloat(u):"number"==typeof u&&(f=u),d===bt.FloatNode){if("object"==typeof u&&"a"in u&&"b"in u){const e=u;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=ha.get(e);return null==t&&(t=Ce(Et.decode(e)),ha.set(e,t)),t}(e.easing),r=s.sample(ke(Te.energy));return W(N(t),N(a),r)}return new X(Ye(e),f,void 0,!1)}return f;case bt.Texture:let m=await s.getTexture(await a.getAsset(u));return"envmap"===e.toLowerCase()&&null!=i&&(m=i.getEnvTexture(m)),m;case bt.Sampler2DNode:const g=await a.getAsset(u);if(null!=g?.texture?.textureArrayFileKey){const{texture:t,layerIndex:a}=await s.getTextureArray(g);if(t&&null!=a)return new K(null,t,new X(Ye(e)+"_i",a,void 0,!1))}const y=await s.getTexture(g);return y?Q(y):null;case bt.Boolean:return u;case bt.BooleanNode:return new Z(Ye(e),u,void 0,!1);case bt.Vector2:case bt.Vec2Node:if("object"==typeof u){const t=u instanceof Array?(new j).fromArray(u):new j(u.x,u.y);return d===bt.Vec2Node?new ee(Ye(e),t,void 0,!1):t}return null;case bt.Vector3:case bt.Vec3Node:if("object"==typeof u){const t=u instanceof Array?(new I).fromArray(u):new I(u.x,u.y,u.z);return d===bt.Vec3Node?new te(Ye(e),t,void 0,!1):t}return null;case bt.Vector4:case bt.Vec4Node:if("object"==typeof u){const t=u instanceof Array?(new P).fromArray(u):new P(u.x,u.y,u.z,u.w);return d===bt.Vec4Node?new ae(Ye(e),t,void 0,!1):t}return null;case bt.Color:case bt.RgbNode:const S=new l(u);return d===bt.RgbNode?new te(Ye(e),new I(S.r,S.g,S.b),void 0,!1).rgb:S;case bt.String:return u;case bt.Scene:return"string"==typeof u?new Se(u):"object"==typeof u&&null!=u&&"string"==typeof u.id?new Se(u.id,"string"==typeof u.name?u.name:void 0):null;case bt.BaseActor:const w=u;if(null==r&&console.warn("Class parameters can not be prepared as actors are not passed in"),null==w)return null;if("object"==typeof w&&null!=w.type&&null!=w.id){if("actor"===w.type)return r?.get(w.id)??null;if("prefab"===w.type){const e=h?h(w.id):null;if(null!=e)return r?.get(e)??null;const t=[];for(const[e,a]of r?.entries()??[])e.startsWith(w.id+"/")&&t.push(a);return 1===t.length?t[0]:null}}if("string"==typeof w){const e=r?.get(w);if(null!=e)return e;const t=h?h(w):null;if(null!=t)return r?.get(t)??null;const a=[];for(const[e,t]of r?.entries()??[])e.startsWith(w+"/")&&a.push(t);return 1===a.length?a[0]:null}return null;case bt.Euler:const b=u;return(new c).fromArray(b);case bt.Object3D:{const e=await a.getAsset(u),t=(await s.getMesh(e,{applyMaterials:!0,rescale:!0,mergeGeomtries:!0})).scene;return t.userData.vfxIncludeRootTransform=!0,t}case bt.Material:{if(null==u)return null;const e=await a.getAsset(u);if(null==e)return console.warn("Material asset not found for material parameter",u),null;if("shaderGraph"===e.type&&null!=e.shaderGraph){const t=`shaderGraphParameter:${e.id}:${JSON.stringify(e.shaderGraph)}:${i?._id??"none"}`,r=la.get(t);if(null!=r)return r;const o=await prepareShaderGraphParameters({},e.shaderGraph,a,s,i,n),l=Kt(e.shaderGraph,{parameters:o});return l.userData.assetId=e.id,la.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 bt.AudioBuffer:return await s.getAudio(await a.getAsset(u));case bt.VisualEffect:const v=await a.getAsset(u);if(null==o){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in v)return new fe(o,v);console.error("Using a non-vfx asset for visual effect parameter");break;case bt.Prefab:{const e=await a.getAsset(u);return null==e?(console.error("Using a non-prefab asset for prefab parameter",u),null):new me(e)}case bt.PrefabActor:{const e=await a.getAsset(u);return null==e?(console.error("Using a non-prefab asset for prefab parameter",u),null):new ge(new me(e))}case bt.DataAsset:return materializeDataAssetRef(u,a,s,r,i,n,o,h);case bt.Sequence:{if("string"!=typeof u)return console.warn("Invalid sequence parameter value",u),null;const e=await a.getAsset(u);if("sequence"===e?.type&&"sequence"in e)return new Zt(e.sequence);console.error("Using a non-sequence asset for sequence parameter");break}case bt.SequenceData:return Ht(u)?u:(console.warn("Invalid inline sequence data parameter value",u),null);case bt.Struct:return async function(e,t,a,s,r,i,n,o,l){const c=fa(e),u=c?.struct??t;if(null==u)return console.warn("Missing parameter definition id for struct parameter"),null;const d=_e(u);if(null==d)return console.warn(`Unknown parameter definition "${u}"`),null;if(Le(u))return console.warn(`Can not instantiate abstract parameter definition "${u}"`),null;if(null!=t&&u!==t&&!Je(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=fa(e);if(null!=t)return t.value;if(ma(e))return e;if(null!=e&&"object"==typeof e&&ma(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}(u,p,a,s,r,i,n,o,h);case bt.Curve:return Et.decode(u);case bt.ColorLayer:case bt.MaskLayer:if(Ut(u)){const e=await Bt.decode(u,async e=>await s.getTexture(await a.getAsset(e))),t=await prepareClassParameters(u.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",u),null;case bt.AnimationClip:{const e="string"==typeof u?u:"object"==typeof u&&null!=u?u.assetId:null;if(null==e)return console.warn("Invalid animation clip asset id value",u),null;return await s.getAnimationClip(await a.getAsset(e))}}return null}export async function materializeDataAssetRef(e,t,a,s,r,i,n,o){const l="string"==typeof e?e:null!=e&&"object"==typeof e?e.assetId??e.id:null;if(null==l||""===l)return null;const c=await t.getAsset(l);if(null==c)return console.warn(`Data asset "${l}" was not found`),null;if("data"!==c.type||null==c.dataAsset)return console.warn("Using a non-data asset for data asset parameter",l),null;const u=c.dataAsset.definition;if(null==u||""===u)return console.warn(`Missing data asset definition id for asset "${c.id}"`),null;if(Ge(u))return console.warn(`Can not instantiate abstract data asset definition "${u}"`),null;const d=We(u);if(null==d)return console.warn(`Unknown data asset definition "${u}"`),null;let h;try{h=new d}catch(e){return console.warn(`Failed to instantiate data asset definition "${u}"`,e),null}const p=c.dataAsset.params??{};if("object"!=typeof p||Array.isArray(p))return console.warn(`Invalid data asset params for asset "${c.id}"`),null;try{const e=await prepareClassParameters(p,null,t,a,s,r,i,n,o,h);Object.assign(h,e)}catch(e){return console.warn(`Failed to materialize data asset "${c.id}"`,e),null}return new ye(c,h)}function fa(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.struct&&ma(e.value)?e:null}function ma(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&Object.values(e).every(e=>null!=e&&"object"==typeof e&&"type"in e)}function ga(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 ya(){}const Sa=new WeakMap;function wa(e,t){if(t)return e.userData.hologyEditorMatrixWorldAutoUpdate=!0,void e.traverse(e=>{const t=Sa.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=>{Sa.has(e)&&s.push(e)}),0!==s.length||a||s.push(e);for(const e of s)ba(e);delete e.userData.hologyEditorMatrixWorldAutoUpdate}function ba(e){const t=Sa.get(e);if(e.updateMatrix(),e.updateWorldMatrix(!0,!0),null==t){const t=new Map;e.traverse(e=>{t.set(e,e.matrixAutoUpdate)}),Sa.set(e,{updateMatrixWorld:e.updateMatrixWorld,matrixAutoUpdate:t})}e.traverse(e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1}),e.updateMatrixWorld=ya}function va(e,t=!1){return Array.isArray(e)?e.every(e=>va(e,t)):t||!e.transparent&&!Ma(e)}function Ma(e){return e instanceof R&&(null!=e.uniforms[aa]||null!=e.uniforms.hology_scene_map)}function Aa(e){return"linear"===e.type?new u(new l(e.color),e.near??100,e.far??1e3):"density"===e.type?new d(e.color,e.density):void console.warn("Invalid fog type",e)}const xa=new I,ja=new M,Ia=new I;new S({color:4229780});async function Pa(e,t,a,s){null==s&&(s=(new f).identity());const r=s.clone().multiply(Da(e,new i.Matrix4));if(null!=e.children&&e.children.length>0)for(let a=e.children.length-1;a>=0;a--)await Pa(e.children[a],t,e,r);await t(e,a,s)}function Da(e,t){return null==e.position||null==e.rotation||null==e.scale?t.identity():t.compose((new I).fromArray(e.position),(new M).setFromEuler((new c).fromArray(e.rotation)),(new I).fromArray(e.scale))}export function toSerializedParamType(e){if(null==e)return;const t=e.constructor.prototype;return t instanceof Number||e===Number?bt.Number:t instanceof U||"function"==typeof e.prototype.isFloat?bt.FloatNode:t instanceof x||e===x||e.isTexture?bt.Texture:t instanceof Be||e===Be||e===Y||"function"==typeof e.prototype?.isSampler2D||!0===e.prototype?.isSampler2D?bt.Sampler2DNode:t instanceof Boolean||e===Boolean?bt.Boolean:t instanceof V?bt.BooleanNode:t instanceof l||e==l?bt.Color:t instanceof L||"function"==typeof e.prototype.isRgb?bt.RgbNode:t instanceof j||e==j?bt.Vector2:t instanceof oe||"function"==typeof e.prototype.isVec2?bt.Vec2Node:t instanceof I||e==I?bt.Vector3:t instanceof ce||"function"==typeof e.prototype.isVec3?bt.Vec3Node:t instanceof P||e==P?bt.Vector4:t instanceof de||"function"==typeof e.prototype.isVec4?bt.Vec4Node:t instanceof String||e===String?bt.String:t instanceof Se||e===Se?bt.Scene:t instanceof we||e==we||e.prototype instanceof we||e.prototype==we?bt.BaseActor:t instanceof c||e==c?bt.Euler:t instanceof b||e==b?bt.Object3D:t instanceof p||e==p?bt.Material:t instanceof AudioBuffer||e==AudioBuffer?bt.AudioBuffer:t instanceof fe||e==fe?bt.VisualEffect:t instanceof me||e==me?bt.Prefab:t instanceof ge||e==ge?bt.PrefabActor:t instanceof ye||e==ye?bt.DataAsset:t instanceof Et||e==Et?bt.Curve:t instanceof Bt||e==Bt?bt.ColorLayer:t instanceof Nt||e==Nt?bt.MaskLayer:t instanceof i.AnimationClip||e==i.AnimationClip?bt.AnimationClip:t instanceof Zt||e==Zt?bt.Sequence:"SequenceData"===e.name||e.prototype&&"tracks"in e.prototype?bt.SequenceData:null!=Re(e)?bt.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===bt.Struct?Re(e.type):void 0;return!0===e.options.array?{type:bt.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=Oa(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 Ht(e)?{type:bt.SequenceData}:void 0}(t);null!=a&&(e=a)}if(e.type!==bt.Struct)return{typeInfo:e,value:t};const a=fa(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===bt.Struct)return Le(e.type)?{}:prepareCustomParamsFromType(e.type,{});return customParameterDefaultValueByType.get(a)}(e,a)),p=function(e,t){if(Oa(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!==bt.SequenceData||!Ht(e))return;return{type:bt.SequenceData,value:e}}(n,h.typeInfo);i=function(e,t,a){if(e.type!==bt.Struct||a?.type!==bt.Struct||null==a.struct)return e;const s=t.struct??e.struct;if(null==s||a.struct===s||Je(a.struct,s)||null==_e(a.struct))return{...e,struct:a.struct};return e}(h.typeInfo,r,p);const f=!1!==u||e.options.array?p?.value??function(e,t,a){if(!0===e.options.array)return a?$a(t):[];return $a(t)}(e,h.value,d):$a(h.value),m=function(e,t,a){if(t.type===bt.Struct){if(null!=t.struct&&Le(t.struct))return a;const s=null!=t.struct?_e(t.struct):e.type;return null!=s&&ma(a)?prepareCustomParamsFromType(s,a):a}if(t.type!==bt.Array||t.element!==bt.Struct||!Array.isArray(a))return a;const s=null!=t.elementStruct?_e(t.elementStruct):e.type;return a.map(e=>{const a=fa(e),r=a?.struct??t.elementStruct;if(null!=r&&Le(r))return e;const i=null!=a?_e(a.struct):s,n=a?.value??(ma(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 Oa(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"number"==typeof e.type&&"value"in e}function Ea(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 Ca(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 ka(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??{},...Va(e.params)}})}return{...e,params:{...e.params??{},...Va(t.prefab.params)},innerParams:[...s.values()]}}function Ta(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=Ba(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:Ba(e.params??{},t.params??{},a.params??{}),innerParams:n}}function Ba(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 Va(e){return null==e?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>function(e){return!0===e?.override}(e)))}function za(e,t){return e.length>=t.length&&t.every((t,a)=>e[a]===t)}export function prepareCustomParamsFromType(e,t,a=null,s={}){const r=Fe(e);if(0===r.length)return{};let i;null!=a?Pe(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=Na(e,t);void 0!==a&&(n[e.name]=a)}}return prepareCustomParams(r,t,n,s)}function Na(e,t){return!0===e.options.array?Array.isArray(t)?t.map(t=>serializeCustomParameter(e.type,t)??t):[]:serializeCustomParameter(e.type,t)}function $a(e){return null==e?e:Array.isArray(e)?e.map(e=>$a(e)):"object"==typeof e?"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e)):e}export function serializeCustomParameter(e,t){function a(){console.error("Failed to serialize value",{type:e,value:t})}switch(e){case Number:case Boolean:return t;case j:return t instanceof j?t.toArray():void a();case I:return t instanceof I?t.toArray():void a();case P:return t instanceof P?t.toArray():void a();case l:return t instanceof l?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new l(t).getHexString():void a();case String:return t;case c:return t instanceof c?t.toArray():void a();case me:return t instanceof me?t.asset?.id??null:void a();case ye:return t instanceof ye?t.id:"string"==typeof t?t:void a();case Se:return t instanceof Se?{id:t.id,...null!=t.name?{name:t.name}:{}}:void a()}const s=Re(e);if(null!=s){const r=fa(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!=Re(a)&&qe(a,e)?a:e}(e,t),n=Re(i),o=function(e,t){if(null==t)return null;if(ma(t))return t;if(null!=t&&"object"==typeof t&&ma(t.params))return t.params;if("object"!=typeof t)return;const a=Fe(e),s={};for(const e of a){const a=t[e.name];if(void 0===a)continue;const r=Na(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(Ht(t))return t}function Ua(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=>Fa(e.materialId)),(t??[]).filter(e=>Fa(e.materialId)),e=>e.name?`name:${e.name}`:`color:${e.color}`)}function Fa(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[bt.RgbNode,"#000000"],[bt.Color,"#000000"],[bt.String,""],[bt.Scene,null],[bt.Vector4,[0,0,0,0]],[bt.Vec4Node,[0,0,0,0]],[bt.Vector3,[0,0,0]],[bt.Vec3Node,[0,0,0]],[bt.Vector2,[0,0]],[bt.Vec2Node,[0,0]],[bt.Euler,[0,0,0,"XYZ"]],[bt.Array,[]],[bt.DataAsset,null],[bt.SequenceData,Qt()],[bt.ColorLayer,Vt],[bt.MaskLayer,zt]]);let Wa=new l;new l;function Ra(e){return null==e?.color?null:(Wa.set(e.color),"#"+Wa.getHexString())}function _a(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=Ra(e);return null!=i&&(i===t.color||a===t.color)}export function applyMaterial(e,t,a,s,r={}){const n=[];return e.traverse(async e=>{if(e instanceof m||e.isMesh||e instanceof i.SkinnedMesh||e.isSkinnedMesh)for(const t of Xe(e.material))t.hasOwnProperty("color")&&n.push(e)}),Promise.all(n.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 l))continue;const o=Ra(n),c=n.name;if(_a(n,t,e.userData["originalColor_"+i],e.userData["originalMaterialName_"+i])){const n=La(await a(t.materialId),r.textureFlipY),l=e.material[i];null!=n&&l.id!=n.id&&(e.material[i]=n,e.userData["originalColor_"+i]=e.userData["originalColor_"+i]??o,e.userData["originalMaterialName_"+i]=e.userData["originalMaterialName_"+i]??c,null!=s&&s.set(e.id+"#"+i,l))}}else if("color"in e.material){const i=e.material,n=Ra(i),o=i.name;if(_a(i,t,e.userData.originalColor,e.userData.originalMaterialName)){const i=La(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 Ga=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 La(e,t){if(null==e||null==t||!function(e,t){return function(e){const t=[];for(const[a,s]of Object.entries(e))Ja(a,s)&&t.push(s);if(e instanceof i.ShaderMaterial)for(const[a,s]of Object.entries(e.uniforms))Ja(a,s.value)&&t.push(s.value);return t}(e).some(e=>e.flipY!==t)}(e,t))return e;let a=Ga.get(e);null==a&&(a=new Map,Ga.set(e,a));const s=a.get(t);if(null!=s)return s;const r=qa(e);if(function(e,t){for(const a of Object.keys(e)){const s=e[a];Ja(a,s)&&(e[a]=Ya(s,t))}}(r,t),r instanceof i.ShaderMaterial){for(const[e,a]of Object.entries(r.uniforms))Ja(e,a.value)&&(a.value=Ya(a.value,t));r.uniformsNeedUpdate=!0}return r.needsUpdate=!0,a.set(t,r),r}function qa(e){const t=e.clone();return t.userData={...e.userData??{}},t}function Ja(e,t){const a=t;return(t instanceof x||!0===a?.isTexture)&&!e.toLowerCase().includes("envmap")&&!0!==a.isCompressedTexture&&!0!==a.isCompressedArrayTexture}function Ya(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 Qa(e,t){if(e instanceof i.ShaderMaterial&&t instanceof i.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof i.ShaderMaterial&&t instanceof i.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 Ha(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}function Za(e,t){const a=tt(e);return null==a?"":function(e,t){const a=Ps(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&&ts(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 Xa(e,t){const a=Ps(e,t);if(a.length===Object.keys(e.attributes).length)return e;const s=new o;s.name=e.name;const r=e.getIndex();null!=r&&s.setIndex(r);for(const t of a)s.setAttribute(t,es(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 Ka=new WeakMap;function es(e,t){return e.getAttribute(t)??function(e,t){if("uv"===t)return function(e){let t=Ka.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 i.Float32BufferAttribute(new Float32Array(2*a.count),2),Ka.set(e,t));return t}(e);throw new Error(`Unsupported synthetic batching geometry attribute: ${t}`)}(e,t)}function ts(e){return null!=e.getAttribute("position")}const as=new WeakMap,ss="hbat_",rs=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 is(e){let t=as.get(e);return null==t&&(t=function(e){let t=e.type;if(e instanceof R)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(ls(a))continue;const s=e.uniforms[a]?.value;us(s)||(t+=`u:${a}:${gs(s)};`)}return t+=os(e.vertexShader),t+=os(e.fragmentShader),t}(e);else if(e instanceof i.MeshStandardMaterial&&!(e instanceof i.MeshPhysicalMaterial)||(t+=e.id+""),(e instanceof i.MeshBasicMaterial||e instanceof i.MeshLambertMaterial||e instanceof S||e instanceof y)&&(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 S&&(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 i.MeshPhysicalMaterial&&(null!=e.sheenColorMap&&(t+="sc"+e.sheenColorMap?.id),null!=e.sheenRoughnessMap&&(t+="sr"+e.sheenRoughnessMap?.id)),(e instanceof g||e instanceof y)&&null!=e.specularMap&&(t+="s"+e.specularMap?.id),e instanceof i.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 Gt&&null!=e.heightMap&&(t+="h"+e.heightMap?.id),e instanceof i.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),as.set(e,t)),t}const ns=new Map;function os(e){return ns.has(e)||ns.set(e,`shader_${ns.size}`),ns.get(e)}function ls(e){return rs.has(e)||e.startsWith("hology_")}function cs(e,t){return e instanceof R?e.uniforms[t]?.value:e[t]}function us(e){return"number"==typeof e||e instanceof j||e instanceof I||e instanceof P||e instanceof l}function ds(e){return"number"==typeof e?1:e instanceof j?2:4}function hs(e,t){const a=e.replace(/[^A-Za-z0-9_]/g,"_");let s=ss+a;for(;t.has(s);)s=ss+s;return t.add(s),s}function ps(e,t){const a={};for(const[s,r]of Object.entries(e.uniforms))t.has(s)||(a[s]={value:r.value});return a}const fs=new WeakMap;let ms=1;function gs(e){if(null==e)return"null";if(e instanceof x||!0===e?.isTexture)return`texture:${e.id}`;if(e instanceof i.Matrix3||e instanceof i.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=fs.get(e);return null==t&&(t=ms++,fs.set(e,t)),`object:${t}`}return String(e)}function ys(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 Ss=new f,ws=new c;function bs(e,t){return ws.copy(e),ws.x*=-1,ws.y*=-1,ws.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(ws.y*=-1,ws.z*=-1),(new i.Matrix3).setFromMatrix4(Ss.makeRotationFromEuler(ws))}function vs(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 Ms=new P;function As(e,t){return e===t||null==e==(null==t)&&("number"==typeof e&&"number"==typeof t?e===t||isNaN(e)&&isNaN(t):e instanceof i.Color&&t instanceof i.Color?e.r===t.r&&e.g===t.g&&e.b===t.b:e instanceof j&&t instanceof j?e.x===t.x&&e.y===t.y:e instanceof I&&t instanceof I?e.x===t.x&&e.y===t.y&&e.z===t.z:e instanceof P&&t instanceof P&&(e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w))}function xs(e){const t=[];for(const[a,s]of Object.entries(e))s instanceof fe?t.push(s):s instanceof Me&&t.push(...xs(s));return t}function js(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 Is=new WeakMap;function Ps(e,t){const a=Object.keys(e.attributes).filter(a=>Ds(e,t,a));return!e.hasAttribute("uv")&&ts(e)&&Ds(e,t,"uv")&&a.push("uv"),a}function Ds(e,t,a){return"position"===a||("uv"===a?function(e){if(e instanceof R)return Es(e,"uv");if(e instanceof i.ShaderMaterial)return Cs(e.vertexShader,"uv");if(e instanceof Gt&&null!=e.heightMap)return!0;return Os.some(t=>e[t]?.isTexture)}(t):t instanceof R?Es(t,a):t instanceof i.ShaderMaterial?function(e,t){if("uv1"===t||"uv2"===t||"uv3"===t)return Cs(e.vertexShader,t);return!0}(t,a):"uv1"!==a&&(("color"!==a||!function(e){let t=Is.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 Is.set(e,t),t}(e))&&("uv2"!==a||(null!=t.lightMap||null!=t.aoMap))))}const Os=["map","alphaMap","emissiveMap","normalMap","bumpMap","displacementMap","roughnessMap","metalnessMap","aoMap","specularMap","gradientMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","iridescenceMap","iridescenceThicknessMap","sheenColorMap","sheenRoughnessMap","transmissionMap","thicknessMap","anisotropyMap"];function Es(e,t){return Cs(e.vertexShader,t)}function Cs(e,t){return new RegExp(`(^|[^A-Za-z0-9_])${a=t,a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}([^A-Za-z0-9_]|$)`).test(e);var a}function ks(e,t,a){if(t(e))return e;for(const s of e.children??[]){const e=ks(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=>ks(e,t,a));if(null!=e)return e}}return null}const Ts=new I,Bs=new I,Vs=new I,zs=new P,Ns=new P,$s=new f,Us=new f,Fs=new w;function Ws(e){e.updateWorldMatrix(!0,!1);const t=e.geometry.clone(),a=t.getAttribute("position"),s=t.getAttribute("normal"),r=t.getAttribute("tangent");if(null!=a){for(let t=0;t<a.count;t++)Ts.fromBufferAttribute(a,t),e.applyBoneTransform(t,Ts),a.setXYZ(t,Ts.x,Ts.y,Ts.z);a.needsUpdate=!0}if(null!=s||null!=r){const a=t.getAttribute("skinIndex"),i=t.getAttribute("skinWeight");if(null!=a&&null!=i){for(let t=0;t<a.count;t++)Rs(e,t,Us),null!=s&&(Bs.fromBufferAttribute(s,t),Fs.getNormalMatrix(Us),Bs.applyMatrix3(Fs).normalize(),s.setXYZ(t,Bs.x,Bs.y,Bs.z)),null!=r&&(Vs.fromBufferAttribute(r,t),Vs.transformDirection(Us),r.setXYZ(t,Vs.x,Vs.y,Vs.z));null!=s&&(s.needsUpdate=!0),null!=r&&(r.needsUpdate=!0)}}t.deleteAttribute("skinIndex"),t.deleteAttribute("skinWeight"),t.computeBoundingBox(),t.computeBoundingSphere();const i=new m(t,e.material);return i.copy(e,!1),i.geometry=t,i.material=e.material,i.userData={...e.userData},i}function Rs(e,t,a){const s=e.geometry,r=s.getAttribute("skinIndex"),i=s.getAttribute("skinWeight"),n=e.skeleton;zs.fromBufferAttribute(r,t),Ns.fromBufferAttribute(i,t),a.identity().multiplyScalar(0);for(let e=0;e<4;e++){const t=Ns.getComponent(e);if(0===t)continue;const s=zs.getComponent(e);$s.multiplyMatrices(n.bones[s].matrixWorld,n.boneInverses[s]);for(let e=0;e<16;e++)a.elements[e]+=$s.elements[e]*t}return a.premultiply(e.bindMatrixInverse).multiply(e.bindMatrix),a}function _s(e){let t=!0;return e.traverse(a=>{a===e||a.isBone||(t=!1)}),t}function Gs(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 Ls(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{Subject as n}from"rxjs";import*as o from"three";import{BoxGeometry as l,BufferGeometry as c,Color as u,Euler as d,Fog as h,FogExp2 as p,Group as f,Material as m,Matrix4 as g,Mesh as y,MeshLambertMaterial as w,MeshPhongMaterial as S,MeshStandardMaterial as b,Matrix3 as v,Object3D as M,PointLight as A,Quaternion as x,Scene as j,Texture as I,Vector2 as P,Vector3 as D,Vector4 as O}from"three";import{attributes as C,batchingUniformFloat as E,batchingUniformVec2 as k,batchingUniformVec3 as T,batchingUniformVec4 as B,bool as V,BooleanExpression as z,BooleanNode as N,colorToNormal as $,float as U,deriveNodeShaderMaterial as F,FloatNode as W,ifDefApply as R,mix as _,NodeShaderMaterial as G,rgb as L,rgba as q,RgbNode as J,select as Y,standardMaterial as Q,Texture2dLookupNode as H,textureSampler2d as Z,textureSampler2dArray as X,UniformBoolNode as K,UniformFloatNode as ee,UniformSampler2dArraySlice as te,UniformVec2Node as ae,UniformVec3Node as se,UniformVec4Node as re,varying as ie,varyingAttributes as ne,varyingTransformed as oe,vec2 as le,Vec2Node as ce,vec3 as ue,Vec3Node as de,vec4 as he,Vec4Node as pe}from"three-shader-graph";import{Service as fe}from"typedi";import{VfxActor as me}from"../effects/vfx/vfx-actor.js";import{VisualEffect as ge}from"../effects/vfx/vfx-param.js";import{Prefab as ye,PrefabOf as we}from"./objects/prefab.js";import{DataAssetRef as Se}from"./objects/data-asset.js";import{SceneRef as be}from"./scene-ref.js";import{ModelRef as ve}from"./model-ref.js";import{BaseActor as Me,getActorOptions as Ae}from"../gameplay/actors/actor.js";import xe from"../gameplay/actors/builtin/index.js";import{ActorComponent as je}from"../gameplay/actors/component.js";import{PhysicsBodyType as Ie}from"../gameplay/services/physics/physics-system.js";import{NetMode as Pe}from"../gameplay/net/net-session.js";import{NetRole as De}from"../gameplay/net/service/net-actor-role.js";import{ThreeBlendingMode as Oe}from"../effects/vfx/vfx-asset.js";import{withInjectionContext as Ce}from"../gameplay/inject.js";import{RenderingView as Ee}from"../rendering.js";import{markMaterialUniformValuesNeedUpdate as ke,setMaterialUniformValuesAutoUpdate as Te}from"../rendering/node-material-webgpu-resolver.js";import{curveSampler as Be,oneMinus as Ve,particleUniforms as ze,Sampler2DNode as Ne}from"../shader-nodes/index.js";import{LambertShader as $e}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as Ue}from"../shader/builtin/landscape-composite-shader.js";import{LandscapeShader as Fe}from"../shader/builtin/landscape-shader.js";import{StandardShader as We}from"../shader/builtin/standard-shader.js";import{UnlitShader as Re}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as _e,getDataAssetDefinitionType as Ge,getParameterDefinitionId as Le,getParameterDefinitionType as qe,isDataAssetDefinitionAbstract as Je,isParameterDefinitionAbstract as Ye,isParameterDefinitionAssignableTo as Qe,isParameterDefinitionStructAssignableTo as He,shaderParameterUniformName as Ze}from"../shader/parameter.js";import{ArrayMap as Xe,DefaultMap as Ke,groupBy as et}from"../utils/collections.js";import{iterateMaterials as tt}from"../utils/materials.js";import{filterChildrenShallow as at,filterSceneShallow as st,findFirstVisibleMesh as rt,findFirstVisibleObject as it,traverseAsync as nt}from"../utils/three/traverse.js";import{AssetMeshInstance as ot,AssetResourceLoader as lt}from"./asset-resource-loader.js";import{AssetsProvider as ct}from"./assets-provider.js";import{isCollisionMesh as ut}from"./collision/collision-shape-import.js";import{BoxCollisionShape as dt,PhysicalShapeMesh as ht}from"./collision/collision-shape.js";import{LandscapeManager as pt}from"./landscape/landscape-manager.js";import{initLandscape as ft}from"./landscape/landscape.js";import{SectionGrid as mt,smoothNormalsCrossMeshes as gt}from"./landscape/utils.js";import{createGrassFoliageMaterial as yt}from"./materials/grass-foliage.js";import{createGrassMaterial as wt}from"./materials/grass.js";import{getMaterialAttribute as St}from"./materials/utils/material-painting.js";import{PaintedScatterManager as bt}from"./scatter/painted-scatter-manager.js";import{SurfaceScatterManager as vt}from"./scatter/surface-scatter-manager.js";import{createWaterMaterial as Mt}from"./materials/water.js";import{SerializedParamType as At}from"./model.js";import{applyRuntimeParamTypeInference as xt,convertConfiguredParamsToRuntimeTypes as jt,convertConfiguredParamValueToRuntimeType as It,inferRuntimeSerializedParamTypeHint as Pt}from"./custom-param-runtime-types.js";import{ShapeLibrary as Dt,ShapeLibraryKeys as Ot}from"./objects/shapes.js";import{ambientLightName as Ct,createSky as Et,defaultSkyMaterial as kt}from"./sky.js";import{Curve2 as Tt}from"../utils/curve.js";import{DecalUnlitShader as Bt}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as Vt}from"../shader/builtin/decal-standard-shader.js";import{ClusterGenerator as zt}from"../rendering/cluster-generator.js";import{ColorLayer as Nt,defaultValueColorLayer as $t,defaultValueMaskLayer as Ut,MaskLayer as Ft}from"../shader/color-layer.js";import{LayeredShader as Wt}from"../shader/builtin/layered-shader.js";import{isColorLayerSerialized as Rt}from"../shader/color-layer.js";import{FogVolume as _t}from"../rendering/fog/fog-volume-actor.js";import{UnscaledSprite as Gt}from"../utils/three/unscaled-sprite.js";import{ToonShader as Lt}from"../shader/builtin/toon-shader.js";import{BatchedMesh2 as qt}from"./batched-mesh-2.js";import{ParallaxStandardMaterial as Jt}from"../shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Yt}from"../shader-nodes/pom.js";import{traverseVisibleEvery as Qt}from"../utils/three/traverse.js";import{BufferGeometryUtils as Ht,RectAreaLightHelper as Zt}from"three/examples/jsm/Addons.js";import{createSequenceData as Xt,isSequenceData as Kt,Sequence as ea}from"../effects/sequence/sequence-data.js";import{applyUvTiling as ta}from"./../shader/uv-nodes.js";import{buildShaderGraphMaterial as aa,shaderGraphMaterialSideToThree as sa}from"../shader/graph/index.js";import{hasExecutableEventGraphDocument as ra}from"../gameplay/event-graph/model.js";import{depthUniformName as ia}from"../shader-nodes/depth.js";export{xt as applyRuntimeParamTypeInference,jt as convertConfiguredParamsToRuntimeTypes,It as convertConfiguredParamValueToRuntimeType,Pt as inferRuntimeSerializedParamTypeHint};const na={},oa=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),la=/^((?!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 ca(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}let ca=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,l,c,u,d=[]){this.scene=e,this.dataProvider=t,this.assetsService=s,this.assetManagerService=r,this.renderingView=i,this.shaders=l,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=Pe.none,this.updated$=new n,this.removed$=new n,this.prefabEventGraphAdded$=new n,this.prefabEventGraphRemoved$=new n,this.error$=new n,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 n,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 o.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=>Vs(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 D,!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 y)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 o.SpotLight&&"spot"===t.userData?.src?.light?.type&&t.userData.src.light.spot.mapTextureId===e.id&&s.push(t),t instanceof y&&(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 o.ShaderMaterial){for(const a of Object.values(e.uniforms))if(a.value instanceof o.Texture&&a.value.userData.assetId===t)return!0}else for(const a of Object.values(e))if(a instanceof o.Texture&&a.userData.assetId===t)return!0;return!1}replaceMaterialTextureReferences(e,t,a){let s=!1;if(e instanceof o.ShaderMaterial)for(const[r,i]of Object.entries(e.uniforms))i.value instanceof o.Texture&&i.value.userData.assetId===t&&(e.uniforms[r].value=a,s=!0);else for(const[r,i]of Object.entries(e))i instanceof o.Texture&&i.userData.assetId===t&&(e[r]=a,s=!0);s&&(e.needsUpdate=!0,ke(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===At.Material&&s.value===a.id){t=!0;break}if(s.type===At.Array&&"element"in s&&s.element===At.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?Xa(e.material[s],i)||(e.material[s]=i):Xa(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===At.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(),da.clear(),ha.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)Ma(e,!1);this.editorMatrixWorldEditingObjects.clear();for(const t of e)this.editorMatrixWorldEditingObjects.add(t),Ma(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)Ma(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===Ie.dynamic)continue;const a=this.sceneObjectMap.get(t.id);null!=a&&this.canUseEditorStaticDrawSet(a)&&e.push(a)}const t=new f;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 f;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 f;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;(ut(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=ba}0!==t.children.length&&(Sa(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 y&&!ut(e)&&(t=!0,null!=e.geometry?.index&&null==e.customDepthMaterial&&xa(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 j;for(const i of e){const e=i.asset;if(t.has(e.id))continue;t.add(e.id),Ds(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=>Ps(e)))}async initActorsPostInit(e=Array.from(this.materializedActors.entries())){const t=e.map(async([e,t])=>{if(t.__isInitialised)return;const a=t.object.userData.src??t.object.userData._src;if("vfx"===a.type)return Promise.resolve();const s="prefab"===a.type?await this.assetsService.getAsset(a.assetId):null,r=e.split("/"),i=r.slice(0,-1),n=i.join("/"),o=(r[r.length-1],new Map);for(const[e,t]of this.materializedActors)if(o.set(e,t),0===n.length)e.includes("/")||o.set(e,t);else if(e.startsWith(n+"/")){const a=e.slice(n.length+1);a.includes("/")||o.set(a,t)}const l={...s?.actor?.params??{},...a.actor?.params??{}},c=[...a.actor?.innerParams??[]];for(let t=i.length-1;t>=0;t--){const a=i.slice(0,t+1).join("/"),s=this.idToSceneObject.get(a);if("prefab"===s?.type&&null!=s.prefab){const i=await this.assetsService.getAsset(s.assetId);if(null!=i){let n=!1,o=a+"/"+i.prefab?.mainActorId;for(;null!=o;){if(o===e){n=!0;break}o=this.prefabInstanceExposedActorMap.get(o)}if(n&&null!=s.prefab.params&&Object.assign(l,$a(s.prefab.params)),null!=s.prefab.innerParams){const e=r.slice(t+1);for(const t of s.prefab.innerParams){const a=$a(t.params);0!==Object.keys(a).length&&(n?c.push({path:Ua(t.path,e)?t.path.slice(e.length):t.path,params:a}):Ua(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!==Ie.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=>{!ut(e)&&e.isMesh&&s.push(e)});const r=1==s.length&&0==s[0].children.length,i=!la,n=s.every(e=>!Array.isArray(e.material)||1===e.material.length),o=s.some(e=>e instanceof y&&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,da.clear(),ha.clear();const e=[],t=new Xe,a=new Xe,s=new Xe;let r=0,i=0,n=0;const l=new Map,c=new Ke(()=>new Map),h="webgpu"===this.renderingView?.requestedBackend?new f:null,p=null!=h?new f:null;null!=h&&(h.name="Hology WebGPU static scene objects",p.name="Hology WebGPU unsorted late static scene objects");const m=(e,t)=>{if(null!=h&&function(e){return e.visible&&null!=e.geometry.index&&null==e.customDepthMaterial&&xa(e.material,!0)}(t)){((Array.isArray(t.material)?t.material:[t.material]).some(e=>e.transparent||ja(e))?p:h).add(e)}else this.scene.add(e)};for(const o of this.dataProvider.getObjects())await Ca(o,async(o,d,h)=>{if(!this.shouldBeMaterialized(o))return;const p="asset_mesh"==o.type&&this.canObjectBeInstanced(o)&&await this.canAssetBeInstanced(o),f="shape_mesh"===o.type&&"landscape"!==o.shape&&o.physics?.type!==Ie.dynamic;if(p||f){if(d&&d.children?.length>0){const e=d.children.findIndex(e=>e.id===o.id);e>=0&&d.children.splice(e,1)}if(f){let e=o.shape+JSON.stringify(o.shapeParams??{})+o.castShadow+o.receiveShadow;const t=o.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===At.Color&&null!=e.value&&(r=new u(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:{...o,parentTransform:h},color:r}),n++}else{const e=this.assets.get(o.assetId);null==e&&console.log("Can't find asset with id "+o.assetId);let s=l.get(o.assetId);if(null==s){const e=await this.createFromAsset(o,{assignMaterials:!1});if(null==e)return;if(s=l.get(o.assetId),null==s){s={useBatchedMesh:null!=rt(e)&&Qt(e,e=>!(e instanceof y)||this.testCanBatch(e.material,e.geometry)),assetMesh:e},l.set(o.assetId,s)}}const n=Ra(o.materialAssignments,e.materialAssignments);if(s.useBatchedMesh)await nt(s.assetMesh,async t=>{if(!(t instanceof y))return;const s=Array.isArray(t.material)?t.material[0]:t.material,i=await this.resolveMaterialForAssignments(s,n,e);if(null!=i){Te(i,!1),c.get(o.id).set(t.uuid,i);let s=es(t,i);if(s+=ls(i),"webgpu"===this.renderingView?.requestedBackend){s+=`|castShadow:${o.castShadow??e.castShadow??!1?1:0}|receiveShadow:${o.receiveShadow??e.receiveShadow??!1?1:0}`}a.push(s,{...o,parentTransform:h,meshUUID:t.uuid}),r++}else console.warn("Can not materialize mesh because missing material",o)});else{const e=o.assetId+JSON.stringify(o.materialAssignments??[]);t.push(e,{...o,parentTransform:h}),i++}}}else null==d&&e.push({...o,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;l.get(t[0].assetId).assetMesh;e=this.createBatchedMesh(t,c,l);const a=this.assets.get(t[0].assetId);"webgl"===this.renderingView?.activeBackend?(e instanceof qt&&e.perInstanceCastShadow||(e.castShadow=Js(t,a?.castShadow??!1)),e.receiveShadow=Ys(t,a?.receiveShadow??!1)):(e.castShadow=!0,e.receiveShadow=!0);const s=new ot;s.add(e),s.userData.src=t[0],s.castShadow=!1,s.receiveShadow=!1,m(s,e)}for(const e of t.values()){if(0==e.length)continue;let t;const a=l.get(e[0].assetId).assetMesh;t=await this.createInstancedMesh(e,a);const s=this.assets.get(e[0].assetId);t.castShadow=Js(e,s?.castShadow??!1),t.receiveShadow=Ys(e,s?.receiveShadow??!1);const r=new ot;r.add(t),r.userData.src=e[0],a instanceof ot&&(r.collisionShapes=a.collisionShapes),this.prepareCollisionShapesForInstanced(r),r.castShadow=!1,r.receiveShadow=!1,m(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=it(a,e=>!ut(e)&&null!=e.geometry),r=Qa(s.material);null!=e[0].color&&null!=r.color&&(r.color=new u(16777215));const i=null==s.geometry.index?Ht.mergeVertices(s.geometry):s.geometry;let n,l;!(la||r instanceof G)?(n=new o.BatchedMesh(e.length,i.getAttribute("position").count,i.index.count,r),n.perObjectFrustumCulled=!0,l=n.addGeometry(i)):n=new o.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 o.Matrix4).compose((new D).fromArray(a.object.position),(new x).setFromEuler((new d).fromArray(a.object.rotation)),(new D).fromArray(a.object.scale)),r=(new g).copy(a.object.parentTransform).multiply(s);let i;i=n instanceof o.BatchedMesh?n.addInstance(l):t,n.setMatrixAt(i,r),a.color}for(let t=0;t<e.length;t++){const s=e[t],r=new ot;r.userData.src=e[0],a instanceof ht&&(r.collisionShapes=[a.collisionShape]),r.castShadow=!0,r.receiveShadow=!0,m(r,n),r.add(n),null==n.userData.hasCollision&&(n.userData.hasCollision=[]),n.userData.hasCollision[t]=!1!==s.object.collisionDetection}}if(null!=h&&h.children.length>0&&(Sa(h),this.scene.add(h),this.experimentalStaticDrawSetDisposer=this.renderingView.registerExperimentalStaticDrawSet(h,"hology-materialized-static-scene")),null!=p&&p.children.length>0){Sa(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 zt;e.initScene(this.scene),e.clusters.forEach(e=>{this.renderingView.addCluster(e)})}prepareCollisionShapesForInstanced(e){e instanceof ot&&e.collisionShapes.forEach(e=>{e instanceof r&&e.mesh instanceof y&&(e.mesh=e.mesh.geometry)})}setScene(e){this.scene=e}testCanBatch(e,t){return!la&&(!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 Xe;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 l=new Map;for(const[e,t]of s.entries()){const s=t[0].assetId,o=a.get(s);if(null==o){console.warn("Missing batching info for asset id "+s);continue}const c=it(o.assetMesh,t=>t instanceof y&&t.uuid===e);if(null==c){console.warn("Missing mesh in batched asset");continue}l.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"],d=new Map,h=new Map,p=[];let f=new o.MeshStandardMaterial({color:"white"});const m=t.get(e[0].id).get(e[0].meshUUID);if(null==m)throw"missing source material";if(m instanceof b&&!(m instanceof o.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 o.CompressedArrayTexture&&null!=r.userData.index&&(r=r.userData.index);const i=s.get(t);void 0===i||Is(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:B(t)},p.push(a)}else a.params.push(e);s=a.name,t=xs(a.node,a.params.length-1)}else if(a instanceof O)t=B(s);else if(a instanceof D||a instanceof u)t=T(s);else if(a instanceof P)t=k(s);else if(a instanceof o.CompressedArrayTexture)s=e+"_i",t=E(s);else if(a instanceof I)continue;d.set(e,t),h.set(e,s)}let r=ne.uv;m instanceof Jt&&null!=m.heightMap&&(r=Yt(r,Z(m.heightMap),U(m.heightScale)));let i=bs(d.get("opacity"),W)??U(m.opacity??1);if(null!=m.alphaMap){let e;if(m.alphaMap instanceof o.CompressedArrayTexture){const t=X(m.alphaMap),a=bs(d.get("alphaMap"),W)??U(m.alphaMap.userData.index??0);e=t.sample(ue(r.x,r.y,a))}else e=Z(m.alphaMap).sample(r);i=i.multiply(e.r)}let n=q(bs(d.get("color"),de)??m.color,i);if(null!=m.map){let e;if(m.map instanceof o.CompressedArrayTexture){const t=X(m.map),a=bs(d.get("map"),W)??U(m.map.userData.index??0);e=t.sample(ue(r.x,r.y,a))}else e=Z(m.map).sample(ta(r,m.map));n=n.multiply(e),i=i.multiply(e.a)}m.vertexColors&&(n=n.multiply(he(ie(C.color.rgb),1)));let l=q(bs(d.get("emissive"),de)??m.emissive,i);if(null!=m.emissiveMap){let e;if(m.emissiveMap instanceof o.CompressedArrayTexture){const t=X(m.emissiveMap),a=bs(d.get("emissiveMap"),W)??U(m.emissiveMap.userData.index??0);e=t.sample(ue(r.x,r.y,a))}else e=Z(m.emissiveMap).sample(ta(r,m.emissiveMap));l=l.multiply(e)}const g=bs(d.get("emissiveIntensity"),W)??U(m.emissiveIntensity??1),y=bs(d.get("normalScale"),ce)??le(m.normalScale??new P(1,1));let w=oe.normal;if(null!=m.normalMap){let e;if(m.normalMap instanceof o.CompressedArrayTexture){const t=X(m.normalMap),a=bs(d.get("normalMap"),W)??U(m.normalMap.userData.index??0);e=t.sample(ue(r.x,r.y,a))}else e=Z(m.normalMap).sample(ta(r,m.normalMap));w=$(e.rgb,y.x)}let S=bs(d.get("roughness"),W)??U(m.roughness??1);if(null!=m.roughnessMap){let e;if(m.roughnessMap instanceof o.CompressedArrayTexture){const t=X(m.roughnessMap),a=bs(d.get("roughnessMap"),W)??U(m.roughnessMap.userData.index??0);e=t.sample(ue(r.x,r.y,a))}else e=Z(m.roughnessMap).sample(ta(r,m.roughnessMap));S=S.multiply(e.g)}let b=bs(d.get("metalness"),W)??U(m.metalness??0);if(null!=m.metalnessMap){let e;if(m.metalnessMap instanceof o.CompressedArrayTexture){const t=X(m.metalnessMap),a=bs(d.get("metalnessMap"),W)??U(m.metalnessMap.userData.index??0);e=t.sample(ue(r.x,r.y,a))}else e=Z(m.metalnessMap).sample(ta(r,m.metalnessMap));b=b.multiply(e.b)}let v=U(1);if(null!=m.aoMap){let e;if(m.aoMap instanceof o.CompressedArrayTexture){const t=X(m.aoMap),a=bs(d.get("aoMap"),W)??U(m.aoMap.userData.index??0);e=t.sample(ue(r.x,r.y,a))}else e=Z(m.aoMap).sample(ta(r,m.aoMap));v=v.multiply(e.r)}const M=bs(d.get("aoMapIntensity"),W)??U(m.aoMapIntensity??0);let A=w;!0!==m.userData.disableAO&&(A=R("DOUBLE_SIDED",A,e=>Y(new z("gl_FrontFacing"),e,e.multiplyScalar(-1))));const x=new G({color:Q({color:n,roughness:S,metalness:b,ambientOcclusion:v,ambientOcclusionIntensity:M,emissive:l,emissiveIntensity:g,normal:A}),normal:w,roughness:S,emissive:l.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:As(m.envMapRotation,m.envMap)}),x.envMap=m.envMap,x.side=m.side,f=x}else if(m instanceof G){const a=new Set,s=new Map,r=Object.keys(m.uniforms).filter(e=>!ds(e));for(const i of e){const e=t.get(i.id).get(i.meshUUID);if(!(e instanceof G))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||Is(r,i)?s.set(t,r):ps(r)&&ps(i)&&fs(r)===fs(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=ms("vp"+p.length,i);s={name:t,params:[e],node:B(t)},p.push(s)}else s.params.push(e);a=s.name,t=xs(s.node,s.params.length-1)}else if(s instanceof O)a=ms(e,i),t=B(a);else if(s instanceof D||s instanceof u)a=ms(e,i),t=T(a);else{if(!(s instanceof P))continue;a=ms(e,i),t=k(a)}d.set(e,t),h.set(e,a),n[e]=t}if(0===d.size)f=m;else{const e=F(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:gs(m,new Set(d.keys())),uniformNodes:n});e.uniformNodes=n,g=m,(w=e).name=g.name,w.side=g.side,w.blending=g.blending,w.depthWrite=g.depthWrite,w.depthTest=g.depthTest,w.colorWrite=g.colorWrite,w.toneMapped=g.toneMapped,w.visible=g.visible,w.opacity=g.opacity,w.forceSinglePass=g.forceSinglePass,w.premultipliedAlpha=g.premultipliedAlpha,w.polygonOffset=g.polygonOffset,w.polygonOffsetFactor=g.polygonOffsetFactor,w.polygonOffsetUnits=g.polygonOffsetUnits,w.shadowSide=g.shadowSide,Object.assign(w.defines,g.defines),Object.assign(w.userData,g.userData),w.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,w;const S=new qt(n,i,r,f);for(const e of p)S.initUniform(e.name,4);for(const[e,t]of d.entries()){if(p.some(t=>t.params.includes(e)))continue;let a=1;t instanceof pe||t instanceof de?a=4:t instanceof ce&&(a=2),S.initUniform(h.get(e)??e,a,0)}for(const[e,r]of s.entries()){const s=r[0].assetId,i=l.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(ts(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=rt(f.assetMesh)?.uuid===e,y=f.assetMesh instanceof ot&&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=hs(i,e.params[a]);"number"==typeof s&&t.setComponent(a,s)}S.setUniformAt(e.name,s,t)}for(let e of d.keys()){if(p.some(t=>t.params.includes(e)))continue;const t=h.get(e)??e;let a=hs(i,e);if(a instanceof u&&(a=new D(a.r,a.g,a.b)),a instanceof o.CompressedArrayTexture)a=a.userData.index??0;else if(a instanceof I||null==a)continue;S.setUniformAt(t,s,a)}}}return S}async createInstancedMesh(e,t){const a=it(t,e=>!ut(e)&&null!=e.geometry),s=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,Ra(e[0].materialAssignments,s.materialAssignments),s),a.updateMatrix();const r=a.geometry.clone(),i=a.material;let n;if(n=new o.InstancedMesh(r,i,e.length),this.configureBatchedInstancedMesh(e,n,a),a.material instanceof m&&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 l=n;t instanceof o.BatchedMesh&&(l=t.addInstance(s)),i.push(l);const c=(new o.Matrix4).compose((new D).fromArray(e[n].position),(new x).setFromEuler((new d).fromArray(e[n].rotation)),(new D).fromArray(e[n].scale)),u=(new g).copy(e[n].parentTransform).multiply(c),h=(new g).copy(u).multiply(a.matrixWorld);t.setMatrixAt(l,h),null==t.userData.hasCollision&&(t.userData.hasCollision=[]);const p=this.assets.get(e[n].assetId);t.userData.hasCollision[l]=!1!==e[n].collisionDetection||!1!==p?.collisionDetection,null!=r&&(null==t.userData.collisionShapes&&(t.userData.collisionShapes=[]),t.userData.collisionShapes[l]=r,null==t.userData.collisionMatrices&&(t.userData.collisionMatrices=[]),t.userData.collisionMatrices[l]=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 st(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(!qa(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=Ya(a,n)),null!=a&&s.id!==a.id&&(r=r??La(s),i=i??s.name,s=a);break}return s}unapplyMaterials(e){e.traverse(async e=>{if(e instanceof y)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(xe));st(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,st(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 da.entries())t.userData.customShaderName&&da.delete(e);ha.clear(),this.landscapeManagers.forEach(t=>t.updateShaders(e)),st(this.scene,e=>!0).forEach(e=>{e.traverse(async e=>{if(e instanceof y)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 y&&(e.material.wireframe=!0)}):t.traverse(e=>{e instanceof y&&(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);Ra(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!==Ie.dynamic?Ma(t,!1):this.inEditor&&function(e){let t=!1;if(e.traverse(e=>{va.has(e)&&(t=!0)}),!t)return;e.updateWorldMatrix(!0,!0),e.traverse(e=>{va.has(e)&&(e.matrixWorldNeedsUpdate=!1)})}(t)),this.applyVertexMaterials(e,t),"light"==e.type){if("point"==e.light.type){const a=t;a.color=new u(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 u(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 u(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 Zt&&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 p?"density":"linear")!==e.fog.type;this.scene.fog=Ia(e.fog),t&&(a=this.scene).traverse(e=>{if(e instanceof y){const t=e.material;t instanceof G&&(a.fog instanceof h?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof p&&(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 _t){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 ht&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}if("shape_mesh"===e.type&&"landscape"!==e.shape)ua(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;ua(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=Ta(e.prefab?.objects??[]),r=Ta(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)??Va(o,n.source,e.prefab?.mainActorId===a),u=Va(o,n.source,e.prefab?.mainActorId===a),d=za(u,Va(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=Ba(e.prefab?.objects??[]),i=Ba(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=Ta(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=Va(i,t,n.prefab.mainActorId===e),u=Va(i,r,n.prefab.mainActorId===e),d=c.desiredActorSettingsById.get(e)??l,h=za(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:at(t,t=>t.children?.some(t=>t.id===e.id),()=>!0))[0];return null==t?this.scene:null!=t?st(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 u(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse(e=>{e instanceof y&&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=et(e.vertexMaterials,e=>e.m);t.traverse(e=>{if(e instanceof y){if(null==e.geometry)return;if(Ka(St(e,0,!1)),a>0){Ka(St(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=St(s,0,!0);Ka(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=St(s,4,!0);Ka(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=Ia(e.fog),this.fixFogColor(),i=new f;break;case"sky":this.sky=Et(),this.updateSky(e),i=this.sky;break;case"world_env":this.updateWorldEnv(e),i=new f,this.worldEnvObj=i;break;case"actor":({object:i,actor:n}=await this.createFromActor(e,s));break;case"group":case"scatter":i=new f;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!==Ie.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(Pa),i.getWorldQuaternion(Da),i.getWorldScale(Oa),this.scene.add(i),i.position.copy(Pa),i.quaternion.copy(Da),i.scale.copy(Oa)),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!==Ie.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)?Ma(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==Ie.dynamic||Sa(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 bt(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 vt(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(o.NoToneMapping,1)}async updateSky(e){null!=this.sky&&(null==e?.sky?.materialId&&this.sky.material!==kt?(this.sky.material=kt,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=o.BackSide,(e instanceof b||e instanceof o.MeshBasicMaterial||e instanceof o.ShaderMaterial)&&(e.fog=!1),e.depthTest=!0,e.depthWrite=!1,e.transparent=!0}async createComponent(e,t,a,s){const r=new na[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??xe[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 D).fromArray(e.position),(new d).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===Pe.none)return;const t=Ae(e.constructor);!0!==t?.replicate?this.netMode===Pe.client&&(e.netRole=De.none):e.netRole=this.netMode===Pe.client?De.simulatedProxy:De.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(me,(new D).fromArray(e.position),(new d).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 y&&this._originalMaterials.set(e.id,e.material)});else{let s=new b({name:"Default",color:new u("#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 f;const a=ft(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new pt(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 mt(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(()=>gt(r),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&Ot.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);if(!this.geometryCache.has(r)){const t=Dt[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,Dt[e].collision(s));return new ht(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(Ra(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,ua(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 y&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()}),s.userData.assetId=e.assetId,s.traverse(e=>{if(e instanceof y)for(const t of tt(e.material))Te(t,!1)}),"webgpu"===this.renderingView.requestedBackend){await this.renderingView.initializeBackend();const e=new Set;s.traverse(t=>{if(t instanceof y)for(const a of tt(t.material))if(a instanceof o.ShaderMaterial)for(const t of Object.values(a.uniforms)){const a=t.value;a instanceof I&&null!=a.image&&e.add(a)}else for(const t of Object.values(a))t instanceof I&&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 f;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([...Ta(e.prefab?.objects??[])].map(([t,a])=>[t,Va(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&&ra(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 M}async createLight(e){if("point"===e.light.type){const t=new A(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 o.TextureLoader).load("assets/light-bulb-icon.webp"),a=new o.SpriteMaterial({map:e,alphaTest:.5}),s=new Gt(a);s.scale.multiplyScalar(.6),t.add(s)}return t}if("spot"===e.light.type){const t=new o.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 M,t.target.position.set(0,-1,0),t.add(t.target),this.inEditor){const e=(new o.TextureLoader).load("assets/light-bulb-icon.webp"),a=new o.SpriteMaterial({map:e,alphaTest:.5}),s=new Gt(a);s.scale.multiplyScalar(.6),t.add(s),t.add(new o.SpotLightHelper(t))}return t}if("rectArea"===e.light.type){const t=new o.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 o.TextureLoader).load("assets/light-bulb-icon.webp"),a=new o.SpriteMaterial({map:e,alphaTest:.5}),s=new Gt(a);s.scale.multiplyScalar(.6),t.add(s);const r=new Zt(t);t.add(r)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional,e),new f):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient,e),new f):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){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(o.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}};ca=e([fe(),t("design:paramtypes",[j,Object,ct,lt,Ee,Array,Array,Object,Array])],ca);export{ca as SceneMaterializer};function ua(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse(e=>{e.castShadow=t,e.receiveShadow=a})}const da=new Map,ha=new Map,pa=new w({color:16711935}),fa=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),pa;const n=JSON.stringify(e.material)+t?._id,o=i&&!("shaderGraph"===e.material.type&&"asset"===e.material.shaderGraph?.source);if(o&&da.has(n))return da.get(n);if(o&&ha.has(n))return await ha.get(n);const l=_materialFromAsset(n,e,t,a,s,r,o);return o?ha.set(n,l).get(n):l}export async function _materialFromAsset(e,t,a,s,r,n,l=!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 u(t.material.params?.color),transparent:null!=t.material.params?.opacity&&t.material.params?.opacity<1},d={};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 S({...c,...d});break;case"water":h=Mt(c,a);break;case"grassFoliage":h=yt({color:c.color,map:c.map},a);break;case"grass":h=wt({...c,colorTwo:new u(t.material.params.colorTwo),colorThree:new u(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=pa;break}"surface"===e.target&&null!=e.materialOptions?.side&&(p=sa(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=aa(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=pa}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:oa?$e:We,lambert:$e,unlit:Re,toon:Lt,layered:Wt,landscape:Fe,"landscape-composite":Ue,"decal-unlit":Bt,"decal-standard":Vt,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),fa.has(t.material.shader)||fa.set(t.material.shader,pa.clone()),h=fa.get(t.material.shader)}h.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),h=pa;break;default:throw new Error("Unsupported material type "+t.material.type)}if(a?.csm.setupMaterial(h),h.side=p??t.material.side??h.side??o.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=Oe[t.material.blending]??o.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 u(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,l&&null!=a&&da.set(e,h),l&&ha.delete(e),h}export function prepareCustomParamsFromShaderGraph(e,t={}){return Object.fromEntries((e.parameters??[]).map(e=>{const a=function(e){switch(e){case"float":return At.FloatNode;case"boolean":return At.BooleanNode;case"texture":return At.Sampler2DNode;case"vec2":return At.Vec2Node;case"vec3":return At.Vec3Node;case"vec4":return At.Vec4Node;case"color":return At.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?Wa(i):s?.value??Wa(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 ga(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:_e,toSerializedParamType:toSerializedParamType});for(const e of h)console.warn(`Skipping stored parameter "${e.key}" because it could not be converted from ${At[e.sourceType]} to ${At[e.targetType]}`);for(const[e,t]of Object.entries(d)){if(!1===t.override)continue;const c=await ga(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 ga(r,i,t,a,null,void 0,void 0,void 0,void 0,void 0);null!=e&&(s[r]=e)}return s}const ma=new Map;async function ga(e,t,a,s,r,i,n,o,l=t.value,c=t.type,h,p=(t.type===At.Struct?t.struct:void 0)){if(null==t||null==l||""===l)return null;switch(c){case At.Array:if(Array.isArray(l)&&"element"in t)return await Promise.all(l.map(l=>ga(e,t,a,s,r,i,n,o,l,t.element,h,t.elementStruct)));break;case At.Number:case At.FloatNode:let f;if("string"==typeof l?f=parseFloat(l):"number"==typeof l&&(f=l),c===At.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=ma.get(e);return null==t&&(t=Be(Tt.decode(e)),ma.set(e,t)),t}(e.easing),r=s.sample(Ve(ze.energy));return _(U(t),U(a),r)}return new ee(Ze(e),f,void 0,!1)}return f;case At.Texture:let m=await s.getTexture(await a.getAsset(l));return"envmap"===e.toLowerCase()&&null!=i&&(m=i.getEnvTexture(m)),m;case At.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 te(null,t,new ee(Ze(e)+"_i",a,void 0,!1))}const y=await s.getTexture(g);return y?Z(y):null;case At.Boolean:return l;case At.BooleanNode:return new K(Ze(e),l,void 0,!1);case At.Vector2:case At.Vec2Node:if("object"==typeof l){const t=l instanceof Array?(new P).fromArray(l):new P(l.x,l.y);return c===At.Vec2Node?new ae(Ze(e),t,void 0,!1):t}return null;case At.Vector3:case At.Vec3Node:if("object"==typeof l){const t=l instanceof Array?(new D).fromArray(l):new D(l.x,l.y,l.z);return c===At.Vec3Node?new se(Ze(e),t,void 0,!1):t}return null;case At.Vector4:case At.Vec4Node:if("object"==typeof l){const t=l instanceof Array?(new O).fromArray(l):new O(l.x,l.y,l.z,l.w);return c===At.Vec4Node?new re(Ze(e),t,void 0,!1):t}return null;case At.Color:case At.RgbNode:const w=new u(l);return c===At.RgbNode?new se(Ze(e),new D(w.r,w.g,w.b),void 0,!1).rgb:w;case At.String:return l;case At.Scene:return"string"==typeof l?new be(l):"object"==typeof l&&null!=l&&"string"==typeof l.id?new be(l.id,"string"==typeof l.name?l.name:void 0):null;case At.ModelRef:return"string"==typeof l?new ve(l):null;case At.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=h?h(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=h?h(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 At.Euler:const b=l;return(new d).fromArray(b);case At.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 At.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=da.get(t);if(null!=r)return r;const o=await prepareShaderGraphParameters({},e.shaderGraph,a,s,i,n),l=aa(e.shaderGraph,{parameters:o});return l.userData.assetId=e.id,da.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 At.AudioBuffer:return await s.getAudio(await a.getAsset(l));case At.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 ge(o,v);console.error("Using a non-vfx asset for visual effect parameter");break;case At.Prefab:{const e=await a.getAsset(l);return null==e?(console.error("Using a non-prefab asset for prefab parameter",l),null):new ye(e)}case At.PrefabActor:{const e=await a.getAsset(l);return null==e?(console.error("Using a non-prefab asset for prefab parameter",l),null):new we(new ye(e))}case At.DataAsset:return materializeDataAssetRef(l,a,s,r,i,n,o,h);case At.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 ea(e.sequence);console.error("Using a non-sequence asset for sequence parameter");break}case At.SequenceData:return Kt(l)?l:(console.warn("Invalid inline sequence data parameter value",l),null);case At.Struct:return async function(e,t,a,s,r,i,n,o,l){const c=ya(e),u=c?.struct??t;if(null==u)return console.warn("Missing parameter definition id for struct parameter"),null;const d=qe(u);if(null==d)return console.warn(`Unknown parameter definition "${u}"`),null;if(Ye(u))return console.warn(`Can not instantiate abstract parameter definition "${u}"`),null;if(null!=t&&u!==t&&!He(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=ya(e);if(null!=t)return t.value;if(wa(e))return e;if(null!=e&&"object"==typeof e&&wa(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,h);case At.Curve:return Tt.decode(l);case At.ColorLayer:case At.MaskLayer:if(Rt(l)){const e=await Nt.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 At.AnimationClip:{const e="string"==typeof l?l:"object"==typeof l&&null!=l?l.assetId:null;if(null==e)return console.warn("Invalid animation clip asset id value",l),null;return await s.getAnimationClip(await a.getAsset(e))}}return null}export async function materializeDataAssetRef(e,t,a,s,r,i,n,o){const l="string"==typeof e?e:null!=e&&"object"==typeof e?e.assetId??e.id:null;if(null==l||""===l)return null;const c=await t.getAsset(l);if(null==c)return console.warn(`Data asset "${l}" was not found`),null;if("data"!==c.type||null==c.dataAsset)return console.warn("Using a non-data asset for data asset parameter",l),null;const u=c.dataAsset.definition;if(null==u||""===u)return console.warn(`Missing data asset definition id for asset "${c.id}"`),null;if(Je(u))return console.warn(`Can not instantiate abstract data asset definition "${u}"`),null;const d=Ge(u);if(null==d)return console.warn(`Unknown data asset definition "${u}"`),null;let h;try{h=new d}catch(e){return console.warn(`Failed to instantiate data asset definition "${u}"`,e),null}const p=c.dataAsset.params??{};if("object"!=typeof p||Array.isArray(p))return console.warn(`Invalid data asset params for asset "${c.id}"`),null;try{const e=await prepareClassParameters(p,null,t,a,s,r,i,n,o,h);Object.assign(h,e)}catch(e){return console.warn(`Failed to materialize data asset "${c.id}"`,e),null}return new Se(c,h)}function ya(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.struct&&wa(e.value)?e:null}function wa(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&Object.values(e).every(e=>null!=e&&"object"==typeof e&&"type"in e)}function Sa(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 ba(){}const va=new WeakMap;function Ma(e,t){if(t)return e.userData.hologyEditorMatrixWorldAutoUpdate=!0,void e.traverse(e=>{const t=va.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=>{va.has(e)&&s.push(e)}),0!==s.length||a||s.push(e);for(const e of s)Aa(e);delete e.userData.hologyEditorMatrixWorldAutoUpdate}function Aa(e){const t=va.get(e);if(e.updateMatrix(),e.updateWorldMatrix(!0,!0),null==t){const t=new Map;e.traverse(e=>{t.set(e,e.matrixAutoUpdate)}),va.set(e,{updateMatrixWorld:e.updateMatrixWorld,matrixAutoUpdate:t})}e.traverse(e=>{e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!1}),e.updateMatrixWorld=ba}function xa(e,t=!1){return Array.isArray(e)?e.every(e=>xa(e,t)):t||!e.transparent&&!ja(e)}function ja(e){return e instanceof G&&(null!=e.uniforms[ia]||null!=e.uniforms.hology_scene_map)}function Ia(e){return"linear"===e.type?new h(new u(e.color),e.near??100,e.far??1e3):"density"===e.type?new p(e.color,e.density):void console.warn("Invalid fog type",e)}const Pa=new D,Da=new x,Oa=new D;new b({color:4229780});async function Ca(e,t,a,s){null==s&&(s=(new g).identity());const r=s.clone().multiply(Ea(e,new o.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 Ea(e,t){return null==e.position||null==e.rotation||null==e.scale?t.identity():t.compose((new D).fromArray(e.position),(new x).setFromEuler((new d).fromArray(e.rotation)),(new D).fromArray(e.scale))}export function toSerializedParamType(e){if(null==e)return;const t=e.constructor.prototype;return t instanceof Number||e===Number?At.Number:t instanceof W||"function"==typeof e.prototype.isFloat?At.FloatNode:t instanceof I||e===I||e.isTexture?At.Texture:t instanceof Ne||e===Ne||e===H||"function"==typeof e.prototype?.isSampler2D||!0===e.prototype?.isSampler2D?At.Sampler2DNode:t instanceof Boolean||e===Boolean?At.Boolean:t instanceof N?At.BooleanNode:t instanceof u||e==u?At.Color:t instanceof J||"function"==typeof e.prototype.isRgb?At.RgbNode:t instanceof P||e==P?At.Vector2:t instanceof ce||"function"==typeof e.prototype.isVec2?At.Vec2Node:t instanceof D||e==D?At.Vector3:t instanceof de||"function"==typeof e.prototype.isVec3?At.Vec3Node:t instanceof O||e==O?At.Vector4:t instanceof pe||"function"==typeof e.prototype.isVec4?At.Vec4Node:t instanceof String||e===String?At.String:t instanceof be||e===be?At.Scene:t instanceof ve||e===ve?At.ModelRef:t instanceof Me||e==Me||e.prototype instanceof Me||e.prototype==Me?At.BaseActor:t instanceof d||e==d?At.Euler:t instanceof M||e==M?At.Object3D:t instanceof m||e==m?At.Material:t instanceof AudioBuffer||e==AudioBuffer?At.AudioBuffer:t instanceof ge||e==ge?At.VisualEffect:t instanceof ye||e==ye?At.Prefab:t instanceof we||e==we?At.PrefabActor:t instanceof Se||e==Se?At.DataAsset:t instanceof Tt||e==Tt?At.Curve:t instanceof Nt||e==Nt?At.ColorLayer:t instanceof Ft||e==Ft?At.MaskLayer:t instanceof o.AnimationClip||e==o.AnimationClip?At.AnimationClip:t instanceof ea||e==ea?At.Sequence:"SequenceData"===e.name||e.prototype&&"tracks"in e.prototype?At.SequenceData:null!=Le(e)?At.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===At.Struct?Le(e.type):void 0;return!0===e.options.array?{type:At.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=ka(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 Kt(e)?{type:At.SequenceData}:void 0}(t);null!=a&&(e=a)}if(e.type!==At.Struct)return{typeInfo:e,value:t};const a=ya(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===At.Struct)return Ye(e.type)?{}:prepareCustomParamsFromType(e.type,{});return customParameterDefaultValueByType.get(a)}(e,a)),p=function(e,t){if(ka(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!==At.SequenceData||!Kt(e))return;return{type:At.SequenceData,value:e}}(n,h.typeInfo);i=function(e,t,a){if(e.type!==At.Struct||a?.type!==At.Struct||null==a.struct)return e;const s=t.struct??e.struct;if(null==s||a.struct===s||He(a.struct,s)||null==qe(a.struct))return{...e,struct:a.struct};return e}(h.typeInfo,r,p);const f=!1!==u||e.options.array?p?.value??function(e,t,a){if(!0===e.options.array)return a?Wa(t):[];return Wa(t)}(e,h.value,d):Wa(h.value),m=function(e,t,a){if(t.type===At.Struct){if(null!=t.struct&&Ye(t.struct))return a;const s=null!=t.struct?qe(t.struct):e.type;return null!=s&&wa(a)?prepareCustomParamsFromType(s,a):a}if(t.type!==At.Array||t.element!==At.Struct||!Array.isArray(a))return a;const s=null!=t.elementStruct?qe(t.elementStruct):e.type;return a.map(e=>{const a=ya(e),r=a?.struct??t.elementStruct;if(null!=r&&Ye(r))return e;const i=null!=a?qe(a.struct):s,n=a?.value??(wa(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 ka(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)&&"number"==typeof e.type&&"value"in e}function Ta(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 Ba(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 Va(e,t,a){if(!a||"prefab"!==t?.type||null==t.prefab)return e;const s=new Map((e.innerParams??[]).map(e=>[JSON.stringify(e.path),{path:e.path,params:{...e.params}}]));for(const e of t.prefab.innerParams??[]){const t=JSON.stringify(e.path),a=s.get(t);s.set(t,{path:e.path,params:{...a?.params??{},...$a(e.params)}})}return{...e,params:{...e.params??{},...$a(t.prefab.params)},innerParams:[...s.values()]}}function za(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=Na(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:Na(e.params??{},t.params??{},a.params??{}),innerParams:n}}function Na(e,t,a){const s={};for(const r of new Set([...Object.keys(e),...Object.keys(t),...Object.keys(a)]))JSON.stringify(a[r])!==JSON.stringify(e[r])?null!=a[r]&&(s[r]=a[r]):null!=t[r]&&(s[r]=t[r]);return s}function $a(e){return null==e?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>function(e){return!0===e?.override}(e)))}function Ua(e,t){return e.length>=t.length&&t.every((t,a)=>e[a]===t)}export function prepareCustomParamsFromType(e,t,a=null,s={}){const r=_e(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=Fa(e,t);void 0!==a&&(n[e.name]=a)}}return prepareCustomParams(r,t,n,s)}function Fa(e,t){return!0===e.options.array?Array.isArray(t)?t.map(t=>serializeCustomParameter(e.type,t)??t):[]:serializeCustomParameter(e.type,t)}function Wa(e){return null==e?e:Array.isArray(e)?e.map(e=>Wa(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 P:return t instanceof P?t.toArray():void a();case D:return t instanceof D?t.toArray():void a();case O:return t instanceof O?t.toArray():void a();case u:return t instanceof u?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new u(t).getHexString():void a();case String:return t;case d:return t instanceof d?t.toArray():void a();case ye:return t instanceof ye?t.asset?.id??null:void a();case Se:return t instanceof Se?t.id:"string"==typeof t?t:void a();case be:return t instanceof be?{id:t.id,...null!=t.name?{name:t.name}:{}}:void a();case ve:return t instanceof ve?t.id:"string"==typeof t?t:void a()}const s=Le(e);if(null!=s){const r=ya(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!=Le(a)&&Qe(a,e)?a:e}(e,t),n=Le(i),o=function(e,t){if(null==t)return null;if(wa(t))return t;if(null!=t&&"object"==typeof t&&wa(t.params))return t.params;if("object"!=typeof t)return;const a=_e(e),s={};for(const e of a){const a=t[e.name];if(void 0===a)continue;const r=Fa(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(Kt(t))return t}function Ra(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=>_a(e.materialId)),(t??[]).filter(e=>_a(e.materialId)),e=>e.name?`name:${e.name}`:`color:${e.color}`)}function _a(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[At.RgbNode,"#000000"],[At.Color,"#000000"],[At.String,""],[At.Scene,null],[At.ModelRef,null],[At.Vector4,[0,0,0,0]],[At.Vec4Node,[0,0,0,0]],[At.Vector3,[0,0,0]],[At.Vec3Node,[0,0,0]],[At.Vector2,[0,0]],[At.Vec2Node,[0,0]],[At.Euler,[0,0,0,"XYZ"]],[At.Array,[]],[At.DataAsset,null],[At.SequenceData,Xt()],[At.ColorLayer,$t],[At.MaskLayer,Ut]]);let Ga=new u;new u;function La(e){return null==e?.color?null:(Ga.set(e.color),"#"+Ga.getHexString())}function qa(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=La(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 y||e.isMesh||e instanceof o.SkinnedMesh||e.isSkinnedMesh)for(const t of tt(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 u))continue;const o=La(n),l=n.name;if(qa(n,t,e.userData["originalColor_"+i],e.userData["originalMaterialName_"+i])){const n=Ya(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=La(i),o=i.name;if(qa(i,t,e.userData.originalColor,e.userData.originalMaterialName)){const i=Ya(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 Ja=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 Ya(e,t){if(null==e||null==t||!function(e,t){return function(e){const t=[];for(const[a,s]of Object.entries(e))Ha(a,s)&&t.push(s);if(e instanceof o.ShaderMaterial)for(const[a,s]of Object.entries(e.uniforms))Ha(a,s.value)&&t.push(s.value);return t}(e).some(e=>e.flipY!==t)}(e,t))return e;let a=Ja.get(e);null==a&&(a=new Map,Ja.set(e,a));const s=a.get(t);if(null!=s)return s;const r=Qa(e);if(function(e,t){for(const a of Object.keys(e)){const s=e[a];Ha(a,s)&&(e[a]=Za(s,t))}}(r,t),r instanceof o.ShaderMaterial){for(const[e,a]of Object.entries(r.uniforms))Ha(e,a.value)&&(a.value=Za(a.value,t));r.uniformsNeedUpdate=!0}return r.needsUpdate=!0,a.set(t,r),r}function Qa(e){const t=e.clone();return t.userData={...e.userData??{}},t}function Ha(e,t){const a=t;return(t instanceof I||!0===a?.isTexture)&&!e.toLowerCase().includes("envmap")&&!0!==a.isCompressedTexture&&!0!==a.isCompressedArrayTexture}function Za(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 Xa(e,t){if(e instanceof o.ShaderMaterial&&t instanceof o.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof o.ShaderMaterial&&t instanceof o.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 Ka(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}function es(e,t){const a=rt(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&&rs(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 ts(e,t){const a=Cs(e,t);if(a.length===Object.keys(e.attributes).length)return e;const s=new c;s.name=e.name;const r=e.getIndex();null!=r&&s.setIndex(r);for(const t of a)s.setAttribute(t,ss(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 as=new WeakMap;function ss(e,t){return e.getAttribute(t)??function(e,t){if("uv"===t)return function(e){let t=as.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 o.Float32BufferAttribute(new Float32Array(2*a.count),2),as.set(e,t));return t}(e);throw new Error(`Unsupported synthetic batching geometry attribute: ${t}`)}(e,t)}function rs(e){return null!=e.getAttribute("position")}const is=new WeakMap,ns="hbat_",os=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 ls(e){let t=is.get(e);return null==t&&(t=function(e){let t=e.type;if(e instanceof G)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(ds(a))continue;const s=e.uniforms[a]?.value;ps(s)||(t+=`u:${a}:${Ss(s)};`)}return t+=us(e.vertexShader),t+=us(e.fragmentShader),t}(e);else if(e instanceof o.MeshStandardMaterial&&!(e instanceof o.MeshPhysicalMaterial)||(t+=e.id+""),(e instanceof o.MeshBasicMaterial||e instanceof o.MeshLambertMaterial||e instanceof b||e instanceof S)&&(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 b&&(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 o.MeshPhysicalMaterial&&(null!=e.sheenColorMap&&(t+="sc"+e.sheenColorMap?.id),null!=e.sheenRoughnessMap&&(t+="sr"+e.sheenRoughnessMap?.id)),(e instanceof w||e instanceof S)&&null!=e.specularMap&&(t+="s"+e.specularMap?.id),e instanceof o.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 Jt&&null!=e.heightMap&&(t+="h"+e.heightMap?.id),e instanceof o.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),is.set(e,t)),t}const cs=new Map;function us(e){return cs.has(e)||cs.set(e,`shader_${cs.size}`),cs.get(e)}function ds(e){return os.has(e)||e.startsWith("hology_")}function hs(e,t){return e instanceof G?e.uniforms[t]?.value:e[t]}function ps(e){return"number"==typeof e||e instanceof P||e instanceof D||e instanceof O||e instanceof u}function fs(e){return"number"==typeof e?1:e instanceof P?2:4}function ms(e,t){const a=e.replace(/[^A-Za-z0-9_]/g,"_");let s=ns+a;for(;t.has(s);)s=ns+s;return t.add(s),s}function gs(e,t){const a={};for(const[s,r]of Object.entries(e.uniforms))t.has(s)||(a[s]={value:r.value});return a}const ys=new WeakMap;let ws=1;function Ss(e){if(null==e)return"null";if(e instanceof I||!0===e?.isTexture)return`texture:${e.id}`;if(e instanceof o.Matrix3||e instanceof o.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=ys.get(e);return null==t&&(t=ws++,ys.set(e,t)),`object:${t}`}return String(e)}function bs(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 vs=new g,Ms=new d;function As(e,t){return Ms.copy(e),Ms.x*=-1,Ms.y*=-1,Ms.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(Ms.y*=-1,Ms.z*=-1),(new o.Matrix3).setFromMatrix4(vs.makeRotationFromEuler(Ms))}function xs(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 O;function Is(e,t){return e===t||null==e==(null==t)&&("number"==typeof e&&"number"==typeof t?e===t||isNaN(e)&&isNaN(t):e instanceof o.Color&&t instanceof o.Color?e.r===t.r&&e.g===t.g&&e.b===t.b:e instanceof P&&t instanceof P?e.x===t.x&&e.y===t.y:e instanceof D&&t instanceof D?e.x===t.x&&e.y===t.y&&e.z===t.z:e instanceof O&&t instanceof O&&(e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w))}function Ps(e){const t=[];for(const[a,s]of Object.entries(e))s instanceof ge?t.push(s):s instanceof je&&t.push(...Ps(s));return t}function Ds(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 Os=new WeakMap;function Cs(e,t){const a=Object.keys(e.attributes).filter(a=>Es(e,t,a));return!e.hasAttribute("uv")&&rs(e)&&Es(e,t,"uv")&&a.push("uv"),a}function Es(e,t,a){return"position"===a||("uv"===a?function(e){if(e instanceof G)return Ts(e,"uv");if(e instanceof o.ShaderMaterial)return Bs(e.vertexShader,"uv");if(e instanceof Jt&&null!=e.heightMap)return!0;return ks.some(t=>e[t]?.isTexture)}(t):t instanceof G?Ts(t,a):t instanceof o.ShaderMaterial?function(e,t){if("uv1"===t||"uv2"===t||"uv3"===t)return Bs(e.vertexShader,t);return!0}(t,a):"uv1"!==a&&(("color"!==a||!function(e){let t=Os.get(e);if(null!=t)return t;const a=e.getAttribute("color");if(null==a)t=!1;else{t=!0;for(let e=0;e<a.count;e++){for(let s=0;s<3;s++)if(1!==a.getComponent(e,s)){t=!1;break}if(!t)break}}return Os.set(e,t),t}(e))&&("uv2"!==a||(null!=t.lightMap||null!=t.aoMap))))}const ks=["map","alphaMap","emissiveMap","normalMap","bumpMap","displacementMap","roughnessMap","metalnessMap","aoMap","specularMap","gradientMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","iridescenceMap","iridescenceThicknessMap","sheenColorMap","sheenRoughnessMap","transmissionMap","thicknessMap","anisotropyMap"];function Ts(e,t){return Bs(e.vertexShader,t)}function Bs(e,t){return new RegExp(`(^|[^A-Za-z0-9_])${a=t,a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}([^A-Za-z0-9_]|$)`).test(e);var a}function Vs(e,t,a){if(t(e))return e;for(const s of e.children??[]){const e=Vs(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=>Vs(e,t,a));if(null!=e)return e}}return null}const zs=new D,Ns=new D,$s=new D,Us=new O,Fs=new O,Ws=new g,Rs=new g,_s=new v;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=Gs(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&&qs(e)&&e.removeFromParent()}(s),s}function Gs(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 g).multiplyMatrices(t.matrixWorld,e.skeleton.boneInverses[a]).elements)]));const r=a.getAttribute("position"),i=a.getAttribute("normal"),n=a.getAttribute("tangent");if(null!=r){for(let t=0;t<r.count;t++)zs.fromBufferAttribute(r,t),e.applyBoneTransform(t,zs),r.setXYZ(t,zs.x,zs.y,zs.z);r.needsUpdate=!0}if(null!=i||null!=n){const t=a.getAttribute("skinIndex"),s=a.getAttribute("skinWeight");if(null!=t&&null!=s){for(let a=0;a<t.count;a++)Ls(e,a,Rs),null!=i&&(Ns.fromBufferAttribute(i,a),_s.getNormalMatrix(Rs),Ns.applyMatrix3(_s).normalize(),i.setXYZ(a,Ns.x,Ns.y,Ns.z)),null!=n&&($s.fromBufferAttribute(n,a),$s.transformDirection(Rs),n.setXYZ(a,$s.x,$s.y,$s.z));null!=i&&(i.needsUpdate=!0),null!=n&&(n.needsUpdate=!0)}}a.deleteAttribute("skinIndex"),a.deleteAttribute("skinWeight"),a.computeBoundingBox(),a.computeBoundingSphere();const o=new y(a,e.material);return o.copy(e,!1),o.geometry=a,o.material=e.material,o.userData={...e.userData},o}function Ls(e,t,a){const s=e.geometry,r=s.getAttribute("skinIndex"),i=s.getAttribute("skinWeight"),n=e.skeleton;Us.fromBufferAttribute(r,t),Fs.fromBufferAttribute(i,t),a.identity().multiplyScalar(0);for(let e=0;e<4;e++){const t=Fs.getComponent(e);if(0===t)continue;const s=Us.getComponent(e);Ws.multiplyMatrices(n.bones[s].matrixWorld,n.boneInverses[s]);for(let e=0;e<16;e++)a.elements[e]+=Ws.elements[e]*t}return a.premultiply(e.bindMatrixInverse).multiply(e.bindMatrix),a}function qs(e){let t=!0;return e.traverse(a=>{a===e||a.isBone||(t=!1)}),t}function Js(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 Ys(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
|
*/
|