@hology/core 0.0.54 → 0.0.56

Sign up to get free protection for your applications and to get access to all the features.
Files changed (55) hide show
  1. package/LICENSE.md +4 -4
  2. package/dist/config/project-config.d.ts +5 -0
  3. package/dist/csm.d.ts +2 -3
  4. package/dist/csm.js +1 -1
  5. package/dist/effects/vfx/behaviours.d.ts +16 -0
  6. package/dist/effects/vfx/behaviours.js +1 -1
  7. package/dist/effects/vfx/index.d.ts +2 -0
  8. package/dist/effects/vfx/index.js +1 -1
  9. package/dist/effects/vfx/initializsers.d.ts +7 -0
  10. package/dist/effects/vfx/initializsers.js +1 -1
  11. package/dist/effects/vfx/rates.d.ts +6 -0
  12. package/dist/effects/vfx/rates.js +1 -1
  13. package/dist/effects/vfx/stretched-sprite.d.ts +4 -0
  14. package/dist/effects/vfx/stretched-sprite.js +5 -0
  15. package/dist/effects/vfx/trail-renderer.d.ts +91 -0
  16. package/dist/effects/vfx/trail-renderer.js +5 -0
  17. package/dist/effects/vfx/vfx-actor.d.ts +15 -2
  18. package/dist/effects/vfx/vfx-actor.js +1 -1
  19. package/dist/effects/vfx/vfx-asset.d.ts +29 -4
  20. package/dist/effects/vfx/vfx-asset.js +1 -1
  21. package/dist/effects/vfx/vfx-defs.d.ts +46 -15
  22. package/dist/effects/vfx/vfx-defs.js +1 -1
  23. package/dist/effects/vfx/vfx-materializer.d.ts +22 -10
  24. package/dist/effects/vfx/vfx-materializer.js +1 -1
  25. package/dist/effects/vfx/vfx-old-materializer.d.ts +11 -0
  26. package/dist/effects/vfx/vfx-old-materializer.js +5 -0
  27. package/dist/effects/vfx/vfx-param.d.ts +2 -3
  28. package/dist/effects/vfx/vfx-param.js +1 -1
  29. package/dist/effects/vfx/vfx-renderers.d.ts +58 -3
  30. package/dist/effects/vfx/vfx-renderers.js +1 -1
  31. package/dist/effects/vfx/vfx-service.d.ts +14 -0
  32. package/dist/effects/vfx/vfx-service.js +5 -0
  33. package/dist/gameplay/actors/builtin/components/mesh-component.d.ts +1 -0
  34. package/dist/gameplay/actors/builtin/components/mesh-component.js +1 -1
  35. package/dist/gameplay/ai/dynamic-tiled-navmesh.worker.js +1 -1
  36. package/dist/gameplay/index.d.ts +1 -0
  37. package/dist/gameplay/index.js +1 -1
  38. package/dist/gameplay/services/physics/physics-system.d.ts +8 -0
  39. package/dist/gameplay/services/physics/physics-system.js +1 -1
  40. package/dist/rendering.js +1 -1
  41. package/dist/scene/asset-resource-loader.d.ts +1 -0
  42. package/dist/scene/asset-resource-loader.js +1 -1
  43. package/dist/scene/landscape/landscape-manager.js +1 -1
  44. package/dist/scene/landscape/landscape.js +1 -1
  45. package/dist/scene/materializer.js +1 -1
  46. package/dist/scene/materials/grass-foliage.js +1 -1
  47. package/dist/scene/sky.js +1 -1
  48. package/dist/shader-nodes/effects.d.ts +2 -2
  49. package/dist/shader-nodes/effects.js +1 -1
  50. package/dist/shader-nodes/landscape.js +1 -1
  51. package/dist/shader-nodes/layers.js +1 -1
  52. package/dist/shader-nodes/shapes.js +1 -1
  53. package/dist/shader-nodes/voronoi.js +1 -1
  54. package/package.json +2 -2
  55. package/tsconfig.tsbuildinfo +1 -1
