@kineviz/gl 0.6.0 → 0.7.0
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/CHANGELOG.md +1270 -2
- package/LICENSE +201 -0
- package/NOTICE +33 -0
- package/README.md +201 -143
- package/dist/chunk-EDTCHJCZ.mjs +1504 -0
- package/dist/chunk-VTIPA7FV.mjs +2 -0
- package/dist/dist-BRW6S3SC.mjs +4 -0
- package/dist/index.d.mts +3493 -340
- package/dist/index.d.ts +3493 -340
- package/dist/index.js +960 -1315
- package/dist/index.mjs +911 -2770
- package/dist/kineviz-gl.umd.js +4014 -1916
- package/dist/layout-gpu.d.mts +1 -0
- package/dist/layout-gpu.d.ts +1 -0
- package/dist/layout-gpu.js +2328 -0
- package/dist/layout-gpu.mjs +903 -0
- package/dist/schemas.js +1 -1
- package/dist/schemas.mjs +1 -1
- package/dist/webgpu-YXDFF4ZT.mjs +2 -0
- package/package.json +32 -19
|
@@ -0,0 +1,2328 @@
|
|
|
1
|
+
"use strict";var Qn=Object.create;var Ve=Object.defineProperty;var Jn=Object.getOwnPropertyDescriptor;var ei=Object.getOwnPropertyNames;var ti=Object.getPrototypeOf,ni=Object.prototype.hasOwnProperty;var ii=(e,t)=>{for(var n in t)Ve(e,n,{get:t[n],enumerable:!0})},Rt=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ei(t))!ni.call(e,r)&&r!==n&&Ve(e,r,{get:()=>t[r],enumerable:!(i=Jn(t,r))||i.enumerable});return e};var pe=(e,t,n)=>(n=e!=null?Qn(ti(e)):{},Rt(t||!e||!e.__esModule?Ve(n,"default",{value:e,enumerable:!0}):n,e)),ri=e=>Rt(Ve({},"__esModule",{value:!0}),e);var Qr={};ii(Qr,{GPUForceLayoutController:()=>It,GPUForceLayoutEngine:()=>Wn,GPULayoutControllerAdapter:()=>Dt,WebGPUForceLayoutController:()=>ot,WebGPULayoutControllerAdapter:()=>st,createForceLayout:()=>Vn,isWebGPUAvailable:()=>Pe});module.exports=ri(Qr);function ai(e){var t=0,n=e.children,i=n&&n.length;if(!i)t=1;else for(;--i>=0;)t+=n[i].value;e.value=t}function Ut(){return this.eachAfter(ai)}function Lt(e,t){let n=-1;for(let i of this)e.call(t,i,++n,this);return this}function Gt(e,t){for(var n=this,i=[n],r,o,a=-1;n=i.pop();)if(e.call(t,n,++a,this),r=n.children)for(o=r.length-1;o>=0;--o)i.push(r[o]);return this}function Nt(e,t){for(var n=this,i=[n],r=[],o,a,s,l=-1;n=i.pop();)if(r.push(n),o=n.children)for(a=0,s=o.length;a<s;++a)i.push(o[a]);for(;n=r.pop();)e.call(t,n,++l,this);return this}function qt(e,t){let n=-1;for(let i of this)if(e.call(t,i,++n,this))return i}function Ot(e){return this.eachAfter(function(t){for(var n=+e(t.data)||0,i=t.children,r=i&&i.length;--r>=0;)n+=i[r].value;t.value=n})}function Ht(e){return this.eachBefore(function(t){t.children&&t.children.sort(e)})}function Xt(e){for(var t=this,n=oi(t,e),i=[t];t!==n;)t=t.parent,i.push(t);for(var r=i.length;e!==n;)i.splice(r,0,e),e=e.parent;return i}function oi(e,t){if(e===t)return e;var n=e.ancestors(),i=t.ancestors(),r=null;for(e=n.pop(),t=i.pop();e===t;)r=e,e=n.pop(),t=i.pop();return r}function Yt(){for(var e=this,t=[e];e=e.parent;)t.push(e);return t}function $t(){return Array.from(this)}function Zt(){var e=[];return this.eachBefore(function(t){t.children||e.push(t)}),e}function jt(){var e=this,t=[];return e.each(function(n){n!==e&&t.push({source:n.parent,target:n})}),t}function*Vt(){var e=this,t,n=[e],i,r,o;do for(t=n.reverse(),n=[];e=t.pop();)if(yield e,i=e.children)for(r=0,o=i.length;r<o;++r)n.push(i[r]);while(n.length)}function dt(e,t){e instanceof Map?(e=[void 0,e],t===void 0&&(t=ui)):t===void 0&&(t=li);for(var n=new we(e),i,r=[n],o,a,s,l;i=r.pop();)if((a=t(i.data))&&(l=(a=Array.from(a)).length))for(i.children=a,s=l-1;s>=0;--s)r.push(o=a[s]=new we(a[s])),o.parent=i,o.depth=i.depth+1;return n.eachBefore(ft)}function si(){return dt(this).eachBefore(ci)}function li(e){return e.children}function ui(e){return Array.isArray(e)?e[1]:null}function ci(e){e.data.value!==void 0&&(e.value=e.data.value),e.data=e.data.data}function ft(e){var t=0;do e.height=t;while((e=e.parent)&&e.height<++t)}function we(e){this.data=e,this.depth=this.height=0,this.parent=null}we.prototype=dt.prototype={constructor:we,count:Ut,each:Lt,eachAfter:Nt,eachBefore:Gt,find:qt,sum:Ot,sort:Ht,path:Xt,ancestors:Yt,descendants:$t,leaves:Zt,links:jt,copy:si,[Symbol.iterator]:Vt};function We(e){return e==null?null:di(e)}function di(e){if(typeof e!="function")throw new Error;return e}var fi={depth:-1},Wt={},pt={};function pi(e){return e.id}function hi(e){return e.parentId}function mt(){var e=pi,t=hi,n;function i(r){var o=Array.from(r),a=e,s=t,l,u,c,d,f,p,g,m,y=new Map;if(n!=null){let M=o.map((v,b)=>mi(n(v,b,r))),S=M.map(Kt),h=new Set(M).add("");for(let v of S)h.has(v)||(h.add(v),M.push(v),S.push(Kt(v)),o.push(pt));a=(v,b)=>M[b],s=(v,b)=>S[b]}for(c=0,l=o.length;c<l;++c)u=o[c],p=o[c]=new we(u),(g=a(u,c,r))!=null&&(g+="")&&(m=p.id=g,y.set(m,y.has(m)?Wt:p)),(g=s(u,c,r))!=null&&(g+="")&&(p.parent=g);for(c=0;c<l;++c)if(p=o[c],g=p.parent){if(f=y.get(g),!f)throw new Error("missing: "+g);if(f===Wt)throw new Error("ambiguous: "+g);f.children?f.children.push(p):f.children=[p],p.parent=f}else{if(d)throw new Error("multiple roots");d=p}if(!d)throw new Error("no root");if(n!=null){for(;d.data===pt&&d.children.length===1;)d=d.children[0],--l;for(let M=o.length-1;M>=0&&(p=o[M],p.data===pt);--M)p.data=null}if(d.parent=fi,d.eachBefore(function(M){M.depth=M.parent.depth+1,--l}).eachBefore(ft),d.parent=null,l>0)throw new Error("cycle");return d}return i.id=function(r){return arguments.length?(e=We(r),i):e},i.parentId=function(r){return arguments.length?(t=We(r),i):t},i.path=function(r){return arguments.length?(n=We(r),i):n},i}function mi(e){e=`${e}`;let t=e.length;return ht(e,t-1)&&!ht(e,t-2)&&(e=e.slice(0,-1)),e[0]==="/"?e:`/${e}`}function Kt(e){let t=e.length;if(t<2)return"";for(;--t>1&&!ht(e,t););return e.slice(0,t)}function ht(e,t){if(e[t]==="/"){let n=0;for(;t>0&&e[--t]==="\\";)++n;if((n&1)===0)return!0}return!1}function gi(e,t){return e.parent===t.parent?1:2}function gt(e){var t=e.children;return t?t[0]:e.t}function yt(e){var t=e.children;return t?t[t.length-1]:e.t}function yi(e,t,n){var i=n/(t.i-e.i);t.c-=i,t.s+=n,e.c+=i,t.z+=n,t.m+=n}function vi(e){for(var t=0,n=0,i=e.children,r=i.length,o;--r>=0;)o=i[r],o.z+=t,o.m+=t,t+=o.s+(n+=o.c)}function xi(e,t,n){return e.a.parent===t.parent?e.a:n}function Ke(e,t){this._=e,this.parent=null,this.children=null,this.A=null,this.a=this,this.z=0,this.m=0,this.c=0,this.s=0,this.t=null,this.i=t}Ke.prototype=Object.create(we.prototype);function bi(e){for(var t=new Ke(e,0),n,i=[t],r,o,a,s;n=i.pop();)if(o=n._.children)for(n.children=new Array(s=o.length),a=s-1;a>=0;--a)i.push(r=n.children[a]=new Ke(o[a],a)),r.parent=n;return(t.parent=new Ke(null,0)).children=[t],t}function vt(){var e=gi,t=1,n=1,i=null;function r(u){var c=bi(u);if(c.eachAfter(o),c.parent.m=-c.z,c.eachBefore(a),i)u.eachBefore(l);else{var d=u,f=u,p=u;u.eachBefore(function(S){S.x<d.x&&(d=S),S.x>f.x&&(f=S),S.depth>p.depth&&(p=S)});var g=d===f?1:e(d,f)/2,m=g-d.x,y=t/(f.x+g+m),M=n/(p.depth||1);u.eachBefore(function(S){S.x=(S.x+m)*y,S.y=S.depth*M})}return u}function o(u){var c=u.children,d=u.parent.children,f=u.i?d[u.i-1]:null;if(c){vi(u);var p=(c[0].z+c[c.length-1].z)/2;f?(u.z=f.z+e(u._,f._),u.m=u.z-p):u.z=p}else f&&(u.z=f.z+e(u._,f._));u.parent.A=s(u,f,u.parent.A||d[0])}function a(u){u._.x=u.z+u.parent.m,u.m+=u.parent.m}function s(u,c,d){if(c){for(var f=u,p=u,g=c,m=f.parent.children[0],y=f.m,M=p.m,S=g.m,h=m.m,v;g=yt(g),f=gt(f),g&&f;)m=gt(m),p=yt(p),p.a=u,v=g.z+S-f.z-y+e(g._,f._),v>0&&(yi(xi(g,u,d),u,v),y+=v,M+=v),S+=g.m,y+=f.m,h+=m.m,M+=p.m;g&&!yt(p)&&(p.t=g,p.m+=S-M),f&&!gt(m)&&(m.t=f,m.m+=y-h,d=u)}return d}function l(u){u.x*=t,u.y=u.depth*n}return r.separation=function(u){return arguments.length?(e=u,r):e},r.size=function(u){return arguments.length?(i=!1,t=+u[0],n=+u[1],r):i?null:[t,n]},r.nodeSize=function(u){return arguments.length?(i=!0,t=+u[0],n=+u[1],r):i?[t,n]:null},r}var Ue=pe(require("lodash"),1);var wi={value:()=>{}};function Jt(){for(var e=0,t=arguments.length,n={},i;e<t;++e){if(!(i=arguments[e]+"")||i in n||/[\s.]/.test(i))throw new Error("illegal type: "+i);n[i]=[]}return new Qe(n)}function Qe(e){this._=e}function _i(e,t){return e.trim().split(/^|\s+/).map(function(n){var i="",r=n.indexOf(".");if(r>=0&&(i=n.slice(r+1),n=n.slice(0,r)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:i}})}Qe.prototype=Jt.prototype={constructor:Qe,on:function(e,t){var n=this._,i=_i(e+"",n),r,o=-1,a=i.length;if(arguments.length<2){for(;++o<a;)if((r=(e=i[o]).type)&&(r=Si(n[r],e.name)))return r;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++o<a;)if(r=(e=i[o]).type)n[r]=Qt(n[r],e.name,t);else if(t==null)for(r in n)n[r]=Qt(n[r],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new Qe(e)},call:function(e,t){if((r=arguments.length-2)>0)for(var n=new Array(r),i=0,r,o;i<r;++i)n[i]=arguments[i+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(o=this._[e],i=0,r=o.length;i<r;++i)o[i].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var i=this._[e],r=0,o=i.length;r<o;++r)i[r].value.apply(t,n)}};function Si(e,t){for(var n=0,i=e.length,r;n<i;++n)if((r=e[n]).name===t)return r.value}function Qt(e,t,n){for(var i=0,r=e.length;i<r;++i)if(e[i].name===t){e[i]=wi,e=e.slice(0,i).concat(e.slice(i+1));break}return n!=null&&e.push({name:t,value:n}),e}var xt=Jt;var Ae=0,He=0,Oe=0,tn=1e3,Je,Xe,et=0,ze=0,tt=0,Ye=typeof performance=="object"&&performance.now?performance:Date,nn=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function wt(){return ze||(nn(Ti),ze=Ye.now()+tt)}function Ti(){ze=0}function bt(){this._call=this._time=this._next=null}bt.prototype=nt.prototype={constructor:bt,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?wt():+n)+(t==null?0:+t),!this._next&&Xe!==this&&(Xe?Xe._next=this:Je=this,Xe=this),this._call=e,this._time=n,Mt()},stop:function(){this._call&&(this._call=null,this._time=1/0,Mt())}};function nt(e,t,n){var i=new bt;return i.restart(e,t,n),i}function rn(){wt(),++Ae;for(var e=Je,t;e;)(t=ze-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Ae}function en(){ze=(et=Ye.now())+tt,Ae=He=0;try{rn()}finally{Ae=0,Bi(),ze=0}}function Pi(){var e=Ye.now(),t=e-et;t>tn&&(tt-=t,et=e)}function Bi(){for(var e,t=Je,n,i=1/0;t;)t._call?(i>t._time&&(i=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:Je=n);Xe=e,Mt(i)}function Mt(e){if(!Ae){He&&(He=clearTimeout(He));var t=e-ze;t>24?(e<1/0&&(He=setTimeout(en,e-Ye.now()-tt)),Oe&&(Oe=clearInterval(Oe))):(Oe||(et=Ye.now(),Oe=setInterval(Pi,tn)),Ae=1,nn(en))}}function be(e){let t=0,n=0,i=0,r=0;for(let[,o]of e)t+=o[0],n+=o[1],i+=o[2],r++;return r===0?[0,0,0]:[t/r,n/r,i/r]}var Se=1;function xe(e,t){let n=new Map;for(let i=0;i<e.nodes.length;i++)n.set(e.nodes[i].id,t[i]);return{positions:n}}function an(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=be(e.positions),r=t?.spacing??Se,o=t?.radius??Math.max(r,n*r/(2*Math.PI)),a=Math.PI*2/n,s=[];for(let l=0;l<n;l++)s.push([o*Math.cos(l*a)+i[0],o*Math.sin(l*a)+i[1],0]);return xe(e,s)}function on(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=be(e.positions),r=t?.columns&&t.columns>0?t.columns:Math.ceil(Math.sqrt(n)),o=t?.spacing??Se,a=o*(r-1),s=[];for(let l=0;l<n;l++)s.push([l%r*o-a/2+i[0],-Math.floor(l/r)*o+a/2+i[1],0]);return xe(e,s)}function sn(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=be(e.positions),r=t?.axis??"x",o=t?.spacing??Se,a=o*(n-1),s=[];for(let l=0;l<n;l++){let u=n>1?-a/2+l*o:0,c=[i[0],i[1],i[2]],d=r==="x"?0:r==="y"?1:2;c[d]=u+i[d],s.push(c)}return xe(e,s)}function ln(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=be(e.positions),r=t?.spacing??1.5,o=r/(2*Math.PI),a=2*Math.PI,s=[];for(let l=0;l<n;l++){let u=o*a;s.push([u*Math.cos(a)+i[0],u*Math.sin(a)+i[1],0]),a+=r/u}return xe(e,s)}function un(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=be(e.positions),r=Math.cbrt(n),o=Math.floor(r),a=Math.ceil(r),s=t?.size??(n-Math.pow(o,3)>Math.pow(a,3)-n?a:o),l=t?.spacing??Se,u=l*Math.max(s-1,0),c=[];for(let d=0;d<n;d++)c.push([d%s*l-u/2+i[0],-(Math.floor(d/s)%s)*l+u/2+i[1],-Math.floor(d/(s*s))*l+u/2+i[2]]);return xe(e,c)}function cn(e,t){let n=e.nodes.length;if(n<=1){let l=new Map;return n===1&&l.set(e.nodes[0].id,e.positions.get(e.nodes[0].id)??[0,0,0]),{positions:l}}let i=be(e.positions),r=t?.spacing??Se,o=t?.density!==void 0?Math.sqrt(n/(4*Math.PI*t.density)):r*Math.sqrt(n/(4*Math.PI)),a=t?.radius??Math.max(r,o),s=[];for(let l=0;l<n;l++){let u=Math.acos(1-(2*(l+1)-1)/n),c=Math.sqrt(n*Math.PI)*u;s.push([a*Math.sin(u)*Math.cos(c)+i[0],a*Math.sin(u)*Math.sin(c)+i[1],a*Math.cos(u)+i[2]])}return xe(e,s)}function dn(e,t){let n=e.nodes.length;if(n===0)return{positions:new Map};let i=t?.spacing??Se,r=t?.range??Math.max(i,i*Math.cbrt(n)/2),o=t?.seed??42;function a(){o|=0,o=o+1831565813|0;let l=Math.imul(o^o>>>15,1|o);return l=l+Math.imul(l^l>>>7,61|l)^l,((l^l>>>14)>>>0)/4294967296}let s=[];for(let l=0;l<n;l++)s.push([(a()-.5)*r*2,(a()-.5)*r*2,(a()-.5)*r*2]);return xe(e,s)}function fn(e,t){if(e.nodes.length===0)return{positions:new Map};let i=t?.axis??"x",r=(t?.degrees??90)*Math.PI/180,o=be(e.positions),a=[];for(let s of e.nodes){let l=e.positions.get(s.id)??[0,0,0],u=l[0]-o[0],c=l[1]-o[1],d=l[2]-o[2],f,p,g,m=Math.cos(r),y=Math.sin(r);i==="x"?(f=u,p=c*m-d*y,g=c*y+d*m):i==="y"?(f=u*m+d*y,p=c,g=-u*y+d*m):(f=u*m-c*y,p=u*y+c*m,g=d),a.push([f+o[0],p+o[1],g+o[2]])}return xe(e,a)}function pn(e,t){if(e.nodes.length===0)return{positions:new Map};let i=t?.factor,r=i??t?.x??1,o=i??t?.y??1,a=i??t?.z??1,s=be(e.positions),l=[];for(let u of e.nodes){let c=e.positions.get(u.id)??[0,0,0];l.push([c[0]+(c[0]-s[0])*(r-1),c[1]+(c[1]-s[1])*(o-1),c[2]+(c[2]-s[2])*(a-1)])}return xe(e,l)}function hn(e,t){if(e.nodes.length===0)return{positions:new Map};let i=t?.x??0,r=t?.y??0,o=t?.z??0,a=[];for(let s of e.nodes){let l=e.positions.get(s.id)??[0,0,0];a.push([l[0]+i,l[1]+r,l[2]+o])}return xe(e,a)}function mn(e,t){if(e.nodes.length===0)return{positions:new Map};let i=t?.axis??"x",r=i==="x"?0:i==="y"?1:2,o=1/0,a=-1/0;for(let u of e.nodes){let c=e.positions.get(u.id)??[0,0,0];c[r]<o&&(o=c[r]),c[r]>a&&(a=c[r])}let s=(o+a)/2,l=[];for(let u of e.nodes){let c=e.positions.get(u.id)??[0,0,0],d=[c[0],c[1],c[2]];d[r]=s,l.push(d)}return xe(e,l)}function gn(e,t){let{depth:n=100,mode:i="tree",orientation:r="right",alongRelationships:o=[]}=t??{},a=t?.spacing??Se,s=t?.spacing===void 0?t?.edgeLength:void 0,l=e.nodes;if(l.length===0)return{positions:new Map};let u=new Set;for(let[x]of e.positions)u.add(x);let c=new Map,d=new Map;for(let x of e.edges)!u.has(x.source)||!u.has(x.target)||(d.set(x.id,x),c.has(x.source)||c.set(x.source,[]),c.has(x.target)||c.set(x.target,[]),c.get(x.source).push({nodeId:x.target,relationship:x.relationship}),c.get(x.target).push({nodeId:x.source,relationship:x.relationship}));let f=o.length>0?new Set(Array.from(c.entries()).filter(([,x])=>x.some(({relationship:E})=>o.includes(E))).map(([x])=>x)):u,p=l.filter(x=>f.has(x.id));if(p.length===0)return{positions:new Map};let g=new Map,m=p.map(x=>[{from:"",to:x.id}]),y=p.map(x=>[[x.id]]),M=p.map(()=>1),S=p.map(()=>[1]),h=p.map(x=>x.id),v=1;for(;v<=n&&Ue.sum(y.map(x=>x[v-1]?.length??0))>0;)y.forEach((x,E)=>{let F=x[v-1];if(!F)return;let R=[];F.forEach(A=>{let I=c.get(A)??[],L=I.map(({nodeId:B})=>B);o.length>0&&(L=I.filter(({relationship:B})=>o.includes(B)).map(({nodeId:B})=>B)),L=Ue.difference(Ue.intersection(L,Array.from(f)),h),L.forEach(B=>{m[E].push({from:A,to:B}),R.push(B),h.push(B)})}),x[v]=R,R.length>0&&(S[E].push(R.length),M[E]++)}),v++;let b=mt().id(x=>x.to).parentId(x=>x.from||null);return p.forEach((x,E)=>{let F=e.positions.get(x.id)??[0,0,0];if(m[E].length<=1){g.set(x.id,[F[0],F[1],F[2]]);return}let R;try{R=b(m[E])}catch{g.set(x.id,[F[0],F[1],F[2]]);return}let A=Math.max(...S[E],1),I=Math.max(M[E]-1,1),L=Math.max(A-1,1),B,k;i==="rings"?(B=2*Math.PI,s!==void 0?k=s*I:k=Math.max(a,a*A/(2*Math.PI))):s!==void 0?(B=s*A*.2*Math.pow(M[E],.3),k=s*I):(B=a*L,k=a*I);let z=vt().size([B,k])(R);yn(i,r,z,z,F,g)}),{positions:g}}function yn(e,t,n,i,r,o){let a=i.id,s,l;if(e==="tree")switch(t){case"up":s=i.x+r[0]-n.x,l=i.y+r[1]+n.y;break;case"down":s=-i.x+r[0]+n.x,l=-i.y+r[1]-n.y;break;case"right":s=i.y+r[0]-n.y,l=-i.x+r[1]+n.x;break;case"left":s=-i.y+r[0]+n.y,l=i.x+r[1]-n.x;break}else switch(t){case"down":s=r[0]+i.y*Math.cos(i.x+Math.PI/2),l=r[1]+i.y*Math.sin(i.x+Math.PI/2);break;case"up":s=r[0]+i.y*Math.cos(i.x+3*Math.PI/2),l=r[1]+i.y*Math.sin(i.x+3*Math.PI/2);break;case"right":s=r[0]+i.y*Math.cos(i.x+Math.PI),l=r[1]+i.y*Math.sin(i.x+Math.PI);break;case"left":s=r[0]+i.y*Math.cos(i.x),l=r[1]+i.y*Math.sin(i.x);break}if(o.set(a,[s,l,r[2]]),i.children)for(let u of i.children)yn(e,t,n,u,r,o)}function _e(e){if(e==null)return null;let t=Number(e);return Number.isNaN(t)?null:t}function Ce(e,t,n){let[i,r]=t,[o,a]=n;return r===i?(o+a)/2:o+(e-i)/(r-i)*(a-o)}function ke(e,t,n){let i=Math.max(t[0],1e-10),r=Math.max(t[1],1e-10),o=Math.max(e,1e-10),[a,s]=n;return r===i?(a+s)/2:a+(Math.log(o)-Math.log(i))/(Math.log(r)-Math.log(i))*(s-a)}function vn(e,t,n){let i=n??_e,r=1/0,o=-1/0;for(let a of e){let s=a.properties?.[t],l=i(s);l!=null&&(l<r&&(r=l),l>o&&(o=l))}return r===1/0?[0,1]:r===o?[r-1,o+1]:[r,o]}function xn(e,t=5){let[n,i]=e,r=i-n;if(r===0)return[n-1,i+1];let o=r/t,a=Math.pow(10,Math.floor(Math.log10(o))),s=o/a,l;return s<=1.5?l=a:s<=3.5?l=2*a:s<=7.5?l=5*a:l=10*a,[Math.floor(n/l)*l,Math.ceil(i/l)*l]}function bn(e,t=5){let[n,i]=e;if(n===i)return[n];let o=(i-n)/t,a=Math.pow(10,Math.floor(Math.log10(o))),s=o/a,l;s<=1.5?l=a:s<=3.5?l=2*a:s<=7.5?l=5*a:l=10*a;let u=Math.ceil(n/l)*l,c=[];for(let d=u;d<=i+l*.001;d+=l)c.push(Math.round(d*1e10)/1e10);return c}var _t=[{name:"1s",ms:1e3},{name:"5s",ms:5e3},{name:"15s",ms:15e3},{name:"30s",ms:3e4},{name:"1m",ms:6e4},{name:"5m",ms:3e5},{name:"15m",ms:9e5},{name:"30m",ms:18e5},{name:"1h",ms:36e5},{name:"3h",ms:108e5},{name:"6h",ms:216e5},{name:"12h",ms:432e5},{name:"1d",ms:864e5},{name:"3d",ms:2592e5},{name:"1w",ms:6048e5},{name:"1mo",ms:2592e6,calendarUnit:"month",calendarStep:1},{name:"3mo",ms:7776e6,calendarUnit:"month",calendarStep:3},{name:"6mo",ms:15552e6,calendarUnit:"month",calendarStep:6},{name:"1y",ms:31536e6,calendarUnit:"year",calendarStep:1},{name:"2y",ms:63072e6,calendarUnit:"year",calendarStep:2},{name:"5y",ms:15768e7,calendarUnit:"year",calendarStep:5},{name:"10y",ms:31536e7,calendarUnit:"year",calendarStep:10},{name:"20y",ms:63072e7,calendarUnit:"year",calendarStep:20},{name:"50y",ms:15768e8,calendarUnit:"year",calendarStep:50}];function Mn(e,t=5){let[n,i]=e,r=i-n;if(r<=0)return[n];let o=r/t,a=_t[_t.length-1];for(let l of _t)if(l.ms>=o*.6){a=l;break}let s=[];if(a.calendarUnit==="year"){let l=a.calendarStep,u=new Date(n),c=Math.ceil(u.getFullYear()/l)*l;for(;;){let d=new Date(c,0,1).getTime();if(d>i)break;d>=n&&s.push(d),c+=l}}else if(a.calendarUnit==="month"){let l=a.calendarStep,u=new Date(n),c=u.getFullYear(),d=Math.ceil(u.getMonth()/l)*l;for(;;){let f=new Date(c,d,1).getTime();if(f>i)break;f>=n&&s.push(f),d+=l,d>=12&&(c+=Math.floor(d/12),d=d%12)}}else{let l=a.ms,u=Math.ceil(n/l)*l;for(let c=u;c<=i;c+=l)s.push(c)}return s}function wn(e,t){let n=t[1]-t[0],i=new Date(e);return n>365*864e5*2?String(i.getFullYear()):n>60*864e5?`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}`:n>2*864e5?`${i.getMonth()+1}/${i.getDate()}`:n>2*36e5?`${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}`:`${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}:${String(i.getSeconds()).padStart(2,"0")}`}function Re(e,t,n){let i=e.domain??vn(t,e.property,e.parse);e.nice&&!e.domain&&(i=xn(i,e.tickCount));let o=(i[1]-i[0])*n,a=[i[0]-o,i[1]+o],s;e.tickValues?s=e.tickValues:e.isDate?s=Mn(i,e.tickCount):s=bn(i,e.tickCount);let l=e.tickFormat;return!l&&e.isDate&&(l=u=>wn(u,i)),{axisInfo:{property:e.property,label:e.property,domain:a,ticks:s,scale:e.scale,tickFormat:l},paddedDomain:a}}function _n(e,t){let{propertyX:n,propertyY:i,propertyZ:r,range:o=[-2,2],scaleX:a="linear",scaleY:s="linear",scaleZ:l="linear",padding:u=.05}=t,c=t.parseX??_e,d=t.parseY??_e,f=t.parseZ??_e,p=!!n,g=!!i,m=!!r,y=e.nodes,M=new Map,S=new Set,h=[];for(let B of y){let k=0,w=0,z=0,P=!1;if(p){let T=c(B.properties?.[n]);T==null?P=!0:k=T}if(g&&!P){let T=d(B.properties?.[i]);T==null?P=!0:w=T}if(m&&!P){let T=f(B.properties?.[r]);T==null?P=!0:z=T}P?S.add(B.id):h.push({id:B.id,x:k,y:w,z})}let v=p?Re({property:n,scale:a,domain:t.domainX,parse:c,tickFormat:t.tickFormatX,tickCount:t.tickCountX??5,tickValues:t.tickValuesX,nice:t.niceX??!0,isDate:t.dateAxisX??!1},y,u):null,b=g?Re({property:i,scale:s,domain:t.domainY,parse:d,tickFormat:t.tickFormatY,tickCount:t.tickCountY??5,tickValues:t.tickValuesY,nice:t.niceY??!0,isDate:t.dateAxisY??!1},y,u):null,x=m?Re({property:r,scale:l,domain:t.domainZ,parse:f,tickFormat:t.tickFormatZ,tickCount:t.tickCountZ??5,tickValues:t.tickValuesZ,nice:t.niceZ??!0,isDate:t.dateAxisZ??!1},y,u):null,E=a==="log"?ke:Ce,F=s==="log"?ke:Ce,R=l==="log"?ke:Ce,A=t.spread??1,I=[o[0]*A,o[1]*A],L=o[0];for(let B of h){let k=v?E(B.x,v.paddedDomain,I):L,w=b?F(B.y,b.paddedDomain,I):L,z=x?R(B.z,x.paddedDomain,I):0;M.set(B.id,[k,w,z])}return{positions:M,axes:{x:v?.axisInfo,y:b?.axisInfo,z:x?.axisInfo},range:I,baseRange:o,excludedNodeIds:S}}function Sn(e,t){let n=t.range??[-2,2],i=t.spread??1,r=[n[0]*i,n[1]*i],o=t.padding??.05,a=n[0],s=t.unmappedMode??"hide",l=new Map;for(let p of t.mappings)l.set(p.category,p);let u=new Map;for(let p of e.nodes){let g=p.category,m=u.get(g);m||(m=[],u.set(g,m)),m.push(p)}let c=new Map,d=new Set,f={};for(let[p,g]of u){let m=l.get(p);if(!m){if(s==="hide")for(let G of g)d.add(G.id);else{let G;s==="boundary"?G=n[0]:G=(n[0]+n[1])/2;for(let _ of g)c.set(_.id,[G,G,0])}continue}let y=!!m.propertyX,M=!!m.propertyY,S=!!m.propertyZ,h=m.scaleX??"linear",v=m.scaleY??"linear",b=m.scaleZ??"linear",x=m.parseX??_e,E=m.parseY??_e,F=m.parseZ??_e,R=m.tickCountX??t.tickCountX??5,A=m.tickCountY??t.tickCountY??5,I=m.tickCountZ??t.tickCountZ??5,L=m.niceX??t.niceX??!0,B=m.niceY??t.niceY??!0,k=m.niceZ??t.niceZ??!0,w=[];for(let G of g){let _=0,D=0,O=0,Y=!1;if(y){let X=x(G.properties?.[m.propertyX]);X==null?Y=!0:_=X}if(M&&!Y){let X=E(G.properties?.[m.propertyY]);X==null?Y=!0:D=X}if(S&&!Y){let X=F(G.properties?.[m.propertyZ]);X==null?Y=!0:O=X}Y?d.add(G.id):w.push({id:G.id,x:_,y:D,z:O})}let z=y?Re({property:m.propertyX,scale:h,domain:m.domainX,parse:x,tickFormat:m.tickFormatX,tickCount:R,tickValues:m.tickValuesX,nice:L,isDate:m.dateAxisX??!1},g,o):null,P=M?Re({property:m.propertyY,scale:v,domain:m.domainY,parse:E,tickFormat:m.tickFormatY,tickCount:A,tickValues:m.tickValuesY,nice:B,isDate:m.dateAxisY??!1},g,o):null,T=S?Re({property:m.propertyZ,scale:b,domain:m.domainZ,parse:F,tickFormat:m.tickFormatZ,tickCount:I,tickValues:m.tickValuesZ,nice:k,isDate:m.dateAxisZ??!1},g,o):null,C=h==="log"?ke:Ce,q=v==="log"?ke:Ce,N=b==="log"?ke:Ce;for(let G of w){let _=z?C(G.x,z.paddedDomain,r):a,D=P?q(G.y,P.paddedDomain,r):a,O=T?N(G.z,T.paddedDomain,r):0;c.set(G.id,[_,D,O])}f[p]={x:z?.axisInfo,y:P?.axisInfo,z:T?.axisInfo}}return{positions:c,axes:{x:void 0,y:void 0,z:void 0},range:r,baseRange:n,excludedNodeIds:d,categoryAxes:f}}var zi=/^[a-z][a-zA-Z0-9]*$/,Ci=/^[a-z][a-z0-9-]*:[A-Za-z][A-Za-z0-9_-]*$/,Tn=class Pn{constructor(){this.entries=new Map}register(t,n,i={}){if(!Ci.test(t))throw new Error(`[LayoutRegistry] invalid layout name "${t}": extension layouts must be named "<pack>:<name>" (e.g. "acme:rack")`);return this.add(t,n,!1,i)}registerBuiltin(t,n,i){if(!zi.test(t))throw new Error(`[LayoutRegistry] invalid built-in layout name "${t}"`);this.add(t,n,!0,{description:i})}add(t,n,i,r){if(typeof n!="function")throw new Error(`[LayoutRegistry] layout "${t}" must be a function`);let o=this.entries.get(t);if(o&&(o.builtin||!r.replace))throw new Error(`[LayoutRegistry] layout "${t}" is already registered`);let a={name:t,fn:n,builtin:i,description:r.description};return this.entries.set(t,a),()=>{this.entries.get(t)===a&&this.entries.delete(t)}}has(t){return this.entries.has(t)}get(t){return this.entries.get(t)}list(){let t=[...this.entries.values()];return[...t.filter(n=>n.builtin),...t.filter(n=>!n.builtin)]}execute(t,n,i){let r=this.entries.get(t);if(!r)throw new Error(`[LayoutRegistry] unknown layout "${t}". Registered: ${[...this.entries.keys()].join(", ")}`);return r.fn(n,i)}fork(){let t=new Pn;for(let[n,i]of this.entries)t.entries.set(n,i);return t}};function ki(){let e=new Tn;return e.registerBuiltin("circle",an,"Nodes on a circle."),e.registerBuiltin("grid",on,"Nodes on a 2-D grid."),e.registerBuiltin("line",sn,"Nodes along an axis."),e.registerBuiltin("spiral",ln,"Nodes on a spiral."),e.registerBuiltin("cube",un,"Nodes in a 3-D lattice."),e.registerBuiltin("sphere",cn,"Nodes on a sphere."),e.registerBuiltin("scatter",dn,"Nodes scattered randomly in a range."),e.registerBuiltin("ego",gn,"Tree or rings around root node(s)."),e.registerBuiltin("rotate",fn,"Rotate current positions (transform)."),e.registerBuiltin("scale",pn,"Scale current positions (transform)."),e.registerBuiltin("shift",hn,"Translate current positions (transform)."),e.registerBuiltin("alignBy",mn,"Align nodes by an axis (transform)."),e.registerBuiltin("plotScatter",_n,"Scatter plot by two properties."),e.registerBuiltin("plotMultiCategoryScatter",Sn,"Scatter plot with category axes."),e}var Ei=ki();var re=pe(require("three"),1);function Pe(){return typeof navigator<"u"&&!!navigator.gpu}async function En(e={}){if(!Pe())throw new Error("WebGPU not available: navigator.gpu is undefined. Use the WebGL backend instead.");let t=await navigator.gpu.requestAdapter({powerPreference:e.preferHighPerformance===!1?"low-power":"high-performance"});if(!t)throw new Error("WebGPU adapter request returned null (no compatible adapter found).");let i=(e.requestedFeatures??[]).filter(o=>t.features.has(o)),r=await t.requestDevice({requiredFeatures:i});return{adapter:t,device:r,features:new Set(t.features),limits:t.limits}}function Ct(e){if(e<=0)return 1;let t=Math.ceil(Math.sqrt(e));return Math.pow(2,Math.ceil(Math.log2(t)))}function Ne(e,t,n=10){if(e<=0)return n;let i;return t===3?i=Math.cbrt(e)*2:i=Math.sqrt(e)*.5,Math.max(n,i)}function Fi(){return{type:re.FloatType,format:re.RGBAFormat,minFilter:re.NearestFilter,magFilter:re.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1}}function Ee(e){let t=Fi();return new re.WebGLRenderTarget(e,e,t)}function qe(e,t){let n=new re.DataTexture(e,t,t,re.RGBAFormat,re.FloatType);return n.minFilter=re.NearestFilter,n.magFilter=re.NearestFilter,n.needsUpdate=!0,n}function Fn(e){let t=[];for(let n=0;n<e;n++)for(let i=0;i<e;i++)t.push(i,n);return new Float32Array(t)}function ye(){return new re.PlaneGeometry(2,2)}function In(e=1){let r=e;return function(){return r=(1664525*r+1013904223)%4294967296,r/4294967296}}function at(e){return(e()-.5)*1e-6}function te(e){return()=>e}function Ze(e,t,n){let i=e.length,r=10,o=Math.PI*(3-Math.sqrt(5)),a=Math.PI*20/(9+Math.sqrt(221));for(let s=0;s<i;s++){let l=e[s];if(l.index=s,l.fx!=null&&(l.x=l.fx),l.fy!=null&&(l.y=l.fy),l.fz!=null&&(l.z=l.fz),isNaN(l.x)||t>1&&isNaN(l.y)||t>2&&isNaN(l.z)){let u=r*(t>2?Math.cbrt(.5+s):t>1?Math.sqrt(.5+s):s),c=s*o,d=s*a;t===1?l.x=u:t===2?(l.x=u*Math.cos(c),l.y=u*Math.sin(c)):(l.x=u*Math.sin(c)*Math.cos(d),l.y=u*Math.cos(c),l.z=u*Math.sin(c)*Math.sin(d))}(isNaN(l.vx)||t>1&&isNaN(l.vy)||t>2&&isNaN(l.vz))&&(l.vx=0,t>1&&(l.vy=0),t>2&&(l.vz=0))}}function Dn(e,t){let n=t*t,i=new Float32Array(n*4);for(let r=0;r<e.length;r++){let o=e[r],a=r*4;i[a]=o.x||0,i[a+1]=o.y||0,i[a+2]=o.z||0,i[a+3]=r}return i}function An(e,t){let n=t*t,i=new Float32Array(n*4);for(let r=0;r<e.length;r++){let o=e[r],a=r*4;i[a]=o.vx||0,i[a+1]=o.vy||0,i[a+2]=o.vz||0,i[a+3]=0}return i}function Rn(e,t){let n=t*t,i=new Float32Array(n*4);for(let r=0;r<e.length;r++){let o=e[r],a=r*4;i[a]=o.fx!=null||o.fy!=null||o.fz!=null?1:0,i[a+1]=0,i[a+2]=0,i[a+3]=0}return i}function Un(e,t,n){for(let i=0;i<e.length;i++){let r=e[i],o=i*4;r.fx==null&&(r.x=t[o]),n>1&&r.fy==null&&(r.y=t[o+1]),n>2&&r.fz==null?r.z=t[o+2]:n<=2&&(r.z=0)}}var Ii=`// Position integration compute shader.
|
|
2
|
+
//
|
|
3
|
+
// One invocation per node. Reads accumulated velocity, applies velocityDecay,
|
|
4
|
+
// CLAMPS velocity magnitude to maxVel (matches WebGL FBO path's
|
|
5
|
+
// \`update-position.frag.glsl\`), updates position, masks out unused dimensions,
|
|
6
|
+
// and writes both buffers back. Pinned nodes (pinned[i] > 0.5) keep their
|
|
7
|
+
// position unchanged.
|
|
8
|
+
//
|
|
9
|
+
// Why the velocity clamp matters: WebGL's update-position.frag.glsl caps
|
|
10
|
+
// per-tick velocity to \`spaceSize * 0.1\` (\u22481.6 units/tick for N\u2248500 in 3D).
|
|
11
|
+
// Without this clamp the WebGPU layout's initial frames let nodes overshoot
|
|
12
|
+
// the equilibrium massively \u2014 outer phyllotaxis-init nodes (radius up to 83
|
|
13
|
+
// for N=578) feel strong gravity and accelerate dozens of units per tick,
|
|
14
|
+
// blowing the layout out to thousands of units before charge can stabilize.
|
|
15
|
+
// Net visual: layout extent 100\xD7 wider than WebGL \u2192 nodes shrink to single
|
|
16
|
+
// pixels in the auto-fit camera frame.
|
|
17
|
+
//
|
|
18
|
+
// Layout \u2014 kept identical across all WebGPU force compute shaders for shared
|
|
19
|
+
// bind group reuse:
|
|
20
|
+
// group(0)
|
|
21
|
+
// binding(0) positions array<vec4<f32>> read_write
|
|
22
|
+
// binding(1) velocities array<vec4<f32>> read_write
|
|
23
|
+
// binding(2) pinned array<f32> read
|
|
24
|
+
// binding(3) params IntegrateParams uniform
|
|
25
|
+
|
|
26
|
+
struct IntegrateParams {
|
|
27
|
+
velocityDecay: f32,
|
|
28
|
+
nDim: f32,
|
|
29
|
+
nodeCount: f32,
|
|
30
|
+
maxVel: f32, // 0 = no clamp; >0 = cap per-tick |v|
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
@group(0) @binding(0) var<storage, read_write> positions: array<vec4<f32>>;
|
|
34
|
+
@group(0) @binding(1) var<storage, read_write> velocities: array<vec4<f32>>;
|
|
35
|
+
@group(0) @binding(2) var<storage, read> pinned: array<f32>;
|
|
36
|
+
@group(0) @binding(3) var<uniform> params: IntegrateParams;
|
|
37
|
+
|
|
38
|
+
@compute @workgroup_size(64)
|
|
39
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
40
|
+
let i = gid.x;
|
|
41
|
+
if (f32(i) >= params.nodeCount) { return; }
|
|
42
|
+
|
|
43
|
+
if (pinned[i] > 0.5) {
|
|
44
|
+
// Pinned nodes: zero out any accumulated velocity but keep position.
|
|
45
|
+
velocities[i] = vec4<f32>(0.0, 0.0, 0.0, 0.0);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// d3-force per-tick: vx *= velocityDecay; x += vx.
|
|
50
|
+
var v: vec3<f32> = velocities[i].xyz * params.velocityDecay;
|
|
51
|
+
|
|
52
|
+
// Clamp velocity magnitude to maxVel (when maxVel > 0). Mirrors WebGL.
|
|
53
|
+
// CRITICAL: the clamp only affects POSITION update this tick; the stored
|
|
54
|
+
// velocity must remain unclamped so momentum can build across ticks (this
|
|
55
|
+
// matches the legacy WebGL FBO pipeline where update-position.frag.glsl
|
|
56
|
+
// clamps its local copy but velocity-decay.frag.glsl's output to the
|
|
57
|
+
// velocity texture is NEVER overwritten by update-position). If we clamp
|
|
58
|
+
// the stored velocity too, every tick the integrator throws away most of
|
|
59
|
+
// the accumulated velocity from forces and nodes barely move from their
|
|
60
|
+
// phyllotaxis initial positions.
|
|
61
|
+
var posDelta: vec3<f32> = v;
|
|
62
|
+
if (params.maxVel > 0.0) {
|
|
63
|
+
let mag = length(posDelta);
|
|
64
|
+
if (mag > params.maxVel) {
|
|
65
|
+
posDelta = posDelta * (params.maxVel / mag);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
var p: vec3<f32> = positions[i].xyz + posDelta;
|
|
70
|
+
|
|
71
|
+
// Mask unused dimensions (2D simulation: zero out z; 1D: also y).
|
|
72
|
+
if (params.nDim < 3.0) {
|
|
73
|
+
p.z = 0.0;
|
|
74
|
+
v.z = 0.0;
|
|
75
|
+
}
|
|
76
|
+
if (params.nDim < 2.0) {
|
|
77
|
+
p.y = 0.0;
|
|
78
|
+
v.y = 0.0;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
positions[i] = vec4<f32>(p, positions[i].w);
|
|
82
|
+
// Store the decayed-but-UNCLAMPED velocity so momentum carries to next tick.
|
|
83
|
+
velocities[i] = vec4<f32>(v, 0.0);
|
|
84
|
+
}
|
|
85
|
+
`,Le=16,Ge=16,Bn=4,Di=16,Ai=64;function Ln(e,t=3,n={}){let i=e,r=i.length,o=t,a=1,s=.001,l=0,u=1-Math.pow(s,1/300),c=.6,d=0,f=Math.random,p=new Map,g=new Map,m=null,y=null,M=null,S=null,h=null,v=null,b=null,x=null,E=null,F=null,R=!1,A=!1,I=!1;Ze(i,o,f),(n.device||Pe())&&L();async function L(){try{y=n.device?await n.device:await En({preferHighPerformance:n.preferHighPerformance}),w(),z(),B(),p.forEach(_=>P(_)),R=!0,T("ready")}catch(_){console.error("[webgpuForceSimulation] device init failed:",_)}}function B(){if(!y||!M||!S||!h)return;let{device:_}=y;x?.destroy(),x=_.createBuffer({label:"integrate-params",size:Di,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let D=_.createShaderModule({label:"integrate-shader",code:Ii});E=_.createComputePipeline({label:"integrate-pipeline",layout:"auto",compute:{module:D,entryPoint:"main"}}),F=_.createBindGroup({label:"integrate-bind-group",layout:E.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:M}},{binding:1,resource:{buffer:S}},{binding:2,resource:{buffer:h}},{binding:3,resource:{buffer:x}}]})}function k(){if(!y||!x)return;let _=new Float32Array([c,o,r,d]);y.device.queue.writeBuffer(x,0,_)}function w(){if(!y)return;let{device:_}=y;M?.destroy(),S?.destroy(),h?.destroy(),v?.destroy(),b?.destroy(),M=_.createBuffer({label:"positions",size:r*Le,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),S=_.createBuffer({label:"velocities",size:r*Ge,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),h=_.createBuffer({label:"pinned",size:r*Bn,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),v=_.createBuffer({label:"readback",size:r*Le,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),b=_.createBuffer({label:"readback-velocity",size:r*Ge,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST})}function z(){if(!y||!M||!S||!h)return;let{device:_}=y,D=new Float32Array(r*4),O=new Float32Array(r*4),Y=new Float32Array(r);for(let X=0;X<r;X++){let W=i[X];D[X*4+0]=W.x??0,D[X*4+1]=W.y??0,D[X*4+2]=W.z??0,D[X*4+3]=X,O[X*4+0]=W.vx??0,O[X*4+1]=W.vy??0,O[X*4+2]=W.vz??0,Y[X]=W.fx!=null||W.fy!=null||W.fz!=null?1:0}_.queue.writeBuffer(M,0,D),_.queue.writeBuffer(S,0,O),_.queue.writeBuffer(h,0,Y)}function P(_){if(!y||!M||!S||!h)return;let D={device:y.device,nodeCount:r,nDim:o,positionBuffer:M,velocityBuffer:S,pinnedBuffer:h};_.initGPU(D)}function T(_){let D=g.get(_);if(D)for(let O of D)O()}function C(_=1){if(!R||!y||!E||!F)return;let{device:D}=y;for(let O=0;O<_;O++){if(a<s){T("end");return}k();let Y=D.createCommandEncoder({label:"tick"});p.forEach(W=>W.apply(a,Y));let X=Y.beginComputePass({label:"integrate"});X.setPipeline(E),X.setBindGroup(0,F),X.dispatchWorkgroups(Math.ceil(r/Ai)),X.end(),D.queue.submit([Y.finish()]),a=a+(l-a)*u,T("tick")}}async function q(){if(!(!y||!M||!v)&&!A){A=!0;try{let{device:_}=y,D=_.createCommandEncoder({label:"readback"});D.copyBufferToBuffer(M,0,v,0,r*Le),_.queue.submit([D.finish()]);try{await v.mapAsync(GPUMapMode.READ,0,r*Le)}catch(Y){let X=Y?.name;if(X==="AbortError"||X==="OperationError")return;throw Y}if(!v)return;let O=new Float32Array(v.getMappedRange(0,r*Le));if(globalThis.__webgpuPathASkip===!0){(!m||m.length<O.length)&&(m=new Float32Array(O.length)),m.set(O),v.unmap();return}for(let Y=0;Y<r;Y++){let X=Y*4,W=i[Y];W.fx==null&&(W.x=O[X]),o>1&&W.fy==null&&(W.y=O[X+1]),o>2&&W.fz==null?W.z=O[X+2]:o<=2&&(W.z=0)}v.unmap()}finally{A=!1}}}async function N(){if(!y||!S||!b)return new Float32Array(0);let{device:_}=y,D=_.createCommandEncoder({label:"readback-vel"});D.copyBufferToBuffer(S,0,b,0,r*Ge),_.queue.submit([D.finish()]);try{await b.mapAsync(GPUMapMode.READ,0,r*Ge)}catch(X){if(X?.name==="AbortError")return new Float32Array(0);throw X}if(!b)return new Float32Array(0);let O=new Float32Array(b.getMappedRange(0,r*Ge)),Y=new Float32Array(O);return b.unmap(),Y}return{tick(_){return C(_??1),this},restart(){return a=1,this},stop(){return this},alpha(_){return arguments.length===0?a:(a=+_,this)},alphaMin(_){return arguments.length===0?s:(s=+_,this)},alphaDecay(_){return arguments.length===0?u:(u=+_,this)},velocityDecay(_){return arguments.length===0?c:(c=+_,this)},alphaTarget(_){return arguments.length===0?l:(l=+_,this)},maxVel(_){return arguments.length===0?d:(d=+_,this)},uploadPosition(_,D,O,Y){if(!y||!M||_<0||_>=r)return;let X=_*Le,W=new Float32Array([D,O,Y,_]);y.device.queue.writeBuffer(M,X,W);let V=i[_];V&&(V.x=D,V.y=O,V.z=Y)},uploadVelocity(_,D,O,Y){if(!y||!S||_<0||_>=r)return;let X=_*Ge,W=new Float32Array([D,O,Y,0]);y.device.queue.writeBuffer(S,X,W);let V=i[_];V&&(V.vx=D,V.vy=O,V.vz=Y)},uploadPinned(_,D){if(!y||!h||_<0||_>=r)return;let O=_*Bn;y.device.queue.writeBuffer(h,O,new Float32Array([D?1:0]))},nodes(_){return arguments.length===0?i:(i=_,r=i.length,Ze(i,o,f),y&&(w(),z(),B(),p.forEach(D=>P(D))),this)},force(_,D){return arguments.length===1?p.get(_):(D==null?p.delete(_):(D.initialize(i,f,o),p.set(_,D),y&&P(D)),this)},numDimensions(_){return arguments.length===0?o:(o=+_,k(),p.forEach(D=>D.initialize(i,f,o)),this)},on(_,D){let O=g.get(_);return O||(O=[],g.set(_,O)),O.push(D),this},dispose(){M?.destroy(),S?.destroy(),h?.destroy(),v?.destroy(),b?.destroy(),x?.destroy(),M=S=h=v=null,b=null,x=null,E=null,F=null,p.forEach(_=>_.dispose?.()),p.clear(),R=!1},isReady(){return R},readPositions(){return q()},readVelocities(){return N()},getDevice(){return y?.device??null},getPositionBuffer(){return M}}}var Ri=`// forceCenter \u2014 pass 1 of 2: parallel reduce centroid \u2192 shift vector.
|
|
86
|
+
//
|
|
87
|
+
// Computes mean(positions) across all nodes inside a single workgroup using
|
|
88
|
+
// shared memory, then writes (mean - target) * strength to shift[0].
|
|
89
|
+
//
|
|
90
|
+
// Single workgroup with 64 threads handles up to ~10M nodes via per-thread
|
|
91
|
+
// striding before the tree reduce. For very large N this is fine for forceCenter
|
|
92
|
+
// since it's invoked once per tick (not per-edge / per-pair like manyBody).
|
|
93
|
+
//
|
|
94
|
+
// f32 atomics aren't supported in WebGPU, so a single-workgroup reduce is the
|
|
95
|
+
// cleanest scalar-precise approach without multi-pass scaffolding.
|
|
96
|
+
//
|
|
97
|
+
// Layout:
|
|
98
|
+
// group(0)
|
|
99
|
+
// binding(0) positions array<vec4<f32>> read
|
|
100
|
+
// binding(1) shift array<vec4<f32>> read_write (1 element)
|
|
101
|
+
// binding(2) params CenterParams uniform
|
|
102
|
+
|
|
103
|
+
struct CenterParams {
|
|
104
|
+
nodeCount: f32,
|
|
105
|
+
nDim: f32,
|
|
106
|
+
strength: f32,
|
|
107
|
+
_pad0: f32,
|
|
108
|
+
targetX: f32,
|
|
109
|
+
targetY: f32,
|
|
110
|
+
targetZ: f32,
|
|
111
|
+
_pad1: f32,
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
@group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
|
|
115
|
+
@group(0) @binding(1) var<storage, read_write> shift: array<vec4<f32>>;
|
|
116
|
+
@group(0) @binding(2) var<uniform> params: CenterParams;
|
|
117
|
+
|
|
118
|
+
var<workgroup> partial: array<vec3<f32>, 64>;
|
|
119
|
+
|
|
120
|
+
@compute @workgroup_size(64)
|
|
121
|
+
fn main(@builtin(local_invocation_id) lid: vec3<u32>) {
|
|
122
|
+
let tid: u32 = lid.x;
|
|
123
|
+
let n: u32 = u32(params.nodeCount);
|
|
124
|
+
|
|
125
|
+
// Strided sum: each thread sums positions[tid], positions[tid+64], ...
|
|
126
|
+
var sum: vec3<f32> = vec3<f32>(0.0, 0.0, 0.0);
|
|
127
|
+
var i: u32 = tid;
|
|
128
|
+
loop {
|
|
129
|
+
if (i >= n) { break; }
|
|
130
|
+
sum = sum + positions[i].xyz;
|
|
131
|
+
i = i + 64u;
|
|
132
|
+
}
|
|
133
|
+
partial[tid] = sum;
|
|
134
|
+
workgroupBarrier();
|
|
135
|
+
|
|
136
|
+
// Unrolled tree reduce 64 \u2192 1.
|
|
137
|
+
if (tid < 32u) { partial[tid] = partial[tid] + partial[tid + 32u]; }
|
|
138
|
+
workgroupBarrier();
|
|
139
|
+
if (tid < 16u) { partial[tid] = partial[tid] + partial[tid + 16u]; }
|
|
140
|
+
workgroupBarrier();
|
|
141
|
+
if (tid < 8u) { partial[tid] = partial[tid] + partial[tid + 8u]; }
|
|
142
|
+
workgroupBarrier();
|
|
143
|
+
if (tid < 4u) { partial[tid] = partial[tid] + partial[tid + 4u]; }
|
|
144
|
+
workgroupBarrier();
|
|
145
|
+
if (tid < 2u) { partial[tid] = partial[tid] + partial[tid + 2u]; }
|
|
146
|
+
workgroupBarrier();
|
|
147
|
+
if (tid < 1u) { partial[tid] = partial[tid] + partial[tid + 1u]; }
|
|
148
|
+
workgroupBarrier();
|
|
149
|
+
|
|
150
|
+
if (tid == 0u) {
|
|
151
|
+
let mean: vec3<f32> = partial[0] / f32(n);
|
|
152
|
+
let centerTarget: vec3<f32> = vec3<f32>(params.targetX, params.targetY, params.targetZ);
|
|
153
|
+
var s: vec3<f32> = (mean - centerTarget) * params.strength;
|
|
154
|
+
// Mask unused dimensions so 2D/1D shifts don't bleed into higher axes.
|
|
155
|
+
if (params.nDim < 3.0) { s.z = 0.0; }
|
|
156
|
+
if (params.nDim < 2.0) { s.y = 0.0; }
|
|
157
|
+
shift[0] = vec4<f32>(s, 0.0);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
`,Ui=`// forceCenter \u2014 pass 2 of 2: subtract shift from every node's position.
|
|
161
|
+
//
|
|
162
|
+
// Mirrors d3-force-3d center.js: \`node.x -= shift\`. Pinned nodes are skipped.
|
|
163
|
+
// One invocation per node.
|
|
164
|
+
//
|
|
165
|
+
// Layout:
|
|
166
|
+
// group(0)
|
|
167
|
+
// binding(0) positions array<vec4<f32>> read_write
|
|
168
|
+
// binding(1) pinned array<f32> read
|
|
169
|
+
// binding(2) shift array<vec4<f32>> read (1 element, written by reduce pass)
|
|
170
|
+
// binding(3) params ApplyParams uniform
|
|
171
|
+
|
|
172
|
+
struct ApplyParams {
|
|
173
|
+
nodeCount: f32,
|
|
174
|
+
nDim: f32,
|
|
175
|
+
_pad0: f32,
|
|
176
|
+
_pad1: f32,
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
@group(0) @binding(0) var<storage, read_write> positions: array<vec4<f32>>;
|
|
180
|
+
@group(0) @binding(1) var<storage, read> pinned: array<f32>;
|
|
181
|
+
@group(0) @binding(2) var<storage, read> shift: array<vec4<f32>>;
|
|
182
|
+
@group(0) @binding(3) var<uniform> params: ApplyParams;
|
|
183
|
+
|
|
184
|
+
@compute @workgroup_size(64)
|
|
185
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
186
|
+
let i: u32 = gid.x;
|
|
187
|
+
if (f32(i) >= params.nodeCount) { return; }
|
|
188
|
+
if (pinned[i] > 0.5) { return; }
|
|
189
|
+
|
|
190
|
+
var p: vec3<f32> = positions[i].xyz - shift[0].xyz;
|
|
191
|
+
if (params.nDim < 3.0) { p.z = 0.0; }
|
|
192
|
+
if (params.nDim < 2.0) { p.y = 0.0; }
|
|
193
|
+
positions[i] = vec4<f32>(p, positions[i].w);
|
|
194
|
+
}
|
|
195
|
+
`,Li=16,Gi=32,Ni=16,qi=64;function Gn(e=0,t=0,n=0){let i=e,r=t,o=n,a=1,s=3,l=0,u=null,c=null,d=null,f=null,p=null,g=null,m=null,y=null;function M(E,F,R){s=R}function S(E){u=E.device,l=E.nodeCount,s=E.nDim,c?.destroy(),c=u.createBuffer({label:"center-shift",size:Li,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),d?.destroy(),d=u.createBuffer({label:"center-reduce-params",size:Gi,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),f?.destroy(),f=u.createBuffer({label:"center-apply-params",size:Ni,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let F=u.createShaderModule({label:"center-reduce-shader",code:Ri});p=u.createComputePipeline({label:"center-reduce-pipeline",layout:"auto",compute:{module:F,entryPoint:"main"}});let R=u.createShaderModule({label:"center-apply-shader",code:Ui});g=u.createComputePipeline({label:"center-apply-pipeline",layout:"auto",compute:{module:R,entryPoint:"main"}}),m=u.createBindGroup({label:"center-reduce-bind-group",layout:p.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:E.positionBuffer}},{binding:1,resource:{buffer:c}},{binding:2,resource:{buffer:d}}]}),y=u.createBindGroup({label:"center-apply-bind-group",layout:g.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:E.positionBuffer}},{binding:1,resource:{buffer:E.pinnedBuffer}},{binding:2,resource:{buffer:c}},{binding:3,resource:{buffer:f}}]})}function h(){if(!u||!d||!f)return;let E=new Float32Array([l,s,a,0,i,r,o,0]);u.queue.writeBuffer(d,0,E);let F=new Float32Array([l,s,0,0]);u.queue.writeBuffer(f,0,F)}function v(E,F){if(!p||!g||!m||!y||l===0)return;h();let R=F.beginComputePass({label:"center-reduce"});R.setPipeline(p),R.setBindGroup(0,m),R.dispatchWorkgroups(1),R.end();let A=F.beginComputePass({label:"center-apply"});A.setPipeline(g),A.setBindGroup(0,y),A.dispatchWorkgroups(Math.ceil(l/qi)),A.end()}function b(){c?.destroy(),d?.destroy(),f?.destroy(),c=d=f=null,p=g=null,m=y=null,u=null}let x={initialize:M,initGPU:S,apply:v,dispose:b,x(E){return arguments.length===0?i:(i=+E,x)},y(E){return arguments.length===0?r:(r=+E,x)},z(E){return arguments.length===0?o:(o=+E,x)},strength(E){return arguments.length===0?a:(a=+E,x)}};return x}var Oi=`// Per-axis attractive force (forceX / forceY / forceZ).
|
|
196
|
+
//
|
|
197
|
+
// One invocation per node. Adds \`(target - position[axis]) * strength * alpha\`
|
|
198
|
+
// to that node's velocity along the configured axis only \u2014 other axes untouched.
|
|
199
|
+
// Axis is selected by uniform: 0=X, 1=Y, 2=Z.
|
|
200
|
+
//
|
|
201
|
+
// d3-force-3d equivalents: x.js, y.js, z.js. All three have identical structure
|
|
202
|
+
// (target accessor + strength accessor + per-tick velocity update on one axis).
|
|
203
|
+
// We collapse to a single shader keyed on axis to avoid 3\xD7 duplication.
|
|
204
|
+
//
|
|
205
|
+
// Layout:
|
|
206
|
+
// group(0)
|
|
207
|
+
// binding(0) positions array<vec4<f32>> read
|
|
208
|
+
// binding(1) velocities array<vec4<f32>> read_write
|
|
209
|
+
// binding(2) params PositionForceParams uniform
|
|
210
|
+
|
|
211
|
+
struct PositionForceParams {
|
|
212
|
+
axis: f32, // 0=X, 1=Y, 2=Z
|
|
213
|
+
targetPos: f32,
|
|
214
|
+
strength: f32,
|
|
215
|
+
alpha: f32,
|
|
216
|
+
nodeCount: f32,
|
|
217
|
+
_pad0: f32,
|
|
218
|
+
_pad1: f32,
|
|
219
|
+
_pad2: f32,
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
@group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
|
|
223
|
+
@group(0) @binding(1) var<storage, read_write> velocities: array<vec4<f32>>;
|
|
224
|
+
@group(0) @binding(2) var<uniform> params: PositionForceParams;
|
|
225
|
+
|
|
226
|
+
@compute @workgroup_size(64)
|
|
227
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
228
|
+
let i: u32 = gid.x;
|
|
229
|
+
if (f32(i) >= params.nodeCount) { return; }
|
|
230
|
+
|
|
231
|
+
let pos: vec3<f32> = positions[i].xyz;
|
|
232
|
+
var vel: vec3<f32> = velocities[i].xyz;
|
|
233
|
+
|
|
234
|
+
if (params.axis < 0.5) {
|
|
235
|
+
vel.x = vel.x + (params.targetPos - pos.x) * params.strength * params.alpha;
|
|
236
|
+
} else if (params.axis < 1.5) {
|
|
237
|
+
vel.y = vel.y + (params.targetPos - pos.y) * params.strength * params.alpha;
|
|
238
|
+
} else {
|
|
239
|
+
vel.z = vel.z + (params.targetPos - pos.z) * params.strength * params.alpha;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
velocities[i] = vec4<f32>(vel, velocities[i].w);
|
|
243
|
+
}
|
|
244
|
+
`,Hi=32,Xi=64;function kt(e,t){let n=t,i=.1,r=0,o=null,a=null,s=null,l=null;function u(){}function c(m){o=m.device,r=m.nodeCount,a?.destroy(),a=o.createBuffer({label:`position-force-${e}-params`,size:Hi,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let y=o.createShaderModule({label:`position-force-${e}-shader`,code:Oi});s=o.createComputePipeline({label:`position-force-${e}-pipeline`,layout:"auto",compute:{module:y,entryPoint:"main"}}),l=o.createBindGroup({label:`position-force-${e}-bind-group`,layout:s.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:m.positionBuffer}},{binding:1,resource:{buffer:m.velocityBuffer}},{binding:2,resource:{buffer:a}}]})}function d(m){if(!o||!a)return;let y=new Float32Array([e,n,i,m,r,0,0,0]);o.queue.writeBuffer(a,0,y)}function f(m,y){if(!s||!l||r===0)return;d(m);let M=y.beginComputePass({label:`position-force-${e}`});M.setPipeline(s),M.setBindGroup(0,l),M.dispatchWorkgroups(Math.ceil(r/Xi)),M.end()}function p(){a?.destroy(),a=null,s=null,l=null,o=null}let g={initialize:u,initGPU:c,apply:f,dispose:p,strength(m){return arguments.length===0?i:(i=+m,g)},target(m){return arguments.length===0?n:(n=+m,g)}};return g}function Nn(e=0){return kt(0,e)}function qn(e=0){return kt(1,e)}function On(e=0){return kt(2,e)}var Yi=`// forceLink \u2014 per-edge spring constraint.
|
|
245
|
+
//
|
|
246
|
+
// One invocation per edge. For each edge (s, t), computes a delta toward the
|
|
247
|
+
// configured \`linkDistance\` and accumulates contributions into an integer
|
|
248
|
+
// accumulator buffer (atomicAdd-safe). A second compute pass (apply) drains the
|
|
249
|
+
// accumulator into the float velocity buffer, dividing by the scale factor.
|
|
250
|
+
//
|
|
251
|
+
// f32 atomics aren't in WebGPU yet \u2014 we quantize to i32 via FIXED_POINT_SCALE.
|
|
252
|
+
// At 1e6 scale + per-edge magnitudes well under |10|, range fits comfortably
|
|
253
|
+
// in i32 even with thousands of edges sharing a node.
|
|
254
|
+
//
|
|
255
|
+
// d3-force formula (link.js):
|
|
256
|
+
// bias_s = countSrc / (countSrc + countTgt) (source's share of pull)
|
|
257
|
+
// delta = (current_dist - linkDistance) * strength * alpha / current_dist
|
|
258
|
+
// src.v += (t - s) * delta * (1 - bias_s)
|
|
259
|
+
// tgt.v -= (t - s) * delta * bias_s
|
|
260
|
+
//
|
|
261
|
+
// Jiggle: if current_dist == 0, perturb to break symmetry.
|
|
262
|
+
//
|
|
263
|
+
// Layout:
|
|
264
|
+
// group(0)
|
|
265
|
+
// binding(0) positions array<vec4<f32>> read
|
|
266
|
+
// binding(1) velAccum array<atomic<i32>> read_write (3 \xD7 nodeCount slots)
|
|
267
|
+
// binding(2) edges array<vec4<f32>> read (src_idx, tgt_idx, biasSrc, distance)
|
|
268
|
+
// binding(3) params LinkParams uniform
|
|
269
|
+
// binding(4) strengths array<f32> read (per-edge strength = defaultStrength * strengthScale)
|
|
270
|
+
// binding(5) velocities array<vec4<f32>> read (for velocity-anticipated half-step: pos + vel)
|
|
271
|
+
|
|
272
|
+
const FIXED_POINT_SCALE: f32 = 1048576.0; // 2^20
|
|
273
|
+
|
|
274
|
+
struct LinkParams {
|
|
275
|
+
edgeCount: f32,
|
|
276
|
+
_pad1: f32, // was: strength (per-edge strengths buffer replaces this)
|
|
277
|
+
alpha: f32,
|
|
278
|
+
_pad0: f32,
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
@group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
|
|
282
|
+
@group(0) @binding(1) var<storage, read_write> velAccum: array<atomic<i32>>;
|
|
283
|
+
@group(0) @binding(2) var<storage, read> edges: array<vec4<f32>>;
|
|
284
|
+
@group(0) @binding(3) var<uniform> params: LinkParams;
|
|
285
|
+
@group(0) @binding(4) var<storage, read> strengths: array<f32>; // per-edge default strength
|
|
286
|
+
@group(0) @binding(5) var<storage, read> velocities: array<vec4<f32>>; // for velocity-anticipated half-step
|
|
287
|
+
|
|
288
|
+
@compute @workgroup_size(64)
|
|
289
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
290
|
+
let e: u32 = gid.x;
|
|
291
|
+
if (f32(e) >= params.edgeCount) { return; }
|
|
292
|
+
|
|
293
|
+
let edge = edges[e];
|
|
294
|
+
let sIdx: u32 = u32(edge.x);
|
|
295
|
+
let tIdx: u32 = u32(edge.y);
|
|
296
|
+
let biasSrc: f32 = edge.z;
|
|
297
|
+
let linkDistance: f32 = edge.w;
|
|
298
|
+
|
|
299
|
+
let src = positions[sIdx].xyz + velocities[sIdx].xyz; // velocity-anticipated half-step
|
|
300
|
+
let tgt = positions[tIdx].xyz + velocities[tIdx].xyz; // (mirrors d3 link.js:37-39)
|
|
301
|
+
var d: vec3<f32> = tgt - src;
|
|
302
|
+
|
|
303
|
+
// Jiggle when zero-vector (d3-force jiggle: \xB10.5e-6 per axis, deterministic
|
|
304
|
+
// here by using edge index as a phase shift \u2014 good enough for breaking ties).
|
|
305
|
+
if (length(d) < 1e-12) {
|
|
306
|
+
let phase = f32(e) * 0.123456;
|
|
307
|
+
d = vec3<f32>(sin(phase) * 1e-6, cos(phase) * 1e-6, sin(phase * 2.0) * 1e-6);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
let dist: f32 = length(d);
|
|
311
|
+
let stretch: f32 = (dist - linkDistance) * strengths[e] * params.alpha / dist;
|
|
312
|
+
let pull: vec3<f32> = d * stretch;
|
|
313
|
+
|
|
314
|
+
let srcShare: vec3<f32> = pull * (1.0 - biasSrc);
|
|
315
|
+
let tgtShare: vec3<f32> = pull * biasSrc;
|
|
316
|
+
|
|
317
|
+
// Quantize and atomic-add into the integer accumulator. Layout: per node,
|
|
318
|
+
// three consecutive i32 slots (x, y, z).
|
|
319
|
+
atomicAdd(&velAccum[sIdx * 3u + 0u], i32(srcShare.x * FIXED_POINT_SCALE));
|
|
320
|
+
atomicAdd(&velAccum[sIdx * 3u + 1u], i32(srcShare.y * FIXED_POINT_SCALE));
|
|
321
|
+
atomicAdd(&velAccum[sIdx * 3u + 2u], i32(srcShare.z * FIXED_POINT_SCALE));
|
|
322
|
+
atomicSub(&velAccum[tIdx * 3u + 0u], i32(tgtShare.x * FIXED_POINT_SCALE));
|
|
323
|
+
atomicSub(&velAccum[tIdx * 3u + 1u], i32(tgtShare.y * FIXED_POINT_SCALE));
|
|
324
|
+
atomicSub(&velAccum[tIdx * 3u + 2u], i32(tgtShare.z * FIXED_POINT_SCALE));
|
|
325
|
+
}
|
|
326
|
+
`,$i=`// forceLink pass 2: drain the i32 atomic accumulator into f32 velocities.
|
|
327
|
+
//
|
|
328
|
+
// One invocation per node. Reads the 3 i32 slots populated by link-force.wgsl,
|
|
329
|
+
// converts back to f32 (divides by FIXED_POINT_SCALE), adds to velocity, then
|
|
330
|
+
// zeros the accumulator for the next tick.
|
|
331
|
+
//
|
|
332
|
+
// Layout:
|
|
333
|
+
// group(0)
|
|
334
|
+
// binding(0) velocities array<vec4<f32>> read_write
|
|
335
|
+
// binding(1) velAccum array<atomic<i32>> read_write
|
|
336
|
+
// binding(2) params DrainParams uniform
|
|
337
|
+
|
|
338
|
+
const FIXED_POINT_SCALE: f32 = 1048576.0; // 2^20; must match link-force.wgsl
|
|
339
|
+
|
|
340
|
+
struct DrainParams {
|
|
341
|
+
nodeCount: f32,
|
|
342
|
+
_pad0: f32,
|
|
343
|
+
_pad1: f32,
|
|
344
|
+
_pad2: f32,
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
@group(0) @binding(0) var<storage, read_write> velocities: array<vec4<f32>>;
|
|
348
|
+
@group(0) @binding(1) var<storage, read_write> velAccum: array<atomic<i32>>;
|
|
349
|
+
@group(0) @binding(2) var<uniform> params: DrainParams;
|
|
350
|
+
|
|
351
|
+
@compute @workgroup_size(64)
|
|
352
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
353
|
+
let i: u32 = gid.x;
|
|
354
|
+
if (f32(i) >= params.nodeCount) { return; }
|
|
355
|
+
|
|
356
|
+
let ax = atomicExchange(&velAccum[i * 3u + 0u], 0);
|
|
357
|
+
let ay = atomicExchange(&velAccum[i * 3u + 1u], 0);
|
|
358
|
+
let az = atomicExchange(&velAccum[i * 3u + 2u], 0);
|
|
359
|
+
|
|
360
|
+
let delta = vec3<f32>(f32(ax), f32(ay), f32(az)) / FIXED_POINT_SCALE;
|
|
361
|
+
velocities[i] = vec4<f32>(velocities[i].xyz + delta, velocities[i].w);
|
|
362
|
+
}
|
|
363
|
+
`,Zi=12,ji=16,Vi=16,zn=64;function Wi(e){return()=>e}function Hn(e=[]){let t=e,n=new Int32Array(0),i=30,r=[],o=0,a=null,s=null,l=null,u=null,c=null,d=null,f=null,p=null,g=null,m=null,y=0,M=new Float32Array(0),S=null,h=null;function v(P){let T=P.source,C=P.target,q=Math.min(n[T]??1,n[C]??1);return q>0?1/q:1}let b=v;function x(P,T,C){r=P}function E(){let P=new Map;for(let N=0;N<r.length;N++){let G=r[N];G.id!=null&&P.set(G.id,N),G.index!=null&&P.set(G.index,N)}let T=new Int32Array(r.length),C=[];for(let N=0;N<t.length;N++){let G=t[N],_=F(G.source,P),D=F(G.target,P);_<0||D<0||(T[_]++,T[D]++,C.push({source:_,target:D,index:N}))}n=T;let q=new Float32Array(C.length*4);M=new Float32Array(C.length);for(let N=0;N<C.length;N++){let G=C[N].source,_=C[N].target,D=T[G]+T[_],O=D>0?T[G]/D:.5;q[N*4+0]=G,q[N*4+1]=_,q[N*4+2]=O,q[N*4+3]=i,M[N]=+b(C[N],N,C)}return y=C.length,q}function F(P,T){if(typeof P=="object"&&P!==null){let C=P;return C.index!=null?C.index:C.id!=null?T.get(C.id)??-1:-1}return T.get(P)??-1}function R(){if(!a)return;let P=E();if(s?.destroy(),l?.destroy(),P.length===0){s=null,l=null;return}s=a.createBuffer({label:"link-edges",size:P.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),a.queue.writeBuffer(s,0,P.buffer,P.byteOffset,P.byteLength),l=a.createBuffer({label:"link-strengths",size:Math.max(M.byteLength,4),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),a.queue.writeBuffer(l,0,M.buffer,M.byteOffset,M.byteLength),h&&S&&I(h,S)}function A(P){a=P.device,o=P.nodeCount,u?.destroy(),u=a.createBuffer({label:"link-vel-accum",size:o*Zi,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});let T=new Int32Array(o*3);a.queue.writeBuffer(u,0,T.buffer,0,T.byteLength),c?.destroy(),c=a.createBuffer({label:"link-params",size:ji,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),d?.destroy(),d=a.createBuffer({label:"link-drain-params",size:Vi,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let C=a.createShaderModule({label:"link-force-shader",code:Yi});f=a.createComputePipeline({label:"link-force-pipeline",layout:"auto",compute:{module:C,entryPoint:"main"}});let q=a.createShaderModule({label:"link-drain-shader",code:$i});p=a.createComputePipeline({label:"link-drain-pipeline",layout:"auto",compute:{module:q,entryPoint:"main"}}),R(),I(P.positionBuffer,P.velocityBuffer)}function I(P,T){!a||!f||!p||!u||!c||!d||(S=T,h=P,s&&l?g=a.createBindGroup({label:"link-force-bind-group",layout:f.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:P}},{binding:1,resource:{buffer:u}},{binding:2,resource:{buffer:s}},{binding:3,resource:{buffer:c}},{binding:4,resource:{buffer:l}},{binding:5,resource:{buffer:T}}]}):g=null,m=a.createBindGroup({label:"link-drain-bind-group",layout:p.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:T}},{binding:1,resource:{buffer:u}},{binding:2,resource:{buffer:d}}]}))}function L(){R()}function B(P){if(!a||!c||!d)return;let T=new Float32Array([y,0,P,0]);a.queue.writeBuffer(c,0,T);let C=new Float32Array([o,0,0,0]);a.queue.writeBuffer(d,0,C)}function k(P,T){if(!f||!p||!m||o===0)return;if(B(P),g&&y>0){let q=T.beginComputePass({label:"link-force"});q.setPipeline(f),q.setBindGroup(0,g),q.dispatchWorkgroups(Math.ceil(y/zn)),q.end()}let C=T.beginComputePass({label:"link-drain"});C.setPipeline(p),C.setBindGroup(0,m),C.dispatchWorkgroups(Math.ceil(o/zn)),C.end()}function w(){s?.destroy(),l?.destroy(),u?.destroy(),c?.destroy(),d?.destroy(),s=l=u=c=d=null,f=p=null,g=m=null,S=null,h=null,a=null}let z={initialize:x,initGPU:A,apply:k,dispose:w,links(P){return arguments.length===0?t:(t=P,a&&R(),z)},strength(P){return arguments.length===0?b:(b=typeof P=="function"?P:Wi(+P),a&&R(),z)},distance(P){return arguments.length===0?i:(i=+P,a&&R(),z)},rebuildEdgeBuffer:L};return z}var Xn=64,Te=32,Ki=.9;function Qi(e){return e<=1?1:1<<Math.ceil(Math.log2(e))}function Ji(e,t,n){let i=t,r=Qi(i),o=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,a=e.createBuffer({label:"lbvh-morton",size:r*4,usage:o}),s=e.createBuffer({label:"lbvh-sortedIndices",size:r*4,usage:o}),l=e.createBuffer({label:"lbvh-internal",size:Math.max(1,i-1)*16,usage:o}),u=e.createBuffer({label:"lbvh-parent",size:Math.max(1,i-1)*4,usage:o}),c=e.createBuffer({label:"lbvh-aabb",size:Math.max(1,2*i-1)*32,usage:o}),d=e.createBuffer({label:"lbvh-com",size:Math.max(1,2*i-1)*16,usage:o}),f=e.createBuffer({label:"lbvh-depth",size:Math.max(1,i-1)*4,usage:o}),p=e.createBuffer({label:"lbvh-bounds",size:32,usage:o}),g=e.createBuffer({label:"lbvh-queueA",size:Math.max(1,i-1)*4,usage:o}),m=e.createBuffer({label:"lbvh-queueB",size:Math.max(1,i-1)*4,usage:o}),y=e.createBuffer({label:"lbvh-frontier",size:(n+1)*4,usage:o}),M=e.createBuffer({label:"lbvh-root",size:4,usage:o});return{paddedN:r,morton:a,sortedIndices:s,internal:l,parent:u,aabb:c,com:d,depth:f,bounds:p,depthQueueA:g,depthQueueB:m,frontierCounts:y,root:M,dispose(){for(let S of[a,s,l,u,c,d,f,p,g,m,y,M])S.destroy()}}}var Et=`// P1: scene AABB via atomicMin/atomicMax on i32 bit-reinterpretation of f32 positions.
|
|
364
|
+
// Uses ordered-i32 trick: for positive floats, integer bit pattern preserves order;
|
|
365
|
+
// for negative, flipping all bits restores order. Inverse on read recovers f32.
|
|
366
|
+
|
|
367
|
+
struct BoundsParams { nodeCount: u32, _pad0: u32, _pad1: u32, _pad2: u32 };
|
|
368
|
+
|
|
369
|
+
@group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
|
|
370
|
+
@group(0) @binding(1) var<storage, read_write> bounds: array<atomic<i32>, 6>;
|
|
371
|
+
@group(0) @binding(2) var<uniform> params: BoundsParams;
|
|
372
|
+
|
|
373
|
+
fn floatToOrderedInt(f: f32) -> i32 {
|
|
374
|
+
let bits = bitcast<i32>(f);
|
|
375
|
+
return select(bits ^ 0x7FFFFFFF, bits, bits >= 0);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
@compute @workgroup_size(64)
|
|
379
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
380
|
+
let i = gid.x;
|
|
381
|
+
if (i >= params.nodeCount) { return; }
|
|
382
|
+
let p = positions[i].xyz;
|
|
383
|
+
let xi = floatToOrderedInt(p.x);
|
|
384
|
+
let yi = floatToOrderedInt(p.y);
|
|
385
|
+
let zi = floatToOrderedInt(p.z);
|
|
386
|
+
atomicMin(&bounds[0], xi); atomicMax(&bounds[1], xi);
|
|
387
|
+
atomicMin(&bounds[2], yi); atomicMax(&bounds[3], yi);
|
|
388
|
+
atomicMin(&bounds[4], zi); atomicMax(&bounds[5], zi);
|
|
389
|
+
}
|
|
390
|
+
`,er=`// P2: per-node Morton code from normalized position. Mirrors mortonReference.ts exactly.
|
|
391
|
+
|
|
392
|
+
struct MortonParams { nodeCount: u32, _pad0: u32, _pad1: u32, _pad2: u32 };
|
|
393
|
+
|
|
394
|
+
@group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
|
|
395
|
+
@group(0) @binding(1) var<storage, read> bounds: array<i32, 6>; // result of P1
|
|
396
|
+
@group(0) @binding(2) var<storage, read_write> mortons: array<u32>;
|
|
397
|
+
@group(0) @binding(3) var<storage, read_write> sortedIndices: array<u32>;
|
|
398
|
+
@group(0) @binding(4) var<uniform> params: MortonParams;
|
|
399
|
+
|
|
400
|
+
fn orderedIntToFloat(i: i32) -> f32 {
|
|
401
|
+
return bitcast<f32>(select(i ^ 0x7FFFFFFF, i, i >= 0));
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
fn mortonExpand10(v: u32) -> u32 {
|
|
405
|
+
var x = v & 0x3FFu;
|
|
406
|
+
x = (x | (x << 16u)) & 0x030000FFu;
|
|
407
|
+
x = (x | (x << 8u)) & 0x0300F00Fu;
|
|
408
|
+
x = (x | (x << 4u)) & 0x030C30C3u;
|
|
409
|
+
x = (x | (x << 2u)) & 0x09249249u;
|
|
410
|
+
return x;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
@compute @workgroup_size(64)
|
|
414
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
415
|
+
let i = gid.x;
|
|
416
|
+
if (i >= params.nodeCount) { return; }
|
|
417
|
+
|
|
418
|
+
let minX = orderedIntToFloat(bounds[0]); let maxX = orderedIntToFloat(bounds[1]);
|
|
419
|
+
let minY = orderedIntToFloat(bounds[2]); let maxY = orderedIntToFloat(bounds[3]);
|
|
420
|
+
let minZ = orderedIntToFloat(bounds[4]); let maxZ = orderedIntToFloat(bounds[5]);
|
|
421
|
+
let span = vec3<f32>(max(maxX - minX, 1e-9), max(maxY - minY, 1e-9), max(maxZ - minZ, 1e-9));
|
|
422
|
+
|
|
423
|
+
let p = positions[i].xyz;
|
|
424
|
+
let n01 = (p - vec3<f32>(minX, minY, minZ)) / span; // [0,1]
|
|
425
|
+
let scaled = clamp(n01 * 1024.0, vec3<f32>(0.0), vec3<f32>(1023.0));
|
|
426
|
+
let xi = u32(scaled.x); let yi = u32(scaled.y); let zi = u32(scaled.z);
|
|
427
|
+
|
|
428
|
+
mortons[i] = mortonExpand10(xi) | (mortonExpand10(yi) << 1u) | (mortonExpand10(zi) << 2u);
|
|
429
|
+
sortedIndices[i] = i;
|
|
430
|
+
}
|
|
431
|
+
`,tr=`// P4: Karras-2012 binary radix tree build. One thread per internal node (N-1 threads).
|
|
432
|
+
// Each internal node i covers a range of sorted Morton codes; the split is the largest
|
|
433
|
+
// prefix-difference inside the range.
|
|
434
|
+
//
|
|
435
|
+
// Child pointer encoding (consistent with comBuffer layout):
|
|
436
|
+
// child < N-1 \u2192 internal node, comBuffer index = child
|
|
437
|
+
// child >= N-1 \u2192 leaf, comBuffer index = child, leaf_index_in_sorted = child - (N-1)
|
|
438
|
+
//
|
|
439
|
+
// Race-avoidance: each thread writes its OWN slot in \`internalBuf\` (left, right, _, last)
|
|
440
|
+
// AND writes parents of its children into a SEPARATE \`parentBuf\`. Each parentBuf slot is
|
|
441
|
+
// written by exactly one thread (the parent \u2014 child\u2192parent is unique), no race.
|
|
442
|
+
|
|
443
|
+
struct BuildParams { nodeCount: u32, _pad0: u32, _pad1: u32, _pad2: u32 };
|
|
444
|
+
|
|
445
|
+
@group(0) @binding(0) var<storage, read> mortons: array<u32>;
|
|
446
|
+
@group(0) @binding(1) var<storage, read_write> internalBuf: array<vec4<i32>>; // (left, right, _unused, last)
|
|
447
|
+
@group(0) @binding(2) var<storage, read_write> parentBuf: array<i32>; // pre-initialized to -1 by orchestrator
|
|
448
|
+
@group(0) @binding(3) var<storage, read_write> aabb: array<vec4<f32>>; // 2*(2N-1): [2i]=min, [2i+1]=max
|
|
449
|
+
@group(0) @binding(4) var<storage, read> sortedIndices: array<u32>;
|
|
450
|
+
@group(0) @binding(5) var<storage, read> positions: array<vec4<f32>>;
|
|
451
|
+
@group(0) @binding(6) var<uniform> params: BuildParams;
|
|
452
|
+
|
|
453
|
+
fn lcp(a: i32, b: i32) -> i32 {
|
|
454
|
+
let n = i32(params.nodeCount);
|
|
455
|
+
if (a < 0 || b < 0 || a >= n || b >= n) { return -1; }
|
|
456
|
+
let ua = u32(a); let ub = u32(b);
|
|
457
|
+
if (mortons[ua] == mortons[ub]) {
|
|
458
|
+
// Tie-break with the index itself to ensure unique ordering when Morton codes collide.
|
|
459
|
+
return 32 + i32(countLeadingZeros(ua ^ ub));
|
|
460
|
+
}
|
|
461
|
+
return i32(countLeadingZeros(mortons[ua] ^ mortons[ub]));
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
@compute @workgroup_size(64)
|
|
465
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
466
|
+
let i = i32(gid.x);
|
|
467
|
+
let n = i32(params.nodeCount);
|
|
468
|
+
let internalCount = n - 1;
|
|
469
|
+
|
|
470
|
+
// Initialize leaf AABBs (one thread per leaf \u2014 reusing internal-node thread pool).
|
|
471
|
+
// Each thread also initializes its own leaf entry to keep this self-contained.
|
|
472
|
+
if (i < n) {
|
|
473
|
+
let p = positions[sortedIndices[u32(i)]].xyz;
|
|
474
|
+
let leafBase = (n - 1) + i;
|
|
475
|
+
aabb[2 * leafBase ] = vec4<f32>(p, 0.0);
|
|
476
|
+
aabb[2 * leafBase + 1] = vec4<f32>(p, 0.0);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
if (i >= internalCount) { return; }
|
|
480
|
+
|
|
481
|
+
// Determine direction d of the range covered by internal node i.
|
|
482
|
+
let lcpRight = lcp(i, i + 1);
|
|
483
|
+
let lcpLeft = lcp(i, i - 1);
|
|
484
|
+
let d = select(-1, 1, lcpRight > lcpLeft);
|
|
485
|
+
let lcpMin = select(lcpRight, lcpLeft, d == 1); // LCP with the "opposite" direction
|
|
486
|
+
|
|
487
|
+
// Exponential search for upper bound of range length.
|
|
488
|
+
var lmax: i32 = 2;
|
|
489
|
+
while (lcp(i, i + lmax * d) > lcpMin) { lmax = lmax * 2; }
|
|
490
|
+
|
|
491
|
+
// Binary search for exact range length l.
|
|
492
|
+
var l: i32 = 0;
|
|
493
|
+
var t: i32 = lmax / 2;
|
|
494
|
+
while (t > 0) {
|
|
495
|
+
if (lcp(i, i + (l + t) * d) > lcpMin) { l = l + t; }
|
|
496
|
+
t = t / 2;
|
|
497
|
+
}
|
|
498
|
+
let j: i32 = i + l * d;
|
|
499
|
+
let first = min(i, j);
|
|
500
|
+
let last = max(i, j);
|
|
501
|
+
|
|
502
|
+
// Find split \u03B3: binary search for the largest position where \u03B4(first, \u03B3) > \u03B4(first, last).
|
|
503
|
+
let lcpNode = lcp(first, last);
|
|
504
|
+
var s: i32 = 0;
|
|
505
|
+
var divisor: i32 = 2;
|
|
506
|
+
var step: i32 = (l + divisor - 1) / divisor; // ceil
|
|
507
|
+
while (step >= 1) {
|
|
508
|
+
if (lcp(i, i + (s + step) * d) > lcpNode) { s = s + step; }
|
|
509
|
+
if (step == 1) { break; }
|
|
510
|
+
divisor = divisor * 2;
|
|
511
|
+
step = (l + divisor - 1) / divisor;
|
|
512
|
+
}
|
|
513
|
+
let gamma: i32 = i + s * d + min(d, 0); // gamma is split point in [first, last)
|
|
514
|
+
|
|
515
|
+
// Encode children: leaf if range collapses to a single element, else internal.
|
|
516
|
+
let leftIsLeaf = (min(i, j) == gamma);
|
|
517
|
+
let rightIsLeaf = (max(i, j) == gamma + 1);
|
|
518
|
+
let leftChild = select(gamma, gamma + (n - 1), leftIsLeaf);
|
|
519
|
+
let rightChild = select(gamma + 1, gamma + 1 + (n - 1), rightIsLeaf);
|
|
520
|
+
|
|
521
|
+
// Write own slot ONLY (no race; each thread owns its index).
|
|
522
|
+
internalBuf[i] = vec4<i32>(leftChild, rightChild, 0, last);
|
|
523
|
+
|
|
524
|
+
// Write parent of each INTERNAL child into parentBuf (leaves don't need parent
|
|
525
|
+
// because depth/COM reduce walks parent\u2192child only). Each parentBuf slot is
|
|
526
|
+
// written by exactly one thread (the unique parent), so no race.
|
|
527
|
+
if (!leftIsLeaf) { parentBuf[leftChild] = i; }
|
|
528
|
+
if (!rightIsLeaf) { parentBuf[rightChild] = i; }
|
|
529
|
+
}
|
|
530
|
+
`,nr=`// P4b: find the root internal node. The root is the unique internal node with
|
|
531
|
+
// parentBuf[i] == -1 (parentBuf is pre-initialized to -1 by orchestrator; P4 overwrote
|
|
532
|
+
// it for every child of every internal node, so only the root remains at -1).
|
|
533
|
+
|
|
534
|
+
struct FindRootParams { nodeCount: u32, _pad0: u32, _pad1: u32, _pad2: u32 };
|
|
535
|
+
|
|
536
|
+
@group(0) @binding(0) var<storage, read> parentBuf: array<i32>;
|
|
537
|
+
@group(0) @binding(1) var<storage, read_write> rootOut: array<u32, 1>;
|
|
538
|
+
@group(0) @binding(2) var<uniform> params: FindRootParams;
|
|
539
|
+
|
|
540
|
+
@compute @workgroup_size(64)
|
|
541
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
542
|
+
let i = i32(gid.x);
|
|
543
|
+
let internalCount = i32(params.nodeCount) - 1;
|
|
544
|
+
if (i >= internalCount) { return; }
|
|
545
|
+
|
|
546
|
+
// Exactly one internal node has parent == -1: the root. Safe plain store.
|
|
547
|
+
if (parentBuf[i] == -1) {
|
|
548
|
+
rootOut[0] = u32(i);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
`,ir=`// P5: BFS ping-pong. One dispatch per BFS level (LBVH_MAX_DEPTH total = 32, empty levels are no-ops).
|
|
552
|
+
// FrontierCount comes from a GPU-side counter buffer (no CPU readback). currentDepth
|
|
553
|
+
// is the only per-dispatch param and uses a DEDICATED per-dispatch uniform buffer
|
|
554
|
+
// (one of LBVH_MAX_DEPTH=32, allocated once in orchestrator init).
|
|
555
|
+
|
|
556
|
+
struct DepthsParams {
|
|
557
|
+
nodeCount: u32,
|
|
558
|
+
currentDepth: u32,
|
|
559
|
+
_pad0: u32,
|
|
560
|
+
_pad1: u32,
|
|
561
|
+
};
|
|
562
|
+
|
|
563
|
+
@group(0) @binding(0) var<storage, read> internalBuf: array<vec4<i32>>;
|
|
564
|
+
@group(0) @binding(1) var<storage, read> queueIn: array<u32>;
|
|
565
|
+
@group(0) @binding(2) var<storage, read_write> queueOut: array<u32>;
|
|
566
|
+
@group(0) @binding(3) var<storage, read_write> frontierCounts: array<atomic<u32>>; // indexed by depth (0..MAX_DEPTH)
|
|
567
|
+
@group(0) @binding(4) var<storage, read_write> depthBuffer: array<u32>;
|
|
568
|
+
@group(0) @binding(5) var<uniform> params: DepthsParams;
|
|
569
|
+
|
|
570
|
+
@compute @workgroup_size(64)
|
|
571
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
572
|
+
let i = gid.x;
|
|
573
|
+
// Read the TRUE frontier size for this depth from the counter buffer.
|
|
574
|
+
// atomicLoad is the correct read primitive for an atomic<u32>.
|
|
575
|
+
let frontierCount = atomicLoad(&frontierCounts[params.currentDepth]);
|
|
576
|
+
if (i >= frontierCount) { return; }
|
|
577
|
+
|
|
578
|
+
let nodeIdx = queueIn[i]; // internal node index (u32)
|
|
579
|
+
depthBuffer[nodeIdx] = params.currentDepth;
|
|
580
|
+
|
|
581
|
+
let entry = internalBuf[nodeIdx];
|
|
582
|
+
let leftChild = entry.x; // i32
|
|
583
|
+
let rightChild = entry.y;
|
|
584
|
+
let internalCount = i32(params.nodeCount) - 1;
|
|
585
|
+
|
|
586
|
+
// Enqueue only INTERNAL children (leaves don't need depth).
|
|
587
|
+
if (leftChild < internalCount) {
|
|
588
|
+
let slot = atomicAdd(&frontierCounts[params.currentDepth + 1u], 1u);
|
|
589
|
+
queueOut[slot] = u32(leftChild);
|
|
590
|
+
}
|
|
591
|
+
if (rightChild < internalCount) {
|
|
592
|
+
let slot = atomicAdd(&frontierCounts[params.currentDepth + 1u], 1u);
|
|
593
|
+
queueOut[slot] = u32(rightChild);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
`,rr=`// P6: COM and AABB reduce.
|
|
597
|
+
// Two entry points, selected by pipeline at dispatch time:
|
|
598
|
+
// leafInit: initialize comBuffer[N-1..2N-2] from leaf positions.
|
|
599
|
+
// levelReduce: for each internal node at depthBuffer[i] == currentLevel, combine
|
|
600
|
+
// child COMs/AABBs into comBuffer[nodeIdx] and aabbBuffer[2i..2i+1].
|
|
601
|
+
|
|
602
|
+
struct ReduceParams {
|
|
603
|
+
nodeCount: u32,
|
|
604
|
+
currentLevel: u32,
|
|
605
|
+
_pad0: u32,
|
|
606
|
+
_pad1: u32,
|
|
607
|
+
};
|
|
608
|
+
|
|
609
|
+
@group(0) @binding(0) var<storage, read> internalBuf: array<vec4<i32>>;
|
|
610
|
+
@group(0) @binding(1) var<storage, read_write> comBuffer: array<vec4<f32>>; // (x, y, z, mass), 2N-1 entries
|
|
611
|
+
@group(0) @binding(2) var<storage, read_write> aabbBuffer: array<vec4<f32>>; // 2*(2N-1) entries (min, max alternating)
|
|
612
|
+
@group(0) @binding(3) var<storage, read> depthBuffer: array<u32>;
|
|
613
|
+
@group(0) @binding(4) var<storage, read> sortedIndices: array<u32>;
|
|
614
|
+
@group(0) @binding(5) var<storage, read> positions: array<vec4<f32>>;
|
|
615
|
+
@group(0) @binding(6) var<uniform> params: ReduceParams;
|
|
616
|
+
|
|
617
|
+
@compute @workgroup_size(64)
|
|
618
|
+
fn leafInit(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
619
|
+
let i = gid.x;
|
|
620
|
+
if (i >= params.nodeCount) { return; }
|
|
621
|
+
let leafIdxInCom = (params.nodeCount - 1u) + i; // comBuffer layout: leaves at [N-1, 2N-2]
|
|
622
|
+
let p = positions[sortedIndices[i]].xyz;
|
|
623
|
+
comBuffer[leafIdxInCom] = vec4<f32>(p, 1.0);
|
|
624
|
+
// aabb already initialized by P4 leaf-init step
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
@compute @workgroup_size(64)
|
|
628
|
+
fn levelReduce(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
629
|
+
let i = gid.x;
|
|
630
|
+
let internalCount = params.nodeCount - 1u;
|
|
631
|
+
if (i >= internalCount) { return; }
|
|
632
|
+
if (depthBuffer[i] != params.currentLevel) { return; }
|
|
633
|
+
|
|
634
|
+
let entry = internalBuf[i];
|
|
635
|
+
let leftChild = u32(entry.x);
|
|
636
|
+
let rightChild = u32(entry.y);
|
|
637
|
+
|
|
638
|
+
// Both children's COMs and AABBs are already in their buffer slots
|
|
639
|
+
// (set either by leafInit or a deeper-level reduce dispatch).
|
|
640
|
+
let cL = comBuffer[leftChild];
|
|
641
|
+
let cR = comBuffer[rightChild];
|
|
642
|
+
let totalMass = cL.w + cR.w;
|
|
643
|
+
let com = vec4<f32>((cL.xyz * cL.w + cR.xyz * cR.w) / totalMass, totalMass);
|
|
644
|
+
comBuffer[i] = com;
|
|
645
|
+
|
|
646
|
+
let aabbMinL = aabbBuffer[2u * leftChild].xyz;
|
|
647
|
+
let aabbMaxL = aabbBuffer[2u * leftChild + 1u].xyz;
|
|
648
|
+
let aabbMinR = aabbBuffer[2u * rightChild].xyz;
|
|
649
|
+
let aabbMaxR = aabbBuffer[2u * rightChild + 1u].xyz;
|
|
650
|
+
aabbBuffer[2u * i] = vec4<f32>(min(aabbMinL, aabbMinR), 0.0);
|
|
651
|
+
aabbBuffer[2u * i + 1u] = vec4<f32>(max(aabbMaxL, aabbMaxR), 0.0);
|
|
652
|
+
}
|
|
653
|
+
`,ar=`// P7: per-query-node DFS traversal with Barnes-Hut criterion. One thread per node.
|
|
654
|
+
// Writes accumulated velocity directly to velocities[i].xyz (no atomics needed \u2014
|
|
655
|
+
// each thread owns its own output slot). Self-interaction guard skips the query
|
|
656
|
+
// node's own entry in leaf cells.
|
|
657
|
+
|
|
658
|
+
struct TraverseParams {
|
|
659
|
+
nodeCount: u32,
|
|
660
|
+
strength: f32,
|
|
661
|
+
alpha: f32,
|
|
662
|
+
theta2: f32, // \u03B8\xB2 for fast Barnes-Hut compare
|
|
663
|
+
distanceMin2: f32, // d3-force-3d distanceMin\xB2 clamp; matches close-range damping
|
|
664
|
+
distanceMax2: f32, // d3-force-3d distanceMax\xB2 cutoff; forces beyond this distance are ignored
|
|
665
|
+
_pad1: f32,
|
|
666
|
+
_pad2: f32,
|
|
667
|
+
};
|
|
668
|
+
|
|
669
|
+
@group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
|
|
670
|
+
@group(0) @binding(1) var<storage, read_write> velocities: array<vec4<f32>>;
|
|
671
|
+
@group(0) @binding(2) var<storage, read> internalBuf: array<vec4<i32>>;
|
|
672
|
+
@group(0) @binding(3) var<storage, read> comBuffer: array<vec4<f32>>;
|
|
673
|
+
@group(0) @binding(4) var<storage, read> aabbBuffer: array<vec4<f32>>;
|
|
674
|
+
@group(0) @binding(5) var<storage, read> sortedIndices: array<u32>;
|
|
675
|
+
@group(0) @binding(6) var<storage, read> rootBuf: array<u32, 1>;
|
|
676
|
+
@group(0) @binding(7) var<uniform> params: TraverseParams;
|
|
677
|
+
|
|
678
|
+
// MAX_DEPTH MUST equal LBVH_MAX_DEPTH from constants.ts (currently 32).
|
|
679
|
+
// Workgroup memory: 64 \xD7 32 \xD7 4 = 8192 bytes (well under 16384-byte default limit).
|
|
680
|
+
const WG_SIZE: u32 = 64u;
|
|
681
|
+
const MAX_DEPTH: u32 = 32u;
|
|
682
|
+
var<workgroup> stack: array<u32, WG_SIZE * MAX_DEPTH>;
|
|
683
|
+
|
|
684
|
+
// d3-force-3d distanceMin clamp: if l < dmin\xB2, l := sqrt(dmin\xB2 \xD7 l).
|
|
685
|
+
// Converts the 1/r\xB2 singularity at close range into 1/r (linear), preventing
|
|
686
|
+
// the close-range "explosion" that produces spiky/streaky layouts.
|
|
687
|
+
fn clampDistance(l: f32) -> f32 {
|
|
688
|
+
return select(l, sqrt(params.distanceMin2 * l), l < params.distanceMin2);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
@compute @workgroup_size(64)
|
|
692
|
+
fn main(
|
|
693
|
+
@builtin(global_invocation_id) gid: vec3<u32>,
|
|
694
|
+
@builtin(local_invocation_index) lid: u32,
|
|
695
|
+
) {
|
|
696
|
+
let queryIdx = gid.x;
|
|
697
|
+
if (queryIdx >= params.nodeCount) { return; }
|
|
698
|
+
|
|
699
|
+
// queryIdx is an ORIGINAL node index (one thread per original node).
|
|
700
|
+
let queryPos = positions[queryIdx].xyz;
|
|
701
|
+
var accum = vec3<f32>(0.0, 0.0, 0.0);
|
|
702
|
+
|
|
703
|
+
// DFS init: stack starts with root.
|
|
704
|
+
var stackTop: u32 = 0u;
|
|
705
|
+
let stackBase = lid * MAX_DEPTH;
|
|
706
|
+
stack[stackBase + stackTop] = rootBuf[0];
|
|
707
|
+
stackTop = stackTop + 1u;
|
|
708
|
+
|
|
709
|
+
let internalCount: u32 = params.nodeCount - 1u;
|
|
710
|
+
|
|
711
|
+
loop {
|
|
712
|
+
if (stackTop == 0u) { break; }
|
|
713
|
+
stackTop = stackTop - 1u;
|
|
714
|
+
let node = stack[stackBase + stackTop];
|
|
715
|
+
|
|
716
|
+
// Barnes-Hut criterion: max axis extent\xB2 vs \u03B8\xB2 \xD7 d\xB2 (matches d3-force-3d's
|
|
717
|
+
// cubic-cell \`w\xB2 < l \xD7 \u03B8\xB2\`, where w is the cell edge length).
|
|
718
|
+
let aMin = aabbBuffer[2u * node].xyz;
|
|
719
|
+
let aMax = aabbBuffer[2u * node + 1u].xyz;
|
|
720
|
+
let com = comBuffer[node];
|
|
721
|
+
let diff = com.xyz - queryPos;
|
|
722
|
+
let d2_raw = max(dot(diff, diff), 1e-12);
|
|
723
|
+
let sizeVec = aMax - aMin;
|
|
724
|
+
let maxEdge = max(sizeVec.x, max(sizeVec.y, sizeVec.z));
|
|
725
|
+
let s2 = maxEdge * maxEdge;
|
|
726
|
+
|
|
727
|
+
if (s2 <= params.theta2 * d2_raw) {
|
|
728
|
+
// Far enough: approximate cluster by COM with d3-distanceMin clamp.
|
|
729
|
+
let l = clampDistance(d2_raw);
|
|
730
|
+
if (l >= params.distanceMax2) { continue; }
|
|
731
|
+
let c = params.strength * params.alpha * com.w / l;
|
|
732
|
+
accum = accum + diff * c;
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
if (node < internalCount) {
|
|
737
|
+
// Internal: descend into both children.
|
|
738
|
+
let entry = internalBuf[node];
|
|
739
|
+
let leftChild = u32(entry.x);
|
|
740
|
+
let rightChild = u32(entry.y);
|
|
741
|
+
if (stackTop < MAX_DEPTH - 1u) {
|
|
742
|
+
stack[stackBase + stackTop] = leftChild; stackTop = stackTop + 1u;
|
|
743
|
+
stack[stackBase + stackTop] = rightChild; stackTop = stackTop + 1u;
|
|
744
|
+
}
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// Leaf: a single original node. Self-interaction guard.
|
|
749
|
+
let leafIdx = node - internalCount; // leaf rank in sortedIndices
|
|
750
|
+
let neighborIdx = sortedIndices[leafIdx];
|
|
751
|
+
if (neighborIdx == queryIdx) { continue; }
|
|
752
|
+
let np = positions[neighborIdx].xyz;
|
|
753
|
+
let nd = np - queryPos;
|
|
754
|
+
let nd2_raw = max(dot(nd, nd), 1e-12);
|
|
755
|
+
let nl = clampDistance(nd2_raw);
|
|
756
|
+
if (nl >= params.distanceMax2) { continue; }
|
|
757
|
+
let nc = params.strength * params.alpha / nl; // unit mass
|
|
758
|
+
accum = accum + nd * nc;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
velocities[queryIdx] = vec4<f32>(velocities[queryIdx].xyz + accum, velocities[queryIdx].w);
|
|
762
|
+
}
|
|
763
|
+
`,or=`// P3: one bitonic compare-swap step. Dispatched once per (k, j) in bitonicSortSteps().
|
|
764
|
+
|
|
765
|
+
struct SortParams { n: u32, k: u32, j: u32, _pad: u32 };
|
|
766
|
+
|
|
767
|
+
@group(0) @binding(0) var<storage, read_write> keys: array<u32>;
|
|
768
|
+
@group(0) @binding(1) var<storage, read_write> values: array<u32>;
|
|
769
|
+
@group(0) @binding(2) var<uniform> params: SortParams;
|
|
770
|
+
|
|
771
|
+
@compute @workgroup_size(64)
|
|
772
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
773
|
+
let i = gid.x;
|
|
774
|
+
if (i >= params.n) { return; }
|
|
775
|
+
let partner = i ^ params.j;
|
|
776
|
+
if (partner <= i) { return; }
|
|
777
|
+
if (partner >= params.n) { return; }
|
|
778
|
+
|
|
779
|
+
let ascending = (i & params.k) == 0u;
|
|
780
|
+
let kI = keys[i];
|
|
781
|
+
let kP = keys[partner];
|
|
782
|
+
// Parens required: bare \`kI < kP, kI > kP\` triggers WGSL template-list parsing.
|
|
783
|
+
let swap = select((kI < kP), (kI > kP), ascending);
|
|
784
|
+
if (swap) {
|
|
785
|
+
keys[i] = kP;
|
|
786
|
+
keys[partner] = kI;
|
|
787
|
+
let vI = values[i];
|
|
788
|
+
values[i] = values[partner];
|
|
789
|
+
values[partner] = vI;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
`;function sr(e){let t=[];for(let n=2;n<=e;n*=2)for(let i=n/2;i>0;i=i>>1)t.push({k:n,j:i});return t}var lr=16,ur=class{constructor(e){this.device=e,this.paramsBuffers=[];let t=e.createShaderModule({label:"lbvh-sort",code:or});this.pipeline=e.createComputePipeline({label:"lbvh-sort-pipeline",layout:"auto",compute:{module:t,entryPoint:"main"}})}ensureParamsBuffer(e){for(;this.paramsBuffers.length<=e;)this.paramsBuffers.push(this.device.createBuffer({label:`lbvh-sort-params-${this.paramsBuffers.length}`,size:lr,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}));return this.paramsBuffers[e]}sort(e,t,n,i){let r=sr(i);for(let o=0;o<r.length;o++){let{k:a,j:s}=r[o],l=this.ensureParamsBuffer(o);this.device.queue.writeBuffer(l,0,new Uint32Array([i,a,s,0]));let u=this.device.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:n}},{binding:2,resource:{buffer:l}}]}),c=e.beginComputePass({label:`bitonic k=${a} j=${s}`});c.setPipeline(this.pipeline),c.setBindGroup(0,u),c.dispatchWorkgroups(Math.ceil(i/Xn)),c.end()}}dispose(){for(let e of this.paramsBuffers)e.destroy();this.paramsBuffers=[]}},cr=class{constructor(e,t){this.ctx=e,this.buffers=t,this.depthsParamsBufs=[],this.reduceParamsBufs=[],this.depthsBG_AtoB=[],this.depthsBG_BtoA=[],this.reduceLevelBGs=[],this.nodeCount=0,this.theta=.9,this.strength=-30,this.distanceMin=1,this.distanceMax=1/0,this.nodeCount=e.nodeCount,this.init()}setTheta(e){this.theta=e}setStrength(e){this.strength=e}setDistanceMin(e){this.distanceMin=e}setDistanceMax(e){this.distanceMax=e}init(){let e=this.ctx.device,t=(o,a=16)=>e.createBuffer({label:o,size:a,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.boundsParamsBuf=t("lbvh-bounds-params"),this.mortonParamsBuf=t("lbvh-morton-params"),this.buildParamsBuf=t("lbvh-build-params"),this.findRootParamsBuf=t("lbvh-find-root-params"),this.traverseParamsBuf=t("lbvh-traverse-params",32);for(let o=0;o<Te;o++){let a=t(`lbvh-depths-params-${o}`);e.queue.writeBuffer(a,0,new Uint32Array([this.nodeCount,o,0,0])),this.depthsParamsBufs.push(a)}for(let o=0;o<=Te;o++){let a=t(`lbvh-reduce-params-${o}`);e.queue.writeBuffer(a,0,new Uint32Array([this.nodeCount,o===0?0:o-1,0,0])),this.reduceParamsBufs.push(a)}let n=(o,a)=>e.createShaderModule({label:o,code:a}),i=(o,a,s)=>e.createComputePipeline({label:o,layout:"auto",compute:{module:a,entryPoint:s}});this.boundsPipeline=i("lbvh-bounds",n("lbvh-bounds",Et),"main"),this.mortonPipeline=i("lbvh-morton",n("lbvh-morton",er),"main"),this.buildPipeline=i("lbvh-build",n("lbvh-build",tr),"main"),this.findRootPipeline=i("lbvh-find-root",n("lbvh-find-root",nr),"main"),this.depthsPipeline=i("lbvh-depths",n("lbvh-depths",ir),"main");let r=n("lbvh-reduce",rr);this.reduceLeafInitPipeline=i("lbvh-reduce-leafInit",r,"leafInit"),this.reduceLevelPipeline=i("lbvh-reduce-level",r,"levelReduce"),this.traversePipeline=i("lbvh-traverse",n("lbvh-traverse",ar),"main"),this.sortPass=new ur(e),this.bindAll()}bindAll(){let e=this.ctx.device,t=this.buffers,n=this.ctx;this.boundsBG=e.createBindGroup({layout:this.boundsPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:n.positions}},{binding:1,resource:{buffer:t.bounds}},{binding:2,resource:{buffer:this.boundsParamsBuf}}]}),this.mortonBG=e.createBindGroup({layout:this.mortonPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:n.positions}},{binding:1,resource:{buffer:t.bounds}},{binding:2,resource:{buffer:t.morton}},{binding:3,resource:{buffer:t.sortedIndices}},{binding:4,resource:{buffer:this.mortonParamsBuf}}]}),this.buildBG=e.createBindGroup({layout:this.buildPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t.morton}},{binding:1,resource:{buffer:t.internal}},{binding:2,resource:{buffer:t.parent}},{binding:3,resource:{buffer:t.aabb}},{binding:4,resource:{buffer:t.sortedIndices}},{binding:5,resource:{buffer:n.positions}},{binding:6,resource:{buffer:this.buildParamsBuf}}]}),this.findRootBG=e.createBindGroup({layout:this.findRootPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t.parent}},{binding:1,resource:{buffer:t.root}},{binding:2,resource:{buffer:this.findRootParamsBuf}}]});for(let i=0;i<Te;i++)this.depthsBG_AtoB.push(e.createBindGroup({layout:this.depthsPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t.internal}},{binding:1,resource:{buffer:t.depthQueueA}},{binding:2,resource:{buffer:t.depthQueueB}},{binding:3,resource:{buffer:t.frontierCounts}},{binding:4,resource:{buffer:t.depth}},{binding:5,resource:{buffer:this.depthsParamsBufs[i]}}]})),this.depthsBG_BtoA.push(e.createBindGroup({layout:this.depthsPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t.internal}},{binding:1,resource:{buffer:t.depthQueueB}},{binding:2,resource:{buffer:t.depthQueueA}},{binding:3,resource:{buffer:t.frontierCounts}},{binding:4,resource:{buffer:t.depth}},{binding:5,resource:{buffer:this.depthsParamsBufs[i]}}]}));this.reduceLeafInitBG=e.createBindGroup({layout:this.reduceLeafInitPipeline.getBindGroupLayout(0),entries:[{binding:1,resource:{buffer:t.com}},{binding:4,resource:{buffer:t.sortedIndices}},{binding:5,resource:{buffer:n.positions}},{binding:6,resource:{buffer:this.reduceParamsBufs[0]}}]});for(let i=0;i<Te;i++)this.reduceLevelBGs.push(e.createBindGroup({layout:this.reduceLevelPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t.internal}},{binding:1,resource:{buffer:t.com}},{binding:2,resource:{buffer:t.aabb}},{binding:3,resource:{buffer:t.depth}},{binding:6,resource:{buffer:this.reduceParamsBufs[i+1]}}]}));this.traverseBG=e.createBindGroup({layout:this.traversePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:n.positions}},{binding:1,resource:{buffer:n.velocities}},{binding:2,resource:{buffer:t.internal}},{binding:3,resource:{buffer:t.com}},{binding:4,resource:{buffer:t.aabb}},{binding:5,resource:{buffer:t.sortedIndices}},{binding:6,resource:{buffer:t.root}},{binding:7,resource:{buffer:this.traverseParamsBuf}}]}),e.queue.writeBuffer(this.boundsParamsBuf,0,new Uint32Array([this.nodeCount,0,0,0])),e.queue.writeBuffer(this.mortonParamsBuf,0,new Uint32Array([this.nodeCount,0,0,0])),e.queue.writeBuffer(this.buildParamsBuf,0,new Uint32Array([this.nodeCount,0,0,0])),e.queue.writeBuffer(this.findRootParamsBuf,0,new Uint32Array([this.nodeCount,0,0,0]))}apply(e,t){let n=this.ctx.device,i=this.nodeCount;if(i<2)return;let r=Xn,o=Math.ceil(i/r),a=Math.ceil(Math.max(1,i-1)/r),s=this.buffers.paddedN,l=new Int32Array([2147483647,-2147483648,2147483647,-2147483648,2147483647,-2147483648]);if(n.queue.writeBuffer(this.buffers.bounds,0,l),s>i){let p=new Uint32Array(s-i).fill(4294967295),g=new Uint32Array(s-i).fill(4294967295);n.queue.writeBuffer(this.buffers.morton,i*4,p),n.queue.writeBuffer(this.buffers.sortedIndices,i*4,g)}let u=new Int32Array(Math.max(1,i-1)).fill(-1);n.queue.writeBuffer(this.buffers.parent,0,u);let c=new Uint32Array(Te+1);c[0]=1,n.queue.writeBuffer(this.buffers.frontierCounts,0,c),n.queue.writeBuffer(this.buffers.root,0,new Uint32Array([0]));let d=Number.isFinite(this.distanceMax)?this.distanceMax*this.distanceMax:34e37,f=new ArrayBuffer(32);new Uint32Array(f,0,1)[0]=i,new Float32Array(f,4,5).set([this.strength,e,this.theta*this.theta,this.distanceMin*this.distanceMin,d]),n.queue.writeBuffer(this.traverseParamsBuf,0,f),this.runSimple(t,this.boundsPipeline,this.boundsBG,o,"p1-bounds"),this.runSimple(t,this.mortonPipeline,this.mortonBG,o,"p2-morton"),this.sortPass.sort(t,this.buffers.morton,this.buffers.sortedIndices,s),this.runSimple(t,this.buildPipeline,this.buildBG,Math.max(a,o),"p4-build"),this.runSimple(t,this.findRootPipeline,this.findRootBG,a,"p4b-find-root"),t.copyBufferToBuffer(this.buffers.root,0,this.buffers.depthQueueA,0,4);for(let p=0;p<Te;p++){let m=p%2===0?this.depthsBG_AtoB[p]:this.depthsBG_BtoA[p],y=t.beginComputePass({label:`p5-depths-${p}`});y.setPipeline(this.depthsPipeline),y.setBindGroup(0,m),y.dispatchWorkgroups(a),y.end()}this.runSimple(t,this.reduceLeafInitPipeline,this.reduceLeafInitBG,o,"p6-leafInit");for(let p=Te-1;p>=0;p--)this.runSimple(t,this.reduceLevelPipeline,this.reduceLevelBGs[p],a,`p6-level-${p}`);this.runSimple(t,this.traversePipeline,this.traverseBG,o,"p7-traverse")}runSimple(e,t,n,i,r){let o=e.beginComputePass({label:r});o.setPipeline(t),o.setBindGroup(0,n),o.dispatchWorkgroups(i),o.end()}dispose(){this.sortPass.dispose();for(let e of[this.boundsParamsBuf,this.mortonParamsBuf,this.buildParamsBuf,this.findRootParamsBuf,this.traverseParamsBuf,...this.depthsParamsBufs,...this.reduceParamsBufs])e.destroy()}};function Yn(){let e=-30,t=Ki,n=1,i=1/0,r=null,o=null,a={initialize(s,l,u){},initGPU(s){(o||r)&&(o?.dispose(),r?.dispose(),o=null,r=null),r=Ji(s.device,s.nodeCount,Te);let l={device:s.device,nodeCount:s.nodeCount,positions:s.positionBuffer,velocities:s.velocityBuffer};o=new cr(l,r),o.setStrength(e),o.setTheta(t),o.setDistanceMin(n),o.setDistanceMax(i)},apply(s,l){o?.apply(s,l)},dispose(){o?.dispose(),r?.dispose(),o=null,r=null},strength(s){return arguments.length===0?e:(e=+s,o?.setStrength(e),a)},theta(s){return arguments.length===0?t:(t=+s,o?.setTheta(t),a)},distanceMin(s){return arguments.length===0?n:(n=+s,o?.setDistanceMin(n),a)},distanceMax(s){return arguments.length===0?i:(i=+s,o?.setDistanceMax(i),a)}};return a}var $n=`// Clear quadtree cell buffer to zero. One thread per cell slot (4 i32s/cell).
|
|
793
|
+
//
|
|
794
|
+
// Layout:
|
|
795
|
+
// group(0)
|
|
796
|
+
// binding(0) cells array<atomic<i32>> read_write
|
|
797
|
+
// binding(1) params ClearParams uniform
|
|
798
|
+
|
|
799
|
+
struct ClearParams {
|
|
800
|
+
cellSlotCount: u32, // totalCells \xD7 CELL_STRIDE (4)
|
|
801
|
+
// Number of invocations per Y-row of the dispatch grid (= workgroupCountX \xD7 workgroup_size).
|
|
802
|
+
// Used to recover the linear slot index from a 2D dispatch. Required because the
|
|
803
|
+
// 3D octree at L=7 needs ~150k workgroups for clear, exceeding WebGPU's 65,535
|
|
804
|
+
// per-dim limit; we split across X and Y instead.
|
|
805
|
+
dispatchStrideX: u32,
|
|
806
|
+
_pad1: u32,
|
|
807
|
+
_pad2: u32,
|
|
808
|
+
};
|
|
809
|
+
|
|
810
|
+
@group(0) @binding(0) var<storage, read_write> cells: array<atomic<i32>>;
|
|
811
|
+
@group(0) @binding(1) var<uniform> params: ClearParams;
|
|
812
|
+
|
|
813
|
+
@compute @workgroup_size(64)
|
|
814
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
815
|
+
let i = gid.y * params.dispatchStrideX + gid.x;
|
|
816
|
+
if (i >= params.cellSlotCount) { return; }
|
|
817
|
+
atomicStore(&cells[i], 0);
|
|
818
|
+
}
|
|
819
|
+
`,dr=`// quad-bin: per-node atomic write of (x, y, mass) into the LEAF cell at MAX level
|
|
820
|
+
// of a fixed-depth 2D quadtree. Reads bounds directly from boundsBuffer (ordered-int
|
|
821
|
+
// encoding produced by lbvh-bounds.wgsl).
|
|
822
|
+
//
|
|
823
|
+
// Cells indexed by Morton interleave (cellX, cellY).
|
|
824
|
+
// leafOffset = (4^L - 1) / 3
|
|
825
|
+
// mortonIdx = interleave(cellX, cellY) in [0, 4^L)
|
|
826
|
+
// Fixed-point sums: position * FIXED_SCALE as i32 atomicAdd. Mass = 1 (count).
|
|
827
|
+
|
|
828
|
+
struct BinParams {
|
|
829
|
+
nodeCount: u32,
|
|
830
|
+
maxLevel: u32,
|
|
831
|
+
leafOffset: u32,
|
|
832
|
+
fixedScale: f32,
|
|
833
|
+
};
|
|
834
|
+
|
|
835
|
+
@group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
|
|
836
|
+
@group(0) @binding(1) var<storage, read_write> cells: array<atomic<i32>>;
|
|
837
|
+
@group(0) @binding(2) var<storage, read> bounds: array<i32, 6>; // xMin,xMax,yMin,yMax,zMin,zMax (ordered-int)
|
|
838
|
+
@group(0) @binding(3) var<uniform> params: BinParams;
|
|
839
|
+
|
|
840
|
+
fn orderedIntToFloat(i: i32) -> f32 {
|
|
841
|
+
return bitcast<f32>(select(i ^ 0x7FFFFFFF, i, i >= 0));
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
fn mortonExpand16(v: u32) -> u32 {
|
|
845
|
+
var x = v & 0xFFFFu;
|
|
846
|
+
x = (x | (x << 8u)) & 0x00FF00FFu;
|
|
847
|
+
x = (x | (x << 4u)) & 0x0F0F0F0Fu;
|
|
848
|
+
x = (x | (x << 2u)) & 0x33333333u;
|
|
849
|
+
x = (x | (x << 1u)) & 0x55555555u;
|
|
850
|
+
return x;
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
@compute @workgroup_size(64)
|
|
854
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
855
|
+
let i = gid.x;
|
|
856
|
+
if (i >= params.nodeCount) { return; }
|
|
857
|
+
|
|
858
|
+
let xMin = orderedIntToFloat(bounds[0]);
|
|
859
|
+
let xMax = orderedIntToFloat(bounds[1]);
|
|
860
|
+
let yMin = orderedIntToFloat(bounds[2]);
|
|
861
|
+
let yMax = orderedIntToFloat(bounds[3]);
|
|
862
|
+
let spanX = max(xMax - xMin, 1e-9);
|
|
863
|
+
let spanY = max(yMax - yMin, 1e-9);
|
|
864
|
+
|
|
865
|
+
let p = positions[i].xy;
|
|
866
|
+
let levelSize = 1u << params.maxLevel;
|
|
867
|
+
let n01 = clamp(vec2<f32>((p.x - xMin) / spanX, (p.y - yMin) / spanY),
|
|
868
|
+
vec2<f32>(0.0), vec2<f32>(0.999999));
|
|
869
|
+
let cellXi = u32(n01.x * f32(levelSize));
|
|
870
|
+
let cellYi = u32(n01.y * f32(levelSize));
|
|
871
|
+
let mortonIdx = mortonExpand16(cellXi) | (mortonExpand16(cellYi) << 1u);
|
|
872
|
+
|
|
873
|
+
let cellArrayIdx = params.leafOffset + mortonIdx;
|
|
874
|
+
let baseSlot = cellArrayIdx * 4u;
|
|
875
|
+
|
|
876
|
+
// Store raw \`p * fixedScale\` (legacy semantics). FIXED_SCALE chosen small
|
|
877
|
+
// enough that N \xD7 max|p| \xD7 scale < 2^31 (no i32 overflow at typical scales).
|
|
878
|
+
// Normalized variant tested 2026-05-21 \u2014 math was correct but produced 3\xD7
|
|
879
|
+
// wider layout than legacy at same params; reverted to raw.
|
|
880
|
+
let xFixed = i32(p.x * params.fixedScale);
|
|
881
|
+
let yFixed = i32(p.y * params.fixedScale);
|
|
882
|
+
atomicAdd(&cells[baseSlot + 0u], xFixed);
|
|
883
|
+
atomicAdd(&cells[baseSlot + 1u], yFixed);
|
|
884
|
+
atomicAdd(&cells[baseSlot + 3u], 1i);
|
|
885
|
+
}
|
|
886
|
+
`,fr=`// quad-accumulate: bottom-up COM aggregation.
|
|
887
|
+
//
|
|
888
|
+
// Dispatched once per level k (from MAX_LEVEL-1 down to 0). For each cell at
|
|
889
|
+
// level k (4^k cells), read its 4 children at level k+1 (Morton-contiguous:
|
|
890
|
+
// children of cell M are M*4, M*4+1, M*4+2, M*4+3), sum their (sum_x, sum_y,
|
|
891
|
+
// mass), write to parent slot.
|
|
892
|
+
//
|
|
893
|
+
// d3-force-3d's accumulate(): treeNode.x = \u03A3(child.x * child.mass) / \u03A3mass.
|
|
894
|
+
// We store (sum_x, sum_y, mass) directly (no division yet) \u2014 traverse divides
|
|
895
|
+
// at read time. Avoids precision loss from premature division.
|
|
896
|
+
|
|
897
|
+
struct AccumParams {
|
|
898
|
+
parentOffset: u32, // (4^k - 1) / 3 \u2014 offset of level k cells
|
|
899
|
+
childOffset: u32, // (4^(k+1) - 1) / 3 \u2014 offset of level k+1 cells
|
|
900
|
+
parentCount: u32, // 4^k \u2014 number of cells at parent level
|
|
901
|
+
_pad: u32,
|
|
902
|
+
};
|
|
903
|
+
|
|
904
|
+
@group(0) @binding(0) var<storage, read_write> cells: array<atomic<i32>>;
|
|
905
|
+
@group(0) @binding(1) var<uniform> params: AccumParams;
|
|
906
|
+
|
|
907
|
+
@compute @workgroup_size(64)
|
|
908
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
909
|
+
let pi = gid.x;
|
|
910
|
+
if (pi >= params.parentCount) { return; }
|
|
911
|
+
|
|
912
|
+
let parentBase = (params.parentOffset + pi) * 4u;
|
|
913
|
+
let child0Base = (params.childOffset + pi * 4u) * 4u;
|
|
914
|
+
|
|
915
|
+
var sx: i32 = 0;
|
|
916
|
+
var sy: i32 = 0;
|
|
917
|
+
var sm: i32 = 0;
|
|
918
|
+
for (var c: u32 = 0u; c < 4u; c = c + 1u) {
|
|
919
|
+
let cb = child0Base + c * 4u;
|
|
920
|
+
sx = sx + atomicLoad(&cells[cb + 0u]);
|
|
921
|
+
sy = sy + atomicLoad(&cells[cb + 1u]);
|
|
922
|
+
sm = sm + atomicLoad(&cells[cb + 3u]);
|
|
923
|
+
}
|
|
924
|
+
atomicStore(&cells[parentBase + 0u], sx);
|
|
925
|
+
atomicStore(&cells[parentBase + 1u], sy);
|
|
926
|
+
atomicStore(&cells[parentBase + 3u], sm);
|
|
927
|
+
}
|
|
928
|
+
`,pr=`// quad-traverse: per-query-node Barnes-Hut DFS over a fixed-depth 2D quadtree.
|
|
929
|
+
// Matches d3-force-3d's apply() (manyBody.js).
|
|
930
|
+
//
|
|
931
|
+
// Reads bounds directly from boundsBuffer to compute cellWidth at each level.
|
|
932
|
+
// 2D only \u2014 z component of position/velocity untouched.
|
|
933
|
+
|
|
934
|
+
struct TraverseParams {
|
|
935
|
+
nodeCount: u32,
|
|
936
|
+
maxLevel: u32,
|
|
937
|
+
_pad0: u32,
|
|
938
|
+
_pad1: u32,
|
|
939
|
+
strength: f32,
|
|
940
|
+
alpha: f32,
|
|
941
|
+
theta2: f32,
|
|
942
|
+
distanceMin2: f32,
|
|
943
|
+
distanceMax2: f32,
|
|
944
|
+
fixedScale: f32,
|
|
945
|
+
_pad2: f32,
|
|
946
|
+
_pad3: f32,
|
|
947
|
+
};
|
|
948
|
+
|
|
949
|
+
@group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
|
|
950
|
+
@group(0) @binding(1) var<storage, read_write> velocities: array<vec4<f32>>;
|
|
951
|
+
// atomic variables MUST be read_write in WGSL (even when only atomicLoad-ed).
|
|
952
|
+
@group(0) @binding(2) var<storage, read_write> cells: array<atomic<i32>>;
|
|
953
|
+
@group(0) @binding(3) var<storage, read> levelOffsets: array<u32>;
|
|
954
|
+
@group(0) @binding(4) var<storage, read> bounds: array<i32, 6>;
|
|
955
|
+
@group(0) @binding(5) var<uniform> params: TraverseParams;
|
|
956
|
+
|
|
957
|
+
fn orderedIntToFloat(i: i32) -> f32 {
|
|
958
|
+
return bitcast<f32>(select(i ^ 0x7FFFFFFF, i, i >= 0));
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
// 16-bit value \u2192 32-bit interleaved (kept in sync with quad-bin.wgsl). Used to
|
|
962
|
+
// compute the query's own leaf cellIdx so the leaf-level branch can subtract
|
|
963
|
+
// the query's contribution from the cell COM (leaf-COM fix; see
|
|
964
|
+
// oct-traverse.wgsl for the 3D analogue).
|
|
965
|
+
fn mortonExpand16(v: u32) -> u32 {
|
|
966
|
+
var x = v & 0xFFFFu;
|
|
967
|
+
x = (x | (x << 8u)) & 0x00FF00FFu;
|
|
968
|
+
x = (x | (x << 4u)) & 0x0F0F0F0Fu;
|
|
969
|
+
x = (x | (x << 2u)) & 0x33333333u;
|
|
970
|
+
x = (x | (x << 1u)) & 0x55555555u;
|
|
971
|
+
return x;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
// MAX_STACK=32: max tree depth = 8 levels, each internal pop pushes 4 \u2192 worst-case
|
|
975
|
+
// stack depth \u2264 4 \xD7 maxLevel = 32. Workgroup memory: 64 \xD7 32 \xD7 4 = 8 KB (limit 16 KB).
|
|
976
|
+
// Pack (level, cellIdx) into single u32: high 8 bits = level (0..32), low 24 bits =
|
|
977
|
+
// cellIdx (max 87381 = ((4^9-1)/3) fits in 17 bits, plenty of room in 24).
|
|
978
|
+
const WG_SIZE: u32 = 64u;
|
|
979
|
+
const MAX_STACK: u32 = 32u;
|
|
980
|
+
var<workgroup> stack: array<u32, 2048>; // WG_SIZE \xD7 MAX_STACK
|
|
981
|
+
|
|
982
|
+
@compute @workgroup_size(64)
|
|
983
|
+
fn main(
|
|
984
|
+
@builtin(global_invocation_id) gid: vec3<u32>,
|
|
985
|
+
@builtin(local_invocation_index) lid: u32,
|
|
986
|
+
) {
|
|
987
|
+
let queryIdx = gid.x;
|
|
988
|
+
if (queryIdx >= params.nodeCount) { return; }
|
|
989
|
+
|
|
990
|
+
let qp = positions[queryIdx].xy;
|
|
991
|
+
var accum = vec2<f32>(0.0, 0.0);
|
|
992
|
+
let stackBase = lid * MAX_STACK;
|
|
993
|
+
let invScale = 1.0 / params.fixedScale;
|
|
994
|
+
|
|
995
|
+
let xMin = orderedIntToFloat(bounds[0]);
|
|
996
|
+
let xMax = orderedIntToFloat(bounds[1]);
|
|
997
|
+
let yMin = orderedIntToFloat(bounds[2]);
|
|
998
|
+
let yMax = orderedIntToFloat(bounds[3]);
|
|
999
|
+
let boundsMax = max(xMax - xMin, yMax - yMin);
|
|
1000
|
+
|
|
1001
|
+
// Precompute query's own leaf cellIdx (same mapping as quad-bin.wgsl) so the
|
|
1002
|
+
// leaf-level branch can subtract self-contribution and avoid the cross-star.
|
|
1003
|
+
let spanXq = max(xMax - xMin, 1e-9);
|
|
1004
|
+
let spanYq = max(yMax - yMin, 1e-9);
|
|
1005
|
+
let levelSizeMax = 1u << params.maxLevel;
|
|
1006
|
+
let n01q = clamp(
|
|
1007
|
+
vec2<f32>((qp.x - xMin) / spanXq, (qp.y - yMin) / spanYq),
|
|
1008
|
+
vec2<f32>(0.0), vec2<f32>(0.999999));
|
|
1009
|
+
let qcx = u32(n01q.x * f32(levelSizeMax));
|
|
1010
|
+
let qcy = u32(n01q.y * f32(levelSizeMax));
|
|
1011
|
+
let queryMorton = mortonExpand16(qcx) | (mortonExpand16(qcy) << 1u);
|
|
1012
|
+
let queryLeafCellIdx = levelOffsets[params.maxLevel] + queryMorton;
|
|
1013
|
+
|
|
1014
|
+
// Push root: level=0, cellIdx=0. Packed: (0 << 24) | 0 = 0.
|
|
1015
|
+
var top: u32 = 0u;
|
|
1016
|
+
stack[stackBase + top] = 0u;
|
|
1017
|
+
top = top + 1u;
|
|
1018
|
+
|
|
1019
|
+
loop {
|
|
1020
|
+
if (top == 0u) { break; }
|
|
1021
|
+
top = top - 1u;
|
|
1022
|
+
let packed = stack[stackBase + top];
|
|
1023
|
+
let level = packed >> 24u;
|
|
1024
|
+
let cellIdx = packed & 0x00FFFFFFu;
|
|
1025
|
+
|
|
1026
|
+
let cb = cellIdx * 4u;
|
|
1027
|
+
let mass = f32(atomicLoad(&cells[cb + 3u]));
|
|
1028
|
+
if (mass < 0.5) { continue; }
|
|
1029
|
+
let sumX = f32(atomicLoad(&cells[cb + 0u])) * invScale;
|
|
1030
|
+
let sumY = f32(atomicLoad(&cells[cb + 1u])) * invScale;
|
|
1031
|
+
let comX = sumX / mass;
|
|
1032
|
+
let comY = sumY / mass;
|
|
1033
|
+
|
|
1034
|
+
let levelSize = f32(1u << level);
|
|
1035
|
+
let cellWidth = boundsMax / levelSize;
|
|
1036
|
+
|
|
1037
|
+
let dx = comX - qp.x;
|
|
1038
|
+
let dy = comY - qp.y;
|
|
1039
|
+
let l = max(dx * dx + dy * dy, 1e-12);
|
|
1040
|
+
|
|
1041
|
+
// BH criterion: cellWidth\xB2 / \u03B8\xB2 < l \u27FA cellWidth\xB2 < l \xD7 \u03B8\xB2
|
|
1042
|
+
if (cellWidth * cellWidth < l * params.theta2) {
|
|
1043
|
+
var l2 = l;
|
|
1044
|
+
if (l2 >= params.distanceMax2) { continue; }
|
|
1045
|
+
if (l2 < params.distanceMin2) { l2 = sqrt(params.distanceMin2 * l2); }
|
|
1046
|
+
let c = params.strength * mass * params.alpha / l2;
|
|
1047
|
+
accum.x = accum.x + dx * c;
|
|
1048
|
+
accum.y = accum.y + dy * c;
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
if (level >= params.maxLevel) {
|
|
1053
|
+
// Leaf-COM fix: if this leaf is the query's own cell, subtract the
|
|
1054
|
+
// query's (x, y, 1) contribution from the cell sum/count so the effective
|
|
1055
|
+
// COM is the centroid of the OTHER nodes in the leaf. See oct-traverse
|
|
1056
|
+
// for rationale (cross-star avoidance on dense graphs).
|
|
1057
|
+
if (cellIdx == queryLeafCellIdx) {
|
|
1058
|
+
let adjMass = mass - 1.0;
|
|
1059
|
+
if (adjMass < 0.5) { continue; } // query was the sole occupant
|
|
1060
|
+
let adjSumX = sumX - qp.x;
|
|
1061
|
+
let adjSumY = sumY - qp.y;
|
|
1062
|
+
let adjComX = adjSumX / adjMass;
|
|
1063
|
+
let adjComY = adjSumY / adjMass;
|
|
1064
|
+
let dxa = adjComX - qp.x;
|
|
1065
|
+
let dya = adjComY - qp.y;
|
|
1066
|
+
var la = max(dxa * dxa + dya * dya, 1e-12);
|
|
1067
|
+
if (la >= params.distanceMax2) { continue; }
|
|
1068
|
+
if (la < params.distanceMin2) { la = sqrt(params.distanceMin2 * la); }
|
|
1069
|
+
let ca = params.strength * adjMass * params.alpha / la;
|
|
1070
|
+
accum.x = accum.x + dxa * ca;
|
|
1071
|
+
accum.y = accum.y + dya * ca;
|
|
1072
|
+
continue;
|
|
1073
|
+
}
|
|
1074
|
+
// Leaf cell: apply COM aggregate (mass nodes). Self-interaction guard:
|
|
1075
|
+
// if leaf contains only this query node, COM == queryPos \u2192 dx=dy=0 \u2192 skip.
|
|
1076
|
+
let isSelf = (mass < 1.5) && (abs(dx) < 1e-6) && (abs(dy) < 1e-6);
|
|
1077
|
+
if (isSelf) { continue; }
|
|
1078
|
+
var l2 = l;
|
|
1079
|
+
if (l2 >= params.distanceMax2) { continue; }
|
|
1080
|
+
if (l2 < params.distanceMin2) { l2 = sqrt(params.distanceMin2 * l2); }
|
|
1081
|
+
let c = params.strength * mass * params.alpha / l2;
|
|
1082
|
+
accum.x = accum.x + dx * c;
|
|
1083
|
+
accum.y = accum.y + dy * c;
|
|
1084
|
+
continue;
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
// Descend into 4 children. Children of cell at Morton M, level k are at
|
|
1088
|
+
// level k+1, Morton M*4..M*4+3, stored at levelOffsets[k+1] + M*4 + c.
|
|
1089
|
+
let parentMorton = cellIdx - levelOffsets[level];
|
|
1090
|
+
let childBase = levelOffsets[level + 1u] + parentMorton * 4u;
|
|
1091
|
+
if (top + 4u <= MAX_STACK) {
|
|
1092
|
+
let nextLevel = level + 1u;
|
|
1093
|
+
for (var c: u32 = 0u; c < 4u; c = c + 1u) {
|
|
1094
|
+
stack[stackBase + top] = (nextLevel << 24u) | (childBase + c);
|
|
1095
|
+
top = top + 1u;
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
velocities[queryIdx] = vec4<f32>(
|
|
1101
|
+
velocities[queryIdx].x + accum.x,
|
|
1102
|
+
velocities[queryIdx].y + accum.y,
|
|
1103
|
+
velocities[queryIdx].z,
|
|
1104
|
+
velocities[queryIdx].w,
|
|
1105
|
+
);
|
|
1106
|
+
}
|
|
1107
|
+
`,hr=8,St=64,Cn=64,Tt=4;function mr(e){return Math.floor((Math.pow(4,e+1)-1)/3)}function it(e){return Math.floor((Math.pow(4,e)-1)/3)}var gr=class{constructor(e,t=hr){this.accumParamsBufs=[],this.accumBGs=[],this.config={strength:-30,theta:.9,distanceMin:1,distanceMax:1/0},this.device=e.device,this.nodeCount=e.nodeCount,this.maxLevel=t,this.totalCells=mr(t);let n=this.device,i=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST;this.cellsBuffer=n.createBuffer({label:"quad-cells",size:this.totalCells*Tt*4,usage:i}),this.boundsBuffer=n.createBuffer({label:"quad-bounds",size:32,usage:i}),this.levelOffsetsBuffer=n.createBuffer({label:"quad-level-offsets",size:(t+1)*4,usage:i});let o=new Uint32Array(t+1);for(let d=0;d<=t;d++)o[d]=it(d);n.queue.writeBuffer(this.levelOffsetsBuffer,0,o),this.boundsParamsBuf=n.createBuffer({label:"quad-bounds-params",size:16,usage:r}),this.clearParamsBuf=n.createBuffer({label:"quad-clear-params",size:16,usage:r}),this.binParamsBuf=n.createBuffer({label:"quad-bin-params",size:16,usage:r}),this.traverseParamsBuf=n.createBuffer({label:"quad-traverse-params",size:48,usage:r});for(let d=0;d<t;d++){let f=n.createBuffer({label:`quad-accum-params-L${d}`,size:16,usage:r}),p=new Uint32Array([it(d),it(d+1),Math.pow(4,d),0]);n.queue.writeBuffer(f,0,p),this.accumParamsBufs.push(f)}let a=this.totalCells*Tt,l=Math.ceil(a/St)*St;n.queue.writeBuffer(this.clearParamsBuf,0,new Uint32Array([a,l,0,0]));let u=(d,f)=>n.createShaderModule({label:d,code:f}),c=(d,f,p="main")=>n.createComputePipeline({label:d,layout:"auto",compute:{module:f,entryPoint:p}});this.boundsPipeline=c("quad-bounds-pipe",u("quad-bounds",Et)),this.clearPipeline=c("quad-clear-pipe",u("quad-clear",$n)),this.binPipeline=c("quad-bin-pipe",u("quad-bin",dr)),this.accumPipeline=c("quad-accum-pipe",u("quad-accum",fr)),this.traversePipeline=c("quad-traverse-pipe",u("quad-traverse",pr)),this.bindAll(e)}bindAll(e){let t=this.device;this.boundsBG=t.createBindGroup({layout:this.boundsPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.positionBuffer}},{binding:1,resource:{buffer:this.boundsBuffer}},{binding:2,resource:{buffer:this.boundsParamsBuf}}]}),this.clearBG=t.createBindGroup({layout:this.clearPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.cellsBuffer}},{binding:1,resource:{buffer:this.clearParamsBuf}}]}),this.binBG=t.createBindGroup({layout:this.binPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.positionBuffer}},{binding:1,resource:{buffer:this.cellsBuffer}},{binding:2,resource:{buffer:this.boundsBuffer}},{binding:3,resource:{buffer:this.binParamsBuf}}]});for(let i=0;i<this.maxLevel;i++)this.accumBGs.push(t.createBindGroup({layout:this.accumPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.cellsBuffer}},{binding:1,resource:{buffer:this.accumParamsBufs[i]}}]}));this.traverseBG=t.createBindGroup({layout:this.traversePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.positionBuffer}},{binding:1,resource:{buffer:e.velocityBuffer}},{binding:2,resource:{buffer:this.cellsBuffer}},{binding:3,resource:{buffer:this.levelOffsetsBuffer}},{binding:4,resource:{buffer:this.boundsBuffer}},{binding:5,resource:{buffer:this.traverseParamsBuf}}]});let n=new ArrayBuffer(16);new Uint32Array(n,0,3).set([this.nodeCount,this.maxLevel,it(this.maxLevel)]),new Float32Array(n,12,1)[0]=Cn,t.queue.writeBuffer(this.binParamsBuf,0,n),t.queue.writeBuffer(this.boundsParamsBuf,0,new Uint32Array([this.nodeCount,0,0,0]))}setConfig(e){Object.assign(this.config,e)}apply(e,t){let n=this.device,i=this.nodeCount,r=St,o=new Int32Array([2147483647,-2147483648,2147483647,-2147483648,2147483647,-2147483648]);n.queue.writeBuffer(this.boundsBuffer,0,o),this.run(t,this.boundsPipeline,this.boundsBG,Math.ceil(i/r),"quad-p1-bounds"),this.run(t,this.clearPipeline,this.clearBG,Math.ceil(this.totalCells*Tt/r),"quad-p2-clear"),this.run(t,this.binPipeline,this.binBG,Math.ceil(i/r),"quad-p3-bin");for(let u=this.maxLevel-1;u>=0;u--)this.run(t,this.accumPipeline,this.accumBGs[u],Math.ceil(Math.pow(4,u)/r),`quad-p4-accum-L${u}`);let a=new ArrayBuffer(48),s=new Uint32Array(a),l=new Float32Array(a);s[0]=i,s[1]=this.maxLevel,l[4]=this.config.strength,l[5]=e,l[6]=this.config.theta*this.config.theta,l[7]=this.config.distanceMin*this.config.distanceMin,l[8]=this.config.distanceMax===1/0?1e30:this.config.distanceMax*this.config.distanceMax,l[9]=Cn,n.queue.writeBuffer(this.traverseParamsBuf,0,a),this.run(t,this.traversePipeline,this.traverseBG,Math.ceil(i/r),"quad-p5-traverse")}run(e,t,n,i,r){let o=e.beginComputePass({label:r});o.setPipeline(t),o.setBindGroup(0,n),o.dispatchWorkgroups(i),o.end()}dispose(){this.cellsBuffer.destroy(),this.boundsBuffer.destroy(),this.levelOffsetsBuffer.destroy(),this.boundsParamsBuf.destroy(),this.clearParamsBuf.destroy(),this.binParamsBuf.destroy(),this.traverseParamsBuf.destroy(),this.accumParamsBufs.forEach(e=>e.destroy())}};function yr(){let e=-30,t=1,n=1/0,i=.9,r=null,o={initialize(a,s,l){},initGPU(a){r?.dispose(),r=new gr(a),r.setConfig({strength:e,theta:i,distanceMin:t,distanceMax:n})},apply(a,s){r?.apply(a,s)},dispose(){r?.dispose(),r=null},strength(a){return arguments.length===0?e:(e=+a,r?.setConfig({strength:e}),o)},distanceMin(a){return arguments.length===0?t:(t=+a,r?.setConfig({distanceMin:t}),o)},distanceMax(a){return arguments.length===0?n:(n=+a,r?.setConfig({distanceMax:n}),o)},theta(a){return arguments.length===0?i:(i=+a,r?.setConfig({theta:i}),o)}};return o}var vr=`// oct-bin: 3D version of quad-bin. Per-node atomic write of (x, y, z, mass)
|
|
1108
|
+
// into the LEAF cell at MAX level of a fixed-depth 3D octree.
|
|
1109
|
+
// Cell address: leafOffset + morton3D(cellX, cellY, cellZ).
|
|
1110
|
+
|
|
1111
|
+
struct BinParams {
|
|
1112
|
+
nodeCount: u32,
|
|
1113
|
+
maxLevel: u32,
|
|
1114
|
+
leafOffset: u32,
|
|
1115
|
+
fixedScale: f32,
|
|
1116
|
+
};
|
|
1117
|
+
|
|
1118
|
+
@group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
|
|
1119
|
+
@group(0) @binding(1) var<storage, read_write> cells: array<atomic<i32>>;
|
|
1120
|
+
@group(0) @binding(2) var<storage, read> bounds: array<i32, 6>;
|
|
1121
|
+
@group(0) @binding(3) var<uniform> params: BinParams;
|
|
1122
|
+
|
|
1123
|
+
fn orderedIntToFloat(i: i32) -> f32 {
|
|
1124
|
+
return bitcast<f32>(select(i ^ 0x7FFFFFFF, i, i >= 0));
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
// 10-bit value \u2192 30-bit interleaved (each input bit at every 3rd output bit).
|
|
1128
|
+
fn mortonExpand10(v: u32) -> u32 {
|
|
1129
|
+
var x = v & 0x3FFu;
|
|
1130
|
+
x = (x | (x << 16u)) & 0x030000FFu;
|
|
1131
|
+
x = (x | (x << 8u)) & 0x0300F00Fu;
|
|
1132
|
+
x = (x | (x << 4u)) & 0x030C30C3u;
|
|
1133
|
+
x = (x | (x << 2u)) & 0x09249249u;
|
|
1134
|
+
return x;
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
@compute @workgroup_size(64)
|
|
1138
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
1139
|
+
let i = gid.x;
|
|
1140
|
+
if (i >= params.nodeCount) { return; }
|
|
1141
|
+
|
|
1142
|
+
let xMin = orderedIntToFloat(bounds[0]);
|
|
1143
|
+
let xMax = orderedIntToFloat(bounds[1]);
|
|
1144
|
+
let yMin = orderedIntToFloat(bounds[2]);
|
|
1145
|
+
let yMax = orderedIntToFloat(bounds[3]);
|
|
1146
|
+
let zMin = orderedIntToFloat(bounds[4]);
|
|
1147
|
+
let zMax = orderedIntToFloat(bounds[5]);
|
|
1148
|
+
let spanX = max(xMax - xMin, 1e-9);
|
|
1149
|
+
let spanY = max(yMax - yMin, 1e-9);
|
|
1150
|
+
let spanZ = max(zMax - zMin, 1e-9);
|
|
1151
|
+
|
|
1152
|
+
let p = positions[i].xyz;
|
|
1153
|
+
let levelSize = 1u << params.maxLevel;
|
|
1154
|
+
let n01 = clamp(
|
|
1155
|
+
vec3<f32>((p.x - xMin) / spanX, (p.y - yMin) / spanY, (p.z - zMin) / spanZ),
|
|
1156
|
+
vec3<f32>(0.0), vec3<f32>(0.999999));
|
|
1157
|
+
let cellXi = u32(n01.x * f32(levelSize));
|
|
1158
|
+
let cellYi = u32(n01.y * f32(levelSize));
|
|
1159
|
+
let cellZi = u32(n01.z * f32(levelSize));
|
|
1160
|
+
let mortonIdx =
|
|
1161
|
+
mortonExpand10(cellXi)
|
|
1162
|
+
| (mortonExpand10(cellYi) << 1u)
|
|
1163
|
+
| (mortonExpand10(cellZi) << 2u);
|
|
1164
|
+
|
|
1165
|
+
let cellArrayIdx = params.leafOffset + mortonIdx;
|
|
1166
|
+
let baseSlot = cellArrayIdx * 4u;
|
|
1167
|
+
|
|
1168
|
+
// Store raw \`p * fixedScale\` (legacy semantics).
|
|
1169
|
+
let xFixed = i32(p.x * params.fixedScale);
|
|
1170
|
+
let yFixed = i32(p.y * params.fixedScale);
|
|
1171
|
+
let zFixed = i32(p.z * params.fixedScale);
|
|
1172
|
+
atomicAdd(&cells[baseSlot + 0u], xFixed);
|
|
1173
|
+
atomicAdd(&cells[baseSlot + 1u], yFixed);
|
|
1174
|
+
atomicAdd(&cells[baseSlot + 2u], zFixed);
|
|
1175
|
+
atomicAdd(&cells[baseSlot + 3u], 1i);
|
|
1176
|
+
}
|
|
1177
|
+
`,xr=`// oct-accumulate: bottom-up COM aggregation for 3D octree.
|
|
1178
|
+
//
|
|
1179
|
+
// Mirrors d3-force-3d's manyBody accumulate:
|
|
1180
|
+
// strength += child.value;
|
|
1181
|
+
// strength *= Math.sqrt(4 / numChildren); // 0.707 for octree (8 children)
|
|
1182
|
+
//
|
|
1183
|
+
// Implemented by scaling the parent's accumulated MASS by sqrt(4/8) = 0.707 in
|
|
1184
|
+
// fixed-point. (Sum_x/Sum_y/Sum_z keep the un-scaled position-weighted sums;
|
|
1185
|
+
// COM at traverse is sum/mass, so mass scaling makes the force F = strength *
|
|
1186
|
+
// mass * alpha / l\xB2 also scale by 0.707 \u2014 matching d3 exactly.)
|
|
1187
|
+
|
|
1188
|
+
struct AccumParams {
|
|
1189
|
+
parentOffset: u32,
|
|
1190
|
+
childOffset: u32,
|
|
1191
|
+
parentCount: u32, // 8^k
|
|
1192
|
+
_pad: u32,
|
|
1193
|
+
};
|
|
1194
|
+
|
|
1195
|
+
@group(0) @binding(0) var<storage, read_write> cells: array<atomic<i32>>;
|
|
1196
|
+
@group(0) @binding(1) var<uniform> params: AccumParams;
|
|
1197
|
+
|
|
1198
|
+
@compute @workgroup_size(64)
|
|
1199
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
1200
|
+
let pi = gid.x;
|
|
1201
|
+
if (pi >= params.parentCount) { return; }
|
|
1202
|
+
|
|
1203
|
+
let parentBase = (params.parentOffset + pi) * 4u;
|
|
1204
|
+
let child0Base = (params.childOffset + pi * 8u) * 4u;
|
|
1205
|
+
|
|
1206
|
+
var sx: i32 = 0;
|
|
1207
|
+
var sy: i32 = 0;
|
|
1208
|
+
var sz: i32 = 0;
|
|
1209
|
+
var sm: i32 = 0;
|
|
1210
|
+
for (var c: u32 = 0u; c < 8u; c = c + 1u) {
|
|
1211
|
+
let cb = child0Base + c * 4u;
|
|
1212
|
+
sx = sx + atomicLoad(&cells[cb + 0u]);
|
|
1213
|
+
sy = sy + atomicLoad(&cells[cb + 1u]);
|
|
1214
|
+
sz = sz + atomicLoad(&cells[cb + 2u]);
|
|
1215
|
+
sm = sm + atomicLoad(&cells[cb + 3u]);
|
|
1216
|
+
}
|
|
1217
|
+
// Store UNSCALED sums + UNSCALED count. d3's sqrt(4/numChildren) scaling
|
|
1218
|
+
// is applied at FORCE APPLICATION time in oct-traverse using the cell's
|
|
1219
|
+
// level \u2014 keeps COM = sum/count correct (scaled COM would inflate positions).
|
|
1220
|
+
atomicStore(&cells[parentBase + 0u], sx);
|
|
1221
|
+
atomicStore(&cells[parentBase + 1u], sy);
|
|
1222
|
+
atomicStore(&cells[parentBase + 2u], sz);
|
|
1223
|
+
atomicStore(&cells[parentBase + 3u], sm);
|
|
1224
|
+
}
|
|
1225
|
+
`,br=`// oct-traverse: per-query-node Barnes-Hut DFS over fixed-depth 3D octree.
|
|
1226
|
+
// Mirrors quad-traverse.wgsl with 8 children per cell + z axis.
|
|
1227
|
+
//
|
|
1228
|
+
// BH criterion uses MAX axis extent of bounds (cell width = boundsMax / 2^level).
|
|
1229
|
+
|
|
1230
|
+
struct TraverseParams {
|
|
1231
|
+
nodeCount: u32,
|
|
1232
|
+
maxLevel: u32,
|
|
1233
|
+
_pad0: u32,
|
|
1234
|
+
_pad1: u32,
|
|
1235
|
+
strength: f32,
|
|
1236
|
+
alpha: f32,
|
|
1237
|
+
theta2: f32,
|
|
1238
|
+
distanceMin2: f32,
|
|
1239
|
+
distanceMax2: f32,
|
|
1240
|
+
fixedScale: f32,
|
|
1241
|
+
_pad2: f32,
|
|
1242
|
+
_pad3: f32,
|
|
1243
|
+
};
|
|
1244
|
+
|
|
1245
|
+
@group(0) @binding(0) var<storage, read> positions: array<vec4<f32>>;
|
|
1246
|
+
@group(0) @binding(1) var<storage, read_write> velocities: array<vec4<f32>>;
|
|
1247
|
+
@group(0) @binding(2) var<storage, read_write> cells: array<atomic<i32>>;
|
|
1248
|
+
@group(0) @binding(3) var<storage, read> levelOffsets: array<u32>;
|
|
1249
|
+
@group(0) @binding(4) var<storage, read> bounds: array<i32, 6>;
|
|
1250
|
+
@group(0) @binding(5) var<uniform> params: TraverseParams;
|
|
1251
|
+
|
|
1252
|
+
fn orderedIntToFloat(i: i32) -> f32 {
|
|
1253
|
+
return bitcast<f32>(select(i ^ 0x7FFFFFFF, i, i >= 0));
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
// 10-bit value \u2192 30-bit interleaved (kept in sync with oct-bin.wgsl). Used to
|
|
1257
|
+
// compute the query's own leaf cellIdx so the leaf-level branch can subtract
|
|
1258
|
+
// the query's contribution from the cell COM, avoiding the d3-force-3d
|
|
1259
|
+
// non-conformance where multiple nodes share a fixed-depth leaf and the BH
|
|
1260
|
+
// approximation feeds back through the query's own position (the historical
|
|
1261
|
+
// "cross-star" artifact on dense graphs \u2014 see
|
|
1262
|
+
// .harness/knowledge/gpu_force_cross_star_known_limit.md).
|
|
1263
|
+
fn mortonExpand10(v: u32) -> u32 {
|
|
1264
|
+
var x = v & 0x3FFu;
|
|
1265
|
+
x = (x | (x << 16u)) & 0x030000FFu;
|
|
1266
|
+
x = (x | (x << 8u)) & 0x0300F00Fu;
|
|
1267
|
+
x = (x | (x << 4u)) & 0x030C30C3u;
|
|
1268
|
+
x = (x | (x << 2u)) & 0x09249249u;
|
|
1269
|
+
return x;
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
// Workgroup memory: 64 \xD7 56 \xD7 4 = 14 KB (under 16 KB limit).
|
|
1273
|
+
// MAX_STACK = 56 covers worst-case DFS depth (7\xB7L + 1 = 50 for L=7) with margin.
|
|
1274
|
+
// Pack (level, cellIdx) into single u32 \u2014 level high 8 bits, cellIdx low 24.
|
|
1275
|
+
// Octree at L=7: total cells = (8^8-1)/7 = 2,396,745 = 22 bits; fits in 24.
|
|
1276
|
+
const WG_SIZE: u32 = 64u;
|
|
1277
|
+
const MAX_STACK: u32 = 56u;
|
|
1278
|
+
var<workgroup> stack: array<u32, 3584>; // WG_SIZE \xD7 MAX_STACK
|
|
1279
|
+
|
|
1280
|
+
@compute @workgroup_size(64)
|
|
1281
|
+
fn main(
|
|
1282
|
+
@builtin(global_invocation_id) gid: vec3<u32>,
|
|
1283
|
+
@builtin(local_invocation_index) lid: u32,
|
|
1284
|
+
) {
|
|
1285
|
+
let queryIdx = gid.x;
|
|
1286
|
+
if (queryIdx >= params.nodeCount) { return; }
|
|
1287
|
+
|
|
1288
|
+
let qp = positions[queryIdx].xyz;
|
|
1289
|
+
var accum = vec3<f32>(0.0, 0.0, 0.0);
|
|
1290
|
+
let stackBase = lid * MAX_STACK;
|
|
1291
|
+
let invScale = 1.0 / params.fixedScale;
|
|
1292
|
+
|
|
1293
|
+
let xMin = orderedIntToFloat(bounds[0]);
|
|
1294
|
+
let xMax = orderedIntToFloat(bounds[1]);
|
|
1295
|
+
let yMin = orderedIntToFloat(bounds[2]);
|
|
1296
|
+
let yMax = orderedIntToFloat(bounds[3]);
|
|
1297
|
+
let zMin = orderedIntToFloat(bounds[4]);
|
|
1298
|
+
let zMax = orderedIntToFloat(bounds[5]);
|
|
1299
|
+
let boundsMax = max(xMax - xMin, max(yMax - yMin, zMax - zMin));
|
|
1300
|
+
|
|
1301
|
+
// Precompute the query's own leaf cellIdx using the same Morton mapping as
|
|
1302
|
+
// oct-bin.wgsl. At leaf level we use this to detect "the cell containing me"
|
|
1303
|
+
// and subtract self-contribution from the COM (leaf-COM fix).
|
|
1304
|
+
let spanXq = max(xMax - xMin, 1e-9);
|
|
1305
|
+
let spanYq = max(yMax - yMin, 1e-9);
|
|
1306
|
+
let spanZq = max(zMax - zMin, 1e-9);
|
|
1307
|
+
let levelSizeMax = 1u << params.maxLevel;
|
|
1308
|
+
let n01q = clamp(
|
|
1309
|
+
vec3<f32>((qp.x - xMin) / spanXq, (qp.y - yMin) / spanYq, (qp.z - zMin) / spanZq),
|
|
1310
|
+
vec3<f32>(0.0), vec3<f32>(0.999999));
|
|
1311
|
+
let qcx = u32(n01q.x * f32(levelSizeMax));
|
|
1312
|
+
let qcy = u32(n01q.y * f32(levelSizeMax));
|
|
1313
|
+
let qcz = u32(n01q.z * f32(levelSizeMax));
|
|
1314
|
+
let queryMorton =
|
|
1315
|
+
mortonExpand10(qcx)
|
|
1316
|
+
| (mortonExpand10(qcy) << 1u)
|
|
1317
|
+
| (mortonExpand10(qcz) << 2u);
|
|
1318
|
+
let queryLeafCellIdx = levelOffsets[params.maxLevel] + queryMorton;
|
|
1319
|
+
|
|
1320
|
+
var top: u32 = 0u;
|
|
1321
|
+
stack[stackBase + top] = 0u; // root: level=0, cellIdx=0
|
|
1322
|
+
top = top + 1u;
|
|
1323
|
+
|
|
1324
|
+
loop {
|
|
1325
|
+
if (top == 0u) { break; }
|
|
1326
|
+
top = top - 1u;
|
|
1327
|
+
let packed = stack[stackBase + top];
|
|
1328
|
+
let level = packed >> 24u;
|
|
1329
|
+
let cellIdx = packed & 0x00FFFFFFu;
|
|
1330
|
+
|
|
1331
|
+
let cb = cellIdx * 4u;
|
|
1332
|
+
let count = f32(atomicLoad(&cells[cb + 3u])); // UN-SCALED count (true node count)
|
|
1333
|
+
if (count < 0.5) { continue; }
|
|
1334
|
+
let sumX = f32(atomicLoad(&cells[cb + 0u])) * invScale;
|
|
1335
|
+
let sumY = f32(atomicLoad(&cells[cb + 1u])) * invScale;
|
|
1336
|
+
let sumZ = f32(atomicLoad(&cells[cb + 2u])) * invScale;
|
|
1337
|
+
let comX = sumX / count;
|
|
1338
|
+
let comY = sumY / count;
|
|
1339
|
+
let comZ = sumZ / count;
|
|
1340
|
+
|
|
1341
|
+
// d3-force-3d dim scaling: effective mass at level k = count \xD7 sqrt(0.5)^(maxLevel-level).
|
|
1342
|
+
// Leaf (level==maxLevel): factor = 1. Root (level=0): factor = 0.7071^6 \u2248 0.125.
|
|
1343
|
+
// Applied here (not in accumulate) so COM = sum/count stays correct.
|
|
1344
|
+
let depthFromLeaf = params.maxLevel - level;
|
|
1345
|
+
var dimFactor: f32 = 1.0;
|
|
1346
|
+
for (var d: u32 = 0u; d < depthFromLeaf; d = d + 1u) {
|
|
1347
|
+
dimFactor = dimFactor * 0.7071067811865476;
|
|
1348
|
+
}
|
|
1349
|
+
let mass = count * dimFactor;
|
|
1350
|
+
|
|
1351
|
+
let levelSize = f32(1u << level);
|
|
1352
|
+
let cellWidth = boundsMax / levelSize;
|
|
1353
|
+
|
|
1354
|
+
let dx = comX - qp.x;
|
|
1355
|
+
let dy = comY - qp.y;
|
|
1356
|
+
let dz = comZ - qp.z;
|
|
1357
|
+
let l = max(dx * dx + dy * dy + dz * dz, 1e-12);
|
|
1358
|
+
|
|
1359
|
+
if (cellWidth * cellWidth < l * params.theta2) {
|
|
1360
|
+
var l2 = l;
|
|
1361
|
+
if (l2 >= params.distanceMax2) { continue; }
|
|
1362
|
+
if (l2 < params.distanceMin2) { l2 = sqrt(params.distanceMin2 * l2); }
|
|
1363
|
+
let c = params.strength * mass * params.alpha / l2;
|
|
1364
|
+
accum = accum + vec3<f32>(dx, dy, dz) * c;
|
|
1365
|
+
continue;
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
if (level >= params.maxLevel) {
|
|
1369
|
+
// Leaf-COM fix: when this leaf is the cell containing the query node,
|
|
1370
|
+
// subtract the query's own (x, y, z, 1) contribution from the cell's
|
|
1371
|
+
// sum/count so the effective COM is the centroid of the OTHER nodes.
|
|
1372
|
+
// Without this, multi-node leaves bias every query toward the axis from
|
|
1373
|
+
// itself to the leaf centroid \u2192 axis-aligned "cross-star" rays on dense
|
|
1374
|
+
// graphs at large N. (d3-force-3d's recursive subdivision keeps leaves
|
|
1375
|
+
// at \u22641 node; this fixed-depth port emulates that semantics here.)
|
|
1376
|
+
if (cellIdx == queryLeafCellIdx) {
|
|
1377
|
+
let adjCount = count - 1.0;
|
|
1378
|
+
if (adjCount < 0.5) { continue; } // query was the sole occupant
|
|
1379
|
+
let adjSumX = sumX - qp.x;
|
|
1380
|
+
let adjSumY = sumY - qp.y;
|
|
1381
|
+
let adjSumZ = sumZ - qp.z;
|
|
1382
|
+
let adjComX = adjSumX / adjCount;
|
|
1383
|
+
let adjComY = adjSumY / adjCount;
|
|
1384
|
+
let adjComZ = adjSumZ / adjCount;
|
|
1385
|
+
let dxa = adjComX - qp.x;
|
|
1386
|
+
let dya = adjComY - qp.y;
|
|
1387
|
+
let dza = adjComZ - qp.z;
|
|
1388
|
+
var la = max(dxa * dxa + dya * dya + dza * dza, 1e-12);
|
|
1389
|
+
if (la >= params.distanceMax2) { continue; }
|
|
1390
|
+
if (la < params.distanceMin2) { la = sqrt(params.distanceMin2 * la); }
|
|
1391
|
+
// dimFactor == 1.0 at leaf, so effective mass = adjCount.
|
|
1392
|
+
let ca = params.strength * adjCount * params.alpha / la;
|
|
1393
|
+
accum = accum + vec3<f32>(dxa, dya, dza) * ca;
|
|
1394
|
+
continue;
|
|
1395
|
+
}
|
|
1396
|
+
let isSelf = (mass < 1.5) && (abs(dx) < 1e-6) && (abs(dy) < 1e-6) && (abs(dz) < 1e-6);
|
|
1397
|
+
if (isSelf) { continue; }
|
|
1398
|
+
var l2 = l;
|
|
1399
|
+
if (l2 >= params.distanceMax2) { continue; }
|
|
1400
|
+
if (l2 < params.distanceMin2) { l2 = sqrt(params.distanceMin2 * l2); }
|
|
1401
|
+
let c = params.strength * mass * params.alpha / l2;
|
|
1402
|
+
accum = accum + vec3<f32>(dx, dy, dz) * c;
|
|
1403
|
+
continue;
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
// Descend into 8 children. Children of cell at Morton M, level k are at
|
|
1407
|
+
// level k+1, Morton M*8..M*8+7, stored at levelOffsets[k+1] + M*8 + c.
|
|
1408
|
+
let parentMorton = cellIdx - levelOffsets[level];
|
|
1409
|
+
let childBase = levelOffsets[level + 1u] + parentMorton * 8u;
|
|
1410
|
+
if (top + 8u <= MAX_STACK) {
|
|
1411
|
+
let nextLevel = level + 1u;
|
|
1412
|
+
for (var c: u32 = 0u; c < 8u; c = c + 1u) {
|
|
1413
|
+
stack[stackBase + top] = (nextLevel << 24u) | (childBase + c);
|
|
1414
|
+
top = top + 1u;
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
velocities[queryIdx] = vec4<f32>(
|
|
1420
|
+
velocities[queryIdx].x + accum.x,
|
|
1421
|
+
velocities[queryIdx].y + accum.y,
|
|
1422
|
+
velocities[queryIdx].z + accum.z,
|
|
1423
|
+
velocities[queryIdx].w,
|
|
1424
|
+
);
|
|
1425
|
+
}
|
|
1426
|
+
`,Mr=7,Pt=64,kn=64,Oa=Math.sqrt(.5);function wr(e){return Math.floor((Math.pow(8,e+1)-1)/7)}function rt(e){return Math.floor((Math.pow(8,e)-1)/7)}var Bt=4,zt=65535,_r=class{constructor(e,t=Mr){this.accumParamsBufs=[],this.accumBGs=[],this.config={strength:-30,theta:.9,distanceMin:1,distanceMax:1/0},this.device=e.device,this.nodeCount=e.nodeCount,this.maxLevel=t,this.totalCells=wr(t);let n=this.device,i=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST;this.cellsBuffer=n.createBuffer({label:"oct-cells",size:this.totalCells*Bt*4,usage:i}),this.boundsBuffer=n.createBuffer({label:"oct-bounds",size:32,usage:i}),this.levelOffsetsBuffer=n.createBuffer({label:"oct-level-offsets",size:(t+1)*4,usage:i});let o=new Uint32Array(t+1);for(let f=0;f<=t;f++)o[f]=rt(f);n.queue.writeBuffer(this.levelOffsetsBuffer,0,o),this.boundsParamsBuf=n.createBuffer({label:"oct-bounds-params",size:16,usage:r}),this.clearParamsBuf=n.createBuffer({label:"oct-clear-params",size:16,usage:r}),this.binParamsBuf=n.createBuffer({label:"oct-bin-params",size:16,usage:r}),this.traverseParamsBuf=n.createBuffer({label:"oct-traverse-params",size:48,usage:r});for(let f=0;f<t;f++){let p=n.createBuffer({label:`oct-accum-params-L${f}`,size:16,usage:r}),g=new ArrayBuffer(16),m=new Uint32Array(g);m[0]=rt(f),m[1]=rt(f+1),m[2]=Math.pow(8,f),n.queue.writeBuffer(p,0,g),this.accumParamsBufs.push(p)}let a=this.totalCells*Bt,s=Math.ceil(a/Pt),u=Math.min(s,zt)*Pt;n.queue.writeBuffer(this.clearParamsBuf,0,new Uint32Array([a,u,0,0]));let c=(f,p)=>n.createShaderModule({label:f,code:p}),d=(f,p,g="main")=>n.createComputePipeline({label:f,layout:"auto",compute:{module:p,entryPoint:g}});this.boundsPipeline=d("oct-bounds-pipe",c("oct-bounds",Et)),this.clearPipeline=d("oct-clear-pipe",c("oct-clear",$n)),this.binPipeline=d("oct-bin-pipe",c("oct-bin",vr)),this.accumPipeline=d("oct-accum-pipe",c("oct-accum",xr)),this.traversePipeline=d("oct-traverse-pipe",c("oct-traverse",br)),this.bindAll(e)}bindAll(e){let t=this.device;this.boundsBG=t.createBindGroup({layout:this.boundsPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.positionBuffer}},{binding:1,resource:{buffer:this.boundsBuffer}},{binding:2,resource:{buffer:this.boundsParamsBuf}}]}),this.clearBG=t.createBindGroup({layout:this.clearPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.cellsBuffer}},{binding:1,resource:{buffer:this.clearParamsBuf}}]}),this.binBG=t.createBindGroup({layout:this.binPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.positionBuffer}},{binding:1,resource:{buffer:this.cellsBuffer}},{binding:2,resource:{buffer:this.boundsBuffer}},{binding:3,resource:{buffer:this.binParamsBuf}}]});for(let i=0;i<this.maxLevel;i++)this.accumBGs.push(t.createBindGroup({layout:this.accumPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.cellsBuffer}},{binding:1,resource:{buffer:this.accumParamsBufs[i]}}]}));this.traverseBG=t.createBindGroup({layout:this.traversePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.positionBuffer}},{binding:1,resource:{buffer:e.velocityBuffer}},{binding:2,resource:{buffer:this.cellsBuffer}},{binding:3,resource:{buffer:this.levelOffsetsBuffer}},{binding:4,resource:{buffer:this.boundsBuffer}},{binding:5,resource:{buffer:this.traverseParamsBuf}}]}),t.queue.writeBuffer(this.boundsParamsBuf,0,new Uint32Array([this.nodeCount,0,0,0]));let n=new ArrayBuffer(16);new Uint32Array(n,0,3).set([this.nodeCount,this.maxLevel,rt(this.maxLevel)]),new Float32Array(n,12,1)[0]=kn,t.queue.writeBuffer(this.binParamsBuf,0,n)}setConfig(e){Object.assign(this.config,e)}apply(e,t){let n=this.device,i=this.nodeCount,r=Pt,o=new Int32Array([2147483647,-2147483648,2147483647,-2147483648,2147483647,-2147483648]);n.queue.writeBuffer(this.boundsBuffer,0,o),this.run(t,this.boundsPipeline,this.boundsBG,Math.ceil(i/r),"oct-p1-bounds");let a=Math.ceil(this.totalCells*Bt/r),s=Math.min(a,zt),l=Math.ceil(a/zt);this.run2D(t,this.clearPipeline,this.clearBG,s,l,"oct-p2-clear"),this.run(t,this.binPipeline,this.binBG,Math.ceil(i/r),"oct-p3-bin");for(let f=this.maxLevel-1;f>=0;f--)this.run(t,this.accumPipeline,this.accumBGs[f],Math.ceil(Math.pow(8,f)/r),`oct-p4-accum-L${f}`);let u=new ArrayBuffer(48),c=new Uint32Array(u),d=new Float32Array(u);c[0]=i,c[1]=this.maxLevel,d[4]=this.config.strength,d[5]=e,d[6]=this.config.theta*this.config.theta,d[7]=this.config.distanceMin*this.config.distanceMin,d[8]=this.config.distanceMax===1/0?1e30:this.config.distanceMax*this.config.distanceMax,d[9]=kn,n.queue.writeBuffer(this.traverseParamsBuf,0,u),this.run(t,this.traversePipeline,this.traverseBG,Math.ceil(i/r),"oct-p5-traverse")}run(e,t,n,i,r){let o=e.beginComputePass({label:r});o.setPipeline(t),o.setBindGroup(0,n),o.dispatchWorkgroups(i),o.end()}run2D(e,t,n,i,r,o){let a=e.beginComputePass({label:o});a.setPipeline(t),a.setBindGroup(0,n),a.dispatchWorkgroups(i,r,1),a.end()}dispose(){this.cellsBuffer.destroy(),this.boundsBuffer.destroy(),this.levelOffsetsBuffer.destroy(),this.boundsParamsBuf.destroy(),this.clearParamsBuf.destroy(),this.binParamsBuf.destroy(),this.traverseParamsBuf.destroy(),this.accumParamsBufs.forEach(e=>e.destroy())}};function Sr(){let e=-30,t=1,n=1/0,i=.9,r=null,o={initialize(a,s,l){},initGPU(a){r?.dispose(),r=new _r(a),r.setConfig({strength:e,theta:i,distanceMin:t,distanceMax:n})},apply(a,s){r?.apply(a,s)},dispose(){r?.dispose(),r=null},strength(a){return arguments.length===0?e:(e=+a,r?.setConfig({strength:e}),o)},distanceMin(a){return arguments.length===0?t:(t=+a,r?.setConfig({distanceMin:t}),o)},distanceMax(a){return arguments.length===0?n:(n=+a,r?.setConfig({distanceMax:n}),o)},theta(a){return arguments.length===0?i:(i=+a,r?.setConfig({theta:i}),o)}};return o}var Tr={charge:-.01,gravity:.1,linkStrength:1,linkDistance:.5,collision:.15,heightCompress:1,alpha:.6,alphaDecay:.1,velocityDecay:.3,dimensions:3,gravityX:1,gravityY:1,gravityZ:1,octreeTheta:.9},$e=240;function Pr(e,t,n){let i=globalThis,r=i.__webgpuPathATiming;r||(r={tick:new Float32Array($e),read:new Float32Array($e),sync:new Float32Array($e),i:0,filled:0,reset(){this.i=0,this.filled=0},summary(){let o=this.filled;if(o===0)return null;let a=s=>{let l=0,u=1/0,c=-1/0;for(let d=0;d<o;d++){let f=s[d];l+=f,f<u&&(u=f),f>c&&(c=f)}return{mean:+(l/o).toFixed(3),min:+u.toFixed(3),max:+c.toFixed(3),n:o}};return{skipFlag:!!globalThis.__webgpuPathASkip,tickMs:a(this.tick),readMs:a(this.read),syncMs:a(this.sync),totalMs:{mean:+(this.tick.reduce((s,l)=>s+l,0)/o+this.read.reduce((s,l)=>s+l,0)/o+this.sync.reduce((s,l)=>s+l,0)/o).toFixed(3)}}}},i.__webgpuPathATiming=r),r.tick[r.i]=e,r.read[r.i]=t,r.sync[r.i]=n,r.i=(r.i+1)%$e,r.filled<$e&&r.filled++}var ot=class{constructor(e,t,n={}){if(this.sharedArray=new Float32Array(0),this.nodeIdToIndex=new Map,this.isFinish=!1,this._enable=!0,this.getOptions=()=>null,this._readbackTimingSink=null,this.simulation=null,this.simNodes=[],this._loopRunning=!1,this._currentSpaceSize=10,this.forceCharge=null,this.forceLinkInstance=null,this.forceXInstance=null,this.forceYInstance=null,this.forceZInstance=null,this.forceCenterInstance=null,this._linkDegree=new Int32Array(0),this._linkStrengthFn=i=>{let r=i.source,o=i.target,a=Math.min(this._linkDegree[r]??1,this._linkDegree[o]??1);return this.params.linkStrength*(a>0?1/a:1)},this._readbackTickCounter=0,!Pe())throw new Error("[WebGPUForceLayoutController] navigator.gpu unavailable in this environment. Use the WebGL-backed GPUForceLayoutController instead.");this.params={...Tr},this.options=n,this.graph=e??{layoutNodes:[],layoutEdges:[],renderNeedsUpdate:!0}}setReadbackTimingSink(e){return this._readbackTimingSink=e,this}config(e){this.getOptions=e;let t=e();return t&&this.applyConfig(t),this}configure(e){return this.config(e)}applyConfig(e){e.charge!==void 0&&(this.params.charge=e.charge),e.gravity!==void 0&&(this.params.gravity=e.gravity),e.linkStrength!==void 0&&(this.params.linkStrength=e.linkStrength),e.linkDistance!==void 0&&(this.params.linkDistance=e.linkDistance),e.collision!==void 0&&(this.params.collision=e.collision),e.heightCompress!==void 0&&(this.params.heightCompress=e.heightCompress),e.alpha!==void 0&&(this.params.alpha=e.alpha),e.alphaDecay!==void 0&&(this.params.alphaDecay=e.alphaDecay),e.velocityDecay!==void 0&&(this.params.velocityDecay=e.velocityDecay),e.friction!==void 0&&(this.params.velocityDecay=e.friction),e.dimensions!==void 0&&(this.params.dimensions=e.dimensions),e.gravityX!==void 0&&(this.params.gravityX=e.gravityX),e.gravityY!==void 0&&(this.params.gravityY=e.gravityY),e.gravityZ!==void 0&&(this.params.gravityZ=e.gravityZ),e.octreeTheta!==void 0&&(this.params.octreeTheta=e.octreeTheta)}startLayout(e=0,t=0,n=!1){let i=this.params.dimensions,r=this.getOptions();r&&this.applyConfig(r),this.params.dimensions=i,this.disposeSimulation(),this.buildSimulation(n),this.simulation&&(this._enable=!0,this.isFinish=!1,this.graph.renderNeedsUpdate=!0,this._loopRunning=!1,this.runLoop())}restartLayout(){if(!this._enable)return;let e=this.getOptions();if(e){let i=this.params.dimensions;this.applyConfig(e),this.params.dimensions=i}this.applyForceParams();let t=this.graph.layoutNodes.length,n=this.simNodes.length;this.simulation&&t===n?(this.simulation.alpha(this.params.alpha),this.isFinish=!1,this.graph.renderNeedsUpdate=!0,this.runLoop()):this.startLayout()}stopLayout(){this._enable=!1,this.isFinish=!0,this.graph.renderNeedsUpdate=!1}destroy(){this.stopLayout(),this.disposeSimulation()}disposeSimulation(){this.simulation?.dispose(),this.simulation=null,this.forceCharge=null,this.forceLinkInstance=null,this.forceXInstance=null,this.forceYInstance=null,this.forceZInstance=null,this.forceCenterInstance=null}buildSimulation(e=!1){let t=this.graph.layoutNodes,n=this.graph.layoutEdges,i=t.length;if(i===0)return;let r=this.params.dimensions,o=t.some(m=>Math.abs(m.position.z)>1e-6),a=r>2&&!o&&!e,s=Math.cbrt(t.length)*2,u=Math.min(10,Math.pow(2,29)/(Math.pow(i,1.5)*64)),c=r===2&&!a&&!e,d=Math.PI*(3-Math.sqrt(5));this.simNodes=t.map((m,y)=>{let M={id:m.id,index:y};if(m.pinned)M.fx=m.position.x,M.fy=m.position.y,M.fz=m.position.z,M.x=m.position.x,M.y=m.position.y,M.z=m.position.z;else if(a){let S=Math.random(),h=Math.random(),v=Math.random(),b=2*Math.PI*S,x=Math.acos(2*h-1),E=Math.cbrt(v)*s;M.x=E*Math.sin(x)*Math.cos(b),M.y=E*Math.sin(x)*Math.sin(b),M.z=E*Math.cos(x)}else if(c){let S=u*Math.sqrt(.5+y),h=y*d;M.x=S*Math.cos(h),M.y=S*Math.sin(h),M.z=0}else e&&(M.x=m.position.x,M.y=m.position.y,M.z=r<=2?0:m.position.z);return M}),this.nodeIdToIndex.clear();for(let m=0;m<i;m++)this.nodeIdToIndex.set(this.simNodes[m].id,m*3);this.sharedArray=new Float32Array(i*3),this._currentSpaceSize=Math.max(10,2*(this.params.dimensions===2?10*Math.sqrt(i):10*Math.cbrt(i)));let f=Ln(this.simNodes,this.params.dimensions,{device:this.options.device});f.alpha(this.params.alpha).alphaDecay(this.params.alphaDecay).velocityDecay(this.params.velocityDecay).alphaTarget(0).maxVel(this.staticMaxVel(this.simNodes.length));let{forcexy:p,forcez:g}=this.calculateAxisForces();if(this.forceXInstance=Nn(0).strength(p*this.params.gravityX),this.forceYInstance=qn(0).strength(p*this.params.gravityY),f.force("x",this.forceXInstance),f.force("y",this.forceYInstance),this.params.dimensions>2&&(this.forceZInstance=On(0).strength(g*this.params.gravityZ),f.force("z",this.forceZInstance)),this.forceCharge=this.makeChargeForce(i),f.force("charge",this.forceCharge),n.length){let m=n.map(M=>{let S=this.nodeIdToIndex.get(M.sourceId),h=this.nodeIdToIndex.get(M.targetId);return S===void 0||h===void 0?null:{id:M.id,source:S/3,target:h/3}}).filter(M=>M!==null),y=m.length;this._linkDegree=new Int32Array(i);for(let M=0;M<y;M++)this._linkDegree[m[M].source]++,this._linkDegree[m[M].target]++;this.forceLinkInstance=Hn(m).strength(this._linkStrengthFn).distance(this.params.linkDistance),f.force("link",this.forceLinkInstance)}this.forceCenterInstance=Gn(0,0,0).strength(1),f.force("center",this.forceCenterInstance),this.simulation=f}makeChargeForce(e){if(this.params.dimensions===2){let n=yr();return n.theta?.(this.params.octreeTheta),n.strength(this.params.charge),n}if(e>=1e4){let n=Yn();return n.theta(this.params.octreeTheta),n.strength(this.params.charge),n}let t=Sr();return t.theta?.(this.params.octreeTheta),t.strength(this.params.charge),t}calculateAxisForces(){let e,t;if(this.params.dimensions===2)e=this.params.gravity*1.5,t=0;else{let n=this.params.heightCompress;t=Math.min(10,this.params.gravity*Math.sqrt(n)),e=this.params.gravity/Math.sqrt(n)}return{forcexy:e,forcez:t}}applyForceParams(){if(!this.simulation)return;this.simulation.alphaDecay(this.params.alphaDecay),this.simulation.velocityDecay(this.params.velocityDecay);let{forcexy:e,forcez:t}=this.calculateAxisForces();this.forceXInstance?.strength(e*this.params.gravityX),this.forceYInstance?.strength(e*this.params.gravityY),this.forceZInstance?.strength(t*this.params.gravityZ),this.forceCharge?.strength(this.params.charge),this.forceLinkInstance&&(this.forceLinkInstance.strength(this._linkStrengthFn),this.forceLinkInstance.distance(this.params.linkDistance))}afterTick(e){let t=this.options.onTick;if(t)try{t({positionBuffer:e.getPositionBuffer(),nodeCount:this.simNodes.length})}catch{}}async runLoop(){if(!this._loopRunning){this._loopRunning=!0;try{let e=this.simulation;for(e&&!e.isReady()&&await new Promise(t=>e.on("ready",()=>t()));this._enable&&this.simulation&&(await this.waitForFrame(),!!this._enable);){let t=this.simulation;if(!t)break;let n=performance.now();t.tick(1),this.afterTick(t);let i=performance.now(),r=Math.max(1,Math.floor(globalThis.__webgpuReadbackInterval??1));this._readbackTickCounter++;let o=this._readbackTickCounter>=r,a=t.alpha()<t.alphaMin(),s=o||a,l=i,u=i;if(s){this._readbackTickCounter=0;try{await t.readPositions()}catch(c){console.warn("[WebGPUForceLayoutController] readPositions threw, skipping:",c);continue}if(t!==this.simulation||!this._enable)break;l=performance.now(),this.syncPositionsToSharedArray(),u=performance.now(),this.graph.renderNeedsUpdate=!0}if(Pr(i-n,l-i,u-l),s&&this._readbackTimingSink)try{this._readbackTimingSink(u-i)}catch{}if(a){this.isFinish=!0,this.graph.renderNeedsUpdate=!1;break}}}finally{this._loopRunning=!1}}}waitForFrame(){return new Promise(e=>requestAnimationFrame(()=>e()))}syncPositionsToSharedArray(){let e=this.sharedArray,t=this.graph.layoutNodes,n=this.simNodes,i=Math.min(e.length/3,n.length,t.length);if(globalThis.__webgpuPathASkip===!0){let o=0;for(let a=0;a<e.length;a++){let s=e[a],l=s<0?-s:s;l>o&&(o=l)}this._currentSpaceSize=Math.max(10,2*o);return}let r=0;for(let o=0;o<i;o++){let a=n[o],s=a.x??0,l=a.y??0,u=a.z??0;e[o*3]=s,e[o*3+1]=l,e[o*3+2]=u;let c=t[o];c?.position&&(c.position.x=s,c.position.y=l,c.position.z=u);let d=Math.max(Math.abs(s),Math.abs(l),Math.abs(u));d>r&&(r=d)}this._currentSpaceSize=Math.max(10,2*r)}staticMaxVel(e){let t=this.params.dimensions===2?Math.max(10,Math.sqrt(e)*.5):Math.max(10,Math.cbrt(e)*2);return Math.min(2,t*.1)}updateLayoutOption(e,t){if(e==="friction"?this.params.velocityDecay=t:this.params[e]=t,!this.simulation||!this._enable)return;let n=()=>{this.simulation.alpha(Math.max(this.simulation.alpha(),.3)),this.isFinish=!1,this.runLoop()};switch(e){case"charge":this.forceCharge?.strength(t),n();break;case"linkDistance":this.forceLinkInstance?.distance(t),n();break;case"linkStrength":this.forceLinkInstance?.strength(this._linkStrengthFn),n();break;case"gravity":case"gravityX":case"gravityY":case"gravityZ":case"heightCompress":{let{forcexy:i,forcez:r}=this.calculateAxisForces();this.forceXInstance?.strength(i*this.params.gravityX),this.forceYInstance?.strength(i*this.params.gravityY),this.forceZInstance?.strength(r*this.params.gravityZ),n();break}case"velocityDecay":case"friction":this.simulation.velocityDecay(this.params.velocityDecay);break;case"alpha":case"alphaDecay":this.restartLayout();return;default:this.restartLayout();return}this.graph.renderNeedsUpdate=!0}pinNodes(e){this.simulation&&(e.forEach(t=>{let n=this.nodeIdToIndex.get(t.id);if(n===void 0)return;let i=n/3,r=this.simNodes[i];r&&(t.pinned?(r.fx=t.position.x,r.fy=t.position.y,r.fz=t.position.z,r.x=t.position.x,r.y=t.position.y,r.z=t.position.z,this.simulation.uploadPosition(i,t.position.x,t.position.y,t.position.z),this.simulation.uploadPinned(i,!0)):(delete r.fx,delete r.fy,delete r.fz,this.simulation.uploadPinned(i,!1)))}),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)),this.isFinish=!1,this.runLoop(),this.graph.renderNeedsUpdate=!0)}unpinNodes(e){this.simulation&&(e.forEach(t=>{let n=this.nodeIdToIndex.get(t);if(n===void 0)return;let i=n/3,r=this.simNodes[i];r&&(delete r.fx,delete r.fy,delete r.fz,this.simulation.uploadPinned(i,!1))}),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)),this.isFinish=!1,this.runLoop(),this.graph.renderNeedsUpdate=!0)}transitionDimensions(e,t=600){this.params.dimensions!==e&&(e===2?(this.readBackPositions(),this.params.dimensions=2,this.startLayout(0,0,!0)):(this.readBackPositions(),this.params.dimensions=3,this.startLayout()))}cancelDimensionTransition(){}getDimensions(){return this.params.dimensions}getPositionTexture(){return null}getTextureSize(){return 0}getSpaceSize(){return this._currentSpaceSize}readBackPositions(){if(this.simNodes.length===0)return;this.syncPositionsToSharedArray();let e=this.params.dimensions,t=this.graph.layoutNodes;for(let n=0;n<this.simNodes.length;n++){let i=this.simNodes[n],r=t[n];!r||!r.position||(r.position.x=i.x??0,r.position.y=i.y??0,r.position.z=e>2?i.z??0:0)}}setExpectedNodeCount(e){}clearExpectedNodeCount(){}updateGraph(e,t,n=!1){this.graph.layoutNodes=e,this.graph.layoutEdges=t}},st=class{constructor(e){this.c=e,this.mode="cpu"}getPositionTexture(){return null}getTextureSize(){return 0}getSpaceSize(){return this.c.getSpaceSize()}get sharedArray(){return this.c.sharedArray}getPositions(){return this.c.sharedArray}tick(){}start(){this.c.startLayout()}restart(){this.c.restartLayout()}stop(){this.c.stopLayout()}get graph(){return this.c.graph}get needsUpdate(){return!this.c.isFinish}clearNeedsUpdate(){}pinNodes(e){this.c.pinNodes(e)}unpinNodes(e){this.c.unpinNodes(e)}readBackPositions(){this.c.readBackPositions()}transitionDimensions(e,t){this.c.transitionDimensions(e,t)}getDimensions(){return this.c.getDimensions()}updateOption(e,t){this.c.updateLayoutOption(e,t)}};var ue=pe(require("three"),1);var Q=pe(require("three"),1),Fe=pe(require("three"),1),$=pe(require("three"),1),Z=pe(require("three"),1),ne=pe(require("three"),1),Ie=pe(require("three"),1),ae=pe(require("three"),1),oe=pe(require("three"),1),se=pe(require("three"),1),De=pe(require("three"),1),jn=pe(require("three"),1),he=`/**
|
|
1427
|
+
* Simple vertex shader for full-screen quad rendering
|
|
1428
|
+
* Used by all GPU compute passes
|
|
1429
|
+
*/
|
|
1430
|
+
varying vec2 vUv;
|
|
1431
|
+
|
|
1432
|
+
void main() {
|
|
1433
|
+
vUv = uv;
|
|
1434
|
+
gl_Position = vec4(position, 1.0);
|
|
1435
|
+
}
|
|
1436
|
+
`,Br=`/**
|
|
1437
|
+
* Position update shader
|
|
1438
|
+
*
|
|
1439
|
+
* Applies accumulated velocity to position, with:
|
|
1440
|
+
* - Optional velocity decay (friction) - typically handled separately now
|
|
1441
|
+
* - Velocity clamping to prevent explosion
|
|
1442
|
+
* - Pinned node handling
|
|
1443
|
+
*
|
|
1444
|
+
* Same logic as d3-force:
|
|
1445
|
+
* if (node.fx == null) node.x += node.vx
|
|
1446
|
+
* else node.x = node.fx, node.vx = 0
|
|
1447
|
+
*
|
|
1448
|
+
* Note: Velocity decay is now applied in velocity-decay.frag.glsl before this shader
|
|
1449
|
+
*/
|
|
1450
|
+
precision highp float;
|
|
1451
|
+
|
|
1452
|
+
uniform sampler2D positionTexture;
|
|
1453
|
+
uniform sampler2D velocityTexture;
|
|
1454
|
+
uniform sampler2D pinnedTexture;
|
|
1455
|
+
uniform float friction; // Set to 1.0 when decay is handled separately
|
|
1456
|
+
uniform float spaceSize;
|
|
1457
|
+
uniform float nDim;
|
|
1458
|
+
|
|
1459
|
+
varying vec2 vUv;
|
|
1460
|
+
|
|
1461
|
+
void main() {
|
|
1462
|
+
vec4 pos = texture2D(positionTexture, vUv);
|
|
1463
|
+
vec4 vel = texture2D(velocityTexture, vUv);
|
|
1464
|
+
vec4 pinned = texture2D(pinnedTexture, vUv);
|
|
1465
|
+
|
|
1466
|
+
// If node is pinned, don't update position
|
|
1467
|
+
if (pinned.r > 0.5) {
|
|
1468
|
+
gl_FragColor = pos;
|
|
1469
|
+
return;
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
// Apply optional friction (usually 1.0 when decay is handled separately)
|
|
1473
|
+
vec3 adjustedVel = vel.xyz * friction;
|
|
1474
|
+
|
|
1475
|
+
// Clamp velocity to prevent nodes from flying too far
|
|
1476
|
+
// Max velocity is proportional to space size
|
|
1477
|
+
float maxVel = spaceSize * 0.1;
|
|
1478
|
+
float velMag = length(adjustedVel);
|
|
1479
|
+
if (velMag > maxVel) {
|
|
1480
|
+
adjustedVel = adjustedVel * (maxVel / velMag);
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
// Update position
|
|
1484
|
+
vec3 newPos = pos.xyz + adjustedVel;
|
|
1485
|
+
|
|
1486
|
+
// Mask z-component for 2D simulations
|
|
1487
|
+
if (nDim < 3.0) {
|
|
1488
|
+
newPos.z = 0.0;
|
|
1489
|
+
}
|
|
1490
|
+
if (nDim < 2.0) {
|
|
1491
|
+
newPos.y = 0.0;
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
gl_FragColor = vec4(newPos, pos.w);
|
|
1495
|
+
}
|
|
1496
|
+
`,Zn=`/**
|
|
1497
|
+
* Clear shader - outputs zero for all fragments
|
|
1498
|
+
* Used to reset velocity buffer at the start of each tick
|
|
1499
|
+
*
|
|
1500
|
+
* IMPORTANT: Alpha must be 1.0 for this to work with default blending.
|
|
1501
|
+
* With alpha = 0, NormalBlending formula (src * srcAlpha + dst * (1-srcAlpha))
|
|
1502
|
+
* would result in dst (no clearing).
|
|
1503
|
+
*/
|
|
1504
|
+
precision highp float;
|
|
1505
|
+
|
|
1506
|
+
void main() {
|
|
1507
|
+
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
|
|
1508
|
+
}
|
|
1509
|
+
`,zr=`/**
|
|
1510
|
+
* Copy shader - copies one texture to another
|
|
1511
|
+
* Used for initializing FBOs with data textures
|
|
1512
|
+
*/
|
|
1513
|
+
precision highp float;
|
|
1514
|
+
|
|
1515
|
+
uniform sampler2D sourceTexture;
|
|
1516
|
+
varying vec2 vUv;
|
|
1517
|
+
|
|
1518
|
+
void main() {
|
|
1519
|
+
gl_FragColor = texture2D(sourceTexture, vUv);
|
|
1520
|
+
}
|
|
1521
|
+
`,Cr=`/**
|
|
1522
|
+
* Velocity decay shader
|
|
1523
|
+
*
|
|
1524
|
+
* Applies velocity decay (friction) to existing velocity.
|
|
1525
|
+
* This is the first step in each tick to decay the accumulated velocity
|
|
1526
|
+
* before adding new forces.
|
|
1527
|
+
*
|
|
1528
|
+
* Same as d3-force: node.vx *= velocityDecay
|
|
1529
|
+
*/
|
|
1530
|
+
precision highp float;
|
|
1531
|
+
|
|
1532
|
+
uniform sampler2D velocityTexture;
|
|
1533
|
+
uniform float decay; // velocityDecay factor (typically 0.6 = keep 60% of velocity, same as d3-force)
|
|
1534
|
+
|
|
1535
|
+
varying vec2 vUv;
|
|
1536
|
+
|
|
1537
|
+
void main() {
|
|
1538
|
+
vec4 vel = texture2D(velocityTexture, vUv);
|
|
1539
|
+
|
|
1540
|
+
// Apply decay to velocity
|
|
1541
|
+
vel.xyz *= decay;
|
|
1542
|
+
|
|
1543
|
+
gl_FragColor = vec4(vel.xyz, 1.0);
|
|
1544
|
+
}
|
|
1545
|
+
`,kr=3;function Er(e,t,n){let i=Math.min(kr,Math.max(1,Math.round(t||3))),r,o=1,a=.001,s=1-Math.pow(a,1/300),l=0,u=.6,c=In(),d=new Map,f=null,p=xt("tick","end");e==null&&(e=[]);let g,m,y,M,S=!1,h=0,v=0,b=null,x=null,E=0,F=null,R=null,A=0,I=null,L=null,B=null,k=null,w=null,z=null,P=null,T=null,C=1e3/10,q=0,N=!1;function G(){if(S)return;if(n)g=n;else{let H=document.createElement("canvas");H.style.display="none",g=new ue.WebGLRenderer({canvas:H,alpha:!0,antialias:!1}),g.setSize(256,256)}m=new ue.Scene,y=new ue.OrthographicCamera(-1,1,1,-1,0,1);let U=ye();w=new ue.ShaderMaterial({uniforms:{},vertexShader:he,fragmentShader:Zn,blending:ue.NoBlending,depthTest:!1,depthWrite:!1}),z=new ue.ShaderMaterial({uniforms:{sourceTexture:{value:null}},vertexShader:he,fragmentShader:zr,depthTest:!1,depthWrite:!1}),k=new ue.ShaderMaterial({uniforms:{positionTexture:{value:null},velocityTexture:{value:null},pinnedTexture:{value:null},friction:{value:1},spaceSize:{value:10},nDim:{value:i}},vertexShader:he,fragmentShader:Br,depthTest:!1,depthWrite:!1}),P=new ue.ShaderMaterial({uniforms:{velocityTexture:{value:null},decay:{value:u}},vertexShader:he,fragmentShader:Cr,depthTest:!1,depthWrite:!1}),M=new ue.Mesh(U,w),m.add(M),S=!0}function _(){if(S||G(),v=e.length,v===0)return;h=Ct(v);let U=Ne(v,i),H=g.getContext(),K=H.getParameter(H.MAX_TEXTURE_SIZE);b?.dispose(),x?.dispose(),F?.dispose(),R?.dispose(),I?.dispose(),L?.dispose(),B?.dispose(),b=Ee(h),x=Ee(h),F=Ee(h),R=Ee(h),I=Ee(h),E=0,A=0;let le=Dn(e,h),J=qe(le,h),ve=An(e,h),me=qe(ve,h),fe=Rn(e,h);L=qe(fe,h);let ee=h*h,Me=new Float32Array(ee*4);for(let ge=0;ge<ee;ge++)Me[ge*4]=(c()-.5)*2,Me[ge*4+1]=(c()-.5)*2,Me[ge*4+2]=(c()-.5)*2,Me[ge*4+3]=c();B=qe(Me,h),z.uniforms.sourceTexture.value=J,M.material=z,g.setRenderTarget(b),g.render(m,y),g.setRenderTarget(x),g.render(m,y),z.uniforms.sourceTexture.value=me,g.setRenderTarget(F),g.render(m,y),g.setRenderTarget(R),g.render(m,y),M.material=w,g.setRenderTarget(I),g.render(m,y),g.setRenderTarget(null),J.dispose(),me.dispose(),k.uniforms.spaceSize.value=U;let je={renderer:g,scene:m,camera:y,textureSize:h,nodeCount:v};d.forEach(ge=>{if(ge.initGPU)try{ge.initGPU(je)}catch{}})}function D(){return E===0?b:x}function O(){return E===0?x:b}function Y(){E=1-E}function X(){return A===0?F:R}function W(){return A===0?R:F}function V(){A=1-A}function ce(){j(),p.call("tick",r),o<a&&(f?.stop(),p.call("end",r))}function j(U){U===void 0&&(U=1);for(let H=0;H<U;H++)o+=(l-o)*s,S&&v>0?Be():ut();return r}let de=0,ie=0;function Be(){de++;let U=performance.now();(de%50===0||U-ie>2e3)&&(ie=U);let H=O(),K=D(),le=W(),J=X(),ve=Ne(v,i);for(let[,ee]of d)if(typeof ee.getSpaceSize=="function"){ve=ee.getSpaceSize();break}let me=ve;z.uniforms.sourceTexture.value=le.texture,M.material=z,g.setRenderTarget(I),g.render(m,y),d.forEach(ee=>{try{ee.apply(o,H.texture,I)}catch{}}),P.uniforms.velocityTexture.value=I.texture,P.uniforms.decay.value=u,M.material=P,g.setRenderTarget(J),g.render(m,y),k.uniforms.positionTexture.value=H.texture,k.uniforms.velocityTexture.value=J.texture,k.uniforms.pinnedTexture.value=L,k.uniforms.friction.value=1,k.uniforms.spaceSize.value=me,M.material=k,g.setRenderTarget(K),g.render(m,y),g.setRenderTarget(null);let fe=d.get("center");if(fe&&fe.applyToPosition&&(fe.applyToPosition(K.texture,H,o),z.uniforms.sourceTexture.value=H.texture,M.material=z,g.setRenderTarget(K),g.render(m,y),g.setRenderTarget(null)),Y(),V(),!N){let ee=performance.now();ee-q>=C&&(q=ee,At())}}function ut(){d.forEach(U=>{U.apply(o)});for(let U=0;U<e.length;U++){let H=e[U];H.fx==null?H.x+=H.vx*=u:(H.x=H.fx,H.vx=0),i>1&&(H.fy==null?H.y+=H.vy*=u:(H.y=H.fy,H.vy=0)),i>2&&(H.fz==null?H.z+=H.vz*=u:(H.z=H.fz,H.vz=0))}}let Kn=0;function At(){if(!S||v===0)return;let U=O(),H=new Float32Array(h*h*4);try{g.readRenderTargetPixels(U,0,0,h,h,H),Un(e,H,i),Kn++}catch{}}function ct(U){return U.initialize(e,c,i),S&&U.initGPU&&U.initGPU({renderer:g,scene:m,camera:y,textureSize:h,nodeCount:v}),U}return Ze(e,i,c),r={tick:function(U){return j(U),this},restart:function(){return e.length>0&&!S&&(G(),_()),f?f.restart(ce):f=nt(ce),this},stop:function(){return f?.stop(),this},numDimensions:function(U){return arguments.length===0?i:this},nodes:function(U){return arguments.length===0?e:(e=U,Ze(e,i,c),_(),d.forEach(ct),this)},alpha:function(U){return arguments.length===0?o:(o=+U,this)},alphaMin:function(U){return arguments.length===0?a:(a=+U,this)},alphaDecay:function(U){return arguments.length===0?s:(s=+U,this)},alphaTarget:function(U){return arguments.length===0?l:(l=+U,this)},velocityDecay:function(U){return arguments.length===0?1-u:(u=1-U,P&&(P.uniforms.decay.value=u),this)},randomSource:function(U){return arguments.length===0?c:(c=U,d.forEach(ct),this)},force:function(U,H){if(arguments.length===1)return d.get(U);if(H==null){let K=d.get(U);K?.dispose&&K.dispose(),d.delete(U)}else{let K=ct(H);if(d.set(U,K),S&&K.initGPU&&v>0&&h>0)try{K.initGPU({renderer:g,scene:m,camera:y,textureSize:h,nodeCount:v})}catch{}}return this},find:function(U,H,K,le){H=H??0,K=K??0,le=le??1/0;let J,ve=le*le;for(let me=0;me<e.length;me++){let fe=e[me],ee=U-(fe.x||0),Me=H-(fe.y||0),je=K-(fe.z||0),ge=ee*ee+Me*Me+je*je;ge<ve&&(J=fe,ve=ge)}return J},on:function(U,H){return arguments.length===1?p.on(U):(p.on(U,H),this)},getPositionTexture:function(){if(!S||v===0)return null;let U=O();return!U||!U.texture?null:U.texture},getTextureSize:function(){return h},getSpaceSize:function(){if(!S||v===0)return 10;for(let[,U]of d)if(typeof U.getSpaceSize=="function")return U.getSpaceSize();return Ne(v,i)},setSkipCPUReadback:function(U){N=U},getSkipCPUReadback:function(){return N},readBackPositions:function(){At()},uploadNodePositions:function(U){if(!S||v===0||U.length===0)return;let H=O();if(!H)return;let K=new Float32Array(h*h*4);try{g.readRenderTargetPixels(H,0,0,h,h,K)}catch{return}for(let{index:J,x:ve,y:me,z:fe}of U)if(J>=0&&J<v){let ee=J*4;K[ee]=ve,K[ee+1]=me,K[ee+2]=fe}let le=qe(K,h);z.uniforms.sourceTexture.value=le,M.material=z,g.setRenderTarget(H),g.render(m,y),g.setRenderTarget(null),le.dispose()},updatePinnedNodes:function(U){if(!L||!S||v===0||U.length===0)return;let H=L.image.data;for(let{index:K,isPinned:le}of U)K>=0&&K<v&&(H[K*4]=le?1:0);L.needsUpdate=!0},debugPositions:function(U=5){if(!S||v===0)return null;let H=O(),K=new Float32Array(h*h*4);try{g.readRenderTargetPixels(H,0,0,h,h,K);let le=[];for(let J=0;J<Math.min(U,v);J++){let ve=K[J*4],me=K[J*4+1],fe=K[J*4+2],ee=K[J*4+3];le.push({x:ve,y:me,z:fe,w:ee})}return le}catch{return null}},dispose:function(){f?.stop(),d.forEach(U=>{U.dispose&&U.dispose()}),d.clear(),b?.dispose(),x?.dispose(),F?.dispose(),R?.dispose(),I?.dispose(),L?.dispose(),B?.dispose(),k?.dispose(),w?.dispose(),z?.dispose(),P?.dispose(),M&&(M.geometry.dispose(),m?.remove(M)),!n&&g&&g.dispose()}},G(),e.length>0&&_(),r}var Fr=`/**
|
|
1546
|
+
* Center force shader
|
|
1547
|
+
*
|
|
1548
|
+
* Implements d3-force's forceCenter behavior:
|
|
1549
|
+
* Calculates the center of mass of all nodes and applies
|
|
1550
|
+
* a uniform translation to shift everything toward the target center.
|
|
1551
|
+
*
|
|
1552
|
+
* This is NOT a per-node attractive force - it's a global translation
|
|
1553
|
+
* that maintains relative positions while centering the graph.
|
|
1554
|
+
*
|
|
1555
|
+
* Reference: d3-force-3d/src/center.js
|
|
1556
|
+
*/
|
|
1557
|
+
precision highp float;
|
|
1558
|
+
|
|
1559
|
+
uniform sampler2D positionTexture;
|
|
1560
|
+
uniform sampler2D centermassTexture; // Pre-computed center of mass
|
|
1561
|
+
uniform float centerX;
|
|
1562
|
+
uniform float centerY;
|
|
1563
|
+
uniform float centerZ;
|
|
1564
|
+
uniform float strength;
|
|
1565
|
+
uniform float textureSize;
|
|
1566
|
+
uniform float nodeCount;
|
|
1567
|
+
uniform float nDim;
|
|
1568
|
+
|
|
1569
|
+
varying vec2 vUv;
|
|
1570
|
+
|
|
1571
|
+
void main() {
|
|
1572
|
+
// Read pre-computed center of mass
|
|
1573
|
+
vec4 centermass = texture2D(centermassTexture, vec2(0.5, 0.5));
|
|
1574
|
+
|
|
1575
|
+
// Calculate node index
|
|
1576
|
+
float x = floor(vUv.x * textureSize);
|
|
1577
|
+
float y = floor(vUv.y * textureSize);
|
|
1578
|
+
float nodeIndex = y * textureSize + x;
|
|
1579
|
+
|
|
1580
|
+
// Output zero for invalid indices
|
|
1581
|
+
if (nodeIndex >= nodeCount) {
|
|
1582
|
+
gl_FragColor = vec4(0.0);
|
|
1583
|
+
return;
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
// Target center (default: origin)
|
|
1587
|
+
vec3 target = vec3(centerX, centerY, centerZ);
|
|
1588
|
+
|
|
1589
|
+
// Calculate the shift needed (same for all nodes)
|
|
1590
|
+
// centermass.rgb contains sum of all positions
|
|
1591
|
+
// centermass.a contains node count
|
|
1592
|
+
vec3 currentCenter = centermass.rgb / max(centermass.a, 1.0);
|
|
1593
|
+
vec3 shift = (target - currentCenter) * strength;
|
|
1594
|
+
|
|
1595
|
+
// Mask for dimensions
|
|
1596
|
+
if (nDim < 3.0) shift.z = 0.0;
|
|
1597
|
+
if (nDim < 2.0) shift.y = 0.0;
|
|
1598
|
+
|
|
1599
|
+
// Output velocity delta (will be added to all nodes uniformly)
|
|
1600
|
+
// Note: alpha must be 1.0 for THREE.AdditiveBlending to work (uses SrcAlphaFactor)
|
|
1601
|
+
gl_FragColor = vec4(shift, 1.0);
|
|
1602
|
+
}
|
|
1603
|
+
`,Ir=`/**
|
|
1604
|
+
* Center force position shader
|
|
1605
|
+
*
|
|
1606
|
+
* Implements d3-force's forceCenter behavior correctly:
|
|
1607
|
+
* Directly modifies node positions (not velocities) to center the graph.
|
|
1608
|
+
*
|
|
1609
|
+
* d3-force center: node.x -= shift (direct position modification)
|
|
1610
|
+
* Unlike other forces which modify velocity: node.vx += force
|
|
1611
|
+
*
|
|
1612
|
+
* Reference: d3-force-3d/src/center.js
|
|
1613
|
+
*/
|
|
1614
|
+
precision highp float;
|
|
1615
|
+
|
|
1616
|
+
uniform sampler2D positionTexture;
|
|
1617
|
+
uniform sampler2D centermassTexture; // Pre-computed center of mass
|
|
1618
|
+
uniform float centerX;
|
|
1619
|
+
uniform float centerY;
|
|
1620
|
+
uniform float centerZ;
|
|
1621
|
+
uniform float strength;
|
|
1622
|
+
uniform float alpha; // Alpha scaling for center force (matches d3-force)
|
|
1623
|
+
uniform float textureSize;
|
|
1624
|
+
uniform float nodeCount;
|
|
1625
|
+
uniform float nDim;
|
|
1626
|
+
|
|
1627
|
+
varying vec2 vUv;
|
|
1628
|
+
|
|
1629
|
+
void main() {
|
|
1630
|
+
// Read pre-computed center of mass
|
|
1631
|
+
vec4 centermass = texture2D(centermassTexture, vec2(0.5, 0.5));
|
|
1632
|
+
|
|
1633
|
+
// Calculate node index
|
|
1634
|
+
float x = floor(vUv.x * textureSize);
|
|
1635
|
+
float y = floor(vUv.y * textureSize);
|
|
1636
|
+
float nodeIndex = y * textureSize + x;
|
|
1637
|
+
|
|
1638
|
+
// Read current position
|
|
1639
|
+
vec2 texCoord = (vec2(x, y) + 0.5) / textureSize;
|
|
1640
|
+
vec4 pos = texture2D(positionTexture, texCoord);
|
|
1641
|
+
|
|
1642
|
+
// Output unchanged position for invalid indices
|
|
1643
|
+
if (nodeIndex >= nodeCount) {
|
|
1644
|
+
gl_FragColor = pos;
|
|
1645
|
+
return;
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
// Target center (default: origin)
|
|
1649
|
+
vec3 target = vec3(centerX, centerY, centerZ);
|
|
1650
|
+
|
|
1651
|
+
// Calculate the shift needed (same for all nodes)
|
|
1652
|
+
// centermass.rgb contains sum of all positions
|
|
1653
|
+
// centermass.a contains node count
|
|
1654
|
+
vec3 currentCenter = centermass.rgb / max(centermass.a, 1.0);
|
|
1655
|
+
vec3 shift = (currentCenter - target) * strength * alpha; // Apply alpha scaling like d3-force
|
|
1656
|
+
|
|
1657
|
+
// Mask for dimensions
|
|
1658
|
+
if (nDim < 3.0) shift.z = 0.0;
|
|
1659
|
+
if (nDim < 2.0) shift.y = 0.0;
|
|
1660
|
+
|
|
1661
|
+
// Apply shift directly to position (same as d3-force: node.x -= shift)
|
|
1662
|
+
vec3 newPos = pos.xyz - shift;
|
|
1663
|
+
|
|
1664
|
+
gl_FragColor = vec4(newPos, pos.w);
|
|
1665
|
+
}
|
|
1666
|
+
`,Dr=`/**
|
|
1667
|
+
* Center of mass calculation - vertex shader
|
|
1668
|
+
*
|
|
1669
|
+
* Renders each node as a point to a 1x1 texture.
|
|
1670
|
+
* Combined with additive blending, this sums all positions.
|
|
1671
|
+
*
|
|
1672
|
+
* All valid nodes render to the same pixel, accumulating position sums.
|
|
1673
|
+
*/
|
|
1674
|
+
precision highp float;
|
|
1675
|
+
|
|
1676
|
+
attribute vec2 pointIndex; // (x, y) in texture space
|
|
1677
|
+
|
|
1678
|
+
uniform sampler2D positionTexture;
|
|
1679
|
+
uniform float textureSize;
|
|
1680
|
+
uniform float nodeCount;
|
|
1681
|
+
|
|
1682
|
+
varying vec2 vPointIndex;
|
|
1683
|
+
|
|
1684
|
+
void main() {
|
|
1685
|
+
vPointIndex = pointIndex;
|
|
1686
|
+
|
|
1687
|
+
float index = pointIndex.y * textureSize + pointIndex.x;
|
|
1688
|
+
|
|
1689
|
+
// Skip if beyond node count - render off-screen
|
|
1690
|
+
if (index >= nodeCount) {
|
|
1691
|
+
gl_Position = vec4(10.0, 10.0, 0.0, 1.0); // Way off-screen in NDC
|
|
1692
|
+
gl_PointSize = 0.0;
|
|
1693
|
+
return;
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
// All valid points render to the center of the 1x1 texture
|
|
1697
|
+
// NDC (0, 0) maps to the center of the viewport
|
|
1698
|
+
// For a 1x1 FBO, this covers the single pixel
|
|
1699
|
+
gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
|
|
1700
|
+
|
|
1701
|
+
// Use gl_PointSize = 1.0 to ensure exactly one fragment per point
|
|
1702
|
+
// Multiple points at the same location with additive blending will sum up
|
|
1703
|
+
gl_PointSize = 1.0;
|
|
1704
|
+
}
|
|
1705
|
+
`,Ar=`/**
|
|
1706
|
+
* Center of mass calculation - fragment shader
|
|
1707
|
+
*
|
|
1708
|
+
* Outputs position.xyz as RGB and 1.0 as A (for counting).
|
|
1709
|
+
* With additive blending, this sums all positions and counts nodes.
|
|
1710
|
+
*/
|
|
1711
|
+
precision highp float;
|
|
1712
|
+
|
|
1713
|
+
uniform sampler2D positionTexture;
|
|
1714
|
+
uniform float textureSize;
|
|
1715
|
+
|
|
1716
|
+
varying vec2 vPointIndex;
|
|
1717
|
+
|
|
1718
|
+
void main() {
|
|
1719
|
+
// Sample position from texture
|
|
1720
|
+
vec2 uv = (vPointIndex + 0.5) / textureSize;
|
|
1721
|
+
vec4 pos = texture2D(positionTexture, uv);
|
|
1722
|
+
|
|
1723
|
+
// Output position (xyz) and count (1.0)
|
|
1724
|
+
gl_FragColor = vec4(pos.xyz, 1.0);
|
|
1725
|
+
}
|
|
1726
|
+
`;function Rr(e,t,n){let i=[],r=2,o=e??0,a=t??0,s=n??0,l=1,u=null,c=null,d=null,f=null,p=0,g=0,m=null,y=null,M=null,S=null,h=null,v=null,b=null,x=null,E=null,F=null,R=null,A=null;function I(w,z,P){if(!u||!z||!P||g===0){L(w);return}}function L(w){let z=0,P=0,T=0,C=i.length;for(let _=0;_<C;_++){let D=i[_];z+=D.x||0,P+=D.y||0,T+=D.z||0}let q=(z/C-o)*l,N=(P/C-a)*l,G=(T/C-s)*l;for(let _=0;_<C;_++){let D=i[_];q&&(D.x-=q),r>1&&N&&(D.y-=N),r>2&&G&&(D.z-=G)}}function B(w,z,P){}function k(w,z,P=1){if(!u||!y||!M||!F||!A||!f){console.warn("[GPU ForceCenter] applyToPosition: missing resources");return}m.remove(M);let T=new Q.Mesh(ye(),v);if(m.add(T),u.setRenderTarget(y),u.render(m,f),m.remove(T),T.geometry.dispose(),m.add(M),h.uniforms.positionTexture.value=w,h.uniforms.textureSize.value=p,h.uniforms.nodeCount.value=g,u.setRenderTarget(y),u.render(m,f),Math.random()<.02){let C=new Float32Array(4);u.readRenderTargetPixels(y,0,0,1,1,C);let q=C[0],N=C[1],G=C[2],_=C[3],D=_>0?q/_:0,O=_>0?N/_:0,Y=_>0?G/_:0;console.log(`[GPU ForceCenter] Centermass: sum=(${q.toFixed(2)}, ${N.toFixed(2)}, ${G.toFixed(2)}), count=${_}, avg=(${D.toFixed(4)}, ${O.toFixed(4)}, ${Y.toFixed(4)})`)}A.uniforms.positionTexture.value=w,A.uniforms.centermassTexture.value=y.texture,A.uniforms.centerX.value=o,A.uniforms.centerY.value=a,A.uniforms.centerZ.value=s,A.uniforms.strength.value=l,A.uniforms.alpha.value=P,A.uniforms.textureSize.value=p,A.uniforms.nodeCount.value=g,A.uniforms.nDim.value=r,u.setRenderTarget(z),u.render(F,d),u.setRenderTarget(null)}return I.initialize=function(w,z,P){i=w,r=P},I.initGPU=function(w){u=w.renderer,d=w.camera,p=w.textureSize,g=w.nodeCount,f=new Q.OrthographicCamera(-1,1,1,-1,0,1),m=new Q.Scene,y=Ee(1);let z=Fn(p);S=new Q.BufferGeometry,S.setAttribute("pointIndex",new Q.BufferAttribute(z,2));let P=p*p,T=new Float32Array(P*3);S.setAttribute("position",new Q.BufferAttribute(T,3)),h=new Q.ShaderMaterial({uniforms:{positionTexture:{value:null},textureSize:{value:p},nodeCount:{value:g}},vertexShader:Dr,fragmentShader:Ar,blending:Q.AdditiveBlending,depthTest:!1,depthWrite:!1}),M=new Q.Points(S,h),m.add(M),console.log(`[GPU ForceCenter] Initialized centermass: ${z.length/2} points, textureSize=${p}, nodeCount=${g}`),console.log(`[GPU ForceCenter] Initialized centermass calculation: ${z.length/2} points, textureSize=${p}, nodeCount=${g}`),v=new Q.ShaderMaterial({uniforms:{},vertexShader:he,fragmentShader:Zn,blending:Q.NoBlending,depthTest:!1,depthWrite:!1}),b=new Q.Scene,E=new Q.ShaderMaterial({uniforms:{positionTexture:{value:null},centermassTexture:{value:null},centerX:{value:o},centerY:{value:a},centerZ:{value:s},strength:{value:l},textureSize:{value:p},nodeCount:{value:g},nDim:{value:r}},vertexShader:he,fragmentShader:Fr,blending:Q.AdditiveBlending,depthTest:!1,depthWrite:!1}),x=new Q.Mesh(ye(),E),b.add(x),F=new Q.Scene,A=new Q.ShaderMaterial({uniforms:{positionTexture:{value:null},centermassTexture:{value:null},centerX:{value:o},centerY:{value:a},centerZ:{value:s},strength:{value:l},alpha:{value:1},textureSize:{value:p},nodeCount:{value:g},nDim:{value:r}},vertexShader:he,fragmentShader:Ir,blending:Q.NoBlending,depthTest:!1,depthWrite:!1}),R=new Q.Mesh(ye(),A),F.add(R)},I.dispose=function(){y?.dispose(),S?.dispose(),h?.dispose(),v?.dispose(),E?.dispose(),A?.dispose(),x&&x.geometry.dispose(),R&&R.geometry.dispose()},I.apply=I,I.applyToPosition=k,I.x=function(w){return arguments.length===0?o:(o=+w,I)},I.y=function(w){return arguments.length===0?a:(a=+w,I)},I.z=function(w){return arguments.length===0?s:(s=+w,I)},I.strength=function(w){return arguments.length===0?l:(l=+w,I)},I}var Ur=`/**
|
|
1727
|
+
* Quadtree build vertex shader
|
|
1728
|
+
*
|
|
1729
|
+
* Accumulates node positions into quadtree cells using point rendering.
|
|
1730
|
+
* Each node is rendered as a point to its cell, with additive blending
|
|
1731
|
+
* to sum up positions and count.
|
|
1732
|
+
*
|
|
1733
|
+
* CRITICAL: Match original cosmograph exactly - use positions directly without conversion!
|
|
1734
|
+
* Original cosmograph: vec4 pointPosition = texture2D(positionsTexture, pointIndices / pointsTextureSize);
|
|
1735
|
+
* Original cosmograph: rgba = vec4(pointPosition.rg, 1.0, 0.0);
|
|
1736
|
+
* Original cosmograph: float n = floor(pointPosition.x / cellSize);
|
|
1737
|
+
*
|
|
1738
|
+
* This means original cosmograph uses positions directly, assuming they're in [0, spaceSize] range
|
|
1739
|
+
* or handles negative positions correctly.
|
|
1740
|
+
*
|
|
1741
|
+
* Output via varying: (x, y, 1.0, 1.0)
|
|
1742
|
+
* After additive blending: (x_sum, y_sum, count, count)
|
|
1743
|
+
* Center of mass = (x_sum/count, y_sum/count)
|
|
1744
|
+
*/
|
|
1745
|
+
precision highp float;
|
|
1746
|
+
|
|
1747
|
+
uniform sampler2D positionTexture;
|
|
1748
|
+
uniform float pointsTextureSize;
|
|
1749
|
+
uniform float levelTextureSize;
|
|
1750
|
+
uniform float cellSize;
|
|
1751
|
+
uniform float spaceSize;
|
|
1752
|
+
|
|
1753
|
+
attribute vec2 pointIndex; // (x, y) index into position texture
|
|
1754
|
+
|
|
1755
|
+
varying vec4 vData;
|
|
1756
|
+
|
|
1757
|
+
void main() {
|
|
1758
|
+
// Get node position from texture
|
|
1759
|
+
vec2 uv = (pointIndex + 0.5) / pointsTextureSize;
|
|
1760
|
+
vec4 pos = texture2D(positionTexture, uv);
|
|
1761
|
+
|
|
1762
|
+
// Convert position to [0, spaceSize] range for consistent coordinate system
|
|
1763
|
+
// Positions may be in [-spaceSize/2, spaceSize/2] range (d3-force convention)
|
|
1764
|
+
// Convert to [0, spaceSize] to match cosmograph coordinate system
|
|
1765
|
+
float x = pos.x + spaceSize * 0.5;
|
|
1766
|
+
float y = pos.y + spaceSize * 0.5;
|
|
1767
|
+
|
|
1768
|
+
// Store CONVERTED coordinates for center of mass calculation
|
|
1769
|
+
// This ensures centermass calculation uses same coordinate system as force shader
|
|
1770
|
+
// IMPORTANT: alpha must be 1.0 for THREE.AdditiveBlending to work correctly!
|
|
1771
|
+
vData = vec4(x, y, 1.0, 1.0);
|
|
1772
|
+
|
|
1773
|
+
// Cell index (positions already in [0, spaceSize] range)
|
|
1774
|
+
float n = floor(x / cellSize);
|
|
1775
|
+
float m = floor(y / cellSize);
|
|
1776
|
+
|
|
1777
|
+
// Clamp to valid range
|
|
1778
|
+
n = clamp(n, 0.0, levelTextureSize - 1.0);
|
|
1779
|
+
m = clamp(m, 0.0, levelTextureSize - 1.0);
|
|
1780
|
+
|
|
1781
|
+
// Convert to clip space [-1, 1]
|
|
1782
|
+
vec2 levelPosition = 2.0 * (vec2(n, m) + 0.5) / levelTextureSize - 1.0;
|
|
1783
|
+
|
|
1784
|
+
gl_Position = vec4(levelPosition, 0.0, 1.0);
|
|
1785
|
+
gl_PointSize = 1.0;
|
|
1786
|
+
}
|
|
1787
|
+
`,Lr=`/**
|
|
1788
|
+
* Quadtree build fragment shader
|
|
1789
|
+
*
|
|
1790
|
+
* Simply passes through the accumulated data.
|
|
1791
|
+
* Additive blending handles the summation.
|
|
1792
|
+
*/
|
|
1793
|
+
precision highp float;
|
|
1794
|
+
|
|
1795
|
+
varying vec4 vData;
|
|
1796
|
+
|
|
1797
|
+
void main() {
|
|
1798
|
+
gl_FragColor = vData;
|
|
1799
|
+
}
|
|
1800
|
+
`;function Gr(e,t){e=Math.min(e,t);let n=t-e,i=`
|
|
1801
|
+
// Match d3-force manyBody.js line 84: skip if beyond distanceMax
|
|
1802
|
+
if (l >= distanceMax2) {
|
|
1803
|
+
// Skip this cell (too far)
|
|
1804
|
+
} else {
|
|
1805
|
+
// Use strength directly (no abs) to match d3-force behavior
|
|
1806
|
+
// strength < 0: repulsion, strength > 0: attraction
|
|
1807
|
+
// Match d3-force manyBody.js line 89: node.vx += x * treeNode.value * alpha / l
|
|
1808
|
+
float c = alpha * strength * centermass.b;
|
|
1809
|
+
addVelocity += calculateAdditionalVelocity(vec2(x, y), l, c, random.rg);
|
|
1810
|
+
}
|
|
1811
|
+
`;function r(s){if(s>=t)return i;{let l=Math.pow(2,s+1),u=new Array(s+1-n).fill(0).map((d,f)=>`pow(2.0, ${s-(f+n)}.0) * i${f+n}`).join("+"),c=new Array(s+1-n).fill(0).map((d,f)=>`pow(2.0, ${s-(f+n)}.0) * j${f+n}`).join("+");return`
|
|
1812
|
+
for (float ij${s} = 0.0; ij${s} < 4.0; ij${s} += 1.0) {
|
|
1813
|
+
float i${s} = 0.0;
|
|
1814
|
+
float j${s} = 0.0;
|
|
1815
|
+
if (ij${s} == 1.0 || ij${s} == 3.0) i${s} = 1.0;
|
|
1816
|
+
if (ij${s} == 2.0 || ij${s} == 3.0) j${s} = 1.0;
|
|
1817
|
+
float i = pow(2.0, ${e}.0) * n / width${s+1} + ${u};
|
|
1818
|
+
float j = pow(2.0, ${e}.0) * m / width${s+1} + ${c};
|
|
1819
|
+
float groupPosX = (i + 0.5) / ${l}.0;
|
|
1820
|
+
float groupPosY = (j + 0.5) / ${l}.0;
|
|
1821
|
+
|
|
1822
|
+
vec4 centermass = texture2D(level${s}, vec2(groupPosX, groupPosY));
|
|
1823
|
+
// Match d3-force: only check if cell has nodes (count > 0)
|
|
1824
|
+
// d3-force manyBody.js line 72: if (!treeNode.value) return true;
|
|
1825
|
+
// CRITICAL: Do NOT check x_sum or y_sum, they can be negative or zero!
|
|
1826
|
+
if (centermass.b > 0.0) {
|
|
1827
|
+
float x = centermass.r / centermass.b - pointPosition.r;
|
|
1828
|
+
float y = centermass.g / centermass.b - pointPosition.g;
|
|
1829
|
+
float l = x * x + y * y;
|
|
1830
|
+
// Match d3-force Barnes-Hut criterion exactly: w^2 / theta^2 < l
|
|
1831
|
+
// d3-force: if (w * w / theta2 < l) where theta2 = theta^2
|
|
1832
|
+
// This is equivalent to: w^2 < l * theta^2
|
|
1833
|
+
float theta2 = theta * theta;
|
|
1834
|
+
if ((width${s+1} * width${s+1}) / theta2 < l) {
|
|
1835
|
+
${i}
|
|
1836
|
+
} else {
|
|
1837
|
+
${r(s+1)}
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
`}}let o=new Array(t).fill(0).map((s,l)=>`uniform sampler2D level${l};`).join(`
|
|
1842
|
+
`),a=new Array(t).fill(0).map((s,l)=>`float width${l+1} = width${l} / 2.0;`).join(`
|
|
1843
|
+
`);return`
|
|
1844
|
+
precision highp float;
|
|
1845
|
+
|
|
1846
|
+
uniform sampler2D positionsTexture;
|
|
1847
|
+
uniform sampler2D randomValues;
|
|
1848
|
+
uniform float spaceSize;
|
|
1849
|
+
uniform float strength;
|
|
1850
|
+
uniform float theta;
|
|
1851
|
+
uniform float alpha;
|
|
1852
|
+
uniform float distanceMin; // Match d3-force: minimum distance (default: 1)
|
|
1853
|
+
uniform float distanceMax; // Match d3-force: maximum distance (default: Infinity)
|
|
1854
|
+
${o}
|
|
1855
|
+
varying vec2 vUv;
|
|
1856
|
+
|
|
1857
|
+
// Pre-computed squared distances for efficiency
|
|
1858
|
+
float distanceMin2;
|
|
1859
|
+
float distanceMax2;
|
|
1860
|
+
|
|
1861
|
+
// Jiggle function: match d3-force jiggle.js exactly
|
|
1862
|
+
// Returns (random - 0.5) * 1e-6
|
|
1863
|
+
// This adds a tiny random displacement to break symmetry when nodes align
|
|
1864
|
+
float jiggle(float randomVal) {
|
|
1865
|
+
return (randomVal - 0.5) * 1e-6;
|
|
1866
|
+
}
|
|
1867
|
+
|
|
1868
|
+
// Calculate velocity with proper jiggle handling - match d3-force manyBody.js exactly
|
|
1869
|
+
vec2 calculateAdditionalVelocity(vec2 xy, float l, float c, vec2 randomVec) {
|
|
1870
|
+
// Match d3-force exactly:
|
|
1871
|
+
// - xy = centermass - pointPosition (vector from point to centermass)
|
|
1872
|
+
// - c = alpha * strength * count (strength can be negative or positive)
|
|
1873
|
+
// - add = c / l (can be negative or positive)
|
|
1874
|
+
// - return add * xy (direction depends on sign of c)
|
|
1875
|
+
// - c < 0: repulsion (points away from centermass)
|
|
1876
|
+
// - c > 0: attraction (points toward centermass)
|
|
1877
|
+
|
|
1878
|
+
// Match d3-force manyBody.js line 85-87 and 101-103: jiggle when component is 0
|
|
1879
|
+
// CRITICAL: This breaks symmetry when nodes are aligned on an axis!
|
|
1880
|
+
// if (x === 0) x = jiggle(random), l += x * x;
|
|
1881
|
+
// if (y === 0) y = jiggle(random), l += y * y;
|
|
1882
|
+
if (xy.x == 0.0) {
|
|
1883
|
+
xy.x = jiggle(randomVec.x);
|
|
1884
|
+
l += xy.x * xy.x;
|
|
1885
|
+
}
|
|
1886
|
+
if (xy.y == 0.0) {
|
|
1887
|
+
xy.y = jiggle(randomVec.y);
|
|
1888
|
+
l += xy.y * xy.y;
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
// Match d3-force manyBody.js line 88 and 104:
|
|
1892
|
+
// if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
|
|
1893
|
+
if (l < distanceMin2) l = sqrt(distanceMin2 * l);
|
|
1894
|
+
|
|
1895
|
+
float add = c / l;
|
|
1896
|
+
return add * xy;
|
|
1897
|
+
}
|
|
1898
|
+
|
|
1899
|
+
void main() {
|
|
1900
|
+
// Read position and convert to [0, spaceSize] range to match quadtree coordinate system
|
|
1901
|
+
// Quadtree build shader stores positions in [0, spaceSize] range, so we must match here
|
|
1902
|
+
vec4 originalPosition = texture2D(positionsTexture, vUv);
|
|
1903
|
+
vec4 random = texture2D(randomValues, vUv);
|
|
1904
|
+
|
|
1905
|
+
// Pre-compute squared distances (match d3-force manyBody.js)
|
|
1906
|
+
distanceMin2 = distanceMin * distanceMin;
|
|
1907
|
+
distanceMax2 = distanceMax * distanceMax;
|
|
1908
|
+
|
|
1909
|
+
// Convert position to [0, spaceSize] range (same as quadtree build shader)
|
|
1910
|
+
vec4 pointPosition = vec4(
|
|
1911
|
+
originalPosition.x + spaceSize * 0.5,
|
|
1912
|
+
originalPosition.y + spaceSize * 0.5,
|
|
1913
|
+
originalPosition.z,
|
|
1914
|
+
originalPosition.w
|
|
1915
|
+
);
|
|
1916
|
+
|
|
1917
|
+
float width0 = spaceSize;
|
|
1918
|
+
|
|
1919
|
+
vec2 velocity = vec2(0.0);
|
|
1920
|
+
vec2 addVelocity = vec2(0.0);
|
|
1921
|
+
|
|
1922
|
+
${a}
|
|
1923
|
+
|
|
1924
|
+
for (float n = 0.0; n < pow(2.0, ${n}.0); n += 1.0) {
|
|
1925
|
+
for (float m = 0.0; m < pow(2.0, ${n}.0); m += 1.0) {
|
|
1926
|
+
${r(n)}
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
// Match d3-force algorithm: velocity += addVelocity
|
|
1931
|
+
// addVelocity already has correct direction based on strength sign:
|
|
1932
|
+
// - strength < 0: addVelocity points away (repulsion)
|
|
1933
|
+
// - strength > 0: addVelocity points toward (attraction)
|
|
1934
|
+
velocity += addVelocity;
|
|
1935
|
+
|
|
1936
|
+
// Note: alpha must be 1.0 for THREE.AdditiveBlending to work correctly
|
|
1937
|
+
gl_FragColor = vec4(velocity, 0.0, 1.0);
|
|
1938
|
+
}
|
|
1939
|
+
`}function Nr(){let e=[],t=2,n=-30,i=.9,r=1,o=1/0,a=null,s=null,l=0,u=0,c=10,d=0,f=[],p=null,g=null,m=null,y=null,M=null,S=null,h=null;function v(I,L,B){!a||!L||!B||u===0||(E(L),R(I,L,B))}let b=[],x=0;function E(I){if(!a||!g||!m||!s)return;m.uniforms.positionTexture.value=I;let L=a.autoClear,B=a.getClearColor(new $.Color),k=a.getClearAlpha();a.autoClear=!0,a.setClearColor(0,0);for(let w=0;w<d;w++){let z=b[w];m.uniforms.levelTextureSize.value=z.textureSize,m.uniforms.cellSize.value=z.cellSize,a.setRenderTarget(f[w]),a.render(g,s)}a.autoClear=L,a.setClearColor(B,k),a.setRenderTarget(null)}let F=!1;function R(I,L,B){if(!a||!M||!S||!s)return;if(S.uniforms.positionsTexture.value=L,S.uniforms.alpha.value=I,!F){S.uniforms.randomValues.value=p?.texture,S.uniforms.strength.value=n,S.uniforms.theta.value=i,S.uniforms.spaceSize.value=c,S.uniforms.distanceMin.value=r,S.uniforms.distanceMax.value=o===1/0?c*10:o;for(let w=0;w<d;w++)S.uniforms[`level${w}`].value=f[w].texture;F=!0}let k=a.autoClear;a.autoClear=!1,a.setRenderTarget(B),a.render(M,s),a.autoClear=k,a.setRenderTarget(null)}let A=Math.random;return v.initialize=function(I,L,B){e=I,t=B,A=L},v.initGPU=function(I){a=I.renderer,s=I.camera,l=I.textureSize,u=I.nodeCount;let L=Ne(u,t),k=Math.max(10,L*2);c=Math.pow(2,Math.ceil(Math.log2(k)));let w=Math.floor(Math.log2(c));d=Math.min(w+4,13);let P=d,T=Math.min(d,14),C=Math.min(d,T),q=d-C,N=new Float32Array(l*l*4);for(let V=0;V<l*l;V++)N[V*4]=A(),N[V*4+1]=A(),N[V*4+2]=0,N[V*4+3]=0;let G=new $.DataTexture(N,l,l,$.RGBAFormat,$.FloatType);G.needsUpdate=!0,p?.dispose(),p=new $.WebGLRenderTarget(l,l,{type:$.FloatType,format:$.RGBAFormat,minFilter:$.NearestFilter,magFilter:$.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});let _=new $.ShaderMaterial({uniforms:{tDiffuse:{value:G}},vertexShader:he,fragmentShader:`
|
|
1940
|
+
precision highp float;
|
|
1941
|
+
uniform sampler2D tDiffuse;
|
|
1942
|
+
varying vec2 vUv;
|
|
1943
|
+
void main() { gl_FragColor = texture2D(tDiffuse, vUv); }
|
|
1944
|
+
`}),D=new $.Scene,O=new $.Mesh(ye(),_);D.add(O),a.setRenderTarget(p),a.render(D,s),a.setRenderTarget(null),_.dispose(),O.geometry.dispose(),G.dispose(),f.forEach(V=>V.dispose()),f=[],b=[];for(let V=0;V<d;V++){let ce=Math.pow(2,V+1),j=new $.WebGLRenderTarget(ce,ce,{type:$.FloatType,format:$.RGBAFormat,minFilter:$.NearestFilter,magFilter:$.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});f.push(j),b.push({textureSize:ce,cellSize:c/ce})}let Y;if(u!==x){let V=new Float32Array(u*2),ce=new Float32Array(u*3);for(let j=0;j<u;j++)V[j*2]=j%l,V[j*2+1]=Math.floor(j/l),ce[j*3]=0,ce[j*3+1]=0,ce[j*3+2]=0;Y=new $.BufferGeometry,Y.setAttribute("position",new $.BufferAttribute(ce,3)),Y.setAttribute("pointIndex",new $.BufferAttribute(V,2)),x=u}else Y=y.geometry;if(m?.dispose(),m=new $.ShaderMaterial({uniforms:{positionTexture:{value:null},pointsTextureSize:{value:l},levelTextureSize:{value:2},cellSize:{value:c/2},spaceSize:{value:c}},vertexShader:Ur,fragmentShader:Lr,blending:$.AdditiveBlending,depthTest:!1,depthWrite:!1}),g||(g=new $.Scene),y){if(y.material=m,u!==x){let V=y.geometry;y.geometry=Y,V.dispose()}}else y=new $.Points(Y,m),g.add(y);S?.dispose(),F=!1;let X={positionsTexture:{value:null},randomValues:{value:null},spaceSize:{value:c},strength:{value:n},theta:{value:i},alpha:{value:1},distanceMin:{value:r},distanceMax:{value:o===1/0?c*10:o}};for(let V=0;V<d;V++)X[`level${V}`]={value:null};let W=Gr(C,d);S=new $.ShaderMaterial({uniforms:X,vertexShader:he,fragmentShader:W,blending:$.AdditiveBlending,depthTest:!1,depthWrite:!1}),M||(M=new $.Scene),h?h.material=S:(h=new $.Mesh(ye(),S),M.add(h))},v.dispose=function(){f.forEach(I=>I.dispose()),f=[],b=[],F=!1,p?.dispose(),p=null,m?.dispose(),S?.dispose(),y?.geometry.dispose(),h?.geometry.dispose()},v.apply=v,v.strength=function(I){return arguments.length===0?n:(n=+I,S&&(S.uniforms.strength.value=n),v)},v.theta=function(I){return arguments.length===0?i:(i=+I,F=!1,v)},v.distanceMin=function(I){return arguments.length===0?r:(r=+I,F=!1,v)},v.distanceMax=function(I){return arguments.length===0?o:(o=+I,F=!1,v)},v}var qr=`
|
|
1945
|
+
precision highp float;
|
|
1946
|
+
|
|
1947
|
+
uniform sampler2D positionTexture;
|
|
1948
|
+
uniform float pointsTextureSize;
|
|
1949
|
+
uniform float levelTextureWidth; // 2D texture width = levelSize * levelSize
|
|
1950
|
+
uniform float levelTextureHeight; // 2D texture height = levelSize
|
|
1951
|
+
uniform float levelSize; // 3D grid size = 2^level
|
|
1952
|
+
uniform float cellSize;
|
|
1953
|
+
uniform float spaceSize;
|
|
1954
|
+
|
|
1955
|
+
attribute vec2 pointIndex;
|
|
1956
|
+
|
|
1957
|
+
varying vec4 vData;
|
|
1958
|
+
|
|
1959
|
+
void main() {
|
|
1960
|
+
// Get node position from texture
|
|
1961
|
+
vec2 uv = (pointIndex + 0.5) / pointsTextureSize;
|
|
1962
|
+
vec4 pos = texture2D(positionTexture, uv);
|
|
1963
|
+
|
|
1964
|
+
// Convert position to [0, spaceSize] range
|
|
1965
|
+
float x = pos.x + spaceSize * 0.5;
|
|
1966
|
+
float y = pos.y + spaceSize * 0.5;
|
|
1967
|
+
float z = pos.z + spaceSize * 0.5;
|
|
1968
|
+
|
|
1969
|
+
// Store converted coordinates and count for center of mass calculation
|
|
1970
|
+
// Format: (x_sum, y_sum, z_sum, count)
|
|
1971
|
+
vData = vec4(x, y, z, 1.0);
|
|
1972
|
+
|
|
1973
|
+
// Calculate 3D cell indices
|
|
1974
|
+
float cellX = floor(x / cellSize);
|
|
1975
|
+
float cellY = floor(y / cellSize);
|
|
1976
|
+
float cellZ = floor(z / cellSize);
|
|
1977
|
+
|
|
1978
|
+
// Clamp to valid range
|
|
1979
|
+
cellX = clamp(cellX, 0.0, levelSize - 1.0);
|
|
1980
|
+
cellY = clamp(cellY, 0.0, levelSize - 1.0);
|
|
1981
|
+
cellZ = clamp(cellZ, 0.0, levelSize - 1.0);
|
|
1982
|
+
|
|
1983
|
+
// Flatten 3D to 2D: (cellX, cellY, cellZ) \u2192 (cellX + cellZ * levelSize, cellY)
|
|
1984
|
+
float flatX = cellX + cellZ * levelSize;
|
|
1985
|
+
float flatY = cellY;
|
|
1986
|
+
|
|
1987
|
+
// Convert to clip space [-1, 1]
|
|
1988
|
+
vec2 levelPosition = 2.0 * (vec2(flatX, flatY) + 0.5) / vec2(levelTextureWidth, levelTextureHeight) - 1.0;
|
|
1989
|
+
|
|
1990
|
+
gl_Position = vec4(levelPosition, 0.0, 1.0);
|
|
1991
|
+
gl_PointSize = 1.0;
|
|
1992
|
+
}
|
|
1993
|
+
`,Or=`
|
|
1994
|
+
precision highp float;
|
|
1995
|
+
varying vec4 vData;
|
|
1996
|
+
void main() {
|
|
1997
|
+
gl_FragColor = vData;
|
|
1998
|
+
}
|
|
1999
|
+
`;function Hr(e,t){e=Math.min(e,t);let n=t-e;function i(s){let l=t-1-Math.min(s,t-1);return`
|
|
2000
|
+
if (l >= distanceMax2) {
|
|
2001
|
+
// Skip this cell (too far)
|
|
2002
|
+
} else {
|
|
2003
|
+
float c = alpha * strength * centermass.w * ${Math.pow(Math.sqrt(4/8),l).toFixed(6)};
|
|
2004
|
+
addVelocity += calculateAdditionalVelocity(vec3(dx, dy, dz), l, c, random.rgb);
|
|
2005
|
+
}
|
|
2006
|
+
`}function r(s){if(s>=t)return i(t-1);{let l=Math.pow(2,s+1),u=new Array(s+1-n).fill(0).map((f,p)=>`pow(2.0, ${s-(p+n)}.0) * i${p+n}`).join("+"),c=new Array(s+1-n).fill(0).map((f,p)=>`pow(2.0, ${s-(p+n)}.0) * j${p+n}`).join("+"),d=new Array(s+1-n).fill(0).map((f,p)=>`pow(2.0, ${s-(p+n)}.0) * k${p+n}`).join("+");return`
|
|
2007
|
+
for (float ijk${s} = 0.0; ijk${s} < 8.0; ijk${s} += 1.0) {
|
|
2008
|
+
float i${s} = mod(ijk${s}, 2.0);
|
|
2009
|
+
float j${s} = mod(floor(ijk${s} / 2.0), 2.0);
|
|
2010
|
+
float k${s} = floor(ijk${s} / 4.0);
|
|
2011
|
+
|
|
2012
|
+
float cellI = pow(2.0, ${e}.0) * outerI / width${s+1} + ${u};
|
|
2013
|
+
float cellJ = pow(2.0, ${e}.0) * outerJ / width${s+1} + ${c};
|
|
2014
|
+
float cellK = pow(2.0, ${e}.0) * outerK / width${s+1} + ${d};
|
|
2015
|
+
|
|
2016
|
+
// Sample from flattened 2D texture
|
|
2017
|
+
// 3D (cellI, cellJ, cellK) \u2192 2D (cellI + cellK * gridSize, cellJ)
|
|
2018
|
+
float texWidth${s} = ${l}.0 * ${l}.0;
|
|
2019
|
+
float texHeight${s} = ${l}.0;
|
|
2020
|
+
float flatX${s} = cellI + cellK * ${l}.0;
|
|
2021
|
+
float flatY${s} = cellJ;
|
|
2022
|
+
vec2 texCoord${s} = (vec2(flatX${s}, flatY${s}) + 0.5) / vec2(texWidth${s}, texHeight${s});
|
|
2023
|
+
|
|
2024
|
+
vec4 centermass = texture2D(level${s}, texCoord${s});
|
|
2025
|
+
|
|
2026
|
+
// Check if cell has nodes (count > 0)
|
|
2027
|
+
if (centermass.w > 0.0) {
|
|
2028
|
+
// Calculate center of mass
|
|
2029
|
+
float cmX = centermass.x / centermass.w;
|
|
2030
|
+
float cmY = centermass.y / centermass.w;
|
|
2031
|
+
float cmZ = centermass.z / centermass.w;
|
|
2032
|
+
|
|
2033
|
+
float dx = cmX - pointPosition.x;
|
|
2034
|
+
float dy = cmY - pointPosition.y;
|
|
2035
|
+
float dz = cmZ - pointPosition.z;
|
|
2036
|
+
float l = dx * dx + dy * dy + dz * dz;
|
|
2037
|
+
|
|
2038
|
+
// 3D Barnes-Hut criterion: w^2 / theta^2 < l
|
|
2039
|
+
float theta2 = theta * theta;
|
|
2040
|
+
if ((width${s+1} * width${s+1}) / theta2 < l) {
|
|
2041
|
+
${i(s)}
|
|
2042
|
+
} else {
|
|
2043
|
+
${r(s+1)}
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
`}}let o=new Array(t).fill(0).map((s,l)=>`uniform sampler2D level${l};`).join(`
|
|
2048
|
+
`),a=new Array(t).fill(0).map((s,l)=>`float width${l+1} = width${l} / 2.0;`).join(`
|
|
2049
|
+
`);return`
|
|
2050
|
+
precision highp float;
|
|
2051
|
+
|
|
2052
|
+
uniform sampler2D positionsTexture;
|
|
2053
|
+
uniform sampler2D randomValues;
|
|
2054
|
+
uniform float spaceSize;
|
|
2055
|
+
uniform float strength;
|
|
2056
|
+
uniform float theta;
|
|
2057
|
+
uniform float alpha;
|
|
2058
|
+
uniform float distanceMin; // Match d3-force: minimum distance (default: 1)
|
|
2059
|
+
uniform float distanceMax; // Match d3-force: maximum distance (default: Infinity)
|
|
2060
|
+
${o}
|
|
2061
|
+
varying vec2 vUv;
|
|
2062
|
+
|
|
2063
|
+
// Pre-computed squared distances for efficiency
|
|
2064
|
+
float distanceMin2;
|
|
2065
|
+
float distanceMax2;
|
|
2066
|
+
|
|
2067
|
+
// Jiggle function: add small random displacement when distance is 0
|
|
2068
|
+
// This prevents nodes from sticking together (match d3-force jiggle.js)
|
|
2069
|
+
float jiggle(float randomVal) {
|
|
2070
|
+
return (randomVal - 0.5) * 1e-6;
|
|
2071
|
+
}
|
|
2072
|
+
|
|
2073
|
+
vec3 calculateAdditionalVelocity(vec3 xyz, float l, float c, vec3 randomVec) {
|
|
2074
|
+
// Match d3-force exactly:
|
|
2075
|
+
// - xyz = centermass - pointPosition (vector from point to centermass)
|
|
2076
|
+
// - c = alpha * strength * count (strength can be negative or positive)
|
|
2077
|
+
// - add = c / l (can be negative or positive)
|
|
2078
|
+
// - return add * xyz (direction depends on sign of c)
|
|
2079
|
+
// - c < 0: repulsion (points away from centermass)
|
|
2080
|
+
// - c > 0: attraction (points toward centermass)
|
|
2081
|
+
// Match d3-force: add jiggle when components are 0
|
|
2082
|
+
if (xyz.x == 0.0) { xyz.x = jiggle(randomVec.x); l += xyz.x * xyz.x; }
|
|
2083
|
+
if (xyz.y == 0.0) { xyz.y = jiggle(randomVec.y); l += xyz.y * xyz.y; }
|
|
2084
|
+
if (xyz.z == 0.0) { xyz.z = jiggle(randomVec.z); l += xyz.z * xyz.z; }
|
|
2085
|
+
|
|
2086
|
+
// Match d3-force manyBody.js line 88 and 104:
|
|
2087
|
+
// if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
|
|
2088
|
+
if (l < distanceMin2) l = sqrt(distanceMin2 * l);
|
|
2089
|
+
float add = c / l;
|
|
2090
|
+
return add * xyz;
|
|
2091
|
+
}
|
|
2092
|
+
|
|
2093
|
+
void main() {
|
|
2094
|
+
vec4 originalPosition = texture2D(positionsTexture, vUv);
|
|
2095
|
+
vec4 random = texture2D(randomValues, vUv);
|
|
2096
|
+
|
|
2097
|
+
// Pre-compute squared distances (match d3-force manyBody.js)
|
|
2098
|
+
distanceMin2 = distanceMin * distanceMin;
|
|
2099
|
+
distanceMax2 = distanceMax * distanceMax;
|
|
2100
|
+
|
|
2101
|
+
// Convert position to [0, spaceSize] range
|
|
2102
|
+
vec3 pointPosition = vec3(
|
|
2103
|
+
originalPosition.x + spaceSize * 0.5,
|
|
2104
|
+
originalPosition.y + spaceSize * 0.5,
|
|
2105
|
+
originalPosition.z + spaceSize * 0.5
|
|
2106
|
+
);
|
|
2107
|
+
|
|
2108
|
+
float width0 = spaceSize;
|
|
2109
|
+
|
|
2110
|
+
vec3 velocity = vec3(0.0);
|
|
2111
|
+
vec3 addVelocity = vec3(0.0);
|
|
2112
|
+
|
|
2113
|
+
${a}
|
|
2114
|
+
|
|
2115
|
+
// Outer loops for coarse levels
|
|
2116
|
+
for (float outerI = 0.0; outerI < pow(2.0, ${n}.0); outerI += 1.0) {
|
|
2117
|
+
for (float outerJ = 0.0; outerJ < pow(2.0, ${n}.0); outerJ += 1.0) {
|
|
2118
|
+
for (float outerK = 0.0; outerK < pow(2.0, ${n}.0); outerK += 1.0) {
|
|
2119
|
+
${r(n)}
|
|
2120
|
+
}
|
|
2121
|
+
}
|
|
2122
|
+
}
|
|
2123
|
+
|
|
2124
|
+
// Match d3-force algorithm: velocity += addVelocity
|
|
2125
|
+
// addVelocity already has correct direction based on strength sign:
|
|
2126
|
+
// - strength < 0: addVelocity points away (repulsion)
|
|
2127
|
+
// - strength > 0: addVelocity points toward (attraction)
|
|
2128
|
+
velocity += addVelocity;
|
|
2129
|
+
|
|
2130
|
+
// Output 3D velocity (xyz) with alpha = 1.0 for blending
|
|
2131
|
+
gl_FragColor = vec4(velocity, 1.0);
|
|
2132
|
+
}
|
|
2133
|
+
`}function Xr(){let e=[],t=2,n=-30,i=.5,r=1,o=1/0,a=null,s=null,l=null,u=0,c=0,d=10,f=0,p=[],g=null,m=null,y=null,M=null,S=null,h=null,v=null;function b(L,B,k){!s||!B||!k||c===0||(F(B),A(L,B,k))}let x=[],E=0;function F(L){if(!s||!m||!y||!l)return;y.uniforms.positionTexture.value=L;let B=s.autoClear,k=s.getClearColor(new Z.Color),w=s.getClearAlpha();s.autoClear=!0,s.setClearColor(0,0);for(let z=0;z<f;z++){let P=x[z];y.uniforms.levelSize.value=P.levelSize,y.uniforms.levelTextureWidth.value=P.textureWidth,y.uniforms.levelTextureHeight.value=P.textureHeight,y.uniforms.cellSize.value=P.cellSize,s.setRenderTarget(p[z]),s.render(m,l)}s.autoClear=B,s.setClearColor(k,w),s.setRenderTarget(null)}let R=!1;function A(L,B,k){if(!s||!S||!h||!l)return;if(h.uniforms.positionsTexture.value=B,h.uniforms.alpha.value=L,!R){h.uniforms.randomValues.value=g?.texture,h.uniforms.strength.value=n,h.uniforms.theta.value=i,h.uniforms.spaceSize.value=d,h.uniforms.distanceMin.value=r,h.uniforms.distanceMax.value=o===1/0?d*10:o;for(let z=0;z<f;z++)h.uniforms[`level${z}`].value=p[z].texture;R=!0}let w=s.autoClear;s.autoClear=!1,s.setRenderTarget(k),s.render(S,l),s.autoClear=w,s.setRenderTarget(null)}let I=Math.random;return b.initialize=function(L,B,k){e=L,t=k,I=B},b.initGPU=function(L){s=L.renderer,l=L.camera,u=L.textureSize,c=L.nodeCount;let B=Ne(c,t),k=Math.min(20,6+Math.log10(Math.max(c,2))),w=Math.max(40,B*k);w>8192&&console.warn(`[ManyBody Octree 3D] paddedSpaceSize=${w.toFixed(0)} exceeds cap 8192; clamping. N=${c} may have boundary spike. Consider Option B adaptive resize.`),d=Math.min(8192,Math.pow(2,Math.ceil(Math.log2(w))));let z=s.getContext(),P=z.getParameter(z.MAX_TEXTURE_SIZE);console.log(`[ManyBody Octree 3D] GPU MAX_TEXTURE_SIZE = ${P}`);let T=Math.floor(Math.log2(P)/2),C=Math.min(Math.floor(Math.log2(d)),T,8);f=a!==null?Math.min(a,C):C,console.log(`[ManyBody Octree 3D] nodeCount=${c}, spaceSize=${d}, maxGPUTexture=${P}`),console.log(`[ManyBody Octree 3D] calculatedLevels=${C}, initialOctreeLevels=${f}`),console.log(`[ManyBody Octree 3D] theta=${i}, strength=${n}`);let q=new Float32Array(u*u*4);for(let j=0;j<u*u;j++)q[j*4]=I(),q[j*4+1]=I(),q[j*4+2]=I(),q[j*4+3]=0;let N=new Z.DataTexture(q,u,u,Z.RGBAFormat,Z.FloatType);N.needsUpdate=!0,g?.dispose(),g=new Z.WebGLRenderTarget(u,u,{type:Z.FloatType,format:Z.RGBAFormat,minFilter:Z.NearestFilter,magFilter:Z.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});let G=new Z.ShaderMaterial({uniforms:{tDiffuse:{value:N}},vertexShader:he,fragmentShader:`
|
|
2134
|
+
precision highp float;
|
|
2135
|
+
uniform sampler2D tDiffuse;
|
|
2136
|
+
varying vec2 vUv;
|
|
2137
|
+
void main() { gl_FragColor = texture2D(tDiffuse, vUv); }
|
|
2138
|
+
`}),_=new Z.Scene,D=new Z.Mesh(ye(),G);_.add(D),s.setRenderTarget(g),s.render(_,l),s.setRenderTarget(null),G.dispose(),D.geometry.dispose(),N.dispose(),p.forEach(j=>j.dispose()),p=[],x=[];for(let j=0;j<f;j++){let de=Math.pow(2,j+1),ie=de*de,Be=de;if(ie>P||Be>P){console.error(`[ManyBody Octree 3D] Level ${j} texture ${ie}\xD7${Be} exceeds GPU limit ${P}! Skipping remaining levels.`),f=j;break}let ut=new Z.WebGLRenderTarget(ie,Be,{type:Z.FloatType,format:Z.RGBAFormat,minFilter:Z.NearestFilter,magFilter:Z.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});p.push(ut),x.push({levelSize:de,textureWidth:ie,textureHeight:Be,cellSize:d/de}),console.log(`[ManyBody Octree 3D] Level ${j}: grid=${de}\xB3, texture=${ie}\xD7${Be}`)}let O=Math.min(f,8),Y=Math.min(f,O),X=f-Y;console.log(`[ManyBody Octree 3D] Final: octreeLevels=${f}, shaderStartLevel=${Y}, delta=${X}`);let W;if(c!==E){let j=new Float32Array(c*2),de=new Float32Array(c*3);for(let ie=0;ie<c;ie++)j[ie*2]=ie%u,j[ie*2+1]=Math.floor(ie/u),de[ie*3]=0,de[ie*3+1]=0,de[ie*3+2]=0;W=new Z.BufferGeometry,W.setAttribute("position",new Z.BufferAttribute(de,3)),W.setAttribute("pointIndex",new Z.BufferAttribute(j,2)),E=c}else W=M.geometry;if(y?.dispose(),y=new Z.ShaderMaterial({uniforms:{positionTexture:{value:null},pointsTextureSize:{value:u},levelSize:{value:2},levelTextureWidth:{value:4},levelTextureHeight:{value:2},cellSize:{value:d/2},spaceSize:{value:d}},vertexShader:qr,fragmentShader:Or,blending:Z.AdditiveBlending,depthTest:!1,depthWrite:!1}),m||(m=new Z.Scene),M){if(M.material=y,c!==E){let j=M.geometry;M.geometry=W,j.dispose()}}else M=new Z.Points(W,y),m.add(M);h?.dispose(),R=!1;let V={positionsTexture:{value:null},randomValues:{value:null},spaceSize:{value:d},strength:{value:n},theta:{value:i},alpha:{value:1},distanceMin:{value:r},distanceMax:{value:o===1/0?d*10:o}};for(let j=0;j<f;j++)V[`level${j}`]={value:null};let ce=Hr(Y,f);h=new Z.ShaderMaterial({uniforms:V,vertexShader:he,fragmentShader:ce,blending:Z.AdditiveBlending,depthTest:!1,depthWrite:!1}),S||(S=new Z.Scene),v?v.material=h:(v=new Z.Mesh(ye(),h),S.add(v))},b.dispose=function(){p.forEach(L=>L.dispose()),p=[],x=[],R=!1,g?.dispose(),g=null,y?.dispose(),h?.dispose(),M?.geometry.dispose(),v?.geometry.dispose()},b.apply=b,b.strength=function(L){return arguments.length===0?n:(n=+L,h&&(h.uniforms.strength.value=n),b)},b.theta=function(L){return arguments.length===0?i:(i=+L,R=!1,b)},b.distanceMin=function(L){return arguments.length===0?r:(r=+L,R=!1,b)},b.distanceMax=function(L){return arguments.length===0?o:(o=+L,R=!1,b)},b.maxLevels=function(L){return arguments.length===0?a??null:(a=L>0?Math.min(L,8):null,R=!1,b)},b.getSpaceSize=function(){return typeof d=="number"&&d>0?d:10},b}var Yr=`/**
|
|
2139
|
+
* Link force vertex shader
|
|
2140
|
+
*
|
|
2141
|
+
* Each point represents one endpoint of a link.
|
|
2142
|
+
* The vertex position is set to the node's location in the velocity texture
|
|
2143
|
+
* so the force is applied to the correct node.
|
|
2144
|
+
*/
|
|
2145
|
+
precision highp float;
|
|
2146
|
+
|
|
2147
|
+
// x = link endpoint index, y = node index
|
|
2148
|
+
attribute vec2 linkEndpoint;
|
|
2149
|
+
|
|
2150
|
+
uniform float nodeTextureSize;
|
|
2151
|
+
|
|
2152
|
+
varying float vLinkIndex;
|
|
2153
|
+
varying float vNodeIndex;
|
|
2154
|
+
|
|
2155
|
+
void main() {
|
|
2156
|
+
vLinkIndex = linkEndpoint.x;
|
|
2157
|
+
vNodeIndex = linkEndpoint.y;
|
|
2158
|
+
|
|
2159
|
+
// Convert node index to UV coordinates in velocity texture
|
|
2160
|
+
float x = mod(vNodeIndex, nodeTextureSize);
|
|
2161
|
+
float y = floor(vNodeIndex / nodeTextureSize);
|
|
2162
|
+
vec2 uv = (vec2(x, y) + 0.5) / nodeTextureSize;
|
|
2163
|
+
|
|
2164
|
+
// Convert UV to clip space [-1, 1]
|
|
2165
|
+
vec2 pos = uv * 2.0 - 1.0;
|
|
2166
|
+
|
|
2167
|
+
gl_Position = vec4(pos, 0.0, 1.0);
|
|
2168
|
+
gl_PointSize = 1.0;
|
|
2169
|
+
}
|
|
2170
|
+
`,$r=`/**
|
|
2171
|
+
* Link force fragment shader
|
|
2172
|
+
*
|
|
2173
|
+
* Implements d3-force's forceLink spring behavior:
|
|
2174
|
+
* - Calculates spring force to pull/push nodes toward target distance
|
|
2175
|
+
* - Uses bias to distribute force asymmetrically based on node degree
|
|
2176
|
+
*
|
|
2177
|
+
* Each fragment represents the force applied to one endpoint of a link.
|
|
2178
|
+
*/
|
|
2179
|
+
precision highp float;
|
|
2180
|
+
|
|
2181
|
+
uniform sampler2D positionTexture;
|
|
2182
|
+
uniform sampler2D linkTexture;
|
|
2183
|
+
uniform float linkTextureSize;
|
|
2184
|
+
uniform float nodeTextureSize;
|
|
2185
|
+
uniform float nodeCount;
|
|
2186
|
+
uniform float alpha;
|
|
2187
|
+
uniform float nDim;
|
|
2188
|
+
|
|
2189
|
+
varying float vLinkIndex;
|
|
2190
|
+
varying float vNodeIndex;
|
|
2191
|
+
|
|
2192
|
+
// Get node position from texture
|
|
2193
|
+
vec3 getNodePosition(float index) {
|
|
2194
|
+
float x = mod(index, nodeTextureSize);
|
|
2195
|
+
float y = floor(index / nodeTextureSize);
|
|
2196
|
+
vec2 uv = (vec2(x, y) + 0.5) / nodeTextureSize;
|
|
2197
|
+
return texture2D(positionTexture, uv).xyz;
|
|
2198
|
+
}
|
|
2199
|
+
|
|
2200
|
+
void main() {
|
|
2201
|
+
// Read link data from texture
|
|
2202
|
+
// Format: [sourceIndex, targetIndex, distance, strength] per link
|
|
2203
|
+
// Endpoint texture: [endpointIndex = linkIndex * 2 + side]
|
|
2204
|
+
|
|
2205
|
+
float linkIndex = floor(vLinkIndex / 2.0);
|
|
2206
|
+
float side = mod(vLinkIndex, 2.0); // 0 = source, 1 = target
|
|
2207
|
+
|
|
2208
|
+
// Calculate link texture UV
|
|
2209
|
+
float lx = mod(linkIndex, linkTextureSize);
|
|
2210
|
+
float ly = floor(linkIndex / linkTextureSize);
|
|
2211
|
+
vec2 luv = (vec2(lx, ly) + 0.5) / linkTextureSize;
|
|
2212
|
+
vec4 linkData = texture2D(linkTexture, luv);
|
|
2213
|
+
|
|
2214
|
+
float sourceIndex = linkData.r;
|
|
2215
|
+
float targetIndex = linkData.g;
|
|
2216
|
+
float linkDistance = linkData.b;
|
|
2217
|
+
float linkStrength = linkData.a;
|
|
2218
|
+
|
|
2219
|
+
// Guard invalid indices
|
|
2220
|
+
if (sourceIndex < 0.0 || targetIndex < 0.0 ||
|
|
2221
|
+
sourceIndex >= nodeCount || targetIndex >= nodeCount) {
|
|
2222
|
+
gl_FragColor = vec4(0.0);
|
|
2223
|
+
return;
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
// Get positions
|
|
2227
|
+
vec3 sourcePos = getNodePosition(sourceIndex);
|
|
2228
|
+
vec3 targetPos = getNodePosition(targetIndex);
|
|
2229
|
+
|
|
2230
|
+
// Calculate direction and distance
|
|
2231
|
+
vec3 delta = targetPos - sourcePos;
|
|
2232
|
+
|
|
2233
|
+
// Mask dimensions
|
|
2234
|
+
if (nDim < 3.0) delta.z = 0.0;
|
|
2235
|
+
if (nDim < 2.0) delta.y = 0.0;
|
|
2236
|
+
|
|
2237
|
+
float dist = length(delta);
|
|
2238
|
+
|
|
2239
|
+
// Prevent division by zero
|
|
2240
|
+
if (dist < 1e-6) {
|
|
2241
|
+
gl_FragColor = vec4(0.0);
|
|
2242
|
+
return;
|
|
2243
|
+
}
|
|
2244
|
+
|
|
2245
|
+
vec3 dir = delta / dist;
|
|
2246
|
+
|
|
2247
|
+
// Spring force calculation
|
|
2248
|
+
// Positive displacement = nodes too close, need to push apart
|
|
2249
|
+
// Negative displacement = nodes too far, need to pull together
|
|
2250
|
+
float displacement = dist - linkDistance;
|
|
2251
|
+
|
|
2252
|
+
// Force magnitude = alpha * strength * displacement
|
|
2253
|
+
float forceMag = alpha * linkStrength * displacement;
|
|
2254
|
+
|
|
2255
|
+
// Force direction depends on which endpoint:
|
|
2256
|
+
// - Source gets force toward target (positive displacement pulls toward target)
|
|
2257
|
+
// - Target gets force toward source (negative of source force)
|
|
2258
|
+
vec3 velocity;
|
|
2259
|
+
if (side < 0.5) {
|
|
2260
|
+
// Source endpoint: force toward target
|
|
2261
|
+
velocity = dir * forceMag;
|
|
2262
|
+
} else {
|
|
2263
|
+
// Target endpoint: force toward source
|
|
2264
|
+
velocity = -dir * forceMag;
|
|
2265
|
+
}
|
|
2266
|
+
|
|
2267
|
+
// Note: alpha must be 1.0 for THREE.AdditiveBlending to work (uses SrcAlphaFactor)
|
|
2268
|
+
gl_FragColor = vec4(velocity, 1.0);
|
|
2269
|
+
}
|
|
2270
|
+
`;function Zr(e){let t=[],n=e||[],i=2,r=Math.random,o=B=>B.index,a=E,s=te(30),l=1,u=[],c=[],d=[],f=[],p=null,g=null,m=null,y=0,M=0,S=null,h=null,v=null,b=null,x=0;function E(B){let k=typeof B.source=="object"?B.source.index:0,w=typeof B.target=="object"?B.target.index:0;return 1/Math.min(u[k]||1,u[w]||1)}function F(){if(!t||t.length===0)return;let B=t.length,k=n.length,w=new Map;for(let T=0;T<B;T++)w.set(o(t[T],T,t),t[T]);u=new Array(B).fill(0);for(let T=0;T<k;T++){let C=n[T];if(C.index=T,typeof C.source!="object"){let q=w.get(C.source);if(!q)throw new Error(`Link source not found: ${C.source}`);C.source=q}if(typeof C.target!="object"){let q=w.get(C.target);if(!q)throw new Error(`Link target not found: ${C.target}`);C.target=q}u[C.source.index]++,u[C.target.index]++}c=new Array(k);for(let T=0;T<k;T++){let C=n[T],q=C.source.index,N=C.target.index;c[T]=u[q]/(u[q]+u[N])}d=new Array(k),f=new Array(k);let z=typeof a=="function"?a:()=>a,P=typeof s=="function"?s:()=>s;for(let T=0;T<k;T++)d[T]=+z(n[T],T,n),f[T]=+P(n[T],T,n);R()}function R(){if(!b||n.length===0)return;let B=b.image.data;for(let k=0;k<n.length;k++){let w=n[k],z=w.source.index,P=w.target.index,T=k*4;B[T]=z,B[T+1]=P,B[T+2]=f[k],B[T+3]=d[k]}b.needsUpdate=!0}function A(B,k,w){if(n.length!==0){if(!p||!k||!w||M===0){I(B);return}L(B,k,w)}}function I(B){for(let k=0;k<l;k++)for(let w=0;w<n.length;w++){let z=n[w],P=z.source,T=z.target,C=(T.x||0)+(T.vx||0)-(P.x||0)-(P.vx||0)||at(r),q=i>1?(T.y||0)+(T.vy||0)-(P.y||0)-(P.vy||0)||at(r):0,N=i>2?(T.z||0)+(T.vz||0)-(P.z||0)-(P.vz||0)||at(r):0,G=Math.sqrt(C*C+q*q+N*N);G=(G-f[w])/G*B*d[w],C*=G,q*=G,N*=G;let _=c[w];T.vx-=C*_,i>1&&(T.vy-=q*_),i>2&&(T.vz-=N*_),P.vx+=C*(1-_),i>1&&(P.vy+=q*(1-_)),i>2&&(P.vz+=N*(1-_))}}function L(B,k,w){if(!S||!v)return;v.uniforms.positionTexture.value=k,v.uniforms.linkTexture.value=b,v.uniforms.linkTextureSize.value=x,v.uniforms.nodeTextureSize.value=y,v.uniforms.nodeCount.value=M,v.uniforms.alpha.value=B,v.uniforms.nDim.value=i;let z=p.autoClear;p.autoClear=!1;for(let P=0;P<l;P++)p.setRenderTarget(w),g&&p.render(g,m);p.autoClear=z,p.setRenderTarget(null)}return A.initialize=function(B,k,w){t=B,r=k,i=w,F()},A.initGPU=function(B){if(p=B.renderer,m=B.camera,y=B.textureSize,M=B.nodeCount,n.length===0)return;x=Ct(n.length);let k=new Float32Array(x*x*4);k.fill(-1);for(let T=0;T<n.length;T++){let C=n[T],q=C.source.index,N=C.target.index,G=T*4;k[G]=q,k[G+1]=N,k[G+2]=f[T],k[G+3]=d[T]}b?.dispose(),b=new ne.DataTexture(k,x,x,ne.RGBAFormat,ne.FloatType),b.needsUpdate=!0;let w=n.length*2,z=new Float32Array(w*2);for(let T=0;T<n.length;T++){let C=n[T],q=C.source.index,N=C.target.index;z[T*4]=T*2,z[T*4+1]=q,z[T*4+2]=T*2+1,z[T*4+3]=N}h?.dispose(),h=new ne.BufferGeometry,h.setAttribute("linkEndpoint",new ne.BufferAttribute(z,2));let P=new Float32Array(z.length/2*3);h.setAttribute("position",new ne.BufferAttribute(P,3)),v?.dispose(),v=new ne.ShaderMaterial({uniforms:{positionTexture:{value:null},linkTexture:{value:b},linkTextureSize:{value:x},nodeTextureSize:{value:y},nodeCount:{value:M},alpha:{value:1},nDim:{value:i}},vertexShader:Yr,fragmentShader:$r,blending:ne.AdditiveBlending,depthTest:!1,depthWrite:!1}),S&&g&&g.remove(S),g=new ne.Scene,S=new ne.Points(h,v),g.add(S)},A.dispose=function(){b?.dispose(),h?.dispose(),v?.dispose(),S&&g?.remove(S)},A.apply=A,A.links=function(B){return arguments.length===0?n:(n=B,F(),A)},A.id=function(B){return arguments.length===0?o:(o=B,A)},A.iterations=function(B){return arguments.length===0?l:(l=+B,A)},A.strength=function(B){return arguments.length===0?a:(a=typeof B=="function"?B:te(+B),F(),R(),A)},A.distance=function(B){return arguments.length===0?s:(s=typeof B=="function"?B:te(+B),F(),R(),A)},A}var Ft=`/**
|
|
2271
|
+
* Position force shader (forceX/Y/Z)
|
|
2272
|
+
*
|
|
2273
|
+
* Implements d3-force's forceX/forceY/forceZ:
|
|
2274
|
+
* - Applies a force that pulls each node toward a target position along one axis
|
|
2275
|
+
* - Uses per-node strength for fine-grained control
|
|
2276
|
+
*
|
|
2277
|
+
* This shader handles all three axes based on uniforms.
|
|
2278
|
+
*/
|
|
2279
|
+
precision highp float;
|
|
2280
|
+
|
|
2281
|
+
uniform sampler2D positionTexture;
|
|
2282
|
+
uniform sampler2D targetTexture; // Target position per node (x in R, strength in G)
|
|
2283
|
+
uniform float alpha;
|
|
2284
|
+
uniform float textureSize;
|
|
2285
|
+
uniform float nodeCount;
|
|
2286
|
+
uniform float axis; // 0 = x, 1 = y, 2 = z
|
|
2287
|
+
|
|
2288
|
+
varying vec2 vUv;
|
|
2289
|
+
|
|
2290
|
+
void main() {
|
|
2291
|
+
// Calculate node index
|
|
2292
|
+
float x = floor(vUv.x * textureSize);
|
|
2293
|
+
float y = floor(vUv.y * textureSize);
|
|
2294
|
+
float nodeIndex = y * textureSize + x;
|
|
2295
|
+
|
|
2296
|
+
// Output zero for invalid indices
|
|
2297
|
+
if (nodeIndex >= nodeCount) {
|
|
2298
|
+
gl_FragColor = vec4(0.0);
|
|
2299
|
+
return;
|
|
2300
|
+
}
|
|
2301
|
+
|
|
2302
|
+
// Get current position
|
|
2303
|
+
vec4 pos = texture2D(positionTexture, vUv);
|
|
2304
|
+
|
|
2305
|
+
// Get target position and strength
|
|
2306
|
+
vec4 target = texture2D(targetTexture, vUv);
|
|
2307
|
+
float targetPos = target.r;
|
|
2308
|
+
float strength = target.g;
|
|
2309
|
+
|
|
2310
|
+
// Calculate force toward target
|
|
2311
|
+
vec3 velocity = vec3(0.0);
|
|
2312
|
+
|
|
2313
|
+
if (axis < 0.5) {
|
|
2314
|
+
// X axis
|
|
2315
|
+
velocity.x = (targetPos - pos.x) * strength * alpha;
|
|
2316
|
+
} else if (axis < 1.5) {
|
|
2317
|
+
// Y axis
|
|
2318
|
+
velocity.y = (targetPos - pos.y) * strength * alpha;
|
|
2319
|
+
} else {
|
|
2320
|
+
// Z axis
|
|
2321
|
+
velocity.z = (targetPos - pos.z) * strength * alpha;
|
|
2322
|
+
}
|
|
2323
|
+
|
|
2324
|
+
// Note: alpha must be 1.0 for THREE.AdditiveBlending to work (uses SrcAlphaFactor)
|
|
2325
|
+
gl_FragColor = vec4(velocity, 1.0);
|
|
2326
|
+
}
|
|
2327
|
+
`;function jr(e){let t=[],n=te(.1),i=e==null?te(0):typeof e=="function"?e:te(+e),r=[],o=[],a=null,s=null,l=null,u=0,c=0,d=null,f=null,p=null;function g(){if(!t)return;let h=t.length;r=new Array(h),o=new Array(h);let v=typeof i=="function"?i:()=>i,b=typeof n=="function"?n:()=>n;for(let x=0;x<h;x++)o[x]=+v(t[x],x,t),r[x]=isNaN(o[x])?0:+b(t[x],x,t);p&&u>0&&m()}function m(){let h=u*u,v=new Float32Array(h*4);for(let b=0;b<t.length;b++){let x=b*4;v[x]=o[b]??0,v[x+1]=r[b]??0,v[x+2]=0,v[x+3]=0}p.image.data.set(v),p.needsUpdate=!0}function y(h,v,b){if(!a||!v||!b||c===0||!f||!p){M(h);return}S(h,v,b)}function M(h){for(let v=0;v<t.length;v++){let b=t[v];b.vx+=(o[v]-(b.x||0))*r[v]*h}}function S(h,v,b){f.uniforms.positionTexture.value=v,f.uniforms.targetTexture.value=p,f.uniforms.alpha.value=h,f.uniforms.textureSize.value=u,f.uniforms.nodeCount.value=c,f.uniforms.axis.value=0;let x=a.autoClear;a.autoClear=!1,a.setRenderTarget(b),a.render(s,l),a.autoClear=x,a.setRenderTarget(null)}return y.initialize=function(h,v,b){t=h,g()},y.initGPU=function(h){a=h.renderer,l=h.camera,u=h.textureSize,c=h.nodeCount,t.length>0&&(o.length===0||r.length===0)&&g();let v=u*u,b=new Float32Array(v*4),x=0,E=0;for(let F=0;F<t.length;F++){let R=F*4;b[R]=o[F]??0,b[R+1]=r[F]??0,b[R+2]=0,b[R+3]=0,F<10&&(x+=r[F]??0,E+=o[F]??0)}p?.dispose(),p=new ae.DataTexture(b,u,u,ae.RGBAFormat,ae.FloatType),p.minFilter=ae.NearestFilter,p.magFilter=ae.NearestFilter,p.needsUpdate=!0,s=new ae.Scene,f=new ae.ShaderMaterial({uniforms:{positionTexture:{value:null},targetTexture:{value:p},alpha:{value:1},textureSize:{value:u},nodeCount:{value:c},axis:{value:0}},vertexShader:he,fragmentShader:Ft,blending:ae.AdditiveBlending,depthTest:!1,depthWrite:!1}),d=new ae.Mesh(ye(),f),s.add(d)},y.dispose=function(){p?.dispose(),f?.dispose(),d&&(d.geometry.dispose(),s?.remove(d))},y.apply=y,y.strength=function(h){return arguments.length===0?n:(n=typeof h=="function"?h:te(+h),g(),y)},y.x=function(h){return arguments.length===0?i:(i=typeof h=="function"?h:te(+h),g(),y)},y}function Vr(e){let t=[],n=te(.1),i=e==null?te(0):typeof e=="function"?e:te(+e),r=[],o=[],a=null,s=null,l=null,u=0,c=0,d=null,f=null,p=null;function g(){if(!t)return;let h=t.length;r=new Array(h),o=new Array(h);let v=typeof i=="function"?i:()=>i,b=typeof n=="function"?n:()=>n;for(let x=0;x<h;x++)o[x]=+v(t[x],x,t),r[x]=isNaN(o[x])?0:+b(t[x],x,t);p&&u>0&&m()}function m(){let h=u*u,v=new Float32Array(h*4);for(let b=0;b<t.length;b++){let x=b*4;v[x]=o[b]??0,v[x+1]=r[b]??0,v[x+2]=0,v[x+3]=0}p.image.data.set(v),p.needsUpdate=!0}function y(h,v,b){if(!a||!v||!b||c===0||!f||!p){M(h);return}S(h,v,b)}function M(h){for(let v=0;v<t.length;v++){let b=t[v];b.vy+=(o[v]-(b.y||0))*r[v]*h}}function S(h,v,b){f.uniforms.positionTexture.value=v,f.uniforms.targetTexture.value=p,f.uniforms.alpha.value=h,f.uniforms.textureSize.value=u,f.uniforms.nodeCount.value=c,f.uniforms.axis.value=1;let x=a.autoClear;a.autoClear=!1,a.setRenderTarget(b),a.render(s,l),a.autoClear=x,a.setRenderTarget(null)}return y.initialize=function(h,v,b){t=h,g()},y.initGPU=function(h){a=h.renderer,l=h.camera,u=h.textureSize,c=h.nodeCount,t.length>0&&(o.length===0||r.length===0)&&g();let v=u*u,b=new Float32Array(v*4),x=0,E=0;for(let F=0;F<t.length;F++){let R=F*4,A=o[F]??0,I=r[F]??0;b[R]=A,b[R+1]=I,b[R+2]=0,b[R+3]=0,F<10&&(x+=A,E+=I)}t.length>0,p?.dispose(),p=new oe.DataTexture(b,u,u,oe.RGBAFormat,oe.FloatType),p.minFilter=oe.NearestFilter,p.magFilter=oe.NearestFilter,p.needsUpdate=!0,s=new oe.Scene,f=new oe.ShaderMaterial({uniforms:{positionTexture:{value:null},targetTexture:{value:p},alpha:{value:1},textureSize:{value:u},nodeCount:{value:c},axis:{value:1}},vertexShader:he,fragmentShader:Ft,blending:oe.AdditiveBlending,depthTest:!1,depthWrite:!1}),d=new oe.Mesh(ye(),f),s.add(d)},y.dispose=function(){p?.dispose(),f?.dispose(),d&&(d.geometry.dispose(),s?.remove(d))},y.apply=y,y.strength=function(h){return arguments.length===0?n:(n=typeof h=="function"?h:te(+h),g(),y)},y.y=function(h){return arguments.length===0?i:(i=typeof h=="function"?h:te(+h),g(),y)},y}function Wr(e){let t=[],n=te(.1),i=e==null?te(0):typeof e=="function"?e:te(+e),r=[],o=[],a=null,s=null,l=null,u=0,c=0,d=null,f=null,p=null;function g(){if(!t)return;let h=t.length;r=new Array(h),o=new Array(h);let v=typeof i=="function"?i:()=>i,b=typeof n=="function"?n:()=>n;for(let x=0;x<h;x++)o[x]=+v(t[x],x,t),r[x]=isNaN(o[x])?0:+b(t[x],x,t);p&&u>0&&m()}function m(){let h=u*u,v=new Float32Array(h*4);for(let b=0;b<t.length;b++){let x=b*4;v[x]=o[b]??0,v[x+1]=r[b]??0,v[x+2]=0,v[x+3]=0}p.image.data.set(v),p.needsUpdate=!0}function y(h,v,b){if(!a||!v||!b||c===0||!f||!p){M(h);return}S(h,v,b)}function M(h){for(let v=0;v<t.length;v++){let b=t[v];b.vz+=(o[v]-(b.z||0))*r[v]*h}}function S(h,v,b){f.uniforms.positionTexture.value=v,f.uniforms.targetTexture.value=p,f.uniforms.alpha.value=h,f.uniforms.textureSize.value=u,f.uniforms.nodeCount.value=c,f.uniforms.axis.value=2;let x=a.autoClear;a.autoClear=!1,a.setRenderTarget(b),a.render(s,l),a.autoClear=x,a.setRenderTarget(null)}return y.initialize=function(h,v,b){t=h,g()},y.initGPU=function(h){a=h.renderer,l=h.camera,u=h.textureSize,c=h.nodeCount,t.length>0&&(o.length===0||r.length===0)&&g();let v=u*u,b=new Float32Array(v*4);for(let x=0;x<t.length;x++){let E=x*4;b[E]=o[x]??0,b[E+1]=r[x]??0,b[E+2]=0,b[E+3]=0}p?.dispose(),p=new se.DataTexture(b,u,u,se.RGBAFormat,se.FloatType),p.minFilter=se.NearestFilter,p.magFilter=se.NearestFilter,p.needsUpdate=!0,s=new se.Scene,f=new se.ShaderMaterial({uniforms:{positionTexture:{value:null},targetTexture:{value:p},alpha:{value:1},textureSize:{value:u},nodeCount:{value:c},axis:{value:2}},vertexShader:he,fragmentShader:Ft,blending:se.AdditiveBlending,depthTest:!1,depthWrite:!1}),d=new se.Mesh(ye(),f),s.add(d)},y.dispose=function(){p?.dispose(),f?.dispose(),d&&(d.geometry.dispose(),s?.remove(d))},y.apply=y,y.strength=function(h){return arguments.length===0?n:(n=typeof h=="function"?h:te(+h),g(),y)},y.z=function(h){return arguments.length===0?i:(i=typeof h=="function"?h:te(+h),g(),y)},y}var lt={charge:-.01,gravity:.1,linkStrength:1,linkDistance:.5,collision:.15,heightCompress:1,alpha:.6,alphaDecay:.1,velocityDecay:.3,dimensions:3,gravityX:1,gravityY:1,gravityZ:1,octreeTheta:.9},It=class{constructor(e,t){if(this.simulation=null,this.getOptions=null,this._enable=!0,this._isFinish=!1,this.nodeIdToIndex=new Map,this.lastUpdateTime=0,this.updateIntervalMs=1e3/24,this.skipCPUPositionUpdate=!1,this._dimTransition=null,this._gpuZZeroed=!1,this.graph=e,t)this.renderer=t;else{let n=document.createElement("canvas");n.style.display="none",this.renderer=new jn.WebGLRenderer({canvas:n,alpha:!0,antialias:!1}),this.renderer.setSize(256,256)}this.params={...lt}}config(e){if(this.getOptions=e,e){let t=e();t&&this.applyConfig(t)}return this}configure(e){return this.config(e)}applyConfig(e){e.friction!==void 0&&e.velocityDecay===void 0&&(e.velocityDecay=e.friction),Object.assign(this.params,e)}calculateForces(){let e=this.params.heightCompress??1,t=this.params.gravity??.1,n=this.params.dimensions??3,i,r,o,a;return n===2?(r=t*1.5,i=0,o=.02,a=.8):(i=t*Math.sqrt(e),r=t/Math.sqrt(e),i=i>10?10:i,o=lt.alphaDecay??.1,a=lt.alpha??.6),{forcexy:r,forcez:i,alphaDecay:o,alpha:a}}startLayout(e=0,t=0,n=!1){let i=this.params.dimensions;if(this.getOptions){let w=this.getOptions();w&&this.applyConfig(w)}this.params.dimensions=i,this._gpuZZeroed=!1;let r=this.graph.layoutNodes||[],o=this.graph.layoutEdges||[];if(r.length===0)return;this.nodeIdToIndex.clear(),r.forEach((w,z)=>{this.nodeIdToIndex.set(w.id,z)});let a=this.params.dimensions??3;this.params.dimensions=a;let s=r.some(w=>Math.abs(w.position.z)>1e-6),l=Math.cbrt(r.length)*2,u=a>2&&!s&&!n,c=r.map((w,z)=>{let P=w.position.x,T=w.position.y,C=a<=2?0:w.position.z;if(u&&!w.pinned){let q=Math.random(),N=Math.random(),G=Math.random(),_=2*Math.PI*q,D=Math.acos(2*N-1),O=Math.cbrt(G)*l;P=O*Math.sin(D)*Math.cos(_),T=O*Math.sin(D)*Math.sin(_),C=O*Math.cos(D)}return{...w,index:z,x:P,y:T,z:C,vx:0,vy:0,vz:0,fx:w.pinned?w.position.x:null,fy:w.pinned?w.position.y:null,fz:w.pinned?w.position.z:null}}),d=o.filter(w=>{let z=this.nodeIdToIndex.get(w.sourceId),P=this.nodeIdToIndex.get(w.targetId);return z!==void 0&&P!==void 0}).map(w=>({source:w.sourceId,target:w.targetId}));this.simulation&&(this.simulation.stop(),this.simulation.dispose()),this.simulation=Er(c,a,this.renderer);let{forcexy:f,forcez:p,alphaDecay:g,alpha:m}=this.calculateForces(),y=this.params.charge??-.01,M=r.length,S=this.params.gravityX??1,h=this.params.gravityY??1,v=this.params.gravityZ??1,b=this.params.linkDistance??.5,x=this.params.linkStrength??1,E=f*this.params.gravityX,F=f*this.params.gravityY,R=p*this.params.gravityZ,A=jr(0).strength(E),I=Vr(0).strength(F);if(this.simulation.force("x",A),this.simulation.force("y",I),a>2){let w=Wr(0).strength(R);this.simulation.force("z",w)}if(this.simulation.force("center",Rr(0,0,0).strength(1)),a>2){let w=Xr();w.strength(y);let z=this.params.octreeTheta??.8,P=r.length,T=Math.max(.2,Math.min(1,1.2-.1*Math.log10(Math.max(P,1)))),C=z*T;w.theta(C);let q=this.params.octreeLevels;q!==void 0&&w.maxLevels(q),this.simulation.force("charge",w)}else{let w=Nr();w.strength(y);let z=this.params.quadtreeTheta??.9,P=Math.max(.5,Math.min(1,500/Math.sqrt(r.length))),T=z*P;w.theta(T),this.simulation.force("charge",w)}if(d.length>0){let w=Zr(d);w.distance(b),w.strength(x),w.id(z=>z.id),this.simulation.force("link",w)}(this.params.collision??.15)>0;let B=this.params.velocityDecay??lt.velocityDecay;this.simulation.alpha(m).alphaMin(.001).alphaDecay(g).velocityDecay(B),this.simulation.on("tick",()=>{this.onTick()}),this.simulation.on("end",()=>{this._isFinish=!0,this.graph.renderNeedsUpdate=!1}),this._isFinish=!1,this._enable=!0,this.graph.renderNeedsUpdate=!0,this.skipCPUPositionUpdate&&this.simulation.setSkipCPUReadback(!0),this.simulation.restart()}onTick(){if(!this._enable||!this.simulation)return;if(this.skipCPUPositionUpdate){(this.params.dimensions??3)<=2&&this.ensureGPUZeroZ(),this.graph.renderNeedsUpdate=!0;return}let e=performance.now();if(e-this.lastUpdateTime<this.updateIntervalMs)return;this.lastUpdateTime=e;let t=this.simulation.nodes(),n=this.params.dimensions??3;t.forEach(i=>{let r=this.nodeIdToIndex.get(i.id);if(r!==void 0&&r<this.graph.layoutNodes.length){let o=this.graph.layoutNodes[r];o&&!o.pinned&&i.fx==null&&(o.position.x=i.x??0,o.position.y=i.y??0,n>2?o.position.z=i.z??0:o.position.z=0,o.isPositionDirty=!0)}}),this.graph.renderNeedsUpdate=!0}ensureGPUZeroZ(){if(this._gpuZZeroed||!this.simulation)return;this._gpuZZeroed=!0,this.simulation.readBackPositions();let e=this.simulation.nodes(),t=[];e.forEach((i,r)=>{Math.abs(i.z??0)>1e-6&&t.push({index:r,x:i.x??0,y:i.y??0,z:0})}),t.length>0&&this.simulation.uploadNodePositions(t);let n=this.graph.layoutNodes;for(let i=0;i<n.length;i++)n[i].position.z=0}restartLayout(){if(!this.simulation||!this._enable)return;if(this.getOptions){let M=this.getOptions();M&&this.applyConfig(M)}let e=this.params.dimensions??3,{forcexy:t,forcez:n,alphaDecay:i,alpha:r}=this.calculateForces(),o=this.params.charge??-.01,a=this.params.linkDistance??.5,s=this.params.linkStrength??1,l=t*(this.params.gravityX??1),u=t*(this.params.gravityY??1),c=n*(this.params.gravityZ??1),d=this.simulation.force("x"),f=this.simulation.force("y"),p=this.simulation.force("z"),g=this.simulation.force("charge"),m=this.simulation.force("link");d&&d.strength(l),f&&f.strength(u),p&&e>2&&p.strength(c),g&&g.strength(o),m&&(m.distance(a),m.strength(s));let y=this.params.velocityDecay??.3;this.simulation.alpha(r).alphaDecay(i).velocityDecay(y).restart(),this._isFinish=!1,this.graph.renderNeedsUpdate=!0}stopLayout(){this.simulation&&this.simulation.stop(),this._isFinish=!0,this.graph.renderNeedsUpdate=!1}updateLayoutOption(e,t){if(e==="friction"?this.params.velocityDecay=t:this.params[e]=t,!this.simulation||!this._enable)return;let n=this.simulation.force("charge"),i=this.simulation.force("link"),r=this.simulation.force("x"),o=this.simulation.force("y"),a=this.simulation.force("z");switch(e){case"charge":n&&(n.strength(t),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)).restart());break;case"linkDistance":i&&(i.distance(t),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)).restart());break;case"linkStrength":i&&(i.strength(t),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)).restart());break;case"gravity":case"gravityX":case"gravityY":case"gravityZ":case"heightCompress":let{forcexy:s,forcez:l}=this.calculateForces(),u=s*(this.params.gravityX??1),c=s*(this.params.gravityY??1),d=l*(this.params.gravityZ??1);r&&r.strength(u),o&&o.strength(c),a&&a.strength(d),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)).restart();break;case"velocityDecay":case"friction":this.simulation.velocityDecay(this.params.velocityDecay??.3);break;case"alpha":case"alphaDecay":this.restartLayout();break;default:this.restartLayout();break}this.graph.renderNeedsUpdate=!0}pinNodes(e){if(!this.simulation)return;let t=this.simulation.nodes(),n=[];e.forEach(r=>{let o=this.nodeIdToIndex.get(r.id);if(o!==void 0){let a=this.graph.layoutNodes[o];a&&(a.pinned=!0);let s=t[o];s&&(s.fx=r.position.x,s.fy=r.position.y,s.fz=r.position.z,n.push({index:o,x:r.position.x,y:r.position.y,z:r.position.z}))}}),n.length>0&&this.simulation.uploadNodePositions(n);let i=n.map(r=>({index:r.index,isPinned:!0}));this.simulation.updatePinnedNodes(i),this._enable&&this.simulation.alpha()<.1&&this.simulation.alpha(.3).restart(),this.graph.renderNeedsUpdate=!0}unpinNodes(e){if(!this.simulation)return;let t=this.simulation.nodes(),n=[];for(let i of e){let r=this.nodeIdToIndex.get(i);if(r===void 0)continue;let o=this.graph.layoutNodes[r];o&&(o.pinned=!1);let a=t[r];a&&(a.fx=null,a.fy=null,a.fz=null),n.push({index:r,isPinned:!1})}n.length>0&&this.simulation.updatePinnedNodes(n),this._enable&&this.simulation.alpha()<.05&&this.simulation.alpha(.15).restart(),this.graph.renderNeedsUpdate=!0}set enable(e){this._enable=e,!e&&this.simulation&&this.simulation.stop(),this._isFinish=!e,this.graph.renderNeedsUpdate=e}get enable(){return this._enable}get isFinish(){return this._isFinish}setExpectedNodeCount(e){}clearExpectedNodeCount(){}updateGraph(e,t,n=!1){this.startLayout()}destroy(){this.cancelDimensionTransition(),this.simulation&&(this.simulation.stop(),this.simulation.dispose(),this.simulation=null)}transitionDimensions(e,t=600){(this.params.dimensions??3)!==e&&(e===2?this.transition3Dto2D(t):this.transition2Dto3D())}transition3Dto2D(e){this.readBackPositions(),this.params.dimensions=2,this.startLayout(0,0,!0)}transition2Dto3D(){this.readBackPositions(),this.params.dimensions=3,this.startLayout()}cancelDimensionTransition(){this._dimTransition=null}getDimensions(){return this.params.dimensions??3}debugNodePositions(){let e=this.simulation?this.simulation.nodes():[];if(this.simulation&&e.length>0)for(let n=0;n<Math.min(3,e.length);n++){let i=e[n]}let t=this.graph.layoutNodes||[];if(t.length>0){for(let n=0;n<Math.min(3,t.length);n++){let i=t[n]}if(this.simulation&&e.length>0)for(let n=0;n<Math.min(3,Math.min(e.length,t.length));n++){let i=e[n],r=t.find(o=>o.id===i.id);if(r){let o=Math.abs((i.x??0)-r.position.x)<.001&&Math.abs((i.y??0)-r.position.y)<.001&&Math.abs((i.z??0)-r.position.z)<.001}}}}getPositionTexture(){return this.simulation?this.simulation.getPositionTexture():null}getTextureSize(){return this.simulation?this.simulation.getTextureSize():0}getSpaceSize(){return this.simulation?this.simulation.getSpaceSize():10}debugGPUPositions(e=5){return this.simulation?this.simulation.debugPositions(e):null}setSkipCPUReadback(e){this.skipCPUPositionUpdate=e,this.simulation&&this.simulation.setSkipCPUReadback(e)}readBackPositions(){if(this.simulation){this.simulation.readBackPositions();let e=this.simulation.nodes(),t=this.params.dimensions??3;e.forEach(n=>{let i=this.nodeIdToIndex.get(n.id);if(i!==void 0&&i<this.graph.layoutNodes.length){let r=this.graph.layoutNodes[i];r&&(r.position.x=n.x??0,r.position.y=n.y??0,r.position.z=t>2?n.z??0:0)}})}}debugTick(){if(!this.simulation)return;this.simulation.nodes().length>0,this.simulation.tick(1),this.simulation.nodes().length>0,this.onTick()}debugZDistribution(){if(!this.simulation)return;let e=this.simulation.nodes();if(e.length===0)return;let t=1/0,n=-1/0,i=0,r=0,o=[];e.forEach(g=>{let m=g.z||0;t=Math.min(t,m),n=Math.max(n,m),i+=m,r++,o.push(m)});let a=i/r,s=n-t,l=0;o.forEach(g=>{l+=Math.pow(g-a,2)});let u=Math.sqrt(l/r),c=s*.1,d=o.filter(g=>Math.abs(g-t)<c).length,f=o.filter(g=>Math.abs(g-n)<c).length,p=(d+f)/r}},Dt=class{constructor(e){this.c=e,this.mode="gpu"}getPositionTexture(){return this.c.getPositionTexture()}getTextureSize(){return this.c.getTextureSize()}getSpaceSize(){return this.c.getSpaceSize()}tick(){}start(){this.c.startLayout()}stop(){this.c.stopLayout()}get graph(){return this.c.graph}get needsUpdate(){return!this.c.isFinish}clearNeedsUpdate(){}pinNodes(e){this.c.pinNodes(e)}unpinNodes(e){this.c.unpinNodes(e)}transitionDimensions(e,t){this.c.transitionDimensions(e,t)}getDimensions(){return this.c.getDimensions()}updateOption(e,t){this.c.updateLayoutOption(e,t)}};function Vn(e){let{backend:t="auto",renderer:n,config:i,graph:r,autoStart:o=!0}=e,a;t==="webgpu"?Pe()?a="webgpu":(console.warn('[createForceLayout] backend="webgpu" requested but navigator.gpu is unavailable; falling back to WebGL.'),a="webgl"):t==="webgl"?a="webgl":a=Pe()?"webgpu":"webgl";let s=r??{layoutNodes:[],layoutEdges:[],renderNeedsUpdate:!0};if(a==="webgpu"){let l=new ot(s);l.config(i);let u=new st(l);return o&&l.startLayout(),{controller:l,adapter:u,backend:"webgpu"}}else{let l=new It(s,n);l.config(i);let u=new Dt(l);return o&&l.startLayout(),{controller:l,adapter:u,backend:"webgl"}}}function Kr(e,t){let n=new Map(e.nodes.map(a=>[a.id,{...a}])),i=new Map(e.edges.map(a=>[a.id,{...a}]));for(let a of t.addNodes??[])n.set(a.id,a);for(let a of t.addEdges??[])i.set(a.id,a);for(let a of t.updateNodes??[]){let s=n.get(a.id);s&&n.set(a.id,{...s,...a.changes})}for(let a of t.updateEdges??[]){let s=i.get(a.id);s&&i.set(a.id,{...s,...a.changes})}for(let a of t.removeNodeIds??[])n.delete(a);for(let a of t.removeEdgeIds??[])i.delete(a);for(let a of t.positionPatches??[]){let s=n.get(a.id);s&&n.set(a.id,{...s,position:a.position})}for(let a of t.pinPatches??[]){let s=n.get(a.id);if(s){let l={...s,pinned:a.pinned};a.position&&(l.position=a.position),n.set(a.id,l)}}let r=Array.from(n.values()).map((a,s)=>({...a,index:s})),o=Array.from(i.values()).map((a,s)=>({...a,index:s}));return{...e,version:t.graphVersion,nodes:r,edges:o}}var Wn=class{constructor(e,t,n={}){this.mode="gpu",this._status="idle",this._snapshot=null,this._tickCount=0,this._listeners=new Map,this.id=e,this.controller=t,this._settings={dimensions:3,...n}}get status(){return this._status}getCapabilities(){return{mode:"gpu",supportsGpuTexture:!0,supportsCpuReadback:!1,supportsIncrementalDelta:!1,supportsPinning:!0,supportsDimensions:!0}}init(e,t){this._status!=="disposed"&&(this._snapshot=e,t&&(this._settings={...this._settings,...t}),this._feedSnapshotToController(e),this._status="idle")}applyDelta(e){if(!this._snapshot||this._status==="disposed")return;this._snapshot=Kr(this._snapshot,e);let t=this._status==="running";this._feedSnapshotToController(this._snapshot),t&&this._controllerStart()}tick(e){this._tickCount++,this.controller.tick&&this.controller.tick();let t=this._readNeedsUpdate(),n={tick:this._tickCount,didChangePositions:t,alpha:void 0};return this._emit("tick",n),n}start(){this._status!=="disposed"&&(this._controllerStart(),this._status="running",this._emit("started",{}))}stop(){this._status!=="disposed"&&(this._controllerStop(),this._status="stopped",this._emit("stopped",{}))}dispose(){this._controllerStop(),typeof this.controller.dispose=="function"?this.controller.dispose():typeof this.controller.destroy=="function"&&this.controller.destroy(),this._status="disposed",this._snapshot=null,this._listeners.clear()}getSettings(){return{...this._settings}}updateSettings(e){this._settings={...this._settings,...e}}setDimensions(e){this._settings={...this._settings,dimensions:e},typeof this.controller.transitionDimensions=="function"&&this.controller.transitionDimensions(e)}getReadback(){return{positions:null,texture:this.controller.getPositionTexture(),textureSize:this.controller.getTextureSize(),spaceSize:this.controller.getSpaceSize()}}getNodePosition(e){return null}setNodePosition(e,t){}pinNodes(e){this._status!=="disposed"&&typeof this.controller.pinNodes=="function"&&this.controller.pinNodes(e)}unpinNodes(e){this._status!=="disposed"&&typeof this.controller.unpinNodes=="function"&&this.controller.unpinNodes(e)}on(e,t){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t),()=>this._listeners.get(e)?.delete(t)}_feedSnapshotToController(e){this._settings={...this._settings,dimensions:e.dimensions},typeof this.controller.startLayout=="function"&&this.controller.startLayout()}_controllerStart(){typeof this.controller.startLayout=="function"?this.controller.startLayout():typeof this.controller.start=="function"&&this.controller.start()}_controllerStop(){typeof this.controller.stopLayout=="function"?this.controller.stopLayout():typeof this.controller.stop=="function"&&this.controller.stop()}_readNeedsUpdate(){return this.controller.needsUpdate!==void 0?!!this.controller.needsUpdate:this.controller.graph!==void 0?!!this.controller.graph.renderNeedsUpdate:!1}_emit(e,t){this._listeners.get(e)?.forEach(n=>n(t))}};
|
|
2328
|
+
//# sourceMappingURL=layout-gpu.js.map
|