@kineviz/gl 0.6.1 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1892 -2
- package/LICENSE +201 -0
- package/NOTICE +33 -0
- package/README.md +201 -143
- package/dist/chunk-3CR3GHJ2.mjs +2 -0
- 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 +5011 -445
- package/dist/index.d.ts +5011 -445
- package/dist/index.js +1604 -1425
- package/dist/index.mjs +1418 -2743
- package/dist/kineviz-gl.umd.js +4243 -1976
- 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,903 @@
|
|
|
1
|
+
import{a as Ie,b as Ne}from"./chunk-3CR3GHJ2.mjs";import{a as Me,c as be,d as Ee,e as ye,f as we,g as $e,h as pe,i as Be,j as Re,k as J,l as ke,m as Le,n as Ge,o as Ve,p as je,y as Ue,z as He}from"./chunk-EDTCHJCZ.mjs";import*as re from"three";import*as X from"three";import*as xe from"three";import*as A from"three";import*as I from"three";import*as Q from"three";import*as Te from"three";import*as ee from"three";import*as te from"three";import*as ne from"three";import*as Se from"three";import*as Xe from"three";var ce=`/**
|
|
2
|
+
* Simple vertex shader for full-screen quad rendering
|
|
3
|
+
* Used by all GPU compute passes
|
|
4
|
+
*/
|
|
5
|
+
varying vec2 vUv;
|
|
6
|
+
|
|
7
|
+
void main() {
|
|
8
|
+
vUv = uv;
|
|
9
|
+
gl_Position = vec4(position, 1.0);
|
|
10
|
+
}
|
|
11
|
+
`,Ye=`/**
|
|
12
|
+
* Position update shader
|
|
13
|
+
*
|
|
14
|
+
* Applies accumulated velocity to position, with:
|
|
15
|
+
* - Optional velocity decay (friction) - typically handled separately now
|
|
16
|
+
* - Velocity clamping to prevent explosion
|
|
17
|
+
* - Pinned node handling
|
|
18
|
+
*
|
|
19
|
+
* Same logic as d3-force:
|
|
20
|
+
* if (node.fx == null) node.x += node.vx
|
|
21
|
+
* else node.x = node.fx, node.vx = 0
|
|
22
|
+
*
|
|
23
|
+
* Note: Velocity decay is now applied in velocity-decay.frag.glsl before this shader
|
|
24
|
+
*/
|
|
25
|
+
precision highp float;
|
|
26
|
+
|
|
27
|
+
uniform sampler2D positionTexture;
|
|
28
|
+
uniform sampler2D velocityTexture;
|
|
29
|
+
uniform sampler2D pinnedTexture;
|
|
30
|
+
uniform float friction; // Set to 1.0 when decay is handled separately
|
|
31
|
+
uniform float spaceSize;
|
|
32
|
+
uniform float nDim;
|
|
33
|
+
|
|
34
|
+
varying vec2 vUv;
|
|
35
|
+
|
|
36
|
+
void main() {
|
|
37
|
+
vec4 pos = texture2D(positionTexture, vUv);
|
|
38
|
+
vec4 vel = texture2D(velocityTexture, vUv);
|
|
39
|
+
vec4 pinned = texture2D(pinnedTexture, vUv);
|
|
40
|
+
|
|
41
|
+
// If node is pinned, don't update position
|
|
42
|
+
if (pinned.r > 0.5) {
|
|
43
|
+
gl_FragColor = pos;
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Apply optional friction (usually 1.0 when decay is handled separately)
|
|
48
|
+
vec3 adjustedVel = vel.xyz * friction;
|
|
49
|
+
|
|
50
|
+
// Clamp velocity to prevent nodes from flying too far
|
|
51
|
+
// Max velocity is proportional to space size
|
|
52
|
+
float maxVel = spaceSize * 0.1;
|
|
53
|
+
float velMag = length(adjustedVel);
|
|
54
|
+
if (velMag > maxVel) {
|
|
55
|
+
adjustedVel = adjustedVel * (maxVel / velMag);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Update position
|
|
59
|
+
vec3 newPos = pos.xyz + adjustedVel;
|
|
60
|
+
|
|
61
|
+
// Mask z-component for 2D simulations
|
|
62
|
+
if (nDim < 3.0) {
|
|
63
|
+
newPos.z = 0.0;
|
|
64
|
+
}
|
|
65
|
+
if (nDim < 2.0) {
|
|
66
|
+
newPos.y = 0.0;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
gl_FragColor = vec4(newPos, pos.w);
|
|
70
|
+
}
|
|
71
|
+
`,Ze=`/**
|
|
72
|
+
* Clear shader - outputs zero for all fragments
|
|
73
|
+
* Used to reset velocity buffer at the start of each tick
|
|
74
|
+
*
|
|
75
|
+
* IMPORTANT: Alpha must be 1.0 for this to work with default blending.
|
|
76
|
+
* With alpha = 0, NormalBlending formula (src * srcAlpha + dst * (1-srcAlpha))
|
|
77
|
+
* would result in dst (no clearing).
|
|
78
|
+
*/
|
|
79
|
+
precision highp float;
|
|
80
|
+
|
|
81
|
+
void main() {
|
|
82
|
+
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
|
|
83
|
+
}
|
|
84
|
+
`,Je=`/**
|
|
85
|
+
* Copy shader - copies one texture to another
|
|
86
|
+
* Used for initializing FBOs with data textures
|
|
87
|
+
*/
|
|
88
|
+
precision highp float;
|
|
89
|
+
|
|
90
|
+
uniform sampler2D sourceTexture;
|
|
91
|
+
varying vec2 vUv;
|
|
92
|
+
|
|
93
|
+
void main() {
|
|
94
|
+
gl_FragColor = texture2D(sourceTexture, vUv);
|
|
95
|
+
}
|
|
96
|
+
`,Qe=`/**
|
|
97
|
+
* Velocity decay shader
|
|
98
|
+
*
|
|
99
|
+
* Applies velocity decay (friction) to existing velocity.
|
|
100
|
+
* This is the first step in each tick to decay the accumulated velocity
|
|
101
|
+
* before adding new forces.
|
|
102
|
+
*
|
|
103
|
+
* Same as d3-force: node.vx *= velocityDecay
|
|
104
|
+
*/
|
|
105
|
+
precision highp float;
|
|
106
|
+
|
|
107
|
+
uniform sampler2D velocityTexture;
|
|
108
|
+
uniform float decay; // velocityDecay factor (typically 0.6 = keep 60% of velocity, same as d3-force)
|
|
109
|
+
|
|
110
|
+
varying vec2 vUv;
|
|
111
|
+
|
|
112
|
+
void main() {
|
|
113
|
+
vec4 vel = texture2D(velocityTexture, vUv);
|
|
114
|
+
|
|
115
|
+
// Apply decay to velocity
|
|
116
|
+
vel.xyz *= decay;
|
|
117
|
+
|
|
118
|
+
gl_FragColor = vec4(vel.xyz, 1.0);
|
|
119
|
+
}
|
|
120
|
+
`,Ke=3;function et(t,o,i){let s=Math.min(Ke,Math.max(1,Math.round(o||3))),u,d=1,r=.001,e=1-Math.pow(r,1/300),g=0,f=.6,w=Be(),x=new Map,v=null,h=Ie("tick","end");t==null&&(t=[]);let p,M,y,U,D=!1,n=0,a=0,c=null,m=null,Z=0,_=null,B=null,H=0,P=null,k=null,S=null,C=null,l=null,z=null,R=null,T=null,F=1e3/10,$=0,G=!1;function j(){if(D)return;if(i)p=i;else{let b=document.createElement("canvas");b.style.display="none",p=new re.WebGLRenderer({canvas:b,alpha:!0,antialias:!1}),p.setSize(256,256)}M=new re.Scene,y=new re.OrthographicCamera(-1,1,1,-1,0,1);let E=pe();l=new re.ShaderMaterial({uniforms:{},vertexShader:ce,fragmentShader:Ze,blending:re.NoBlending,depthTest:!1,depthWrite:!1}),z=new re.ShaderMaterial({uniforms:{sourceTexture:{value:null}},vertexShader:ce,fragmentShader:Je,depthTest:!1,depthWrite:!1}),C=new re.ShaderMaterial({uniforms:{positionTexture:{value:null},velocityTexture:{value:null},pinnedTexture:{value:null},friction:{value:1},spaceSize:{value:10},nDim:{value:s}},vertexShader:ce,fragmentShader:Ye,depthTest:!1,depthWrite:!1}),R=new re.ShaderMaterial({uniforms:{velocityTexture:{value:null},decay:{value:f}},vertexShader:ce,fragmentShader:Qe,depthTest:!1,depthWrite:!1}),U=new re.Mesh(E,l),M.add(U),D=!0}function L(){if(D||j(),a=t.length,a===0)return;n=be(a);let E=Ee(a,s),b=p.getContext(),V=b.getParameter(b.MAX_TEXTURE_SIZE);c?.dispose(),m?.dispose(),_?.dispose(),B?.dispose(),P?.dispose(),k?.dispose(),S?.dispose(),c=ye(n),m=ye(n),_=ye(n),B=ye(n),P=ye(n),Z=0,H=0;let oe=Le(t,n),W=we(oe,n),he=Ge(t,n),de=we(he,n),ue=Ve(t,n);k=we(ue,n);let Y=n*n,ge=new Float32Array(Y*4);for(let fe=0;fe<Y;fe++)ge[fe*4]=(w()-.5)*2,ge[fe*4+1]=(w()-.5)*2,ge[fe*4+2]=(w()-.5)*2,ge[fe*4+3]=w();S=we(ge,n),z.uniforms.sourceTexture.value=W,U.material=z,p.setRenderTarget(c),p.render(M,y),p.setRenderTarget(m),p.render(M,y),z.uniforms.sourceTexture.value=de,p.setRenderTarget(_),p.render(M,y),p.setRenderTarget(B),p.render(M,y),U.material=l,p.setRenderTarget(P),p.render(M,y),p.setRenderTarget(null),W.dispose(),de.dispose(),C.uniforms.spaceSize.value=E;let Ce={renderer:p,scene:M,camera:y,textureSize:n,nodeCount:a};x.forEach(fe=>{if(fe.initGPU)try{fe.initGPU(Ce)}catch{}})}function O(){return Z===0?c:m}function ie(){return Z===0?m:c}function ae(){Z=1-Z}function ze(){return H===0?_:B}function me(){return H===0?B:_}function q(){H=1-H}function se(){N(),h.call("tick",u),d<r&&(v?.stop(),h.call("end",u))}function N(E){E===void 0&&(E=1);for(let b=0;b<E;b++)d+=(g-d)*e,D&&a>0?ve():Pe();return u}let le=0,K=0;function ve(){le++;let E=performance.now();(le%50===0||E-K>2e3)&&(K=E);let b=ie(),V=O(),oe=me(),W=ze(),he=Ee(a,s);for(let[,Y]of x)if(typeof Y.getSpaceSize=="function"){he=Y.getSpaceSize();break}let de=he;z.uniforms.sourceTexture.value=oe.texture,U.material=z,p.setRenderTarget(P),p.render(M,y),x.forEach(Y=>{try{Y.apply(d,b.texture,P)}catch{}}),R.uniforms.velocityTexture.value=P.texture,R.uniforms.decay.value=f,U.material=R,p.setRenderTarget(W),p.render(M,y),C.uniforms.positionTexture.value=b.texture,C.uniforms.velocityTexture.value=W.texture,C.uniforms.pinnedTexture.value=k,C.uniforms.friction.value=1,C.uniforms.spaceSize.value=de,U.material=C,p.setRenderTarget(V),p.render(M,y),p.setRenderTarget(null);let ue=x.get("center");if(ue&&ue.applyToPosition&&(ue.applyToPosition(V.texture,b,d),z.uniforms.sourceTexture.value=b.texture,U.material=z,p.setRenderTarget(V),p.render(M,y),p.setRenderTarget(null)),ae(),q(),!G){let Y=performance.now();Y-$>=F&&($=Y,Ae())}}function Pe(){x.forEach(E=>{E.apply(d)});for(let E=0;E<t.length;E++){let b=t[E];b.fx==null?b.x+=b.vx*=f:(b.x=b.fx,b.vx=0),s>1&&(b.fy==null?b.y+=b.vy*=f:(b.y=b.fy,b.vy=0)),s>2&&(b.fz==null?b.z+=b.vz*=f:(b.z=b.fz,b.vz=0))}}let We=0;function Ae(){if(!D||a===0)return;let E=ie(),b=new Float32Array(n*n*4);try{p.readRenderTargetPixels(E,0,0,n,n,b),je(t,b,s),We++}catch{}}function Fe(E){return E.initialize(t,w,s),D&&E.initGPU&&E.initGPU({renderer:p,scene:M,camera:y,textureSize:n,nodeCount:a}),E}return ke(t,s,w),u={tick:function(E){return N(E),this},restart:function(){return t.length>0&&!D&&(j(),L()),v?v.restart(se):v=Ne(se),this},stop:function(){return v?.stop(),this},numDimensions:function(E){return arguments.length===0?s:this},nodes:function(E){return arguments.length===0?t:(t=E,ke(t,s,w),L(),x.forEach(Fe),this)},alpha:function(E){return arguments.length===0?d:(d=+E,this)},alphaMin:function(E){return arguments.length===0?r:(r=+E,this)},alphaDecay:function(E){return arguments.length===0?e:(e=+E,this)},alphaTarget:function(E){return arguments.length===0?g:(g=+E,this)},velocityDecay:function(E){return arguments.length===0?1-f:(f=1-E,R&&(R.uniforms.decay.value=f),this)},randomSource:function(E){return arguments.length===0?w:(w=E,x.forEach(Fe),this)},force:function(E,b){if(arguments.length===1)return x.get(E);if(b==null){let V=x.get(E);V?.dispose&&V.dispose(),x.delete(E)}else{let V=Fe(b);if(x.set(E,V),D&&V.initGPU&&a>0&&n>0)try{V.initGPU({renderer:p,scene:M,camera:y,textureSize:n,nodeCount:a})}catch{}}return this},find:function(E,b,V,oe){b=b??0,V=V??0,oe=oe??1/0;let W,he=oe*oe;for(let de=0;de<t.length;de++){let ue=t[de],Y=E-(ue.x||0),ge=b-(ue.y||0),Ce=V-(ue.z||0),fe=Y*Y+ge*ge+Ce*Ce;fe<he&&(W=ue,he=fe)}return W},on:function(E,b){return arguments.length===1?h.on(E):(h.on(E,b),this)},getPositionTexture:function(){if(!D||a===0)return null;let E=ie();return!E||!E.texture?null:E.texture},getTextureSize:function(){return n},getSpaceSize:function(){if(!D||a===0)return 10;for(let[,E]of x)if(typeof E.getSpaceSize=="function")return E.getSpaceSize();return Ee(a,s)},setSkipCPUReadback:function(E){G=E},getSkipCPUReadback:function(){return G},readBackPositions:function(){Ae()},uploadNodePositions:function(E){if(!D||a===0||E.length===0)return;let b=ie();if(!b)return;let V=new Float32Array(n*n*4);try{p.readRenderTargetPixels(b,0,0,n,n,V)}catch{return}for(let{index:W,x:he,y:de,z:ue}of E)if(W>=0&&W<a){let Y=W*4;V[Y]=he,V[Y+1]=de,V[Y+2]=ue}let oe=we(V,n);z.uniforms.sourceTexture.value=oe,U.material=z,p.setRenderTarget(b),p.render(M,y),p.setRenderTarget(null),oe.dispose()},updatePinnedNodes:function(E){if(!k||!D||a===0||E.length===0)return;let b=k.image.data;for(let{index:V,isPinned:oe}of E)V>=0&&V<a&&(b[V*4]=oe?1:0);k.needsUpdate=!0},debugPositions:function(E=5){if(!D||a===0)return null;let b=ie(),V=new Float32Array(n*n*4);try{p.readRenderTargetPixels(b,0,0,n,n,V);let oe=[];for(let W=0;W<Math.min(E,a);W++){let he=V[W*4],de=V[W*4+1],ue=V[W*4+2],Y=V[W*4+3];oe.push({x:he,y:de,z:ue,w:Y})}return oe}catch{return null}},dispose:function(){v?.stop(),x.forEach(E=>{E.dispose&&E.dispose()}),x.clear(),c?.dispose(),m?.dispose(),_?.dispose(),B?.dispose(),P?.dispose(),k?.dispose(),S?.dispose(),C?.dispose(),l?.dispose(),z?.dispose(),R?.dispose(),U&&(U.geometry.dispose(),M?.remove(U)),!i&&p&&p.dispose()}},j(),t.length>0&&L(),u}var tt=`/**
|
|
121
|
+
* Center force shader
|
|
122
|
+
*
|
|
123
|
+
* Implements d3-force's forceCenter behavior:
|
|
124
|
+
* Calculates the center of mass of all nodes and applies
|
|
125
|
+
* a uniform translation to shift everything toward the target center.
|
|
126
|
+
*
|
|
127
|
+
* This is NOT a per-node attractive force - it's a global translation
|
|
128
|
+
* that maintains relative positions while centering the graph.
|
|
129
|
+
*
|
|
130
|
+
* Reference: d3-force-3d/src/center.js
|
|
131
|
+
*/
|
|
132
|
+
precision highp float;
|
|
133
|
+
|
|
134
|
+
uniform sampler2D positionTexture;
|
|
135
|
+
uniform sampler2D centermassTexture; // Pre-computed center of mass
|
|
136
|
+
uniform float centerX;
|
|
137
|
+
uniform float centerY;
|
|
138
|
+
uniform float centerZ;
|
|
139
|
+
uniform float strength;
|
|
140
|
+
uniform float textureSize;
|
|
141
|
+
uniform float nodeCount;
|
|
142
|
+
uniform float nDim;
|
|
143
|
+
|
|
144
|
+
varying vec2 vUv;
|
|
145
|
+
|
|
146
|
+
void main() {
|
|
147
|
+
// Read pre-computed center of mass
|
|
148
|
+
vec4 centermass = texture2D(centermassTexture, vec2(0.5, 0.5));
|
|
149
|
+
|
|
150
|
+
// Calculate node index
|
|
151
|
+
float x = floor(vUv.x * textureSize);
|
|
152
|
+
float y = floor(vUv.y * textureSize);
|
|
153
|
+
float nodeIndex = y * textureSize + x;
|
|
154
|
+
|
|
155
|
+
// Output zero for invalid indices
|
|
156
|
+
if (nodeIndex >= nodeCount) {
|
|
157
|
+
gl_FragColor = vec4(0.0);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Target center (default: origin)
|
|
162
|
+
vec3 target = vec3(centerX, centerY, centerZ);
|
|
163
|
+
|
|
164
|
+
// Calculate the shift needed (same for all nodes)
|
|
165
|
+
// centermass.rgb contains sum of all positions
|
|
166
|
+
// centermass.a contains node count
|
|
167
|
+
vec3 currentCenter = centermass.rgb / max(centermass.a, 1.0);
|
|
168
|
+
vec3 shift = (target - currentCenter) * strength;
|
|
169
|
+
|
|
170
|
+
// Mask for dimensions
|
|
171
|
+
if (nDim < 3.0) shift.z = 0.0;
|
|
172
|
+
if (nDim < 2.0) shift.y = 0.0;
|
|
173
|
+
|
|
174
|
+
// Output velocity delta (will be added to all nodes uniformly)
|
|
175
|
+
// Note: alpha must be 1.0 for THREE.AdditiveBlending to work (uses SrcAlphaFactor)
|
|
176
|
+
gl_FragColor = vec4(shift, 1.0);
|
|
177
|
+
}
|
|
178
|
+
`,nt=`/**
|
|
179
|
+
* Center force position shader
|
|
180
|
+
*
|
|
181
|
+
* Implements d3-force's forceCenter behavior correctly:
|
|
182
|
+
* Directly modifies node positions (not velocities) to center the graph.
|
|
183
|
+
*
|
|
184
|
+
* d3-force center: node.x -= shift (direct position modification)
|
|
185
|
+
* Unlike other forces which modify velocity: node.vx += force
|
|
186
|
+
*
|
|
187
|
+
* Reference: d3-force-3d/src/center.js
|
|
188
|
+
*/
|
|
189
|
+
precision highp float;
|
|
190
|
+
|
|
191
|
+
uniform sampler2D positionTexture;
|
|
192
|
+
uniform sampler2D centermassTexture; // Pre-computed center of mass
|
|
193
|
+
uniform float centerX;
|
|
194
|
+
uniform float centerY;
|
|
195
|
+
uniform float centerZ;
|
|
196
|
+
uniform float strength;
|
|
197
|
+
uniform float alpha; // Alpha scaling for center force (matches d3-force)
|
|
198
|
+
uniform float textureSize;
|
|
199
|
+
uniform float nodeCount;
|
|
200
|
+
uniform float nDim;
|
|
201
|
+
|
|
202
|
+
varying vec2 vUv;
|
|
203
|
+
|
|
204
|
+
void main() {
|
|
205
|
+
// Read pre-computed center of mass
|
|
206
|
+
vec4 centermass = texture2D(centermassTexture, vec2(0.5, 0.5));
|
|
207
|
+
|
|
208
|
+
// Calculate node index
|
|
209
|
+
float x = floor(vUv.x * textureSize);
|
|
210
|
+
float y = floor(vUv.y * textureSize);
|
|
211
|
+
float nodeIndex = y * textureSize + x;
|
|
212
|
+
|
|
213
|
+
// Read current position
|
|
214
|
+
vec2 texCoord = (vec2(x, y) + 0.5) / textureSize;
|
|
215
|
+
vec4 pos = texture2D(positionTexture, texCoord);
|
|
216
|
+
|
|
217
|
+
// Output unchanged position for invalid indices
|
|
218
|
+
if (nodeIndex >= nodeCount) {
|
|
219
|
+
gl_FragColor = pos;
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Target center (default: origin)
|
|
224
|
+
vec3 target = vec3(centerX, centerY, centerZ);
|
|
225
|
+
|
|
226
|
+
// Calculate the shift needed (same for all nodes)
|
|
227
|
+
// centermass.rgb contains sum of all positions
|
|
228
|
+
// centermass.a contains node count
|
|
229
|
+
vec3 currentCenter = centermass.rgb / max(centermass.a, 1.0);
|
|
230
|
+
vec3 shift = (currentCenter - target) * strength * alpha; // Apply alpha scaling like d3-force
|
|
231
|
+
|
|
232
|
+
// Mask for dimensions
|
|
233
|
+
if (nDim < 3.0) shift.z = 0.0;
|
|
234
|
+
if (nDim < 2.0) shift.y = 0.0;
|
|
235
|
+
|
|
236
|
+
// Apply shift directly to position (same as d3-force: node.x -= shift)
|
|
237
|
+
vec3 newPos = pos.xyz - shift;
|
|
238
|
+
|
|
239
|
+
gl_FragColor = vec4(newPos, pos.w);
|
|
240
|
+
}
|
|
241
|
+
`,it=`/**
|
|
242
|
+
* Center of mass calculation - vertex shader
|
|
243
|
+
*
|
|
244
|
+
* Renders each node as a point to a 1x1 texture.
|
|
245
|
+
* Combined with additive blending, this sums all positions.
|
|
246
|
+
*
|
|
247
|
+
* All valid nodes render to the same pixel, accumulating position sums.
|
|
248
|
+
*/
|
|
249
|
+
precision highp float;
|
|
250
|
+
|
|
251
|
+
attribute vec2 pointIndex; // (x, y) in texture space
|
|
252
|
+
|
|
253
|
+
uniform sampler2D positionTexture;
|
|
254
|
+
uniform float textureSize;
|
|
255
|
+
uniform float nodeCount;
|
|
256
|
+
|
|
257
|
+
varying vec2 vPointIndex;
|
|
258
|
+
|
|
259
|
+
void main() {
|
|
260
|
+
vPointIndex = pointIndex;
|
|
261
|
+
|
|
262
|
+
float index = pointIndex.y * textureSize + pointIndex.x;
|
|
263
|
+
|
|
264
|
+
// Skip if beyond node count - render off-screen
|
|
265
|
+
if (index >= nodeCount) {
|
|
266
|
+
gl_Position = vec4(10.0, 10.0, 0.0, 1.0); // Way off-screen in NDC
|
|
267
|
+
gl_PointSize = 0.0;
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// All valid points render to the center of the 1x1 texture
|
|
272
|
+
// NDC (0, 0) maps to the center of the viewport
|
|
273
|
+
// For a 1x1 FBO, this covers the single pixel
|
|
274
|
+
gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
|
|
275
|
+
|
|
276
|
+
// Use gl_PointSize = 1.0 to ensure exactly one fragment per point
|
|
277
|
+
// Multiple points at the same location with additive blending will sum up
|
|
278
|
+
gl_PointSize = 1.0;
|
|
279
|
+
}
|
|
280
|
+
`,ot=`/**
|
|
281
|
+
* Center of mass calculation - fragment shader
|
|
282
|
+
*
|
|
283
|
+
* Outputs position.xyz as RGB and 1.0 as A (for counting).
|
|
284
|
+
* With additive blending, this sums all positions and counts nodes.
|
|
285
|
+
*/
|
|
286
|
+
precision highp float;
|
|
287
|
+
|
|
288
|
+
uniform sampler2D positionTexture;
|
|
289
|
+
uniform float textureSize;
|
|
290
|
+
|
|
291
|
+
varying vec2 vPointIndex;
|
|
292
|
+
|
|
293
|
+
void main() {
|
|
294
|
+
// Sample position from texture
|
|
295
|
+
vec2 uv = (vPointIndex + 0.5) / textureSize;
|
|
296
|
+
vec4 pos = texture2D(positionTexture, uv);
|
|
297
|
+
|
|
298
|
+
// Output position (xyz) and count (1.0)
|
|
299
|
+
gl_FragColor = vec4(pos.xyz, 1.0);
|
|
300
|
+
}
|
|
301
|
+
`;function rt(t,o,i){let s=[],u=2,d=t??0,r=o??0,e=i??0,g=1,f=null,w=null,x=null,v=null,h=0,p=0,M=null,y=null,U=null,D=null,n=null,a=null,c=null,m=null,Z=null,_=null,B=null,H=null;function P(l,z,R){if(!f||!z||!R||p===0){k(l);return}}function k(l){let z=0,R=0,T=0,F=s.length;for(let L=0;L<F;L++){let O=s[L];z+=O.x||0,R+=O.y||0,T+=O.z||0}let $=(z/F-d)*g,G=(R/F-r)*g,j=(T/F-e)*g;for(let L=0;L<F;L++){let O=s[L];$&&(O.x-=$),u>1&&G&&(O.y-=G),u>2&&j&&(O.z-=j)}}function S(l,z,R){}function C(l,z,R=1){if(!f||!y||!U||!_||!H||!v){console.warn("[GPU ForceCenter] applyToPosition: missing resources");return}M.remove(U);let T=new X.Mesh(pe(),a);if(M.add(T),f.setRenderTarget(y),f.render(M,v),M.remove(T),T.geometry.dispose(),M.add(U),n.uniforms.positionTexture.value=l,n.uniforms.textureSize.value=h,n.uniforms.nodeCount.value=p,f.setRenderTarget(y),f.render(M,v),Math.random()<.02){let F=new Float32Array(4);f.readRenderTargetPixels(y,0,0,1,1,F);let $=F[0],G=F[1],j=F[2],L=F[3],O=L>0?$/L:0,ie=L>0?G/L:0,ae=L>0?j/L:0;console.log(`[GPU ForceCenter] Centermass: sum=(${$.toFixed(2)}, ${G.toFixed(2)}, ${j.toFixed(2)}), count=${L}, avg=(${O.toFixed(4)}, ${ie.toFixed(4)}, ${ae.toFixed(4)})`)}H.uniforms.positionTexture.value=l,H.uniforms.centermassTexture.value=y.texture,H.uniforms.centerX.value=d,H.uniforms.centerY.value=r,H.uniforms.centerZ.value=e,H.uniforms.strength.value=g,H.uniforms.alpha.value=R,H.uniforms.textureSize.value=h,H.uniforms.nodeCount.value=p,H.uniforms.nDim.value=u,f.setRenderTarget(z),f.render(_,x),f.setRenderTarget(null)}return P.initialize=function(l,z,R){s=l,u=R},P.initGPU=function(l){f=l.renderer,x=l.camera,h=l.textureSize,p=l.nodeCount,v=new X.OrthographicCamera(-1,1,1,-1,0,1),M=new X.Scene,y=ye(1);let z=$e(h);D=new X.BufferGeometry,D.setAttribute("pointIndex",new X.BufferAttribute(z,2));let R=h*h,T=new Float32Array(R*3);D.setAttribute("position",new X.BufferAttribute(T,3)),n=new X.ShaderMaterial({uniforms:{positionTexture:{value:null},textureSize:{value:h},nodeCount:{value:p}},vertexShader:it,fragmentShader:ot,blending:X.AdditiveBlending,depthTest:!1,depthWrite:!1}),U=new X.Points(D,n),M.add(U),console.log(`[GPU ForceCenter] Initialized centermass: ${z.length/2} points, textureSize=${h}, nodeCount=${p}`),console.log(`[GPU ForceCenter] Initialized centermass calculation: ${z.length/2} points, textureSize=${h}, nodeCount=${p}`),a=new X.ShaderMaterial({uniforms:{},vertexShader:ce,fragmentShader:Ze,blending:X.NoBlending,depthTest:!1,depthWrite:!1}),c=new X.Scene,Z=new X.ShaderMaterial({uniforms:{positionTexture:{value:null},centermassTexture:{value:null},centerX:{value:d},centerY:{value:r},centerZ:{value:e},strength:{value:g},textureSize:{value:h},nodeCount:{value:p},nDim:{value:u}},vertexShader:ce,fragmentShader:tt,blending:X.AdditiveBlending,depthTest:!1,depthWrite:!1}),m=new X.Mesh(pe(),Z),c.add(m),_=new X.Scene,H=new X.ShaderMaterial({uniforms:{positionTexture:{value:null},centermassTexture:{value:null},centerX:{value:d},centerY:{value:r},centerZ:{value:e},strength:{value:g},alpha:{value:1},textureSize:{value:h},nodeCount:{value:p},nDim:{value:u}},vertexShader:ce,fragmentShader:nt,blending:X.NoBlending,depthTest:!1,depthWrite:!1}),B=new X.Mesh(pe(),H),_.add(B)},P.dispose=function(){y?.dispose(),D?.dispose(),n?.dispose(),a?.dispose(),Z?.dispose(),H?.dispose(),m&&m.geometry.dispose(),B&&B.geometry.dispose()},P.apply=P,P.applyToPosition=C,P.x=function(l){return arguments.length===0?d:(d=+l,P)},P.y=function(l){return arguments.length===0?r:(r=+l,P)},P.z=function(l){return arguments.length===0?e:(e=+l,P)},P.strength=function(l){return arguments.length===0?g:(g=+l,P)},P}var at=`/**
|
|
302
|
+
* Quadtree build vertex shader
|
|
303
|
+
*
|
|
304
|
+
* Accumulates node positions into quadtree cells using point rendering.
|
|
305
|
+
* Each node is rendered as a point to its cell, with additive blending
|
|
306
|
+
* to sum up positions and count.
|
|
307
|
+
*
|
|
308
|
+
* CRITICAL: Match original cosmograph exactly - use positions directly without conversion!
|
|
309
|
+
* Original cosmograph: vec4 pointPosition = texture2D(positionsTexture, pointIndices / pointsTextureSize);
|
|
310
|
+
* Original cosmograph: rgba = vec4(pointPosition.rg, 1.0, 0.0);
|
|
311
|
+
* Original cosmograph: float n = floor(pointPosition.x / cellSize);
|
|
312
|
+
*
|
|
313
|
+
* This means original cosmograph uses positions directly, assuming they're in [0, spaceSize] range
|
|
314
|
+
* or handles negative positions correctly.
|
|
315
|
+
*
|
|
316
|
+
* Output via varying: (x, y, 1.0, 1.0)
|
|
317
|
+
* After additive blending: (x_sum, y_sum, count, count)
|
|
318
|
+
* Center of mass = (x_sum/count, y_sum/count)
|
|
319
|
+
*/
|
|
320
|
+
precision highp float;
|
|
321
|
+
|
|
322
|
+
uniform sampler2D positionTexture;
|
|
323
|
+
uniform float pointsTextureSize;
|
|
324
|
+
uniform float levelTextureSize;
|
|
325
|
+
uniform float cellSize;
|
|
326
|
+
uniform float spaceSize;
|
|
327
|
+
|
|
328
|
+
attribute vec2 pointIndex; // (x, y) index into position texture
|
|
329
|
+
|
|
330
|
+
varying vec4 vData;
|
|
331
|
+
|
|
332
|
+
void main() {
|
|
333
|
+
// Get node position from texture
|
|
334
|
+
vec2 uv = (pointIndex + 0.5) / pointsTextureSize;
|
|
335
|
+
vec4 pos = texture2D(positionTexture, uv);
|
|
336
|
+
|
|
337
|
+
// Convert position to [0, spaceSize] range for consistent coordinate system
|
|
338
|
+
// Positions may be in [-spaceSize/2, spaceSize/2] range (d3-force convention)
|
|
339
|
+
// Convert to [0, spaceSize] to match cosmograph coordinate system
|
|
340
|
+
float x = pos.x + spaceSize * 0.5;
|
|
341
|
+
float y = pos.y + spaceSize * 0.5;
|
|
342
|
+
|
|
343
|
+
// Store CONVERTED coordinates for center of mass calculation
|
|
344
|
+
// This ensures centermass calculation uses same coordinate system as force shader
|
|
345
|
+
// IMPORTANT: alpha must be 1.0 for THREE.AdditiveBlending to work correctly!
|
|
346
|
+
vData = vec4(x, y, 1.0, 1.0);
|
|
347
|
+
|
|
348
|
+
// Cell index (positions already in [0, spaceSize] range)
|
|
349
|
+
float n = floor(x / cellSize);
|
|
350
|
+
float m = floor(y / cellSize);
|
|
351
|
+
|
|
352
|
+
// Clamp to valid range
|
|
353
|
+
n = clamp(n, 0.0, levelTextureSize - 1.0);
|
|
354
|
+
m = clamp(m, 0.0, levelTextureSize - 1.0);
|
|
355
|
+
|
|
356
|
+
// Convert to clip space [-1, 1]
|
|
357
|
+
vec2 levelPosition = 2.0 * (vec2(n, m) + 0.5) / levelTextureSize - 1.0;
|
|
358
|
+
|
|
359
|
+
gl_Position = vec4(levelPosition, 0.0, 1.0);
|
|
360
|
+
gl_PointSize = 1.0;
|
|
361
|
+
}
|
|
362
|
+
`,st=`/**
|
|
363
|
+
* Quadtree build fragment shader
|
|
364
|
+
*
|
|
365
|
+
* Simply passes through the accumulated data.
|
|
366
|
+
* Additive blending handles the summation.
|
|
367
|
+
*/
|
|
368
|
+
precision highp float;
|
|
369
|
+
|
|
370
|
+
varying vec4 vData;
|
|
371
|
+
|
|
372
|
+
void main() {
|
|
373
|
+
gl_FragColor = vData;
|
|
374
|
+
}
|
|
375
|
+
`;function lt(t,o){t=Math.min(t,o);let i=o-t,s=`
|
|
376
|
+
// Match d3-force manyBody.js line 84: skip if beyond distanceMax
|
|
377
|
+
if (l >= distanceMax2) {
|
|
378
|
+
// Skip this cell (too far)
|
|
379
|
+
} else {
|
|
380
|
+
// Use strength directly (no abs) to match d3-force behavior
|
|
381
|
+
// strength < 0: repulsion, strength > 0: attraction
|
|
382
|
+
// Match d3-force manyBody.js line 89: node.vx += x * treeNode.value * alpha / l
|
|
383
|
+
float c = alpha * strength * centermass.b;
|
|
384
|
+
addVelocity += calculateAdditionalVelocity(vec2(x, y), l, c, random.rg);
|
|
385
|
+
}
|
|
386
|
+
`;function u(e){if(e>=o)return s;{let g=Math.pow(2,e+1),f=new Array(e+1-i).fill(0).map((x,v)=>`pow(2.0, ${e-(v+i)}.0) * i${v+i}`).join("+"),w=new Array(e+1-i).fill(0).map((x,v)=>`pow(2.0, ${e-(v+i)}.0) * j${v+i}`).join("+");return`
|
|
387
|
+
for (float ij${e} = 0.0; ij${e} < 4.0; ij${e} += 1.0) {
|
|
388
|
+
float i${e} = 0.0;
|
|
389
|
+
float j${e} = 0.0;
|
|
390
|
+
if (ij${e} == 1.0 || ij${e} == 3.0) i${e} = 1.0;
|
|
391
|
+
if (ij${e} == 2.0 || ij${e} == 3.0) j${e} = 1.0;
|
|
392
|
+
float i = pow(2.0, ${t}.0) * n / width${e+1} + ${f};
|
|
393
|
+
float j = pow(2.0, ${t}.0) * m / width${e+1} + ${w};
|
|
394
|
+
float groupPosX = (i + 0.5) / ${g}.0;
|
|
395
|
+
float groupPosY = (j + 0.5) / ${g}.0;
|
|
396
|
+
|
|
397
|
+
vec4 centermass = texture2D(level${e}, vec2(groupPosX, groupPosY));
|
|
398
|
+
// Match d3-force: only check if cell has nodes (count > 0)
|
|
399
|
+
// d3-force manyBody.js line 72: if (!treeNode.value) return true;
|
|
400
|
+
// CRITICAL: Do NOT check x_sum or y_sum, they can be negative or zero!
|
|
401
|
+
if (centermass.b > 0.0) {
|
|
402
|
+
float x = centermass.r / centermass.b - pointPosition.r;
|
|
403
|
+
float y = centermass.g / centermass.b - pointPosition.g;
|
|
404
|
+
float l = x * x + y * y;
|
|
405
|
+
// Match d3-force Barnes-Hut criterion exactly: w^2 / theta^2 < l
|
|
406
|
+
// d3-force: if (w * w / theta2 < l) where theta2 = theta^2
|
|
407
|
+
// This is equivalent to: w^2 < l * theta^2
|
|
408
|
+
float theta2 = theta * theta;
|
|
409
|
+
if ((width${e+1} * width${e+1}) / theta2 < l) {
|
|
410
|
+
${s}
|
|
411
|
+
} else {
|
|
412
|
+
${u(e+1)}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
`}}let d=new Array(o).fill(0).map((e,g)=>`uniform sampler2D level${g};`).join(`
|
|
417
|
+
`),r=new Array(o).fill(0).map((e,g)=>`float width${g+1} = width${g} / 2.0;`).join(`
|
|
418
|
+
`);return`
|
|
419
|
+
precision highp float;
|
|
420
|
+
|
|
421
|
+
uniform sampler2D positionsTexture;
|
|
422
|
+
uniform sampler2D randomValues;
|
|
423
|
+
uniform float spaceSize;
|
|
424
|
+
uniform float strength;
|
|
425
|
+
uniform float theta;
|
|
426
|
+
uniform float alpha;
|
|
427
|
+
uniform float distanceMin; // Match d3-force: minimum distance (default: 1)
|
|
428
|
+
uniform float distanceMax; // Match d3-force: maximum distance (default: Infinity)
|
|
429
|
+
${d}
|
|
430
|
+
varying vec2 vUv;
|
|
431
|
+
|
|
432
|
+
// Pre-computed squared distances for efficiency
|
|
433
|
+
float distanceMin2;
|
|
434
|
+
float distanceMax2;
|
|
435
|
+
|
|
436
|
+
// Jiggle function: match d3-force jiggle.js exactly
|
|
437
|
+
// Returns (random - 0.5) * 1e-6
|
|
438
|
+
// This adds a tiny random displacement to break symmetry when nodes align
|
|
439
|
+
float jiggle(float randomVal) {
|
|
440
|
+
return (randomVal - 0.5) * 1e-6;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// Calculate velocity with proper jiggle handling - match d3-force manyBody.js exactly
|
|
444
|
+
vec2 calculateAdditionalVelocity(vec2 xy, float l, float c, vec2 randomVec) {
|
|
445
|
+
// Match d3-force exactly:
|
|
446
|
+
// - xy = centermass - pointPosition (vector from point to centermass)
|
|
447
|
+
// - c = alpha * strength * count (strength can be negative or positive)
|
|
448
|
+
// - add = c / l (can be negative or positive)
|
|
449
|
+
// - return add * xy (direction depends on sign of c)
|
|
450
|
+
// - c < 0: repulsion (points away from centermass)
|
|
451
|
+
// - c > 0: attraction (points toward centermass)
|
|
452
|
+
|
|
453
|
+
// Match d3-force manyBody.js line 85-87 and 101-103: jiggle when component is 0
|
|
454
|
+
// CRITICAL: This breaks symmetry when nodes are aligned on an axis!
|
|
455
|
+
// if (x === 0) x = jiggle(random), l += x * x;
|
|
456
|
+
// if (y === 0) y = jiggle(random), l += y * y;
|
|
457
|
+
if (xy.x == 0.0) {
|
|
458
|
+
xy.x = jiggle(randomVec.x);
|
|
459
|
+
l += xy.x * xy.x;
|
|
460
|
+
}
|
|
461
|
+
if (xy.y == 0.0) {
|
|
462
|
+
xy.y = jiggle(randomVec.y);
|
|
463
|
+
l += xy.y * xy.y;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// Match d3-force manyBody.js line 88 and 104:
|
|
467
|
+
// if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
|
|
468
|
+
if (l < distanceMin2) l = sqrt(distanceMin2 * l);
|
|
469
|
+
|
|
470
|
+
float add = c / l;
|
|
471
|
+
return add * xy;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
void main() {
|
|
475
|
+
// Read position and convert to [0, spaceSize] range to match quadtree coordinate system
|
|
476
|
+
// Quadtree build shader stores positions in [0, spaceSize] range, so we must match here
|
|
477
|
+
vec4 originalPosition = texture2D(positionsTexture, vUv);
|
|
478
|
+
vec4 random = texture2D(randomValues, vUv);
|
|
479
|
+
|
|
480
|
+
// Pre-compute squared distances (match d3-force manyBody.js)
|
|
481
|
+
distanceMin2 = distanceMin * distanceMin;
|
|
482
|
+
distanceMax2 = distanceMax * distanceMax;
|
|
483
|
+
|
|
484
|
+
// Convert position to [0, spaceSize] range (same as quadtree build shader)
|
|
485
|
+
vec4 pointPosition = vec4(
|
|
486
|
+
originalPosition.x + spaceSize * 0.5,
|
|
487
|
+
originalPosition.y + spaceSize * 0.5,
|
|
488
|
+
originalPosition.z,
|
|
489
|
+
originalPosition.w
|
|
490
|
+
);
|
|
491
|
+
|
|
492
|
+
float width0 = spaceSize;
|
|
493
|
+
|
|
494
|
+
vec2 velocity = vec2(0.0);
|
|
495
|
+
vec2 addVelocity = vec2(0.0);
|
|
496
|
+
|
|
497
|
+
${r}
|
|
498
|
+
|
|
499
|
+
for (float n = 0.0; n < pow(2.0, ${i}.0); n += 1.0) {
|
|
500
|
+
for (float m = 0.0; m < pow(2.0, ${i}.0); m += 1.0) {
|
|
501
|
+
${u(i)}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// Match d3-force algorithm: velocity += addVelocity
|
|
506
|
+
// addVelocity already has correct direction based on strength sign:
|
|
507
|
+
// - strength < 0: addVelocity points away (repulsion)
|
|
508
|
+
// - strength > 0: addVelocity points toward (attraction)
|
|
509
|
+
velocity += addVelocity;
|
|
510
|
+
|
|
511
|
+
// Note: alpha must be 1.0 for THREE.AdditiveBlending to work correctly
|
|
512
|
+
gl_FragColor = vec4(velocity, 0.0, 1.0);
|
|
513
|
+
}
|
|
514
|
+
`}function ut(){let t=[],o=2,i=-30,s=.9,u=1,d=1/0,r=null,e=null,g=0,f=0,w=10,x=0,v=[],h=null,p=null,M=null,y=null,U=null,D=null,n=null;function a(P,k,S){!r||!k||!S||f===0||(Z(k),B(P,k,S))}let c=[],m=0;function Z(P){if(!r||!p||!M||!e)return;M.uniforms.positionTexture.value=P;let k=r.autoClear,S=r.getClearColor(new A.Color),C=r.getClearAlpha();r.autoClear=!0,r.setClearColor(0,0);for(let l=0;l<x;l++){let z=c[l];M.uniforms.levelTextureSize.value=z.textureSize,M.uniforms.cellSize.value=z.cellSize,r.setRenderTarget(v[l]),r.render(p,e)}r.autoClear=k,r.setClearColor(S,C),r.setRenderTarget(null)}let _=!1;function B(P,k,S){if(!r||!U||!D||!e)return;if(D.uniforms.positionsTexture.value=k,D.uniforms.alpha.value=P,!_){D.uniforms.randomValues.value=h?.texture,D.uniforms.strength.value=i,D.uniforms.theta.value=s,D.uniforms.spaceSize.value=w,D.uniforms.distanceMin.value=u,D.uniforms.distanceMax.value=d===1/0?w*10:d;for(let l=0;l<x;l++)D.uniforms[`level${l}`].value=v[l].texture;_=!0}let C=r.autoClear;r.autoClear=!1,r.setRenderTarget(S),r.render(U,e),r.autoClear=C,r.setRenderTarget(null)}let H=Math.random;return a.initialize=function(P,k,S){t=P,o=S,H=k},a.initGPU=function(P){r=P.renderer,e=P.camera,g=P.textureSize,f=P.nodeCount;let k=Ee(f,o),C=Math.max(10,k*2);w=Math.pow(2,Math.ceil(Math.log2(C)));let l=Math.floor(Math.log2(w));x=Math.min(l+4,13);let R=x,T=Math.min(x,14),F=Math.min(x,T),$=x-F,G=new Float32Array(g*g*4);for(let q=0;q<g*g;q++)G[q*4]=H(),G[q*4+1]=H(),G[q*4+2]=0,G[q*4+3]=0;let j=new A.DataTexture(G,g,g,A.RGBAFormat,A.FloatType);j.needsUpdate=!0,h?.dispose(),h=new A.WebGLRenderTarget(g,g,{type:A.FloatType,format:A.RGBAFormat,minFilter:A.NearestFilter,magFilter:A.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});let L=new A.ShaderMaterial({uniforms:{tDiffuse:{value:j}},vertexShader:ce,fragmentShader:`
|
|
515
|
+
precision highp float;
|
|
516
|
+
uniform sampler2D tDiffuse;
|
|
517
|
+
varying vec2 vUv;
|
|
518
|
+
void main() { gl_FragColor = texture2D(tDiffuse, vUv); }
|
|
519
|
+
`}),O=new A.Scene,ie=new A.Mesh(pe(),L);O.add(ie),r.setRenderTarget(h),r.render(O,e),r.setRenderTarget(null),L.dispose(),ie.geometry.dispose(),j.dispose(),v.forEach(q=>q.dispose()),v=[],c=[];for(let q=0;q<x;q++){let se=Math.pow(2,q+1),N=new A.WebGLRenderTarget(se,se,{type:A.FloatType,format:A.RGBAFormat,minFilter:A.NearestFilter,magFilter:A.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});v.push(N),c.push({textureSize:se,cellSize:w/se})}let ae;if(f!==m){let q=new Float32Array(f*2),se=new Float32Array(f*3);for(let N=0;N<f;N++)q[N*2]=N%g,q[N*2+1]=Math.floor(N/g),se[N*3]=0,se[N*3+1]=0,se[N*3+2]=0;ae=new A.BufferGeometry,ae.setAttribute("position",new A.BufferAttribute(se,3)),ae.setAttribute("pointIndex",new A.BufferAttribute(q,2)),m=f}else ae=y.geometry;if(M?.dispose(),M=new A.ShaderMaterial({uniforms:{positionTexture:{value:null},pointsTextureSize:{value:g},levelTextureSize:{value:2},cellSize:{value:w/2},spaceSize:{value:w}},vertexShader:at,fragmentShader:st,blending:A.AdditiveBlending,depthTest:!1,depthWrite:!1}),p||(p=new A.Scene),y){if(y.material=M,f!==m){let q=y.geometry;y.geometry=ae,q.dispose()}}else y=new A.Points(ae,M),p.add(y);D?.dispose(),_=!1;let ze={positionsTexture:{value:null},randomValues:{value:null},spaceSize:{value:w},strength:{value:i},theta:{value:s},alpha:{value:1},distanceMin:{value:u},distanceMax:{value:d===1/0?w*10:d}};for(let q=0;q<x;q++)ze[`level${q}`]={value:null};let me=lt(F,x);D=new A.ShaderMaterial({uniforms:ze,vertexShader:ce,fragmentShader:me,blending:A.AdditiveBlending,depthTest:!1,depthWrite:!1}),U||(U=new A.Scene),n?n.material=D:(n=new A.Mesh(pe(),D),U.add(n))},a.dispose=function(){v.forEach(P=>P.dispose()),v=[],c=[],_=!1,h?.dispose(),h=null,M?.dispose(),D?.dispose(),y?.geometry.dispose(),n?.geometry.dispose()},a.apply=a,a.strength=function(P){return arguments.length===0?i:(i=+P,D&&(D.uniforms.strength.value=i),a)},a.theta=function(P){return arguments.length===0?s:(s=+P,_=!1,a)},a.distanceMin=function(P){return arguments.length===0?u:(u=+P,_=!1,a)},a.distanceMax=function(P){return arguments.length===0?d:(d=+P,_=!1,a)},a}var ct=`
|
|
520
|
+
precision highp float;
|
|
521
|
+
|
|
522
|
+
uniform sampler2D positionTexture;
|
|
523
|
+
uniform float pointsTextureSize;
|
|
524
|
+
uniform float levelTextureWidth; // 2D texture width = levelSize * levelSize
|
|
525
|
+
uniform float levelTextureHeight; // 2D texture height = levelSize
|
|
526
|
+
uniform float levelSize; // 3D grid size = 2^level
|
|
527
|
+
uniform float cellSize;
|
|
528
|
+
uniform float spaceSize;
|
|
529
|
+
|
|
530
|
+
attribute vec2 pointIndex;
|
|
531
|
+
|
|
532
|
+
varying vec4 vData;
|
|
533
|
+
|
|
534
|
+
void main() {
|
|
535
|
+
// Get node position from texture
|
|
536
|
+
vec2 uv = (pointIndex + 0.5) / pointsTextureSize;
|
|
537
|
+
vec4 pos = texture2D(positionTexture, uv);
|
|
538
|
+
|
|
539
|
+
// Convert position to [0, spaceSize] range
|
|
540
|
+
float x = pos.x + spaceSize * 0.5;
|
|
541
|
+
float y = pos.y + spaceSize * 0.5;
|
|
542
|
+
float z = pos.z + spaceSize * 0.5;
|
|
543
|
+
|
|
544
|
+
// Store converted coordinates and count for center of mass calculation
|
|
545
|
+
// Format: (x_sum, y_sum, z_sum, count)
|
|
546
|
+
vData = vec4(x, y, z, 1.0);
|
|
547
|
+
|
|
548
|
+
// Calculate 3D cell indices
|
|
549
|
+
float cellX = floor(x / cellSize);
|
|
550
|
+
float cellY = floor(y / cellSize);
|
|
551
|
+
float cellZ = floor(z / cellSize);
|
|
552
|
+
|
|
553
|
+
// Clamp to valid range
|
|
554
|
+
cellX = clamp(cellX, 0.0, levelSize - 1.0);
|
|
555
|
+
cellY = clamp(cellY, 0.0, levelSize - 1.0);
|
|
556
|
+
cellZ = clamp(cellZ, 0.0, levelSize - 1.0);
|
|
557
|
+
|
|
558
|
+
// Flatten 3D to 2D: (cellX, cellY, cellZ) \u2192 (cellX + cellZ * levelSize, cellY)
|
|
559
|
+
float flatX = cellX + cellZ * levelSize;
|
|
560
|
+
float flatY = cellY;
|
|
561
|
+
|
|
562
|
+
// Convert to clip space [-1, 1]
|
|
563
|
+
vec2 levelPosition = 2.0 * (vec2(flatX, flatY) + 0.5) / vec2(levelTextureWidth, levelTextureHeight) - 1.0;
|
|
564
|
+
|
|
565
|
+
gl_Position = vec4(levelPosition, 0.0, 1.0);
|
|
566
|
+
gl_PointSize = 1.0;
|
|
567
|
+
}
|
|
568
|
+
`,dt=`
|
|
569
|
+
precision highp float;
|
|
570
|
+
varying vec4 vData;
|
|
571
|
+
void main() {
|
|
572
|
+
gl_FragColor = vData;
|
|
573
|
+
}
|
|
574
|
+
`;function ft(t,o){t=Math.min(t,o);let i=o-t;function s(e){let g=o-1-Math.min(e,o-1);return`
|
|
575
|
+
if (l >= distanceMax2) {
|
|
576
|
+
// Skip this cell (too far)
|
|
577
|
+
} else {
|
|
578
|
+
float c = alpha * strength * centermass.w * ${Math.pow(Math.sqrt(4/8),g).toFixed(6)};
|
|
579
|
+
addVelocity += calculateAdditionalVelocity(vec3(dx, dy, dz), l, c, random.rgb);
|
|
580
|
+
}
|
|
581
|
+
`}function u(e){if(e>=o)return s(o-1);{let g=Math.pow(2,e+1),f=new Array(e+1-i).fill(0).map((v,h)=>`pow(2.0, ${e-(h+i)}.0) * i${h+i}`).join("+"),w=new Array(e+1-i).fill(0).map((v,h)=>`pow(2.0, ${e-(h+i)}.0) * j${h+i}`).join("+"),x=new Array(e+1-i).fill(0).map((v,h)=>`pow(2.0, ${e-(h+i)}.0) * k${h+i}`).join("+");return`
|
|
582
|
+
for (float ijk${e} = 0.0; ijk${e} < 8.0; ijk${e} += 1.0) {
|
|
583
|
+
float i${e} = mod(ijk${e}, 2.0);
|
|
584
|
+
float j${e} = mod(floor(ijk${e} / 2.0), 2.0);
|
|
585
|
+
float k${e} = floor(ijk${e} / 4.0);
|
|
586
|
+
|
|
587
|
+
float cellI = pow(2.0, ${t}.0) * outerI / width${e+1} + ${f};
|
|
588
|
+
float cellJ = pow(2.0, ${t}.0) * outerJ / width${e+1} + ${w};
|
|
589
|
+
float cellK = pow(2.0, ${t}.0) * outerK / width${e+1} + ${x};
|
|
590
|
+
|
|
591
|
+
// Sample from flattened 2D texture
|
|
592
|
+
// 3D (cellI, cellJ, cellK) \u2192 2D (cellI + cellK * gridSize, cellJ)
|
|
593
|
+
float texWidth${e} = ${g}.0 * ${g}.0;
|
|
594
|
+
float texHeight${e} = ${g}.0;
|
|
595
|
+
float flatX${e} = cellI + cellK * ${g}.0;
|
|
596
|
+
float flatY${e} = cellJ;
|
|
597
|
+
vec2 texCoord${e} = (vec2(flatX${e}, flatY${e}) + 0.5) / vec2(texWidth${e}, texHeight${e});
|
|
598
|
+
|
|
599
|
+
vec4 centermass = texture2D(level${e}, texCoord${e});
|
|
600
|
+
|
|
601
|
+
// Check if cell has nodes (count > 0)
|
|
602
|
+
if (centermass.w > 0.0) {
|
|
603
|
+
// Calculate center of mass
|
|
604
|
+
float cmX = centermass.x / centermass.w;
|
|
605
|
+
float cmY = centermass.y / centermass.w;
|
|
606
|
+
float cmZ = centermass.z / centermass.w;
|
|
607
|
+
|
|
608
|
+
float dx = cmX - pointPosition.x;
|
|
609
|
+
float dy = cmY - pointPosition.y;
|
|
610
|
+
float dz = cmZ - pointPosition.z;
|
|
611
|
+
float l = dx * dx + dy * dy + dz * dz;
|
|
612
|
+
|
|
613
|
+
// 3D Barnes-Hut criterion: w^2 / theta^2 < l
|
|
614
|
+
float theta2 = theta * theta;
|
|
615
|
+
if ((width${e+1} * width${e+1}) / theta2 < l) {
|
|
616
|
+
${s(e)}
|
|
617
|
+
} else {
|
|
618
|
+
${u(e+1)}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
`}}let d=new Array(o).fill(0).map((e,g)=>`uniform sampler2D level${g};`).join(`
|
|
623
|
+
`),r=new Array(o).fill(0).map((e,g)=>`float width${g+1} = width${g} / 2.0;`).join(`
|
|
624
|
+
`);return`
|
|
625
|
+
precision highp float;
|
|
626
|
+
|
|
627
|
+
uniform sampler2D positionsTexture;
|
|
628
|
+
uniform sampler2D randomValues;
|
|
629
|
+
uniform float spaceSize;
|
|
630
|
+
uniform float strength;
|
|
631
|
+
uniform float theta;
|
|
632
|
+
uniform float alpha;
|
|
633
|
+
uniform float distanceMin; // Match d3-force: minimum distance (default: 1)
|
|
634
|
+
uniform float distanceMax; // Match d3-force: maximum distance (default: Infinity)
|
|
635
|
+
${d}
|
|
636
|
+
varying vec2 vUv;
|
|
637
|
+
|
|
638
|
+
// Pre-computed squared distances for efficiency
|
|
639
|
+
float distanceMin2;
|
|
640
|
+
float distanceMax2;
|
|
641
|
+
|
|
642
|
+
// Jiggle function: add small random displacement when distance is 0
|
|
643
|
+
// This prevents nodes from sticking together (match d3-force jiggle.js)
|
|
644
|
+
float jiggle(float randomVal) {
|
|
645
|
+
return (randomVal - 0.5) * 1e-6;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
vec3 calculateAdditionalVelocity(vec3 xyz, float l, float c, vec3 randomVec) {
|
|
649
|
+
// Match d3-force exactly:
|
|
650
|
+
// - xyz = centermass - pointPosition (vector from point to centermass)
|
|
651
|
+
// - c = alpha * strength * count (strength can be negative or positive)
|
|
652
|
+
// - add = c / l (can be negative or positive)
|
|
653
|
+
// - return add * xyz (direction depends on sign of c)
|
|
654
|
+
// - c < 0: repulsion (points away from centermass)
|
|
655
|
+
// - c > 0: attraction (points toward centermass)
|
|
656
|
+
// Match d3-force: add jiggle when components are 0
|
|
657
|
+
if (xyz.x == 0.0) { xyz.x = jiggle(randomVec.x); l += xyz.x * xyz.x; }
|
|
658
|
+
if (xyz.y == 0.0) { xyz.y = jiggle(randomVec.y); l += xyz.y * xyz.y; }
|
|
659
|
+
if (xyz.z == 0.0) { xyz.z = jiggle(randomVec.z); l += xyz.z * xyz.z; }
|
|
660
|
+
|
|
661
|
+
// Match d3-force manyBody.js line 88 and 104:
|
|
662
|
+
// if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
|
|
663
|
+
if (l < distanceMin2) l = sqrt(distanceMin2 * l);
|
|
664
|
+
float add = c / l;
|
|
665
|
+
return add * xyz;
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
void main() {
|
|
669
|
+
vec4 originalPosition = texture2D(positionsTexture, vUv);
|
|
670
|
+
vec4 random = texture2D(randomValues, vUv);
|
|
671
|
+
|
|
672
|
+
// Pre-compute squared distances (match d3-force manyBody.js)
|
|
673
|
+
distanceMin2 = distanceMin * distanceMin;
|
|
674
|
+
distanceMax2 = distanceMax * distanceMax;
|
|
675
|
+
|
|
676
|
+
// Convert position to [0, spaceSize] range
|
|
677
|
+
vec3 pointPosition = vec3(
|
|
678
|
+
originalPosition.x + spaceSize * 0.5,
|
|
679
|
+
originalPosition.y + spaceSize * 0.5,
|
|
680
|
+
originalPosition.z + spaceSize * 0.5
|
|
681
|
+
);
|
|
682
|
+
|
|
683
|
+
float width0 = spaceSize;
|
|
684
|
+
|
|
685
|
+
vec3 velocity = vec3(0.0);
|
|
686
|
+
vec3 addVelocity = vec3(0.0);
|
|
687
|
+
|
|
688
|
+
${r}
|
|
689
|
+
|
|
690
|
+
// Outer loops for coarse levels
|
|
691
|
+
for (float outerI = 0.0; outerI < pow(2.0, ${i}.0); outerI += 1.0) {
|
|
692
|
+
for (float outerJ = 0.0; outerJ < pow(2.0, ${i}.0); outerJ += 1.0) {
|
|
693
|
+
for (float outerK = 0.0; outerK < pow(2.0, ${i}.0); outerK += 1.0) {
|
|
694
|
+
${u(i)}
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
// Match d3-force algorithm: velocity += addVelocity
|
|
700
|
+
// addVelocity already has correct direction based on strength sign:
|
|
701
|
+
// - strength < 0: addVelocity points away (repulsion)
|
|
702
|
+
// - strength > 0: addVelocity points toward (attraction)
|
|
703
|
+
velocity += addVelocity;
|
|
704
|
+
|
|
705
|
+
// Output 3D velocity (xyz) with alpha = 1.0 for blending
|
|
706
|
+
gl_FragColor = vec4(velocity, 1.0);
|
|
707
|
+
}
|
|
708
|
+
`}function pt(){let t=[],o=2,i=-30,s=.5,u=1,d=1/0,r=null,e=null,g=null,f=0,w=0,x=10,v=0,h=[],p=null,M=null,y=null,U=null,D=null,n=null,a=null;function c(k,S,C){!e||!S||!C||w===0||(_(S),H(k,S,C))}let m=[],Z=0;function _(k){if(!e||!M||!y||!g)return;y.uniforms.positionTexture.value=k;let S=e.autoClear,C=e.getClearColor(new I.Color),l=e.getClearAlpha();e.autoClear=!0,e.setClearColor(0,0);for(let z=0;z<v;z++){let R=m[z];y.uniforms.levelSize.value=R.levelSize,y.uniforms.levelTextureWidth.value=R.textureWidth,y.uniforms.levelTextureHeight.value=R.textureHeight,y.uniforms.cellSize.value=R.cellSize,e.setRenderTarget(h[z]),e.render(M,g)}e.autoClear=S,e.setClearColor(C,l),e.setRenderTarget(null)}let B=!1;function H(k,S,C){if(!e||!D||!n||!g)return;if(n.uniforms.positionsTexture.value=S,n.uniforms.alpha.value=k,!B){n.uniforms.randomValues.value=p?.texture,n.uniforms.strength.value=i,n.uniforms.theta.value=s,n.uniforms.spaceSize.value=x,n.uniforms.distanceMin.value=u,n.uniforms.distanceMax.value=d===1/0?x*10:d;for(let z=0;z<v;z++)n.uniforms[`level${z}`].value=h[z].texture;B=!0}let l=e.autoClear;e.autoClear=!1,e.setRenderTarget(C),e.render(D,g),e.autoClear=l,e.setRenderTarget(null)}let P=Math.random;return c.initialize=function(k,S,C){t=k,o=C,P=S},c.initGPU=function(k){e=k.renderer,g=k.camera,f=k.textureSize,w=k.nodeCount;let S=Ee(w,o),C=Math.min(20,6+Math.log10(Math.max(w,2))),l=Math.max(40,S*C);l>8192&&console.warn(`[ManyBody Octree 3D] paddedSpaceSize=${l.toFixed(0)} exceeds cap 8192; clamping. N=${w} may have boundary spike. Consider Option B adaptive resize.`),x=Math.min(8192,Math.pow(2,Math.ceil(Math.log2(l))));let z=e.getContext(),R=z.getParameter(z.MAX_TEXTURE_SIZE);console.log(`[ManyBody Octree 3D] GPU MAX_TEXTURE_SIZE = ${R}`);let T=Math.floor(Math.log2(R)/2),F=Math.min(Math.floor(Math.log2(x)),T,8);v=r!==null?Math.min(r,F):F,console.log(`[ManyBody Octree 3D] nodeCount=${w}, spaceSize=${x}, maxGPUTexture=${R}`),console.log(`[ManyBody Octree 3D] calculatedLevels=${F}, initialOctreeLevels=${v}`),console.log(`[ManyBody Octree 3D] theta=${s}, strength=${i}`);let $=new Float32Array(f*f*4);for(let N=0;N<f*f;N++)$[N*4]=P(),$[N*4+1]=P(),$[N*4+2]=P(),$[N*4+3]=0;let G=new I.DataTexture($,f,f,I.RGBAFormat,I.FloatType);G.needsUpdate=!0,p?.dispose(),p=new I.WebGLRenderTarget(f,f,{type:I.FloatType,format:I.RGBAFormat,minFilter:I.NearestFilter,magFilter:I.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});let j=new I.ShaderMaterial({uniforms:{tDiffuse:{value:G}},vertexShader:ce,fragmentShader:`
|
|
709
|
+
precision highp float;
|
|
710
|
+
uniform sampler2D tDiffuse;
|
|
711
|
+
varying vec2 vUv;
|
|
712
|
+
void main() { gl_FragColor = texture2D(tDiffuse, vUv); }
|
|
713
|
+
`}),L=new I.Scene,O=new I.Mesh(pe(),j);L.add(O),e.setRenderTarget(p),e.render(L,g),e.setRenderTarget(null),j.dispose(),O.geometry.dispose(),G.dispose(),h.forEach(N=>N.dispose()),h=[],m=[];for(let N=0;N<v;N++){let le=Math.pow(2,N+1),K=le*le,ve=le;if(K>R||ve>R){console.error(`[ManyBody Octree 3D] Level ${N} texture ${K}\xD7${ve} exceeds GPU limit ${R}! Skipping remaining levels.`),v=N;break}let Pe=new I.WebGLRenderTarget(K,ve,{type:I.FloatType,format:I.RGBAFormat,minFilter:I.NearestFilter,magFilter:I.NearestFilter,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});h.push(Pe),m.push({levelSize:le,textureWidth:K,textureHeight:ve,cellSize:x/le}),console.log(`[ManyBody Octree 3D] Level ${N}: grid=${le}\xB3, texture=${K}\xD7${ve}`)}let ie=Math.min(v,8),ae=Math.min(v,ie),ze=v-ae;console.log(`[ManyBody Octree 3D] Final: octreeLevels=${v}, shaderStartLevel=${ae}, delta=${ze}`);let me;if(w!==Z){let N=new Float32Array(w*2),le=new Float32Array(w*3);for(let K=0;K<w;K++)N[K*2]=K%f,N[K*2+1]=Math.floor(K/f),le[K*3]=0,le[K*3+1]=0,le[K*3+2]=0;me=new I.BufferGeometry,me.setAttribute("position",new I.BufferAttribute(le,3)),me.setAttribute("pointIndex",new I.BufferAttribute(N,2)),Z=w}else me=U.geometry;if(y?.dispose(),y=new I.ShaderMaterial({uniforms:{positionTexture:{value:null},pointsTextureSize:{value:f},levelSize:{value:2},levelTextureWidth:{value:4},levelTextureHeight:{value:2},cellSize:{value:x/2},spaceSize:{value:x}},vertexShader:ct,fragmentShader:dt,blending:I.AdditiveBlending,depthTest:!1,depthWrite:!1}),M||(M=new I.Scene),U){if(U.material=y,w!==Z){let N=U.geometry;U.geometry=me,N.dispose()}}else U=new I.Points(me,y),M.add(U);n?.dispose(),B=!1;let q={positionsTexture:{value:null},randomValues:{value:null},spaceSize:{value:x},strength:{value:i},theta:{value:s},alpha:{value:1},distanceMin:{value:u},distanceMax:{value:d===1/0?x*10:d}};for(let N=0;N<v;N++)q[`level${N}`]={value:null};let se=ft(ae,v);n=new I.ShaderMaterial({uniforms:q,vertexShader:ce,fragmentShader:se,blending:I.AdditiveBlending,depthTest:!1,depthWrite:!1}),D||(D=new I.Scene),a?a.material=n:(a=new I.Mesh(pe(),n),D.add(a))},c.dispose=function(){h.forEach(k=>k.dispose()),h=[],m=[],B=!1,p?.dispose(),p=null,y?.dispose(),n?.dispose(),U?.geometry.dispose(),a?.geometry.dispose()},c.apply=c,c.strength=function(k){return arguments.length===0?i:(i=+k,n&&(n.uniforms.strength.value=i),c)},c.theta=function(k){return arguments.length===0?s:(s=+k,B=!1,c)},c.distanceMin=function(k){return arguments.length===0?u:(u=+k,B=!1,c)},c.distanceMax=function(k){return arguments.length===0?d:(d=+k,B=!1,c)},c.maxLevels=function(k){return arguments.length===0?r??null:(r=k>0?Math.min(k,8):null,B=!1,c)},c.getSpaceSize=function(){return typeof x=="number"&&x>0?x:10},c}var ht=`/**
|
|
714
|
+
* Link force vertex shader
|
|
715
|
+
*
|
|
716
|
+
* Each point represents one endpoint of a link.
|
|
717
|
+
* The vertex position is set to the node's location in the velocity texture
|
|
718
|
+
* so the force is applied to the correct node.
|
|
719
|
+
*/
|
|
720
|
+
precision highp float;
|
|
721
|
+
|
|
722
|
+
// x = link endpoint index, y = node index
|
|
723
|
+
attribute vec2 linkEndpoint;
|
|
724
|
+
|
|
725
|
+
uniform float nodeTextureSize;
|
|
726
|
+
|
|
727
|
+
varying float vLinkIndex;
|
|
728
|
+
varying float vNodeIndex;
|
|
729
|
+
|
|
730
|
+
void main() {
|
|
731
|
+
vLinkIndex = linkEndpoint.x;
|
|
732
|
+
vNodeIndex = linkEndpoint.y;
|
|
733
|
+
|
|
734
|
+
// Convert node index to UV coordinates in velocity texture
|
|
735
|
+
float x = mod(vNodeIndex, nodeTextureSize);
|
|
736
|
+
float y = floor(vNodeIndex / nodeTextureSize);
|
|
737
|
+
vec2 uv = (vec2(x, y) + 0.5) / nodeTextureSize;
|
|
738
|
+
|
|
739
|
+
// Convert UV to clip space [-1, 1]
|
|
740
|
+
vec2 pos = uv * 2.0 - 1.0;
|
|
741
|
+
|
|
742
|
+
gl_Position = vec4(pos, 0.0, 1.0);
|
|
743
|
+
gl_PointSize = 1.0;
|
|
744
|
+
}
|
|
745
|
+
`,mt=`/**
|
|
746
|
+
* Link force fragment shader
|
|
747
|
+
*
|
|
748
|
+
* Implements d3-force's forceLink spring behavior:
|
|
749
|
+
* - Calculates spring force to pull/push nodes toward target distance
|
|
750
|
+
* - Uses bias to distribute force asymmetrically based on node degree
|
|
751
|
+
*
|
|
752
|
+
* Each fragment represents the force applied to one endpoint of a link.
|
|
753
|
+
*/
|
|
754
|
+
precision highp float;
|
|
755
|
+
|
|
756
|
+
uniform sampler2D positionTexture;
|
|
757
|
+
uniform sampler2D linkTexture;
|
|
758
|
+
uniform float linkTextureSize;
|
|
759
|
+
uniform float nodeTextureSize;
|
|
760
|
+
uniform float nodeCount;
|
|
761
|
+
uniform float alpha;
|
|
762
|
+
uniform float nDim;
|
|
763
|
+
|
|
764
|
+
varying float vLinkIndex;
|
|
765
|
+
varying float vNodeIndex;
|
|
766
|
+
|
|
767
|
+
// Get node position from texture
|
|
768
|
+
vec3 getNodePosition(float index) {
|
|
769
|
+
float x = mod(index, nodeTextureSize);
|
|
770
|
+
float y = floor(index / nodeTextureSize);
|
|
771
|
+
vec2 uv = (vec2(x, y) + 0.5) / nodeTextureSize;
|
|
772
|
+
return texture2D(positionTexture, uv).xyz;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
void main() {
|
|
776
|
+
// Read link data from texture
|
|
777
|
+
// Format: [sourceIndex, targetIndex, distance, strength] per link
|
|
778
|
+
// Endpoint texture: [endpointIndex = linkIndex * 2 + side]
|
|
779
|
+
|
|
780
|
+
float linkIndex = floor(vLinkIndex / 2.0);
|
|
781
|
+
float side = mod(vLinkIndex, 2.0); // 0 = source, 1 = target
|
|
782
|
+
|
|
783
|
+
// Calculate link texture UV
|
|
784
|
+
float lx = mod(linkIndex, linkTextureSize);
|
|
785
|
+
float ly = floor(linkIndex / linkTextureSize);
|
|
786
|
+
vec2 luv = (vec2(lx, ly) + 0.5) / linkTextureSize;
|
|
787
|
+
vec4 linkData = texture2D(linkTexture, luv);
|
|
788
|
+
|
|
789
|
+
float sourceIndex = linkData.r;
|
|
790
|
+
float targetIndex = linkData.g;
|
|
791
|
+
float linkDistance = linkData.b;
|
|
792
|
+
float linkStrength = linkData.a;
|
|
793
|
+
|
|
794
|
+
// Guard invalid indices
|
|
795
|
+
if (sourceIndex < 0.0 || targetIndex < 0.0 ||
|
|
796
|
+
sourceIndex >= nodeCount || targetIndex >= nodeCount) {
|
|
797
|
+
gl_FragColor = vec4(0.0);
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
// Get positions
|
|
802
|
+
vec3 sourcePos = getNodePosition(sourceIndex);
|
|
803
|
+
vec3 targetPos = getNodePosition(targetIndex);
|
|
804
|
+
|
|
805
|
+
// Calculate direction and distance
|
|
806
|
+
vec3 delta = targetPos - sourcePos;
|
|
807
|
+
|
|
808
|
+
// Mask dimensions
|
|
809
|
+
if (nDim < 3.0) delta.z = 0.0;
|
|
810
|
+
if (nDim < 2.0) delta.y = 0.0;
|
|
811
|
+
|
|
812
|
+
float dist = length(delta);
|
|
813
|
+
|
|
814
|
+
// Prevent division by zero
|
|
815
|
+
if (dist < 1e-6) {
|
|
816
|
+
gl_FragColor = vec4(0.0);
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
vec3 dir = delta / dist;
|
|
821
|
+
|
|
822
|
+
// Spring force calculation
|
|
823
|
+
// Positive displacement = nodes too close, need to push apart
|
|
824
|
+
// Negative displacement = nodes too far, need to pull together
|
|
825
|
+
float displacement = dist - linkDistance;
|
|
826
|
+
|
|
827
|
+
// Force magnitude = alpha * strength * displacement
|
|
828
|
+
float forceMag = alpha * linkStrength * displacement;
|
|
829
|
+
|
|
830
|
+
// Force direction depends on which endpoint:
|
|
831
|
+
// - Source gets force toward target (positive displacement pulls toward target)
|
|
832
|
+
// - Target gets force toward source (negative of source force)
|
|
833
|
+
vec3 velocity;
|
|
834
|
+
if (side < 0.5) {
|
|
835
|
+
// Source endpoint: force toward target
|
|
836
|
+
velocity = dir * forceMag;
|
|
837
|
+
} else {
|
|
838
|
+
// Target endpoint: force toward source
|
|
839
|
+
velocity = -dir * forceMag;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
// Note: alpha must be 1.0 for THREE.AdditiveBlending to work (uses SrcAlphaFactor)
|
|
843
|
+
gl_FragColor = vec4(velocity, 1.0);
|
|
844
|
+
}
|
|
845
|
+
`;function gt(t){let o=[],i=t||[],s=2,u=Math.random,d=S=>S.index,r=Z,e=J(30),g=1,f=[],w=[],x=[],v=[],h=null,p=null,M=null,y=0,U=0,D=null,n=null,a=null,c=null,m=0;function Z(S){let C=typeof S.source=="object"?S.source.index:0,l=typeof S.target=="object"?S.target.index:0;return 1/Math.min(f[C]||1,f[l]||1)}function _(){if(!o||o.length===0)return;let S=o.length,C=i.length,l=new Map;for(let T=0;T<S;T++)l.set(d(o[T],T,o),o[T]);f=new Array(S).fill(0);for(let T=0;T<C;T++){let F=i[T];if(F.index=T,typeof F.source!="object"){let $=l.get(F.source);if(!$)throw new Error(`Link source not found: ${F.source}`);F.source=$}if(typeof F.target!="object"){let $=l.get(F.target);if(!$)throw new Error(`Link target not found: ${F.target}`);F.target=$}f[F.source.index]++,f[F.target.index]++}w=new Array(C);for(let T=0;T<C;T++){let F=i[T],$=F.source.index,G=F.target.index;w[T]=f[$]/(f[$]+f[G])}x=new Array(C),v=new Array(C);let z=typeof r=="function"?r:()=>r,R=typeof e=="function"?e:()=>e;for(let T=0;T<C;T++)x[T]=+z(i[T],T,i),v[T]=+R(i[T],T,i);B()}function B(){if(!c||i.length===0)return;let S=c.image.data;for(let C=0;C<i.length;C++){let l=i[C],z=l.source.index,R=l.target.index,T=C*4;S[T]=z,S[T+1]=R,S[T+2]=v[C],S[T+3]=x[C]}c.needsUpdate=!0}function H(S,C,l){if(i.length!==0){if(!h||!C||!l||U===0){P(S);return}k(S,C,l)}}function P(S){for(let C=0;C<g;C++)for(let l=0;l<i.length;l++){let z=i[l],R=z.source,T=z.target,F=(T.x||0)+(T.vx||0)-(R.x||0)-(R.vx||0)||Re(u),$=s>1?(T.y||0)+(T.vy||0)-(R.y||0)-(R.vy||0)||Re(u):0,G=s>2?(T.z||0)+(T.vz||0)-(R.z||0)-(R.vz||0)||Re(u):0,j=Math.sqrt(F*F+$*$+G*G);j=(j-v[l])/j*S*x[l],F*=j,$*=j,G*=j;let L=w[l];T.vx-=F*L,s>1&&(T.vy-=$*L),s>2&&(T.vz-=G*L),R.vx+=F*(1-L),s>1&&(R.vy+=$*(1-L)),s>2&&(R.vz+=G*(1-L))}}function k(S,C,l){if(!D||!a)return;a.uniforms.positionTexture.value=C,a.uniforms.linkTexture.value=c,a.uniforms.linkTextureSize.value=m,a.uniforms.nodeTextureSize.value=y,a.uniforms.nodeCount.value=U,a.uniforms.alpha.value=S,a.uniforms.nDim.value=s;let z=h.autoClear;h.autoClear=!1;for(let R=0;R<g;R++)h.setRenderTarget(l),p&&h.render(p,M);h.autoClear=z,h.setRenderTarget(null)}return H.initialize=function(S,C,l){o=S,u=C,s=l,_()},H.initGPU=function(S){if(h=S.renderer,M=S.camera,y=S.textureSize,U=S.nodeCount,i.length===0)return;m=be(i.length);let C=new Float32Array(m*m*4);C.fill(-1);for(let T=0;T<i.length;T++){let F=i[T],$=F.source.index,G=F.target.index,j=T*4;C[j]=$,C[j+1]=G,C[j+2]=v[T],C[j+3]=x[T]}c?.dispose(),c=new Q.DataTexture(C,m,m,Q.RGBAFormat,Q.FloatType),c.needsUpdate=!0;let l=i.length*2,z=new Float32Array(l*2);for(let T=0;T<i.length;T++){let F=i[T],$=F.source.index,G=F.target.index;z[T*4]=T*2,z[T*4+1]=$,z[T*4+2]=T*2+1,z[T*4+3]=G}n?.dispose(),n=new Q.BufferGeometry,n.setAttribute("linkEndpoint",new Q.BufferAttribute(z,2));let R=new Float32Array(z.length/2*3);n.setAttribute("position",new Q.BufferAttribute(R,3)),a?.dispose(),a=new Q.ShaderMaterial({uniforms:{positionTexture:{value:null},linkTexture:{value:c},linkTextureSize:{value:m},nodeTextureSize:{value:y},nodeCount:{value:U},alpha:{value:1},nDim:{value:s}},vertexShader:ht,fragmentShader:mt,blending:Q.AdditiveBlending,depthTest:!1,depthWrite:!1}),D&&p&&p.remove(D),p=new Q.Scene,D=new Q.Points(n,a),p.add(D)},H.dispose=function(){c?.dispose(),n?.dispose(),a?.dispose(),D&&p?.remove(D)},H.apply=H,H.links=function(S){return arguments.length===0?i:(i=S,_(),H)},H.id=function(S){return arguments.length===0?d:(d=S,H)},H.iterations=function(S){return arguments.length===0?g:(g=+S,H)},H.strength=function(S){return arguments.length===0?r:(r=typeof S=="function"?S:J(+S),_(),B(),H)},H.distance=function(S){return arguments.length===0?e:(e=typeof S=="function"?S:J(+S),_(),B(),H)},H}var _e=`/**
|
|
846
|
+
* Position force shader (forceX/Y/Z)
|
|
847
|
+
*
|
|
848
|
+
* Implements d3-force's forceX/forceY/forceZ:
|
|
849
|
+
* - Applies a force that pulls each node toward a target position along one axis
|
|
850
|
+
* - Uses per-node strength for fine-grained control
|
|
851
|
+
*
|
|
852
|
+
* This shader handles all three axes based on uniforms.
|
|
853
|
+
*/
|
|
854
|
+
precision highp float;
|
|
855
|
+
|
|
856
|
+
uniform sampler2D positionTexture;
|
|
857
|
+
uniform sampler2D targetTexture; // Target position per node (x in R, strength in G)
|
|
858
|
+
uniform float alpha;
|
|
859
|
+
uniform float textureSize;
|
|
860
|
+
uniform float nodeCount;
|
|
861
|
+
uniform float axis; // 0 = x, 1 = y, 2 = z
|
|
862
|
+
|
|
863
|
+
varying vec2 vUv;
|
|
864
|
+
|
|
865
|
+
void main() {
|
|
866
|
+
// Calculate node index
|
|
867
|
+
float x = floor(vUv.x * textureSize);
|
|
868
|
+
float y = floor(vUv.y * textureSize);
|
|
869
|
+
float nodeIndex = y * textureSize + x;
|
|
870
|
+
|
|
871
|
+
// Output zero for invalid indices
|
|
872
|
+
if (nodeIndex >= nodeCount) {
|
|
873
|
+
gl_FragColor = vec4(0.0);
|
|
874
|
+
return;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
// Get current position
|
|
878
|
+
vec4 pos = texture2D(positionTexture, vUv);
|
|
879
|
+
|
|
880
|
+
// Get target position and strength
|
|
881
|
+
vec4 target = texture2D(targetTexture, vUv);
|
|
882
|
+
float targetPos = target.r;
|
|
883
|
+
float strength = target.g;
|
|
884
|
+
|
|
885
|
+
// Calculate force toward target
|
|
886
|
+
vec3 velocity = vec3(0.0);
|
|
887
|
+
|
|
888
|
+
if (axis < 0.5) {
|
|
889
|
+
// X axis
|
|
890
|
+
velocity.x = (targetPos - pos.x) * strength * alpha;
|
|
891
|
+
} else if (axis < 1.5) {
|
|
892
|
+
// Y axis
|
|
893
|
+
velocity.y = (targetPos - pos.y) * strength * alpha;
|
|
894
|
+
} else {
|
|
895
|
+
// Z axis
|
|
896
|
+
velocity.z = (targetPos - pos.z) * strength * alpha;
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
// Note: alpha must be 1.0 for THREE.AdditiveBlending to work (uses SrcAlphaFactor)
|
|
900
|
+
gl_FragColor = vec4(velocity, 1.0);
|
|
901
|
+
}
|
|
902
|
+
`;function vt(t){let o=[],i=J(.1),s=t==null?J(0):typeof t=="function"?t:J(+t),u=[],d=[],r=null,e=null,g=null,f=0,w=0,x=null,v=null,h=null;function p(){if(!o)return;let n=o.length;u=new Array(n),d=new Array(n);let a=typeof s=="function"?s:()=>s,c=typeof i=="function"?i:()=>i;for(let m=0;m<n;m++)d[m]=+a(o[m],m,o),u[m]=isNaN(d[m])?0:+c(o[m],m,o);h&&f>0&&M()}function M(){let n=f*f,a=new Float32Array(n*4);for(let c=0;c<o.length;c++){let m=c*4;a[m]=d[c]??0,a[m+1]=u[c]??0,a[m+2]=0,a[m+3]=0}h.image.data.set(a),h.needsUpdate=!0}function y(n,a,c){if(!r||!a||!c||w===0||!v||!h){U(n);return}D(n,a,c)}function U(n){for(let a=0;a<o.length;a++){let c=o[a];c.vx+=(d[a]-(c.x||0))*u[a]*n}}function D(n,a,c){v.uniforms.positionTexture.value=a,v.uniforms.targetTexture.value=h,v.uniforms.alpha.value=n,v.uniforms.textureSize.value=f,v.uniforms.nodeCount.value=w,v.uniforms.axis.value=0;let m=r.autoClear;r.autoClear=!1,r.setRenderTarget(c),r.render(e,g),r.autoClear=m,r.setRenderTarget(null)}return y.initialize=function(n,a,c){o=n,p()},y.initGPU=function(n){r=n.renderer,g=n.camera,f=n.textureSize,w=n.nodeCount,o.length>0&&(d.length===0||u.length===0)&&p();let a=f*f,c=new Float32Array(a*4),m=0,Z=0;for(let _=0;_<o.length;_++){let B=_*4;c[B]=d[_]??0,c[B+1]=u[_]??0,c[B+2]=0,c[B+3]=0,_<10&&(m+=u[_]??0,Z+=d[_]??0)}h?.dispose(),h=new ee.DataTexture(c,f,f,ee.RGBAFormat,ee.FloatType),h.minFilter=ee.NearestFilter,h.magFilter=ee.NearestFilter,h.needsUpdate=!0,e=new ee.Scene,v=new ee.ShaderMaterial({uniforms:{positionTexture:{value:null},targetTexture:{value:h},alpha:{value:1},textureSize:{value:f},nodeCount:{value:w},axis:{value:0}},vertexShader:ce,fragmentShader:_e,blending:ee.AdditiveBlending,depthTest:!1,depthWrite:!1}),x=new ee.Mesh(pe(),v),e.add(x)},y.dispose=function(){h?.dispose(),v?.dispose(),x&&(x.geometry.dispose(),e?.remove(x))},y.apply=y,y.strength=function(n){return arguments.length===0?i:(i=typeof n=="function"?n:J(+n),p(),y)},y.x=function(n){return arguments.length===0?s:(s=typeof n=="function"?n:J(+n),p(),y)},y}function yt(t){let o=[],i=J(.1),s=t==null?J(0):typeof t=="function"?t:J(+t),u=[],d=[],r=null,e=null,g=null,f=0,w=0,x=null,v=null,h=null;function p(){if(!o)return;let n=o.length;u=new Array(n),d=new Array(n);let a=typeof s=="function"?s:()=>s,c=typeof i=="function"?i:()=>i;for(let m=0;m<n;m++)d[m]=+a(o[m],m,o),u[m]=isNaN(d[m])?0:+c(o[m],m,o);h&&f>0&&M()}function M(){let n=f*f,a=new Float32Array(n*4);for(let c=0;c<o.length;c++){let m=c*4;a[m]=d[c]??0,a[m+1]=u[c]??0,a[m+2]=0,a[m+3]=0}h.image.data.set(a),h.needsUpdate=!0}function y(n,a,c){if(!r||!a||!c||w===0||!v||!h){U(n);return}D(n,a,c)}function U(n){for(let a=0;a<o.length;a++){let c=o[a];c.vy+=(d[a]-(c.y||0))*u[a]*n}}function D(n,a,c){v.uniforms.positionTexture.value=a,v.uniforms.targetTexture.value=h,v.uniforms.alpha.value=n,v.uniforms.textureSize.value=f,v.uniforms.nodeCount.value=w,v.uniforms.axis.value=1;let m=r.autoClear;r.autoClear=!1,r.setRenderTarget(c),r.render(e,g),r.autoClear=m,r.setRenderTarget(null)}return y.initialize=function(n,a,c){o=n,p()},y.initGPU=function(n){r=n.renderer,g=n.camera,f=n.textureSize,w=n.nodeCount,o.length>0&&(d.length===0||u.length===0)&&p();let a=f*f,c=new Float32Array(a*4),m=0,Z=0;for(let _=0;_<o.length;_++){let B=_*4,H=d[_]??0,P=u[_]??0;c[B]=H,c[B+1]=P,c[B+2]=0,c[B+3]=0,_<10&&(m+=H,Z+=P)}o.length>0,h?.dispose(),h=new te.DataTexture(c,f,f,te.RGBAFormat,te.FloatType),h.minFilter=te.NearestFilter,h.magFilter=te.NearestFilter,h.needsUpdate=!0,e=new te.Scene,v=new te.ShaderMaterial({uniforms:{positionTexture:{value:null},targetTexture:{value:h},alpha:{value:1},textureSize:{value:f},nodeCount:{value:w},axis:{value:1}},vertexShader:ce,fragmentShader:_e,blending:te.AdditiveBlending,depthTest:!1,depthWrite:!1}),x=new te.Mesh(pe(),v),e.add(x)},y.dispose=function(){h?.dispose(),v?.dispose(),x&&(x.geometry.dispose(),e?.remove(x))},y.apply=y,y.strength=function(n){return arguments.length===0?i:(i=typeof n=="function"?n:J(+n),p(),y)},y.y=function(n){return arguments.length===0?s:(s=typeof n=="function"?n:J(+n),p(),y)},y}function xt(t){let o=[],i=J(.1),s=t==null?J(0):typeof t=="function"?t:J(+t),u=[],d=[],r=null,e=null,g=null,f=0,w=0,x=null,v=null,h=null;function p(){if(!o)return;let n=o.length;u=new Array(n),d=new Array(n);let a=typeof s=="function"?s:()=>s,c=typeof i=="function"?i:()=>i;for(let m=0;m<n;m++)d[m]=+a(o[m],m,o),u[m]=isNaN(d[m])?0:+c(o[m],m,o);h&&f>0&&M()}function M(){let n=f*f,a=new Float32Array(n*4);for(let c=0;c<o.length;c++){let m=c*4;a[m]=d[c]??0,a[m+1]=u[c]??0,a[m+2]=0,a[m+3]=0}h.image.data.set(a),h.needsUpdate=!0}function y(n,a,c){if(!r||!a||!c||w===0||!v||!h){U(n);return}D(n,a,c)}function U(n){for(let a=0;a<o.length;a++){let c=o[a];c.vz+=(d[a]-(c.z||0))*u[a]*n}}function D(n,a,c){v.uniforms.positionTexture.value=a,v.uniforms.targetTexture.value=h,v.uniforms.alpha.value=n,v.uniforms.textureSize.value=f,v.uniforms.nodeCount.value=w,v.uniforms.axis.value=2;let m=r.autoClear;r.autoClear=!1,r.setRenderTarget(c),r.render(e,g),r.autoClear=m,r.setRenderTarget(null)}return y.initialize=function(n,a,c){o=n,p()},y.initGPU=function(n){r=n.renderer,g=n.camera,f=n.textureSize,w=n.nodeCount,o.length>0&&(d.length===0||u.length===0)&&p();let a=f*f,c=new Float32Array(a*4);for(let m=0;m<o.length;m++){let Z=m*4;c[Z]=d[m]??0,c[Z+1]=u[m]??0,c[Z+2]=0,c[Z+3]=0}h?.dispose(),h=new ne.DataTexture(c,f,f,ne.RGBAFormat,ne.FloatType),h.minFilter=ne.NearestFilter,h.magFilter=ne.NearestFilter,h.needsUpdate=!0,e=new ne.Scene,v=new ne.ShaderMaterial({uniforms:{positionTexture:{value:null},targetTexture:{value:h},alpha:{value:1},textureSize:{value:f},nodeCount:{value:w},axis:{value:2}},vertexShader:ce,fragmentShader:_e,blending:ne.AdditiveBlending,depthTest:!1,depthWrite:!1}),x=new ne.Mesh(pe(),v),e.add(x)},y.dispose=function(){h?.dispose(),v?.dispose(),x&&(x.geometry.dispose(),e?.remove(x))},y.apply=y,y.strength=function(n){return arguments.length===0?i:(i=typeof n=="function"?n:J(+n),p(),y)},y.z=function(n){return arguments.length===0?s:(s=typeof n=="function"?n:J(+n),p(),y)},y}var De={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},qe=class{constructor(t,o){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=t,o)this.renderer=o;else{let i=document.createElement("canvas");i.style.display="none",this.renderer=new Xe.WebGLRenderer({canvas:i,alpha:!0,antialias:!1}),this.renderer.setSize(256,256)}this.params={...De}}config(t){if(this.getOptions=t,t){let o=t();o&&this.applyConfig(o)}return this}configure(t){return this.config(t)}applyConfig(t){t.friction!==void 0&&t.velocityDecay===void 0&&(t.velocityDecay=t.friction),Object.assign(this.params,t)}calculateForces(){let t=this.params.heightCompress??1,o=this.params.gravity??.1,i=this.params.dimensions??3,s,u,d,r;return i===2?(u=o*1.5,s=0,d=.02,r=.8):(s=o*Math.sqrt(t),u=o/Math.sqrt(t),s=s>10?10:s,d=De.alphaDecay??.1,r=De.alpha??.6),{forcexy:u,forcez:s,alphaDecay:d,alpha:r}}startLayout(t=0,o=0,i=!1){let s=this.params.dimensions;if(this.getOptions){let l=this.getOptions();l&&this.applyConfig(l)}this.params.dimensions=s,this._gpuZZeroed=!1;let u=this.graph.layoutNodes||[],d=this.graph.layoutEdges||[];if(u.length===0)return;this.nodeIdToIndex.clear(),u.forEach((l,z)=>{this.nodeIdToIndex.set(l.id,z)});let r=this.params.dimensions??3;this.params.dimensions=r;let e=u.some(l=>Math.abs(l.position.z)>1e-6),g=Math.cbrt(u.length)*2,f=r>2&&!e&&!i,w=u.map((l,z)=>{let R=l.position.x,T=l.position.y,F=r<=2?0:l.position.z;if(f&&!l.pinned){let $=Math.random(),G=Math.random(),j=Math.random(),L=2*Math.PI*$,O=Math.acos(2*G-1),ie=Math.cbrt(j)*g;R=ie*Math.sin(O)*Math.cos(L),T=ie*Math.sin(O)*Math.sin(L),F=ie*Math.cos(O)}return{...l,index:z,x:R,y:T,z:F,vx:0,vy:0,vz:0,fx:l.pinned?l.position.x:null,fy:l.pinned?l.position.y:null,fz:l.pinned?l.position.z:null}}),x=d.filter(l=>{let z=this.nodeIdToIndex.get(l.sourceId),R=this.nodeIdToIndex.get(l.targetId);return z!==void 0&&R!==void 0}).map(l=>({source:l.sourceId,target:l.targetId}));this.simulation&&(this.simulation.stop(),this.simulation.dispose()),this.simulation=et(w,r,this.renderer);let{forcexy:v,forcez:h,alphaDecay:p,alpha:M}=this.calculateForces(),y=this.params.charge??-.01,U=u.length,D=this.params.gravityX??1,n=this.params.gravityY??1,a=this.params.gravityZ??1,c=this.params.linkDistance??.5,m=this.params.linkStrength??1,Z=v*this.params.gravityX,_=v*this.params.gravityY,B=h*this.params.gravityZ,H=vt(0).strength(Z),P=yt(0).strength(_);if(this.simulation.force("x",H),this.simulation.force("y",P),r>2){let l=xt(0).strength(B);this.simulation.force("z",l)}if(this.simulation.force("center",rt(0,0,0).strength(1)),r>2){let l=pt();l.strength(y);let z=this.params.octreeTheta??.8,R=u.length,T=Math.max(.2,Math.min(1,1.2-.1*Math.log10(Math.max(R,1)))),F=z*T;l.theta(F);let $=this.params.octreeLevels;$!==void 0&&l.maxLevels($),this.simulation.force("charge",l)}else{let l=ut();l.strength(y);let z=this.params.quadtreeTheta??.9,R=Math.max(.5,Math.min(1,500/Math.sqrt(u.length))),T=z*R;l.theta(T),this.simulation.force("charge",l)}if(x.length>0){let l=gt(x);l.distance(c),l.strength(m),l.id(z=>z.id),this.simulation.force("link",l)}(this.params.collision??.15)>0;let S=this.params.velocityDecay??De.velocityDecay;this.simulation.alpha(M).alphaMin(.001).alphaDecay(p).velocityDecay(S),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 t=performance.now();if(t-this.lastUpdateTime<this.updateIntervalMs)return;this.lastUpdateTime=t;let o=this.simulation.nodes(),i=this.params.dimensions??3;o.forEach(s=>{let u=this.nodeIdToIndex.get(s.id);if(u!==void 0&&u<this.graph.layoutNodes.length){let d=this.graph.layoutNodes[u];d&&!d.pinned&&s.fx==null&&(d.position.x=s.x??0,d.position.y=s.y??0,i>2?d.position.z=s.z??0:d.position.z=0,d.isPositionDirty=!0)}}),this.graph.renderNeedsUpdate=!0}ensureGPUZeroZ(){if(this._gpuZZeroed||!this.simulation)return;this._gpuZZeroed=!0,this.simulation.readBackPositions();let t=this.simulation.nodes(),o=[];t.forEach((s,u)=>{Math.abs(s.z??0)>1e-6&&o.push({index:u,x:s.x??0,y:s.y??0,z:0})}),o.length>0&&this.simulation.uploadNodePositions(o);let i=this.graph.layoutNodes;for(let s=0;s<i.length;s++)i[s].position.z=0}restartLayout(){if(!this.simulation||!this._enable)return;if(this.getOptions){let U=this.getOptions();U&&this.applyConfig(U)}let t=this.params.dimensions??3,{forcexy:o,forcez:i,alphaDecay:s,alpha:u}=this.calculateForces(),d=this.params.charge??-.01,r=this.params.linkDistance??.5,e=this.params.linkStrength??1,g=o*(this.params.gravityX??1),f=o*(this.params.gravityY??1),w=i*(this.params.gravityZ??1),x=this.simulation.force("x"),v=this.simulation.force("y"),h=this.simulation.force("z"),p=this.simulation.force("charge"),M=this.simulation.force("link");x&&x.strength(g),v&&v.strength(f),h&&t>2&&h.strength(w),p&&p.strength(d),M&&(M.distance(r),M.strength(e));let y=this.params.velocityDecay??.3;this.simulation.alpha(u).alphaDecay(s).velocityDecay(y).restart(),this._isFinish=!1,this.graph.renderNeedsUpdate=!0}stopLayout(){this.simulation&&this.simulation.stop(),this._isFinish=!0,this.graph.renderNeedsUpdate=!1}updateLayoutOption(t,o){if(t==="friction"?this.params.velocityDecay=o:this.params[t]=o,!this.simulation||!this._enable)return;let i=this.simulation.force("charge"),s=this.simulation.force("link"),u=this.simulation.force("x"),d=this.simulation.force("y"),r=this.simulation.force("z");switch(t){case"charge":i&&(i.strength(o),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)).restart());break;case"linkDistance":s&&(s.distance(o),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)).restart());break;case"linkStrength":s&&(s.strength(o),this.simulation.alpha(Math.max(this.simulation.alpha(),.3)).restart());break;case"gravity":case"gravityX":case"gravityY":case"gravityZ":case"heightCompress":let{forcexy:e,forcez:g}=this.calculateForces(),f=e*(this.params.gravityX??1),w=e*(this.params.gravityY??1),x=g*(this.params.gravityZ??1);u&&u.strength(f),d&&d.strength(w),r&&r.strength(x),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(t){if(!this.simulation)return;let o=this.simulation.nodes(),i=[];t.forEach(u=>{let d=this.nodeIdToIndex.get(u.id);if(d!==void 0){let r=this.graph.layoutNodes[d];r&&(r.pinned=!0);let e=o[d];e&&(e.fx=u.position.x,e.fy=u.position.y,e.fz=u.position.z,i.push({index:d,x:u.position.x,y:u.position.y,z:u.position.z}))}}),i.length>0&&this.simulation.uploadNodePositions(i);let s=i.map(u=>({index:u.index,isPinned:!0}));this.simulation.updatePinnedNodes(s),this._enable&&this.simulation.alpha()<.1&&this.simulation.alpha(.3).restart(),this.graph.renderNeedsUpdate=!0}unpinNodes(t){if(!this.simulation)return;let o=this.simulation.nodes(),i=[];for(let s of t){let u=this.nodeIdToIndex.get(s);if(u===void 0)continue;let d=this.graph.layoutNodes[u];d&&(d.pinned=!1);let r=o[u];r&&(r.fx=null,r.fy=null,r.fz=null),i.push({index:u,isPinned:!1})}i.length>0&&this.simulation.updatePinnedNodes(i),this._enable&&this.simulation.alpha()<.05&&this.simulation.alpha(.15).restart(),this.graph.renderNeedsUpdate=!0}set enable(t){this._enable=t,!t&&this.simulation&&this.simulation.stop(),this._isFinish=!t,this.graph.renderNeedsUpdate=t}get enable(){return this._enable}get isFinish(){return this._isFinish}setExpectedNodeCount(t){}clearExpectedNodeCount(){}updateGraph(t,o,i=!1){this.startLayout()}destroy(){this.cancelDimensionTransition(),this.simulation&&(this.simulation.stop(),this.simulation.dispose(),this.simulation=null)}transitionDimensions(t,o=600){(this.params.dimensions??3)!==t&&(t===2?this.transition3Dto2D(o):this.transition2Dto3D())}transition3Dto2D(t){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 t=this.simulation?this.simulation.nodes():[];if(this.simulation&&t.length>0)for(let i=0;i<Math.min(3,t.length);i++){let s=t[i]}let o=this.graph.layoutNodes||[];if(o.length>0){for(let i=0;i<Math.min(3,o.length);i++){let s=o[i]}if(this.simulation&&t.length>0)for(let i=0;i<Math.min(3,Math.min(t.length,o.length));i++){let s=t[i],u=o.find(d=>d.id===s.id);if(u){let d=Math.abs((s.x??0)-u.position.x)<.001&&Math.abs((s.y??0)-u.position.y)<.001&&Math.abs((s.z??0)-u.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(t=5){return this.simulation?this.simulation.debugPositions(t):null}setSkipCPUReadback(t){this.skipCPUPositionUpdate=t,this.simulation&&this.simulation.setSkipCPUReadback(t)}readBackPositions(){if(this.simulation){this.simulation.readBackPositions();let t=this.simulation.nodes(),o=this.params.dimensions??3;t.forEach(i=>{let s=this.nodeIdToIndex.get(i.id);if(s!==void 0&&s<this.graph.layoutNodes.length){let u=this.graph.layoutNodes[s];u&&(u.position.x=i.x??0,u.position.y=i.y??0,u.position.z=o>2?i.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 t=this.simulation.nodes();if(t.length===0)return;let o=1/0,i=-1/0,s=0,u=0,d=[];t.forEach(p=>{let M=p.z||0;o=Math.min(o,M),i=Math.max(i,M),s+=M,u++,d.push(M)});let r=s/u,e=i-o,g=0;d.forEach(p=>{g+=Math.pow(p-r,2)});let f=Math.sqrt(g/u),w=e*.1,x=d.filter(p=>Math.abs(p-o)<w).length,v=d.filter(p=>Math.abs(p-i)<w).length,h=(x+v)/u}},Oe=class{constructor(t){this.c=t,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(t){this.c.pinNodes(t)}unpinNodes(t){this.c.unpinNodes(t)}transitionDimensions(t,o){this.c.transitionDimensions(t,o)}getDimensions(){return this.c.getDimensions()}updateOption(t,o){this.c.updateLayoutOption(t,o)}};function Tt(t){let{backend:o="auto",renderer:i,config:s,graph:u,autoStart:d=!0}=t,r;o==="webgpu"?Me()?r="webgpu":(console.warn('[createForceLayout] backend="webgpu" requested but navigator.gpu is unavailable; falling back to WebGL.'),r="webgl"):o==="webgl"?r="webgl":r=Me()?"webgpu":"webgl";let e=u??{layoutNodes:[],layoutEdges:[],renderNeedsUpdate:!0};if(r==="webgpu"){let g=new Ue(e);g.config(s);let f=new He(g);return d&&g.startLayout(),{controller:g,adapter:f,backend:"webgpu"}}else{let g=new qe(e,i);g.config(s);let f=new Oe(g);return d&&g.startLayout(),{controller:g,adapter:f,backend:"webgl"}}}function St(t,o){let i=new Map(t.nodes.map(r=>[r.id,{...r}])),s=new Map(t.edges.map(r=>[r.id,{...r}]));for(let r of o.addNodes??[])i.set(r.id,r);for(let r of o.addEdges??[])s.set(r.id,r);for(let r of o.updateNodes??[]){let e=i.get(r.id);e&&i.set(r.id,{...e,...r.changes})}for(let r of o.updateEdges??[]){let e=s.get(r.id);e&&s.set(r.id,{...e,...r.changes})}for(let r of o.removeNodeIds??[])i.delete(r);for(let r of o.removeEdgeIds??[])s.delete(r);for(let r of o.positionPatches??[]){let e=i.get(r.id);e&&i.set(r.id,{...e,position:r.position})}for(let r of o.pinPatches??[]){let e=i.get(r.id);if(e){let g={...e,pinned:r.pinned};r.position&&(g.position=r.position),i.set(r.id,g)}}let u=Array.from(i.values()).map((r,e)=>({...r,index:e})),d=Array.from(s.values()).map((r,e)=>({...r,index:e}));return{...t,version:o.graphVersion,nodes:u,edges:d}}var zt=class{constructor(t,o,i={}){this.mode="gpu",this._status="idle",this._snapshot=null,this._tickCount=0,this._listeners=new Map,this.id=t,this.controller=o,this._settings={dimensions:3,...i}}get status(){return this._status}getCapabilities(){return{mode:"gpu",supportsGpuTexture:!0,supportsCpuReadback:!1,supportsIncrementalDelta:!1,supportsPinning:!0,supportsDimensions:!0}}init(t,o){this._status!=="disposed"&&(this._snapshot=t,o&&(this._settings={...this._settings,...o}),this._feedSnapshotToController(t),this._status="idle")}applyDelta(t){if(!this._snapshot||this._status==="disposed")return;this._snapshot=St(this._snapshot,t);let o=this._status==="running";this._feedSnapshotToController(this._snapshot),o&&this._controllerStart()}tick(t){this._tickCount++,this.controller.tick&&this.controller.tick();let o=this._readNeedsUpdate(),i={tick:this._tickCount,didChangePositions:o,alpha:void 0};return this._emit("tick",i),i}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(t){this._settings={...this._settings,...t}}setDimensions(t){this._settings={...this._settings,dimensions:t},typeof this.controller.transitionDimensions=="function"&&this.controller.transitionDimensions(t)}getReadback(){return{positions:null,texture:this.controller.getPositionTexture(),textureSize:this.controller.getTextureSize(),spaceSize:this.controller.getSpaceSize()}}getNodePosition(t){return null}setNodePosition(t,o){}pinNodes(t){this._status!=="disposed"&&typeof this.controller.pinNodes=="function"&&this.controller.pinNodes(t)}unpinNodes(t){this._status!=="disposed"&&typeof this.controller.unpinNodes=="function"&&this.controller.unpinNodes(t)}on(t,o){return this._listeners.has(t)||this._listeners.set(t,new Set),this._listeners.get(t).add(o),()=>this._listeners.get(t)?.delete(o)}_feedSnapshotToController(t){this._settings={...this._settings,dimensions:t.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(t,o){this._listeners.get(t)?.forEach(i=>i(o))}};export{qe as GPUForceLayoutController,zt as GPUForceLayoutEngine,Oe as GPULayoutControllerAdapter,Ue as WebGPUForceLayoutController,He as WebGPULayoutControllerAdapter,Tt as createForceLayout,Me as isWebGPUAvailable};
|
|
903
|
+
//# sourceMappingURL=layout-gpu.mjs.map
|