@@ -1,4 +1,4 @@
1
- import{materialFromAsset as e}from"../../scene/materializer.js";import{Mesh as t,PlaneGeometry as s,Vector3 as n,InstancedMesh as o,Matrix4 as a,Vector2 as i,Triangle as r,Box3 as c,MathUtils as l,MeshStandardMaterial as h,ShaderMaterial as u,PerspectiveCamera as f}from"three";import{indexBy as d}from"../../utils/collections.js";import{smoothNormalsCrossMeshes as p}from"./utils.js";import{defaultLandscapeMaterial as m,LandscapeMesh as w}from"./landscape.js";import{meanVectors3withWeight as g}from"../../utils/math.js";import{Subject as y,debounceTime as M}from"rxjs";new n,new n;const x=new n,b=new n,S=new n;export class LandscapeManager{constructor(e,t,s,o,i,r,c){this.source=e,this.view=t,this.landscape=s,this.assetManagerService=o,this.assetService=i,this.shaders=r,this.applyMaterial=c,this.scatterMeshes=new Map,this.loadedScatterSquares=new Set,this.refreshRequests=new y,this.defaultLandscapeMaterial=m.clone(),this.scatterMeshPool=[],this.onLoopHandler=()=>this.update(),this.sectionCache=new Map,this._matrix=new a,this.scatterGeometryCache=new Map,this._lastUpdatePosition=new n,this._cameraPosition=new n,this.view.onLoop(this.onLoopHandler),this.defaultLandscapeMaterial.name=m.name,this.defaultLandscapeMaterial.color=m.color,this.refreshRequests.pipe(M(500)).subscribe((e=>this.refreshScatter(e.origin,e.force,e.predicate)))}updateShaders(e){this.shaders=e}async loadGrass(){const e=await this.assetService.getAsset("6ij937n72g");await this.assetManagerService.getMesh(e);this.grassGeometry=new s(2,2,3,3);const t=this.grassGeometry.getAttribute("normal");for(let e=0;e<t.count;e++)t.setXYZ(e,0,1,0);t.needsUpdate=!0,this.grassMaterial=new h({color:3765785})}refreshGeometry(){const e=this.source.landscape.options,t=(new n,new n);this.view.camera.getWorldPosition(t);const s=[];S.fromArray(this.source.position);const o=this.view.camera instanceof f?Math.min(this.view.camera.far,1e3):1e3,a=1.1*o,i=e.sections.y*e.sectionSize/-2,r=e.sections.x*e.sectionSize/-2;for(let n=0;n<e.sections.x;n++)if(x.x=r+n*e.sectionSize,!(Math.abs(t.x-x.x)>a))for(let c=0;c<e.sections.y;c++){x.z=i+c*e.sectionSize,b.copy(S).add(x);const l=b.distanceTo(t),h=`${n},${c}`,u=this.landscape.sections.find((e=>e.x===n&&e.y===c));if(l<=o){if(null==u){this.sectionCache.has(h)||this.sectionCache.set(h,this.createLandscapeMesh(this.source,e,r,i,n,c));const t=this.sectionCache.get(h);this.applyMaterial(t),this.landscape.add(t),s.push(t)}}else l>a&&this.landscape.remove(u)}p(s)}applyHeightMap(e,t,s,n=1){const o=Math.pow(s+1,2),a=e.getAttribute("position");if(1===n)for(const e of t.points)a.setY(e.i,e.y);else{const e=d(t.points??[],(e=>e.i));for(let t=0;t<a.count;t++){const s=v(t,a.count,o);let n=0;n=s%1==0?e.get(s)?.y??0:Math.floor(e.get(s)?.y),a.setY(t,n)}}a.needsUpdate=!0,e.computeVertexNormals()}deleteOldScatterMeshes(){const e=new Set;for(const[t,s]of this.source.grass?.layers.entries()??[])for(const[n,o]of s.meshes.entries()){const s=`${t}-${n}`;e.add(s)}for(const t of this.scatterMeshes.keys())if(!e.has(t)){this.scatterMeshes.get(t).forEach((e=>{e.parent?.remove(e),e.dispose()})),this.scatterMeshes.delete(t)}}queueRefreshScatter(e,t=!1,s=(()=>!0)){this.refreshRequests.next({origin:e,force:t,predicate:s})}async refreshScatter(s,a=!1,i=(()=>!0)){a&&this.scatterGeometryCache.clear(),this.deleteOldScatterMeshes();for(const[c,h]of this.source.grass?.layers.entries()??[])for(const[u,f]of h.meshes.entries()){const h=`${c}-${u}`;this.scatterMeshes.has(h)||this.scatterMeshes.set(h,new Map);const p=this.scatterMeshes.get(h),m=await this.assetService.getAsset(f.assetId),w=await this.assetManagerService.getMesh(m),y=[];if(w.scene.traverse((e=>{e instanceof t&&y.push(e)})),1!==y.length){console.log(w),console.warn("Dynamic grass only works for meshes with a single geometry.");continue}if(!(y[0]instanceof t)){console.warn("Only meshes can be used for dynamic grass. Found:",w.scene);continue}const M=y[0];let x=M.geometry;this.scatterGeometryCache.has(M.geometry.uuid)?x=this.scatterGeometryCache.get(M.geometry.uuid):(x=M.geometry.clone(),!0===f.normalsUp&&O(x),null==x.userData.updatedMatrix&&(w.scene.updateMatrixWorld(),x.applyMatrix4(M.matrixWorld),x.userData.updatedMatrix=!0));const b=x.getIndex().count/3;if(b>400){console.warn(`The triangle count of ${m.name} is too big ${b}. Keep it below 400`);continue}const S=null!=m.materialAssignments&&m.materialAssignments.length>0?m.materialAssignments[0].materialId:null,v=null!=S&&"null"!==S?await e(await this.assetService.getAsset(S),null,this.assetService,this.assetManagerService,this.shaders,!1):null;let A=null!=v?v:M.material;const j=l.degToRad(f.maxSlope??90),C=Math.cos(j),G=this.landscape.sections,R=G.filter(P(s,f.viewDistance)),k=R.filter((e=>!p.has(e.uuid)||a)).filter((e=>i(e)));G.filter(z(s,2*f.viewDistance)).forEach((e=>{const t=p.get(e.uuid);null!=t&&(t.visible=!1)}));for(const e of R){const t=p.get(e.uuid);null!=t&&(t.visible=!0)}performance.now();const T=this.source.landscape.options,U=T.sectionSize,W=f.density??1??1,H=T.density,X=U/H,Y=W,E=X/Math.sqrt(Y),F=Math.pow(H,2),N=E/X,Z=Math.floor(F*Y),K=[0,0,0];for(const e of k){e.updateWorldMatrix(!0,!1);const t=this._matrix,s=new n,i=e.geometry.getAttribute("position"),l=e.geometry.getAttribute("normal"),h=(this.source.vertexMaterials??[]).filter((t=>t.m===e.name)),u=d(h,(e=>e.i));let m=p.get(e.uuid);if(null==m||m.count==Z&&!a||(m.parent?.remove(m),this.scatterMeshPool.push(m),p.delete(e.uuid),m=null),null==m){const e=this.scatterMeshPool.findIndex((e=>e.count>=Z));e>-1?(m=this.scatterMeshPool[e],m.geometry=x,m.material=A,this.scatterMeshPool.splice(e,1)):m=new o(x,A,Z),m.raycast=()=>{},m.receiveShadow=!0}m.visible=!0;const w=new r(new n,new n,new n);let[y,M,b,S]=[new n,new n,new n,new n],[v,z,P]=[[],[],[]],[j,G,R]=[new n,new n,new n,new n];const k=new n,T=new n,U=new n,W=new n,O=new r(new n,new n,new n),X=new r(new n,new n,new n),E=new r(new n,new n,new n),V=new r(new n,new n,new n);let J=0;e:for(let n=0;n<F;n++){const o=Math.floor(n/H);y.fromBufferAttribute(i,n+o),W.copy(y).applyMatrix4(e.matrixWorld),O.a.copy(y),O.b.fromBufferAttribute(i,n+1+o),O.c.fromBufferAttribute(i,n+H+1+o),X.a.copy(O.b),X.b.copy(O.c),X.c.fromBufferAttribute(i,n+H+2+o),E.a.fromBufferAttribute(l,n+o),E.b.fromBufferAttribute(l,n+1+o),E.c.fromBufferAttribute(l,n+H+1+o),V.a.copy(E.b),V.b.copy(E.c),V.c.fromBufferAttribute(l,n+H+2+o);const a=[];a[0]=u.get(n+o)?.w,a[1]=u.get(n+1+o)?.w,a[2]=u.get(n+H+1+o)?.w,a[3]=u.get(n+H+2+o)?.w;let r=0;for(let n=0;n<=1+N;n+=N)for(let o=0;o<=1+N;o+=N){if(J>Z)break e;if(r++,r>Y)continue e;1-n>o?(M=O.a,b=O.b,S=O.c,j=E.a,G=E.b,R=E.c,v=a[0],z=a[1],P=a[2]):(M=X.a,b=X.b,S=X.c,j=V.a,G=V.b,R=V.c,v=a[1],z=a[2],P=a[3]),w.a.copy(M),w.b.copy(b),w.c.copy(S),L(w),k.set(y.x,0,y.z),q(w,k),w.getBarycoord(k,s).toArray(K),B[0]=v,B[1]=z,B[2]=P;if($(B,K,.2)!==c-1)continue;if(g([M,b,S],K,T),g([j,G,R],K,U),null!=f.maxSlope&&f.maxSlope<90&&U.y<C)continue;const i=T.applyMatrix4(e.matrixWorld);i.y+=_(f.offsetMin,f.offsetMax);const l=_(f.scaleMin,f.scaleMax);t.makeScale(l,l,l);const h=t.elements;h[12]=i.x,h[13]=i.y,h[14]=i.z,f.alignToNormal&&D(t,i,m.matrixWorld,U),!1!==f.randomRotation&&I(t);const u=m.instanceMatrix.array,d=16*J;u[d]=h[0],u[d+1]=h[1],u[d+2]=h[2],u[d+3]=h[3],u[d+4]=h[4],u[d+5]=h[5],u[d+6]=h[6],u[d+7]=h[7],u[d+8]=h[8],u[d+9]=h[9],u[d+10]=h[10],u[d+11]=h[11],u[d+12]=h[12],u[d+13]=h[13],u[d+14]=h[14],u[d+15]=h[15],J++}}m.count=J,m.instanceMatrix.needsUpdate=!0,p.has(e.uuid)||this.landscape?.add(m),p.set(e.uuid,m),m.userData.meshConfig=f}performance.now()}}stop(){this.view.removeOnLoop(this.onLoopHandler)}update(){this.view.camera&&(this.view.camera.getWorldPosition(this._cameraPosition),this._cameraPosition.distanceTo(this._lastUpdatePosition)>10&&(this._lastUpdatePosition.copy(this._cameraPosition),this.refreshGeometry(),this.refreshScatter(this._cameraPosition)))}clear(){this.scatterMeshes.forEach((e=>e.forEach((e=>e.parent?.remove(e)))))}createLandscapeMesh(e,t,n,o,a,i){const r=new s(t.sectionSize,t.sectionSize,t.density,t.density);r.rotateX(Math.PI/-2);const c=this.defaultLandscapeMaterial,l=new w(r,c);l.position.x=n+a*t.sectionSize,l.position.z=o+i*t.sectionSize,l.receiveShadow=!0,l.castShadow=!1,l.userData.landscape={x:a,y:i},l.x=a,l.y=i,l.name=`${a},${i}`;const h=e.landscape.heightMaps.find((e=>e.x===a&&e.y===i));return null!=h&&this.applyHeightMap(r,h,t.density,1),r.computeBoundsTree(),l}}function v(e,t,s){const n=Math.sqrt(t),o=Math.floor(e/n)/(n-1),a=e%n/(n-1),i=Math.sqrt(s);return(s-1)*o-(i-1)*o+(i-1)*a}new Map,new i(0,0),new i(1,0),new i(0,1),new i(1,0),new i(0,1),new i(1,1),new n;const A=new c;function z(e,t){return function(s){return A.setFromObject(s).distanceToPoint(e)>t}}function P(e,t){return function(s){return A.setFromObject(s).distanceToPoint(e)<t}}function L(e){e.a.y=0,e.b.y=0,e.c.y=0}const B=[];function $(e,t,s=.5){const n=B;let o=-1,a=0;for(let e=0;e<n.length;e++)if(null!=n[e])for(let i=0;i<n[e].length;i++){const r=n[e][i]*t[e];r>s&&r>a&&(a=r,o=i)}return o}function _(e,t){let s=t-e,n=G();return n*=s,n+=e,n}const j=[];let C=1e3;for(;C--;)j.push(Math.random());function G(){return++C>=j.length?j[C=0]:j[C]}const R=[];let k=20;for(;k--;)R.push((new a).makeRotationY(G()*Math.PI/2));function q(e,t){let s=G(),n=G();s+n>1&&(s=1-s,n=1-n);const o=e.a,a=e.b,i=e.c;t.x=o.x+s*(a.x-o.x)+n*(i.x-o.x),t.z=o.z+s*(a.z-o.z)+n*(i.z-o.z)}new n;new n;const T=new n,U=new n(0,1,0),W=(new a).makeRotationX(Math.PI/-2);function D(e,t,s,n){e.lookAt(T,n,U).multiply(W)}new a;function I(e){e.makeRotationX;const t=(++k>=R.length?R[k=0]:R[k]).elements,s=e.elements;s[0]=t[0],s[4]=t[4],s[8]=t[8],s[1]=t[1],s[5]=t[5],s[9]=t[9],s[2]=t[2],s[6]=t[6],s[10]=t[10]}function O(e){const t=e.getAttribute("normal");for(let e=0;e<t.count;e++)t.setXYZ(e,0,1,0);t.normalized=!0,t.needsUpdate=!0}
1
+ import{materialFromAsset as e}from"../../scene/materializer.js";import{Mesh as t,PlaneGeometry as s,Vector3 as n,InstancedMesh as o,Matrix4 as a,Vector2 as i,Triangle as r,Box3 as c,MathUtils as l,MeshStandardMaterial as h,ShaderMaterial as u,PerspectiveCamera as f}from"three";import{indexBy as d}from"../../utils/collections.js";import{smoothNormalsCrossMeshes as p}from"./utils.js";import{defaultLandscapeMaterial as m,LandscapeMesh as w}from"./landscape.js";import{meanVectors3withWeight as y}from"../../utils/math.js";import{whenIdle as g}from"../../utils/async.js";import{Subject as M,debounceTime as x}from"rxjs";new n,new n;const b=new n,S=new n,v=new n;export class LandscapeManager{constructor(e,t,s,o,i,r,c){this.source=e,this.view=t,this.landscape=s,this.assetManagerService=o,this.assetService=i,this.shaders=r,this.applyMaterial=c,this.scatterMeshes=new Map,this.loadedScatterSquares=new Set,this.refreshRequests=new M,this.defaultLandscapeMaterial=m.clone(),this.scatterMeshPool=[],this.onLoopHandler=()=>this.update(),this.sectionCache=new Map,this._matrix=new a,this.scatterGeometryCache=new Map,this._lastUpdatePosition=new n,this._cameraPosition=new n,this.view.onLoop(this.onLoopHandler),this.defaultLandscapeMaterial.name=m.name,this.defaultLandscapeMaterial.color=m.color,this.refreshRequests.pipe(x(500)).subscribe((e=>this.refreshScatter(e.origin,e.force,e.predicate)))}updateShaders(e){this.shaders=e}async loadGrass(){const e=await this.assetService.getAsset("6ij937n72g");await this.assetManagerService.getMesh(e);this.grassGeometry=new s(2,2,3,3);const t=this.grassGeometry.getAttribute("normal");for(let e=0;e<t.count;e++)t.setXYZ(e,0,1,0);t.needsUpdate=!0,this.grassMaterial=new h({color:3765785})}refreshGeometry(){const e=this.source.landscape.options,t=(new n,new n);this.view.camera.getWorldPosition(t);const s=[];v.fromArray(this.source.position);const o=this.view.camera instanceof f?Math.min(this.view.camera.far,1e3):1e3,a=1.1*o,i=e.sections.y*e.sectionSize/-2,r=e.sections.x*e.sectionSize/-2;for(let n=0;n<e.sections.x;n++)if(b.x=r+n*e.sectionSize,!(Math.abs(t.x-b.x)>a))for(let c=0;c<e.sections.y;c++){b.z=i+c*e.sectionSize,S.copy(v).add(b);const l=S.distanceTo(t),h=`${n},${c}`,u=this.landscape.sections.find((e=>e.x===n&&e.y===c));if(l<=o){if(null==u){this.sectionCache.has(h)||this.sectionCache.set(h,this.createLandscapeMesh(this.source,e,r,i,n,c));const t=this.sectionCache.get(h);this.applyMaterial(t),this.landscape.add(t),s.push(t)}}else l>a&&this.landscape.remove(u)}p(s)}applyHeightMap(e,t,s,n=1){const o=Math.pow(s+1,2),a=e.getAttribute("position");if(1===n)for(const e of t.points)a.setY(e.i,e.y);else{const e=d(t.points??[],(e=>e.i));for(let t=0;t<a.count;t++){const s=A(t,a.count,o);let n=0;n=s%1==0?e.get(s)?.y??0:Math.floor(e.get(s)?.y),a.setY(t,n)}}a.needsUpdate=!0,e.computeVertexNormals()}deleteOldScatterMeshes(){const e=new Set;for(const[t,s]of this.source.grass?.layers.entries()??[])for(const[n,o]of s.meshes.entries()){const s=`${t}-${n}`;e.add(s)}for(const t of this.scatterMeshes.keys())if(!e.has(t)){this.scatterMeshes.get(t).forEach((e=>{e.parent?.remove(e),e.dispose()})),this.scatterMeshes.delete(t)}}queueRefreshScatter(e,t=!1,s=(()=>!0)){this.refreshRequests.next({origin:e,force:t,predicate:s})}async refreshScatter(s,a=!1,i=(()=>!0)){a&&this.scatterGeometryCache.clear(),this.deleteOldScatterMeshes();for(const[c,h]of this.source.grass?.layers.entries()??[])for(const[u,f]of h.meshes.entries()){const h=`${c}-${u}`;this.scatterMeshes.has(h)||this.scatterMeshes.set(h,new Map);const p=this.scatterMeshes.get(h),m=await this.assetService.getAsset(f.assetId),w=await this.assetManagerService.getMesh(m),M=[];if(w.scene.traverse((e=>{e instanceof t&&M.push(e)})),1!==M.length){console.log(w),console.warn("Dynamic grass only works for meshes with a single geometry.");continue}if(!(M[0]instanceof t)){console.warn("Only meshes can be used for dynamic grass. Found:",w.scene);continue}const x=M[0];let b=x.geometry;this.scatterGeometryCache.has(x.geometry.uuid)?b=this.scatterGeometryCache.get(x.geometry.uuid):(b=x.geometry.clone(),!0===f.normalsUp&&H(b),null==b.userData.updatedMatrix&&(w.scene.updateMatrixWorld(),b.applyMatrix4(x.matrixWorld),b.userData.updatedMatrix=!0));const S=b.getIndex().count/3;if(S>400){console.warn(`The triangle count of ${m.name} is too big ${S}. Keep it below 400`);continue}const v=null!=m.materialAssignments&&m.materialAssignments.length>0?m.materialAssignments[0].materialId:null,A=null!=v&&"null"!==v?await e(await this.assetService.getAsset(v),null,this.assetService,this.assetManagerService,this.shaders,!1):null;let z=null!=A?A:x.material;const C=l.degToRad(f.maxSlope??90),G=Math.cos(C),R=this.landscape.sections,k=R.filter(L(s,f.viewDistance)),q=k.filter((e=>!p.has(e.uuid)||a)).filter((e=>i(e)));R.filter(P(s,2*f.viewDistance)).forEach((e=>{const t=p.get(e.uuid);null!=t&&(t.visible=!1)}));for(const e of k){const t=p.get(e.uuid);null!=t&&(t.visible=!0)}performance.now();const U=this.source.landscape.options,W=U.sectionSize,D=f.density??1??1,X=U.density,Y=W/X,E=D,F=Y/Math.sqrt(E),N=Math.pow(X,2),Z=F/Y,K=Math.floor(N*E),V=[0,0,0];for(const e of q)await g((async()=>{e.updateWorldMatrix(!0,!1);const t=this._matrix,s=new n,i=e.geometry.getAttribute("position"),l=e.geometry.getAttribute("normal"),h=(this.source.vertexMaterials??[]).filter((t=>t.m===e.name)),u=d(h,(e=>e.i));let m=p.get(e.uuid);if(null==m||m.count==K&&!a||(m.parent?.remove(m),this.scatterMeshPool.push(m),p.delete(e.uuid),m=null),null==m){const e=this.scatterMeshPool.findIndex((e=>e.count>=K));e>-1?(m=this.scatterMeshPool[e],m.geometry=b,m.material=z,this.scatterMeshPool.splice(e,1)):m=new o(b,z,K),m.raycast=()=>{},m.receiveShadow=!0}m.visible=!0;const w=new r(new n,new n,new n);let[g,M,x,S]=[new n,new n,new n,new n],[v,A,P]=[[],[],[]],[L,C,R]=[new n,new n,new n,new n];const k=new n,q=new n,U=new n,W=new n,D=new r(new n,new n,new n),H=new r(new n,new n,new n),Y=new r(new n,new n,new n),F=new r(new n,new n,new n);let J=0;e:for(let n=0;n<N;n++){const o=Math.floor(n/X);g.fromBufferAttribute(i,n+o),W.copy(g).applyMatrix4(e.matrixWorld),D.a.copy(g),D.b.fromBufferAttribute(i,n+1+o),D.c.fromBufferAttribute(i,n+X+1+o),H.a.copy(D.b),H.b.copy(D.c),H.c.fromBufferAttribute(i,n+X+2+o),Y.a.fromBufferAttribute(l,n+o),Y.b.fromBufferAttribute(l,n+1+o),Y.c.fromBufferAttribute(l,n+X+1+o),F.a.copy(Y.b),F.b.copy(Y.c),F.c.fromBufferAttribute(l,n+X+2+o);const a=[];a[0]=u.get(n+o)?.w,a[1]=u.get(n+1+o)?.w,a[2]=u.get(n+X+1+o)?.w,a[3]=u.get(n+X+2+o)?.w;let r=0;for(let n=0;n<=1+Z;n+=Z)for(let o=0;o<=1+Z;o+=Z){if(J>K)break e;if(r++,r>E)continue e;1-n>o?(M=D.a,x=D.b,S=D.c,L=Y.a,C=Y.b,R=Y.c,v=a[0],A=a[1],P=a[2]):(M=H.a,x=H.b,S=H.c,L=F.a,C=F.b,R=F.c,v=a[1],A=a[2],P=a[3]),w.a.copy(M),w.b.copy(x),w.c.copy(S),j(w),k.set(g.x,0,g.z),T(w,k),w.getBarycoord(k,s).toArray(V),B[0]=v,B[1]=A,B[2]=P;if($(B,V,.2)!==c-1)continue;if(y([M,x,S],V,q),y([L,C,R],V,U),null!=f.maxSlope&&f.maxSlope<90&&U.y<G)continue;const i=q.applyMatrix4(e.matrixWorld);i.y+=_(f.offsetMin,f.offsetMax);const l=_(f.scaleMin,f.scaleMax);t.makeScale(l,l,l);const h=t.elements;h[12]=i.x,h[13]=i.y,h[14]=i.z,!1!==f.randomRotation&&O(t),f.alignToNormal&&I(t,i,m.matrixWorld,U);const u=m.instanceMatrix.array,d=16*J;u[d]=h[0],u[d+1]=h[1],u[d+2]=h[2],u[d+3]=h[3],u[d+4]=h[4],u[d+5]=h[5],u[d+6]=h[6],u[d+7]=h[7],u[d+8]=h[8],u[d+9]=h[9],u[d+10]=h[10],u[d+11]=h[11],u[d+12]=h[12],u[d+13]=h[13],u[d+14]=h[14],u[d+15]=h[15],J++}}m.count=J,m.instanceMatrix.needsUpdate=!0,p.has(e.uuid)||this.landscape?.add(m),p.set(e.uuid,m),m.userData.meshConfig=f}));performance.now()}}stop(){this.view.removeOnLoop(this.onLoopHandler)}update(){this.view.camera&&(this.view.camera.getWorldPosition(this._cameraPosition),this._cameraPosition.distanceTo(this._lastUpdatePosition)>10&&(this._lastUpdatePosition.copy(this._cameraPosition),this.refreshGeometry(),this.refreshScatter(this._cameraPosition)))}clear(){this.scatterMeshes.forEach((e=>e.forEach((e=>e.parent?.remove(e)))))}createLandscapeMesh(e,t,n,o,a,i){const r=new s(t.sectionSize,t.sectionSize,t.density,t.density);r.rotateX(Math.PI/-2);const c=this.defaultLandscapeMaterial,l=new w(r,c);l.position.x=n+a*t.sectionSize,l.position.z=o+i*t.sectionSize,l.receiveShadow=!0,l.castShadow=!1,l.userData.landscape={x:a,y:i},l.x=a,l.y=i,l.name=`${a},${i}`;const h=e.landscape.heightMaps.find((e=>e.x===a&&e.y===i));return null!=h&&this.applyHeightMap(r,h,t.density,1),r.computeBoundsTree(),l}}function A(e,t,s){const n=Math.sqrt(t),o=Math.floor(e/n)/(n-1),a=e%n/(n-1),i=Math.sqrt(s);return(s-1)*o-(i-1)*o+(i-1)*a}new Map,new i(0,0),new i(1,0),new i(0,1),new i(1,0),new i(0,1),new i(1,1),new n;const z=new c;function P(e,t){return function(s){return z.setFromObject(s).distanceToPoint(e)>t}}function L(e,t){return function(s){return z.setFromObject(s).distanceToPoint(e)<t}}function j(e){e.a.y=0,e.b.y=0,e.c.y=0}const B=[];function $(e,t,s=.5){const n=B;let o=-1,a=0;for(let e=0;e<n.length;e++)if(null!=n[e])for(let i=0;i<n[e].length;i++){const r=n[e][i]*t[e];r>s&&r>a&&(a=r,o=i)}return o}function _(e,t){let s=t-e,n=R();return n*=s,n+=e,n}const C=[];let G=1e3;for(;G--;)C.push(Math.random());function R(){return++G>=C.length?C[G=0]:C[G]}const k=[];let q=20;for(;q--;)k.push((new a).makeRotationY(R()*Math.PI/2));function T(e,t){let s=R(),n=R();s+n>1&&(s=1-s,n=1-n);const o=e.a,a=e.b,i=e.c;t.x=o.x+s*(a.x-o.x)+n*(i.x-o.x),t.z=o.z+s*(a.z-o.z)+n*(i.z-o.z)}new n;new n;const U=new n,W=new n(0,1,0),D=(new a).makeRotationX(Math.PI/-2);function I(e,t,s,n){e.lookAt(U,n,W).multiply(D)}new a;function O(e){e.makeRotationX;const t=(++q>=k.length?k[q=0]:k[q]).elements,s=e.elements;s[0]=t[0],s[4]=t[4],s[8]=t[8],s[1]=t[1],s[5]=t[5],s[9]=t[9],s[2]=t[2],s[6]=t[6],s[10]=t[10]}function H(e){const t=e.getAttribute("normal");for(let e=0;e<t.count;e++)t.setXYZ(e,0,1,0);t.normalized=!0,t.needsUpdate=!0}
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -1,4 +1,4 @@
1
- import{Group as e,Mesh as a}from"three";import{Color as r}from"three";import{varyingAttributes as t,float as n,mod as o,dot as s,vec2 as c,step as i,fract as l,mix as p,rgb as d,NodeShaderMaterial as u,rgba as m,standardMaterial as f}from"three-shader-graph";import{mixColorsByLayer as L,select as h}from"../../shader-nodes/index.js";export function initLandscape(e){e.sections.y,e.sectionSize,e.sections.x,e.sectionSize;return new LandscapeGroup}export function createLandscapeDefaultMaterial(){const e=t.uv,a=n(10),h=n(7),x=o(s(c(1,1),i(c(.5,.5),l(e.multiplyScalar(a)))),n(2)),S=o(s(c(1,1),i(c(.5,.5),l(e.multiplyScalar(h.multiply(a))))),n(2)),w=p(d(new r(4473924).convertLinearToSRGB()),d(new r(5592405).convertLinearToSRGB()),x),v=p(w,w.addScalar(n(.1)),S),y=L({layerColors:[m(v).rgb(),...["#55DDE0","#33658A","#2F4858"].map((e=>new r(e).convertLinearToSRGB())).map((e=>d(e))).reverse()],enableNoise:!1}),D=new u({color:f({color:y})});return D.color=new r("#aaaaaa"),D.name="Default",D}export const defaultLandscapeMaterial=createLandscapeDefaultMaterial();export class LandscapeMesh extends a{}export class LandscapeGroup extends e{get sections(){return this.children.filter((e=>e instanceof LandscapeMesh))}}
1
+ import{Group as e,Mesh as a}from"three";import{Color as r}from"three";import{varyingAttributes as t,float as n,mod as o,dot as s,vec2 as c,step as i,fract as l,mix as p,rgb as d,NodeShaderMaterial as u,rgba as m,standardMaterial as f}from"three-shader-graph";import{mixColorsByLayer as L,select as h}from"../../shader-nodes/index.js";export function initLandscape(e){e.sections.y,e.sectionSize,e.sections.x,e.sectionSize;return new LandscapeGroup}export function createLandscapeDefaultMaterial(){const e=t.uv,a=n(10),h=n(7),x=o(s(c(1,1),i(c(.5,.5),l(e.multiplyScalar(a)))),n(2)),S=o(s(c(1,1),i(c(.5,.5),l(e.multiplyScalar(h.multiply(a))))),n(2)),w=p(d(new r(4473924).convertLinearToSRGB()),d(new r(5592405).convertLinearToSRGB()),x),v=p(w,w.addScalar(n(.1)),S),y=L({layerColors:[m(v).rgb,...["#55DDE0","#33658A","#2F4858"].map((e=>new r(e).convertLinearToSRGB())).map((e=>d(e))).reverse()],enableNoise:!1}),D=new u({color:f({color:y})});return D.color=new r("#aaaaaa"),D.name="Default",D}export const defaultLandscapeMaterial=createLandscapeDefaultMaterial();export class LandscapeMesh extends a{}export class LandscapeGroup extends e{get sections(){return this.children.filter((e=>e instanceof LandscapeMesh))}}
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -1,4 +1,4 @@
1
- import{Subject as e}from"rxjs";import*as t from"three";import{BoxGeometry as a,Color as s,Euler as r,Fog as i,FogExp2 as n,Group as o,Material as c,Mesh as l,MeshLambertMaterial as h,MeshPhongMaterial as m,MeshStandardMaterial as p,Object3D as d,PointLight as u,Quaternion as f,SphereGeometry as y,Texture as g,Vector2 as w,Vector3 as S,Vector4 as v}from"three";import A,{SpriteRenderer as b}from"three-nebula";import{bool as M,BooleanNode as x,float as j,FloatNode as I,NodeShaderMaterial as P,rgb as D,RgbNode as N,Texture2dLookupNode as E,textureSampler2d as V,vec2 as C,Vec2Node as F,vec3 as k,Vec3Node as z,vec4 as O}from"three-shader-graph";import B from"../gameplay/actors/builtin/index.js";import{extractShaderParameters as _}from"../shader/parameter.js";import{groupBy as T,ArrayMap as $}from"../utils/collections.js";import{filterChildrenShallow as L,filterSceneShallow as R}from"../utils/three/traverse.js";import{AssetMeshInstance as U}from"./asset-resource-loader.js";import{BoxCollisionShape as J,PhysicalShapeMesh as H}from"./collision/collision-shape.js";import{isCollisionMesh as W}from"./collision/collision-shape-import.js";import{initLandscape as q}from"./landscape/landscape.js";import{LandscapeManager as X}from"./landscape/landscape-manager.js";import{SectionGrid as G,smoothNormalsCrossMeshes as Y}from"./landscape/utils.js";import{createGrassMaterial as Z}from"./materials/grass.js";import{createGrassFoliageMaterial as Q}from"./materials/grass-foliage.js";import{getMaterialAttribute as K}from"./materials/utils/material-painting.js";import{createWaterMaterial as ee}from"./materials/water.js";import{SerializedParamType as te}from"./model.js";import{Matrix4 as ae}from"three";import{BaseActor as se}from"../gameplay/actors/actor.js";import{Sampler2DNode as re}from"../shader-nodes/index.js";import{StandardShader as ie}from"../shader/builtin/standard-shader.js";import{LambertShader as ne}from"../shader/builtin/lambert-shader.js";import{ShapeLibrary as oe,ShapeLibraryKeys as ce}from"./objects/shapes.js";import{ambientLightName as le,createSky as he,defaultSkyMaterial as me}from"./sky.js";import{PhysicsBodyType as pe,withInjectionContext as de}from"../gameplay/index.js";import{iterateMaterials as ue}from"../utils/materials.js";import{VfxActor as fe}from"../effects/vfx/vfx-actor.js";import{VisualEffect as ye}from"../effects/vfx/vfx-param.js";import{findFirstVisibleObject as ge}from"../utils/three/traverse.js";const we={};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(a,s,r,i,n,o,c,l){this.scene=a,this.dataProvider=s,this.assetsService=r,this.assetManagerService=i,this.renderingView=n,this.shaders=o,this.actorTypes=c,this.actorProvider=l,this.objectMap=new Map,this.sceneObjectMap=new Map,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.inEditor=!0,this.updated$=new e,this.removed$=new e,this.error$=new e,this.editorActorParamSnapshot=new Map,this.assets=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,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 e=>{this.assets.set(e.id,e),"material"==e.type?a.traverse((a=>{if(a instanceof t.Mesh)if(Array.isArray(a.material))for(let t=0;t<a.material.length;t++)this.refreshMaterial(a,a.material[t],e,t);else this.refreshMaterial(a,a.material,e)})):"mesh"==e.type?(this.findByAssetId(e.id).forEach((t=>{De(t.userData.src.materialAssignments,e.materialAssignments).forEach((e=>{this.applyMaterial(t,e)}))})),this.landscapeManagers.forEach((t=>{t.source.grass.layers.some((t=>t.meshes.some((t=>t.assetId===e.id))))&&t.queueRefreshScatter(this.renderingView?.camera.position??new S,!0)}))):"prefab"===e.type&&this.findByAssetId(e.id).forEach((e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t)}))}))}async refreshMaterial(e,t,a,s){if(t?.userData?.assetId!==a.id)return;const r=await materialFromAsset(a,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!0);r.userData=t.userData,null!=s?Ee(e.material[s],r)||(e.material[s]=r):Ee(e.material,r)||(e.material=r)}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(),ve.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 Me(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 Me(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!==pe.dynamic&&"sky"!==e.type&&"global_fog"!==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=>{!W(e)&&e.isMesh&&a.push(e)}));const s=1==a.length&&0==a[0].children.length,r=a[0]instanceof l&&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 e=[],a=new $,s=new $;for(const t of this.dataProvider.getObjects())await Pe(t,(async(t,r,i)=>{const n="asset_mesh"==t.type&&this.canObjectBeInstanced(t)&&await this.canAssetBeInstanced(t),o="shape_mesh"===t.type&&"landscape"!==t.shape&&t.physics?.type!==pe.dynamic;if(n||o)if(r&&r.children?.length>0&&r.children.splice(r.children.findIndex((e=>e.id===t.id)),1),o){const e=t.shape+JSON.stringify(t.materialAssignments??[])+JSON.stringify(t.shapeParams??{})+t.castShadow+t.receiveShadow;s.push(e,{...t,parentTransform:i})}else{const e=t.assetId+JSON.stringify(t.materialAssignments??[]);a.push(e,{...t,parentTransform:i})}else null==r&&e.push({...t,parentTransform:i})}));for(const e of a.values()){if(0==e.length)continue;const t=await this.createFromAsset(e[0]);if(null==t)continue;const a=await this.createInstancedMesh(e,t),s=new U;s.add(a),s.userData.src=e[0],t instanceof U&&(s.collisionShapes=t.collisionShapes),s.castShadow=!1,s.receiveShadow=!1,this.scene.add(s)}for(const e of s.values()){if(0==e.length)continue;const a=await this.createFromShape(e[0]),s=ge(a,(e=>!W(e)&&null!=e.geometry)),i=s.geometry,n=new t.InstancedMesh(i,s.material.clone(),e.length);for(let i=0;i<e.length;i++){const o=(new t.Matrix4).compose((new S).fromArray(e[i].position),(new f).setFromEuler((new r).fromArray(e[i].rotation)),(new S).fromArray(e[i].scale)),c=(new ae).copy(e[i].parentTransform).multiply(o);n.setMatrixAt(i,c),n.castShadow=a.castShadow??!0,n.receiveShadow=s.receiveShadow??!0;const l=new U;l.add(n),l.userData.src=e[0],a instanceof H&&(l.collisionShapes=[a.collisionShape]),l.castShadow=!1,l.receiveShadow=!1,this.scene.add(l)}}await Promise.all(e.map((e=>this.materialize(e)))),await this.initActorsPostInit()}async createInstancedMesh(e,a){const s=ge(a,(e=>!W(e)&&null!=e.geometry)),i=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(a,De(e[0].materialAssignments,i.materialAssignments)),s.updateMatrix();const n=s.geometry.clone().applyMatrix4(s.matrix),o=new t.InstancedMesh(n,s.material,e.length);s.material instanceof c&&(o.material.side=t.FrontSide);for(let a=0;a<e.length;a++){const s=(new t.Matrix4).compose((new S).fromArray(e[a].position),(new f).setFromEuler((new r).fromArray(e[a].rotation)),(new S).fromArray(e[a].scale)),i=(new ae).copy(e[a].parentTransform).multiply(s);o.setMatrixAt(a,i)}return o.castShadow=e[0].castShadow??i.castShadow??!0,o.receiveShadow=e[0].receiveShadow??i.receiveShadow??!0,o}remove(e){if(console.log("Remove scene object",e),"global_fog"==e.type)return void(this.scene.fog=this.originalFog);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 R(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)return materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders)}),this._originalMaterials)}unapplyMaterials(e){e.traverse((async e=>{if(e instanceof l)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(B));R(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 ve.entries())t.userData.customShaderName&&ve.delete(e);this.landscapeManagers.forEach((t=>t.updateShaders(e))),R(this.scene,(e=>!0)).forEach((e=>{e.traverse((async e=>{if(e instanceof l)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);const t=this.sceneObjectMap.get(e.id);if(t){let r=!1;if(t.traverseAncestors((e=>{"_hology_transform_group"===e.name&&(r=!0)})),!r){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 l&&(e.material.wireframe=!0)})):t.traverse((e=>{e instanceof l&&(e.material.wireframe=!1)}))}if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);De(e.materialAssignments,a.materialAssignments).forEach((e=>this.applyMaterial(t,e)))}else"shape_mesh"===e.type&&this.applyMaterials(t,e.materialAssignments);if(r||(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 s(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)this.applyHeightMaps(t,e.landscape.heightMaps),this.inEditor&&this.landscapeManagers.filter((t=>t.source.id===e.id)).forEach((e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,(e=>!0))));else if("global_fog"===e.type){const t=(this.scene.fog instanceof n?"density":"linear")!==e.fog.type;this.scene.fog=je(e.fog),t&&(a=this.scene).traverse((e=>{if(e instanceof l){const t=e.material;t instanceof P&&(a.fog instanceof i?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof n&&(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"),r||(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 H&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&Se(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}async materializeAndInitActor(e,t=this.findParent(e)){console.log("materialize actor and init");const a=await this.materialize(e,t);return Pe(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:L(t,(t=>t.children?.some((t=>t.id===e.id))),(()=>!0))))[0];return null==t?this.scene:null!=t?R(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 s(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse((e=>{e instanceof l&&e.geometry&&(t=e)})),t}applyVertexMaterials(e,t){if(null==e.vertexMaterials||0===e.vertexMaterials.length)return;const a=T(e.vertexMaterials,(e=>e.m));t.traverse((e=>{if(e instanceof l){const t=K(e,!1);if(null!=t){for(let e=0;e<t.array.length;e++)t.setX(e,0);t.needsUpdate=!0}}}));const s=new Set;for(const[e,r]of a.entries()){const a=null!=e?t.getObjectByName(e):this.findMeshWithGeometry(t);let i=!1;if(null==a)return void console.warn(`Failed to apply vertex materials on mesh with name "${e}"`);const n=K(a,!0);for(let e=0;e<n.array.length;e++)n.setX(e,0);for(const e of r)n.setX(e.i,e.w[0]),n.setY(e.i,e.w[1]),n.setZ(e.i,e.w[2]),i=!0;i&&s.add(e)}this.inEditor&&this.landscapeManagers.filter((t=>t.source.id===e.id)).forEach((e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,(e=>s.has(e.name)))))}async materialize(e,t,s=!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=je(e.fog),this.fixFogColor(),r=new o;break;case"sky":this.sky=he(),this.updateSky(e),r=this.sky;break;case"actor":r=await this.createFromActor(e);break;case"group":r=new o;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),s||(r.userData.src=e),this.inEditor,this.inEditor){let e=null;r instanceof H&&(e=function(e){if(e instanceof J)return new l(new a(...e.offset.toArray()),Ie);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!==pe.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,s)))),r}}async updateSky(e){if(null==e?.sky?.materialId)return void(this.sky.material=me);const a=await this.assetsService.getAsset(e.sky.materialId),s=await materialFromAsset(a,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);s.side=t.BackSide,null!=this.sky?this.sky.material=s:console.warn("No sky has been created")}async createComponent(e,t,a,s){const r=new we[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??B[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 S).fromArray(e.position),(new r).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(fe,(new S).fromArray(e.position),(new r).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 l&&this._originalMaterials.set(e.id,e.material)}));else{let r=new p({name:"Default",color:new s("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});const i=await this.createMeshByShape(e.shape,r,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||((e.materialAssignments??[]).filter((e=>null!=e.materialId)).forEach((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 o;const a=q(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new X(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 G(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((()=>Y(r)),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&ce.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);return this.geometryCache.has(r)||this.geometryCache.set(r,oe[e].geometry(s)),this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,oe[e].collision(s)),new H(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);De(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,Se(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 l&&"computeBoundsTree"in e.geometry&&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 o;return t.prefab.objects.filter((e=>"global_fog"!==e.type)).forEach((e=>this.materialize(e,a,!0))),a}async createParticleSystem(e){const a=await this.assetsService.getAsset(e.assetId),s=new d;return await A.fromJSONAsync(a.particleSystem,t).then((e=>{const a=new b(s,t);e.addRenderer(a),this.renderingView.onLoop((t=>e.update()))})),s}async createLight(e){if("point"===e.light.type){const t=new u(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 y(.3,10,10),a=new p({color:new s(16771709)}),r=new l(e,a);t.add(r)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional),new o):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient),new o):void 0}applyDirectionalAmbientLight(e,t){const a=this.scene.children.find((e=>e.name===le));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 Se(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse((e=>{e.castShadow=t,e.receiveShadow=a}))}const ve=new Map,Ae=new h({color:16711935}),be=new Map;export async function materialFromAsset(e,a,r,i,n,o=!0){const c=JSON.stringify(e.material);if(o&&ve.has(c))return ve.get(c);const l={opacity:e.material.params.opacity,map:null,emissive:e.material.params.emissive??null,metalness:e.material.params.metalness??0,flatShading:e.material.params.flatShading??!1,color:new s(e.material.params.color),transparent:null!=e.material.params.opacity&&e.material.params.opacity<1},h={};if(null!=e.material.params.map){const t=e.material.params.map,a=await r.getAsset(t);null!=a&&(l.map=await i.getTexture(a))}let p;switch(e.material.type){case"phong":p=new m({...l,...h});break;case"water":p=ee(l,a);break;case"grassFoliage":p=Q({color:l.color,map:l.map},a);break;case"grass":p=Z({...l,colorTwo:new s(e.material.params.colorTwo),colorThree:new s(e.material.params.colorThree)},a);break;case"standard":case"lambert":case"shader":const t={standard:ie,lambert:ne}[e.material.type]??n.find((t=>t.name==e.material.shader))?.type;if(t){const s=new t,o=await Me(e.material?.shaderParams??{},t,r,i,null,a,n);Object.assign(s,o);try{p=s.build()}catch(t){console.log("Shader runtime error: "+t),be.has(e.material.shader)||be.set(e.material.shader,Ae.clone()),p=be.get(e.material.shader)}p.userData.customShaderName=e.material.shader}else console.warn("Missing shader implementation with name "+e.material.shader),p=Ae;break;default:throw new Error("Unsupported material type"+e.material.type)}return a?.csm.setupMaterial(p),o&&ve.set(c,p),p.side=e.material.side??p.side??t.FrontSide,p.transparent=(e.material.transparent??l.transparent??!1)||p.transparent,e.material.bloom&&(p.userData.hasBloom=!0),p.userData.assetId=e.id,p}async function Me(e,t,a,s,r,i,n,o){const c={};for(const[t,l]of Object.entries(e)){const e=await xe(l,a,s,r,i,n,o);null!=e&&(c[t]=e)}return c}export async function prepareShapeParameters(e){const t={};for(const[a,s]of Object.entries(e)){const e=await xe(s,null,null,null);null!=e&&(t[a]=e)}return t}async function xe(e,t,a,i,n,o,c){if(te.String,null==e||null==e.value||""==e.value)return null;const l=e.value;switch(e.type){case te.Number:case te.FloatNode:let h="string"==typeof l?parseFloat(l):l;return e.type===te.FloatNode?j(h):h;case te.Texture:return await a.getTexture(await t.getAsset(l));case te.Sampler2DNode:return V(await a.getTexture(await t.getAsset(l)));case te.Boolean:return l;case te.BooleanNode:return M(l);case te.Vector2:case te.Vec2Node:if("object"==typeof l){const t=l instanceof Array?(new w).fromArray(l):new w(l.x,l.y);return e.type===te.Vec2Node?C(t):t}return null;case te.Vector3:case te.Vec3Node:if("object"==typeof l){const t=l instanceof Array?(new S).fromArray(l):new S(l.x,l.y,l.z);return e.type===te.Vec3Node?k(t):t}return null;case te.Color:case te.RgbNode:const m=new s(l);return e.type===te.RgbNode?D(m):m;case te.String:return l;case te.BaseActor:const p=l;return null==i&&console.warn("Class parameters can not be prepared as actors are not passed in"),i?.get(p);case te.Euler:const d=l;return(new r).fromArray(d);case te.Object3D:return(await a.getMesh(await t.getAsset(l))).scene;case te.Material:return await materialFromAsset(await t.getAsset(l),n,t,a,o);case te.AudioBuffer:return await a.getAudio(await t.getAsset(l));case te.VisualEffect:const u=await t.getAsset(l);if(null==c){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in u)return new ye(c,u);console.error("Using a non-vfx asset for visual effect parameter")}return null}function je(e){return"linear"===e.type?new i(new s(e.color),e.near??100,e.far??1e3):"density"===e.type?new n(e.color,e.density):void console.warn("Invalid fog type",e)}const Ie=new p({color:4229780});async function Pe(e,a,s,i){null==i&&(i=(new ae).identity()),await a(e,s,i);const n=i.clone().multiply(function(e,t){if(null==e.position||null==e.rotation||null==e.scale)return t.identity();return t.compose((new S).fromArray(e.position),(new f).setFromEuler((new r).fromArray(e.rotation)),(new S).fromArray(e.scale))}(e,new t.Matrix4));return Promise.all((e.children??[]).map((t=>Pe(t,a,e,n))))}export function toSerializedParamType(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?te.Number:t instanceof I||"function"==typeof e.prototype.isFloat?te.FloatNode:t instanceof g||e===g||e.isTexture?te.Texture:t instanceof re||e===E?te.Sampler2DNode:t instanceof Boolean||e===Boolean?te.Boolean:t instanceof x?te.BooleanNode:t instanceof s||e==s?te.Color:t instanceof N||"function"==typeof e.prototype.isRgb?te.RgbNode:t instanceof w||e==w?te.Vector2:t instanceof F||"function"==typeof e.prototype.isVec2?te.Vec2Node:t instanceof S||e==S?te.Vector3:t instanceof z||"function"==typeof e.prototype.isVec3?te.Vec3Node:t instanceof String||e===String?te.String:t instanceof se||e==se||e.prototype instanceof se||e.prototype==se?te.BaseActor:t instanceof r||e==r?te.Euler:t instanceof d||e==d?te.Object3D:t instanceof c||e==c?te.Material:t instanceof AudioBuffer||e==AudioBuffer?te.AudioBuffer:t instanceof ye||e==ye?te.VisualEffect: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:toSerializedParamType(e.type),value:t[e.name]?.value??a[e.name]??customParameterDefaultValueByType.get(toSerializedParamType(e.type))}])))}export function prepareCustomParamsFromType(e,t,a=null){const s=_(e);if(0===s.length)return{};let r;null!=a?de(a,(()=>{r=a.get(e)})):r=new e;const i={};for(const e of s){const t=r[e.name];if(null!=t){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 w:return t instanceof w?t.toArray():void a();case S:return t instanceof S?t.toArray():void a();case v:return t instanceof v?t.toArray():void a();case s:return t instanceof s?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new s(t).getHexString():void a();case String:return t;case r:return t instanceof r?t.toArray():void a()}}function De(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=>Ne(e.materialId))),(t??[]).filter((e=>Ne(e.materialId))),(e=>e.color+e.name))}function Ne(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[te.RgbNode,"#000000"],[te.Color,"#000000"],[te.Vector4,[0,0,0,0]],[te.Vec4Node,[0,0,0,0]],[te.Vector3,[0,0,0]],[te.Vec3Node,[0,0,0]],[te.Vector2,[0,0]],[te.Vec2Node,[0,0]],[te.Euler,[0,0,0,"XYZ"]]]);export function applyMaterial(e,a,r,i){const n=[];return e.traverse((async e=>{if(e instanceof l||e.isMesh||e instanceof t.SkinnedMesh||e.isSkinnedMesh)for(const t of ue(e.material))t.hasOwnProperty("color")&&n.push(e)})),Promise.all(n.map((async e=>{if(e.material instanceof Array)for(let t=0;t<e.material.length;t++){const n=e.material[t];if(null==n.color||!(n.color instanceof s))continue;const o="#"+n.color.getHexString(),c=n.name;if(o===a.color&&(n.name===a.name||null==a.name)||e.userData["originalColor_"+t]===a.color&&e.userData["originalMaterialName_"+t]===a.name){const s=await r(a.materialId),n=e.material[t];null!=s&&(e.material[t]=s,e.userData["originalColor_"+t]=e.userData["originalColor_"+t]??o,e.userData["originalMaterialName_"+t]=e.userData["originalMaterialName_"+t]??c,null!=i&&i.set(e.id+"#"+t,n))}}else if("color"in e.material){const t="#"+e.material.color.getHexString(),s=e.material.name;if(t===a.color&&(e.material.name===a.name||null==a.name)||e.userData.originalColor===a.color&&e.userData.originalName===a.name){const n=await r(a.materialId),o=e.material;null!=n&&(e.material=n,e.userData.originalColor=e.userData.originalColor??t,e.userData.originalMaterialName=e.userData.originalMaterialName??s,null!=i&&(i.has(e.id)||i.set(e.id,o)))}}})))}function Ee(e,a){if(e instanceof t.ShaderMaterial&&a instanceof t.ShaderMaterial){return e.fragmentShader+e.vertexShader==a.fragmentShader+a.vertexShader&&function(e,a){if(e instanceof t.ShaderMaterial&&a instanceof t.ShaderMaterial){for(const t in e.uniforms){if(null==a.uniforms[t])return!1;if(a.uniforms[t].value!==e.uniforms[t].value)return console.log("Different values",a.uniforms[t].value,e.uniforms[t].value),!1}return!0}return!1}(e,a)}return!1}
1
+ import{Subject as e}from"rxjs";import*as t from"three";import{BoxGeometry as a,Color as s,Euler as r,Fog as i,FogExp2 as n,Group as o,Material as c,Mesh as l,MeshLambertMaterial as h,MeshPhongMaterial as m,MeshStandardMaterial as p,Object3D as d,PointLight as u,Quaternion as f,SphereGeometry as y,Texture as g,Vector2 as w,Vector3 as S,Vector4 as v}from"three";import A,{SpriteRenderer as b}from"three-nebula";import{bool as M,BooleanNode as x,float as j,FloatNode as I,NodeShaderMaterial as P,rgb as D,RgbNode as N,Texture2dLookupNode as E,textureSampler2d as V,vec2 as C,Vec2Node as F,vec3 as k,Vec3Node as z,vec4 as O}from"three-shader-graph";import B from"../gameplay/actors/builtin/index.js";import{extractShaderParameters as _}from"../shader/parameter.js";import{groupBy as T,ArrayMap as $}from"../utils/collections.js";import{filterChildrenShallow as L,filterSceneShallow as R}from"../utils/three/traverse.js";import{AssetMeshInstance as U}from"./asset-resource-loader.js";import{BoxCollisionShape as J,PhysicalShapeMesh as H}from"./collision/collision-shape.js";import{isCollisionMesh as W}from"./collision/collision-shape-import.js";import{initLandscape as q}from"./landscape/landscape.js";import{LandscapeManager as X}from"./landscape/landscape-manager.js";import{SectionGrid as G,smoothNormalsCrossMeshes as Y}from"./landscape/utils.js";import{createGrassMaterial as Z}from"./materials/grass.js";import{createGrassFoliageMaterial as Q}from"./materials/grass-foliage.js";import{getMaterialAttribute as K}from"./materials/utils/material-painting.js";import{createWaterMaterial as ee}from"./materials/water.js";import{SerializedParamType as te}from"./model.js";import{Matrix4 as ae}from"three";import{BaseActor as se}from"../gameplay/actors/actor.js";import{Sampler2DNode as re}from"../shader-nodes/index.js";import{StandardShader as ie}from"../shader/builtin/standard-shader.js";import{LambertShader as ne}from"../shader/builtin/lambert-shader.js";import{ShapeLibrary as oe,ShapeLibraryKeys as ce}from"./objects/shapes.js";import{ambientLightName as le,createSky as he,defaultSkyMaterial as me}from"./sky.js";import{PhysicsBodyType as pe,withInjectionContext as de}from"../gameplay/index.js";import{iterateMaterials as ue}from"../utils/materials.js";import{VfxActor as fe}from"../effects/vfx/vfx-actor.js";import{VisualEffect as ye}from"../effects/vfx/vfx-param.js";import{findFirstVisibleObject as ge}from"../utils/three/traverse.js";const we={};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(a,s,r,i,n,o,c,l){this.scene=a,this.dataProvider=s,this.assetsService=r,this.assetManagerService=i,this.renderingView=n,this.shaders=o,this.actorTypes=c,this.actorProvider=l,this.objectMap=new Map,this.sceneObjectMap=new Map,this.components=[],this.landscapeManagers=[],this.materializedActors=new Map,this.inEditor=!0,this.updated$=new e,this.removed$=new e,this.error$=new e,this.editorActorParamSnapshot=new Map,this.assets=new Map,this._canBeInstancedCache=new Map,this._originalMaterials=new Map,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 e=>{this.assets.set(e.id,e),"material"==e.type?a.traverse((a=>{if(a instanceof t.Mesh)if(Array.isArray(a.material))for(let t=0;t<a.material.length;t++)this.refreshMaterial(a,a.material[t],e,t);else this.refreshMaterial(a,a.material,e)})):"mesh"==e.type?(this.findByAssetId(e.id).forEach((t=>{De(t.userData.src.materialAssignments,e.materialAssignments).forEach((e=>{this.applyMaterial(t,e)}))})),this.landscapeManagers.forEach((t=>{t.source.grass.layers.some((t=>t.meshes.some((t=>t.assetId===e.id))))&&t.queueRefreshScatter(this.renderingView?.camera.position??new S,!0)}))):"prefab"===e.type&&this.findByAssetId(e.id).forEach((e=>{const t=e.userData.src;this.remove(t),this.materializeAndInitActor(t)}))}))}async refreshMaterial(e,t,a,s){if(t?.userData?.assetId!==a.id)return;const r=await materialFromAsset(a,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!0);r.userData=t.userData,null!=s?Ee(e.material[s],r)||(e.material[s]=r):Ee(e.material,r)||(e.material=r)}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(),ve.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 Me(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 Me(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!==pe.dynamic&&"sky"!==e.type&&"global_fog"!==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=>{!W(e)&&e.isMesh&&a.push(e)}));const s=1==a.length&&0==a[0].children.length,r=a[0]instanceof l&&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 e=[],a=new $,s=new $;for(const t of this.dataProvider.getObjects())await Pe(t,(async(t,r,i)=>{const n="asset_mesh"==t.type&&this.canObjectBeInstanced(t)&&await this.canAssetBeInstanced(t),o="shape_mesh"===t.type&&"landscape"!==t.shape&&t.physics?.type!==pe.dynamic;if(n||o)if(r&&r.children?.length>0&&r.children.splice(r.children.findIndex((e=>e.id===t.id)),1),o){const e=t.shape+JSON.stringify(t.materialAssignments??[])+JSON.stringify(t.shapeParams??{})+t.castShadow+t.receiveShadow;s.push(e,{...t,parentTransform:i})}else{const e=t.assetId+JSON.stringify(t.materialAssignments??[]);a.push(e,{...t,parentTransform:i})}else null==r&&e.push({...t,parentTransform:i})}));for(const e of a.values()){if(0==e.length)continue;const t=await this.createFromAsset(e[0]);if(null==t)continue;const a=await this.createInstancedMesh(e,t),s=new U;s.add(a),s.userData.src=e[0],t instanceof U&&(s.collisionShapes=t.collisionShapes),s.castShadow=!1,s.receiveShadow=!1,this.scene.add(s)}for(const e of s.values()){if(0==e.length)continue;const a=await this.createFromShape(e[0]),s=ge(a,(e=>!W(e)&&null!=e.geometry)),i=s.geometry,n=new t.InstancedMesh(i,s.material.clone(),e.length);for(let i=0;i<e.length;i++){const o=(new t.Matrix4).compose((new S).fromArray(e[i].position),(new f).setFromEuler((new r).fromArray(e[i].rotation)),(new S).fromArray(e[i].scale)),c=(new ae).copy(e[i].parentTransform).multiply(o);n.setMatrixAt(i,c),n.castShadow=a.castShadow??!0,n.receiveShadow=s.receiveShadow??!0;const l=new U;l.add(n),l.userData.src=e[0],a instanceof H&&(l.collisionShapes=[a.collisionShape]),l.castShadow=!1,l.receiveShadow=!1,this.scene.add(l)}}await Promise.all(e.map((e=>this.materialize(e)))),await this.initActorsPostInit()}async createInstancedMesh(e,a){const s=ge(a,(e=>!W(e)&&null!=e.geometry)),i=await this.assetsService.getAsset(e[0].assetId);await this.applyMaterials(a,De(e[0].materialAssignments,i.materialAssignments)),s.updateMatrix();const n=s.geometry.clone().applyMatrix4(s.matrix),o=new t.InstancedMesh(n,s.material,e.length);s.material instanceof c&&(o.material.side=t.FrontSide);for(let a=0;a<e.length;a++){const s=(new t.Matrix4).compose((new S).fromArray(e[a].position),(new f).setFromEuler((new r).fromArray(e[a].rotation)),(new S).fromArray(e[a].scale)),i=(new ae).copy(e[a].parentTransform).multiply(s);o.setMatrixAt(a,i)}return o.castShadow=e[0].castShadow??i.castShadow??!0,o.receiveShadow=e[0].receiveShadow??i.receiveShadow??!0,o}remove(e){if(console.log("Remove scene object",e),"global_fog"==e.type)return void(this.scene.fog=this.originalFog);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 R(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)return materialFromAsset(t,this.renderingView,this.assetsService,this.assetManagerService,this.shaders)}),this._originalMaterials)}unapplyMaterials(e){e.traverse((async e=>{if(e instanceof l)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(B));R(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 ve.entries())t.userData.customShaderName&&ve.delete(e);this.landscapeManagers.forEach((t=>t.updateShaders(e))),R(this.scene,(e=>!0)).forEach((e=>{e.traverse((async e=>{if(e instanceof l)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);const t=this.sceneObjectMap.get(e.id);if(t){let r=!1;if(t.traverseAncestors((e=>{"_hology_transform_group"===e.name&&(r=!0)})),!r){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 l&&(e.material.wireframe=!0)})):t.traverse((e=>{e instanceof l&&(e.material.wireframe=!1)}))}if("asset_mesh"===e.type){const a=this.assets.get(e.assetId);De(e.materialAssignments,a.materialAssignments).forEach((e=>this.applyMaterial(t,e)))}else"shape_mesh"===e.type&&this.applyMaterials(t,e.materialAssignments);if(r||(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 s(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)this.applyHeightMaps(t,e.landscape.heightMaps),this.inEditor&&this.landscapeManagers.filter((t=>t.source.id===e.id)).forEach((e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,(e=>!0))));else if("global_fog"===e.type){const t=(this.scene.fog instanceof n?"density":"linear")!==e.fog.type;this.scene.fog=je(e.fog),t&&(a=this.scene).traverse((e=>{if(e instanceof l){const t=e.material;t instanceof P&&(a.fog instanceof i?(t.uniforms.fogFar.value=a.fog.far,t.uniforms.fogNear.value=a.fog.near):a.fog instanceof n&&(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"),r||(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 H&&(t.geometry=a.geometry,t.collisionShape=a.collisionShape)}("asset_mesh"===e.type||"shape_mesh"===e.type&&"landscape"!==e.shape)&&Se(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}async materializeAndInitActor(e,t=this.findParent(e)){console.log("materialize actor and init");const a=await this.materialize(e,t);return Pe(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:L(t,(t=>t.children?.some((t=>t.id===e.id))),(()=>!0))))[0];return null==t?this.scene:null!=t?R(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 s(this.scene.fog.color))}findMeshWithGeometry(e){let t;return e.traverse((e=>{e instanceof l&&e.geometry&&(t=e)})),t}applyVertexMaterials(e,t){if(null==e.vertexMaterials||0===e.vertexMaterials.length)return;const a=T(e.vertexMaterials,(e=>e.m));t.traverse((e=>{if(e instanceof l){const t=K(e,!1);if(null!=t){for(let e=0;e<t.array.length;e++)t.setX(e,0);t.needsUpdate=!0}}}));const s=new Set;for(const[e,r]of a.entries()){const a=null!=e?t.getObjectByName(e):this.findMeshWithGeometry(t);let i=!1;if(null==a)return void console.warn(`Failed to apply vertex materials on mesh with name "${e}"`);const n=K(a,!0);for(let e=0;e<n.array.length;e++)n.setX(e,0);for(const e of r)n.setX(e.i,e.w[0]),n.setY(e.i,e.w[1]),n.setZ(e.i,e.w[2]),i=!0;i&&s.add(e)}this.inEditor&&this.landscapeManagers.filter((t=>t.source.id===e.id)).forEach((e=>e.queueRefreshScatter(this.renderingView.camera.position,!0,(e=>s.has(e.name)))))}async materialize(e,t,s=!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=je(e.fog),this.fixFogColor(),r=new o;break;case"sky":this.sky=he(),this.updateSky(e),r=this.sky;break;case"actor":r=await this.createFromActor(e);break;case"group":r=new o;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),s||(r.userData.src=e),this.inEditor,this.inEditor){let e=null;r instanceof H&&(e=function(e){if(e instanceof J)return new l(new a(...e.offset.toArray()),Ie);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!==pe.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,s)))),r}}async updateSky(e){if(null==e?.sky?.materialId)return void(this.sky.material=me);const a=await this.assetsService.getAsset(e.sky.materialId),s=await materialFromAsset(a,this.renderingView,this.assetsService,this.assetManagerService,this.shaders,!1);s.side=t.BackSide,null!=this.sky?this.sky.material=s:console.warn("No sky has been created")}async createComponent(e,t,a,s){const r=new we[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??B[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 S).fromArray(e.position),(new r).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(fe,(new S).fromArray(e.position),(new r).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 l&&this._originalMaterials.set(e.id,e.material)}));else{let r=new p({name:"Default",color:new s("#aaaaaa"),visible:this.inEditor||!e.hidden,wireframe:!!t});const i=await this.createMeshByShape(e.shape,r,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||((e.materialAssignments??[]).filter((e=>null!=e.materialId)).forEach((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 o;const a=q(e.landscape.options);this.applyHeightMaps(a,e.landscape.heightMaps,!0);const s=new X(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 G(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((()=>Y(r)),50)}async createMeshByShape(e,t,a={}){if("landscape"!==e&&ce.includes(e)){const s=await prepareShapeParameters(a??{}),r=e+JSON.stringify(a);return this.geometryCache.has(r)||this.geometryCache.set(r,oe[e].geometry(s)),this.collisionShapeCache.has(r)||this.collisionShapeCache.set(r,oe[e].collision(s)),new H(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);De(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,Se(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 l&&"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 o;return t.prefab.objects.filter((e=>"global_fog"!==e.type)).forEach((e=>this.materialize(e,a,!0))),a}async createParticleSystem(e){const a=await this.assetsService.getAsset(e.assetId),s=new d;return await A.fromJSONAsync(a.particleSystem,t).then((e=>{const a=new b(s,t);e.addRenderer(a),this.renderingView.onLoop((t=>e.update()))})),s}async createLight(e){if("point"===e.light.type){const t=new u(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 y(.3,10,10),a=new p({color:new s(16771709)}),r=new l(e,a);t.add(r)}return t}return"directional"===e.light.type?(this.applyDirectionalLight(e.light.directional),new o):"ambient"===e.light.type?(this.applyDirectionalAmbientLight(null,e.light.ambient),new o):void 0}applyDirectionalAmbientLight(e,t){const a=this.scene.children.find((e=>e.name===le));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 Se(e,t,a){e.castShadow=t,e.receiveShadow=a,e.traverse((e=>{e.castShadow=t,e.receiveShadow=a}))}const ve=new Map,Ae=new h({color:16711935}),be=new Map;export async function materialFromAsset(e,a,r,i,n,o=!0){const c=JSON.stringify(e.material);if(o&&ve.has(c))return ve.get(c);const l={opacity:e.material.params.opacity,map:null,emissive:e.material.params.emissive??null,metalness:e.material.params.metalness??0,flatShading:e.material.params.flatShading??!1,color:new s(e.material.params.color),transparent:null!=e.material.params.opacity&&e.material.params.opacity<1},h={};if(null!=e.material.params.map){const t=e.material.params.map,a=await r.getAsset(t);null!=a&&(l.map=await i.getTexture(a))}let p;switch(e.material.type){case"phong":p=new m({...l,...h});break;case"water":p=ee(l,a);break;case"grassFoliage":p=Q({color:l.color,map:l.map},a);break;case"grass":p=Z({...l,colorTwo:new s(e.material.params.colorTwo),colorThree:new s(e.material.params.colorThree)},a);break;case"standard":case"lambert":case"shader":const t={standard:ie,lambert:ne}[e.material.type]??n.find((t=>t.name==e.material.shader))?.type;if(t){const s=new t,o=await Me(e.material?.shaderParams??{},t,r,i,null,a,n);Object.assign(s,o);try{p=s.build()}catch(t){console.log("Shader runtime error: "+t),be.has(e.material.shader)||be.set(e.material.shader,Ae.clone()),p=be.get(e.material.shader)}p.userData.customShaderName=e.material.shader}else console.warn("Missing shader implementation with name "+e.material.shader),p=Ae;break;default:throw new Error("Unsupported material type"+e.material.type)}return a?.csm.setupMaterial(p),o&&ve.set(c,p),p.side=e.material.side??p.side??t.FrontSide,p.transparent=(e.material.transparent??l.transparent??!1)||p.transparent,e.material.bloom&&(p.userData.hasBloom=!0),p.userData.assetId=e.id,p}async function Me(e,t,a,s,r,i,n,o){const c={};for(const[t,l]of Object.entries(e)){const e=await xe(l,a,s,r,i,n,o);null!=e&&(c[t]=e)}return c}export async function prepareShapeParameters(e){const t={};for(const[a,s]of Object.entries(e)){const e=await xe(s,null,null,null);null!=e&&(t[a]=e)}return t}async function xe(e,t,a,i,n,o,c){if(te.String,null==e||null==e.value||""==e.value)return null;const l=e.value;switch(e.type){case te.Number:case te.FloatNode:let h="string"==typeof l?parseFloat(l):l;return e.type===te.FloatNode?j(h):h;case te.Texture:return await a.getTexture(await t.getAsset(l));case te.Sampler2DNode:return V(await a.getTexture(await t.getAsset(l)));case te.Boolean:return l;case te.BooleanNode:return M(l);case te.Vector2:case te.Vec2Node:if("object"==typeof l){const t=l instanceof Array?(new w).fromArray(l):new w(l.x,l.y);return e.type===te.Vec2Node?C(t):t}return null;case te.Vector3:case te.Vec3Node:if("object"==typeof l){const t=l instanceof Array?(new S).fromArray(l):new S(l.x,l.y,l.z);return e.type===te.Vec3Node?k(t):t}return null;case te.Color:case te.RgbNode:const m=new s(l);return e.type===te.RgbNode?D(m):m;case te.String:return l;case te.BaseActor:const p=l;return null==i&&console.warn("Class parameters can not be prepared as actors are not passed in"),i?.get(p);case te.Euler:const d=l;return(new r).fromArray(d);case te.Object3D:return(await a.getMesh(await t.getAsset(l))).scene;case te.Material:return await materialFromAsset(await t.getAsset(l),n,t,a,o);case te.AudioBuffer:return await a.getAudio(await t.getAsset(l));case te.VisualEffect:const u=await t.getAsset(l);if(null==c){console.error("Can not create instance of visual effect because missing actor provider");break}if("vfx"in u)return new ye(c,u);console.error("Using a non-vfx asset for visual effect parameter")}return null}function je(e){return"linear"===e.type?new i(new s(e.color),e.near??100,e.far??1e3):"density"===e.type?new n(e.color,e.density):void console.warn("Invalid fog type",e)}const Ie=new p({color:4229780});async function Pe(e,a,s,i){null==i&&(i=(new ae).identity()),await a(e,s,i);const n=i.clone().multiply(function(e,t){if(null==e.position||null==e.rotation||null==e.scale)return t.identity();return t.compose((new S).fromArray(e.position),(new f).setFromEuler((new r).fromArray(e.rotation)),(new S).fromArray(e.scale))}(e,new t.Matrix4));return Promise.all((e.children??[]).map((t=>Pe(t,a,e,n))))}export function toSerializedParamType(e){const t=e.constructor.prototype;return t instanceof Number||e===Number?te.Number:t instanceof I||"function"==typeof e.prototype.isFloat?te.FloatNode:t instanceof g||e===g||e.isTexture?te.Texture:t instanceof re||e===E?te.Sampler2DNode:t instanceof Boolean||e===Boolean?te.Boolean:t instanceof x?te.BooleanNode:t instanceof s||e==s?te.Color:t instanceof N||"function"==typeof e.prototype.isRgb?te.RgbNode:t instanceof w||e==w?te.Vector2:t instanceof F||"function"==typeof e.prototype.isVec2?te.Vec2Node:t instanceof S||e==S?te.Vector3:t instanceof z||"function"==typeof e.prototype.isVec3?te.Vec3Node:t instanceof String||e===String?te.String:t instanceof se||e==se||e.prototype instanceof se||e.prototype==se?te.BaseActor:t instanceof r||e==r?te.Euler:t instanceof d||e==d?te.Object3D:t instanceof c||e==c?te.Material:t instanceof AudioBuffer||e==AudioBuffer?te.AudioBuffer:t instanceof ye||e==ye?te.VisualEffect: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:toSerializedParamType(e.type),value:t[e.name]?.value??a[e.name]??customParameterDefaultValueByType.get(toSerializedParamType(e.type))}])))}export function prepareCustomParamsFromType(e,t,a=null){const s=_(e);if(0===s.length)return{};let r;null!=a?de(a,(()=>{r=a.get(e)})):r=new e;const i={};for(const e of s){const t=r[e.name];if(null!=t){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 w:return t instanceof w?t.toArray():void a();case S:return t instanceof S?t.toArray():void a();case v:return t instanceof v?t.toArray():void a();case s:return t instanceof s?"#"+t.getHexString():"string"==typeof t?t:"number"==typeof t?"#"+new s(t).getHexString():void a();case String:return t;case r:return t instanceof r?t.toArray():void a()}}function De(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=>Ne(e.materialId))),(t??[]).filter((e=>Ne(e.materialId))),(e=>e.color+e.name))}function Ne(e){return"null"!=e&&null!=e}export const customParameterDefaultValueByType=new Map([[te.RgbNode,"#000000"],[te.Color,"#000000"],[te.Vector4,[0,0,0,0]],[te.Vec4Node,[0,0,0,0]],[te.Vector3,[0,0,0]],[te.Vec3Node,[0,0,0]],[te.Vector2,[0,0]],[te.Vec2Node,[0,0]],[te.Euler,[0,0,0,"XYZ"]]]);export function applyMaterial(e,a,r,i){const n=[];return e.traverse((async e=>{if(e instanceof l||e.isMesh||e instanceof t.SkinnedMesh||e.isSkinnedMesh)for(const t of ue(e.material))t.hasOwnProperty("color")&&n.push(e)})),Promise.all(n.map((async e=>{if(e.material instanceof Array)for(let t=0;t<e.material.length;t++){const n=e.material[t];if(null==n.color||!(n.color instanceof s))continue;const o="#"+n.color.getHexString(),c=n.name;if(o===a.color&&(n.name===a.name||null==a.name)||e.userData["originalColor_"+t]===a.color&&e.userData["originalMaterialName_"+t]===a.name){const s=await r(a.materialId),n=e.material[t];null!=s&&(e.material[t]=s,e.userData["originalColor_"+t]=e.userData["originalColor_"+t]??o,e.userData["originalMaterialName_"+t]=e.userData["originalMaterialName_"+t]??c,null!=i&&i.set(e.id+"#"+t,n))}}else if("color"in e.material){const t="#"+e.material.color.getHexString(),s=e.material.name;if(t===a.color&&(e.material.name===a.name||null==a.name)||e.userData.originalColor===a.color&&e.userData.originalName===a.name){const n=await r(a.materialId),o=e.material;null!=n&&(e.material=n,e.userData.originalColor=e.userData.originalColor??t,e.userData.originalMaterialName=e.userData.originalMaterialName??s,null!=i&&(i.has(e.id)||i.set(e.id,o)))}}})))}function Ee(e,a){if(e instanceof t.ShaderMaterial&&a instanceof t.ShaderMaterial){return e.fragmentShader+e.vertexShader==a.fragmentShader+a.vertexShader&&function(e,a){if(e instanceof t.ShaderMaterial&&a instanceof t.ShaderMaterial){for(const t in e.uniforms){if(null==a.uniforms[t])return!1;if(a.uniforms[t].value!==e.uniforms[t].value)return console.log("Different values",a.uniforms[t].value,e.uniforms[t].value),!1}return!0}return!1}(e,a)}return!1}
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -1,4 +1,4 @@
1
- import{attributes as m,float as o,lambertMaterial as l,NodeShaderMaterial as e,rgb as r,rgba as i,select as t,sin as a,smoothstep as p,transformed as n,translateAxis as u,uniformFloat as s,uniformSampler2d as f,varyingFloat as y,varyingVec2 as c}from"../../shader-nodes/index.js";import{Vector3 as v}from"three";import{CSMUtil as d}from"../../csm.js";export function createGrassFoliageMaterial(g,w){const x=n.mvPosition.z().multiply(o(-1)),h=y(p(o(100),o(60),x)),j=m.uv.y(),z=r(11977268),B=o(.2),C=l(r(g.color)).rgb().multiplyScalar(o(.9)).add(z.multiplyScalar(y(j).multiply(B))),S=c(m.uv),b=f("map").sample(S,o(0)),F=i(C,b.x().multiply(h)),G=s("time"),L=o(.5).multiply(t(j.gt(o(0)),j.multiply(j),o(0))).multiply(a(G.multiply(o(.001)))),M=u(new v(1,0,0).normalize(),L),P=new e({color:F,transform:M,uniforms:{map:{value:g.map},time:{value:0}},transparent:!0});return P.onBeforeCompile=m=>{d.onBeforeCompile(P,m)},P.uniforms.map.value=g.map,w.onLoop((()=>{P.uniforms.time.value=performance.now()})),P}
1
+ import{attributes as m,float as o,lambertMaterial as l,NodeShaderMaterial as e,rgb as r,rgba as i,select as t,sin as a,smoothstep as p,transformed as n,translateAxis as u,uniformFloat as s,uniformSampler2d as f,varyingFloat as y,varyingVec2 as c}from"../../shader-nodes/index.js";import{Vector3 as v}from"three";import{CSMUtil as d}from"../../csm.js";export function createGrassFoliageMaterial(g,w){const x=n.mvPosition.z.multiply(o(-1)),h=y(p(o(100),o(60),x)),j=m.uv.y,z=r(11977268),B=o(.2),C=l(r(g.color)).rgb.multiplyScalar(o(.9)).add(z.multiplyScalar(y(j).multiply(B))),S=c(m.uv),b=f("map").sample(S,o(0)),F=i(C,b.x.multiply(h)),G=s("time"),L=o(.5).multiply(t(j.gt(o(0)),j.multiply(j),o(0))).multiply(a(G.multiply(o(.001)))),M=u(new v(1,0,0).normalize(),L),P=new e({color:F,transform:M,uniforms:{map:{value:g.map},time:{value:0}},transparent:!0});return P.onBeforeCompile=m=>{d.onBeforeCompile(P,m)},P.uniforms.map.value=g.map,w.onLoop((()=>{P.uniforms.time.value=performance.now()})),P}
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
package/dist/scene/sky.js CHANGED
@@ -1,4 +1,4 @@
1
- import*as e from"three";import{AmbientLight as a,FogExp2 as t}from"three";import{attributes as r,NodeShaderMaterial as o,uniforms as i,vec4 as n,varyingVec3 as s,float as h,normalize as d,rgb as c,mix as m,max as w,pow as p}from"three-shader-graph";export function basicSceneSetup(r){!function(t){new a(16777215,.5);var r=new e.HemisphereLight(16777215,273,.5*Math.PI);r.name=ambientLightName,r.position.set(0,100,0),t.add(r);new e.HemisphereLightHelper(r,10);var o=new e.DirectionalLight(16777215,.7);o.position.set(-30,50,30),o.castShadow=!0,o.shadow.mapSize.width=2048,o.shadow.mapSize.height=2048;var i=250;o.shadow.normalBias=.3,o.shadow.camera.left=-i,o.shadow.camera.right=i,o.shadow.camera.top=i,o.shadow.camera.bottom=-i,o.shadow.camera.far=500,o.shadow.bias=-5e-4;new e.DirectionalLightHelper(o,10);var n=new e.PointLight(16777215,1,50);n.castShadow=!0,n.position.set(0,40,0),n.shadow.camera.near=1,n.shadow.camera.far=60,n.shadow.bias=-.005}(r),function(e){e.fog=new t(l,f)}(r)}export const ambientLightName="default_ambient";const l=157554,f=.005;export const defaultSkyMaterial=function(){const a=h(5),t=h(.6),l=new e.Color(16777215),f=new e.Color(13431551),g=s(i.modelMatrix.multiplyVec(n(r.position,1)).xyz()),u=d(g.addScalar(a)).y(),S=w(p(w(u,h(0)),h(t)),h(0)),b=n(m(c(f),c(l),S),h(1)),y=new o({color:b.rgba()});return y.side=e.BackSide,y.depthTest=!1,y}();export function createSky(){var a=new e.SphereGeometry(300,10,15),t=new e.Mesh(a,defaultSkyMaterial);return t.renderOrder=-999,t.raycast=()=>{},t}
1
+ import*as e from"three";import{AmbientLight as a,FogExp2 as t}from"three";import{attributes as r,NodeShaderMaterial as o,uniforms as i,vec4 as n,varyingVec3 as s,float as h,normalize as d,rgb as c,mix as m,max as w,pow as p}from"three-shader-graph";export function basicSceneSetup(r){!function(t){new a(16777215,.5);var r=new e.HemisphereLight(16777215,273,.5*Math.PI);r.name=ambientLightName,r.position.set(0,100,0),t.add(r);new e.HemisphereLightHelper(r,10);var o=new e.DirectionalLight(16777215,.7);o.position.set(-30,50,30),o.castShadow=!0,o.shadow.mapSize.width=2048,o.shadow.mapSize.height=2048;var i=250;o.shadow.normalBias=.3,o.shadow.camera.left=-i,o.shadow.camera.right=i,o.shadow.camera.top=i,o.shadow.camera.bottom=-i,o.shadow.camera.far=500,o.shadow.bias=-5e-4;new e.DirectionalLightHelper(o,10);var n=new e.PointLight(16777215,1,50);n.castShadow=!0,n.position.set(0,40,0),n.shadow.camera.near=1,n.shadow.camera.far=60,n.shadow.bias=-.005}(r),function(e){e.fog=new t(l,f)}(r)}export const ambientLightName="default_ambient";const l=157554,f=.005;export const defaultSkyMaterial=function(){const a=h(5),t=h(.6),l=new e.Color(16777215),f=new e.Color(13431551),g=s(i.modelMatrix.multiplyVec(n(r.position,1)).xyz),u=d(g.addScalar(a)).y,S=w(p(w(u,h(0)),h(t)),h(0)),b=n(m(c(f),c(l),S),h(1)),y=new o({color:b.rgba});return y.side=e.BackSide,y.depthTest=!1,y}();export function createSky(){var a=new e.SphereGeometry(300,10,15),t=new e.Mesh(a,defaultSkyMaterial);return t.renderOrder=-999,t.raycast=()=>{},t}
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -1,5 +1,5 @@
1
- import { FloatNode } from "three-shader-graph";
2
- export declare function fresnelEffect(power?: number | FloatNode): FloatNode;
1
+ import { FloatNode, Vec3Node } from "three-shader-graph";
2
+ export declare function fresnelEffect(power?: number | FloatNode, normal?: Vec3Node): FloatNode;
3
3
  /**
4
4
  * Gives a factor for how shallow the depth is where 1 is the most shallow.
5
5
  * This can be useful to for example create a highlight where an object intersects
@@ -1,4 +1,4 @@
1
- import{Vec3ExpressionNode as t,attributes as r,dot as e,float as o,normalize as n,pow as c,saturate as i,uniforms as s,varyingAttributes as a,varyingVec3 as f,vec4 as p}from"three-shader-graph";import{fragmentLinearEyeDepth as u,linearEyeDepth as m}from"./depth.js";const d=s.modelMatrix.multiplyVec(p(r.position,1));export function fresnelEffect(s=1){const a=r.normal,f=new t("cameraPosition"),p=n(f.subtract(d.xyz())),u=o(1);return c(i(u.subtract(e(a,p))),o(s))}const h=o(1).subtract(m.subtract(u).divide(m));export function edgeDepthEffect(t=1){return c(h,o(t))}
1
+ import{Vec3ExpressionNode as t,attributes as e,dot as r,float as o,normalize as c,pow as i,saturate as n,uniforms as s,varyingAttributes as a,varyingVec3 as m,vec4 as p}from"three-shader-graph";import{fragmentLinearEyeDepth as u,linearEyeDepth as f}from"./depth.js";const l=s.modelMatrix.multiplyVec(p(e.position,1)),d=s.modelMatrix.multiplyVec(p(e.normal,0)).xyz;export function fresnelEffect(e=1,s=d){const a=new t("cameraPosition"),m=c(a.subtract(l.xyz)),p=o(1);return i(n(p.subtract(r(s,m))),o(e))}const x=o(1).subtract(f.subtract(u).divide(f));export function edgeDepthEffect(t=1){return i(x,o(t))}
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -1,4 +1,4 @@
1
- import{attributes as r,float as t,uniforms as o,vec4 as e,varyingVec2 as a}from"three-shader-graph";const i=o.modelMatrix.multiplyVec(e(r.position,1));export function getLandscapeCoords(r){return a(i.xz().multiplyScalar(t(r)))}
1
+ import{attributes as r,float as t,uniforms as o,vec4 as e,varyingVec2 as a}from"three-shader-graph";const i=o.modelMatrix.multiplyVec(e(r.position,1));export function getLandscapeCoords(r){return a(i.xz.multiplyScalar(t(r)))}
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -1,4 +1,4 @@
1
- import{float as e,uniforms as o,vec4 as r,attributes as t,varyingVec2 as a,AttributeVec3Node as i,varyingVec3 as l,SimplexNoiseNode as d,select as n,mix as s,smoothstep as y}from"three-shader-graph";export var LayerMixMode;!function(e){e[e.hard=0]="hard",e[e.soft=1]="soft"}(LayerMixMode||(LayerMixMode={}));const c={enableNoise:!0,noiseScale:e(.1),noiseAmount:e(.5),decay:.3,mode:LayerMixMode.soft},u=a(o.modelMatrix.multiplyVec(r(t.position,1)).xz()),m=l(new i("material")),p=[e(0),m.x(),m.y(),m.z()];export function mixColorsByLayer(o){const r={...c,...o},t=e(r.noiseAmount).multiply(e(.1)),a=e(r.noiseScale),i=new d(u.multiplyScalar(a)).multiply(e(2)).subtract(e(1)).multiply(t),l=e(.5),m=r.enableNoise?l.add(i.multiply(e(.1))):l;if(r.mode==LayerMixMode.hard)return r.layerColors.reduce(((e,o,r)=>n(p[r].gt(m),o,e)));{const o=e(r.decay),t=e(.5),a=o.divide(e(2)),l=t.subtract(a),d=t.add(a);return r.layerColors.slice(0,p.length).reduce(((e,o,r)=>s(e,o,y(l,d,p[r].add(i)))))}}
1
+ import{float as e,uniforms as o,vec4 as r,attributes as t,varyingVec2 as a,AttributeVec3Node as i,varyingVec3 as l,SimplexNoiseNode as d,select as n,mix as s,smoothstep as y}from"three-shader-graph";export var LayerMixMode;!function(e){e[e.hard=0]="hard",e[e.soft=1]="soft"}(LayerMixMode||(LayerMixMode={}));const c={enableNoise:!0,noiseScale:e(.1),noiseAmount:e(.5),decay:.3,mode:LayerMixMode.soft},u=a(o.modelMatrix.multiplyVec(r(t.position,1)).xz),m=l(new i("material")),p=[e(0),m.x,m.y,m.z];export function mixColorsByLayer(o){const r={...c,...o},t=e(r.noiseAmount).multiply(e(.1)),a=e(r.noiseScale),i=new d(u.multiplyScalar(a)).multiply(e(2)).subtract(e(1)).multiply(t),l=e(.5),m=r.enableNoise?l.add(i.multiply(e(.1))):l;if(r.mode==LayerMixMode.hard)return r.layerColors.reduce(((e,o,r)=>n(p[r].gt(m),o,e)));{const o=e(r.decay),t=e(.5),a=o.divide(e(2)),l=t.subtract(a),d=t.add(a);return r.layerColors.slice(0,p.length).reduce(((e,o,r)=>s(e,o,y(l,d,p[r].add(i)))))}}
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -1,4 +1,4 @@
1
- import{float as t,length as a,min as r,max as e,saturate as c,dFdx as d,dFdy as l,abs as u,ComponentsVec2Node as n,vec2 as i}from"three-shader-graph";export function rectangleFloat(t,a,e){const o=u(t.multiplyScalar(2).subtractScalar(1)).subtract(new n(a,e)),s=i(1,1).subtract(o.divide(u(d(p=o)).add(u(l(p)))));var p;return c(r(s.x(),s.y()))}export function roundedRectangleFloat(o,s,p,b){const m=e(r(r(u(b.multiply(2)),u(s)),u(p)),t(1e-5)),v=u(o.multiplyScalar(2).subtractScalar(1)).subtract(new n(s,p)).addScalar(m),S=a(e(i(0,0),v)).divide(m);return c(t(1).subtract(S).divide(u(d(y=S)).add(u(l(y)))));var y}
1
+ import{float as t,length as a,min as r,max as e,saturate as c,dFdx as d,dFdy as l,abs as u,ComponentsVec2Node as n,vec2 as i}from"three-shader-graph";export function rectangleFloat(t,a,e){const o=u(t.multiplyScalar(2).subtractScalar(1)).subtract(new n(a,e)),s=i(1,1).subtract(o.divide(u(d(p=o)).add(u(l(p)))));var p;return c(r(s.x,s.y))}export function roundedRectangleFloat(o,s,p,b){const m=e(r(r(u(b.multiply(2)),u(s)),u(p)),t(1e-5)),v=u(o.multiplyScalar(2).subtractScalar(1)).subtract(new n(s,p)).addScalar(m),S=a(e(i(0,0),v)).divide(m);return c(t(1).subtract(S).divide(u(d(y=S)).add(u(l(y)))));var y}
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -1,4 +1,4 @@
1
- import{select as t,length as a,ComponentsVec2Node as r,ConstantMat2Node as l,fract as d,sin as n,cos as e,vec2 as o,vec3 as u,floor as c}from"three-shader-graph";export function voronoi(i,p,m){const y=i.multiplyScalar(m),s=c(y),x=d(y),f=[-1,0,1],h=f.flatMap((t=>f.map((a=>[t,a])))).reduce(((c,[i,m])=>{const y=o(i,m),f=function(t,a){const o=new l(15.27,47.63,99.41,89.98);return t=d(n(t.multiplyMat(o)).multiplyScalar(46839.32)),new r(n(t.y().add(a)).multiply(.5).add(.5),e(t.x().add(a)).multiply(.5).add(.5))}(y.add(s),p),h=a(y.add(f).subtract(x));return t(h.lt(c.x()),u(h,f.x(),f.y()),c)}),u(8,0,0));return{noise:h.x(),cells:h.y()}}
1
+ import{select as t,length as a,ComponentsVec2Node as r,ConstantMat2Node as l,fract as d,sin as n,cos as e,vec2 as o,vec3 as u,floor as c}from"three-shader-graph";export function voronoi(i,p,m){const y=i.multiplyScalar(m),s=c(y),x=d(y),f=[-1,0,1],h=f.flatMap((t=>f.map((a=>[t,a])))).reduce(((c,[i,m])=>{const y=o(i,m),f=function(t,a){const o=new l(15.27,47.63,99.41,89.98);return t=d(n(t.multiplyMat(o)).multiplyScalar(46839.32)),new r(n(t.y.add(a)).multiply(.5).add(.5),e(t.x.add(a)).multiply(.5).add(.5))}(y.add(s),p),h=a(y.add(f).subtract(x));return t(h.lt(c.x),u(h,f.x,f.y),c)}),u(8,0,0));return{noise:h.x,cells:h.y}}
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hology/core",
3
- "version": "0.0.54",
3
+ "version": "0.0.56",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -94,7 +94,7 @@
94
94
  "three-csm": "^4.2.1",
95
95
  "three-mesh-bvh": "^0.7.5",
96
96
  "three-nebula": "^10.0.3",
97
- "three-shader-graph": "^0.1.29",
97
+ "three-shader-graph": "^0.2.1",
98
98
  "three-stdlib": "2.30.3",
99
99
  "ts-key-enum": "^2.0.12",
100
100
  "typedi": "^0.10.0"