@hology/core 0.0.50 → 0.0.52

Sign up to get free protection for your applications and to get access to all the features.
package/dist/rendering.js CHANGED
@@ -1,4 +1,4 @@
1
- var e;import{__decorate as t,__metadata as i}from"tslib";import*as s from"three";import{Mesh as r,Matrix4 as n,ShaderMaterial as a,Color as o,PerspectiveCamera as h,ShaderChunk as l}from"three";import{EffectComposer as d,UnrealBloomPass as c,VRButton as m}from"three-stdlib";import{RenderPass as p}from"three-stdlib";import{ShaderPass as u}from"three-stdlib";import{FXAAShader as g}from"three-stdlib";import{CSMShader as f,CSMUtil as v}from"./csm.js";import{GammaCorrectionShader as w}from"three-stdlib";import{Reflector as x}from"three-stdlib";import{depthUniformName as b,resolutionUniformName as C,supportsDepthTextureExtension as P,nearUniformName as S,farUniformName as R}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as M}from"./shader-nodes/time.js";import{OutlinePass as y}from"./utils/three/outline-pass.js";import T from"./utils/three/stats.js";import{findFirstVisibleObject as W}from"./utils/three/traverse.js";import{DepthPass as L}from"./utils/three/depth-pass.js";import{Service as E}from"typedi";import{CSM as H}from"three/examples/jsm/csm/CSM.js";import{GPUStatsPanel as B}from"three/examples/jsm/utils/GPUStatsPanel.js";(new s.Layers).set(9);const D=new s.MeshBasicMaterial({color:"black"}),F=new s.MeshDepthMaterial;F.depthPacking=s.RGBADepthPacking,F.blending=s.NoBlending,l.lights_pars_begin=f.lights_pars_begin(5);const j=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let z=e=class{setPaused(e){this.paused=e}resizeRender(){this.previousClientWith===this.container.clientWidth&&this.previousClientHeight===this.container.clientHeight||(this.camera instanceof h&&(this.camera.aspect=this.container.clientWidth/this.container.clientHeight,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(this.container.clientWidth,this.container.clientHeight),this.composer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.previousClientWith=this.container.clientWidth,this.previousClientHeight=this.container.clientHeight)}constructor(t,i={}){this.container=t,this.options=i,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.resolutionScale=j?.5:1,this.maxPixelRatio=j?1:window.devicePixelRatio,this.onResize=()=>{this.resizeRender(),this.paused||this.render()},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!1,this.onLoopCallbacks=[],this.stats=T(),this._showStats=!1,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new o,this.hadBloom=!1,this.bloomStoredMaterials={},null!=i.maxPixelRatio&&(this.maxPixelRatio=i.maxPixelRatio),window.renderer=this.renderer=new s.WebGLRenderer({antialias:!0,powerPreference:"high-performance"}),this.scene=new s.Scene,this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(m.createButton(this.renderer)),this.composer=new d(this.renderer);var r=t.clientWidth/t.clientHeight;const n=new s.PerspectiveCamera(45,r,.5,800);n.layers.enable(19),this.setCamera(n),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=s.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=!1,this.renderer.outputColorSpace=s.SRGBColorSpace,this.renderer.toneMapping=s.NoToneMapping,this.renderer.toneMappingExposure=1,this.renderer.gammaFactor=1.4,v.renderingView=this,v.patchThreeAdd(),this.isDepthTextureExtensionSupported=P(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.depthRenderTarget=e.createDepthRenderTarget(this.renderer,this.container);const a=new p(this.scene,this.camera);this.composer.addPass(a);const h=new c(new s.Vector2(t.clientWidth,t.clientHeight),1.5,.4,.85);h.threshold=0,h.strength=.9,h.radius=1,this.renderer.info.autoReset=!1;const l=new d(this.renderer);l.renderToScreen=!1,l.addPass(a),l.addPass(h),this.bloomComposer=l;const f=new u(new s.ShaderMaterial({uniforms:{baseTexture:{value:null},bloomTexture:{value:l.renderTarget2.texture}},vertexShader:"\n varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n }",fragmentShader:"\n uniform sampler2D baseTexture;\n uniform sampler2D bloomTexture;\n varying vec2 vUv;\n void main() {\n gl_FragColor = ( texture2D( baseTexture, vUv ) + vec4( 1.0 ) * texture2D( bloomTexture, vUv ) );\n }",defines:{}}),"baseTexture");if(f.needsSwap=!0,this.composer.addPass(f),this.outlinePass=new y(new s.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),!0===i.enableOutlines){this.outlinePass.edgeThickness=0,this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.composer.addPass(this.outlinePass);const e=new u(g);e.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(e)}var x=new u(w);x.clear=!1,this.composer.addPass(x)}setCamera(e){this.camera=e,this.composer.passes.forEach((t=>{t instanceof p?t.camera=e:t instanceof y?t.renderCamera=e:t instanceof L&&(t.camera=e)})),null==this.csm?this.csm=new H({maxFar:250,lightFar:250,lightMargin:20,cascades:4,shadowMapSize:2048,lightDirection:new s.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene,mode:"logarithmic"}):(this.csm.camera=this.camera,this.camera instanceof h&&(this.csm.maxFar=this.camera.far)),this.csm.updateFrustums()}setSelectedObjects(e){const t=new Map;for(const i of e)t.set(i.uuid,i);for(const i of e)i.traverse((e=>{e.uuid!==i.uuid&&t.has(e.uuid)&&t.delete(e.uuid)}));this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t){var i=!!e.extensions.get("WEBGL_depth_texture");const r=new s.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio());return r.texture.minFilter=s.NearestFilter,r.texture.magFilter=s.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,!0===i&&(r.depthTexture=new s.DepthTexture(128,128),r.depthTexture.type=s.UnsignedShortType,r.depthTexture.minFilter=s.NearestFilter,r.depthTexture.magFilter=s.NearestFilter),r}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(){this.running=!1,window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],this.renderer.dispose(),this.depthRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren()}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.container.contains(this.stats.dom)?this.container.appendChild(this.stats.dom):!this._showStats&&this.container.contains(this.stats.dom)&&this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}loop(e,t=!1){const i=this.stats,a=i.addPanel(new T.Panel("Calls","#83f","#002"));let o;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(o=new B(this.renderer.getContext()),i.addPanel(o)),i.showPanel(0),this.showStats=t;let h=10;const l=()=>{const e=this.renderer.info.render.calls;e>h&&(h=e,setTimeout((()=>h=10),5e3)),a.update(e,h)};performance.now();s.Ray.prototype.intersectTriangle;let d=0;const c=new n,m=new n,p=t=>{const s=this.renderer.getContext();if(this.paused&&this.running&&s.drawingBufferHeight>1)return void setTimeout((()=>p(t)),500);this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,i.begin();let n=(t*=.001)-d;if(d=t,c.copy(this.camera.matrixWorld),n>1){let t=n;for(;t>.05;)e(O),t-=O;e(t)}else e(n);this.onLoopCallbacks.forEach((e=>e(n))),this.camera?.updateMatrixWorld(),m.copy(this.camera.matrixWorld),m.equals(c)||(this.renderer.shadowMap.needsUpdate=!0),this.resizeRender();const a=[],h=[];if(this.scene.traverse((e=>{e instanceof r&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[b])?(e.visible=!1,a.push(e),this.initDepthUniform(e.material),e.renderOrder=100):e instanceof x&&(e.visible=!1,h.push(e)),e instanceof r&&e.material?.uniforms&&null!=e.material?.uniforms[M]&&(e.material.uniforms[M].value=t)})),a.length>0){if(this.scene.overrideMaterial=F,this.renderer.setRenderTarget(this.depthRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(),this.renderer.render(this.scene,this.camera)}catch(e){console.warn(e)}this.renderer.setRenderTarget(null),this.scene.overrideMaterial=null}a.forEach((e=>e.visible=!0)),h.forEach((e=>e.visible=!0));try{!this.paused&&this.running&&(o?.startQuery(),this.render(n),o?.endQuery(),this.showStats&&l(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}i.end(),this.csm?.update(),this.running&&!0!==this.options.enableXR&&(this.fpsCap?setTimeout((()=>{requestAnimationFrame(p)}),1e3/this.fpsCap):requestAnimationFrame(p))};!0===this.options.enableXR?this.renderer.setAnimationLoop(p):requestAnimationFrame(p)}renderOverlay(){const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.container.clientWidth/2,i=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let s=0;s<e.length;s++)this.renderer.clearDepth(),this.renderer.setViewport(t-i/2+this.insetWidth*s+this.insetMargin*s,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[s])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){const t=this.hasBloom();if(t||this.hadBloom){const e=this.scene.fog;this.scene.fog=null;const t=this.renderer.getClearColor(this.prevClearColor);this.renderer.setClearColor(0),this.scene.traverseVisible((e=>this.darkenNonBloomed(e))),this.bloomComposer.render(),this.scene.traverse((e=>this.restoreMaterial(e))),this.renderer.setClearColor(t),this.scene.fog=e}this.hadBloom=t,this.composer.render(e)}hasBloom(){return null!=W(this.scene,(e=>e instanceof r&&!0===e.material?.userData?.hasBloom))}darkenNonBloomed(e){e.isMesh&&e.visible&&!0!==e.material.userData.hasBloom&&(this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=D:e.visible=!1)}restoreMaterial(e){this.bloomStoredMaterials[e.uuid]&&(e.material=this.bloomStoredMaterials[e.uuid],delete this.bloomStoredMaterials[e.uuid],e.visible=!0)}initDepthUniform(e){e instanceof a&&(e.uniforms[b].value=this.isDepthTextureExtensionSupported?this.depthRenderTarget.depthTexture:this.depthRenderTarget.texture,null!=e.uniforms[C]&&e.uniforms[C].value.set(this.container.clientWidth*this.renderer.getPixelRatio(),this.container.clientHeight*this.renderer.getPixelRatio()),this.camera instanceof h&&(e.uniforms[S].value=this.camera.near,e.uniforms[R].value=this.camera.far))}};z=e=t([E(),i("design:paramtypes",[HTMLElement,Object])],z);export{z as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const O=.05;
1
+ var e;import{__decorate as t,__metadata as i}from"tslib";import*as s from"three";import{Mesh as r,Matrix4 as n,ShaderMaterial as a,Color as o,PerspectiveCamera as h,ShaderChunk as l}from"three";import{EffectComposer as d,UnrealBloomPass as c,VRButton as m}from"three-stdlib";import{RenderPass as p}from"three-stdlib";import{ShaderPass as u}from"three-stdlib";import{FXAAShader as g}from"three-stdlib";import{CSMShader as f,CSMUtil as v}from"./csm.js";import{GammaCorrectionShader as w}from"three-stdlib";import{Reflector as x}from"three-stdlib";import{depthUniformName as b,resolutionUniformName as C,supportsDepthTextureExtension as P,nearUniformName as S,farUniformName as R}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as M}from"./shader-nodes/time.js";import{OutlinePass as y}from"./utils/three/outline-pass.js";import T from"./utils/three/stats.js";import{findFirstVisibleObject as W}from"./utils/three/traverse.js";import{DepthPass as L}from"./utils/three/depth-pass.js";import{Service as E}from"typedi";import{CSM as H}from"three/examples/jsm/csm/CSM.js";import{GPUStatsPanel as B}from"three/examples/jsm/utils/GPUStatsPanel.js";(new s.Layers).set(9);const D=new s.MeshBasicMaterial({color:"black"}),F=new s.MeshDepthMaterial;F.depthPacking=s.RGBADepthPacking,F.blending=s.NoBlending,l.lights_pars_begin=f.lights_pars_begin(5);const j=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let z=e=class{setPaused(e){this.paused=e}resizeRender(){this.previousClientWith===this.container.clientWidth&&this.previousClientHeight===this.container.clientHeight||(this.previousClientWith=this.container.clientWidth,this.previousClientHeight=this.container.clientHeight,this.camera instanceof h&&(this.camera.aspect=this.container.clientWidth/this.container.clientHeight,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(this.container.clientWidth,this.container.clientHeight),this.composer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale))}constructor(t,i={}){this.container=t,this.options=i,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.resolutionScale=j?.5:1,this.maxPixelRatio=j?1:window.devicePixelRatio,this.onResize=()=>{this.resizeRender(),this.paused||this.render()},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!1,this.onLoopCallbacks=[],this.stats=T(),this._showStats=!1,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new o,this.hadBloom=!1,this.bloomStoredMaterials={},null!=i.maxPixelRatio&&(this.maxPixelRatio=i.maxPixelRatio),window.renderer=this.renderer=new s.WebGLRenderer({antialias:!0,powerPreference:"high-performance"}),this.scene=new s.Scene,this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(m.createButton(this.renderer)),this.composer=new d(this.renderer);var r=t.clientWidth/t.clientHeight;const n=new s.PerspectiveCamera(45,r,.5,800);n.layers.enable(19),this.setCamera(n),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=s.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=!1,this.renderer.outputColorSpace=s.SRGBColorSpace,this.renderer.toneMapping=s.NoToneMapping,this.renderer.toneMappingExposure=1,this.renderer.gammaFactor=1.4,v.renderingView=this,v.patchThreeAdd(),this.isDepthTextureExtensionSupported=P(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.depthRenderTarget=e.createDepthRenderTarget(this.renderer,this.container);const a=new p(this.scene,this.camera);this.composer.addPass(a);const h=new c(new s.Vector2(t.clientWidth,t.clientHeight),1.5,.4,.85);h.threshold=0,h.strength=.9,h.radius=1,this.renderer.info.autoReset=!1;const l=new d(this.renderer);l.renderToScreen=!1,l.addPass(a),l.addPass(h),this.bloomComposer=l;const f=new u(new s.ShaderMaterial({uniforms:{baseTexture:{value:null},bloomTexture:{value:l.renderTarget2.texture}},vertexShader:"\n varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n }",fragmentShader:"\n uniform sampler2D baseTexture;\n uniform sampler2D bloomTexture;\n varying vec2 vUv;\n void main() {\n gl_FragColor = ( texture2D( baseTexture, vUv ) + vec4( 1.0 ) * texture2D( bloomTexture, vUv ) );\n }",defines:{}}),"baseTexture");if(f.needsSwap=!0,this.composer.addPass(f),this.outlinePass=new y(new s.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),!0===i.enableOutlines){this.outlinePass.edgeThickness=0,this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.composer.addPass(this.outlinePass);const e=new u(g);e.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(e)}var x=new u(w);x.clear=!1,this.composer.addPass(x)}setCamera(e){this.camera=e,this.composer.passes.forEach((t=>{t instanceof p?t.camera=e:t instanceof y?t.renderCamera=e:t instanceof L&&(t.camera=e)})),null==this.csm?this.csm=new H({maxFar:250,lightFar:250,lightMargin:20,cascades:4,shadowMapSize:2048,lightDirection:new s.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene,mode:"logarithmic"}):(this.csm.camera=this.camera,this.camera instanceof h&&(this.csm.maxFar=this.camera.far)),this.csm.updateFrustums()}setSelectedObjects(e){const t=new Map;for(const i of e)t.set(i.uuid,i);for(const i of e)i.traverse((e=>{e.uuid!==i.uuid&&t.has(e.uuid)&&t.delete(e.uuid)}));this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t){var i=!!e.extensions.get("WEBGL_depth_texture");const r=new s.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio());return r.texture.minFilter=s.NearestFilter,r.texture.magFilter=s.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,!0===i&&(r.depthTexture=new s.DepthTexture(128,128),r.depthTexture.type=s.UnsignedShortType,r.depthTexture.minFilter=s.NearestFilter,r.depthTexture.magFilter=s.NearestFilter),r}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(){this.running=!1,window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],this.renderer.dispose(),this.depthRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren()}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.container.contains(this.stats.dom)?this.container.appendChild(this.stats.dom):!this._showStats&&this.container.contains(this.stats.dom)&&this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}loop(e,t=!1){const i=this.stats,a=i.addPanel(new T.Panel("Calls","#83f","#002"));let o;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(o=new B(this.renderer.getContext()),i.addPanel(o)),i.showPanel(0),this.showStats=t;let h=10;const l=()=>{const e=this.renderer.info.render.calls;e>h&&(h=e,setTimeout((()=>h=10),5e3)),a.update(e,h)};performance.now();s.Ray.prototype.intersectTriangle;let d=0;const c=new n,m=new n,p=t=>{const s=this.renderer.getContext();if(this.paused&&this.running&&s.drawingBufferHeight>1)return void setTimeout((()=>p(t)),500);this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,i.begin();let n=(t*=.001)-d;if(d=t,c.copy(this.camera.matrixWorld),n>1){let t=n;for(;t>.05;)e(O),t-=O;e(t)}else e(n);this.onLoopCallbacks.forEach((e=>e(n))),this.camera?.updateMatrixWorld(),m.copy(this.camera.matrixWorld),m.equals(c)||(this.renderer.shadowMap.needsUpdate=!0),this.resizeRender();const a=[],h=[];if(this.scene.traverse((e=>{e instanceof r&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[b])?(e.visible=!1,a.push(e),this.initDepthUniform(e.material),e.renderOrder=100):e instanceof x&&(e.visible=!1,h.push(e)),e instanceof r&&e.material?.uniforms&&null!=e.material?.uniforms[M]&&(e.material.uniforms[M].value=t)})),a.length>0){if(this.scene.overrideMaterial=F,this.renderer.setRenderTarget(this.depthRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(),this.renderer.render(this.scene,this.camera)}catch(e){console.warn(e)}this.renderer.setRenderTarget(null),this.scene.overrideMaterial=null}a.forEach((e=>e.visible=!0)),h.forEach((e=>e.visible=!0));try{!this.paused&&this.running&&(o?.startQuery(),this.render(n),o?.endQuery(),this.showStats&&l(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}i.end(),this.csm?.update(),this.running&&!0!==this.options.enableXR&&(this.fpsCap?setTimeout((()=>{requestAnimationFrame(p)}),1e3/this.fpsCap):requestAnimationFrame(p))};!0===this.options.enableXR?this.renderer.setAnimationLoop(p):requestAnimationFrame(p)}renderOverlay(){const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.container.clientWidth/2,i=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let s=0;s<e.length;s++)this.renderer.clearDepth(),this.renderer.setViewport(t-i/2+this.insetWidth*s+this.insetMargin*s,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[s])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){const t=this.hasBloom();if(t||this.hadBloom){const e=this.scene.fog;this.scene.fog=null;const t=this.renderer.getClearColor(this.prevClearColor);this.renderer.setClearColor(0),this.scene.traverseVisible((e=>this.darkenNonBloomed(e))),this.bloomComposer.render(),this.scene.traverse((e=>this.restoreMaterial(e))),this.renderer.setClearColor(t),this.scene.fog=e}this.hadBloom=t,this.composer.render(e)}hasBloom(){return null!=W(this.scene,(e=>e instanceof r&&!0===e.material?.userData?.hasBloom))}darkenNonBloomed(e){e.isMesh&&e.visible&&!0!==e.material.userData.hasBloom&&(this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=D:e.visible=!1)}restoreMaterial(e){this.bloomStoredMaterials[e.uuid]&&(e.material=this.bloomStoredMaterials[e.uuid],delete this.bloomStoredMaterials[e.uuid],e.visible=!0)}initDepthUniform(e){e instanceof a&&(e.uniforms[b].value=this.isDepthTextureExtensionSupported?this.depthRenderTarget.depthTexture:this.depthRenderTarget.texture,null!=e.uniforms[C]&&e.uniforms[C].value.set(this.container.clientWidth*this.renderer.getPixelRatio(),this.container.clientHeight*this.renderer.getPixelRatio()),this.camera instanceof h&&(e.uniforms[S].value=this.camera.near,e.uniforms[R].value=this.camera.far))}};z=e=t([E(),i("design:paramtypes",[HTMLElement,Object])],z);export{z as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const O=.05;
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -1,4 +1,4 @@
1
- import{AudioLoader as e,Group as t,LoadingManager as a,Mesh as i,Object3D as s,TextureLoader as r}from"three";import{GLTFLoader as n,MTLLoader as o,OBJLoader as c}from"three-stdlib";import{FBXLoader as h}from"three-stdlib";import{cloneMesh as l}from"../utils/mesh.js";import{pathJoin as d}from"../utils/files.js";import{Subject as p,firstValueFrom as m}from"rxjs";import{importCollisionShapes as f}from"./collision/collision-shape-import.js";import*as u from"three";import{iterateMaterials as g}from"../utils/materials.js";const w=["glb","gltf","fbx","obj"];export class AssetResourceLoader{onError(e){console.error(e)}constructor(){this.cache=new Map,this.textureCache=new Map,this.loadingManager=new a,this.glbLoader=new n(this.loadingManager),this.fbxLoader=new h(this.loadingManager),this.objLoader=new c(this.loadingManager),this.textureLoader=new r(this.loadingManager),this.audioLoader=new e(this.loadingManager),this.makeReady=new p,this.ready=m(this.makeReady),this.collisionShapeCache=new Map}setDataDir(e){this.basePath=d(e,"asset-resources"),this.makeReady.next(!0)}getUri(e){return d(this.basePath,e)+`?windowId=${getElectronArg("windowId")}`}async getTexture(e){return null==e?null:(await this.ready,this.cache.has(e.id)||await this.textureLoader.loadAsync(this.getUri(e.fileKey)).then((t=>(t.wrapS=L(e.texture?.wrapS),t.wrapT=L(e.texture?.wrapT),t.flipY=e.texture?.flipY??!0,this.textureCache.set(e.id,t),t))),this.textureCache.get(e.id))}async getMesh(e){if(await this.ready,!w.includes(e.fileFormat?.toLowerCase()))return console.error("Unsupported mesh file format "+e.fileFormat,e),{scene:new t,animations:[]};if(!this.cache.has(e.fileKey))try{this.cache.set(e.fileKey,await this.loadMesh(e))}catch(e){return this.onError(e),{scene:new t,animations:[]}}const a=l(this.cache.get(e.fileKey).scene),s=this.cache.get(e.fileKey).animations;a.traverse((e=>{e instanceof i&&e.material instanceof Array&&(e.material=e.material.slice())}));const r=this.computeCollisionShapes(e,a),n=new AssetMeshInstance;n.add(a),n.collisionShapes=r;const o=!!e.receiveShadow??!0,c=!!e.castShadow??!1;return a.traverse((e=>{e.castShadow=c,e.receiveShadow=o})),{scene:n,animations:s}}async getAudio(e){return await this.ready,this.audioLoader.loadAsync(this.getUri(e.fileKey))}computeCollisionShapes(e,t){return this.collisionShapeCache.get(e.id)||this.collisionShapeCache.set(e.id,f(t)),this.collisionShapeCache.get(e.id)}async loadMesh(e){return await this.ready,await this.loadByAsset(e).then((e=>(e.scene=function(e,t){let a=!1;if(t.traverseVisible((e=>{b.test(e.name)&&(a=!0)})),!a)return t;const i=new u.LOD,s=[t];for(;s.length>0;){const e=s.shift(),t=e.name.match(b);if(null!=t){const a=parseInt(t[1]);0===a?i.addLevel(e,0):console.warn(`Skipping LOD level ${a} for now as LOD is not fully supported`)}else s.push(...e.children)}return i}(0,e.scene),e)))}async loadByAsset(e){const t=this.getUri(e.fileKey);switch(e.fileFormat){case"glb":case"gltf":return this.glbLoader.loadAsync(t).then((e=>({scene:e.scene,animations:e.animations})));case"fbx":return this.fbxLoader.loadAsync(t).then((e=>({scene:e,animations:e.animations})));case"obj":if(null!=e.materialLib){const t=new o;t.materialOptions={normalizeRGB:!1};const a=await t.loadAsync(this.getUri(e.materialLib));this.objLoader.setMaterials(a)}return this.objLoader.loadAsync(t).then((e=>(y(e),e))).then((e=>({scene:e,animations:e.animations})))}}}function y(e){if(e instanceof i)for(const t of g(e.material))t instanceof u.MeshPhongMaterial&&!t.color.isLinear&&(t.color.isLinear=!0);e.children?.forEach(y)}export class AssetMeshInstance extends s{}export function getElectronArg(e){const t=`--${e}=`,a=window.process?.argv.find((e=>e.startsWith(t)));return a?.substring(t.length)}function L(e){switch(e){case"clamp":return u.ClampToEdgeWrapping;case"repeat":return u.RepeatWrapping;case"mirror":return u.MirroredRepeatWrapping}return u.RepeatWrapping}const b=/_LOD(\d+)$/;
1
+ import{AudioLoader as e,Group as t,LoadingManager as a,Mesh as s,Object3D as i,TextureLoader as r}from"three";import{GLTFLoader as n,MTLLoader as o,OBJLoader as h}from"three-stdlib";import{FBXLoader as c}from"three-stdlib";import{cloneMesh as l}from"../utils/mesh.js";import{pathJoin as d}from"../utils/files.js";import{Subject as p,firstValueFrom as m}from"rxjs";import{importCollisionShapes as f}from"./collision/collision-shape-import.js";import*as u from"three";import{iterateMaterials as g}from"../utils/materials.js";const w=["glb","gltf","fbx","obj"];export class AssetResourceLoader{onError(e){console.error(e)}constructor(){this.cache=new Map,this.textureCache=new Map,this.loadingManager=new a,this.glbLoader=new n(this.loadingManager),this.fbxLoader=new c(this.loadingManager),this.objLoader=new h(this.loadingManager),this.textureLoader=new r(this.loadingManager),this.audioLoader=new e(this.loadingManager),this.makeReady=new p,this.ready=m(this.makeReady),this.collisionShapeCache=new Map}setDataDir(e){this.basePath=d(e,"asset-resources"),this.makeReady.next(!0)}getUri(e){return d(this.basePath,e)+`?windowId=${getElectronArg("windowId")}`}async getTexture(e){return null==e?null:(await this.ready,this.cache.has(e.id)||await this.textureLoader.loadAsync(this.getUri(e.fileKey)).then((t=>(t.wrapS=L(e.texture?.wrapS),t.wrapT=L(e.texture?.wrapT),t.flipY=e.texture?.flipY??!0,this.textureCache.set(e.id,t),t))),this.textureCache.get(e.id))}async getMesh(e){if(await this.ready,!w.includes(e.fileFormat?.toLowerCase()))return console.error("Unsupported mesh file format "+e.fileFormat,e),{scene:new t,animations:[]};if(!this.cache.has(e.fileKey))try{this.cache.set(e.fileKey,await this.loadMesh(e))}catch(e){return this.onError(e),{scene:new t,animations:[]}}const a=l(this.cache.get(e.fileKey).scene),i=this.cache.get(e.fileKey).animations;a.traverse((e=>{e instanceof s&&e.material instanceof Array&&(e.material=e.material.slice())}));const r=this.computeCollisionShapes(e,a),n=new AssetMeshInstance;n.add(a),n.collisionShapes=r,n.animations=i;const o=!!e.receiveShadow??!0,h=!!e.castShadow??!1;return a.traverse((e=>{e.castShadow=h,e.receiveShadow=o})),{scene:n,animations:i}}async getAudio(e){return await this.ready,this.audioLoader.loadAsync(this.getUri(e.fileKey))}computeCollisionShapes(e,t){const a=e.id+e.mesh?.collisions?.shapeType;return this.collisionShapeCache.has(a)||this.collisionShapeCache.set(a,f(t,e)),this.collisionShapeCache.get(a)}async loadMesh(e){return await this.ready,await this.loadByAsset(e).then((e=>(e.scene=function(e,t){let a=!1;if(t.traverseVisible((e=>{b.test(e.name)&&(a=!0)})),!a)return t;const s=new u.LOD,i=[t];for(;i.length>0;){const e=i.shift(),t=e.name.match(b);if(null!=t){const a=parseInt(t[1]);0===a?s.addLevel(e,0):console.warn(`Skipping LOD level ${a} for now as LOD is not fully supported`)}else i.push(...e.children)}return s}(0,e.scene),e)))}async loadByAsset(e){const t=this.getUri(e.fileKey);switch(e.fileFormat){case"glb":case"gltf":return this.glbLoader.loadAsync(t).then((e=>({scene:e.scene,animations:e.animations})));case"fbx":return this.fbxLoader.loadAsync(t).then((e=>({scene:e,animations:e.animations})));case"obj":if(null!=e.materialLib){const t=new o;t.materialOptions={normalizeRGB:!1};const a=await t.loadAsync(this.getUri(e.materialLib));this.objLoader.setMaterials(a)}return this.objLoader.loadAsync(t).then((e=>(y(e),e))).then((e=>({scene:e,animations:e.animations})))}}}function y(e){if(e instanceof s)for(const t of g(e.material))t instanceof u.MeshPhongMaterial&&!t.color.isLinear&&(t.color.isLinear=!0);e.children?.forEach(y)}export class AssetMeshInstance extends i{}export function getElectronArg(e){const t=`--${e}=`,a=window.process?.argv.find((e=>e.startsWith(t)));return a?.substring(t.length)}function L(e){switch(e){case"clamp":return u.ClampToEdgeWrapping;case"repeat":return u.RepeatWrapping;case"mirror":return u.MirroredRepeatWrapping}return u.RepeatWrapping}const b=/_LOD(\d+)$/;
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -1,4 +1,5 @@
1
1
  import { Object3D } from "three";
2
2
  import { CollisionShape } from './collision-shape.js';
3
- export declare function importCollisionShapes(group: Object3D): CollisionShape[];
3
+ import { Asset } from "../../scene/model.js";
4
+ export declare function importCollisionShapes(group: Object3D, asset: Asset): CollisionShape[];
4
5
  export declare function isCollisionMesh(object: Object3D): boolean;
@@ -1,4 +1,4 @@
1
- import{Box3 as e,Euler as t,Mesh as n,Quaternion as o,Vector3 as r}from"three";import{BoxCollisionShape as i,ConvexPolyhedronCollisionShape as s,SphereCollisionShape as a,TrimeshCollisionShape as m}from"./collision-shape.js";const u=new o;export function importCollisionShapes(o){const x=[];return o.traverse((o=>{if(o instanceof n||o.isMesh){const n=function(t){if(t.name.startsWith(c.convex))return new s(t);if(t.name.startsWith(c.box)){const n=t.clone();n.quaternion.set(0,0,0,1),n.updateMatrixWorld();const o=(new e).setFromObject(n);return isFinite(o.min.lengthSq())?new i(new r(o.max.x-o.min.x,o.max.y-o.min.y,o.max.z-o.min.z)):null}if(t.name.startsWith(c.sphere)){t.geometry.computeBoundingSphere();const e=t.geometry.boundingSphere.radius*Math.max(t.scale.x,t.scale.y,t.scale.z);return new a(e)}if(t.name.startsWith(c.trimesh))return new m(t.geometry);{t.geometry.computeBoundingBox();const e=function(e){const t=e.max.x-e.min.x,n=e.max.y-e.min.y,o=e.max.z-e.min.z;return t+n+o}(h.copy(t.geometry.boundingBox).applyMatrix4(t.matrixWorld));if(e>1)return new m(t.geometry);if(e>.001)return new s(t)}}(o);null!=n&&(n.offset=o.getWorldPosition(new r),n.rotation=(new t).setFromQuaternion(o.getWorldQuaternion(u)),x.push(n),isCollisionMesh(o)&&(o.visible=!1))}})),x}export function isCollisionMesh(e){return e.name.startsWith(c.convex)||e.name.startsWith(c.box)||e.name.startsWith(c.sphere)||e.name.startsWith(c.trimesh)}var c;!function(e){e.convex="UCX_",e.box="UBX_",e.sphere="USP_",e.trimesh="UTM_"}(c||(c={}));const h=new e;
1
+ import{Box3 as e,Euler as t,Mesh as n,Quaternion as s,Vector3 as i}from"three";import{BoxCollisionShape as o,ConvexPolyhedronCollisionShape as r,SphereCollisionShape as a,TrimeshCollisionShape as m}from"./collision-shape.js";const h=new s;export function importCollisionShapes(s,c){let u=c.mesh?.collisions?.shapeType;if(null==u){let e=!1;s.traverse((t=>{(t instanceof n||t.isMesh)&&isCollisionMesh(t)&&(e=!0)})),u=e?"imported":"convex"}const p=[];return s.traverse((s=>{if(s instanceof n||s.isMesh){let n;"imported"===u?n=function(t){if(t.name.startsWith(l.convex))return new r(t);if(t.name.startsWith(l.box)){const n=t.clone();n.quaternion.set(0,0,0,1),n.updateMatrixWorld();const s=(new e).setFromObject(n);return isFinite(s.min.lengthSq())?new o(new i(s.max.x-s.min.x,s.max.y-s.min.y,s.max.z-s.min.z)):null}if(t.name.startsWith(l.sphere)){t.geometry.computeBoundingSphere();const e=t.geometry.boundingSphere.radius*Math.max(t.scale.x,t.scale.y,t.scale.z);return new a(e)}if(t.name.startsWith(l.trimesh))return new m(t.geometry)}(s):"convex"===u?n=new r(s):"mesh"===u&&(n=new m(s.geometry)),null!=n&&(n.offset=s.getWorldPosition(new i),n.rotation=(new t).setFromQuaternion(s.getWorldQuaternion(h)),p.push(n),isCollisionMesh(s)&&(s.visible=!1))}})),p}export function isCollisionMesh(e){return e.name.startsWith(l.convex)||e.name.startsWith(l.box)||e.name.startsWith(l.sphere)||e.name.startsWith(l.trimesh)}var l;!function(e){e.convex="UCX_",e.box="UBX_",e.sphere="USP_",e.trimesh="UTM_"}(l||(l={}));new e;
2
2
  /*
3
3
  * Copyright (©) 2023. All rights reserved.
4
4
  * See the LICENSE.md file for details.
@@ -35,6 +35,7 @@ export type CustomParamValue = {
35
35
  value: unknown;
36
36
  };
37
37
  export type WrapMode = 'clamp' | 'repeat' | 'mirror';
38
+ export type CollisionShapeType = 'convex' | 'mesh' | 'imported';
38
39
  export type TextureSettings = {
39
40
  flipY?: boolean;
40
41
  wrapS?: WrapMode;
@@ -65,6 +66,9 @@ export interface Asset {
65
66
  };
66
67
  mesh?: {
67
68
  rescale?: number;
69
+ collisions?: {
70
+ shapeType?: CollisionShapeType;
71
+ };
68
72
  };
69
73
  prefab?: {
70
74
  objects: SceneObject[];
@@ -21,21 +21,23 @@ export declare class ObjectStorage<T extends Entity> {
21
21
  constructor(name: string, filePathFn?: (o: ObjectIndexEntry) => string);
22
22
  setBasePath(path: string): void;
23
23
  private determineIfMetaFileShouldBeCreated;
24
+ watch(): void;
24
25
  getAll(): Promise<T[]>;
25
26
  get(id: string): Promise<T>;
26
27
  save(obj: T): Promise<T>;
27
28
  rename(obj: T, name: string): Promise<T>;
28
29
  delete(obj: T): Promise<void>;
29
30
  create(obj: Partial<T>): Promise<T>;
31
+ private serialize;
30
32
  private updateIndex;
31
33
  private get indexFilePath();
32
34
  private loadIndex;
33
35
  ensureResourceDir(): Promise<void>;
34
- saveFile(asset: T, file: File): Promise<any>;
35
- saveExtraFile(sourcePath: string, relativePath: string): Promise<any>;
36
+ saveFile(asset: T, file: File): Promise<void>;
37
+ saveExtraFile(sourcePath: string, relativePath: string): Promise<void>;
36
38
  getAssetPath(asset: T): any;
37
- replaceFile(asset: T, replacementFile: String): Promise<any>;
38
- deleteFile(fileKey: string): Promise<any>;
39
+ replaceFile(asset: T, replacementFile: string): Promise<void>;
40
+ deleteFile(fileKey: string): Promise<void>;
39
41
  private privateObjectPath;
40
42
  }
41
43
  export declare function tokenizeName(name: string): string;
@@ -1,4 +1,4 @@
1
- import{randomUUID as t}from"../../utils/uuid.js";import{pathJoin as e}from"../../utils/files.js";import{firstValueFrom as i,map as a,Subject as s,tap as n}from"rxjs";import{sleepDelay as r}from"../../utils/async.js";const h={},o={},c={};null==h.read&&window.require&&(Object.assign(h,window.require("fs")),Object.assign(o,h.promises),Object.assign(c,window.require("path")));const l=null!=h.existsSync;function d(){if(l){const t="--path=",e=window.process.argv.find((e=>e.startsWith(t)));return e?e.substring(t.length):""}return""}const u=/^[A-Z]:/;function p(...t){return 0===t.length?"":u.test(t[0])?c.join(...t):e(...t)}export class ObjectStorage{constructor(t,e){this.name=t,this.filePathFn=e,this.basePathUpdates=new s,this.basePath=this.basePathUpdates.pipe(a((t=>p(d(),t))),n((t=>{this.path=p(t,this.name),w(this.path),this.determineIfMetaFileShouldBeCreated()}))),this.loaded=i(this.basePath),this.shouldCreateIndex=!0}setBasePath(t){this.basePathUpdates.next(t)}async determineIfMetaFileShouldBeCreated(){try{(await o.readFile(p(d(),"vite.config.ts"))).toString().includes("hologyBuild")&&(this.shouldCreateIndex=!1)}catch(t){console.warn("Failed to read vite config to determine if meta files should be created")}}async getAll(){if(l){await this.loaded,await w(this.path);const t=(await o.readdir(this.path)).filter((t=>!/^[\._]/.test(t)));return(await Promise.all(t.map((t=>o.readFile(p(this.path,t)))))).map((t=>JSON.parse(t.toString())))}const t=await this.loadIndex();return Promise.all(Object.keys(t).map((t=>this.get(t))))}async get(t){const e=await this.loadIndex(),i=e[t]??Object.values(e).find((e=>e.name===t));if(null==i)return;const a=this.privateObjectPath(i);if(!l)return(await fetch(a)).json();return await f(a)?JSON.parse((await o.readFile(a)).toString()):null}async save(t){return m(),await this.loaded,await o.writeFile(this.privateObjectPath(t),JSON.stringify(t,null,2)),await this.updateIndex(),t}async rename(t,e){const i={...t,name:e},a=this.privateObjectPath(t),s=this.privateObjectPath(i);try{await o.rename(a,s)}catch(t){console.error(t),console.warn("Rename failed, retrying",{currentPath:a,newPath:s}),await r(400),await o.rename(a,s)}return await this.save(i),await this.updateIndex(),i}async delete(t){await o.unlink(this.privateObjectPath(t)),this.updateIndex()}async create(e){return m(),await this.loaded,e.id=t(),await o.writeFile(this.privateObjectPath(e),JSON.stringify(e,null,2)),await this.updateIndex(),e}async updateIndex(){m();const t=await this.getAll(),e={};for(const i of t)e[i.id]={id:i.id,name:i.name??i.id,path:i.path};if(this.cachedIndex=e,l){if(!this.shouldCreateIndex)return;await o.writeFile(this.indexFilePath,JSON.stringify(e,null,2))}}get indexFilePath(){return p(this.path,"_meta.json")}async loadIndex(){return null==this.cachedIndex&&(l?await this.updateIndex():this.cachedIndex=await(await fetch(this.indexFilePath)).json()),this.cachedIndex}async ensureResourceDir(){await w(p(this.path+"-resources"))}async saveFile(t,e){return m(),await w(p(this.path+"-resources")),o.copyFile(e.path,p(this.path+"-resources",t.fileKey))}async saveExtraFile(t,e){return m(),await w(p(this.path+"-resources")),o.copyFile(t,p(this.path+"-resources",e))}getAssetPath(t){return window&&"function"==typeof window.require?window.require("path").join(this.path+"-resources",t.fileKey):p(this.path+"-resources",t.fileKey)}async replaceFile(t,e){if(await f(e))return o.copyFile(e,p(this.path+"-resources",t.fileKey));console.error("Failed to replace file using path "+e)}async deleteFile(t){if(null==t)return;m();const e=p(this.path+"-resources",t);return await f(e)?o.unlink(e):void 0}privateObjectPath(t){return this.filePathFn?p(this.path,this.filePathFn(t)):p(this.path,tokenizeName(t.name??t.id)+".json")}}export function tokenizeName(t){return t.trim().replace(/\s/g,"_").replace(/[^a-z0-9_\-\.]/gi,"")}async function w(t){l&&(await f(t)||await o.mkdir(t,{recursive:!0}))}function f(t){return!!l&&new Promise((function(e,i){h.exists(t,(function(t){e(t)}))}))}function m(){if(!l)throw new Error("Must have direct access to filesystem")}
1
+ import{randomUUID as t}from"../../utils/uuid.js";import{pathJoin as e}from"../../utils/files.js";import{firstValueFrom as i,map as a,Observable as s,Subject as n,tap as r}from"rxjs";import{sleepDelay as h}from"../../utils/async.js";const o={},c={},l={};null==o.read&&window.require&&(Object.assign(o,window.require("fs")),Object.assign(c,o.promises),Object.assign(l,window.require("path")));const d=null!=o.existsSync;function u(){if(d){const t="--path=",e=window.process.argv.find((e=>e.startsWith(t)));return e?e.substring(t.length):""}return""}const p=/^[A-Z]:/;function w(...t){return 0===t.length?"":p.test(t[0])?l.join(...t):e(...t)}export class ObjectStorage{constructor(t,e){this.name=t,this.filePathFn=e,this.basePathUpdates=new n,this.basePath=this.basePathUpdates.pipe(a((t=>w(u(),t))),r((t=>{this.path=w(t,this.name),f(this.path),this.determineIfMetaFileShouldBeCreated()}))),this.loaded=i(this.basePath),this.shouldCreateIndex=!0}setBasePath(t){this.basePathUpdates.next(t)}async determineIfMetaFileShouldBeCreated(){try{(await c.readFile(w(u(),"vite.config.ts"))).toString().includes("hologyBuild")&&(this.shouldCreateIndex=!1)}catch(t){console.warn("Failed to read vite config to determine if meta files should be created")}}watch(){y(),function(t){return new s((e=>{const i=new AbortController,{signal:a}=i,s=c.watch(t,{recursive:!0,signal:a});return(async()=>{for await(const t of s)console.log(t),e.next(t)})(),()=>{i.abort()}}))}(this.path).pipe(a((t=>t.eventType)))}async getAll(){if(d){await this.loaded,await f(this.path);const t=(await c.readdir(this.path,{recursive:!0,withFileTypes:!0})).filter((t=>t.isFile()&&t.name.endsWith(".json")&&!/^[\._]/.test(t.name)));return await Promise.all(t.map((t=>c.readFile(w(this.path,t.path,t.name)).then((e=>({...JSON.parse(e.toString()),path:t}))))))}const t=await this.loadIndex();return Promise.all(Object.keys(t).map((t=>this.get(t))))}async get(t){const e=await this.loadIndex(),i=e[t]??Object.values(e).find((e=>e.name===t));if(null==i)return;const a=this.privateObjectPath(i);if(!d)return(await fetch(a)).json();return await m(a)?JSON.parse((await c.readFile(a)).toString()):null}async save(t){return y(),await this.loaded,await c.writeFile(this.privateObjectPath(t),this.serialize(t)),await this.updateIndex(),t}async rename(t,e){const i={...t,name:e},a=this.privateObjectPath(t),s=this.privateObjectPath(i);try{await c.rename(a,s)}catch(t){console.error(t),console.warn("Rename failed, retrying",{currentPath:a,newPath:s}),await h(400),await c.rename(a,s)}return await this.save(i),await this.updateIndex(),i}async delete(t){await c.unlink(this.privateObjectPath(t)),this.updateIndex()}async create(e){return y(),await this.loaded,e.id=t(),await c.writeFile(this.privateObjectPath(e),this.serialize(e)),await this.updateIndex(),e}serialize(t){const e={...t};return delete e.path,JSON.stringify(e,null,2)}async updateIndex(){y();const t=await this.getAll(),e={};for(const i of t)e[i.id]={id:i.id,name:i.name??i.id,path:i.path};if(this.cachedIndex=e,d){if(!this.shouldCreateIndex)return;await c.writeFile(this.indexFilePath,JSON.stringify(e,null,2))}}get indexFilePath(){return w(this.path,"_meta.json")}async loadIndex(){return null==this.cachedIndex&&(d?await this.updateIndex():this.cachedIndex=await(await fetch(this.indexFilePath)).json()),this.cachedIndex}async ensureResourceDir(){await f(w(this.path+"-resources"))}async saveFile(t,e){return y(),await f(w(this.path+"-resources")),c.copyFile(e.path,w(this.path+"-resources",t.fileKey))}async saveExtraFile(t,e){return y(),await f(w(this.path+"-resources")),c.copyFile(t,w(this.path+"-resources",e))}getAssetPath(t){return window&&"function"==typeof window.require?window.require("path").join(this.path+"-resources",t.fileKey):w(this.path+"-resources",t.fileKey)}async replaceFile(t,e){if(await m(e))return c.copyFile(e,w(this.path+"-resources",t.fileKey));console.error("Failed to replace file using path "+e)}async deleteFile(t){if(null==t)return;y();const e=w(this.path+"-resources",t);return await m(e)?c.unlink(e):void 0}privateObjectPath(t){return this.filePathFn?w(this.path,this.filePathFn(t)):w(this.path,tokenizeName(t.name??t.id)+".json")}}export function tokenizeName(t){return t.trim().replace(/\s/g,"_").replace(/[^a-z0-9_\-\.]/gi,"")}async function f(t){d&&(await m(t)||await c.mkdir(t,{recursive:!0}))}function m(t){return!!d&&new Promise((function(e,i){o.exists(t,(function(t){e(t)}))}))}function y(){if(!d)throw new Error("Must have direct access to filesystem")}
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.50",
3
+ "version": "0.0.52",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -83,6 +83,7 @@
83
83
  "author": "",
84
84
  "license": "SEE LICENSE IN LICENSE.md",
85
85
  "dependencies": {
86
+ "@babel/runtime": "^7.24.8",
86
87
  "@dimforge/rapier3d-compat": "^0.13.1",
87
88
  "@plumier/reflect": "^1.1.0",
88
89
  "@types/three-nebula": "^10.0.3",
@@ -99,7 +100,6 @@
99
100
  "typedi": "^0.10.0"
100
101
  },
101
102
  "devDependencies": {
102
- "@babel/runtime": "^7.24.8",
103
103
  "@types/node": "^20.3.1",
104
104
  "@types/offscreencanvas": "^2019.7.0",
105
105
  "@types/three": "0.166.0",