@hology/core 0.0.138 → 0.0.140

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{__decorate as e,__metadata as t}from"tslib";import{ConvexPolyhedronCollisionShape as a}from"@hology/core";import{Subject as s}from"rxjs";import*as r from"three";import{BoxGeometry as i,Color as n,Euler as o,Fog as l,FogExp2 as c,Group as h,Material as d,Matrix4 as p,Mesh as m,MeshLambertMaterial as u,MeshPhongMaterial as f,MeshStandardMaterial as g,Object3D as y,PointLight as w,Quaternion as b,Scene as v,Texture as A,Vector2 as S,Vector3 as M,Vector4 as j}from"three";import x,{SpriteRenderer as P}from"@hology/nebula";import{bool as I,BooleanNode as D,float as C,FloatNode as E,NodeShaderMaterial as V,rgb as O,RgbNode as N,Texture2dLookupNode as k,textureSampler2d as F,vec2 as T,Vec2Node as z,vec3 as _,Vec3Node as B,vec4 as L}from"three-shader-graph";import{Service as W}from"typedi";import{VfxActor as $}from"../effects/vfx/vfx-actor.js";import{VisualEffect as R}from"../effects/vfx/vfx-param.js";import{BaseActor as G}from"../gameplay/actors/actor.js";import U from"../gameplay/actors/builtin/index.js";import{PhysicsBodyType as H,ThreeBlendingMode as J,withInjectionContext as q}from"../gameplay/index.js";import{RenderingView as X}from"../rendering.js";import{Sampler2DNode as Y}from"../shader-nodes/index.js";import{LambertShader as Z}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as Q}from"../shader/builtin/landscape-composite-shader";import{LandscapeShader as K}from"../shader/builtin/landscape-shader.js";import{StandardShader as ee}from"../shader/builtin/standard-shader.js";import{UnlitShader as te}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as ae}from"../shader/parameter.js";import{ArrayMap as se,groupBy as re}from"../utils/collections.js";import{iterateMaterials as ie}from"../utils/materials.js";import{filterChildrenShallow as ne,filterSceneShallow as oe,findFirstVisibleObject as le}from"../utils/three/traverse.js";import{AssetMeshInstance as ce,AssetResourceLoader as he}from"./asset-resource-loader.js";import{isCollisionMesh as de}from"./collision/collision-shape-import.js";import{BoxCollisionShape as pe,PhysicalShapeMesh as me}from"./collision/collision-shape.js";import{LandscapeManager as ue}from"./landscape/landscape-manager.js";import{initLandscape as fe}from"./landscape/landscape.js";import{SectionGrid as ge,smoothNormalsCrossMeshes as ye}from"./landscape/utils.js";import{createGrassFoliageMaterial as we}from"./materials/grass-foliage.js";import{createGrassMaterial as be}from"./materials/grass.js";import{getMaterialAttribute as ve}from"./materials/utils/material-painting.js";import{createWaterMaterial as Ae}from"./materials/water.js";import{SerializedParamType as Se}from"./model.js";import{ShapeLibrary as Me,ShapeLibraryKeys as je}from"./objects/shapes.js";import{ambientLightName as xe,createSky as Pe,defaultSkyMaterial as Ie}from"./sky.js";import{Curve2 as De}from"../utils/curve.js";import{DecalUnlitShader as Ce}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as Ee}from"../shader/builtin/decal-standard-shader.js";import{ColorLayer as Ve,defaultValueColorLayer as Oe,defaultValueMaskLayer as Ne,MaskLayer as ke}from"../shader/color-layer.js";import{LayeredShader as Fe}from"../shader/builtin/layered-shader";import{isColorLayerSerialized as Te}from"../shader/color-layer";import{FogVolume as ze}from"../rendering/fog/fog-volume-actor.js";import{UnscaledSprite as _e}from"../utils/three/unscaled-sprite.js";import{ToonShader as Be}from"../shader/builtin/toon-shader.js";const Le={};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 We(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}let We=class{constructor(e,t,a,i,n,o,l,c){this.scene=e,this.dataProvider=t,this.assetsService=a,this.assetManagerService=i,this.renderingView=n,this.shaders=o,this.actorTypes=l,this.actorProvider=c,this.objectMap=new Map,this.sceneObjectMap=new Map,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.inEditor=!0,this.updated$=new s,this.removed$=new s,this.error$=new s,this.editorActorParamSnapshot=new Map,this.assets=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,this.pmremGeneratorResults=new WeakMap,this.prefabInstanceChain=[],this.geometryCache=new Map,this.collisionShapeCache=new Map,this.originalFog=null,t.onCreate(e=>this.update(e)),t.onUpdate(e=>this.update(e)),t.onRemove(e=>this.remove(e)),this.createAssetSubscription=a.onCreate.subscribe(e=>{this.assets.set(e.id,e)}),this.updateSubscription=a.onUpdate.subscribe(async t=>{this.assets.set(t.id,t),"material"==t.type?e.traverse(e=>{if(e instanceof r.Mesh)if(Array.isArray(e.material))for(let a=0;a<e.material.length;a++)this.refreshMaterial(e,e.material[a],t,a);else this.refreshMaterial(e,e.material,t)}):"mesh"==t.type?(this.findByAssetId(t.id).forEach(e=>{this.remove(e.userData.src),this.materializeAndInitActor(e.userData.src)}),this.landscapeManagers.forEach(e=>{const a=e.source?.grass?.layers?.some(e=>e.meshes.some(e=>e.assetId===t.id));a&&e.queueRefreshScatter(this.renderingView?.camera.position??new M,!0)})):"prefab"===t.type?this.findByAssetId(t.id).forEach(e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t)}):"vfx"===t.type&&this.dataProvider.getObjects().forEach(e=>{Ze(e,(e,a)=>{"vfx"===e.type&&e.assetId===t.id&&(this.remove(e),this.materializeAndInitActor(e))})})})}async refreshMaterial(e,t,a,s){const r=t?.userData?.assetId;if(r!==a.id){const e=this.assets.get(r);let t=!1;if(null!=e)for(const s of Object.values(e.material.shaderParams)){if(s.type===Se.Material&&s.value===a.id){t=!0;break}if(s.type===Se.Array&&"element"in s&&s.element===Se.Material&&s.value.includes(a.id)){t=!0;break}}if(!t)return}const i=await materialFromAsset(this.assets.get(r),this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1),n=i.userData;i.userData=t.userData,i.userData.hasBloom=n.hasBloom,i.userData.reflective=n.reflective,i.userData.outlineParameters=n.outlineParameters,null!=s?et(e.material[s],i)||(e.material[s]=i):et(e.material,i)||(e.material=i)}getTopLevelActors(){return Array.from(this.materializedActors.entries()).filter(([e,t])=>!e.includes("/")).map(([,e])=>e)}get actorInstances(){return Array.from(this.materializedActors.values())}async initTextures(){const e=[];if(await Promise.all(this.dataProvider.getObjects().filter(e=>"shape_mesh"===e.type||"asset_mesh"===e.type).filter(e=>null!=e.materialAssignments).flatMap(e=>e.materialAssignments).map(async t=>{const a=this.assets.get(t.materialId);if(null!=a)for(const t of Object.values(a.material.shaderParams))if(t.type===Se.Texture&&"string"==typeof t.value){const a=this.assets.get(t.value),s=await this.assetManagerService.getTexture(a);null!=s&&e.push(s)}})),0!==e.length){console.log(`Initializing ${e.length} textures`),console.time("Init textures");for(const t of e)this.renderingView.renderer.initTexture(t);console.timeEnd("Init textures")}}async prefetchAssets(){const e=Array.from(new Set(this.dataProvider.getObjects().filter(e=>null!=e.assetId&&"asset_mesh"==e.type).filter(e=>e.assetId)));await Promise.all(e.map(e=>this.assetsService.getAsset(e.assetId).then(e=>{if(null!=e)return this.assetManagerService.getMesh(e)}))),this.initTextures()}async init(){await this.preInit(),Re.clear(),await this.prefetchAssets(),await Promise.all(this.dataProvider.getObjects().map(e=>this.materialize(e))),await this.initActorsPostInit()}initActorsPostInit(e=this.getTopLevelActors(),t){const a=e.map(async e=>{const a=e.object.userData.src??e.object.userData._src;if("vfx"===a.type)return Promise.resolve();const s=await this.assetsService.getAsset(a.assetId),r={...s?.actor?.params??{},...a.actor?.params??{}},i=null!=t?new Map(Array.from(this.materializedActors.entries()).filter(([e,a])=>e.startsWith(t.sceneObjectChain.join("/"))&&e.split("/").length-1===t.sceneObjectChain.length).map(([e,t])=>[e.split("/").pop(),t])):this.materializedActors;for(const t of a.actor.innerParams??[])await this.applyActorComponentParams(e,t.path.slice(),t.params,i);const n=await prepareClassParameters(r,e.constructor,this.assetsService,this.assetManagerService,i,this.renderingView,this.shaders,this.actorProvider);Object.assign(e,n);try{return await this.actorProvider.initActor(e)}catch(e){console.error(`Failed to initiate actor (name="${a.name}", id=${a.id})`,e)}});return Promise.all(a)}addVfxChildActors(e,t=e){}async applyActorComponentParams(e,t,a,s){const r=t.length,i=t.shift();if(0==r){const t=await prepareClassParameters(a,null,this.assetsService,this.assetManagerService,s,this.renderingView,this.shaders);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!==H.dynamic&&"sky"!==e.type&&"global_fog"!==e.type&&"world_env"!==e.type}async canAssetBeInstanced(e){if(!this._canBeInstancedCache.has(e.assetId)){const t=await this.createFromAsset(e);if(null==t)return!1;const a=[];t.traverse(e=>{!de(e)&&e.isMesh&&a.push(e)});const s=1==a.length&&0==a[0].children.length,r=a[0]instanceof m&&null!=a[0].geometry.morphAttributes&&Object.keys(a[0].geometry.morphAttributes).length>0,i=!0;this._canBeInstancedCache.set(e.assetId,s&&i&&!r)}return this._canBeInstancedCache.get(e.assetId)}async preInit(){this.renderingView?.onLoop(()=>{null!=this.sky&&this.renderingView.camera.getWorldPosition(this.sky.position)}),this.assetsService.getAssets().then(e=>{for(const t of e)this.assets.set(t.id,t)})}shouldBeMaterialized(e){if(null!=this.detailTier&&"asset_mesh"===e.type&&null!=e.assetId){const t=this.assets.get(e.assetId);if(null!=t){const e=t.mesh?.detailTier;if(null!=e)return e<=this.detailTier}}return!0}async initWithInstancing(){await this.preInit(),await this.prefetchAssets();const e=[],t=new se,s=new se;for(const a of this.dataProvider.getObjects())await Ze(a,async(a,r,i)=>{if(!this.shouldBeMaterialized(a))return;const o="asset_mesh"==a.type&&this.canObjectBeInstanced(a)&&await this.canAssetBeInstanced(a),l="shape_mesh"===a.type&&"landscape"!==a.shape&&a.physics?.type!==H.dynamic;if(o||l){if(r&&r.children?.length>0){const e=r.children.findIndex(e=>e.id===a.id);e>=0&&r.children.splice(e,1)}if(l){let e=a.shape+JSON.stringify(a.shapeParams??{})+a.castShadow+a.receiveShadow;const t=a.materialAssignments?.at(0)?.materialId,r=null!=t?this.assets.get(t):null;let o=null;if(null!=r&&"shader"!==r.material.type){if(e+=r.material.type+r.material.shader,null!=r.material.shaderParams){if(e+=Object.entries(r.material.shaderParams).filter(([e,t])=>"color"!=e).map(e=>JSON.stringify(e)).join(),null!=r.material.shaderParams.color){const e=r.material.shaderParams.color;e.type===Se.Color&&null!=e.value&&(o=new n(e.value))}}}else e+=t;s.push(e,{object:{...a,parentTransform:i},color:o})}else{const e=a.assetId+JSON.stringify(a.materialAssignments??[]);t.push(e,{...a,parentTransform:i})}}else null==r&&e.push({...a,parentTransform:i})});for(const e of t.values()){if(0==e.length)continue;const t=await this.createFromAsset(e[0]);if(null==t)continue;const s=await this.createInstancedMesh(e,t),r=new ce;r.add(s),r.userData.src=e[0],t instanceof ce&&(r.collisionShapes=t.collisionShapes),r.collisionShapes.forEach(e=>{e instanceof a&&e.mesh instanceof m&&(e.mesh=e.mesh.geometry)}),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r)}for(const e of s.values()){if(0==e.length)continue;const t=e[0].object,a=await this.createFromShape(t),s=le(a,e=>!de(e)&&null!=e.geometry),i=s.material.clone();null!=e[0].color&&null!=i.color&&(i.color=new n(16777215));const l=s.geometry;let c,h;!(i instanceof V)?(c=new r.BatchedMesh(e.length,l.getAttribute("position").count,l.index.count,i),c.perObjectFrustumCulled=!0,h=c.addGeometry(l)):c=new r.InstancedMesh(l,i,e.length),c.castShadow=a.castShadow??!0,c.receiveShadow=s.receiveShadow??!0;for(let t=0;t<e.length;t++){const a=e[t],s=(new r.Matrix4).compose((new M).fromArray(a.object.position),(new b).setFromEuler((new o).fromArray(a.object.rotation)),(new M).fromArray(a.object.scale)),i=(new p).copy(a.object.parentTransform).multiply(s);let n;n=c instanceof r.BatchedMesh?c.addInstance(h):t,c.setMatrixAt(n,i),null!=a.color&&c.setColorAt(n,a.color)}for(let t=0;t<e.length;t++){const s=e[t],r=new ce;r.userData.src=e[0],a instanceof me&&(r.collisionShapes=[a.collisionShape]),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r),r.add(c),null==c.userData.hasCollision&&(c.userData.hasCollision=[]),c.userData.hasCollision[t]=!!s.object.collisionDetection}}await Promise.all(e.map(e=>this.materialize(e))),await this.initActorsPostInit()}async createInstancedMesh(e,t){const a=le(t,e=>!de(e)&&null!=e.geometry),s=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,Qe(e[0].materialAssignments,s.materialAssignments)),a.updateMatrix();const i=a.geometry.clone(),n=a.material;let l,c;if(!(n instanceof V)&&i.groups.length<2&&(!Array.isArray(n)||1==n.length)){const t=Array.isArray(n)?n[0]:n,a=i.getAttribute("position").count;l=new r.BatchedMesh(e.length,a,null!=i.index?i.index.count:a,t),l.perObjectFrustumCulled=!0,c=l.addGeometry(i)}else l=new r.InstancedMesh(i,n,e.length);for(let t=0;t<e.length;t++){let s=t;l instanceof r.BatchedMesh&&(s=l.addInstance(c));const i=(new r.Matrix4).compose((new M).fromArray(e[t].position),(new b).setFromEuler((new o).fromArray(e[t].rotation)),(new M).fromArray(e[t].scale)),n=(new p).copy(e[t].parentTransform).multiply(i).multiply(a.matrixWorld);l.setMatrixAt(s,n),null==l.userData.hasCollision&&(l.userData.hasCollision=[]),l.userData.hasCollision[t]=!!e[t].collisionDetection}if(l.castShadow=e[0].castShadow??s.castShadow??!0,l.receiveShadow=e[0].receiveShadow??s.receiveShadow??!0,a.material instanceof d&&l.castShadow&&l.receiveShadow)if(Array.isArray(n))for(const e of n)e.side=r.FrontSide;else n.side=r.FrontSide;return l}remove(e){if(console.log("Remove scene object",e),"global_fog"==e.type)return void(this.scene.fog=this.originalFog);if("world_env"===e.type)this.resetWorldEnv(),this.worldEnvObj=null;else if("actor"==e.type||"vfx"===e.type){const t=this.materializedActors.get(e.id);null!=t?(t.disposed.next(!0),t.onEndPlay()):console.warn("Failed to remove actor",e)}else"prefab"===e.type&&this.materializedActors.forEach((t,a)=>{a.startsWith(e.id)&&(t.disposed.next(!0),t.onEndPlay()),this.materializedActors.delete(a)});const t=this.sceneObjectMap.get(e.id);t?.parent.remove(t),this.sceneObjectMap.delete(e.id),this.components.filter(t=>t.object.userData.src?.id===e.id).forEach(e=>this.components.splice(this.components.indexOf(e,1))),this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>{e.clear(),e.stop(),this.landscapeManagers.splice(this.landscapeManagers.indexOf(e,1))}),this.removed$.next({object:t,source:e})}deleteSceneObject(e){const t=this.sceneObjectMap.get(e.id);if(this.scene.remove(t),"landscape"==e.type){const t=this.landscapeManagers.findIndex(t=>t.source.id===e.id);if(t>-1){const e=this.landscapeManagers.splice(t,1)[0];e.clear(),e.stop()}}}findByAssetId(e){return oe(this.scene,t=>t.userData.src?.assetId==e,e=>null!=e.userData.src)}applyMaterials(e,t){return null==t?Promise.resolve([]):Promise.all(t.filter(e=>"null"!==e.materialId).map(t=>this.applyMaterial(e,t)))}async applyMaterial(e,t){await applyMaterial(e,t,e=>{const t=this.assets.get(e);if(null!=t)try{return materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders)}catch(e){console.error("Failed to apply material",e)}},this._originalMaterials)}unapplyMaterials(e){e.traverse(async e=>{if(e instanceof 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(U));oe(this.scene,e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&!t.has(e.userData.src.actor.type)).forEach(async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)})}updateShaders(e){this.shaders=e;for(const[e,t]of Re.entries())t.userData.customShaderName&&Re.delete(e);this.landscapeManagers.forEach(t=>t.updateShaders(e)),oe(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=this.assets.get(e.material[t].userData.assetId);this.refreshMaterial(e,e.material[t],a,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=this.assets.get(e.material.userData.assetId);this.refreshMaterial(e,e.material,t)}}})})}async update(e){if("sky"===e.type&&null!=this.sky&&null!=this.sky.parent)return void this.updateSky(e);if("world_env"===e.type&&null!=this.worldEnvObj)return void this.updateWorldEnv(e);const t=this.sceneObjectMap.get(e.id);if(t){let s=!1;if(t.traverseAncestors(e=>{"_hology_transform_group"===e.name&&(s=!0)}),!s){const a=this.findParent(e);null!=a&&a.uuid!=t.uuid?a.attach(t):console.error("Parent is wrong")}if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(t);this.inEditor&&e.hidden&&!1?t.traverse(e=>{e instanceof m&&(e.material.wireframe=!0)}):t.traverse(e=>{e instanceof m&&(e.material.wireframe=!1)})}if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);Qe(e.materialAssignments,a.materialAssignments).forEach(e=>this.applyMaterial(t,e))}else"shape_mesh"===e.type&&this.applyMaterials(t,e.materialAssignments);if(s||(null!=e.position&&t.position.fromArray(e.position),null!=e.scale&&t.scale.fromArray(e.scale),null!=e.rotation&&t.rotation.fromArray(e.rotation)),this.applyVertexMaterials(e,t),"light"==e.type)if("point"==e.light.type){const a=t;a.color=new n(e.light.point.color),a.intensity=e.light.point.intensity,a.decay=e.light.point.decay,a.castShadow=e.light.point.castShadow,a.distance=Math.max(e.light.point.distance,0)}else if("spot"==e.light.type){const a=t;a.color=new n(e.light.spot.color),a.intensity=e.light.spot.intensity,a.decay=e.light.spot.decay,a.angle=e.light.spot.angle,a.penumbra=e.light.spot.penumbra,a.castShadow=e.light.spot.castShadow,a.distance=Math.max(e.light.spot.distance,0)}else"directional"===e.light.type?this.applyDirectionalLight(e.light.directional,e):"ambient"===e.light.type&&this.applyDirectionalAmbientLight(t,e.light.ambient,e);else if("landscape"===e.shape){const a=this.landscapeManagers.find(t=>t.source.id===e.id).source.landscape.options.density!==e.landscape.options.density;if(this.inEditor&&a){this.remove(e);const t=await this.materializeAndInitActor(e);return void this.updated$.next({object:t,source:e})}this.applyHeightMaps(t,e.landscape.heightMaps),this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(t=>{t.updateSource(e),t.queueRefreshScatter(this.renderingView.camera.position,!0,e=>!0)})}else if("global_fog"===e.type){const t=(this.scene.fog instanceof c?"density":"linear")!==e.fog.type;this.scene.fog=Xe(e.fog),t&&(a=this.scene).traverse(e=>{if(e instanceof m){const t=e.material;t instanceof V&&(a.fog instanceof l?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof c&&(t.uniforms.density={value:a.fog.density}),t.needsUpdate=!0,t.uniformsNeedUpdate=!0)}}),this.fixFogColor()}else if("actor"===e.type){if(this.materializedActors.has(e.id)){const t=this.materializedActors.get(e.id);if(t instanceof ze){const a=await prepareClassParameters(e.actor.params,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,[],this.actorProvider);return void Object.assign(t,a)}const a=this.editorActorParamSnapshot.get(e.id);null!=a&&a===JSON.stringify(e.actor)||s||(this.remove(e),await this.materializeAndInitActor(e))}}else if("shape_mesh"===e.type){const a=await this.createMeshByShape(e.shape,t.material,e.shapeParams);t instanceof me&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&$e(t,e.castShadow,e.receiveShadow),e.name&&e.name.length>0&&(t.name=e.name),this.updated$.next({object:t,source:e})}else{const t=await this.materializeAndInitActor(e);this.updated$.next({object:t,source:e})}var a;this.renderingView.renderer.shadowMap.needsUpdate=!0}async materializeAndInitActor(e,t=this.findParent(e)){const a=await this.materialize(e,t);return Ze(e,async e=>{if("actor"===e.type){const t=this.materializedActors.get(e.id);null!=t?await this.initActorsPostInit([t]):console.error(`Something went wrong when creating actor ${e.id}`)}}),a}findParent(e){const t=this.dataProvider.getObjects().flatMap(t=>t.id===e.id?null:ne(t,t=>t.children?.some(t=>t.id===e.id),()=>!0))[0];return null==t?this.scene:null!=t?oe(this.scene,e=>e.userData?.src?.id===t.id,e=>null!=e.userData?.src)[0]:void 0}fixFogColor(){!0===this.renderingView.options.enableOutlines&&(this.scene.fog.color=new n(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse(e=>{e instanceof 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=re(e.vertexMaterials,e=>e.m);t.traverse(e=>{if(e instanceof m){if(null==e.geometry)return;if(tt(ve(e,0,!1)),a>0){tt(ve(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=ve(s,0,!0);tt(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=ve(s,4,!0);tt(e);for(const t of i)e.setX(t.i,t.w[4]??0),e.setY(t.i,t.w[5]??0),e.setZ(t.i,t.w[6]??0),e.setW(t.i,t.w[7]??0),e.needsUpdate=!0,n=!0}n&&r.add(e)}this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,e=>r.has(e.name)))}async materialize(e,t,a=!1,s){if(!this.shouldBeMaterialized(e))return;let r,n;switch(e.type){case"asset_mesh":r=await this.createFromAsset(e);break;case"shape_mesh":r=await this.createFromShape(e);break;case"light":r=await this.createLight(e);break;case"particles":r=await this.createParticleSystem(e),e.collisionDetection=!1;break;case"global_fog":this.scene.fog=Xe(e.fog),this.fixFogColor(),r=new h;break;case"sky":this.sky=Pe(),this.updateSky(e),r=this.sky;break;case"world_env":this.updateWorldEnv(e),r=new h,this.worldEnvObj=r;break;case"actor":({object:r,actor:n}=await this.createFromActor(e,s));break;case"group":r=new h;break;case"prefab":r=await this.createFromPrefab(e,s);break;case"vfx":r=await this.createFromVfx(e,s);break;default:if(this.inEditor)throw new Error("unknown type "+e.type);console.warn(`Failed to materialize object. Unknown type '${e.type}'. This might be because the hology/core library is not compatible with the editor version.`)}if(null!=r){if(e.name&&e.name.length>0&&(r.name=e.name),null!=e.position&&r.position.fromArray(e.position),null!=e.scale&&r.scale.fromArray(e.scale),null!=e.rotation&&r.rotation.fromArray(e.rotation),a?r.userData._src=e:r.userData.src=e,null!=n&&(r.userData.actor=n),this.inEditor,this.inEditor){let e=null;r instanceof me&&(e=function(e){if(e instanceof pe)return new m(new i(...e.offset.toArray()),Ye);return null}(r.collisionShape)),null!=e&&(e.layers.disable(0),e.layers.enable(18),e.scale.multiplyScalar(1.1),r.add(e))}if(this.objectMap.set(r.uuid,e),this.sceneObjectMap.set(e.id,r),e.physics?.type!==H.dynamic||null==t||this.inEditor?null==t?this.scene.add(r):t?.add(r):(t.add(r),r.getWorldPosition(r.position),r.getWorldQuaternion(r.quaternion),r.getWorldScale(r.scale),this.scene?.attach(r)),null!=e.children&&await Promise.all(e.children?.map(e=>this.materialize(e,r,a))),this.inEditor||"asset_mesh"!=e.type&&"shape_mesh"!==e.type||"landscape"===e.shape||null!=e.physics?.type&&e.physics.type==H.dynamic||qe(r),null!=this.renderingView)return this.renderingView.renderer.shadowMap.needsUpdate=!0,r;console.warn("RenderingView not found in materializer. No idea what called this")}}updateWorldEnv(e){this.renderingView.aoPass.enabled=e.worldEnv.ao.enabled,this.renderingView.aoPass.blendIntensity=e.worldEnv.ao.blendIntensity,this.renderingView.aoPass.updateGtaoMaterial(e.worldEnv.ao),this.renderingView.aoPass.output=!0===e.worldEnv.ao.onlyAO?5:0;const t=e.worldEnv.toneMapping;null!=t&&(this.renderingView.renderer.toneMapping=t.mapping??0,this.renderingView.renderer.toneMappingExposure=t.exposure??1);const a=e.worldEnv.environment;null!=a&&null!=a.textureId?this.assetManagerService.getTexture(this.assets.get(a.textureId)).then(e=>{null==this.pmremGenerator&&(this.pmremGenerator=new r.PMREMGenerator(this.renderingView.renderer),this.pmremGenerator.compileEquirectangularShader()),this.pmremGeneratorResults.has(e)||this.pmremGeneratorResults.set(e,this.pmremGenerator.fromEquirectangular(e).texture);const t=this.pmremGeneratorResults.get(e);this.renderingView.scene.environment=t,this.renderingView.scene.environmentIntensity=a.intensity??1}):this.renderingView.scene.environment=null}resetWorldEnv(){this.renderingView.aoPass.enabled=!1,this.renderingView.aoPass.blendIntensity=1,this.renderingView.aoPass.output=0,this.renderingView.renderer.toneMapping=0,this.renderingView.renderer.toneMappingExposure=1}async updateSky(e){if(null==e?.sky?.materialId)return void(this.sky.material=Ie);const t=await this.assetsService.getAsset(e.sky.materialId),a=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);a.side=r.BackSide,(a instanceof g||a instanceof r.MeshBasicMaterial||a instanceof r.ShaderMaterial)&&(a.fog=!1),null!=this.sky?this.sky.material=a:console.warn("No sky has been created")}async createComponent(e,t,a,s){const r=new Le[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??U[e.actor?.type];if(null==a)return{object:null,actor:null};this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const s=await this.actorProvider.create(a,(new M).fromArray(e.position),(new o).fromArray(e.rotation),!0);return this.materializedActors.set(this.getNestedActorId(e.id,t),s),{object:s?.object,actor:s}}getNestedActorId(e,t){return null!=t?t.sceneObjectChain.join("/")+"/"+e:e}async createFromVfx(e,t){const a=await this.assetsService.getAsset(e.assetId);null==a&&console.error("Could not find asset",e);const s=await this.actorProvider.create($,(new M).fromArray(e.position),(new o).fromArray(e.rotation),!1);try{await s.fromAsset(a)}catch(e){return console.error("Failed to create VFX asset",e),null}return s.play(),this.materializedActors.set(this.getNestedActorId(e.id,t),s),null!=s&&(s.object.userData.actor=s),s?.object}async createFromShape(e){const t=this.inEditor&&e.hidden;let a;if("landscape"==e.shape)a=this.createLandscape(e),a.traverse(e=>{e instanceof m&&this._originalMaterials.set(e.id,e.material)});else{let s=new g({name:"Default",color:new n("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});const r=await this.createMeshByShape(e.shape,s,e.shapeParams);r.castShadow=e.castShadow??!0,r.receiveShadow=e.castShadow??!1,e.collisionDetection||(r.collisionShape=null),r.physics=e.physics,a=r,this._originalMaterials.set(a.id,r.material),a.traverse(e=>{})}return t||(await Promise.all((e.materialAssignments??[]).filter(e=>null!=e.materialId).map(e=>this.applyMaterial(a,e))),this.applyVertexMaterials(e,a)),a}createLandscape(e){const t=e.landscape?.options;if(null==t)return console.error(`No landscape options exist on scene object ${e.id} ${e.name}`),new h;const a=fe(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new ue(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 ge(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(()=>ye(r),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&je.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);if(!this.geometryCache.has(r)){const t=Me[e].geometry(s);t.computeTangents(),this.geometryCache.set(r,t)}this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,Me[e].collision(s));return new me(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){const t=await this.assetsService.getAsset(e.assetId);if(null==t)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);let{scene:a}=await this.assetManagerService.getMesh(t,{mergeGeomtries:!0});Qe(e.materialAssignments,t.materialAssignments).forEach(e=>this.applyMaterial(a,e));const s=e.receiveShadow??!!t.receiveShadow??!0,r=e.castShadow??!!t.castShadow??!1;return a.receiveShadow=s,$e(a,r,s),e.collisionDetection||(a.collisionShapes=[]),null!=e.physics&&!0!==this.inEditor&&(a.physics=e.physics),this.applyVertexMaterials(e,a),a.traverse(e=>{e instanceof m&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()}),a}async createFromPrefab(e,t){const a=await this.assetsService.getAsset(e.assetId);if(null==a)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);null==t&&(t={sceneObjectChain:[]}),t.sceneObjectChain.push(e.id);const{object:s}=await this.createFromPrefabAsset(a,t);return t.sceneObjectChain.pop(),s}async createFromPrefabAsset(e,t){const a=new h;await Promise.all(e.prefab.objects.filter(e=>"global_fog"!==e.type&&"world_env"!==e.type).map(e=>this.materialize(e,a,!0,structuredClone(t))));const s=t.sceneObjectChain.join("/"),r=Array.from(this.materializedActors.entries()).filter(([e,a])=>e.startsWith(s)&&e.split("/").length-1===t.sceneObjectChain.length).map(([,e])=>e);r.forEach(e=>{a.add(e.object)}),this.initActorsPostInit(r,structuredClone(t));const i=Array.from(this.materializedActors.entries()).filter(([e,t])=>e.startsWith(s)).map(([,e])=>e);return{object:a,actors:i}}async createParticleSystem(e){const t=await this.assetsService.getAsset(e.assetId),a=new y;return await x.fromJSONAsync(t.particleSystem,r).then(e=>{const t=new P(a,r);e.addRenderer(t),this.renderingView.onLoop(t=>e.update())}),a}async createLight(e){if("point"===e.light.type){const t=new w(e.light.point.color,e.light.point.intensity,e.light.point.distance,e.light.point.decay);if(t.castShadow=e.light.point.castShadow??!0,this.inEditor){const e=(new r.TextureLoader).load("assets/light-bulb-icon.webp"),a=new r.SpriteMaterial({map:e,alphaTest:.5}),s=new _e(a);s.scale.multiplyScalar(.6),t.add(s)}return t}if("spot"===e.light.type){const t=new r.SpotLight(e.light.spot.color,e.light.spot.intensity,e.light.spot.distance,e.light.spot.angle,e.light.spot.penumbra,e.light.spot.decay);if(t.castShadow=e.light.spot.castShadow??!0,t.target=new y,t.target.position.set(0,-1,0),t.add(t.target),this.inEditor){const e=(new r.TextureLoader).load("assets/light-bulb-icon.webp"),a=new r.SpriteMaterial({map:e,alphaTest:.5}),s=new _e(a);s.scale.multiplyScalar(.6),t.add(s),t.add(new r.SpotLightHelper(t))}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional,e),new h):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient,e),new h):void 0}applyDirectionalAmbientLight(e,t,a){const s=this.scene.children.find(e=>e.name===xe);null!=s?(s.intensity=t.intensity,s.color.set(t.color),s.groundColor.set(t.color),s.userData.src=a):console.warn("Couldn't find ambient light")}applyDirectionalLight(e,t){for(const a of this.renderingView.csm.lights)a.intensity=e.intensity,a.color.set(e.color),a.castShadow=e.castShadow,a.userData.src=t;this.renderingView.csm.lightDirection.fromArray(e.direction).normalize()}dispose(){this.updateSubscription.unsubscribe(),this.createAssetSubscription.unsubscribe(),this.materializedActors.forEach(e=>e.disposed.next(!0)),this.materializedActors.clear()}};We=e([W(),t("design:paramtypes",[v,Object,Object,he,X,Array,Array,Object])],We);export{We as SceneMaterializer};function $e(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse(e=>{e.castShadow=t,e.receiveShadow=a})}const Re=new Map,Ge=new Map,Ue=new u({color:16711935}),He=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){const n=JSON.stringify(e.material);return i&&Re.has(n)?Re.get(n):i&&Ge.has(n)?await Ge.get(n):Ge.set(n,_materialFromAsset(n,e,t,a,s,r,i)).get(n)}export async function _materialFromAsset(e,t,a,s,i,o,l=!0){const c={opacity:t.material.params.opacity,map:null,emissive:t.material.params.emissive??null,metalness:t.material.params.metalness??0,flatShading:t.material.params.flatShading??!1,color:new n(t.material.params.color),transparent:null!=t.material.params.opacity&&t.material.params.opacity<1},h={};if(null!=t.material.params.map){const e=t.material.params.map,a=await s.getAsset(e);null!=a&&(c.map=await i.getTexture(a))}let d;switch(t.material.type){case"phong":d=new f({...c,...h});break;case"water":d=Ae(c,a);break;case"grassFoliage":d=we({color:c.color,map:c.map},a);break;case"grass":d=be({...c,colorTwo:new n(t.material.params.colorTwo),colorThree:new n(t.material.params.colorThree)},a);break;case"standard":case"unlit":case"toon":case"layered":case"lambert":case"shader":case"landscape":case"landscape-composite":case"decal-unlit":case"decal-standard":const e={standard:ee,lambert:Z,unlit:te,toon:Be,layered:Fe,landscape:K,"landscape-composite":Q,"decal-unlit":Ce,"decal-standard":Ee}[t.material.type]??o.find(e=>e.name==t.material.shader)?.type;if(e){try{let r=new e;const n=await prepareClassParameters(t.material?.shaderParams??{},e,s,i,null,a,o);Object.assign(r,n),d=r.build()}catch(e){console.log("Shader runtime error: "+e),He.has(t.material.shader)||He.set(t.material.shader,Ue.clone()),d=He.get(t.material.shader)}d.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),d=Ue;break;default:throw new Error("Unsupported material type"+t.material.type)}return a?.csm.setupMaterial(d),null!=a&&Re.set(e,d),d.side=t.material.side??d.side??r.FrontSide,d.transparent=(t.material.transparent??c.transparent??!1)||d.transparent,d.alphaTest=t.material.alphaTest??d.alphaTest??0,null!=t.material.blending&&(d.blending=J[t.material.blending]??r.NormalBlending),t.material.bloom&&(d.userData.hasBloom=!0),t.material.reflective&&(d.userData.reflective=!0),!0===t.material.outlines&&(d.userData.outlineParameters={},null!=t.material.outlineParams&&(null!=t.material.outlineParams.color&&(d.userData.outlineParameters.color=new n(t.material.outlineParams.color).toArray()),null!=t.material.outlineParams.thickness&&(d.userData.outlineParameters.thickness=t.material.outlineParams.thickness))),d.userData.assetId=t.id,Ge.delete(e),d}export async function prepareClassParameters(e,t,a,s,r,i,n,o){const l={};for(const[t,c]of Object.entries(e)){const e=await Je(c,a,s,r,i,n,o);null!=e&&(l[t]=e)}return l}export async function prepareShapeParameters(e){const t={};for(const[a,s]of Object.entries(e)){const e=await Je(s,null,null,null);null!=e&&(t[a]=e)}return t}async function Je(e,t,a,s,r,i,l,c=e.value,h=e.type){if(null==e||null==c||""===c)return null;switch(h){case Se.Array:if(Array.isArray(c)&&"element"in e)return await Promise.all(c.map(n=>Je(e,t,a,s,r,i,l,n,e.element)));break;case Se.Number:case Se.FloatNode:let h="string"==typeof c?parseFloat(c):c;return e.type===Se.FloatNode?C(h):h;case Se.Texture:return await a.getTexture(await t.getAsset(c));case Se.Sampler2DNode:return F(await a.getTexture(await t.getAsset(c)));case Se.Boolean:return c;case Se.BooleanNode:return I(c);case Se.Vector2:case Se.Vec2Node:if("object"==typeof c){const t=c instanceof Array?(new S).fromArray(c):new S(c.x,c.y);return e.type===Se.Vec2Node?T(t):t}return null;case Se.Vector3:case Se.Vec3Node:if("object"==typeof c){const t=c instanceof Array?(new M).fromArray(c):new M(c.x,c.y,c.z);return e.type===Se.Vec3Node?_(t):t}return null;case Se.Color:case Se.RgbNode:const d=new n(c);return e.type===Se.RgbNode?O(d):d;case Se.String:return c;case Se.BaseActor:const p=c;return null==s&&console.warn("Class parameters can not be prepared as actors are not passed in"),s?.get(p);case Se.Euler:const m=c;return(new o).fromArray(m);case Se.Object3D:return(await a.getMesh(await t.getAsset(c))).scene;case Se.Material:return await materialFromAsset(await t.getAsset(c),r,t,a,i);case Se.AudioBuffer:return await a.getAudio(await t.getAsset(c));case Se.VisualEffect:const u=await t.getAsset(c);if(null==l){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in u)return new R(l,u);console.error("Using a non-vfx asset for visual effect parameter");break;case Se.Curve:return De.decode(c);case Se.ColorLayer:case Se.MaskLayer:if(Te(c)){const e=await Ve.decode(c,async e=>await a.getTexture(await t.getAsset(e))),s=await prepareClassParameters(c.params,null,t,a);return Object.assign(e,s),e}return console.warn("Expecting color layer but got",c),null}return null}function qe(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 Xe(e){return"linear"===e.type?new l(new n(e.color),e.near??100,e.far??1e3):"density"===e.type?new c(e.color,e.density):void console.warn("Invalid fog type",e)}const Ye=new g({color:4229780});async function Ze(e,t,a,s){null==s&&(s=(new p).identity()),await t(e,a,s);const i=s.clone().multiply(function(e,t){if(null==e.position||null==e.rotation||null==e.scale)return t.identity();return t.compose((new M).fromArray(e.position),(new b).setFromEuler((new o).fromArray(e.rotation)),(new M).fromArray(e.scale))}(e,new r.Matrix4));return Promise.all((e.children??[]).map(a=>Ze(a,t,e,i)))}export function toSerializedParamType(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?Se.Number:t instanceof E||"function"==typeof e.prototype.isFloat?Se.FloatNode:t instanceof A||e===A||e.isTexture?Se.Texture:t instanceof Y||e===k?Se.Sampler2DNode:t instanceof Boolean||e===Boolean?Se.Boolean:t instanceof D?Se.BooleanNode:t instanceof n||e==n?Se.Color:t instanceof N||"function"==typeof e.prototype.isRgb?Se.RgbNode:t instanceof S||e==S?Se.Vector2:t instanceof z||"function"==typeof e.prototype.isVec2?Se.Vec2Node:t instanceof M||e==M?Se.Vector3:t instanceof B||"function"==typeof e.prototype.isVec3?Se.Vec3Node:t instanceof String||e===String?Se.String:t instanceof G||e==G||e.prototype instanceof G||e.prototype==G?Se.BaseActor:t instanceof o||e==o?Se.Euler:t instanceof y||e==y?Se.Object3D:t instanceof d||e==d?Se.Material:t instanceof AudioBuffer||e==AudioBuffer?Se.AudioBuffer:t instanceof R||e==R?Se.VisualEffect:t instanceof De||e==De?Se.Curve:t instanceof Ve||e==Ve?Se.ColorLayer:t instanceof ke||e==ke?Se.MaskLayer:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function prepareCustomParams(e,t,a={}){return Object.fromEntries(e.map(e=>[e.name,{type:e.options.array?Se.Array:toSerializedParamType(e.type),...e.options.array?{element:toSerializedParamType(e.type)}:{},value:t[e.name]?.value??(!0!==e.options.array?a[e.name]??customParameterDefaultValueByType.get(toSerializedParamType(e.type)):[])}]))}export function prepareCustomParamsFromType(e,t,a=null){const s=ae(e);if(0===s.length)return{};let r;null!=a?q(a,()=>{r=a.get(e)}):r=new e;const i={};for(const e of s){const t=r[e.name];if(null!=t&&!0!==e.options.array){const a=serializeCustomParameter(e.type,t);null!=a&&(i[e.name]=a)}}return prepareCustomParams(s,t,i)}export function serializeCustomParameter(e,t){function a(){console.error("Failed to serialize value",{type:e,value:t})}switch(e){case Number:case Boolean:return t;case S:return t instanceof S?t.toArray():void a();case M:return t instanceof M?t.toArray():void a();case j:return t instanceof j?t.toArray():void a();case n:return t instanceof n?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new n(t).getHexString():void a();case String:return t;case o:return t instanceof o?t.toArray():void a()}}function Qe(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=>Ke(e.materialId)),(t??[]).filter(e=>Ke(e.materialId)),e=>e.color+e.name)}function Ke(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[Se.RgbNode,"#000000"],[Se.Color,"#000000"],[Se.Vector4,[0,0,0,0]],[Se.Vec4Node,[0,0,0,0]],[Se.Vector3,[0,0,0]],[Se.Vec3Node,[0,0,0]],[Se.Vector2,[0,0]],[Se.Vec2Node,[0,0]],[Se.Euler,[0,0,0,"XYZ"]],[Se.Array,[]],[Se.ColorLayer,Oe],[Se.MaskLayer,Ne]]);export function applyMaterial(e,t,a,s){const i=[];return e.traverse(async e=>{if(e instanceof m||e.isMesh||e instanceof r.SkinnedMesh||e.isSkinnedMesh)for(const t of ie(e.material))t.hasOwnProperty("color")&&i.push(e)}),Promise.all(i.map(async e=>{if(e.material instanceof Array)for(let r=0;r<e.material.length;r++){const i=e.material[r];if(null==i.color||!(i.color instanceof n))continue;const o="#"+i.color.getHexString(),l=i.name;if(o===t.color&&(i.name===t.name||null==t.name)||e.userData["originalColor_"+r]===t.color&&e.userData["originalMaterialName_"+r]===t.name){const i=await a(t.materialId),n=e.material[r];null!=i&&n.id!=i.id&&(e.material[r]=i,e.userData["originalColor_"+r]=e.userData["originalColor_"+r]??o,e.userData["originalMaterialName_"+r]=e.userData["originalMaterialName_"+r]??l,null!=s&&s.set(e.id+"#"+r,n))}}else if("color"in e.material){const r="#"+e.material.color.getHexString(),i=e.material.name;if(r===t.color&&(e.material.name===t.name||null==t.name)||e.userData.originalColor===t.color&&e.userData.originalName===t.name){const n=await a(t.materialId),o=e.material;null!=n&&(e.material=n,e.userData.originalColor=e.userData.originalColor??r,e.userData.originalMaterialName=e.userData.originalMaterialName??i,null!=s&&(s.has(e.id)||s.set(e.id,o)))}}}))}function et(e,t){if(e instanceof r.ShaderMaterial&&t instanceof r.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof r.ShaderMaterial&&t instanceof r.ShaderMaterial){for(const a in e.uniforms){if(null==t.uniforms[a])return!1;if(t.uniforms[a].value!==e.uniforms[a].value)return!1}return!0}return!1}(e,t)}return!1}function tt(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}/*
1
+ import{__decorate as e,__metadata as t}from"tslib";import{ConvexPolyhedronCollisionShape as a}from"@hology/core";import{Subject as s}from"rxjs";import*as r from"three";import{BoxGeometry as i,Color as n,Euler as o,Fog as l,FogExp2 as c,Group as h,Material as d,Matrix4 as m,Mesh as p,MeshLambertMaterial as u,MeshPhongMaterial as f,MeshStandardMaterial as g,Object3D as y,PointLight as w,Quaternion as v,Scene as b,Texture as A,Vector2 as S,Vector3 as M,Vector4 as j}from"three";import x,{SpriteRenderer as P}from"@hology/nebula";import{bool as I,BooleanNode as D,float as C,FloatNode as E,NodeShaderMaterial as V,rgb as O,RgbNode as N,Texture2dLookupNode as k,textureSampler2d as F,vec2 as T,Vec2Node as z,vec3 as _,Vec3Node as B,vec4 as L}from"three-shader-graph";import{Service as W}from"typedi";import{VfxActor as $}from"../effects/vfx/vfx-actor.js";import{VisualEffect as R}from"../effects/vfx/vfx-param.js";import{BaseActor as G}from"../gameplay/actors/actor.js";import U from"../gameplay/actors/builtin/index.js";import{PhysicsBodyType as H,ThreeBlendingMode as J,withInjectionContext as q}from"../gameplay/index.js";import{RenderingView as X}from"../rendering.js";import{Sampler2DNode as Y}from"../shader-nodes/index.js";import{LambertShader as Z}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as Q}from"../shader/builtin/landscape-composite-shader";import{LandscapeShader as K}from"../shader/builtin/landscape-shader.js";import{StandardShader as ee}from"../shader/builtin/standard-shader.js";import{UnlitShader as te}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as ae}from"../shader/parameter.js";import{ArrayMap as se,groupBy as re}from"../utils/collections.js";import{iterateMaterials as ie}from"../utils/materials.js";import{filterChildrenShallow as ne,filterSceneShallow as oe,findFirstVisibleObject as le}from"../utils/three/traverse.js";import{AssetMeshInstance as ce,AssetResourceLoader as he}from"./asset-resource-loader.js";import{isCollisionMesh as de}from"./collision/collision-shape-import.js";import{BoxCollisionShape as me,PhysicalShapeMesh as pe}from"./collision/collision-shape.js";import{LandscapeManager as ue}from"./landscape/landscape-manager.js";import{initLandscape as fe}from"./landscape/landscape.js";import{SectionGrid as ge,smoothNormalsCrossMeshes as ye}from"./landscape/utils.js";import{createGrassFoliageMaterial as we}from"./materials/grass-foliage.js";import{createGrassMaterial as ve}from"./materials/grass.js";import{getMaterialAttribute as be}from"./materials/utils/material-painting.js";import{createWaterMaterial as Ae}from"./materials/water.js";import{SerializedParamType as Se}from"./model.js";import{ShapeLibrary as Me,ShapeLibraryKeys as je}from"./objects/shapes.js";import{ambientLightName as xe,createSky as Pe,defaultSkyMaterial as Ie}from"./sky.js";import{Curve2 as De}from"../utils/curve.js";import{DecalUnlitShader as Ce}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as Ee}from"../shader/builtin/decal-standard-shader.js";import{ColorLayer as Ve,defaultValueColorLayer as Oe,defaultValueMaskLayer as Ne,MaskLayer as ke}from"../shader/color-layer.js";import{LayeredShader as Fe}from"../shader/builtin/layered-shader";import{isColorLayerSerialized as Te}from"../shader/color-layer";import{FogVolume as ze}from"../rendering/fog/fog-volume-actor.js";import{UnscaledSprite as _e}from"../utils/three/unscaled-sprite.js";import{ToonShader as Be}from"../shader/builtin/toon-shader.js";const Le={};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 We(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}let We=class{constructor(e,t,a,i,n,o,l,c){this.scene=e,this.dataProvider=t,this.assetsService=a,this.assetManagerService=i,this.renderingView=n,this.shaders=o,this.actorTypes=l,this.actorProvider=c,this.objectMap=new Map,this.sceneObjectMap=new Map,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.inEditor=!0,this.updated$=new s,this.removed$=new s,this.error$=new s,this.editorActorParamSnapshot=new Map,this.assets=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,this.pmremGeneratorResults=new WeakMap,this.prefabInstanceChain=[],this.geometryCache=new Map,this.collisionShapeCache=new Map,this.originalFog=null,t.onCreate(e=>this.update(e)),t.onUpdate(e=>this.update(e)),t.onRemove(e=>this.remove(e)),this.createAssetSubscription=a.onCreate.subscribe(e=>{this.assets.set(e.id,e)}),this.updateSubscription=a.onUpdate.subscribe(async t=>{this.assets.set(t.id,t),"material"==t.type?e.traverse(e=>{if(e instanceof r.Mesh)if(Array.isArray(e.material))for(let a=0;a<e.material.length;a++)this.refreshMaterial(e,e.material[a],t,a);else this.refreshMaterial(e,e.material,t)}):"mesh"==t.type?(this.findByAssetId(t.id).forEach(e=>{this.remove(e.userData.src),this.materializeAndInitActor(e.userData.src)}),this.landscapeManagers.forEach(e=>{const a=e.source?.grass?.layers?.some(e=>e.meshes.some(e=>e.assetId===t.id));a&&e.queueRefreshScatter(this.renderingView?.camera.position??new M,!0)})):"prefab"===t.type?this.findByAssetId(t.id).forEach(e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t)}):"vfx"===t.type&&this.dataProvider.getObjects().forEach(e=>{Ze(e,(e,a)=>{"vfx"===e.type&&e.assetId===t.id&&(this.remove(e),this.materializeAndInitActor(e))})})})}async refreshMaterial(e,t,a,s){const r=t?.userData?.assetId;if(r!==a.id){const e=this.assets.get(r);let t=!1;if(null!=e)for(const s of Object.values(e.material.shaderParams)){if(s.type===Se.Material&&s.value===a.id){t=!0;break}if(s.type===Se.Array&&"element"in s&&s.element===Se.Material&&s.value.includes(a.id)){t=!0;break}}if(!t)return}const i=await materialFromAsset(this.assets.get(r),this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1),n=i.userData;i.userData=t.userData,i.userData.hasBloom=n.hasBloom,i.userData.reflective=n.reflective,i.userData.outlineParameters=n.outlineParameters,null!=s?et(e.material[s],i)||(e.material[s]=i):et(e.material,i)||(e.material=i)}getTopLevelActors(){return Array.from(this.materializedActors.entries()).filter(([e,t])=>!e.includes("/")).map(([,e])=>e)}get actorInstances(){return Array.from(this.materializedActors.values())}async initTextures(){const e=[];if(await Promise.all(this.dataProvider.getObjects().filter(e=>"shape_mesh"===e.type||"asset_mesh"===e.type).filter(e=>null!=e.materialAssignments).flatMap(e=>e.materialAssignments).map(async t=>{const a=this.assets.get(t.materialId);if(null!=a)for(const t of Object.values(a.material.shaderParams))if(t.type===Se.Texture&&"string"==typeof t.value){const a=this.assets.get(t.value),s=await this.assetManagerService.getTexture(a);null!=s&&e.push(s)}})),0!==e.length&&this.renderingView){console.log(`Initializing ${e.length} textures`),console.time("Init textures");for(const t of e)this.renderingView.renderer.initTexture(t);console.timeEnd("Init textures")}}async prefetchAssets(){const e=Array.from(new Set(this.dataProvider.getObjects().filter(e=>null!=e.assetId&&"asset_mesh"==e.type).filter(e=>e.assetId)));await Promise.all(e.map(e=>this.assetsService.getAsset(e.assetId).then(e=>{if(null!=e)return this.assetManagerService.getMesh(e)}))),this.initTextures()}async init(){await this.preInit(),Re.clear(),await this.prefetchAssets(),await Promise.all(this.dataProvider.getObjects().map(e=>this.materialize(e))),await this.initActorsPostInit()}initActorsPostInit(e=this.getTopLevelActors(),t){const a=e.map(async e=>{const a=e.object.userData.src??e.object.userData._src;if("vfx"===a.type)return Promise.resolve();const s=await this.assetsService.getAsset(a.assetId),r={...s?.actor?.params??{},...a.actor?.params??{}},i=null!=t?new Map(Array.from(this.materializedActors.entries()).filter(([e,a])=>e.startsWith(t.sceneObjectChain.join("/"))&&e.split("/").length-1===t.sceneObjectChain.length).map(([e,t])=>[e.split("/").pop(),t])):this.materializedActors;for(const t of a.actor.innerParams??[])await this.applyActorComponentParams(e,t.path.slice(),t.params,i);const n=await prepareClassParameters(r,e.constructor,this.assetsService,this.assetManagerService,i,this.renderingView,this.shaders,this.actorProvider);Object.assign(e,n);try{return await this.actorProvider.initActor(e)}catch(e){console.error(`Failed to initiate actor (name="${a.name}", id=${a.id})`,e)}});return Promise.all(a)}addVfxChildActors(e,t=e){}async applyActorComponentParams(e,t,a,s){const r=t.length,i=t.shift();if(0==r){const t=await prepareClassParameters(a,null,this.assetsService,this.assetManagerService,s,this.renderingView,this.shaders);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!==H.dynamic&&"sky"!==e.type&&"global_fog"!==e.type&&"world_env"!==e.type}async canAssetBeInstanced(e){if(!this._canBeInstancedCache.has(e.assetId)){const t=await this.createFromAsset(e);if(null==t)return!1;const a=[];t.traverse(e=>{!de(e)&&e.isMesh&&a.push(e)});const s=1==a.length&&0==a[0].children.length,r=a[0]instanceof p&&null!=a[0].geometry.morphAttributes&&Object.keys(a[0].geometry.morphAttributes).length>0,i=!0;this._canBeInstancedCache.set(e.assetId,s&&i&&!r)}return this._canBeInstancedCache.get(e.assetId)}async preInit(){this.renderingView?.onLoop(()=>{null!=this.sky&&this.renderingView.camera.getWorldPosition(this.sky.position)}),this.assetsService.getAssets().then(e=>{for(const t of e)this.assets.set(t.id,t)})}shouldBeMaterialized(e){if(null!=this.detailTier&&"asset_mesh"===e.type&&null!=e.assetId){const t=this.assets.get(e.assetId);if(null!=t){const e=t.mesh?.detailTier;if(null!=e)return e<=this.detailTier}}return!0}async initWithInstancing(){await this.preInit(),await this.prefetchAssets();const e=[],t=new se,s=new se;for(const a of this.dataProvider.getObjects())await Ze(a,async(a,r,i)=>{if(!this.shouldBeMaterialized(a))return;const o="asset_mesh"==a.type&&this.canObjectBeInstanced(a)&&await this.canAssetBeInstanced(a),l="shape_mesh"===a.type&&"landscape"!==a.shape&&a.physics?.type!==H.dynamic;if(o||l){if(r&&r.children?.length>0){const e=r.children.findIndex(e=>e.id===a.id);e>=0&&r.children.splice(e,1)}if(l){let e=a.shape+JSON.stringify(a.shapeParams??{})+a.castShadow+a.receiveShadow;const t=a.materialAssignments?.at(0)?.materialId,r=null!=t?this.assets.get(t):null;let o=null;if(null!=r&&"shader"!==r.material.type){if(e+=r.material.type+r.material.shader,null!=r.material.shaderParams){if(e+=Object.entries(r.material.shaderParams).filter(([e,t])=>"color"!=e).map(e=>JSON.stringify(e)).join(),null!=r.material.shaderParams.color){const e=r.material.shaderParams.color;e.type===Se.Color&&null!=e.value&&(o=new n(e.value))}}}else e+=t;s.push(e,{object:{...a,parentTransform:i},color:o})}else{const e=a.assetId+JSON.stringify(a.materialAssignments??[]);t.push(e,{...a,parentTransform:i})}}else null==r&&e.push({...a,parentTransform:i})});for(const e of t.values()){if(0==e.length)continue;const t=await this.createFromAsset(e[0]);if(null==t)continue;const s=await this.createInstancedMesh(e,t),r=new ce;r.add(s),r.userData.src=e[0],t instanceof ce&&(r.collisionShapes=t.collisionShapes),r.collisionShapes.forEach(e=>{e instanceof a&&e.mesh instanceof p&&(e.mesh=e.mesh.geometry)}),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r)}for(const e of s.values()){if(0==e.length)continue;const t=e[0].object,a=await this.createFromShape(t),s=le(a,e=>!de(e)&&null!=e.geometry),i=s.material.clone();null!=e[0].color&&null!=i.color&&(i.color=new n(16777215));const l=s.geometry;let c,h;!(i instanceof V)?(c=new r.BatchedMesh(e.length,l.getAttribute("position").count,l.index.count,i),c.perObjectFrustumCulled=!0,h=c.addGeometry(l)):c=new r.InstancedMesh(l,i,e.length),c.castShadow=a.castShadow??!0,c.receiveShadow=s.receiveShadow??!0;for(let t=0;t<e.length;t++){const a=e[t],s=(new r.Matrix4).compose((new M).fromArray(a.object.position),(new v).setFromEuler((new o).fromArray(a.object.rotation)),(new M).fromArray(a.object.scale)),i=(new m).copy(a.object.parentTransform).multiply(s);let n;n=c instanceof r.BatchedMesh?c.addInstance(h):t,c.setMatrixAt(n,i),null!=a.color&&c.setColorAt(n,a.color)}for(let t=0;t<e.length;t++){const s=e[t],r=new ce;r.userData.src=e[0],a instanceof pe&&(r.collisionShapes=[a.collisionShape]),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r),r.add(c),null==c.userData.hasCollision&&(c.userData.hasCollision=[]),c.userData.hasCollision[t]=!!s.object.collisionDetection}}await Promise.all(e.map(e=>this.materialize(e))),await this.initActorsPostInit()}async createInstancedMesh(e,t){const a=le(t,e=>!de(e)&&null!=e.geometry),s=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,Qe(e[0].materialAssignments,s.materialAssignments)),a.updateMatrix();const i=a.geometry.clone(),n=a.material;let l,c;if(!(n instanceof V)&&i.groups.length<2&&(!Array.isArray(n)||1==n.length)){const t=Array.isArray(n)?n[0]:n,a=i.getAttribute("position").count;l=new r.BatchedMesh(e.length,a,null!=i.index?i.index.count:a,t),l.perObjectFrustumCulled=!0,c=l.addGeometry(i)}else l=new r.InstancedMesh(i,n,e.length);for(let t=0;t<e.length;t++){let s=t;l instanceof r.BatchedMesh&&(s=l.addInstance(c));const i=(new r.Matrix4).compose((new M).fromArray(e[t].position),(new v).setFromEuler((new o).fromArray(e[t].rotation)),(new M).fromArray(e[t].scale)),n=(new m).copy(e[t].parentTransform).multiply(i).multiply(a.matrixWorld);l.setMatrixAt(s,n),null==l.userData.hasCollision&&(l.userData.hasCollision=[]),l.userData.hasCollision[t]=!!e[t].collisionDetection}if(l.castShadow=e[0].castShadow??s.castShadow??!0,l.receiveShadow=e[0].receiveShadow??s.receiveShadow??!0,a.material instanceof d&&l.castShadow&&l.receiveShadow)if(Array.isArray(n))for(const e of n)e.side=r.FrontSide;else n.side=r.FrontSide;return l}remove(e){if(console.log("Remove scene object",e),"global_fog"==e.type)return void(this.scene.fog=this.originalFog);if("world_env"===e.type)this.resetWorldEnv(),this.worldEnvObj=null;else if("actor"==e.type||"vfx"===e.type){const t=this.materializedActors.get(e.id);null!=t?(t.disposed.next(!0),t.onEndPlay()):console.warn("Failed to remove actor",e)}else"prefab"===e.type&&this.materializedActors.forEach((t,a)=>{a.startsWith(e.id)&&(t.disposed.next(!0),t.onEndPlay()),this.materializedActors.delete(a)});const t=this.sceneObjectMap.get(e.id);t?.parent.remove(t),this.sceneObjectMap.delete(e.id),this.components.filter(t=>t.object.userData.src?.id===e.id).forEach(e=>this.components.splice(this.components.indexOf(e,1))),this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>{e.clear(),e.stop(),this.landscapeManagers.splice(this.landscapeManagers.indexOf(e,1))}),this.removed$.next({object:t,source:e})}deleteSceneObject(e){const t=this.sceneObjectMap.get(e.id);if(this.scene.remove(t),"landscape"==e.type){const t=this.landscapeManagers.findIndex(t=>t.source.id===e.id);if(t>-1){const e=this.landscapeManagers.splice(t,1)[0];e.clear(),e.stop()}}}findByAssetId(e){return oe(this.scene,t=>t.userData.src?.assetId==e,e=>null!=e.userData.src)}applyMaterials(e,t){return null==t?Promise.resolve([]):Promise.all(t.filter(e=>"null"!==e.materialId).map(t=>this.applyMaterial(e,t)))}async applyMaterial(e,t){await applyMaterial(e,t,e=>{const t=this.assets.get(e);if(null!=t)try{return materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders)}catch(e){console.error("Failed to apply material",e)}},this._originalMaterials)}unapplyMaterials(e){e.traverse(async e=>{if(e instanceof p)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(U));oe(this.scene,e=>e.userData.src?.id&&"actor"===e.userData.src.type&&this.materializedActors.has(e.userData.src?.id)&&!t.has(e.userData.src.actor.type)).forEach(async e=>{this.remove(e.userData.src),await this.materializeAndInitActor(e.userData.src)})}updateShaders(e){this.shaders=e;for(const[e,t]of Re.entries())t.userData.customShaderName&&Re.delete(e);this.landscapeManagers.forEach(t=>t.updateShaders(e)),oe(this.scene,e=>!0).forEach(e=>{e.traverse(async e=>{if(e instanceof p)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++){const a=e.material[t].userData?.customShaderName;if(null!=a){const a=this.assets.get(e.material[t].userData.assetId);this.refreshMaterial(e,e.material[t],a,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=this.assets.get(e.material.userData.assetId);this.refreshMaterial(e,e.material,t)}}})})}async update(e){if("sky"===e.type&&null!=this.sky&&null!=this.sky.parent)return void this.updateSky(e);if("world_env"===e.type&&null!=this.worldEnvObj)return void this.updateWorldEnv(e);const t=this.sceneObjectMap.get(e.id);if(t){let s=!1;if(t.traverseAncestors(e=>{"_hology_transform_group"===e.name&&(s=!0)}),!s){const a=this.findParent(e);null!=a&&a.uuid!=t.uuid?a.attach(t):console.error("Parent is wrong")}if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(t);this.inEditor&&e.hidden&&!1?t.traverse(e=>{e instanceof p&&(e.material.wireframe=!0)}):t.traverse(e=>{e instanceof p&&(e.material.wireframe=!1)})}if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);Qe(e.materialAssignments,a.materialAssignments).forEach(e=>this.applyMaterial(t,e))}else"shape_mesh"===e.type&&this.applyMaterials(t,e.materialAssignments);if(s||(null!=e.position&&t.position.fromArray(e.position),null!=e.scale&&t.scale.fromArray(e.scale),null!=e.rotation&&t.rotation.fromArray(e.rotation)),this.applyVertexMaterials(e,t),"light"==e.type)if("point"==e.light.type){const a=t;a.color=new n(e.light.point.color),a.intensity=e.light.point.intensity,a.decay=e.light.point.decay,a.castShadow=e.light.point.castShadow,a.distance=Math.max(e.light.point.distance,0),a.userData.volumetricIntensity=e.light.point.volumetricIntensity}else if("spot"==e.light.type){const a=t;a.color=new n(e.light.spot.color),a.intensity=e.light.spot.intensity,a.decay=e.light.spot.decay,a.angle=e.light.spot.angle,a.penumbra=e.light.spot.penumbra,a.castShadow=e.light.spot.castShadow,a.distance=Math.max(e.light.spot.distance,0),a.userData.volumetricIntensity=e.light.spot.volumetricIntensity}else"directional"===e.light.type?this.applyDirectionalLight(e.light.directional,e):"ambient"===e.light.type&&this.applyDirectionalAmbientLight(t,e.light.ambient,e);else if("landscape"===e.shape){const a=this.landscapeManagers.find(t=>t.source.id===e.id).source.landscape.options.density!==e.landscape.options.density;if(this.inEditor&&a){this.remove(e);const t=await this.materializeAndInitActor(e);return void this.updated$.next({object:t,source:e})}this.applyHeightMaps(t,e.landscape.heightMaps),this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(t=>{t.updateSource(e),t.queueRefreshScatter(this.renderingView.camera.position,!0,e=>!0)})}else if("global_fog"===e.type){const t=(this.scene.fog instanceof c?"density":"linear")!==e.fog.type;this.scene.fog=Xe(e.fog),t&&(a=this.scene).traverse(e=>{if(e instanceof p){const t=e.material;t instanceof V&&(a.fog instanceof l?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof c&&(t.uniforms.density={value:a.fog.density}),t.needsUpdate=!0,t.uniformsNeedUpdate=!0)}}),this.fixFogColor()}else if("actor"===e.type){if(this.materializedActors.has(e.id)){const t=this.materializedActors.get(e.id);if(t instanceof ze){const a=await prepareClassParameters(e.actor.params,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,[],this.actorProvider);return void Object.assign(t,a)}const a=this.editorActorParamSnapshot.get(e.id);null!=a&&a===JSON.stringify(e.actor)||s||(this.remove(e),await this.materializeAndInitActor(e))}}else if("shape_mesh"===e.type){const a=await this.createMeshByShape(e.shape,t.material,e.shapeParams);t instanceof pe&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&$e(t,e.castShadow,e.receiveShadow),e.name&&e.name.length>0&&(t.name=e.name),this.updated$.next({object:t,source:e})}else{const t=await this.materializeAndInitActor(e);this.updated$.next({object:t,source:e})}var a;this.renderingView.renderer.shadowMap.needsUpdate=!0}async materializeAndInitActor(e,t=this.findParent(e)){const a=await this.materialize(e,t);return Ze(e,async e=>{if("actor"===e.type){const t=this.materializedActors.get(e.id);null!=t?await this.initActorsPostInit([t]):console.error(`Something went wrong when creating actor ${e.id}`)}}),a}findParent(e){const t=this.dataProvider.getObjects().flatMap(t=>t.id===e.id?null:ne(t,t=>t.children?.some(t=>t.id===e.id),()=>!0))[0];return null==t?this.scene:null!=t?oe(this.scene,e=>e.userData?.src?.id===t.id,e=>null!=e.userData?.src)[0]:void 0}fixFogColor(){!0===this.renderingView.options.enableOutlines&&(this.scene.fog.color=new n(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse(e=>{e instanceof p&&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=re(e.vertexMaterials,e=>e.m);t.traverse(e=>{if(e instanceof p){if(null==e.geometry)return;if(tt(be(e,0,!1)),a>0){tt(be(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=be(s,0,!0);tt(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=be(s,4,!0);tt(e);for(const t of i)e.setX(t.i,t.w[4]??0),e.setY(t.i,t.w[5]??0),e.setZ(t.i,t.w[6]??0),e.setW(t.i,t.w[7]??0),e.needsUpdate=!0,n=!0}n&&r.add(e)}this.inEditor&&this.landscapeManagers.filter(t=>t.source.id===e.id).forEach(e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,e=>r.has(e.name)))}async materialize(e,t,a=!1,s){if(!this.shouldBeMaterialized(e))return;let r,n;switch(e.type){case"asset_mesh":r=await this.createFromAsset(e);break;case"shape_mesh":r=await this.createFromShape(e);break;case"light":r=await this.createLight(e);break;case"particles":r=await this.createParticleSystem(e),e.collisionDetection=!1;break;case"global_fog":this.scene.fog=Xe(e.fog),this.fixFogColor(),r=new h;break;case"sky":this.sky=Pe(),this.updateSky(e),r=this.sky;break;case"world_env":this.updateWorldEnv(e),r=new h,this.worldEnvObj=r;break;case"actor":({object:r,actor:n}=await this.createFromActor(e,s));break;case"group":r=new h;break;case"prefab":r=await this.createFromPrefab(e,s);break;case"vfx":r=await this.createFromVfx(e,s);break;default:if(this.inEditor)throw new Error("unknown type "+e.type);console.warn(`Failed to materialize object. Unknown type '${e.type}'. This might be because the hology/core library is not compatible with the editor version.`)}if(null!=r){if(e.name&&e.name.length>0&&(r.name=e.name),null!=e.position&&r.position.fromArray(e.position),null!=e.scale&&r.scale.fromArray(e.scale),null!=e.rotation&&r.rotation.fromArray(e.rotation),a?r.userData._src=e:r.userData.src=e,null!=n&&(r.userData.actor=n),this.inEditor,this.inEditor){let e=null;r instanceof pe&&(e=function(e){if(e instanceof me)return new p(new i(...e.offset.toArray()),Ye);return null}(r.collisionShape)),null!=e&&(e.layers.disable(0),e.layers.enable(18),e.scale.multiplyScalar(1.1),r.add(e))}if(this.objectMap.set(r.uuid,e),this.sceneObjectMap.set(e.id,r),e.physics?.type!==H.dynamic||null==t||this.inEditor?null==t?this.scene.add(r):t?.add(r):(t.add(r),r.getWorldPosition(r.position),r.getWorldQuaternion(r.quaternion),r.getWorldScale(r.scale),this.scene?.attach(r)),null!=e.children&&await Promise.all(e.children?.map(e=>this.materialize(e,r,a))),this.inEditor||"asset_mesh"!=e.type&&"shape_mesh"!==e.type||"landscape"===e.shape||null!=e.physics?.type&&e.physics.type==H.dynamic||qe(r),null!=this.renderingView)return this.renderingView.renderer.shadowMap.needsUpdate=!0,r;console.warn("RenderingView not found in materializer. No idea what called this")}}updateWorldEnv(e){this.renderingView.aoPass.enabled=e.worldEnv.ao.enabled,this.renderingView.aoPass.blendIntensity=e.worldEnv.ao.blendIntensity,this.renderingView.aoPass.updateGtaoMaterial(e.worldEnv.ao),this.renderingView.aoPass.output=!0===e.worldEnv.ao.onlyAO?5:0;const t=e.worldEnv.toneMapping;null!=t&&(this.renderingView.renderer.toneMapping=t.mapping??0,this.renderingView.renderer.toneMappingExposure=t.exposure??1);const a=e.worldEnv.environment;null!=a&&null!=a.textureId?this.assetManagerService.getTexture(this.assets.get(a.textureId)).then(e=>{null==this.pmremGenerator&&(this.pmremGenerator=new r.PMREMGenerator(this.renderingView.renderer),this.pmremGenerator.compileEquirectangularShader()),this.pmremGeneratorResults.has(e)||this.pmremGeneratorResults.set(e,this.pmremGenerator.fromEquirectangular(e).texture);const t=this.pmremGeneratorResults.get(e);this.renderingView.scene.environment=t,this.renderingView.scene.environmentIntensity=a.intensity??1}):this.renderingView.scene.environment=null}resetWorldEnv(){this.renderingView.aoPass.enabled=!1,this.renderingView.aoPass.blendIntensity=1,this.renderingView.aoPass.output=0,this.renderingView.renderer.toneMapping=0,this.renderingView.renderer.toneMappingExposure=1}async updateSky(e){if(null==e?.sky?.materialId)return void(this.sky.material=Ie);const t=await this.assetsService.getAsset(e.sky.materialId),a=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);a.side=r.BackSide,(a instanceof g||a instanceof r.MeshBasicMaterial||a instanceof r.ShaderMaterial)&&(a.fog=!1),null!=this.sky?this.sky.material=a:console.warn("No sky has been created")}async createComponent(e,t,a,s){const r=new Le[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??U[e.actor?.type];if(null==a)return{object:null,actor:null};this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const s=await this.actorProvider.create(a,(new M).fromArray(e.position),(new o).fromArray(e.rotation),!0);return this.materializedActors.set(this.getNestedActorId(e.id,t),s),{object:s?.object,actor:s}}getNestedActorId(e,t){return null!=t?t.sceneObjectChain.join("/")+"/"+e:e}async createFromVfx(e,t){const a=await this.assetsService.getAsset(e.assetId);null==a&&console.error("Could not find asset",e);const s=await this.actorProvider.create($,(new M).fromArray(e.position),(new o).fromArray(e.rotation),!1);try{await s.fromAsset(a)}catch(e){return console.error("Failed to create VFX asset",e),null}return s.play(),this.materializedActors.set(this.getNestedActorId(e.id,t),s),null!=s&&(s.object.userData.actor=s),s?.object}async createFromShape(e){const t=this.inEditor&&e.hidden;let a;if("landscape"==e.shape)a=this.createLandscape(e),a.traverse(e=>{e instanceof p&&this._originalMaterials.set(e.id,e.material)});else{let s=new g({name:"Default",color:new n("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});const r=await this.createMeshByShape(e.shape,s,e.shapeParams);r.castShadow=e.castShadow??!0,r.receiveShadow=e.castShadow??!1,e.collisionDetection||(r.collisionShape=null),r.physics=e.physics,a=r,this._originalMaterials.set(a.id,r.material),a.traverse(e=>{})}return t||(await Promise.all((e.materialAssignments??[]).filter(e=>null!=e.materialId).map(e=>this.applyMaterial(a,e))),this.applyVertexMaterials(e,a)),a}createLandscape(e){const t=e.landscape?.options;if(null==t)return console.error(`No landscape options exist on scene object ${e.id} ${e.name}`),new h;const a=fe(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new ue(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 ge(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(()=>ye(r),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&je.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);if(!this.geometryCache.has(r)){const t=Me[e].geometry(s);t.computeTangents(),this.geometryCache.set(r,t)}this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,Me[e].collision(s));return new pe(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){const t=await this.assetsService.getAsset(e.assetId);if(null==t)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);let{scene:a}=await this.assetManagerService.getMesh(t,{mergeGeomtries:!0});Qe(e.materialAssignments,t.materialAssignments).forEach(e=>this.applyMaterial(a,e));const s=e.receiveShadow??!!t.receiveShadow??!0,r=e.castShadow??!!t.castShadow??!1;return a.receiveShadow=s,$e(a,r,s),e.collisionDetection||(a.collisionShapes=[]),null!=e.physics&&!0!==this.inEditor&&(a.physics=e.physics),this.applyVertexMaterials(e,a),a.traverse(e=>{e instanceof p&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()}),a}async createFromPrefab(e,t){const a=await this.assetsService.getAsset(e.assetId);if(null==a)return void console.warn(`Can not find asset with id ${e.assetId} and name ${e.name}`);null==t&&(t={sceneObjectChain:[]}),t.sceneObjectChain.push(e.id);const{object:s}=await this.createFromPrefabAsset(a,t);return t.sceneObjectChain.pop(),s}async createFromPrefabAsset(e,t){const a=new h;await Promise.all(e.prefab.objects.filter(e=>"global_fog"!==e.type&&"world_env"!==e.type).map(e=>this.materialize(e,a,!0,structuredClone(t))));const s=t.sceneObjectChain.join("/"),r=Array.from(this.materializedActors.entries()).filter(([e,a])=>e.startsWith(s)&&e.split("/").length-1===t.sceneObjectChain.length).map(([,e])=>e);r.forEach(e=>{a.add(e.object)}),this.initActorsPostInit(r,structuredClone(t));const i=Array.from(this.materializedActors.entries()).filter(([e,t])=>e.startsWith(s)).map(([,e])=>e);return{object:a,actors:i}}async createParticleSystem(e){const t=await this.assetsService.getAsset(e.assetId),a=new y;return await x.fromJSONAsync(t.particleSystem,r).then(e=>{const t=new P(a,r);e.addRenderer(t),this.renderingView.onLoop(t=>e.update())}),a}async createLight(e){if("point"===e.light.type){const t=new w(e.light.point.color,e.light.point.intensity,e.light.point.distance,e.light.point.decay);if(t.castShadow=e.light.point.castShadow??!0,this.inEditor){const e=(new r.TextureLoader).load("assets/light-bulb-icon.webp"),a=new r.SpriteMaterial({map:e,alphaTest:.5}),s=new _e(a);s.scale.multiplyScalar(.6),t.add(s)}return t}if("spot"===e.light.type){const t=new r.SpotLight(e.light.spot.color,e.light.spot.intensity,e.light.spot.distance,e.light.spot.angle,e.light.spot.penumbra,e.light.spot.decay);if(t.castShadow=e.light.spot.castShadow??!0,t.target=new y,t.target.position.set(0,-1,0),t.add(t.target),this.inEditor){const e=(new r.TextureLoader).load("assets/light-bulb-icon.webp"),a=new r.SpriteMaterial({map:e,alphaTest:.5}),s=new _e(a);s.scale.multiplyScalar(.6),t.add(s),t.add(new r.SpotLightHelper(t))}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional,e),new h):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient,e),new h):void 0}applyDirectionalAmbientLight(e,t,a){const s=this.scene.children.find(e=>e.name===xe);null!=s?(s.intensity=t.intensity,s.color.set(t.color),s.groundColor.set(t.color),s.userData.src=a,s.userData.volumetricIntensity=t.volumetricIntensity):console.warn("Couldn't find ambient light")}applyDirectionalLight(e,t){for(const a of this.renderingView.csm.lights)a.intensity=e.intensity,a.color.set(e.color),a.castShadow=e.castShadow,a.userData.src=t,a.userData.volumetricIntensity=e.volumetricIntensity;this.renderingView.csm.lightDirection.fromArray(e.direction).normalize()}dispose(){this.updateSubscription.unsubscribe(),this.createAssetSubscription.unsubscribe(),this.materializedActors.forEach(e=>e.disposed.next(!0)),this.materializedActors.clear()}};We=e([W(),t("design:paramtypes",[b,Object,Object,he,X,Array,Array,Object])],We);export{We as SceneMaterializer};function $e(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse(e=>{e.castShadow=t,e.receiveShadow=a})}const Re=new Map,Ge=new Map,Ue=new u({color:16711935}),He=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){const n=JSON.stringify(e.material);return i&&Re.has(n)?Re.get(n):i&&Ge.has(n)?await Ge.get(n):Ge.set(n,_materialFromAsset(n,e,t,a,s,r,i)).get(n)}export async function _materialFromAsset(e,t,a,s,i,o,l=!0){const c={opacity:t.material.params.opacity,map:null,emissive:t.material.params.emissive??null,metalness:t.material.params.metalness??0,flatShading:t.material.params.flatShading??!1,color:new n(t.material.params.color),transparent:null!=t.material.params.opacity&&t.material.params.opacity<1},h={};if(null!=t.material.params.map){const e=t.material.params.map,a=await s.getAsset(e);null!=a&&(c.map=await i.getTexture(a))}let d;switch(t.material.type){case"phong":d=new f({...c,...h});break;case"water":d=Ae(c,a);break;case"grassFoliage":d=we({color:c.color,map:c.map},a);break;case"grass":d=ve({...c,colorTwo:new n(t.material.params.colorTwo),colorThree:new n(t.material.params.colorThree)},a);break;case"standard":case"unlit":case"toon":case"layered":case"lambert":case"shader":case"landscape":case"landscape-composite":case"decal-unlit":case"decal-standard":const e={standard:ee,lambert:Z,unlit:te,toon:Be,layered:Fe,landscape:K,"landscape-composite":Q,"decal-unlit":Ce,"decal-standard":Ee}[t.material.type]??o.find(e=>e.name==t.material.shader)?.type;if(e){try{let r=new e;const n=await prepareClassParameters(t.material?.shaderParams??{},e,s,i,null,a,o);Object.assign(r,n),d=r.build()}catch(e){console.log("Shader runtime error: "+e),He.has(t.material.shader)||He.set(t.material.shader,Ue.clone()),d=He.get(t.material.shader)}d.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),d=Ue;break;default:throw new Error("Unsupported material type"+t.material.type)}return a?.csm.setupMaterial(d),null!=a&&Re.set(e,d),d.side=t.material.side??d.side??r.FrontSide,d.transparent=(t.material.transparent??c.transparent??!1)||d.transparent,d.alphaTest=t.material.alphaTest??d.alphaTest??0,null!=t.material.blending&&(d.blending=J[t.material.blending]??r.NormalBlending),t.material.bloom&&(d.userData.hasBloom=!0),t.material.reflective&&(d.userData.reflective=!0),!0===t.material.outlines&&(d.userData.outlineParameters={},null!=t.material.outlineParams&&(null!=t.material.outlineParams.color&&(d.userData.outlineParameters.color=new n(t.material.outlineParams.color).toArray()),null!=t.material.outlineParams.thickness&&(d.userData.outlineParameters.thickness=t.material.outlineParams.thickness))),d.userData.assetId=t.id,Ge.delete(e),d}export async function prepareClassParameters(e,t,a,s,r,i,n,o){const l={};for(const[t,c]of Object.entries(e)){const e=await Je(c,a,s,r,i,n,o);null!=e&&(l[t]=e)}return l}export async function prepareShapeParameters(e){const t={};for(const[a,s]of Object.entries(e)){const e=await Je(s,null,null,null);null!=e&&(t[a]=e)}return t}async function Je(e,t,a,s,r,i,l,c=e.value,h=e.type){if(null==e||null==c||""===c)return null;switch(h){case Se.Array:if(Array.isArray(c)&&"element"in e)return await Promise.all(c.map(n=>Je(e,t,a,s,r,i,l,n,e.element)));break;case Se.Number:case Se.FloatNode:let h="string"==typeof c?parseFloat(c):c;return e.type===Se.FloatNode?C(h):h;case Se.Texture:return await a.getTexture(await t.getAsset(c));case Se.Sampler2DNode:return F(await a.getTexture(await t.getAsset(c)));case Se.Boolean:return c;case Se.BooleanNode:return I(c);case Se.Vector2:case Se.Vec2Node:if("object"==typeof c){const t=c instanceof Array?(new S).fromArray(c):new S(c.x,c.y);return e.type===Se.Vec2Node?T(t):t}return null;case Se.Vector3:case Se.Vec3Node:if("object"==typeof c){const t=c instanceof Array?(new M).fromArray(c):new M(c.x,c.y,c.z);return e.type===Se.Vec3Node?_(t):t}return null;case Se.Color:case Se.RgbNode:const d=new n(c);return e.type===Se.RgbNode?O(d):d;case Se.String:return c;case Se.BaseActor:const m=c;return null==s&&console.warn("Class parameters can not be prepared as actors are not passed in"),s?.get(m);case Se.Euler:const p=c;return(new o).fromArray(p);case Se.Object3D:return(await a.getMesh(await t.getAsset(c))).scene;case Se.Material:return await materialFromAsset(await t.getAsset(c),r,t,a,i);case Se.AudioBuffer:return await a.getAudio(await t.getAsset(c));case Se.VisualEffect:const u=await t.getAsset(c);if(null==l){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in u)return new R(l,u);console.error("Using a non-vfx asset for visual effect parameter");break;case Se.Curve:return De.decode(c);case Se.ColorLayer:case Se.MaskLayer:if(Te(c)){const e=await Ve.decode(c,async e=>await a.getTexture(await t.getAsset(e))),s=await prepareClassParameters(c.params,null,t,a);return Object.assign(e,s),e}return console.warn("Expecting color layer but got",c),null}return null}function qe(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 Xe(e){return"linear"===e.type?new l(new n(e.color),e.near??100,e.far??1e3):"density"===e.type?new c(e.color,e.density):void console.warn("Invalid fog type",e)}const Ye=new g({color:4229780});async function Ze(e,t,a,s){null==s&&(s=(new m).identity()),await t(e,a,s);const i=s.clone().multiply(function(e,t){if(null==e.position||null==e.rotation||null==e.scale)return t.identity();return t.compose((new M).fromArray(e.position),(new v).setFromEuler((new o).fromArray(e.rotation)),(new M).fromArray(e.scale))}(e,new r.Matrix4));return Promise.all((e.children??[]).map(a=>Ze(a,t,e,i)))}export function toSerializedParamType(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?Se.Number:t instanceof E||"function"==typeof e.prototype.isFloat?Se.FloatNode:t instanceof A||e===A||e.isTexture?Se.Texture:t instanceof Y||e===k?Se.Sampler2DNode:t instanceof Boolean||e===Boolean?Se.Boolean:t instanceof D?Se.BooleanNode:t instanceof n||e==n?Se.Color:t instanceof N||"function"==typeof e.prototype.isRgb?Se.RgbNode:t instanceof S||e==S?Se.Vector2:t instanceof z||"function"==typeof e.prototype.isVec2?Se.Vec2Node:t instanceof M||e==M?Se.Vector3:t instanceof B||"function"==typeof e.prototype.isVec3?Se.Vec3Node:t instanceof String||e===String?Se.String:t instanceof G||e==G||e.prototype instanceof G||e.prototype==G?Se.BaseActor:t instanceof o||e==o?Se.Euler:t instanceof y||e==y?Se.Object3D:t instanceof d||e==d?Se.Material:t instanceof AudioBuffer||e==AudioBuffer?Se.AudioBuffer:t instanceof R||e==R?Se.VisualEffect:t instanceof De||e==De?Se.Curve:t instanceof Ve||e==Ve?Se.ColorLayer:t instanceof ke||e==ke?Se.MaskLayer:void console.warn("Failed to map parameter type to serialized version",{type:e})}export function prepareCustomParams(e,t,a={}){return Object.fromEntries(e.map(e=>[e.name,{type:e.options.array?Se.Array:toSerializedParamType(e.type),...e.options.array?{element:toSerializedParamType(e.type)}:{},value:t[e.name]?.value??(!0!==e.options.array?a[e.name]??customParameterDefaultValueByType.get(toSerializedParamType(e.type)):[])}]))}export function prepareCustomParamsFromType(e,t,a=null){const s=ae(e);if(0===s.length)return{};let r;null!=a?q(a,()=>{r=a.get(e)}):r=new e;const i={};for(const e of s){const t=r[e.name];if(null!=t&&!0!==e.options.array){const a=serializeCustomParameter(e.type,t);null!=a&&(i[e.name]=a)}}return prepareCustomParams(s,t,i)}export function serializeCustomParameter(e,t){function a(){console.error("Failed to serialize value",{type:e,value:t})}switch(e){case Number:case Boolean:return t;case S:return t instanceof S?t.toArray():void a();case M:return t instanceof M?t.toArray():void a();case j:return t instanceof j?t.toArray():void a();case n:return t instanceof n?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new n(t).getHexString():void a();case String:return t;case o:return t instanceof o?t.toArray():void a()}}function Qe(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=>Ke(e.materialId)),(t??[]).filter(e=>Ke(e.materialId)),e=>e.color+e.name)}function Ke(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[Se.RgbNode,"#000000"],[Se.Color,"#000000"],[Se.Vector4,[0,0,0,0]],[Se.Vec4Node,[0,0,0,0]],[Se.Vector3,[0,0,0]],[Se.Vec3Node,[0,0,0]],[Se.Vector2,[0,0]],[Se.Vec2Node,[0,0]],[Se.Euler,[0,0,0,"XYZ"]],[Se.Array,[]],[Se.ColorLayer,Oe],[Se.MaskLayer,Ne]]);export function applyMaterial(e,t,a,s){const i=[];return e.traverse(async e=>{if(e instanceof p||e.isMesh||e instanceof r.SkinnedMesh||e.isSkinnedMesh)for(const t of ie(e.material))t.hasOwnProperty("color")&&i.push(e)}),Promise.all(i.map(async e=>{if(e.material instanceof Array)for(let r=0;r<e.material.length;r++){const i=e.material[r];if(null==i.color||!(i.color instanceof n))continue;const o="#"+i.color.getHexString(),l=i.name;if(o===t.color&&(i.name===t.name||null==t.name)||e.userData["originalColor_"+r]===t.color&&e.userData["originalMaterialName_"+r]===t.name){const i=await a(t.materialId),n=e.material[r];null!=i&&n.id!=i.id&&(e.material[r]=i,e.userData["originalColor_"+r]=e.userData["originalColor_"+r]??o,e.userData["originalMaterialName_"+r]=e.userData["originalMaterialName_"+r]??l,null!=s&&s.set(e.id+"#"+r,n))}}else if("color"in e.material){const r="#"+e.material.color.getHexString(),i=e.material.name;if(r===t.color&&(e.material.name===t.name||null==t.name)||e.userData.originalColor===t.color&&e.userData.originalName===t.name){const n=await a(t.materialId),o=e.material;null!=n&&(e.material=n,e.userData.originalColor=e.userData.originalColor??r,e.userData.originalMaterialName=e.userData.originalMaterialName??i,null!=s&&(s.has(e.id)||s.set(e.id,o)))}}}))}function et(e,t){if(e instanceof r.ShaderMaterial&&t instanceof r.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof r.ShaderMaterial&&t instanceof r.ShaderMaterial){for(const a in e.uniforms){if(null==t.uniforms[a])return!1;if(t.uniforms[a].value!==e.uniforms[a].value)return!1}return!0}return!1}(e,t)}return!1}function tt(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}/*
2
2
  * Copyright (©) 2025 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1,4 +1,4 @@
1
- import{BehaviorSubject as e}from"rxjs";import{Matrix4 as t,Vector3 as s,Quaternion as i,Euler as n,NoToneMapping as o}from"three";export class SceneDataService{constructor(){this.objects=[],this.callbacks=[],this.createCallbacks=[],this.removeCallbacks=[],this.objectChange=new e([])}initiate(e){this.objects=e??[],this.objectChange.next(this.objects)}createDefaultObjects(){this.objects.some(e=>"global_fog"===e.type)||this.objects.unshift(createInitialFog());this.objects.some(e=>"sky"===e.type)||this.objects.unshift(createInitialSky())}removeOnUpdateCallback(e){this.callbacks.splice(this.callbacks.indexOf(e),1)}onCreate(e){this.createCallbacks.push(e)}onUpdate(e){this.callbacks.push(e)}onRemove(e){this.removeCallbacks.push(e)}getObjects(){return this.objects}getObjectsRecursive(){const e=[],t=this.objects.slice();for(;t.length>0;){const s=t.pop();e.push(s),null!=s.children&&t.push(...s.children)}return e}addObject(e,t=!1){this.objects.push(e),this.createCallbacks.forEach(s=>s(e,t)),this.objectChange.next(this.objects)}updateObject(e,t=!1){const s=this.findObjectById(e.id);s?(Object.assign(s,e),this.callbacks.forEach(s=>s(e,t))):this.addObject(e),this.objectChange.next(this.objects)}findObjectById(e){const t=[...this.objects];for(;t.length>0;){const s=t.pop();if(s.id===e)return s;s.children&&t.push(...s.children)}}findAncestorsById(e){const t=this.findParentById(e);return null==t?[]:[t,...this.findAncestorsById(t.id)]}findParentById(e){return this._findParentById(e,this.objects)}_findParentById(e,t,s=null){return t.some(t=>t.id===e)?s:t.filter(e=>null!=e.children).map(t=>this._findParentById(e,t.children,t)).find(e=>null!=e)}updateParent(e,o){const r=this.findParentById(e.id);{const c=null!=o?this.getMatrixWorld(o).invert():(new t).identity();null!=r&&c.multiply(this.getMatrixWorld(r));const l=this.getLocalMatrix(e),a=c.multiply(l),h=new s,d=new i,b=new s;a.decompose(h,d,b),e.position=h.toArray(),e.rotation=(new n).setFromQuaternion(d).toArray(),e.scale=b.toArray()}this.removeRecursive(e.id,r?.children??this.objects),null!=r?r.children=r.children.slice():this.objects=this.objects.slice(),null!=o?(o.children??(o.children=[]),o.children.push(e),o.children=o.children.slice()):(this.objects.push(e),this.objects=this.objects.slice()),this.objectChange.next(this.objects),this.callbacks.forEach(t=>t(e,!1))}getMatrixWorld(e){const t=this.findAncestorsById(e.id).reverse();t.push(e);const s=this.getLocalMatrix(t.shift());for(const e of t){const t=this.getLocalMatrix(e);s.multiply(t)}return s}getLocalMatrix(e){const o=new t,r=(new s).fromArray(e.position),c=(new i).setFromEuler((new n).fromArray(e.rotation)),l=(new s).fromArray(e.scale);return o.compose(r,c,l),o}removeObjectById(e,t=!1){const s=this.findObjectById(e);this.removeObject(s,t)}removeObject(e,t=!1){this.removeRecursive(e.id,this.objects),this.removeCallbacks.forEach(s=>s(e,t)),this.objectChange.next([...this.objects])}removeRecursive(e,t){const s=t.findIndex(t=>t.id===e);if(s>-1)t.splice(s,1);else for(const s of t)null!=s.children&&this.removeRecursive(e,s.children??[])}save(){}serialize(){return JSON.stringify(this.objects)}}export function createInitialFog(){return{id:"auto-global-fog",name:"Global fog",type:"global_fog",fog:{type:"density",color:"#b8f8ff",density:.005,near:100,far:1e3}}}export function createInitialSky(){return{id:"auto-sky",name:"Sky",type:"sky",sky:{materialId:null}}}export function createWorldEnvironment(){return{id:"auto-world-env",name:"World Environment",type:"world_env",worldEnv:{ao:{enabled:!1,blendIntensity:1,radius:.25,distanceExponent:1,thickness:1,distanceFallOff:1,scale:1,samples:16,onlyAO:!1},toneMapping:{mapping:o,exposure:1},environment:{textureId:null,intensity:1}}}}/*
1
+ import{BehaviorSubject as e}from"rxjs";import{Matrix4 as t,Vector3 as s,Quaternion as i,Euler as n,NoToneMapping as o}from"three";export class SceneDataService{constructor(){this.objects=[],this.callbacks=[],this.createCallbacks=[],this.removeCallbacks=[],this.objectChange=new e([])}initiate(e){this.objects=e??[],this.objectChange.next(this.objects)}createDefaultObjects(){this.objects.some(e=>"global_fog"===e.type)||this.objects.unshift(createInitialFog());this.objects.some(e=>"sky"===e.type)||this.objects.unshift(createInitialSky())}removeOnUpdateCallback(e){this.callbacks.splice(this.callbacks.indexOf(e),1)}onCreate(e){this.createCallbacks.push(e)}onUpdate(e){this.callbacks.push(e)}onRemove(e){this.removeCallbacks.push(e)}getObjects(){return this.objects}getObjectsRecursive(){const e=[],t=this.objects.slice();for(;t.length>0;){const s=t.pop();e.push(s),null!=s.children&&t.push(...s.children)}return e}addObject(e,t=!1){this.objects.push(e),this.createCallbacks.forEach(s=>s(e,t)),this.objectChange.next(this.objects)}updateObject(e,t=!1){const s=this.findObjectById(e.id);s?(Object.assign(s,e),this.callbacks.forEach(s=>s(e,t))):this.addObject(e),this.objectChange.next(this.objects)}findObjectById(e){const t=[...this.objects];for(;t.length>0;){const s=t.pop();if(s.id===e)return s;s.children&&t.push(...s.children)}}findAncestorsById(e){const t=this.findParentById(e);return null==t?[]:[t,...this.findAncestorsById(t.id)]}findParentById(e){return this._findParentById(e,this.objects)}_findParentById(e,t,s=null){return t.some(t=>t.id===e)?s:t.filter(e=>null!=e.children).map(t=>this._findParentById(e,t.children,t)).find(e=>null!=e)}updateParent(e,o){const r=this.findParentById(e.id);if("sky"!==e.type&&"directional"!==e.light?.type&&"ambient"!==e.light?.type&&null!=e.position){const c=null!=o?this.getMatrixWorld(o).invert():(new t).identity();null!=r&&c.multiply(this.getMatrixWorld(r));const l=this.getLocalMatrix(e),a=c.multiply(l),h=new s,d=new i,b=new s;a.decompose(h,d,b),e.position=h.toArray(),e.rotation=(new n).setFromQuaternion(d).toArray(),e.scale=b.toArray()}this.removeRecursive(e.id,r?.children??this.objects),null!=r?r.children=r.children.slice():this.objects=this.objects.slice(),null!=o?(o.children??(o.children=[]),o.children.push(e),o.children=o.children.slice()):(this.objects.push(e),this.objects=this.objects.slice()),this.objectChange.next(this.objects),this.callbacks.forEach(t=>t(e,!1))}getMatrixWorld(e){const t=this.findAncestorsById(e.id).reverse();t.push(e);const s=this.getLocalMatrix(t.shift());for(const e of t){const t=this.getLocalMatrix(e);s.multiply(t)}return s}getLocalMatrix(e){const o=new t,r=(new s).fromArray(e.position),c=(new i).setFromEuler((new n).fromArray(e.rotation)),l=(new s).fromArray(e.scale);return o.compose(r,c,l),o}removeObjectById(e,t=!1){const s=this.findObjectById(e);this.removeObject(s,t)}removeObject(e,t=!1){this.removeRecursive(e.id,this.objects),this.removeCallbacks.forEach(s=>s(e,t)),this.objectChange.next([...this.objects])}removeRecursive(e,t){const s=t.findIndex(t=>t.id===e);if(s>-1)t.splice(s,1);else for(const s of t)null!=s.children&&this.removeRecursive(e,s.children??[])}save(){}serialize(){return JSON.stringify(this.objects)}}export function createInitialFog(){return{id:"auto-global-fog",name:"Global fog",type:"global_fog",fog:{type:"density",color:"#b8f8ff",density:.005,near:100,far:1e3}}}export function createInitialSky(){return{id:"auto-sky",name:"Sky",type:"sky",sky:{materialId:null}}}export function createWorldEnvironment(){return{id:"auto-world-env",name:"World Environment",type:"world_env",worldEnv:{ao:{enabled:!1,blendIntensity:1,radius:.25,distanceExponent:1,thickness:1,distanceFallOff:1,scale:1,samples:16,onlyAO:!1},toneMapping:{mapping:o,exposure:1},environment:{textureId:null,intensity:1}}}}/*
2
2
  * Copyright (©) 2025 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -1 +1 @@
1
- {"version":3,"file":"standard-shader.d.ts","sourceRoot":"","sources":["../../../src/shader/builtin/standard-shader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,oBAAoB,EAAE,8BAA8B,EAAkB,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAChI,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAKtC,qBAAa,cAAe,SAAQ,MAAM;IAE3B,KAAK,EAAE,KAAK,CAAwB;IAChB,GAAG,CAAC,EAAE,OAAO,CAAC;IACpB,OAAO,EAAE,MAAM,CAAI;IACjC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACL,SAAS,CAAC,EAAE,MAAM,CAAK;IACrC,YAAY,CAAC,EAAE,OAAO,CAAC;IACT,SAAS,CAAC,EAAE,MAAM,CAAK;IACrC,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,KAAK,CAAC;IACF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC1C,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,MAAM,CAAC,EAAE,OAAO,CAAC;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,eAAe,CAAC,EAAE,MAAM,CAAC;IAGvC,SAAS,CAAC,EAAE,OAAO,CAAgB;IACnC,WAAW,CAAC,EAAE,MAAM,CAAA;IAGjC,KAAK,IAAI,QAAQ;CA8ClB;AAGD,oBAAY,YAAY;IACtB,IAAI,IAAA;IACJ,MAAM,IAAA;IACN,GAAG,IAAA;CACJ;AAED,qBAAa,wBAAyB,SAAQ,oBAAoB;IACzD,SAAS,EAAE,OAAO,CAAA;IAClB,WAAW,EAAE,MAAM,CAAA;IACnB,YAAY,EAAE,YAAY,CAAA;IAC1B,SAAS,EAAE,MAAM,CAAA;IACjB,SAAS,EAAE,MAAM,CAAA;gBAEZ,MAAM,GAAE,OAAO,CAAC;QAC1B,SAAS,EAAE,OAAO,CAAC;QACnB,WAAW,EAAE,MAAM,CAAC;QACpB,YAAY,EAAE,YAAY,CAAC;QAC3B,SAAS,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,MAAM,CAAA;KAClB,GAAG,8BAA8B,CAAM;IAYxC,eAAe,CAAC,MAAM,KAAA;IAqLtB,KAAK,IAAI,IAAI;CAUd"}
1
+ {"version":3,"file":"standard-shader.d.ts","sourceRoot":"","sources":["../../../src/shader/builtin/standard-shader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,oBAAoB,EAAE,8BAA8B,EAAkB,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAChI,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAMtC,qBAAa,cAAe,SAAQ,MAAM;IAE3B,KAAK,EAAE,KAAK,CAAwB;IAChB,GAAG,CAAC,EAAE,OAAO,CAAC;IACpB,OAAO,EAAE,MAAM,CAAI;IACjC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACL,SAAS,CAAC,EAAE,MAAM,CAAK;IACrC,YAAY,CAAC,EAAE,OAAO,CAAC;IACT,SAAS,CAAC,EAAE,MAAM,CAAK;IACrC,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,KAAK,CAAC;IACF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC1C,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,MAAM,CAAC,EAAE,OAAO,CAAC;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,eAAe,CAAC,EAAE,MAAM,CAAC;IAGvC,SAAS,CAAC,EAAE,OAAO,CAAiB;IACpC,WAAW,CAAC,EAAE,MAAM,CAAA;IAGjC,KAAK,IAAI,QAAQ;CA8ClB;AAGD,oBAAY,YAAY;IACtB,IAAI,IAAA;IACJ,MAAM,IAAA;IACN,GAAG,IAAA;CACJ;AAED,qBAAa,wBAAyB,SAAQ,oBAAoB;IACzD,SAAS,EAAE,OAAO,CAAA;IAClB,WAAW,EAAE,MAAM,CAAA;IACnB,YAAY,EAAE,YAAY,CAAA;IAC1B,SAAS,EAAE,MAAM,CAAA;IACjB,SAAS,EAAE,MAAM,CAAA;gBAEZ,MAAM,GAAE,OAAO,CAAC;QAC1B,SAAS,EAAE,OAAO,CAAC;QACnB,WAAW,EAAE,MAAM,CAAC;QACpB,YAAY,EAAE,YAAY,CAAC;QAC3B,SAAS,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,MAAM,CAAA;KAClB,GAAG,8BAA8B,CAAM;IAYxC,eAAe,CAAC,MAAM,KAAA;IAqLtB,KAAK,IAAI,IAAI;CAUd"}
@@ -1,4 +1,4 @@
1
- import{__decorate as e,__metadata as a}from"tslib";import{Color as t,MeshStandardMaterial as n,Texture as r,Vector2 as i}from"three";import{Shader as s}from"../shader.js";import{Parameter as o}from"../parameter.js";import{removeObjectUndefined as p}from"../../utils/collections.js";export class StandardShader extends s{constructor(){super(...arguments),this.color=new t("#FFFFFF"),this.opacity=1,this.roughness=1,this.metalness=0,this.heightMap=new r}build(){const e=null!=this.normalMap&&null!=this.map&&null!=this.heightMap&&0!==this.heightScale;return new(e?ParallaxStandardMaterial:n)(p({color:this.color,opacity:this.opacity,roughness:this.roughness,metalness:this.metalness,map:this.map,lightMap:this.lightMap,lightMapIntensity:this.lightMapIntensity,aoMap:this.aoMap,aoMapIntensity:this.aoMapIntensity,emissive:this.emissive,emissiveIntensity:this.emissiveIntensity,emissiveMap:this.emissiveMap,bumpMap:this.bumpMap,bumpScale:this.bumpScale,normalMap:this.normalMap,normalScale:this.normalScale,displacementMap:this.displacementMap,displacementScale:this.displacementScale,displacementBias:this.displacementBias,roughnessMap:this.roughnessMap,metalnessMap:this.metalnessMap,alphaMap:this.alphaMap,envMap:this.envMap,envMapIntensity:this.envMapIntensity,refractionRatio:this.refractionRatio,...e?{heightMap:this.heightMap,heightScale:this.heightScale}:{}}))}}e([o(),a("design:type",t)],StandardShader.prototype,"color",void 0),e([o({label:"Color Map"}),a("design:type",r)],StandardShader.prototype,"map",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"opacity",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"alphaMap",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"roughness",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"roughnessMap",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"metalness",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"metalnessMap",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"lightMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"lightMapIntensity",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"aoMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"aoMapIntensity",void 0),e([o(),a("design:type",t)],StandardShader.prototype,"emissive",void 0),e([o({range:[0,10]}),a("design:type",Number)],StandardShader.prototype,"emissiveIntensity",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"emissiveMap",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"bumpMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"bumpScale",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"normalMap",void 0),e([o(),a("design:type",i)],StandardShader.prototype,"normalScale",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"displacementMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"displacementScale",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"displacementBias",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"envMap",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"envMapIntensity",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"refractionRatio",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"heightMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"heightScale",void 0);export var ParallaxType;!function(e){e[e.none=0]="none",e[e.offset=1]="offset",e[e.pom=2]="pom"}(ParallaxType||(ParallaxType={}));export class ParallaxStandardMaterial extends n{constructor(e={}){super(e),e.heightMap&&(this.heightMap=e.heightMap),this.heightScale=e.heightScale??.05,this.parallaxType=e.parallaxType??ParallaxType.pom,this.minLayers=e.minLayers??10,this.maxLayers=e.maxLayers??32}onBeforeCompile(e){e.uniforms.heightMap={value:this.heightMap},e.uniforms.heightScale={value:this.heightScale},e.uniforms.minLayers={value:this.minLayers},e.uniforms.maxLayers={value:this.maxLayers},e.uniforms.parallaxType={value:this.parallaxType},e.vertexTangents=!0,e.vertexShader=e.vertexShader.replace("#include <uv_pars_vertex>","\n #include <uv_pars_vertex>\n varying vec3 vViewDirTS;\n varying mat3 vTBN;\n "),e.vertexShader=e.vertexShader.replace("#include <begin_vertex>","\n #include <begin_vertex>\n vec3 N = normalize(normalMatrix * normal);\n vec3 T = normalize(normalMatrix * tangent.xyz);\n vec3 B = cross(N, T) * tangent.w;\n vTBN = mat3(T, B, N);\n\n vec3 viewDir = cameraPosition - (modelMatrix * vec4(transformed, 1.0)).xyz;\n vViewDirTS = normalize(vTBN * viewDir);\n "),e.fragmentShader=e.fragmentShader.replace("#include <uv_pars_fragment>","\n #include <uv_pars_fragment>\n uniform sampler2D heightMap;\n uniform float heightScale;\n uniform int minLayers;\n uniform int maxLayers;\n uniform int parallaxType;\n\n varying vec3 vViewDirTS;\n varying mat3 vTBN;\n\n vec2 parallaxOffset(vec2 uv, vec3 viewDirTS) {\n float h = texture(heightMap, uv).r;\n return uv - (viewDirTS.xy / viewDirTS.z) * (h * heightScale);\n }\n\n vec2 parallaxOcclusion2(vec2 uv, vec3 viewDirTS) {\n vec3 viewDir = normalize(vViewPosition);\n vec3 vv = -viewDir * vTBN;\n float parallaxLimit = -length(vv.xy) / vv.z;\n parallaxLimit *= heightScale;\n\n vec2 vOffsetDir = normalize(vv.xy);\n vec2 vMaxOffset = vOffsetDir * parallaxLimit;\n\n // Probably should use actual normal but it might not matter\n vec3 nNormal = vec3(0.0, 0.0, 1.0);\n float nNumSamples = mix(float(maxLayers), float(minLayers), dot(viewDir, nNormal));\n float fStepSize = 1.0 / nNumSamples;\n\n float fCurrRayHeight = 1.0;\n vec2 vCurrOffset = vec2(0.0);\n vec2 vLastOffset = vec2(0.0);\n float fLastSampledHeight = 1.0;\n float fCurrSampledHeight = 1.0;\n\n for (int nCurrSample = 0; nCurrSample < 50; nCurrSample++) {\n if (float(nCurrSample) > nNumSamples) break;\n\n fCurrSampledHeight = texture2D(heightMap, uv + vCurrOffset).r;\n if (fCurrSampledHeight > fCurrRayHeight) {\n float delta1 = fCurrSampledHeight - fCurrRayHeight;\n float delta2 = (fCurrRayHeight + fStepSize) - fLastSampledHeight;\n float ratio = delta1 / (delta1 + delta2);\n vCurrOffset = ratio * vLastOffset + (1.0 - ratio) * vCurrOffset;\n break;\n } else {\n fCurrRayHeight -= fStepSize;\n vLastOffset = vCurrOffset;\n vCurrOffset += fStepSize * vMaxOffset;\n fLastSampledHeight = fCurrSampledHeight;\n }\n }\n\n return uv + vCurrOffset;\n }\n "),e.fragmentShader=e.fragmentShader.replace("#include <map_fragment>","\n vec2 uvPOM = vMapUv ;\n if (parallaxType == 1) {\n uvPOM = parallaxOffset(vMapUv , vViewDirTS);\n } else if (parallaxType == 2) {\n uvPOM = parallaxOcclusion2(vMapUv , vViewDirTS);\n }\n\n\n vec4 texelColor = texture2D(map, uvPOM);\n //texelColor = mapTexelToLinear(texelColor);\n diffuseColor *= texelColor;\n "),e.fragmentShader=e.fragmentShader.replace("#include <normal_fragment_maps>","\n vec3 mapN = texture2D(normalMap, uvPOM).xyz * 2.0 - 1.0;\n mapN.xy *= normalScale;\n normal = normalize( tbn * mapN );\n "),e.fragmentShader=e.fragmentShader.replace("#include <roughnessmap_fragment>","\n float roughnessFactor = roughness;\n #ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, uvPOM );\n // reads channel G, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n roughnessFactor *= texelRoughness.g;\n #endif\n "),e.fragmentShader=e.fragmentShader.replace("#include <metalnesssmap_fragment>","\n float metalnessFactor = metalness;\n #ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, uvPOM );\n // reads channel B, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n metalnessFactor *= texelMetalness.b;\n #endif\n "),e.fragmentShader=e.fragmentShader.replace("#include <aomap_fragment>","\n #ifdef USE_AOMAP\n\n // reads channel R, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n float ambientOcclusion = ( texture2D( aoMap, uvPOM ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n reflectedLight.indirectDiffuse *= ambientOcclusion;\n\n #if defined( USE_CLEARCOAT ) \n clearcoatSpecularIndirect *= ambientOcclusion;\n #endif\n\n #if defined( USE_SHEEN ) \n sheenSpecularIndirect *= ambientOcclusion;\n #endif\n\n #if defined( USE_ENVMAP ) && defined( STANDARD )\n\n float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\n reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\n #endif\n\n #endif\n "),this.userData.shader=e}clone(){const e=super.clone();return e.heightMap=this.heightMap,e.heightScale=this.heightScale,e.parallaxType=this.parallaxType,e.minLayers=this.minLayers,e.maxLayers=this.maxLayers,e}}/*
1
+ import{__decorate as e,__metadata as a}from"tslib";import{Color as t,MeshStandardMaterial as n,Texture as r,Vector2 as i}from"three";import{Shader as s}from"../shader.js";import{Parameter as o}from"../parameter.js";import{removeObjectUndefined as p}from"../../utils/collections.js";const l=new r;export class StandardShader extends s{constructor(){super(...arguments),this.color=new t("#FFFFFF"),this.opacity=1,this.roughness=1,this.metalness=0,this.heightMap=l}build(){const e=null!=this.normalMap&&null!=this.map&&null!=this.heightMap&&this.heightMap!=l&&0!==this.heightScale;return new(e?ParallaxStandardMaterial:n)(p({color:this.color,opacity:this.opacity,roughness:this.roughness,metalness:this.metalness,map:this.map,lightMap:this.lightMap,lightMapIntensity:this.lightMapIntensity,aoMap:this.aoMap,aoMapIntensity:this.aoMapIntensity,emissive:this.emissive,emissiveIntensity:this.emissiveIntensity,emissiveMap:this.emissiveMap,bumpMap:this.bumpMap,bumpScale:this.bumpScale,normalMap:this.normalMap,normalScale:this.normalScale,displacementMap:this.displacementMap,displacementScale:this.displacementScale,displacementBias:this.displacementBias,roughnessMap:this.roughnessMap,metalnessMap:this.metalnessMap,alphaMap:this.alphaMap,envMap:this.envMap,envMapIntensity:this.envMapIntensity,refractionRatio:this.refractionRatio,...e?{heightMap:this.heightMap,heightScale:this.heightScale}:{}}))}}e([o(),a("design:type",t)],StandardShader.prototype,"color",void 0),e([o({label:"Color Map"}),a("design:type",r)],StandardShader.prototype,"map",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"opacity",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"alphaMap",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"roughness",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"roughnessMap",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"metalness",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"metalnessMap",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"lightMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"lightMapIntensity",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"aoMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"aoMapIntensity",void 0),e([o(),a("design:type",t)],StandardShader.prototype,"emissive",void 0),e([o({range:[0,10]}),a("design:type",Number)],StandardShader.prototype,"emissiveIntensity",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"emissiveMap",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"bumpMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"bumpScale",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"normalMap",void 0),e([o(),a("design:type",i)],StandardShader.prototype,"normalScale",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"displacementMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"displacementScale",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"displacementBias",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"envMap",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"envMapIntensity",void 0),e([o({range:[0,1]}),a("design:type",Number)],StandardShader.prototype,"refractionRatio",void 0),e([o(),a("design:type",r)],StandardShader.prototype,"heightMap",void 0),e([o(),a("design:type",Number)],StandardShader.prototype,"heightScale",void 0);export var ParallaxType;!function(e){e[e.none=0]="none",e[e.offset=1]="offset",e[e.pom=2]="pom"}(ParallaxType||(ParallaxType={}));export class ParallaxStandardMaterial extends n{constructor(e={}){super(e),e.heightMap&&(this.heightMap=e.heightMap),this.heightScale=e.heightScale??.05,this.parallaxType=e.parallaxType??ParallaxType.pom,this.minLayers=e.minLayers??10,this.maxLayers=e.maxLayers??32}onBeforeCompile(e){e.uniforms.heightMap={value:this.heightMap},e.uniforms.heightScale={value:this.heightScale},e.uniforms.minLayers={value:this.minLayers},e.uniforms.maxLayers={value:this.maxLayers},e.uniforms.parallaxType={value:this.parallaxType},e.vertexTangents=!0,e.vertexShader=e.vertexShader.replace("#include <uv_pars_vertex>","\n #include <uv_pars_vertex>\n varying vec3 vViewDirTS;\n varying mat3 vTBN;\n "),e.vertexShader=e.vertexShader.replace("#include <begin_vertex>","\n #include <begin_vertex>\n vec3 N = normalize(normalMatrix * normal);\n vec3 T = normalize(normalMatrix * tangent.xyz);\n vec3 B = cross(N, T) * tangent.w;\n vTBN = mat3(T, B, N);\n\n vec3 viewDir = cameraPosition - (modelMatrix * vec4(transformed, 1.0)).xyz;\n vViewDirTS = normalize(vTBN * viewDir);\n "),e.fragmentShader=e.fragmentShader.replace("#include <uv_pars_fragment>","\n #include <uv_pars_fragment>\n uniform sampler2D heightMap;\n uniform float heightScale;\n uniform int minLayers;\n uniform int maxLayers;\n uniform int parallaxType;\n\n varying vec3 vViewDirTS;\n varying mat3 vTBN;\n\n vec2 parallaxOffset(vec2 uv, vec3 viewDirTS) {\n float h = texture(heightMap, uv).r;\n return uv - (viewDirTS.xy / viewDirTS.z) * (h * heightScale);\n }\n\n vec2 parallaxOcclusion2(vec2 uv, vec3 viewDirTS) {\n vec3 viewDir = normalize(vViewPosition);\n vec3 vv = -viewDir * vTBN;\n float parallaxLimit = -length(vv.xy) / vv.z;\n parallaxLimit *= heightScale;\n\n vec2 vOffsetDir = normalize(vv.xy);\n vec2 vMaxOffset = vOffsetDir * parallaxLimit;\n\n // Probably should use actual normal but it might not matter\n vec3 nNormal = vec3(0.0, 0.0, 1.0);\n float nNumSamples = mix(float(maxLayers), float(minLayers), dot(viewDir, nNormal));\n float fStepSize = 1.0 / nNumSamples;\n\n float fCurrRayHeight = 1.0;\n vec2 vCurrOffset = vec2(0.0);\n vec2 vLastOffset = vec2(0.0);\n float fLastSampledHeight = 1.0;\n float fCurrSampledHeight = 1.0;\n\n for (int nCurrSample = 0; nCurrSample < 50; nCurrSample++) {\n if (float(nCurrSample) > nNumSamples) break;\n\n fCurrSampledHeight = texture2D(heightMap, uv + vCurrOffset).r;\n if (fCurrSampledHeight > fCurrRayHeight) {\n float delta1 = fCurrSampledHeight - fCurrRayHeight;\n float delta2 = (fCurrRayHeight + fStepSize) - fLastSampledHeight;\n float ratio = delta1 / (delta1 + delta2);\n vCurrOffset = ratio * vLastOffset + (1.0 - ratio) * vCurrOffset;\n break;\n } else {\n fCurrRayHeight -= fStepSize;\n vLastOffset = vCurrOffset;\n vCurrOffset += fStepSize * vMaxOffset;\n fLastSampledHeight = fCurrSampledHeight;\n }\n }\n\n return uv + vCurrOffset;\n }\n "),e.fragmentShader=e.fragmentShader.replace("#include <map_fragment>","\n vec2 uvPOM = vMapUv ;\n if (parallaxType == 1) {\n uvPOM = parallaxOffset(vMapUv , vViewDirTS);\n } else if (parallaxType == 2) {\n uvPOM = parallaxOcclusion2(vMapUv , vViewDirTS);\n }\n\n\n vec4 texelColor = texture2D(map, uvPOM);\n //texelColor = mapTexelToLinear(texelColor);\n diffuseColor *= texelColor;\n "),e.fragmentShader=e.fragmentShader.replace("#include <normal_fragment_maps>","\n vec3 mapN = texture2D(normalMap, uvPOM).xyz * 2.0 - 1.0;\n mapN.xy *= normalScale;\n normal = normalize( tbn * mapN );\n "),e.fragmentShader=e.fragmentShader.replace("#include <roughnessmap_fragment>","\n float roughnessFactor = roughness;\n #ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, uvPOM );\n // reads channel G, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n roughnessFactor *= texelRoughness.g;\n #endif\n "),e.fragmentShader=e.fragmentShader.replace("#include <metalnesssmap_fragment>","\n float metalnessFactor = metalness;\n #ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, uvPOM );\n // reads channel B, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n metalnessFactor *= texelMetalness.b;\n #endif\n "),e.fragmentShader=e.fragmentShader.replace("#include <aomap_fragment>","\n #ifdef USE_AOMAP\n\n // reads channel R, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\n float ambientOcclusion = ( texture2D( aoMap, uvPOM ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n reflectedLight.indirectDiffuse *= ambientOcclusion;\n\n #if defined( USE_CLEARCOAT ) \n clearcoatSpecularIndirect *= ambientOcclusion;\n #endif\n\n #if defined( USE_SHEEN ) \n sheenSpecularIndirect *= ambientOcclusion;\n #endif\n\n #if defined( USE_ENVMAP ) && defined( STANDARD )\n\n float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\n reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\n #endif\n\n #endif\n "),this.userData.shader=e}clone(){const e=super.clone();return e.heightMap=this.heightMap,e.heightScale=this.heightScale,e.parallaxType=this.parallaxType,e.minLayers=this.minLayers,e.maxLayers=this.maxLayers,e}}/*
2
2
  * Copyright (©) 2025 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hology/core",
3
- "version": "0.0.138",
3
+ "version": "0.0.140",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -168,7 +168,7 @@
168
168
  "dependencies": {
169
169
  "@babel/runtime": "^7.24.8",
170
170
  "@dimforge/rapier3d-compat": "^0.14.0",
171
- "@hology/nebula": "^0.0.138",
171
+ "@hology/nebula": "^0.0.140",
172
172
  "@plumier/reflect": "^1.1.0",
173
173
  "@recast-navigation/three": "0.39.0",
174
174
  "recast-navigation": "0.39.0",