@protomaze/geometry 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -0
- package/engine/GeometryEngine.d.ts +17 -7
- package/engine/GeometryEngine.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -101,6 +101,13 @@ keep their compiled shaders (`GeometryPrimitive.adopt`). An edit to one pipe of
|
|
|
101
101
|
50 ms of buffers, not a recompile. `layer.setOverride(ids, 'faded' | 'hidden' | 'selected')` forces a
|
|
102
102
|
state on features whatever their style says: what an editor fades while it works on them.
|
|
103
103
|
|
|
104
|
+
Shaders are made in the background. What a layer adds - its first build, its 2D map, a selection's
|
|
105
|
+
glow - is held back while three builds its shaders, a step at a time, and the driver links them
|
|
106
|
+
side by side (`compileAsync`; WebGL 2's parallel compile), then drawn whole. The page answers
|
|
107
|
+
meanwhile: switching the demo to its City size keeps every frame under 150 ms, where building the
|
|
108
|
+
shaders inside the frames took up to 530 ms. What was compiled once draws at once when it comes
|
|
109
|
+
back, as a 2D map toggled back to 3D does. `engine.compilingShaders` says whether any are being made.
|
|
110
|
+
|
|
104
111
|
## Calculations
|
|
105
112
|
|
|
106
113
|
Plain functions on GeoJSON-shaped geometry, in world units - metres in a projected or local
|
|
@@ -119,14 +119,16 @@ export declare abstract class GeometryEngine extends TypedEventEmitter<GeometryE
|
|
|
119
119
|
private attached;
|
|
120
120
|
/**
|
|
121
121
|
* Meshes attached and not yet compiled, by pass: three compiles them in the background
|
|
122
|
-
* (`compileAsync`) while frames go on without them,
|
|
123
|
-
*
|
|
124
|
-
*
|
|
122
|
+
* (`compileAsync`) while frames go on without them, in batches - what a frame found new, a
|
|
123
|
+
* layer's primitives as it builds - each shown whole when it is done. A page that answers
|
|
124
|
+
* while its shaders are made, rather than one frozen for a second or more at its first frames
|
|
125
|
+
* (three's node building and WebGL 2's linking, all inside them).
|
|
125
126
|
*/
|
|
126
127
|
private readonly unready;
|
|
127
128
|
/** Meshes compiled once: attached again - a 2D map toggled back - they draw at once. */
|
|
128
129
|
private readonly compiled;
|
|
129
|
-
|
|
130
|
+
/** Meshes being compiled now, in batches of their own: a layer's starts as it is attached. */
|
|
131
|
+
private readonly compiling;
|
|
130
132
|
private readonly startTime;
|
|
131
133
|
/** The view-projection the last frame was drawn with, relative to the origin, column-major. */
|
|
132
134
|
private readonly drawnCamera;
|
|
@@ -222,11 +224,19 @@ export declare abstract class GeometryEngine extends TypedEventEmitter<GeometryE
|
|
|
222
224
|
protected renderFrame(input: FrameInput, prepareDepth?: () => boolean): boolean;
|
|
223
225
|
private drawFrame;
|
|
224
226
|
/**
|
|
225
|
-
* Starts compiling what was attached and is shown
|
|
226
|
-
* the target its pass draws to, so that the frame finds its pipelines made. What is
|
|
227
|
-
* waits until it is shown. A renderer without `compileAsync` draws everything at once.
|
|
227
|
+
* Starts compiling what was attached and is shown and not under way yet, as one batch: each
|
|
228
|
+
* mesh into the target its pass draws to, so that the frame finds its pipelines made. What is
|
|
229
|
+
* hidden waits until it is shown. A renderer without `compileAsync` draws everything at once.
|
|
228
230
|
*/
|
|
229
231
|
private warmUp;
|
|
232
|
+
/** Whether shaders of what is attached are being compiled now, in the background. */
|
|
233
|
+
get compilingShaders(): boolean;
|
|
234
|
+
/**
|
|
235
|
+
* A batch's meshes started one task after another, out of the frame - each start builds that
|
|
236
|
+
* mesh's first nodes at once - and then compiled side by side: three builds the rest of each
|
|
237
|
+
* mesh's nodes in steps, yielding between them, and the driver links their programs in
|
|
238
|
+
* parallel (WebGL 2's parallel compile), rather than one waiting on the other's link.
|
|
239
|
+
*/
|
|
230
240
|
private compile;
|
|
231
241
|
/** The target a pass draws into: the frame's own (null) for the scene and the underlay. */
|
|
232
242
|
private targetOf;
|
package/engine/GeometryEngine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AddEquation as e,Camera as t,Color as r,CustomBlending as s,DepthTexture as i,FloatType as n,LinearSRGBColorSpace as a,Matrix4 as o,NearestFilter as h,NoToneMapping as c,OneFactor as d,PostProcessing as l,RenderTarget as p,Scene as u,Vector2 as m,Vector3 as f,WebGPUCoordinateSystem as g,ZeroFactor as y}from"three/webgpu";import{pass as w,uniform as b}from"three/tsl";import{bloom as T}from"three/examples/jsm/tsl/display/BloomNode.js";import{TypedEventEmitter as x}from"../event/TypedEventEmitter.js";import{DensityMap as k}from"../three/DensityMap.js";import{Halo as P}from"../three/Halo.js";import{pickPassUniforms as R}from"./GeometryFrame.js";export class HostCamera extends t{updateProjectionMatrix(){}}export class GeometryEngine extends x{constructor(){super(),this.scene=new u,this.underlayScene=new u,this.bloomScene=new u,this.pickScene=new u,this.pickPass=R(),this.density=new k,this.halo=new P,this.camera=new HostCamera,this.lastRenderMs=0,this.frame={pxPerWorld:1,pixelRatio:1,near:.3,geocentric:!1,depth:!1,focal:1e3,orthographic:!0,width:1,height:1,eye:new f,time:0},this.bloom=null,this.renderer=null,this.ready=!1,this.disposed=!1,this.depthWanted=!1,this.bloomPost=null,this.bloomTarget=null,this.origins=new Map,this.drawn=new m,this.beforeRender=new Set,this.beforeDraw=new Set,this.pickSources=new Map,this.nextPickSource=1,this.pending=[],this.attached=new Map,this.unready=new Map,this.compiled=new WeakSet,this.warming=null,this.startTime=performance.now(),this.drawnCamera=new o,this.pickTarget=new p(7,7,{type:n,depthBuffer:!0,generateMipmaps:!1,minFilter:h,magFilter:h}),this.depthUniforms={enabled:b(0),near:b(.3)},this.clearColor=new r,this.camera.matrixAutoUpdate=!1,this.camera.matrixWorldAutoUpdate=!1,this.scene.add(this.density.quad),this.underlayScene.add(this.halo.quad),this.depth=this.createDepthTexture(),this.sceneDepth={texture:this.depth,enabled:this.depthUniforms.enabled,near:this.depthUniforms.near}}createDepthTexture(){const e=new i(1,1,n);return e.minFilter=h,e.magFilter=h,e}getRenderer(){return this.renderer}get webgpu(){return this.renderer?.coordinateSystem===g}originKey(){return"world"}setOrigin(e,t,r=0){this.origins.set(this.originKey(),[e,t,r])}getOrigin(){return this.origins.get(this.originKey())??null}originFor(e){let t=this.getOrigin();return t||(this.setOrigin(e[0],e[1],e[2]??0),t=this.getOrigin()),t}depthTexture(){return this.depthWanted=!0,this.depth}onBeforeRender(e){return this.beforeRender.add(e),()=>{this.beforeRender.delete(e)}}onBeforeDraw(e){return this.beforeDraw.add(e),()=>{this.beforeDraw.delete(e)}}attach(e){if(this.attached.has(e))return;const t=[],r=e.passes();Object.keys(r).forEach(e=>{for(const s of r[e]??[])s&&(this.sceneOf(e).add(s),t.push({mesh:s,pass:e}),this.compiled.has(s)||this.unready.set(s,e))}),this.attached.set(e,{primitive:e,meshes:t}),e.setFrame(this.frame),this.requestRepaint()}detach(e){const t=this.attached.get(e);t&&(t.meshes.forEach(({mesh:e,pass:t})=>{this.sceneOf(t).remove(e),this.unready.delete(e)}),this.attached.delete(e),this.requestRepaint())}sceneOf(e){switch(e){case"scene":return this.scene;case"underlay":return this.underlayScene;case"bloom":return this.bloomScene;case"pick":return this.pickScene;case"density":return this.density.scene;case"halo":return this.halo.scene}}renderToTarget(e,t){const r=this.renderer;if(!r||!this.ready)return!1;const s=r.getRenderTarget();return r.setRenderTarget(t),this.clearToZero(r),r.render(e,this.camera),r.setRenderTarget(s),!0}clearToZero(e){e.getClearColor(this.clearColor);const t=e.getClearAlpha();e.setClearColor(0,0),e.clear(!0,!0,!0),e.setClearColor(this.clearColor,t)}addPickSource(e){const t=this.nextPickSource++;return this.pickSources.set(t,e),{id:t,remove:()=>{this.pickSources.delete(t)}}}pick(e,t){return new Promise(r=>{const s={x:e,y:t,resolve:r},i=setTimeout(()=>{this.pending=this.pending.filter(e=>e!==s),r(null)},1e3);s.resolve=e=>{clearTimeout(i),r(e)},this.ready&&this.renderer&&this.drawn.x>0?this.runPick(s,this.drawn.x,this.drawn.y):(this.pending.push(s),this.requestRepaint())})}dispose(){this.disposed=!0,this.missPicks(),[...this.attached.keys()].forEach(e=>this.detach(e)),this.pickTarget.dispose(),this.density.dispose(),this.halo.dispose(),this.depth.dispose();try{this.bloomPost?.dispose()}catch{}this.bloomPost=null;try{this.renderer?.dispose()}catch{}this.renderer=null,this.ready=!1}adoptRenderer(e){try{this.bloomPost?.dispose()}catch{}this.bloomPost=null,this.renderer=e,this.ready=!1,e.outputColorSpace=a,e.toneMapping=c,e.autoClear=!0,e.autoClearColor=!1,e.autoClearStencil=!1,this.createBloom(e)}createBloom(t){const r=w(this.bloomScene,this.camera);this.bloomTarget=r;const i=T(r,1.2,.5,0);this.bloom=i;const n=new(function(){const e=Object.getPrototypeOf(l);return"function"==typeof e&&e!==Function.prototype&&"function"==typeof e.prototype?.render?e:l}())(t,i);n.outputColorTransform=!1;const a=n._quadMesh.material;a.transparent=!0,a.blending=s,a.blendSrc=d,a.blendDst=d,a.blendEquation=e,a.blendSrcAlpha=y,a.blendDstAlpha=d,a.depthTest=!1,a.depthWrite=!1,this.bloomPost=n}updateCamera(e){const t=e.viewProjection,r=this.frame,{width:s,height:i}=e;r.width=s,r.height=i,r.pixelRatio=e.pixelRatio,r.near=e.near,r.geocentric=!!e.geocentric,r.pxPerWorld=e.pxPerWorld??Math.hypot(t[0]*s/2,t[4]*i/2);const n=e.orthographic??Math.abs(t[12])+Math.abs(t[13])+Math.abs(t[14])<1e-12;r.orthographic=n,r.focal=e.focal??(n?r.pxPerWorld:Math.hypot(t[0],t[1],t[2])*s/2),r.depth=this.depthWanted&&this.depthReady(),r.time=(performance.now()-this.startTime)/1e3,this.depthUniforms.near.value=e.near,this.depthUniforms.enabled.value=r.depth?1:0;const[a,o,h]=this.getOrigin()??[0,0,0];e.eye&&r.eye.set(e.eye[0]-a,e.eye[1]-o,(e.eye[2]??0)-h);const c=this.camera.projectionMatrix.elements;for(let e=0;e<4;e++)c[e]=t[4*e],c[4+e]=t[4*e+1],c[8+e]=t[4*e+2],c[12+e]=t[4*e]*a+t[4*e+1]*o+t[4*e+2]*h+t[4*e+3];if(e.glDepth&&this.webgpu)for(let e=0;e<4;e++)c[4*e+2]=.5*c[4*e+2]+.5*c[4*e+3];this.camera.projectionMatrixInverse.copy(this.camera.projectionMatrix).invert()}depthReady(){return!0}renderFrame(e,t){const r=this.renderer;if(this.lastRenderMs=0,!this.ready||!r)return!1;const s=performance.now();r._nodes?.nodeFrame?.update?.(),this.updateCamera(e),this.attached.forEach(({primitive:e})=>e.setFrame(this.frame)),this.beforeRender.forEach(e=>e(this.frame)),this.warmUp(r);const i=this.holdBack();try{return this.drawFrame(r,e,s,t)}finally{i.forEach(e=>{e.visible=!0})}}drawFrame(e,t,r,s){this.density.update();const i=e=>e.children.some(e=>e.visible);if(!i(this.scene)&&!i(this.underlayScene))return this.missPicks(),this.lastRenderMs=performance.now()-r,!1;if(s&&!s())return!1;this.beforeDraw.forEach(e=>e(t.width,t.height));const n=(e,t)=>{this.renderToTarget(e,t)};if(this.halo.draw(t.width,t.height,n),this.density.draw(t.width,t.height,n),this.drawn.set(t.width,t.height),this.drawnCamera.copy(this.camera.projectionMatrix),this.pending.length>0&&this.runPick(this.pending.shift(),t.width,t.height),i(this.underlayScene)&&e.render(this.underlayScene,this.camera),e.render(this.scene,this.camera),this.bloomPost&&i(this.bloomScene)){const t=this.bloomTarget?.renderTarget;if(t){const r=e.getRenderTarget();e.setRenderTarget(t),this.clearToZero(e),e.setRenderTarget(r)}this.bloomPost.render()}return this.lastRenderMs=performance.now()-r,this.emit("frame",{ms:this.lastRenderMs,width:t.width,height:t.height}),!0}warmUp(e){if(this.warming||0===this.unready.size)return;if("function"!=typeof e.compileAsync)return void this.unready.clear();const t=[...this.unready].filter(([e])=>e.visible);0!==t.length&&(this.warming=this.compile(e,t).catch(e=>console.warn("[geometry] Compiling in the background failed; drawn as it comes",e)).finally(()=>{t.forEach(([e])=>{this.unready.delete(e),this.compiled.add(e)}),this.warming=null,this.requestRepaint()}))}async compile(e,t){for(const[r,s]of t){const t=this.sceneOf(s);if(!this.unready.has(r)||r.parent!==t||!this.renderer)continue;const i=e.getRenderTarget();let n;try{e.setRenderTarget(this.targetOf(s)),n=e.compileAsync(r,this.camera,t)}finally{e.setRenderTarget(i)}await n}}targetOf(e){switch(e){case"scene":case"underlay":return null;case"bloom":return this.bloomTarget?.renderTarget??null;case"pick":return this.pickTarget;case"density":return this.density.target;case"halo":return this.halo.target}}holdBack(){const e=[];return this.unready.forEach((t,r)=>{r.visible&&(r.visible=!1,e.push(r))}),e}missPicks(){this.drawn.set(0,0);const e=this.pending;this.pending=[],e.forEach(e=>e.resolve(null))}runPick(e,t,r){this.pending.length>0&&this.requestRepaint();const s=Math.floor(e.x*this.frame.pixelRatio),i=Math.floor(e.y*this.frame.pixelRatio),n=(s+.5)/t*2-1,a=1-(i+.5)/r*2,o=t/7,h=r/7;this.pickPass.window.value.set(o,0,0,-n*o,0,h,0,-a*h,0,0,1,0,0,0,0,1),this.pickPass.origin.value.set(s-3,i-3),this.pickPass.frameSize.value.set(t,r);const c=this.drawnCamera.clone(),d=this.getOrigin()??[0,0,0];this.renderToTarget(this.pickScene,this.pickTarget)?this.readPick(s,i,t,r,c,d).then(e.resolve,t=>{console.warn("[geometry] Pick failed",t),e.resolve(null)}):e.resolve(null)}async readTexels(){const e=this.renderer;if(!e)return null;const t=e.backend,r=t?.device,s=t?.get?.(this.pickTarget.texture)?.texture;if(this.webgpu&&r&&s){const{GPUBufferUsage:e,GPUMapMode:t}=globalThis,i=256,n=r.createBuffer({size:7*i,usage:e.COPY_DST|e.MAP_READ}),a=r.createCommandEncoder();a.copyTextureToBuffer({texture:s},{buffer:n,bytesPerRow:i},[7,7]),r.queue.submit([a.finish()]);try{return await n.mapAsync(t.READ),{data:new Float32Array(n.getMappedRange().slice(0)),stride:i/4,bottomUp:!1}}finally{n.destroy()}}const i=await e.readRenderTargetPixelsAsync(this.pickTarget,0,0,7,7);return{data:new Float32Array(i.buffer,i.byteOffset,i.byteLength/4),stride:28,bottomUp:!0}}async readPick(e,t,r,s,i,n){const a=await this.readTexels();if(!a)return null;const{data:o,stride:h,bottomUp:c}=a,d=[];for(let r=0;r<7;r++)for(let s=0;s<7;s++){const i=r*h+4*s,n=Math.round(o[i]);if(n<=0)continue;const a=s-3,l=c?3-r:r-3;d.push({source:n,index:Math.round(o[i+1]),w:o[i+2],x:e+a,y:t+l,d:a*a+l*l})}d.sort((e,t)=>e.d-t.d||e.w-t.w);for(const e of d){const t=this.pickSources.get(e.source)?.(e.index);if(null==t)continue;const a=unproject(i,(e.x+.5)/r*2-1,1-(e.y+.5)/s*2,e.w,-n[2]);return{hit:t,point:[a[0]+n[0],a[1]+n[1],a[2]+n[2]],source:e.source,index:e.index,distance:e.w}}return null}}export function unproject(e,t,r,s,i=0){const n=e.elements,a=e=>[n[e],n[4+e],n[8+e],n[12+e]],[o,h,c]=[a(0),a(1),a(3)];if(Math.abs(c[0])+Math.abs(c[1])+Math.abs(c[2])<1e-12){const[e,s,n,a]=[o[0],o[1],h[0],h[1]],[d,l]=[t*c[3]-o[3]-o[2]*i,r*c[3]-h[3]-h[2]*i],p=e*a-s*n;return[(d*a-s*l)/p,(e*l-d*n)/p,i]}const d=[[0,1,2].map(e=>o[e]-t*c[e]),[0,1,2].map(e=>h[e]-r*c[e]),[c[0],c[1],c[2]]],l=[t*c[3]-o[3],r*c[3]-h[3],s-c[3]],p=e=>e[0][0]*(e[1][1]*e[2][2]-e[1][2]*e[2][1])-e[0][1]*(e[1][0]*e[2][2]-e[1][2]*e[2][0])+e[0][2]*(e[1][0]*e[2][1]-e[1][1]*e[2][0]),u=p(d),m=[0,1,2].map(e=>p(d.map((t,r)=>t.map((t,s)=>s===e?l[r]:t)))/u);return[m[0],m[1],m[2]]}
|
|
1
|
+
import{AddEquation as e,Camera as t,Color as r,CustomBlending as s,DepthTexture as i,FloatType as n,LinearSRGBColorSpace as a,Matrix4 as o,NearestFilter as h,NoToneMapping as c,OneFactor as d,PostProcessing as l,RenderTarget as p,Scene as u,Vector2 as m,Vector3 as f,WebGPUCoordinateSystem as g,ZeroFactor as y}from"three/webgpu";import{pass as w,uniform as b}from"three/tsl";import{bloom as T}from"three/examples/jsm/tsl/display/BloomNode.js";import{TypedEventEmitter as x}from"../event/TypedEventEmitter.js";import{DensityMap as P}from"../three/DensityMap.js";import{Halo as k}from"../three/Halo.js";import{pickPassUniforms as R}from"./GeometryFrame.js";export class HostCamera extends t{updateProjectionMatrix(){}}export class GeometryEngine extends x{constructor(){super(),this.scene=new u,this.underlayScene=new u,this.bloomScene=new u,this.pickScene=new u,this.pickPass=R(),this.density=new P,this.halo=new k,this.camera=new HostCamera,this.lastRenderMs=0,this.frame={pxPerWorld:1,pixelRatio:1,near:.3,geocentric:!1,depth:!1,focal:1e3,orthographic:!0,width:1,height:1,eye:new f,time:0},this.bloom=null,this.renderer=null,this.ready=!1,this.disposed=!1,this.depthWanted=!1,this.bloomPost=null,this.bloomTarget=null,this.origins=new Map,this.drawn=new m,this.beforeRender=new Set,this.beforeDraw=new Set,this.pickSources=new Map,this.nextPickSource=1,this.pending=[],this.attached=new Map,this.unready=new Map,this.compiled=new WeakSet,this.compiling=new Set,this.startTime=performance.now(),this.drawnCamera=new o,this.pickTarget=new p(7,7,{type:n,depthBuffer:!0,generateMipmaps:!1,minFilter:h,magFilter:h}),this.depthUniforms={enabled:b(0),near:b(.3)},this.clearColor=new r,this.camera.matrixAutoUpdate=!1,this.camera.matrixWorldAutoUpdate=!1,this.scene.add(this.density.quad),this.underlayScene.add(this.halo.quad),this.depth=this.createDepthTexture(),this.sceneDepth={texture:this.depth,enabled:this.depthUniforms.enabled,near:this.depthUniforms.near}}createDepthTexture(){const e=new i(1,1,n);return e.minFilter=h,e.magFilter=h,e}getRenderer(){return this.renderer}get webgpu(){return this.renderer?.coordinateSystem===g}originKey(){return"world"}setOrigin(e,t,r=0){this.origins.set(this.originKey(),[e,t,r])}getOrigin(){return this.origins.get(this.originKey())??null}originFor(e){let t=this.getOrigin();return t||(this.setOrigin(e[0],e[1],e[2]??0),t=this.getOrigin()),t}depthTexture(){return this.depthWanted=!0,this.depth}onBeforeRender(e){return this.beforeRender.add(e),()=>{this.beforeRender.delete(e)}}onBeforeDraw(e){return this.beforeDraw.add(e),()=>{this.beforeDraw.delete(e)}}attach(e){if(this.attached.has(e))return;const t=[],r=e.passes();Object.keys(r).forEach(e=>{for(const s of r[e]??[])s&&(this.sceneOf(e).add(s),t.push({mesh:s,pass:e}),this.compiled.has(s)||this.unready.set(s,e))}),this.attached.set(e,{primitive:e,meshes:t}),e.setFrame(this.frame),this.requestRepaint()}detach(e){const t=this.attached.get(e);t&&(t.meshes.forEach(({mesh:e,pass:t})=>{this.sceneOf(t).remove(e),this.unready.delete(e)}),this.attached.delete(e),this.requestRepaint())}sceneOf(e){switch(e){case"scene":return this.scene;case"underlay":return this.underlayScene;case"bloom":return this.bloomScene;case"pick":return this.pickScene;case"density":return this.density.scene;case"halo":return this.halo.scene}}renderToTarget(e,t){const r=this.renderer;if(!r||!this.ready)return!1;const s=r.getRenderTarget();return r.setRenderTarget(t),this.clearToZero(r),r.render(e,this.camera),r.setRenderTarget(s),!0}clearToZero(e){e.getClearColor(this.clearColor);const t=e.getClearAlpha();e.setClearColor(0,0),e.clear(!0,!0,!0),e.setClearColor(this.clearColor,t)}addPickSource(e){const t=this.nextPickSource++;return this.pickSources.set(t,e),{id:t,remove:()=>{this.pickSources.delete(t)}}}pick(e,t){return new Promise(r=>{const s={x:e,y:t,resolve:r},i=setTimeout(()=>{this.pending=this.pending.filter(e=>e!==s),r(null)},1e3);s.resolve=e=>{clearTimeout(i),r(e)},this.ready&&this.renderer&&this.drawn.x>0?this.runPick(s,this.drawn.x,this.drawn.y):(this.pending.push(s),this.requestRepaint())})}dispose(){this.disposed=!0,this.missPicks(),[...this.attached.keys()].forEach(e=>this.detach(e)),this.pickTarget.dispose(),this.density.dispose(),this.halo.dispose(),this.depth.dispose();try{this.bloomPost?.dispose()}catch{}this.bloomPost=null;try{this.renderer?.dispose()}catch{}this.renderer=null,this.ready=!1}adoptRenderer(e){try{this.bloomPost?.dispose()}catch{}this.bloomPost=null,this.renderer=e,this.ready=!1,e.outputColorSpace=a,e.toneMapping=c,e.autoClear=!0,e.autoClearColor=!1,e.autoClearStencil=!1,this.createBloom(e)}createBloom(t){const r=w(this.bloomScene,this.camera);this.bloomTarget=r;const i=T(r,1.2,.5,0);this.bloom=i;const n=new(function(){const e=Object.getPrototypeOf(l);return"function"==typeof e&&e!==Function.prototype&&"function"==typeof e.prototype?.render?e:l}())(t,i);n.outputColorTransform=!1;const a=n._quadMesh.material;a.transparent=!0,a.blending=s,a.blendSrc=d,a.blendDst=d,a.blendEquation=e,a.blendSrcAlpha=y,a.blendDstAlpha=d,a.depthTest=!1,a.depthWrite=!1,this.bloomPost=n}updateCamera(e){const t=e.viewProjection,r=this.frame,{width:s,height:i}=e;r.width=s,r.height=i,r.pixelRatio=e.pixelRatio,r.near=e.near,r.geocentric=!!e.geocentric,r.pxPerWorld=e.pxPerWorld??Math.hypot(t[0]*s/2,t[4]*i/2);const n=e.orthographic??Math.abs(t[12])+Math.abs(t[13])+Math.abs(t[14])<1e-12;r.orthographic=n,r.focal=e.focal??(n?r.pxPerWorld:Math.hypot(t[0],t[1],t[2])*s/2),r.depth=this.depthWanted&&this.depthReady(),r.time=(performance.now()-this.startTime)/1e3,this.depthUniforms.near.value=e.near,this.depthUniforms.enabled.value=r.depth?1:0;const[a,o,h]=this.getOrigin()??[0,0,0];e.eye&&r.eye.set(e.eye[0]-a,e.eye[1]-o,(e.eye[2]??0)-h);const c=this.camera.projectionMatrix.elements;for(let e=0;e<4;e++)c[e]=t[4*e],c[4+e]=t[4*e+1],c[8+e]=t[4*e+2],c[12+e]=t[4*e]*a+t[4*e+1]*o+t[4*e+2]*h+t[4*e+3];if(e.glDepth&&this.webgpu)for(let e=0;e<4;e++)c[4*e+2]=.5*c[4*e+2]+.5*c[4*e+3];this.camera.projectionMatrixInverse.copy(this.camera.projectionMatrix).invert()}depthReady(){return!0}renderFrame(e,t){const r=this.renderer;if(this.lastRenderMs=0,!this.ready||!r)return!1;const s=performance.now();r._nodes?.nodeFrame?.update?.(),this.updateCamera(e),this.attached.forEach(({primitive:e})=>e.setFrame(this.frame)),this.beforeRender.forEach(e=>e(this.frame)),this.warmUp(r);const i=this.holdBack();try{return this.drawFrame(r,e,s,t)}finally{i.forEach(e=>{e.visible=!0})}}drawFrame(e,t,r,s){this.density.update();const i=e=>e.children.some(e=>e.visible);if(!i(this.scene)&&!i(this.underlayScene))return this.missPicks(),this.lastRenderMs=performance.now()-r,!1;if(s&&!s())return!1;this.beforeDraw.forEach(e=>e(t.width,t.height));const n=(e,t)=>{this.renderToTarget(e,t)};if(this.halo.draw(t.width,t.height,n),this.density.draw(t.width,t.height,n),this.drawn.set(t.width,t.height),this.drawnCamera.copy(this.camera.projectionMatrix),this.pending.length>0&&this.runPick(this.pending.shift(),t.width,t.height),i(this.underlayScene)&&e.render(this.underlayScene,this.camera),e.render(this.scene,this.camera),this.bloomPost&&i(this.bloomScene)){const t=this.bloomTarget?.renderTarget;if(t){const r=e.getRenderTarget();e.setRenderTarget(t),this.clearToZero(e),e.setRenderTarget(r)}this.bloomPost.render()}return this.lastRenderMs=performance.now()-r,this.emit("frame",{ms:this.lastRenderMs,width:t.width,height:t.height}),!0}warmUp(e){if(0===this.unready.size)return;if("function"!=typeof e.compileAsync)return void this.unready.clear();const t=[...this.unready].filter(([e])=>e.visible&&!this.compiling.has(e));0!==t.length&&(t.forEach(([e])=>this.compiling.add(e)),this.compile(e,t).catch(e=>console.warn("[geometry] Compiling in the background failed; drawn as it comes",e)).finally(()=>{t.forEach(([e])=>{this.compiling.delete(e),this.unready.delete(e),this.compiled.add(e)}),this.requestRepaint()}))}get compilingShaders(){return this.compiling.size>0}async compile(e,t){const r=[];for(const[s,i]of t){await M();const t=this.sceneOf(i);if(!this.renderer||!this.unready.has(s)||s.parent!==t)continue;const n=e.getRenderTarget();try{e.setRenderTarget(this.targetOf(i)),r.push(e.compileAsync(s,this.camera,t))}finally{e.setRenderTarget(n)}}await Promise.all(r)}targetOf(e){switch(e){case"scene":case"underlay":return null;case"bloom":return this.bloomTarget?.renderTarget??null;case"pick":return this.pickTarget;case"density":return this.density.target;case"halo":return this.halo.target}}holdBack(){const e=[];return this.unready.forEach((t,r)=>{r.visible&&(r.visible=!1,e.push(r))}),e}missPicks(){this.drawn.set(0,0);const e=this.pending;this.pending=[],e.forEach(e=>e.resolve(null))}runPick(e,t,r){this.pending.length>0&&this.requestRepaint();const s=Math.floor(e.x*this.frame.pixelRatio),i=Math.floor(e.y*this.frame.pixelRatio),n=(s+.5)/t*2-1,a=1-(i+.5)/r*2,o=t/7,h=r/7;this.pickPass.window.value.set(o,0,0,-n*o,0,h,0,-a*h,0,0,1,0,0,0,0,1),this.pickPass.origin.value.set(s-3,i-3),this.pickPass.frameSize.value.set(t,r);const c=this.drawnCamera.clone(),d=this.getOrigin()??[0,0,0];this.renderToTarget(this.pickScene,this.pickTarget)?this.readPick(s,i,t,r,c,d).then(e.resolve,t=>{console.warn("[geometry] Pick failed",t),e.resolve(null)}):e.resolve(null)}async readTexels(){const e=this.renderer;if(!e)return null;const t=e.backend,r=t?.device,s=t?.get?.(this.pickTarget.texture)?.texture;if(this.webgpu&&r&&s){const{GPUBufferUsage:e,GPUMapMode:t}=globalThis,i=256,n=r.createBuffer({size:7*i,usage:e.COPY_DST|e.MAP_READ}),a=r.createCommandEncoder();a.copyTextureToBuffer({texture:s},{buffer:n,bytesPerRow:i},[7,7]),r.queue.submit([a.finish()]);try{return await n.mapAsync(t.READ),{data:new Float32Array(n.getMappedRange().slice(0)),stride:i/4,bottomUp:!1}}finally{n.destroy()}}const i=await e.readRenderTargetPixelsAsync(this.pickTarget,0,0,7,7);return{data:new Float32Array(i.buffer,i.byteOffset,i.byteLength/4),stride:28,bottomUp:!0}}async readPick(e,t,r,s,i,n){const a=await this.readTexels();if(!a)return null;const{data:o,stride:h,bottomUp:c}=a,d=[];for(let r=0;r<7;r++)for(let s=0;s<7;s++){const i=r*h+4*s,n=Math.round(o[i]);if(n<=0)continue;const a=s-3,l=c?3-r:r-3;d.push({source:n,index:Math.round(o[i+1]),w:o[i+2],x:e+a,y:t+l,d:a*a+l*l})}d.sort((e,t)=>e.d-t.d||e.w-t.w);for(const e of d){const t=this.pickSources.get(e.source)?.(e.index);if(null==t)continue;const a=unproject(i,(e.x+.5)/r*2-1,1-(e.y+.5)/s*2,e.w,-n[2]);return{hit:t,point:[a[0]+n[0],a[1]+n[1],a[2]+n[2]],source:e.source,index:e.index,distance:e.w}}return null}}export function unproject(e,t,r,s,i=0){const n=e.elements,a=e=>[n[e],n[4+e],n[8+e],n[12+e]],[o,h,c]=[a(0),a(1),a(3)];if(Math.abs(c[0])+Math.abs(c[1])+Math.abs(c[2])<1e-12){const[e,s,n,a]=[o[0],o[1],h[0],h[1]],[d,l]=[t*c[3]-o[3]-o[2]*i,r*c[3]-h[3]-h[2]*i],p=e*a-s*n;return[(d*a-s*l)/p,(e*l-d*n)/p,i]}const d=[[0,1,2].map(e=>o[e]-t*c[e]),[0,1,2].map(e=>h[e]-r*c[e]),[c[0],c[1],c[2]]],l=[t*c[3]-o[3],r*c[3]-h[3],s-c[3]],p=e=>e[0][0]*(e[1][1]*e[2][2]-e[1][2]*e[2][1])-e[0][1]*(e[1][0]*e[2][2]-e[1][2]*e[2][0])+e[0][2]*(e[1][0]*e[2][1]-e[1][1]*e[2][0]),u=p(d),m=[0,1,2].map(e=>p(d.map((t,r)=>t.map((t,s)=>s===e?l[r]:t)))/u);return[m[0],m[1],m[2]]}function M(){const e=globalThis.scheduler;return"function"==typeof e?.yield?e.yield():new Promise(e=>setTimeout(e,0))}
|
package/package.json
CHANGED