@hology/core 0.0.93 → 0.0.96
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +14 -14
- package/README.md +2 -2
- package/dist/effects/vfx/initializsers.d.ts +10 -3
- package/dist/effects/vfx/initializsers.d.ts.map +1 -1
- package/dist/effects/vfx/initializsers.js +1 -1
- package/dist/effects/vfx/rates.d.ts +8 -0
- package/dist/effects/vfx/rates.d.ts.map +1 -1
- package/dist/effects/vfx/rates.js +1 -1
- package/dist/effects/vfx/vfx-defs.d.ts +38 -1
- package/dist/effects/vfx/vfx-defs.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-defs.js +1 -1
- package/dist/effects/vfx/vfx-materializer.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-materializer.js +1 -1
- package/dist/effects/vfx/vfx-renderers.d.ts +1 -0
- package/dist/effects/vfx/vfx-renderers.d.ts.map +1 -1
- package/dist/effects/vfx/vfx-renderers.js +1 -1
- package/dist/gameplay/actors/builtin/navmesh-actor.d.ts +11 -0
- package/dist/gameplay/actors/builtin/navmesh-actor.d.ts.map +1 -1
- package/dist/gameplay/actors/builtin/navmesh-actor.js +1 -1
- package/dist/gameplay/ai/behavior-tree/move.js +1 -1
- package/dist/gameplay/ai/dynamic-tiled-navmesh.d.ts.map +1 -1
- package/dist/gameplay/ai/dynamic-tiled-navmesh.js +1 -1
- package/dist/gameplay/ai/navigation.d.ts +8 -0
- package/dist/gameplay/ai/navigation.d.ts.map +1 -1
- package/dist/gameplay/ai/navigation.js +1 -1
- package/dist/gameplay/services/physics/physics-system.d.ts.map +1 -1
- package/dist/gameplay/services/physics/physics-system.js +1 -1
- package/dist/rendering.d.ts +1 -0
- package/dist/rendering.d.ts.map +1 -1
- package/dist/rendering.js +1 -1
- package/dist/scene/asset-resource-loader.js +1 -1
- package/dist/scene/collision/collision-shape-import.d.ts.map +1 -1
- package/dist/scene/collision/collision-shape-import.js +1 -1
- package/dist/scene/landscape/landscape-manager.d.ts.map +1 -1
- package/dist/scene/landscape/landscape-manager.js +1 -1
- package/dist/scene/materializer.d.ts +11 -2
- package/dist/scene/materializer.d.ts.map +1 -1
- package/dist/scene/materializer.js +1 -1
- package/dist/scene/model.d.ts +3 -3
- package/dist/scene/model.d.ts.map +1 -1
- package/dist/scene/objects/prefab.d.ts +8 -0
- package/dist/scene/objects/prefab.d.ts.map +1 -0
- package/dist/scene/objects/prefab.js +4 -0
- package/dist/scene/scene-data-service.d.ts +17 -7
- package/dist/scene/scene-data-service.d.ts.map +1 -1
- package/dist/scene/scene-data-service.js +1 -1
- package/dist/scene/storage/storage.d.ts +9 -8
- package/dist/scene/storage/storage.d.ts.map +1 -1
- package/dist/scene/storage/storage.js +1 -1
- package/dist/shader/builtin/decal-standard-shader.d.ts +24 -0
- package/dist/shader/builtin/decal-standard-shader.d.ts.map +1 -0
- package/dist/shader/builtin/decal-standard-shader.js +4 -0
- package/dist/shader/builtin/decal-unlit-shader.d.ts +12 -0
- package/dist/shader/builtin/decal-unlit-shader.d.ts.map +1 -0
- package/dist/shader/builtin/decal-unlit-shader.js +4 -0
- package/dist/shader/decal-shader.d.ts +7 -0
- package/dist/shader/decal-shader.d.ts.map +1 -0
- package/dist/shader/decal-shader.js +4 -0
- package/dist/shader-nodes/decal.d.ts +8 -0
- package/dist/shader-nodes/decal.d.ts.map +1 -0
- package/dist/shader-nodes/decal.js +4 -0
- package/dist/shader-nodes/depth.d.ts +8 -0
- package/dist/shader-nodes/depth.d.ts.map +1 -1
- package/dist/shader-nodes/depth.js +1 -1
- package/dist/shader-nodes/index.d.ts +1 -0
- package/dist/shader-nodes/index.d.ts.map +1 -1
- package/dist/shader-nodes/index.js +1 -1
- package/dist/shader-nodes/particle.d.ts +4 -2
- package/dist/shader-nodes/particle.d.ts.map +1 -1
- package/dist/shader-nodes/particle.js +1 -1
- package/dist/utils/math.js +1 -1
- package/package.json +3 -3
- package/tsconfig.tsbuildinfo +1 -1
@@ -1,4 +1,4 @@
|
|
1
|
-
import{ConvexPolyhedronCollisionShape as e}from"@hology/core";import{Subject as t}from"rxjs";import*as a from"three";import{BoxGeometry as s,Color as r,Euler as i,Fog as n,FogExp2 as o,Group as l,Material as c,Matrix4 as h,Mesh as d,MeshLambertMaterial as m,MeshPhongMaterial as p,MeshStandardMaterial as u,Object3D as f,PointLight as y,Quaternion as g,SphereGeometry as w,Texture as v,Vector2 as S,Vector3 as A,Vector4 as b}from"three";import M,{SpriteRenderer as x}from"@hology/nebula";import{bool as j,BooleanNode as P,float as I,FloatNode as E,NodeShaderMaterial as V,rgb as D,RgbNode as N,Texture2dLookupNode as k,textureSampler2d as C,vec2 as F,Vec2Node as _,vec3 as O,Vec3Node as z,vec4 as B}from"three-shader-graph";import{VfxActor as T}from"../effects/vfx/vfx-actor.js";import{VisualEffect as W}from"../effects/vfx/vfx-param.js";import{BaseActor as $}from"../gameplay/actors/actor.js";import R from"../gameplay/actors/builtin/index.js";import{PhysicsBodyType as U,withInjectionContext as G}from"../gameplay/index.js";import{Sampler2DNode as L}from"../shader-nodes/index.js";import{LambertShader as J}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as H}from"../shader/builtin/landscape-composite-shader";import{LandscapeShader as q}from"../shader/builtin/landscape-shader.js";import{StandardShader as X}from"../shader/builtin/standard-shader.js";import{UnlitShader as Y}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as Z}from"../shader/parameter.js";import{ArrayMap as Q,groupBy as K}from"../utils/collections.js";import{iterateMaterials as ee}from"../utils/materials.js";import{filterChildrenShallow as te,filterSceneShallow as ae,findFirstVisibleObject as se}from"../utils/three/traverse.js";import{AssetMeshInstance as re}from"./asset-resource-loader.js";import{isCollisionMesh as ie}from"./collision/collision-shape-import.js";import{BoxCollisionShape as ne,PhysicalShapeMesh as oe}from"./collision/collision-shape.js";import{LandscapeManager as le}from"./landscape/landscape-manager.js";import{initLandscape as ce}from"./landscape/landscape.js";import{SectionGrid as he,smoothNormalsCrossMeshes as de}from"./landscape/utils.js";import{createGrassFoliageMaterial as me}from"./materials/grass-foliage.js";import{createGrassMaterial as pe}from"./materials/grass.js";import{getMaterialAttribute as ue}from"./materials/utils/material-painting.js";import{createWaterMaterial as fe}from"./materials/water.js";import{SerializedParamType as ye}from"./model.js";import{ShapeLibrary as ge,ShapeLibraryKeys as we}from"./objects/shapes.js";import{ambientLightName as ve,createSky as Se,defaultSkyMaterial as Ae}from"./sky.js";import{Curve2 as be}from"../utils/curve.js";const Me={};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 SceneMaterializer(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}export class SceneMaterializer{constructor(e,s,r,i,n,o,l,c){this.scene=e,this.dataProvider=s,this.assetsService=r,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 t,this.removed$=new t,this.error$=new t,this.editorActorParamSnapshot=new Map,this.assets=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,this.pmremGeneratorResults=new WeakMap,this.geometryCache=new Map,this.collisionShapeCache=new Map,this.originalFog=null,s.onUpdate((e=>this.update(e))),s.onRemove((e=>this.remove(e))),this.createAssetSubscription=r.onCreate.subscribe((e=>{this.assets.set(e.id,e)})),this.updateSubscription=r.onUpdate.subscribe((async t=>{this.assets.set(t.id,t),"material"==t.type?e.traverse((e=>{if(e instanceof a.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=>{_e(e.userData.src.materialAssignments,t.materialAssignments).forEach((t=>{this.applyMaterial(e,t)}))})),this.landscapeManagers.forEach((e=>{e.source.grass.layers.some((e=>e.meshes.some((e=>e.assetId===t.id))))&&e.queueRefreshScatter(this.renderingView?.camera.position??new A,!0)}))):"prefab"===t.type&&this.findByAssetId(t.id).forEach((e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t)}))}))}async refreshMaterial(e,t,a,s){const r=t?.userData?.assetId;if(r!==a.id){const e=this.assets.get(r);let t=!1;if(null!=e)for(const s of Object.values(e.material.shaderParams)){if(s.type===ye.Material&&s.value===a.id){t=!0;break}if(s.type===ye.Array&&"element"in s&&s.element===ye.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);i.userData=t.userData,null!=s?ze(e.material[s],i)||(e.material[s]=i):ze(e.material,i)||(e.material=i)}get actorInstances(){return Array.from(this.materializedActors.values())}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)})))))}async init(){await this.preInit(),je.clear(),await this.prefetchAssets(),await Promise.all(this.dataProvider.getObjects().map((e=>this.materialize(e)))),await this.initActorsPostInit()}initActorsPostInit(e=this.actorInstances){const t=e.map((async e=>{const t=e.object.userData.src;if("vfx"===t.type)return Promise.resolve();const a=await this.assetsService.getAsset(t.assetId),s={...a?.actor?.params??{},...t.actor?.params??{}};for(const a of t.actor.innerParams??[])await this.applyActorComponentParams(e,a.path.slice(),a.params);const r=await Ve(s,e.constructor,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders,this.actorProvider);Object.assign(e,r);try{return await this.actorProvider.initActor(e)}catch(e){console.error(`Failed to initiate actor (name="${t.name}", id=${t.id})`,e)}}));return Promise.all(t)}addVfxChildActors(e,t=e){}async applyActorComponentParams(e,t,a){const s=t.length,r=t.shift();if(0==s){const t=await Ve(a,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders);for(const[a,s]of Object.entries(t))null!=s&&(e[a]=s)}else null!=e[r]&&await this.applyActorComponentParams(e[r],t,a)}canObjectBeInstanced(e){return e.physics?.type!==U.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=>{!ie(e)&&e.isMesh&&a.push(e)}));const s=1==a.length&&0==a[0].children.length,r=a[0]instanceof d&&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)}))}async initWithInstancing(){await this.preInit(),await this.prefetchAssets();const t=[],s=new Q,n=new Q;for(const e of this.dataProvider.getObjects())await Fe(e,(async(e,a,i)=>{const o="asset_mesh"==e.type&&this.canObjectBeInstanced(e)&&await this.canAssetBeInstanced(e),l="shape_mesh"===e.type&&"landscape"!==e.shape&&e.physics?.type!==U.dynamic;if(o||l){if(a&&a.children?.length>0){const t=a.children.findIndex((t=>t.id===e.id));t>=0&&a.children.splice(t,1)}if(l){let t=e.shape+JSON.stringify(e.shapeParams??{})+e.castShadow+e.receiveShadow;const a=e.materialAssignments?.at(0)?.materialId,s=null!=a?this.assets.get(a):null;let o=null;if(null!=s&&"shader"!==s.material.type){if(t+=s.material.type+s.material.shader,null!=s.material.shaderParams){if(t+=Object.entries(s.material.shaderParams).filter((([e,t])=>"color"!=e)).map((e=>JSON.stringify(e))).join(),null!=s.material.shaderParams.color){const e=s.material.shaderParams.color;e.type===ye.Color&&null!=e.value&&(o=new r(e.value))}}}else t+=a;n.push(t,{object:{...e,parentTransform:i},color:o})}else{const t=e.assetId+JSON.stringify(e.materialAssignments??[]);s.push(t,{...e,parentTransform:i})}}else null==a&&t.push({...e,parentTransform:i})}));for(const t of s.values()){if(0==t.length)continue;const a=await this.createFromAsset(t[0]);if(null==a)continue;const s=await this.createInstancedMesh(t,a),r=new re;r.add(s),r.userData.src=t[0],a instanceof re&&(r.collisionShapes=a.collisionShapes),r.collisionShapes.forEach((t=>{t instanceof e&&t.mesh instanceof d&&(t.mesh=t.mesh.geometry)})),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r)}for(const e of n.values()){if(0==e.length)continue;const t=e[0].object,s=await this.createFromShape(t),n=se(s,(e=>!ie(e)&&null!=e.geometry)),o=n.material.clone();null!=e[0].color&&null!=o.color&&(o.color=new r(16777215));const l=n.geometry,c=new a.InstancedMesh(l,o,e.length);for(let t=0;t<e.length;t++){const r=e[t],o=(new a.Matrix4).compose((new A).fromArray(r.object.position),(new g).setFromEuler((new i).fromArray(r.object.rotation)),(new A).fromArray(r.object.scale)),l=(new h).copy(r.object.parentTransform).multiply(o);c.setMatrixAt(t,l),null!=r.color&&c.setColorAt(t,r.color),c.castShadow=s.castShadow??!0,c.receiveShadow=n.receiveShadow??!0;const d=new re;d.add(c),d.userData.src=e[0],s instanceof oe&&(d.collisionShapes=[s.collisionShape]),d.castShadow=!1,d.receiveShadow=!1,this.scene.add(d)}}await Promise.all(t.map((e=>this.materialize(e)))),await this.initActorsPostInit()}async createInstancedMesh(e,t){const s=se(t,(e=>!ie(e)&&null!=e.geometry)),r=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,_e(e[0].materialAssignments,r.materialAssignments)),s.updateMatrix();const n=s.geometry.clone(),o=new a.InstancedMesh(n,s.material,e.length);for(let t=0;t<e.length;t++){const r=(new a.Matrix4).compose((new A).fromArray(e[t].position),(new g).setFromEuler((new i).fromArray(e[t].rotation)),(new A).fromArray(e[t].scale)),n=(new h).copy(e[t].parentTransform).multiply(r).multiply(s.matrixWorld);o.setMatrixAt(t,n)}return o.castShadow=e[0].castShadow??r.castShadow??!0,o.receiveShadow=e[0].receiveShadow??r.receiveShadow??!0,s.material instanceof c&&o.castShadow&&o.receiveShadow&&(o.material.side=a.FrontSide),o}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){const t=this.materializedActors.get(e.id);null!=t?(t.disposed.next(!0),t.onEndPlay()):console.warn("Failed to remove actor",e)}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 ae(this.scene,(t=>t.userData.src?.assetId==e),(e=>null!=e.userData.src))}applyMaterials(e,t){return null==t?Promise.resolve([]):Promise.all(t.filter((e=>"null"!==e.materialId)).map((t=>this.applyMaterial(e,t))))}async applyMaterial(e,t){await applyMaterial(e,t,(e=>{const t=this.assets.get(e);if(null!=t)try{return materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders)}catch(e){console.error("Failed to apply material",e)}}),this._originalMaterials)}unapplyMaterials(e){e.traverse((async e=>{if(e instanceof d)if(e.material instanceof Array)for(let t=0;t<e.material.length;t++)e.material[t]=this._originalMaterials.get(e.id+"#"+t)??e.material[t];else e.material=this._originalMaterials.get(e.id)??e.material}))}updateActors(e){console.log("update actors"),this.actorTypes=e;const t=new Set(Object.values(R));ae(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 je.entries())t.userData.customShaderName&&je.delete(e);this.landscapeManagers.forEach((t=>t.updateShaders(e))),ae(this.scene,(e=>!0)).forEach((e=>{e.traverse((async e=>{if(e instanceof d)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++){const a=e.material[t].userData?.customShaderName;if(null!=a){const a=this.assets.get(e.material[t].userData.assetId);this.refreshMaterial(e,e.material[t],a,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=this.assets.get(e.material.userData.assetId);this.refreshMaterial(e,e.material,t)}}}))}))}async update(e){if("sky"===e.type&&null!=this.sky&&null!=this.sky.parent)return void this.updateSky(e);if("world_env"===e.type&&null!=this.worldEnvObj)return void this.updateWorldEnv(e);const t=this.sceneObjectMap.get(e.id);if(t){let s=!1;if(t.traverseAncestors((e=>{"_hology_transform_group"===e.name&&(s=!0)})),!s){const a=this.findParent(e);null!=a&&a.uuid!=t.uuid?a.attach(t):console.error("Parent is wrong")}if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(t);this.inEditor&&e.hidden&&!1?t.traverse((e=>{e instanceof d&&(e.material.wireframe=!0)})):t.traverse((e=>{e instanceof d&&(e.material.wireframe=!1)}))}if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);_e(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 r(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"directional"===e.light.type?this.applyDirectionalLight(e.light.directional):"ambient"===e.light.type&&this.applyDirectionalAmbientLight(t,e.light.ambient);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 o?"density":"linear")!==e.fog.type;this.scene.fog=ke(e.fog),t&&(a=this.scene).traverse((e=>{if(e instanceof d){const t=e.material;t instanceof V&&(a.fog instanceof n?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof o&&(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.editorActorParamSnapshot.get(e.id);null!=t&&t===JSON.stringify(e.actor)||(console.log("Rematerializing actor because parameters changed"),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 oe&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&xe(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)){console.log("materialize actor and init");const a=await this.materialize(e,t);return Fe(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:te(t,(t=>t.children?.some((t=>t.id===e.id))),(()=>!0))))[0];return null==t?this.scene:null!=t?ae(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 r(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse((e=>{e instanceof d&&e.geometry&&(t=e)})),t}applyVertexMaterials(e,t){if(null==e.vertexMaterials||0===e.vertexMaterials.length)return;let a=1;for(const t of e.vertexMaterials)a=Math.max(t.w.length,a);const s=K(e.vertexMaterials,(e=>e.m));t.traverse((e=>{if(e instanceof d){if(null==e.geometry)return;if(Be(ue(e,0,!1)),a>0){Be(ue(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=ue(s,0,!0);Be(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=ue(s,4,!0);Be(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){let r;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=ke(e.fog),this.fixFogColor(),r=new l;break;case"sky":this.sky=Se(),this.updateSky(e),r=this.sky;break;case"world_env":this.updateWorldEnv(e),r=new l,this.worldEnvObj=r;break;case"actor":r=await this.createFromActor(e);break;case"group":r=new l;break;case"prefab":r=await this.createFromPrefabAsset(e);break;case"vfx":r=await this.createFromVfx(e);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),this.inEditor,this.inEditor){let e=null;r instanceof oe&&(e=function(e){if(e instanceof ne)return new d(new s(...e.offset.toArray()),Ce);return null}(r.collisionShape)),null!=e&&(e.layers.disable(0),e.layers.enable(18),e.scale.multiplyScalar(1.1),r.add(e))}return this.objectMap.set(r.uuid,e),this.sceneObjectMap.set(e.id,r),e.physics?.type!==U.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==U.dynamic||Ne(r),this.renderingView.renderer.shadowMap.needsUpdate=!0,r}}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 s=e.worldEnv.environment;null!=s&&null!=s.textureId?this.assetManagerService.getTexture(this.assets.get(s.textureId)).then((e=>{null==this.pmremGenerator&&(this.pmremGenerator=new a.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=s.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=Ae);const t=await this.assetsService.getAsset(e.sky.materialId),s=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);s.side=a.BackSide,(s instanceof u||s instanceof a.MeshBasicMaterial||s instanceof a.ShaderMaterial)&&(s.fog=!1),null!=this.sky?this.sky.material=s:console.warn("No sky has been created")}async createComponent(e,t,a,s){const r=new Me[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){const t=this.actorTypes.find((t=>t.name===e.actor?.type))?.type??R[e.actor?.type];if(null==t)return null;this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const a=await this.actorProvider.create(t,(new A).fromArray(e.position),(new i).fromArray(e.rotation),!0);return this.materializedActors.set(e.id,a),a?.object}async createFromVfx(e){const t=await this.assetsService.getAsset(e.assetId);null==t&&console.error("Could not find asset",e);const a=await this.actorProvider.create(T,(new A).fromArray(e.position),(new i).fromArray(e.rotation),!1);return await a.fromAsset(t),a.play(),this.materializedActors.set(e.id,a),a?.object}cleanup(){this.materializedActors.clear()}async createFromShape(e){const t=this.inEditor&&e.hidden;let a;if("landscape"==e.shape)a=this.createLandscape(e),a.traverse((e=>{e instanceof d&&this._originalMaterials.set(e.id,e.material)}));else{let s=new u({name:"Default",color:new r("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});const i=await this.createMeshByShape(e.shape,s,e.shapeParams);i.castShadow=e.castShadow??!0,i.receiveShadow=e.castShadow??!1,e.collisionDetection||(i.collisionShape=null),i.physics=e.physics,a=i,this._originalMaterials.set(a.id,i.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 l;const a=ce(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new le(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 he(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((()=>de(r)),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&we.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);return this.geometryCache.has(r)||this.geometryCache.set(r,ge[e].geometry(s)),this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,ge[e].collision(s)),new oe(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});_e(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,xe(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 d&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()})),a}async createFromPrefabAsset(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}`);const a=new l;return t.prefab.objects.filter((e=>"global_fog"!==e.type&&"world_env"!==e.type)).forEach((e=>this.materialize(e,a,!0))),a}async createParticleSystem(e){const t=await this.assetsService.getAsset(e.assetId),s=new f;return await M.fromJSONAsync(t.particleSystem,a).then((e=>{const t=new x(s,a);e.addRenderer(t),this.renderingView.onLoop((t=>e.update()))})),s}async createLight(e){if("point"===e.light.type){const t=new y(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 w(.3,10,10),a=new u({color:new r(16771709)}),s=new d(e,a);t.add(s)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional),new l):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient),new l):void 0}applyDirectionalAmbientLight(e,t){const a=this.scene.children.find((e=>e.name===ve));null!=a?(a.intensity=t.intensity,a.color.set(t.color),a.groundColor.set(t.color)):console.warn("Couldn't find ambient light")}applyDirectionalLight(e){for(const t of this.renderingView.csm.lights)t.intensity=e.intensity,t.color.set(e.color),t.castShadow=e.castShadow;this.renderingView.csm.lightDirection.fromArray(e.direction).normalize()}dispose(){this.updateSubscription.unsubscribe(),this.createAssetSubscription.unsubscribe(),this.materializedActors.forEach((e=>e.disposed.next(!0)))}}function xe(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse((e=>{e.castShadow=t,e.receiveShadow=a}))}const je=new Map,Pe=new Map,Ie=new m({color:16711935}),Ee=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){const n=JSON.stringify(e.material);return i&&je.has(n)?je.get(n):i&&Pe.has(n)?await Pe.get(n):Pe.set(n,_materialFromAsset(n,e,t,a,s,r,i)).get(n)}export async function _materialFromAsset(e,t,s,i,n,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 r(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 i.getAsset(e);null!=a&&(c.map=await n.getTexture(a))}let d;switch(t.material.type){case"phong":d=new p({...c,...h});break;case"water":d=fe(c,s);break;case"grassFoliage":d=me({color:c.color,map:c.map},s);break;case"grass":d=pe({...c,colorTwo:new r(t.material.params.colorTwo),colorThree:new r(t.material.params.colorThree)},s);break;case"standard":case"unlit":case"lambert":case"shader":case"landscape":case"landscape-composite":const e={standard:X,lambert:J,unlit:Y,landscape:q,"landscape-composite":H}[t.material.type]??o.find((e=>e.name==t.material.shader))?.type;if(e){try{let a=new e;const r=await Ve(t.material?.shaderParams??{},e,i,n,null,s,o);Object.assign(a,r),d=a.build()}catch(e){console.log("Shader runtime error: "+e),Ee.has(t.material.shader)||Ee.set(t.material.shader,Ie.clone()),d=Ee.get(t.material.shader)}d.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),d=Ie;break;default:throw new Error("Unsupported material type"+t.material.type)}return s?.csm.setupMaterial(d),null!=s&&je.set(e,d),d.side=t.material.side??d.side??a.FrontSide,d.transparent=(t.material.transparent??c.transparent??!1)||d.transparent,d.alphaTest=t.material.alphaTest??d.alphaTest??0,t.material.bloom&&(d.userData.hasBloom=!0),d.userData.assetId=t.id,Pe.delete(e),d}async function Ve(e,t,a,s,r,i,n,o){const l={};for(const[t,c]of Object.entries(e)){const e=await De(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 De(s,null,null,null);null!=e&&(t[a]=e)}return t}async function De(e,t,a,s,n,o,l,c=e.value,h=e.type){if(null==e||null==c||""===c)return null;switch(h){case ye.Array:if(Array.isArray(c)&&"element"in e)return await Promise.all(c.map((r=>De(e,t,a,s,n,o,l,r,e.element))));break;case ye.Number:case ye.FloatNode:let h="string"==typeof c?parseFloat(c):c;return e.type===ye.FloatNode?I(h):h;case ye.Texture:return await a.getTexture(await t.getAsset(c));case ye.Sampler2DNode:return C(await a.getTexture(await t.getAsset(c)));case ye.Boolean:return c;case ye.BooleanNode:return j(c);case ye.Vector2:case ye.Vec2Node:if("object"==typeof c){const t=c instanceof Array?(new S).fromArray(c):new S(c.x,c.y);return e.type===ye.Vec2Node?F(t):t}return null;case ye.Vector3:case ye.Vec3Node:if("object"==typeof c){const t=c instanceof Array?(new A).fromArray(c):new A(c.x,c.y,c.z);return e.type===ye.Vec3Node?O(t):t}return null;case ye.Color:case ye.RgbNode:const d=new r(c);return e.type===ye.RgbNode?D(d):d;case ye.String:return c;case ye.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 ye.Euler:const p=c;return(new i).fromArray(p);case ye.Object3D:return(await a.getMesh(await t.getAsset(c))).scene;case ye.Material:return await materialFromAsset(await t.getAsset(c),n,t,a,o);case ye.AudioBuffer:return await a.getAudio(await t.getAsset(c));case ye.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 W(l,u);console.error("Using a non-vfx asset for visual effect parameter");break;case ye.Curve:return be.decode(c)}return null}function Ne(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 ke(e){return"linear"===e.type?new n(new r(e.color),e.near??100,e.far??1e3):"density"===e.type?new o(e.color,e.density):void console.warn("Invalid fog type",e)}const Ce=new u({color:4229780});async function Fe(e,t,s,r){null==r&&(r=(new h).identity()),await t(e,s,r);const n=r.clone().multiply(function(e,t){if(null==e.position||null==e.rotation||null==e.scale)return t.identity();return t.compose((new A).fromArray(e.position),(new g).setFromEuler((new i).fromArray(e.rotation)),(new A).fromArray(e.scale))}(e,new a.Matrix4));return Promise.all((e.children??[]).map((a=>Fe(a,t,e,n))))}export function toSerializedParamType(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?ye.Number:t instanceof E||"function"==typeof e.prototype.isFloat?ye.FloatNode:t instanceof v||e===v||e.isTexture?ye.Texture:t instanceof L||e===k?ye.Sampler2DNode:t instanceof Boolean||e===Boolean?ye.Boolean:t instanceof P?ye.BooleanNode:t instanceof r||e==r?ye.Color:t instanceof N||"function"==typeof e.prototype.isRgb?ye.RgbNode:t instanceof S||e==S?ye.Vector2:t instanceof _||"function"==typeof e.prototype.isVec2?ye.Vec2Node:t instanceof A||e==A?ye.Vector3:t instanceof z||"function"==typeof e.prototype.isVec3?ye.Vec3Node:t instanceof String||e===String?ye.String:t instanceof $||e==$||e.prototype instanceof $||e.prototype==$?ye.BaseActor:t instanceof i||e==i?ye.Euler:t instanceof f||e==f?ye.Object3D:t instanceof c||e==c?ye.Material:t instanceof AudioBuffer||e==AudioBuffer?ye.AudioBuffer:t instanceof W||e==W?ye.VisualEffect:t instanceof be||e==be?ye.Curve: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?ye.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=Z(e);if(0===s.length)return{};let r;null!=a?G(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 A:return t instanceof A?t.toArray():void a();case b:return t instanceof b?t.toArray():void a();case r:return t instanceof r?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new r(t).getHexString():void a();case String:return t;case i:return t instanceof i?t.toArray():void a()}}function _e(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=>Oe(e.materialId))),(t??[]).filter((e=>Oe(e.materialId))),(e=>e.color+e.name))}function Oe(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[ye.RgbNode,"#000000"],[ye.Color,"#000000"],[ye.Vector4,[0,0,0,0]],[ye.Vec4Node,[0,0,0,0]],[ye.Vector3,[0,0,0]],[ye.Vec3Node,[0,0,0]],[ye.Vector2,[0,0]],[ye.Vec2Node,[0,0]],[ye.Euler,[0,0,0,"XYZ"]],[ye.Array,[]]]);export function applyMaterial(e,t,s,i){const n=[];return e.traverse((async e=>{if(e instanceof d||e.isMesh||e instanceof a.SkinnedMesh||e.isSkinnedMesh)for(const t of ee(e.material))t.hasOwnProperty("color")&&n.push(e)})),Promise.all(n.map((async e=>{if(e.material instanceof Array)for(let a=0;a<e.material.length;a++){const n=e.material[a];if(null==n.color||!(n.color instanceof r))continue;const o="#"+n.color.getHexString(),l=n.name;if(o===t.color&&(n.name===t.name||null==t.name)||e.userData["originalColor_"+a]===t.color&&e.userData["originalMaterialName_"+a]===t.name){const r=await s(t.materialId),n=e.material[a];null!=r&&n.id!=r.id&&(e.material[a]=r,e.userData["originalColor_"+a]=e.userData["originalColor_"+a]??o,e.userData["originalMaterialName_"+a]=e.userData["originalMaterialName_"+a]??l,null!=i&&i.set(e.id+"#"+a,n))}}else if("color"in e.material){const a="#"+e.material.color.getHexString(),r=e.material.name;if(a===t.color&&(e.material.name===t.name||null==t.name)||e.userData.originalColor===t.color&&e.userData.originalName===t.name){const n=await s(t.materialId),o=e.material;null!=n&&(e.material=n,e.userData.originalColor=e.userData.originalColor??a,e.userData.originalMaterialName=e.userData.originalMaterialName??r,null!=i&&(i.has(e.id)||i.set(e.id,o)))}}})))}function ze(e,t){if(e instanceof a.ShaderMaterial&&t instanceof a.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof a.ShaderMaterial&&t instanceof a.ShaderMaterial){for(const a in e.uniforms){if(null==t.uniforms[a])return!1;if(t.uniforms[a].value!==e.uniforms[a].value)return console.log("Different values",t.uniforms[a].value,e.uniforms[a].value),!1}return!0}return!1}(e,t)}return!1}function Be(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}/*
|
1
|
+
import{ConvexPolyhedronCollisionShape as e}from"@hology/core";import{Subject as t}from"rxjs";import*as a from"three";import{BoxGeometry as s,Color as r,Euler as i,Fog as n,FogExp2 as o,Group as l,Material as c,Matrix4 as h,Mesh as d,MeshLambertMaterial as m,MeshPhongMaterial as p,MeshStandardMaterial as u,Object3D as f,PointLight as y,Quaternion as g,SphereGeometry as w,Texture as v,Vector2 as S,Vector3 as A,Vector4 as b}from"three";import M,{SpriteRenderer as x}from"@hology/nebula";import{bool as j,BooleanNode as P,float as I,FloatNode as E,NodeShaderMaterial as V,rgb as D,RgbNode as N,Texture2dLookupNode as C,textureSampler2d as k,vec2 as _,Vec2Node as F,vec3 as O,Vec3Node as T,vec4 as z}from"three-shader-graph";import{VfxActor as B}from"../effects/vfx/vfx-actor.js";import{VisualEffect as W}from"../effects/vfx/vfx-param.js";import{BaseActor as $}from"../gameplay/actors/actor.js";import R from"../gameplay/actors/builtin/index.js";import{PhysicsBodyType as U,withInjectionContext as G}from"../gameplay/index.js";import{Sampler2DNode as L}from"../shader-nodes/index.js";import{LambertShader as J}from"../shader/builtin/lambert-shader.js";import{LandscapeCompositeShader as H}from"../shader/builtin/landscape-composite-shader";import{LandscapeShader as q}from"../shader/builtin/landscape-shader.js";import{StandardShader as X}from"../shader/builtin/standard-shader.js";import{UnlitShader as Y}from"../shader/builtin/unlit-shader.js";import{extractShaderParameters as Z}from"../shader/parameter.js";import{ArrayMap as Q,groupBy as K}from"../utils/collections.js";import{iterateMaterials as ee}from"../utils/materials.js";import{filterChildrenShallow as te,filterSceneShallow as ae,findFirstVisibleObject as se}from"../utils/three/traverse.js";import{AssetMeshInstance as re}from"./asset-resource-loader.js";import{isCollisionMesh as ie}from"./collision/collision-shape-import.js";import{BoxCollisionShape as ne,PhysicalShapeMesh as oe}from"./collision/collision-shape.js";import{LandscapeManager as le}from"./landscape/landscape-manager.js";import{initLandscape as ce}from"./landscape/landscape.js";import{SectionGrid as he,smoothNormalsCrossMeshes as de}from"./landscape/utils.js";import{createGrassFoliageMaterial as me}from"./materials/grass-foliage.js";import{createGrassMaterial as pe}from"./materials/grass.js";import{getMaterialAttribute as ue}from"./materials/utils/material-painting.js";import{createWaterMaterial as fe}from"./materials/water.js";import{SerializedParamType as ye}from"./model.js";import{ShapeLibrary as ge,ShapeLibraryKeys as we}from"./objects/shapes.js";import{ambientLightName as ve,createSky as Se,defaultSkyMaterial as Ae}from"./sky.js";import{Curve2 as be}from"../utils/curve.js";import{DecalUnlitShader as Me}from"../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as xe}from"../shader/builtin/decal-standard-shader.js";const je={};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 SceneMaterializer(e,this.dataProvider,this.assetsService,this.assetManagerService,t,[],[],{create:()=>null,initActor:async()=>{}})}}export class SceneMaterializer{constructor(e,s,r,i,n,o,l,c){this.scene=e,this.dataProvider=s,this.assetsService=r,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 t,this.removed$=new t,this.error$=new t,this.editorActorParamSnapshot=new Map,this.assets=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,this.pmremGeneratorResults=new WeakMap,this.geometryCache=new Map,this.collisionShapeCache=new Map,this.originalFog=null,s.onCreate((e=>this.update(e))),s.onUpdate((e=>this.update(e))),s.onRemove((e=>this.remove(e))),this.createAssetSubscription=r.onCreate.subscribe((e=>{this.assets.set(e.id,e)})),this.updateSubscription=r.onUpdate.subscribe((async t=>{this.assets.set(t.id,t),"material"==t.type?e.traverse((e=>{if(e instanceof a.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=>{Te(e.userData.src.materialAssignments,t.materialAssignments).forEach((t=>{this.applyMaterial(e,t)}))})),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 A,!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=>{Oe(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===ye.Material&&s.value===a.id){t=!0;break}if(s.type===ye.Array&&"element"in s&&s.element===ye.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,null!=s?Be(e.material[s],i)||(e.material[s]=i):Be(e.material,i)||(e.material=i)}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===ye.Texture&&"string"==typeof t.value){const a=this.assets.get(t.value),s=await this.assetManagerService.getTexture(a);null!=s&&e.push(s)}}))),await Promise.all(Array.from(this.assets.values()).map((async t=>{if("texture"===t.type){const a=await this.assetManagerService.getTexture(t);e.push(a)}}))),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(),Ie.clear(),await this.prefetchAssets(),await Promise.all(this.dataProvider.getObjects().map((e=>this.materialize(e)))),await this.initActorsPostInit()}initActorsPostInit(e=this.actorInstances){const t=e.map((async e=>{const t=e.object.userData.src??e.object.userData._src;if("vfx"===t.type)return Promise.resolve();const a=await this.assetsService.getAsset(t.assetId),s={...a?.actor?.params??{},...t.actor?.params??{}};for(const a of t.actor.innerParams??[])await this.applyActorComponentParams(e,a.path.slice(),a.params);const r=await Ne(s,e.constructor,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders,this.actorProvider);Object.assign(e,r);try{return await this.actorProvider.initActor(e)}catch(e){console.error(`Failed to initiate actor (name="${t.name}", id=${t.id})`,e)}}));return Promise.all(t)}addVfxChildActors(e,t=e){}async applyActorComponentParams(e,t,a){const s=t.length,r=t.shift();if(0==s){const t=await Ne(a,null,this.assetsService,this.assetManagerService,this.materializedActors,this.renderingView,this.shaders);for(const[a,s]of Object.entries(t))null!=s&&(e[a]=s)}else null!=e[r]&&await this.applyActorComponentParams(e[r],t,a)}canObjectBeInstanced(e){return e.physics?.type!==U.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=>{!ie(e)&&e.isMesh&&a.push(e)}));const s=1==a.length&&0==a[0].children.length,r=a[0]instanceof d&&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)}))}async initWithInstancing(){await this.preInit(),await this.prefetchAssets();const t=[],s=new Q,n=new Q;for(const e of this.dataProvider.getObjects())await Oe(e,(async(e,a,i)=>{const o="asset_mesh"==e.type&&this.canObjectBeInstanced(e)&&await this.canAssetBeInstanced(e),l="shape_mesh"===e.type&&"landscape"!==e.shape&&e.physics?.type!==U.dynamic;if(o||l){if(a&&a.children?.length>0){const t=a.children.findIndex((t=>t.id===e.id));t>=0&&a.children.splice(t,1)}if(l){let t=e.shape+JSON.stringify(e.shapeParams??{})+e.castShadow+e.receiveShadow;const a=e.materialAssignments?.at(0)?.materialId,s=null!=a?this.assets.get(a):null;let o=null;if(null!=s&&"shader"!==s.material.type){if(t+=s.material.type+s.material.shader,null!=s.material.shaderParams){if(t+=Object.entries(s.material.shaderParams).filter((([e,t])=>"color"!=e)).map((e=>JSON.stringify(e))).join(),null!=s.material.shaderParams.color){const e=s.material.shaderParams.color;e.type===ye.Color&&null!=e.value&&(o=new r(e.value))}}}else t+=a;n.push(t,{object:{...e,parentTransform:i},color:o})}else{const t=e.assetId+JSON.stringify(e.materialAssignments??[]);s.push(t,{...e,parentTransform:i})}}else null==a&&t.push({...e,parentTransform:i})}));for(const t of s.values()){if(0==t.length)continue;const a=await this.createFromAsset(t[0]);if(null==a)continue;const s=await this.createInstancedMesh(t,a),r=new re;r.add(s),r.userData.src=t[0],a instanceof re&&(r.collisionShapes=a.collisionShapes),r.collisionShapes.forEach((t=>{t instanceof e&&t.mesh instanceof d&&(t.mesh=t.mesh.geometry)})),r.castShadow=!1,r.receiveShadow=!1,this.scene.add(r)}for(const e of n.values()){if(0==e.length)continue;const t=e[0].object,s=await this.createFromShape(t),n=se(s,(e=>!ie(e)&&null!=e.geometry)),o=n.material.clone();null!=e[0].color&&null!=o.color&&(o.color=new r(16777215));const l=n.geometry,c=new a.InstancedMesh(l,o,e.length);for(let t=0;t<e.length;t++){const r=e[t],o=(new a.Matrix4).compose((new A).fromArray(r.object.position),(new g).setFromEuler((new i).fromArray(r.object.rotation)),(new A).fromArray(r.object.scale)),l=(new h).copy(r.object.parentTransform).multiply(o);c.setMatrixAt(t,l),null!=r.color&&c.setColorAt(t,r.color),c.castShadow=s.castShadow??!0,c.receiveShadow=n.receiveShadow??!0;const d=new re;d.add(c),d.userData.src=e[0],s instanceof oe&&(d.collisionShapes=[s.collisionShape]),d.castShadow=!1,d.receiveShadow=!1,this.scene.add(d)}}await Promise.all(t.map((e=>this.materialize(e)))),await this.initActorsPostInit()}async createInstancedMesh(e,t){const s=se(t,(e=>!ie(e)&&null!=e.geometry)),r=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(t,Te(e[0].materialAssignments,r.materialAssignments)),s.updateMatrix();const n=s.geometry.clone(),o=new a.InstancedMesh(n,s.material,e.length);for(let t=0;t<e.length;t++){const r=(new a.Matrix4).compose((new A).fromArray(e[t].position),(new g).setFromEuler((new i).fromArray(e[t].rotation)),(new A).fromArray(e[t].scale)),n=(new h).copy(e[t].parentTransform).multiply(r).multiply(s.matrixWorld);o.setMatrixAt(t,n)}return o.castShadow=e[0].castShadow??r.castShadow??!0,o.receiveShadow=e[0].receiveShadow??r.receiveShadow??!0,s.material instanceof c&&o.castShadow&&o.receiveShadow&&(o.material.side=a.FrontSide),o}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)}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 ae(this.scene,(t=>t.userData.src?.assetId==e),(e=>null!=e.userData.src))}applyMaterials(e,t){return null==t?Promise.resolve([]):Promise.all(t.filter((e=>"null"!==e.materialId)).map((t=>this.applyMaterial(e,t))))}async applyMaterial(e,t){await applyMaterial(e,t,(e=>{const t=this.assets.get(e);if(null!=t)try{return materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders)}catch(e){console.error("Failed to apply material",e)}}),this._originalMaterials)}unapplyMaterials(e){e.traverse((async e=>{if(e instanceof d)if(e.material instanceof Array)for(let t=0;t<e.material.length;t++)e.material[t]=this._originalMaterials.get(e.id+"#"+t)??e.material[t];else e.material=this._originalMaterials.get(e.id)??e.material}))}updateActors(e){console.log("update actors"),this.actorTypes=e;const t=new Set(Object.values(R));ae(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 Ie.entries())t.userData.customShaderName&&Ie.delete(e);this.landscapeManagers.forEach((t=>t.updateShaders(e))),ae(this.scene,(e=>!0)).forEach((e=>{e.traverse((async e=>{if(e instanceof d)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++){const a=e.material[t].userData?.customShaderName;if(null!=a){const a=this.assets.get(e.material[t].userData.assetId);this.refreshMaterial(e,e.material[t],a,t)}}else{const t=e.material.userData?.customShaderName;if(null!=t){const t=this.assets.get(e.material.userData.assetId);this.refreshMaterial(e,e.material,t)}}}))}))}async update(e){if("sky"===e.type&&null!=this.sky&&null!=this.sky.parent)return void this.updateSky(e);if("world_env"===e.type&&null!=this.worldEnvObj)return void this.updateWorldEnv(e);const t=this.sceneObjectMap.get(e.id);if(t){let s=!1;if(t.traverseAncestors((e=>{"_hology_transform_group"===e.name&&(s=!0)})),!s){const a=this.findParent(e);null!=a&&a.uuid!=t.uuid?a.attach(t):console.error("Parent is wrong")}if("prefab"!==e.type&&"group"!==e.type){this.unapplyMaterials(t);this.inEditor&&e.hidden&&!1?t.traverse((e=>{e instanceof d&&(e.material.wireframe=!0)})):t.traverse((e=>{e instanceof d&&(e.material.wireframe=!1)}))}if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);Te(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 r(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"directional"===e.light.type?this.applyDirectionalLight(e.light.directional):"ambient"===e.light.type&&this.applyDirectionalAmbientLight(t,e.light.ambient);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 o?"density":"linear")!==e.fog.type;this.scene.fog=_e(e.fog),t&&(a=this.scene).traverse((e=>{if(e instanceof d){const t=e.material;t instanceof V&&(a.fog instanceof n?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof o&&(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.editorActorParamSnapshot.get(e.id);null!=t&&t===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 oe&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&Pe(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)){console.log("materialize actor and init");const a=await this.materialize(e,t);return Oe(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:te(t,(t=>t.children?.some((t=>t.id===e.id))),(()=>!0))))[0];return null==t?this.scene:null!=t?ae(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 r(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse((e=>{e instanceof d&&e.geometry&&(t=e)})),t}applyVertexMaterials(e,t){if(null==e.vertexMaterials||0===e.vertexMaterials.length)return;let a=1;for(const t of e.vertexMaterials)a=Math.max(t.w.length,a);const s=K(e.vertexMaterials,(e=>e.m));t.traverse((e=>{if(e instanceof d){if(null==e.geometry)return;if(We(ue(e,0,!1)),a>0){We(ue(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=ue(s,0,!0);We(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=ue(s,4,!0);We(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){let r;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=_e(e.fog),this.fixFogColor(),r=new l;break;case"sky":this.sky=Se(),this.updateSky(e),r=this.sky;break;case"world_env":this.updateWorldEnv(e),r=new l,this.worldEnvObj=r;break;case"actor":r=await this.createFromActor(e);break;case"group":r=new l;break;case"prefab":r=await this.createFromPrefabAsset(e);break;case"vfx":r=await this.createFromVfx(e);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,this.inEditor,this.inEditor){let e=null;r instanceof oe&&(e=function(e){if(e instanceof ne)return new d(new s(...e.offset.toArray()),Fe);return null}(r.collisionShape)),null!=e&&(e.layers.disable(0),e.layers.enable(18),e.scale.multiplyScalar(1.1),r.add(e))}return this.objectMap.set(r.uuid,e),this.sceneObjectMap.set(e.id,r),e.physics?.type!==U.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==U.dynamic||ke(r),this.renderingView.renderer.shadowMap.needsUpdate=!0,r}}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 s=e.worldEnv.environment;null!=s&&null!=s.textureId?this.assetManagerService.getTexture(this.assets.get(s.textureId)).then((e=>{null==this.pmremGenerator&&(this.pmremGenerator=new a.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=s.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=Ae);const t=await this.assetsService.getAsset(e.sky.materialId),s=await materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);s.side=a.BackSide,(s instanceof u||s instanceof a.MeshBasicMaterial||s instanceof a.ShaderMaterial)&&(s.fog=!1),null!=this.sky?this.sky.material=s:console.warn("No sky has been created")}async createComponent(e,t,a,s){const r=new je[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){const t=this.actorTypes.find((t=>t.name===e.actor?.type))?.type??R[e.actor?.type];if(null==t)return null;this.inEditor&&this.editorActorParamSnapshot.set(e.id,JSON.stringify(e.actor));const a=await this.actorProvider.create(t,(new A).fromArray(e.position),(new i).fromArray(e.rotation),!0);return this.materializedActors.set(e.id,a),a?.object}async createFromVfx(e){const t=await this.assetsService.getAsset(e.assetId);null==t&&console.error("Could not find asset",e);const a=await this.actorProvider.create(B,(new A).fromArray(e.position),(new i).fromArray(e.rotation),!1);return await a.fromAsset(t),a.play(),this.materializedActors.set(e.id,a),a?.object}cleanup(){this.materializedActors.clear()}async createFromShape(e){const t=this.inEditor&&e.hidden;let a;if("landscape"==e.shape)a=this.createLandscape(e),a.traverse((e=>{e instanceof d&&this._originalMaterials.set(e.id,e.material)}));else{let s=new u({name:"Default",color:new r("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});const i=await this.createMeshByShape(e.shape,s,e.shapeParams);i.castShadow=e.castShadow??!0,i.receiveShadow=e.castShadow??!1,e.collisionDetection||(i.collisionShape=null),i.physics=e.physics,a=i,this._originalMaterials.set(a.id,i.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 l;const a=ce(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new le(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 he(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((()=>de(r)),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&we.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);return this.geometryCache.has(r)||this.geometryCache.set(r,ge[e].geometry(s)),this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,ge[e].collision(s)),new oe(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});Te(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,Pe(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 d&&"computeBoundsTree"in e.geometry&&null==e.geometry.boundsTree&&e.geometry.computeBoundsTree()})),a}async createFromPrefabAsset(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}`);const a=new l;return t.prefab.objects.filter((e=>"global_fog"!==e.type&&"world_env"!==e.type)).forEach((e=>this.materialize(e,a,!0))),a}async createParticleSystem(e){const t=await this.assetsService.getAsset(e.assetId),s=new f;return await M.fromJSONAsync(t.particleSystem,a).then((e=>{const t=new x(s,a);e.addRenderer(t),this.renderingView.onLoop((t=>e.update()))})),s}async createLight(e){if("point"===e.light.type){const t=new y(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 w(.3,10,10),a=new u({color:new r(16771709)}),s=new d(e,a);t.add(s)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional),new l):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient),new l):void 0}applyDirectionalAmbientLight(e,t){const a=this.scene.children.find((e=>e.name===ve));null!=a?(a.intensity=t.intensity,a.color.set(t.color),a.groundColor.set(t.color)):console.warn("Couldn't find ambient light")}applyDirectionalLight(e){for(const t of this.renderingView.csm.lights)t.intensity=e.intensity,t.color.set(e.color),t.castShadow=e.castShadow;this.renderingView.csm.lightDirection.fromArray(e.direction).normalize()}dispose(){this.updateSubscription.unsubscribe(),this.createAssetSubscription.unsubscribe(),this.materializedActors.forEach((e=>e.disposed.next(!0)))}}function Pe(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse((e=>{e.castShadow=t,e.receiveShadow=a}))}const Ie=new Map,Ee=new Map,Ve=new m({color:16711935}),De=new Map;export async function materialFromAsset(e,t,a,s,r,i=!0){const n=JSON.stringify(e.material);return i&&Ie.has(n)?Ie.get(n):i&&Ee.has(n)?await Ee.get(n):Ee.set(n,_materialFromAsset(n,e,t,a,s,r,i)).get(n)}export async function _materialFromAsset(e,t,s,i,n,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 r(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 i.getAsset(e);null!=a&&(c.map=await n.getTexture(a))}let d;switch(t.material.type){case"phong":d=new p({...c,...h});break;case"water":d=fe(c,s);break;case"grassFoliage":d=me({color:c.color,map:c.map},s);break;case"grass":d=pe({...c,colorTwo:new r(t.material.params.colorTwo),colorThree:new r(t.material.params.colorThree)},s);break;case"standard":case"unlit":case"lambert":case"shader":case"landscape":case"landscape-composite":case"decal-unlit":case"decal-standard":const e={standard:X,lambert:J,unlit:Y,landscape:q,"landscape-composite":H,"decal-unlit":Me,"decal-standard":xe}[t.material.type]??o.find((e=>e.name==t.material.shader))?.type;if(e){try{let a=new e;const r=await Ne(t.material?.shaderParams??{},e,i,n,null,s,o);Object.assign(a,r),d=a.build()}catch(e){console.log("Shader runtime error: "+e),De.has(t.material.shader)||De.set(t.material.shader,Ve.clone()),d=De.get(t.material.shader)}d.userData.customShaderName=t.material.shader}else console.warn("Missing shader implementation with name "+t.material.shader),d=Ve;break;default:throw new Error("Unsupported material type"+t.material.type)}return s?.csm.setupMaterial(d),null!=s&&Ie.set(e,d),d.side=t.material.side??d.side??a.FrontSide,d.transparent=(t.material.transparent??c.transparent??!1)||d.transparent,d.alphaTest=t.material.alphaTest??d.alphaTest??0,t.material.bloom&&(d.userData.hasBloom=!0),d.userData.assetId=t.id,Ee.delete(e),d}async function Ne(e,t,a,s,r,i,n,o){const l={};for(const[t,c]of Object.entries(e)){const e=await Ce(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 Ce(s,null,null,null);null!=e&&(t[a]=e)}return t}async function Ce(e,t,a,s,n,o,l,c=e.value,h=e.type){if(null==e||null==c||""===c)return null;switch(h){case ye.Array:if(Array.isArray(c)&&"element"in e)return await Promise.all(c.map((r=>Ce(e,t,a,s,n,o,l,r,e.element))));break;case ye.Number:case ye.FloatNode:let h="string"==typeof c?parseFloat(c):c;return e.type===ye.FloatNode?I(h):h;case ye.Texture:return await a.getTexture(await t.getAsset(c));case ye.Sampler2DNode:return k(await a.getTexture(await t.getAsset(c)));case ye.Boolean:return c;case ye.BooleanNode:return j(c);case ye.Vector2:case ye.Vec2Node:if("object"==typeof c){const t=c instanceof Array?(new S).fromArray(c):new S(c.x,c.y);return e.type===ye.Vec2Node?_(t):t}return null;case ye.Vector3:case ye.Vec3Node:if("object"==typeof c){const t=c instanceof Array?(new A).fromArray(c):new A(c.x,c.y,c.z);return e.type===ye.Vec3Node?O(t):t}return null;case ye.Color:case ye.RgbNode:const d=new r(c);return e.type===ye.RgbNode?D(d):d;case ye.String:return c;case ye.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 ye.Euler:const p=c;return(new i).fromArray(p);case ye.Object3D:return(await a.getMesh(await t.getAsset(c))).scene;case ye.Material:return await materialFromAsset(await t.getAsset(c),n,t,a,o);case ye.AudioBuffer:return await a.getAudio(await t.getAsset(c));case ye.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 W(l,u);console.error("Using a non-vfx asset for visual effect parameter");break;case ye.Curve:return be.decode(c)}return null}function ke(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 _e(e){return"linear"===e.type?new n(new r(e.color),e.near??100,e.far??1e3):"density"===e.type?new o(e.color,e.density):void console.warn("Invalid fog type",e)}const Fe=new u({color:4229780});async function Oe(e,t,s,r){null==r&&(r=(new h).identity()),await t(e,s,r);const n=r.clone().multiply(function(e,t){if(null==e.position||null==e.rotation||null==e.scale)return t.identity();return t.compose((new A).fromArray(e.position),(new g).setFromEuler((new i).fromArray(e.rotation)),(new A).fromArray(e.scale))}(e,new a.Matrix4));return Promise.all((e.children??[]).map((a=>Oe(a,t,e,n))))}export function toSerializedParamType(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?ye.Number:t instanceof E||"function"==typeof e.prototype.isFloat?ye.FloatNode:t instanceof v||e===v||e.isTexture?ye.Texture:t instanceof L||e===C?ye.Sampler2DNode:t instanceof Boolean||e===Boolean?ye.Boolean:t instanceof P?ye.BooleanNode:t instanceof r||e==r?ye.Color:t instanceof N||"function"==typeof e.prototype.isRgb?ye.RgbNode:t instanceof S||e==S?ye.Vector2:t instanceof F||"function"==typeof e.prototype.isVec2?ye.Vec2Node:t instanceof A||e==A?ye.Vector3:t instanceof T||"function"==typeof e.prototype.isVec3?ye.Vec3Node:t instanceof String||e===String?ye.String:t instanceof $||e==$||e.prototype instanceof $||e.prototype==$?ye.BaseActor:t instanceof i||e==i?ye.Euler:t instanceof f||e==f?ye.Object3D:t instanceof c||e==c?ye.Material:t instanceof AudioBuffer||e==AudioBuffer?ye.AudioBuffer:t instanceof W||e==W?ye.VisualEffect:t instanceof be||e==be?ye.Curve: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?ye.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=Z(e);if(0===s.length)return{};let r;null!=a?G(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 A:return t instanceof A?t.toArray():void a();case b:return t instanceof b?t.toArray():void a();case r:return t instanceof r?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new r(t).getHexString():void a();case String:return t;case i:return t instanceof i?t.toArray():void a()}}function Te(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=>ze(e.materialId))),(t??[]).filter((e=>ze(e.materialId))),(e=>e.color+e.name))}function ze(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[ye.RgbNode,"#000000"],[ye.Color,"#000000"],[ye.Vector4,[0,0,0,0]],[ye.Vec4Node,[0,0,0,0]],[ye.Vector3,[0,0,0]],[ye.Vec3Node,[0,0,0]],[ye.Vector2,[0,0]],[ye.Vec2Node,[0,0]],[ye.Euler,[0,0,0,"XYZ"]],[ye.Array,[]]]);export function applyMaterial(e,t,s,i){const n=[];return e.traverse((async e=>{if(e instanceof d||e.isMesh||e instanceof a.SkinnedMesh||e.isSkinnedMesh)for(const t of ee(e.material))t.hasOwnProperty("color")&&n.push(e)})),Promise.all(n.map((async e=>{if(e.material instanceof Array)for(let a=0;a<e.material.length;a++){const n=e.material[a];if(null==n.color||!(n.color instanceof r))continue;const o="#"+n.color.getHexString(),l=n.name;if(o===t.color&&(n.name===t.name||null==t.name)||e.userData["originalColor_"+a]===t.color&&e.userData["originalMaterialName_"+a]===t.name){const r=await s(t.materialId),n=e.material[a];null!=r&&n.id!=r.id&&(e.material[a]=r,e.userData["originalColor_"+a]=e.userData["originalColor_"+a]??o,e.userData["originalMaterialName_"+a]=e.userData["originalMaterialName_"+a]??l,null!=i&&i.set(e.id+"#"+a,n))}}else if("color"in e.material){const a="#"+e.material.color.getHexString(),r=e.material.name;if(a===t.color&&(e.material.name===t.name||null==t.name)||e.userData.originalColor===t.color&&e.userData.originalName===t.name){const n=await s(t.materialId),o=e.material;null!=n&&(e.material=n,e.userData.originalColor=e.userData.originalColor??a,e.userData.originalMaterialName=e.userData.originalMaterialName??r,null!=i&&(i.has(e.id)||i.set(e.id,o)))}}})))}function Be(e,t){if(e instanceof a.ShaderMaterial&&t instanceof a.ShaderMaterial){return e.fragmentShader+e.vertexShader==t.fragmentShader+t.vertexShader&&function(e,t){if(e instanceof a.ShaderMaterial&&t instanceof a.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 We(e){if(null!=e){for(let t=0;t<e.array.length;t++)e.setX(t,0);e.needsUpdate=!0}}/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
package/dist/scene/model.d.ts
CHANGED
@@ -47,7 +47,7 @@ export type TextureSettings = {
|
|
47
47
|
wrapS?: WrapMode;
|
48
48
|
wrapT?: WrapMode;
|
49
49
|
};
|
50
|
-
export
|
50
|
+
export type Asset = {
|
51
51
|
id: string;
|
52
52
|
name: string;
|
53
53
|
filename?: string;
|
@@ -88,11 +88,11 @@ export interface Asset {
|
|
88
88
|
receiveShadow?: boolean;
|
89
89
|
castShadow?: boolean;
|
90
90
|
vfx?: VfxAssetData;
|
91
|
-
}
|
91
|
+
};
|
92
92
|
export type VfxAsset = Asset & {
|
93
93
|
vfx: VfxAssetData;
|
94
94
|
};
|
95
|
-
export type MaterialType = 'standard' | 'phong' | 'lambert' | 'shader' | 'water' | 'grass' | 'grassFoliage' | 'unlit' | 'landscape' | 'landscape-composite';
|
95
|
+
export type MaterialType = 'standard' | 'phong' | 'lambert' | 'shader' | 'water' | 'grass' | 'grassFoliage' | 'unlit' | 'landscape' | 'landscape-composite' | 'decal-unlit' | 'decal-standard';
|
96
96
|
export type MaterialParameters = {
|
97
97
|
opacity: number;
|
98
98
|
transparent: boolean;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../src/scene/model.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAClF,OAAO,EAAE,oBAAoB,EAAE,MAAM,gDAAgD,CAAC;AACtF,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAE3D,MAAM,MAAM,SAAS,GAAG,MAAM,GAAC,UAAU,GAAC,OAAO,GAAC,WAAW,GAAC,OAAO,GAAC,SAAS,GAAC,OAAO,GAAC,OAAO,GAAC,QAAQ,GAAC,KAAK,CAAA;AAC9G,MAAM,MAAM,SAAS,GAAG,gBAAgB,GAAC,WAAW,CAAA;AACpD,MAAM,MAAM,SAAS,GAAG,OAAO,GAAC,aAAa,GAAC,SAAS,CAAA;AAKvD,oBAAY,mBAAmB;IAC7B,SAAS,IAAI;IACb,MAAM,IAAI;IACV,OAAO,IAAI;IACX,aAAa,IAAI;IACjB,OAAO,IAAI;IACX,WAAW,IAAI;IACf,OAAO,IAAI;IACX,QAAQ,IAAI;IACZ,OAAO,IAAI;IACX,QAAQ,IAAI;IACZ,KAAK,KAAK;IACV,OAAO,KAAK;IACZ,MAAM,KAAK;IACX,SAAS,KAAK;IACd,KAAK,KAAK;IACV,QAAQ,KAAK;IACb,QAAQ,KAAK;IACb,WAAW,KAAK;IAChB,OAAO,KAAK;IACZ,QAAQ,KAAK;IACb,YAAY,KAAK;IACjB,KAAK,KAAK;IACV,KAAK,KAAK;CACX;AACD,MAAM,MAAM,gBAAgB,GAAG;IAC7B,IAAI,EAAE,mBAAmB,CAAA;IACzB,KAAK,EAAE,OAAO,CAAA;CACf,GAAG;IACF,IAAI,EAAE,mBAAmB,CAAC,KAAK,CAAC;IAChC,OAAO,EAAE,mBAAmB,CAAA;IAC5B,KAAK,EAAE,OAAO,EAAE,CAAA;CACjB,CAAA;AAED,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,QAAQ,GAAG,QAAQ,CAAA;AAEpD,MAAM,MAAM,kBAAkB,GAAG,QAAQ,GAAG,MAAM,GAAG,UAAU,CAAA;AAE/D,MAAM,MAAM,eAAe,GAAG;IAC5B,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,KAAK,CAAC,EAAE,QAAQ,CAAA;IAChB,KAAK,CAAC,EAAE,QAAQ,CAAA;CACjB,CAAA;AAED,MAAM,
|
1
|
+
{"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../src/scene/model.ts"],"names":[],"mappings":"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"}
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"prefab.d.ts","sourceRoot":"","sources":["../../../src/scene/objects/prefab.ts"],"names":[],"mappings":"AAAA,OAAO,EAAS,QAAQ,EAAE,MAAM,OAAO,CAAA;AAMvC,qBAAa,MAAM;IACjB,OAAO,EAAE,MAAM,CAAA;IAQf,MAAM,IAAI;QAAC,MAAM,EAAE,QAAQ,CAAA;KAA0B;CActD"}
|
@@ -1,21 +1,30 @@
|
|
1
|
-
import { SceneDataProvider, SceneObject } from '../scene/materializer.js';
|
1
|
+
import { SceneDataProvider, SceneObject, ChangeCallback } from '../scene/materializer.js';
|
2
2
|
import { BehaviorSubject } from 'rxjs';
|
3
3
|
import { Matrix4 } from 'three';
|
4
4
|
export declare class SceneDataService implements SceneDataProvider {
|
5
5
|
private objects;
|
6
6
|
private callbacks;
|
7
|
+
private createCallbacks;
|
7
8
|
private removeCallbacks;
|
8
9
|
objectChange: BehaviorSubject<SceneObject[]>;
|
9
10
|
constructor();
|
10
11
|
initiate(data: SceneObject[]): void;
|
11
12
|
private createDefaultObjects;
|
12
|
-
removeOnUpdateCallback(callback:
|
13
|
-
|
14
|
-
|
13
|
+
removeOnUpdateCallback(callback: ChangeCallback): void;
|
14
|
+
onCreate(callback: ChangeCallback): void;
|
15
|
+
onUpdate(callback: ChangeCallback): void;
|
16
|
+
onRemove(callback: ChangeCallback): void;
|
15
17
|
getObjects(): SceneObject[];
|
16
18
|
getObjectsRecursive(): SceneObject[];
|
17
|
-
addObject(object: SceneObject): void;
|
18
|
-
|
19
|
+
addObject(object: SceneObject, remote?: boolean): void;
|
20
|
+
/**
|
21
|
+
* Replaces the object with its new state.
|
22
|
+
* @param object
|
23
|
+
* @param remote Whether the update is made by a synchronization service. This
|
24
|
+
* is forwarded in onUpdate callbacks so they can decide if they should ignore the events
|
25
|
+
* to avoid infite loops by differentiating between updates made locally and remotely.
|
26
|
+
*/
|
27
|
+
updateObject(object: SceneObject, remote?: boolean): void;
|
19
28
|
findObjectById(id: string): SceneObject;
|
20
29
|
findAncestorsById(id: string): SceneObject[];
|
21
30
|
/**
|
@@ -28,7 +37,8 @@ export declare class SceneDataService implements SceneDataProvider {
|
|
28
37
|
updateParent(object: SceneObject, newParent: SceneObject): void;
|
29
38
|
getMatrixWorld(object: SceneObject): Matrix4;
|
30
39
|
getLocalMatrix(object: SceneObject): Matrix4;
|
31
|
-
|
40
|
+
removeObjectById(objectId: string, remote?: boolean): void;
|
41
|
+
removeObject(object: SceneObject, remote?: boolean): void;
|
32
42
|
private removeRecursive;
|
33
43
|
save(): void;
|
34
44
|
serialize(): string;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"scene-data-service.d.ts","sourceRoot":"","sources":["../../src/scene/scene-data-service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;
|
1
|
+
{"version":3,"file":"scene-data-service.d.ts","sourceRoot":"","sources":["../../src/scene/scene-data-service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1F,OAAO,EAAE,eAAe,EAAE,MAAM,MAAM,CAAC;AACvC,OAAO,EAAE,OAAO,EAA6C,MAAM,OAAO,CAAC;AAI3E,qBAAa,gBAAiB,YAAW,iBAAiB;IACxD,OAAO,CAAC,OAAO,CAAoB;IACnC,OAAO,CAAC,SAAS,CAAuB;IACxC,OAAO,CAAC,eAAe,CAAuB;IAC9C,OAAO,CAAC,eAAe,CAAuB;IACvC,YAAY,iCAAyC;;IAW5D,QAAQ,CAAC,IAAI,EAAE,WAAW,EAAE;IAK5B,OAAO,CAAC,oBAAoB;IAY5B,sBAAsB,CAAC,QAAQ,EAAE,cAAc;IAI/C,QAAQ,CAAC,QAAQ,EAAE,cAAc;IAIjC,QAAQ,CAAC,QAAQ,EAAE,cAAc;IAIjC,QAAQ,CAAC,QAAQ,EAAE,cAAc;IAIjC,UAAU,IAAI,WAAW,EAAE;IAI3B,mBAAmB,IAAI,WAAW,EAAE;IAapC,SAAS,CAAC,MAAM,EAAE,WAAW,EAAE,MAAM,UAAQ;IAM7C;;;;;;OAMG;IACH,YAAY,CAAC,MAAM,EAAE,WAAW,EAAE,MAAM,UAAQ;IAWhD,cAAc,CAAC,EAAE,EAAE,MAAM;IAazB,iBAAiB,CAAC,EAAE,EAAE,MAAM,GAAG,WAAW,EAAE;IAQ5C;;;;OAIG;IACH,cAAc,CAAC,EAAE,EAAE,MAAM,GAAG,WAAW;IAGvC,OAAO,CAAC,eAAe;IAOvB,YAAY,CAAC,MAAM,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW;IA8CxD,cAAc,CAAC,MAAM,EAAE,WAAW;IAWlC,cAAc,CAAC,MAAM,EAAE,WAAW;IASlC,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,UAAQ;IAKjD,YAAY,CAAC,MAAM,EAAE,WAAW,EAAE,MAAM,UAAQ;IAMhD,OAAO,CAAC,eAAe;IAavB,IAAI;IAKJ,SAAS,IAAI,MAAM;CAIpB;AAGD,wBAAgB,gBAAgB,IAAI,WAAW,CAa9C;AAED,wBAAgB,gBAAgB,IAAI,WAAW,CAS9C;AAED,wBAAgB,sBAAsB,IAAI,WAAW,CA2BpD"}
|
@@ -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.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)}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){this.objects.push(e),this.
|
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}}}}/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1,5 +1,5 @@
|
|
1
1
|
import { Observable } from 'rxjs';
|
2
|
-
interface
|
2
|
+
export interface StorageEntity {
|
3
3
|
id: string;
|
4
4
|
name: string;
|
5
5
|
fileKey?: string;
|
@@ -10,7 +10,7 @@ type ObjectIndexEntry = {
|
|
10
10
|
name: string;
|
11
11
|
path?: string;
|
12
12
|
};
|
13
|
-
export declare class ObjectStorage<T extends
|
13
|
+
export declare class ObjectStorage<T extends StorageEntity> {
|
14
14
|
private name;
|
15
15
|
private filePathFn?;
|
16
16
|
private path;
|
@@ -45,12 +45,7 @@ export declare class ObjectStorage<T extends Entity> {
|
|
45
45
|
* @returns An array of folders
|
46
46
|
*/
|
47
47
|
watchFolders(): Observable<string[]>;
|
48
|
-
watch(): Observable<
|
49
|
-
event: "add" | "addDir" | "change" | "unlink" | "unlinkDir";
|
50
|
-
object: T;
|
51
|
-
path: string;
|
52
|
-
filename: string;
|
53
|
-
}>;
|
48
|
+
watch(): Observable<StorageWatchEvent<T>>;
|
54
49
|
private reloadSubdirectory;
|
55
50
|
private readFileIfExists;
|
56
51
|
getAll(relativePath?: string): Promise<T[]>;
|
@@ -75,5 +70,11 @@ export declare class ObjectStorage<T extends Entity> {
|
|
75
70
|
private watchDir;
|
76
71
|
}
|
77
72
|
export declare function tokenizeName(name: string): string;
|
73
|
+
export type StorageWatchEvent<T> = {
|
74
|
+
event: "add" | "addDir" | "change" | "unlink" | "unlinkDir";
|
75
|
+
object: T | null;
|
76
|
+
path: string;
|
77
|
+
filename: string;
|
78
|
+
};
|
78
79
|
export {};
|
79
80
|
//# sourceMappingURL=storage.d.ts.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../../../src/scene/storage/storage.ts"],"names":[],"mappings":"AAEA,OAAO,EAAsF,UAAU,EAA0C,MAAM,MAAM,CAAC;
|
1
|
+
{"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../../../src/scene/storage/storage.ts"],"names":[],"mappings":"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"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{randomUUID as e}from"../../utils/uuid.js";import{pathJoin as t}from"../../utils/files.js";import{combineLatest as a,EMPTY as i,filter as r,firstValueFrom as
|
1
|
+
import{randomUUID as e}from"../../utils/uuid.js";import{pathJoin as t}from"../../utils/files.js";import{combineLatest as a,EMPTY as i,filter as r,firstValueFrom as n,from as s,map as h,mergeAll as o,mergeMap as l,Observable as c,of as d,startWith as u,Subject as p,switchMap as w,tap as f}from"rxjs";import{sleepDelay as m}from"../../utils/async.js";const y={},v={},j={},F={};null==y.read&&window.require&&(Object.assign(y,window.require("fs")),Object.assign(v,y.promises),Object.assign(j,window.require("path")),Object.assign(F,window.require("chokidar")));const b=null!=y.existsSync;function g(){if(b){const e="--path=",t=window.process.argv.find((t=>t.startsWith(e)));return t?t.substring(e.length):""}return""}const x=/^[A-Z]:/;function P(...e){return 0===e.length?"":x.test(e[0])||b?j.join(...e):t(...e)}export class ObjectStorage{constructor(e,t){this.name=e,this.filePathFn=t,this.basePathUpdates=new p,this.basePath=this.basePathUpdates.pipe(h((e=>P(g(),e))),f((e=>{this.path=P(e,this.name),O(this.path),this.determineIfMetaFileShouldBeCreated()}))),this.loaded=n(this.basePath),this.shouldCreateIndex=!0,this.watchers=[]}setBasePath(e){this.basePathUpdates.next(e)}async determineIfMetaFileShouldBeCreated(){try{(await v.readFile(P(g(),"vite.config.ts"))).toString().includes("hologyBuild")&&(this.shouldCreateIndex=!1)}catch(e){console.warn("Failed to read vite config to determine if meta files should be created")}}async createFolder(e,t=""){S(),await v.mkdir(j.join(this.path,t,e),{recursive:!0})}async deleteFolderForceDangerous(e){await v.rm(j.join(this.path,e),{recursive:!0,force:!0})}async moveFolder(e,t){if(S(),""==e)return void console.warn("Can not move a folder in root");const a=j.resolve(j.join(this.path,t),j.basename(e));if(await async function(e){try{await v.access(e,v.constants.F_OK)}catch(e){return!1}return!0}(a)){if(a!==j.resolve(this.path,e))throw new Error("Can not move to directory as a file already exists with the same name")}else{if(function(e,t){const a=j.resolve(e),i=j.resolve(t),r=j.normalize(a)+j.sep;return(j.normalize(i)+j.sep).startsWith(r)}(j.join(this.path,e),j.join(this.path,t)))throw new Error("Can not move a folder into a folder it contains");await v.rename(j.join(this.path,e),a)}}async renameFolder(e,t){await v.rename(j.join(this.path,e),j.resolve(j.dirname(j.join(this.path,e)),t))}async moveToFolder(e,t){if(S(),e.path===t)return;const a=this.privateObjectPath({...e,path:t});await v.rename(this.privateObjectPath(e),a)}getAbsolutePath(e=""){return j.join(this.path,e)}watchFolders(){const e=v.readdir(this.path,{recursive:!0,withFileTypes:!0});return a([s(e),this.watchDir(this.path).pipe(r((e=>!e.filename.endsWith(".json"))),u(null))]).pipe(w((([e,t])=>null!=t?s(v.readdir(this.path,{recursive:!0,withFileTypes:!0})):d(e))),h((e=>Array.from(new Set(e.filter((e=>e.isDirectory())).map((e=>j.relative(this.path,j.join(e.path,e.name)).replace(/^\.$/,""))).values())))))}watch(){return S(),s(this.loaded).pipe(w((()=>this.watchDir(this.path))),l((e=>{const t={event:e.event,path:j.dirname(e.filename).replace(/^\.$/,""),filename:j.basename(e.filename)};return e.filename.endsWith(".json")?"unlink"!==e.event?s(this.readFileIfExists(e.filename)).pipe(h((e=>({object:e,...t})))):d({object:null,...t}):"change"===e.event?s(this.reloadSubdirectory(e.filename)).pipe(o(),h((e=>({object:e,...t})))):i})))}async reloadSubdirectory(e){return(await this.getAll(e)).filter((t=>t.path.startsWith(e)))}async readFileIfExists(e){const t=P(this.path,e);try{const a=await v.readFile(t);return{...JSON.parse(a.toString()),path:j.dirname(e).replace(/^\.$/,""),filename:j.basename(e)}}catch{return console.error("Could not find file at "+t),null}}async getAll(e){if(b){await this.loaded,await O(this.path);const t=(await v.readdir(j.join(this.path,e??""),{recursive:!0,withFileTypes:!0})).filter((e=>e.isFile()&&e.name.endsWith(".json")&&!/^[\._]/.test(e.name)));return await Promise.all(t.map((e=>v.readFile(P(e.path,e.name)).then((t=>({...JSON.parse(t.toString()),path:j.relative(this.path,e.path).replace(/^\.$/,""),filename:j.basename(e.path)}))))))}const t=await this.loadIndex();return Promise.all(Object.keys(t).map((e=>this.get(e))))}async get(e){const t=await this.loadIndex(),a=t[e]??Object.values(t).find((t=>t.name===e));if(null==a)return;const i=this.privateObjectPath(a);if(!b)return(await fetch(i)).json();return await I(i)?JSON.parse((await v.readFile(i)).toString()):null}async save(e){return S(),await this.loaded,await v.writeFile(this.privateObjectPath(e),this.serialize(e)),await this.updateIndex(),e}async rename(e,t){const a={...e,name:t},i=this.privateObjectPath(e),r=this.privateObjectPath(a);try{await v.rename(i,r)}catch(e){console.error(e),console.warn("Rename failed, retrying",{currentPath:i,newPath:r}),await m(400),await v.rename(i,r)}return await this.save(a),await this.updateIndex(),a}async delete(e){await v.unlink(this.privateObjectPath(e)),this.updateIndex()}async create(t){return S(),await this.loaded,t.id=e(),await v.writeFile(this.privateObjectPath(t),this.serialize(t)),await this.updateIndex(),t}prepareCreate(t){return S(),t.id=e(),t}serialize(e){const t={...e};return delete t.path,delete t.filename,JSON.stringify(t,null,2)}async updateIndex(){S();const e=await this.getAll(),t={};for(const a of e)t[a.id]={id:a.id,name:a.name??a.id,path:a.path};if(this.cachedIndex=t,b){if(!this.shouldCreateIndex)return;await v.writeFile(this.indexFilePath,JSON.stringify(t,null,2))}}get indexFilePath(){return P(this.path,"_meta.json")}async loadIndex(){return null==this.cachedIndex&&(b?await this.updateIndex():this.cachedIndex=await(await fetch(this.indexFilePath)).json()),this.cachedIndex}async ensureResourceDir(){await O(P(this.path+"-resources"))}async saveFile(e,t){return S(),await O(P(this.path+"-resources")),v.copyFile(t.path,P(this.path+"-resources",e.fileKey))}async saveExtraFile(e,t){return S(),await O(P(this.path+"-resources")),v.copyFile(e,P(this.path+"-resources",t))}getAssetPath(e){return window&&"function"==typeof window.require?window.require("path").join(this.path+"-resources",e.fileKey):P(this.path+"-resources",e.fileKey)}async replaceFile(e,t){if(await I(t))return v.copyFile(t,P(this.path+"-resources",e.fileKey));console.error("Failed to replace file using path "+t)}async deleteFile(e){if(null==e)return;S();const t=P(this.path+"-resources",e);return await I(t)?v.unlink(t):void 0}privateObjectPath(e){return this.filePathFn?P(this.path,e.path??"",this.filePathFn(e)):P(this.path,e.path??"",tokenizeName(e.name??e.id)+".json")}watchDir(e){return new c((t=>{const a=F.watch(e,{cwd:e});return a.on("all",((e,a,i)=>{t.next({event:e,filename:a})})),a.on("unlinkDir",(e=>{})),a.on("error",(()=>{})),this.watchers.push(a),()=>{a.close()}}))}}export function tokenizeName(e){return e.trim().replace(/\s/g,"_").replace(/[^a-z0-9_\-\.]/gi,"")}async function O(e){b&&(await I(e)||await v.mkdir(e,{recursive:!0}))}function I(e){return!!b&&new Promise((function(t,a){y.exists(e,(function(e){t(e)}))}))}function S(){if(!b)throw new Error("Must have direct access to filesystem")}/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -0,0 +1,24 @@
|
|
1
|
+
import { Color, Texture, Vector2 } from 'three';
|
2
|
+
import { DecalNodeShader } from '../decal-shader.js';
|
3
|
+
export declare class DecalStandardShader extends DecalNodeShader {
|
4
|
+
color: Color;
|
5
|
+
opacity: number;
|
6
|
+
colorMap?: Texture;
|
7
|
+
alphaMap?: Texture;
|
8
|
+
roughness?: number;
|
9
|
+
roughnessMap?: Texture;
|
10
|
+
metalness?: number;
|
11
|
+
metalnessMap?: Texture;
|
12
|
+
aoMap?: Texture;
|
13
|
+
aoMapIntensity?: number;
|
14
|
+
emissive?: Color;
|
15
|
+
emissiveIntensity?: number;
|
16
|
+
emissiveMap?: Texture;
|
17
|
+
normalMap?: Texture;
|
18
|
+
normalScale?: Vector2;
|
19
|
+
output(): {
|
20
|
+
color: import("three-shader-graph").RgbaNode;
|
21
|
+
};
|
22
|
+
build(): import("three").Material;
|
23
|
+
}
|
24
|
+
//# sourceMappingURL=decal-standard-shader.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"decal-standard-shader.d.ts","sourceRoot":"","sources":["../../../src/shader/builtin/decal-standard-shader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAIhD,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAGrD,qBAAa,mBAAoB,SAAQ,eAAe;IACzC,KAAK,EAAE,KAAK,CAAwB;IACtB,OAAO,EAAE,MAAM,CAAI;IACjC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEL,SAAS,CAAC,EAAE,MAAM,CAAK;IACrC,YAAY,CAAC,EAAE,OAAO,CAAC;IAET,SAAS,CAAC,EAAE,MAAM,CAAK;IACrC,YAAY,CAAC,EAAE,OAAO,CAAC;IAEvB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB,QAAQ,CAAC,EAAE,KAAK,CAAC;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IACzC,WAAW,CAAC,EAAE,OAAO,CAAC;IAEtB,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB,WAAW,CAAC,EAAE,OAAO,CAAC;IAInC,MAAM;;;IA4DN,KAAK;CASN"}
|
@@ -0,0 +1,4 @@
|
|
1
|
+
import{__decorate as e,__metadata as t}from"tslib";import{Color as a,Texture as s,Vector2 as r}from"three";import{colorToNormal as o,float as i,rgba as p,standardMaterial as l,textureSampler2d as d,uniforms as n,normalize as h,varying as m}from"three-shader-graph";import{decalAlpha as y,decalNormal as c,decalUV as u}from"../../shader-nodes/decal.js";import{depthWorldPosition as S}from"../../shader-nodes/depth.js";import{DecalNodeShader as g}from"../decal-shader.js";import{Parameter as v}from"../parameter.js";export class DecalStandardShader extends g{constructor(){super(...arguments),this.color=new a("#FFFFFF"),this.opacity=1,this.roughness=1,this.metalness=0}output(){const e=u;let t=i(this.opacity);null!=this.alphaMap&&(t=t.multiply(d(this.alphaMap).sample(e).r)),t=t.multiply(y);let a=p(this.color,t);null!=this.colorMap&&(a=a.multiply(d(this.colorMap).sample(e)));let s=p(this.emissive,t);null!=this.emissiveMap&&(s=s.multiply(d(this.emissiveMap).sample(e)));let r=i(this.roughness);null!=this.roughnessMap&&(r=r.multiply(d(this.roughnessMap).sample(e).g));let g=i(this.metalness);null!=this.metalnessMap&&(g=g.multiply(d(this.metalnessMap).sample(e).b));let v=h(m(n.normalMatrix).multiplyVec(c));null!=this.normalMap&&(v=o(d(this.normalMap).sample(e),this.normalScale?.x??1,v,S,e));let M=null;return null!=this.aoMap&&(M=d(this.aoMap).sample(e).r),{color:l({color:a,emissive:s,emissiveIntensity:i(this.emissiveIntensity??1),roughness:r,metalness:g,normal:v,ambientOcclusion:M,ambientOcclusionIntensity:i(this.aoMapIntensity??1),worldPosition:S})}}build(){const e=super.build();return e.depthTest=!0,e.depthWrite=!1,e.userData.isDecal=!0,e}}e([v(),t("design:type",a)],DecalStandardShader.prototype,"color",void 0),e([v({range:[0,1]}),t("design:type",Number)],DecalStandardShader.prototype,"opacity",void 0),e([v(),t("design:type",s)],DecalStandardShader.prototype,"colorMap",void 0),e([v(),t("design:type",s)],DecalStandardShader.prototype,"alphaMap",void 0),e([v({range:[0,1]}),t("design:type",Number)],DecalStandardShader.prototype,"roughness",void 0),e([v(),t("design:type",s)],DecalStandardShader.prototype,"roughnessMap",void 0),e([v({range:[0,1]}),t("design:type",Number)],DecalStandardShader.prototype,"metalness",void 0),e([v(),t("design:type",s)],DecalStandardShader.prototype,"metalnessMap",void 0),e([v(),t("design:type",s)],DecalStandardShader.prototype,"aoMap",void 0),e([v(),t("design:type",Number)],DecalStandardShader.prototype,"aoMapIntensity",void 0),e([v(),t("design:type",a)],DecalStandardShader.prototype,"emissive",void 0),e([v({range:[0,1]}),t("design:type",Number)],DecalStandardShader.prototype,"emissiveIntensity",void 0),e([v(),t("design:type",s)],DecalStandardShader.prototype,"emissiveMap",void 0),e([v(),t("design:type",s)],DecalStandardShader.prototype,"normalMap",void 0),e([v(),t("design:type",r)],DecalStandardShader.prototype,"normalScale",void 0);/*
|
2
|
+
* Copyright (©) 2023. All rights reserved.
|
3
|
+
* See the LICENSE.md file for details.
|
4
|
+
*/
|
@@ -0,0 +1,12 @@
|
|
1
|
+
import { Color, Texture } from 'three';
|
2
|
+
import { DecalNodeShader } from '../decal-shader.js';
|
3
|
+
export declare class DecalUnlitShader extends DecalNodeShader {
|
4
|
+
color: Color;
|
5
|
+
opacity: number;
|
6
|
+
colorMap?: Texture;
|
7
|
+
alphaMap?: Texture;
|
8
|
+
output(): {
|
9
|
+
color: import("three-shader-graph").RgbaNode;
|
10
|
+
};
|
11
|
+
}
|
12
|
+
//# sourceMappingURL=decal-unlit-shader.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"decal-unlit-shader.d.ts","sourceRoot":"","sources":["../../../src/shader/builtin/decal-unlit-shader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiD,KAAK,EAAqE,OAAO,EAAW,MAAM,OAAO,CAAC;AAIlK,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAIrD,qBAAa,gBAAiB,SAAQ,eAAe;IACtC,KAAK,EAAE,KAAK,CAAwB;IACtB,OAAO,EAAE,MAAM,CAAI;IACjC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEhC,MAAM;;;CAoBP"}
|
@@ -0,0 +1,4 @@
|
|
1
|
+
import{__decorate as t,__metadata as o}from"tslib";import{Color as e,Texture as r}from"three";import{Parameter as p}from"../parameter.js";import{DecalNodeShader as l}from"../decal-shader.js";import{rgba as a,textureSampler2d as i,float as s}from"three-shader-graph";import{decalAlpha as h,decalUV as c}from"../../shader-nodes/decal.js";export class DecalUnlitShader extends l{constructor(){super(...arguments),this.color=new e("#FFFFFF"),this.opacity=1}output(){const t=c;let o=s(this.opacity);null!=this.alphaMap&&(o=o.multiply(i(this.alphaMap).sample(t).r)),o=o.multiply(h);let e=a(this.color,o);return null!=this.colorMap&&(e=e.multiply(i(this.colorMap).sample(t))),{color:e}}}t([p(),o("design:type",e)],DecalUnlitShader.prototype,"color",void 0),t([p({range:[0,1]}),o("design:type",Number)],DecalUnlitShader.prototype,"opacity",void 0),t([p(),o("design:type",r)],DecalUnlitShader.prototype,"colorMap",void 0),t([p(),o("design:type",r)],DecalUnlitShader.prototype,"alphaMap",void 0);/*
|
2
|
+
* Copyright (©) 2023. All rights reserved.
|
3
|
+
* See the LICENSE.md file for details.
|
4
|
+
*/
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"decal-shader.d.ts","sourceRoot":"","sources":["../../src/shader/decal-shader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAGhC,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;AAE9C,8BAAsB,eAAe;IACnC,KAAK,IAAI,QAAQ;IAejB,QAAQ,CAAC,MAAM,IAAI,gBAAgB;CACpC"}
|
@@ -0,0 +1,4 @@
|
|
1
|
+
import{NodeShaderMaterial as r}from"../shader-nodes/index.js";import{decalDiscard as d}from"../shader-nodes/decal.js";export class DecalNodeShader{build(){const e=this.output();let s=d;return null!=e.discard&&(s=s.or(e.discard)),new r({transparent:!1,...e,discard:s})}}/*
|
2
|
+
* Copyright (©) 2023. All rights reserved.
|
3
|
+
* See the LICENSE.md file for details.
|
4
|
+
*/
|
@@ -0,0 +1,8 @@
|
|
1
|
+
export declare const decalNormal: import("three-shader-graph").Vec3Node;
|
2
|
+
export declare const decalDiscard: import("three-shader-graph").BoolOrNode;
|
3
|
+
export declare const decalUV: import("three-shader-graph").Vec2Node;
|
4
|
+
/**
|
5
|
+
* Fade away decal when close to the edges.
|
6
|
+
*/
|
7
|
+
export declare const decalAlpha: import("three-shader-graph").FloatNode;
|
8
|
+
//# sourceMappingURL=decal.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"decal.d.ts","sourceRoot":"","sources":["../../src/shader-nodes/decal.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,WAAW,uCAA2D,CAAA;AAEnF,eAAO,MAAM,YAAY,yCAAwF,CAAA;AACjH,eAAO,MAAM,OAAO,uCAA+B,CAAA;AAInD;;GAEG;AACH,eAAO,MAAM,UAAU,wCAGqC,CAAA"}
|
@@ -0,0 +1,4 @@
|
|
1
|
+
import{abs as t,inverse as r,min as o,smoothstep as e,uniforms as a,varying as c,vec4 as l}from"three-shader-graph";import{depthNormal as p,depthWorldPosition as x}from"./depth";const d=c(r(a.instanceMatrix.multiply(a.modelMatrix))),i=d.multiplyVec(l(x,1)).xyz;export const decalNormal=d.multiplyVec(l(p,0)).xyz;export const decalDiscard=t(i.x).gt(.5).or(t(i.y).gt(.5)).or(t(i.z).gt(.5));export const decalUV=i.xz.addScalar(.5);export const decalAlpha=o(e(.5,.4,t(i.x)),o(e(.5,.4,t(i.y)),e(.5,.4,t(i.z))));/*
|
2
|
+
* Copyright (©) 2023. All rights reserved.
|
3
|
+
* See the LICENSE.md file for details.
|
4
|
+
*/
|
@@ -8,4 +8,12 @@ export declare const farUniformName = "hology_camera_far";
|
|
8
8
|
export declare const depthSampler: import("three-shader-graph").UniformSampler2d;
|
9
9
|
export declare const fragmentLinearEyeDepth: FloatNode;
|
10
10
|
export declare const linearEyeDepth: FloatNode;
|
11
|
+
/**
|
12
|
+
* The position of the fragment closest behind the surface.
|
13
|
+
*/
|
14
|
+
export declare const depthWorldPosition: import("three-shader-graph").Vec3Node;
|
15
|
+
/**
|
16
|
+
* An approximated normal created by taking multiple samples using a depth texture
|
17
|
+
*/
|
18
|
+
export declare const depthNormal: import("three-shader-graph").Vec3Node;
|
11
19
|
//# sourceMappingURL=depth.d.ts.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"depth.d.ts","sourceRoot":"","sources":["../../src/shader-nodes/depth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,aAAa,EAAE,MAAM,OAAO,CAAC;AACzD,OAAO,EAAmC,SAAS,
|
1
|
+
{"version":3,"file":"depth.d.ts","sourceRoot":"","sources":["../../src/shader-nodes/depth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,aAAa,EAAE,MAAM,OAAO,CAAC;AACzD,OAAO,EAAmC,SAAS,EAAuK,MAAM,oBAAoB,CAAC;AAKrP,wBAAgB,6BAA6B,CAAC,QAAQ,EAAE,aAAa,WAEpE;AAID,eAAO,MAAM,gBAAgB,qBAAqB,CAAA;AAClD,eAAO,MAAM,qBAAqB,sBAAsB,CAAA;AACxD,eAAO,MAAM,eAAe,uBAAuB,CAAA;AACnD,eAAO,MAAM,cAAc,sBAAsB,CAAA;AAEjD,eAAO,MAAM,YAAY,+CAAkE,CAAA;AA2G3F,eAAO,MAAM,sBAAsB,WAAkB,CAAA;AAOrD,eAAO,MAAM,cAAc,WAA+B,CAAA;AAgB1D;;GAEG;AACH,eAAO,MAAM,kBAAkB,uCAAkC,CAAA;AASjE;;GAEG;AACH,eAAO,MAAM,WAAW,uCAAyF,CAAA"}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import{Vector2 as
|
1
|
+
import{Vector2 as t}from"three";import{dot as e,float as o,FloatExpressionNode as r,FloatNode as n,texture2d as a,uniformVec2 as c,vec2 as s,Vec2ExpressionNode as i,vec4 as p,Vec4Node as h,uniformSampler2d as l,uniformFloat as d,varying as u,inverse as m,uniforms as x,cross as f,normalize as _}from"three-shader-graph";import*as g from"three";export function supportsDepthTextureExtension(t){return!!t.extensions.get("WEBGL_depth_texture")}export const depthUniformName="hology_depth_map";export const resolutionUniformName="hology_resolution";export const nearUniformName="hology_camera_near";export const farUniformName="hology_camera_far";export const depthSampler=l(depthUniformName,new g.DepthTexture(1,1));const k=d(nearUniformName,.5),y=d(farUniformName,500);class $ extends n{compile(t){const e=t.variable();var o=t.get(k),r=t.get(y);return{chunk:`\n float depth_${e} = 2.0 * ${o} * ${r} / (${r} + ${o} - (2.0 * ${t.get(this.depth)} - 1.0) * (${r} - ${o}));\n `,out:`depth_${e}`}}constructor(t){super(),this.depth=t}}function v(t){return new $(t)}const U=new class extends h{constructor(){super(...arguments),this.k="31u50"}compile(t){return{pars:`\n const float UnpackDownscale_${this.k} = 255. / 256.; // 0..1 -> fraction (excluding 1)\n const vec4 PackFactors_${this.k} = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\n const vec4 UnpackFactors_${this.k} = vec4( UnpackDownscale_${this.k} / PackFactors_${this.k}.rgb, 1.0 / PackFactors_${this.k}.a );\n `,out:`UnpackFactors_${this.k}`}}};function w(t){return o=a(depthSampler,t),e(o,U);var o}const N=new r("gl_FragCoord.z");export const fragmentLinearEyeDepth=v(N);const F=c("hology_resolution",new t(250,1e3)),b=new i("gl_FragCoord.xy").divide(F);export const linearEyeDepth=v(w(b));const D=u(m(x.projectionMatrix)),P=u(m(x.viewMatrix));function S(t=b){const e=w(t).multiply(2).subtract(1),o=t.multiplyScalar(2).subtractScalar(1),r=p(o.x,o.y,e,1),n=D.multiplyVec(r),a=n.xyz.divideScalar(n.w);return P.multiplyVec(p(a,1)).xyz}export const depthWorldPosition=S(b);const E=o(1).divide(F.x),W=o(1).divide(F.y),z=S(b.add(s(E,o(0)))),C=S(b.add(s(o(0),W)));export const depthNormal=_(f(z.subtract(depthWorldPosition),C.subtract(depthWorldPosition)));/*
|
2
2
|
* Copyright (©) 2023. All rights reserved.
|
3
3
|
* See the LICENSE.md file for details.
|
4
4
|
*/
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/shader-nodes/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAA;AAClC,OAAO,EAAE,cAAc,EAAE,sBAAsB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AACjF,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA;AACxC,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAA;AAChD,cAAc,aAAa,CAAA;AAC3B,cAAc,gBAAgB,CAAA;AAC9B,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,cAAc,cAAc,CAAA;AAC5B,cAAc,WAAW,CAAA;AACzB,cAAc,YAAY,CAAA;AAC1B,cAAc,uBAAuB,CAAA"}
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/shader-nodes/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAA;AAClC,OAAO,EAAE,cAAc,EAAE,sBAAsB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AACjF,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA;AACxC,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAA;AAChD,cAAc,aAAa,CAAA;AAC3B,cAAc,gBAAgB,CAAA;AAC9B,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,cAAc,cAAc,CAAA;AAC5B,cAAc,WAAW,CAAA;AACzB,cAAc,YAAY,CAAA;AAC1B,cAAc,uBAAuB,CAAA;AACrC,cAAc,YAAY,CAAA"}
|