@kineviz/gl 0.7.0 → 0.8.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.
@@ -0,0 +1,1538 @@
1
+ function y(l){return Math.min(512,Math.max(8,2**Math.ceil(Math.log2(2*Math.sqrt(Math.max(1,l))))))}function V(l){return Math.log2(y(l)/8)+1}function B(l){let e=l<=16384?32:l<=65536?16:8,t=y(l)**2*8,n=Math.min(16e5/Math.max(1,l),33554432/t),i=Math.min(64,Math.max(8,2**Math.floor(Math.log2(n))));return Math.min(e,i)}function I(l,e,t){return t&&l!==e-1?2:1}function k(l){return 2*4096/y(l)}function C(l){return Math.max(1,Math.ceil(Math.sqrt(l)))}function _(l){let e=l>>>0;return()=>{e=e+1831565813>>>0;let t=e;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}function G(l){return 1-Math.pow(.001,1/Math.max(1,l))}function z(l,e,t,n){let i=e.length>>1,o=new Uint32Array(l),s=new Uint8Array(i);for(let a=0;a<i;a++){let h=e[a*2],d=e[a*2+1];h>=l||d>=l||h===d||(s[a]=1,o[h]++,o[d]++)}let r=a=>{let h=new Uint32Array(l+1);for(let c=0;c<i;c++)s[c]&&h[e[c*2+a]+1]++;for(let c=0;c<l;c++)h[c+1]+=h[c];let d=h[l],p=C(d),u=new Float32Array(p*p*4),A=h.slice(0,l);for(let c=0;c<i;c++){if(!s[c])continue;let m=e[c*2+a],x=e[c*2+(1-a)],T=A[m]++,E=o[x],N=o[m],O=E+N;u[T*4]=x,u[T*4+1]=n(),u[T*4+2]=O!==0?E/O:.5,u[T*4+3]=Math.sqrt(1/Math.max(Math.min(E,N),1))}let f=new Float32Array(t*t*4);for(let c=0;c<l;c++)f[c*4]=h[c],f[c*4+1]=h[c+1]-h[c];return{info:f,entries:u,entriesSide:p,entryCount:d}};return[r(0),r(1)]}var F={repulsion:1,gravity:.25,linkSpring:1,linkDistRandomVariationRange:[1,1.2],friction:.85,decay:Math.round(Math.log(.001)/Math.log(1-.01)),alpha:1};function X(l){return Math.min(4096/4,10*Math.sqrt(Math.max(1,l)))}var ae=-.01,he=.1,ue=.5;function W(l){let e={...F,linkDistRandomVariationRange:[...F.linkDistRandomVariationRange]};S(l.charge)&&(e.repulsion=Math.max(0,-l.charge/-ae*F.repulsion)),S(l.gravity)&&(e.gravity=Math.max(0,l.gravity/he*F.gravity)),S(l.linkStrength)&&(e.linkSpring=Math.max(0,l.linkStrength)),S(l.alpha)&&l.alpha>0&&(e.alpha=Math.min(1,l.alpha)),S(l.alphaDecay)&&l.alphaDecay>0&&l.alphaDecay<1&&(e.decay=Math.max(1,Math.round(Math.log(.001)/Math.log(1-l.alphaDecay))));let t=S(l.linkDistance)&&l.linkDistance>0?l.linkDistance:ue;return{params:e,scale:t/10}}function S(l){return typeof l=="number"&&Number.isFinite(l)}var g=`#version 300 es
2
+ precision highp float;
3
+ precision highp int;
4
+ precision highp sampler2D;
5
+ precision highp sampler2DArray;
6
+ `,R=`
7
+ ivec2 pointTexel(int i, int size) { return ivec2(i % size, i / size); }
8
+ `,D=`
9
+ uniform sampler2D dataBoundsTexture; // [originX, originY, extent, 1 / extent]
10
+ ivec2 gridCell(vec2 worldPosition, float cellsPerAxis) {
11
+ vec4 dataBox = texelFetch(dataBoundsTexture, ivec2(0), 0);
12
+ float cellsPerUnit = dataBox.w * cellsPerAxis;
13
+ ivec2 lastCell = ivec2(int(cellsPerAxis) - 1);
14
+ return clamp(ivec2(floor((worldPosition - dataBox.xy) * cellsPerUnit)), ivec2(0), lastCell);
15
+ }
16
+ `,H=`
17
+ vec2 pairwiseVelocity(vec2 position, vec2 otherPosition, vec2 randomDir, float alpha, float repulsion) {
18
+ vec2 distVector = position - otherPosition;
19
+ float l = dot(distVector, distVector);
20
+ if (l <= 0.0) {
21
+ // Coincident points have no separation direction; kick along this point's
22
+ // own random vector so a pile disperses.
23
+ distVector = randomDir;
24
+ l = dot(distVector, distVector);
25
+ if (l <= 0.0) return vec2(0.0);
26
+ }
27
+ if (l < 1.0) l = sqrt(l);
28
+ float addV = alpha * repulsion / sqrt(l);
29
+ return addV * normalize(distVector);
30
+ }
31
+ `,v=`${g}
32
+ void main() {
33
+ vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));
34
+ gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
35
+ }
36
+ `,$=`${g}
37
+ uniform sampler2D source;
38
+ out vec4 fragColor;
39
+ void main() { fragColor = texelFetch(source, ivec2(gl_FragCoord.xy), 0); }
40
+ `,q=`${g}
41
+ uniform sampler2D positionsTexture;
42
+ uniform sampler2D velocityTexture;
43
+ uniform sampler2D pinnedTexture;
44
+ uniform float friction;
45
+ uniform float maxStep;
46
+ out vec4 fragColor;
47
+
48
+ bool isFiniteVector(vec2 v) {
49
+ uvec2 exponent = floatBitsToUint(v) & 0x7f800000u;
50
+ return all(notEqual(exponent, uvec2(0x7f800000u)));
51
+ }
52
+
53
+ void main() {
54
+ ivec2 texel = ivec2(gl_FragCoord.xy);
55
+ vec4 position = texelFetch(positionsTexture, texel, 0);
56
+ vec4 velocity = texelFetch(velocityTexture, texel, 0);
57
+ if (texelFetch(pinnedTexture, texel, 0).r > 0.5 || !isFiniteVector(velocity.rg)) {
58
+ fragColor = position;
59
+ return;
60
+ }
61
+ float largestVelocity = max(abs(velocity.r), abs(velocity.g));
62
+ float largest = largestVelocity * abs(friction);
63
+ if (largest > 0.5 * maxStep) {
64
+ vec2 scaled = largestVelocity > 1.0e30 ? velocity.rg * 1.0e-30 : velocity.rg;
65
+ vec2 direction = scaled / max(abs(scaled.x), abs(scaled.y)) * sign(friction);
66
+ float directionLength = length(direction);
67
+ if (largest > maxStep / directionLength) {
68
+ position.rg += direction * (maxStep / directionLength);
69
+ fragColor = position;
70
+ return;
71
+ }
72
+ }
73
+ position.rg += velocity.rg * friction;
74
+ fragColor = position;
75
+ }
76
+ `,Y=`${g}
77
+ uniform sampler2D positionsTexture;
78
+ uniform float gravity;
79
+ uniform float alpha;
80
+ out vec4 fragColor;
81
+ void main() {
82
+ vec2 position = texelFetch(positionsTexture, ivec2(gl_FragCoord.xy), 0).rg;
83
+ vec2 distVector = -position;
84
+ float dist = length(distVector);
85
+ vec2 velocity = vec2(0.0);
86
+ if (dist > 0.0) velocity = (alpha * gravity * dist * 0.1) * (distVector / dist);
87
+ fragColor = vec4(velocity, 0.0, 0.0);
88
+ }
89
+ `,Q=`${g}
90
+ uniform sampler2D positionsTexture;
91
+ uniform sampler2D linkInfoTexture;
92
+ uniform sampler2D linkTexture;
93
+ uniform float linkSpring;
94
+ uniform float linkDistance;
95
+ uniform vec2 linkDistRandomVariationRange;
96
+ uniform float alpha;
97
+ uniform int pointsTextureSize;
98
+ uniform int linksTextureSize;
99
+ out vec4 fragColor;
100
+ ${R}
101
+ void main() {
102
+ ivec2 texel = ivec2(gl_FragCoord.xy);
103
+ vec2 position = texelFetch(positionsTexture, texel, 0).rg;
104
+ vec4 info = texelFetch(linkInfoTexture, texel, 0);
105
+ int first = int(info.r);
106
+ int amount = int(info.g);
107
+ vec2 velocity = vec2(0.0);
108
+ for (int k = 0; k < amount; k += 1) {
109
+ vec4 link = texelFetch(linkTexture, pointTexel(first + k, linksTextureSize), 0);
110
+ float restLength = (link.g * (linkDistRandomVariationRange.y - linkDistRandomVariationRange.x)
111
+ + linkDistRandomVariationRange.x) * linkDistance;
112
+ vec2 other = texelFetch(positionsTexture, pointTexel(int(link.r), pointsTextureSize), 0).rg;
113
+ vec2 d = other - (position + velocity);
114
+ float l = length(d);
115
+ l = max(l, restLength * 0.99);
116
+ l = (l - restLength) / l;
117
+ l *= linkSpring * alpha * link.a * link.b;
118
+ velocity += d * l;
119
+ }
120
+ fragColor = vec4(velocity, 0.0, 0.0);
121
+ }
122
+ `,j=`${g}
123
+ uniform sampler2D positionsTexture;
124
+ uniform sampler2D randomValues;
125
+ uniform int pointsTextureSize;
126
+ uniform int pointsNumber;
127
+ uniform float alpha;
128
+ uniform float repulsion;
129
+ uniform float maxStep;
130
+ out vec4 fragColor;
131
+ ${R}
132
+ ${H}
133
+ void main() {
134
+ ivec2 texel = ivec2(gl_FragCoord.xy);
135
+ int selfIndex = texel.y * pointsTextureSize + texel.x;
136
+ if (selfIndex >= pointsNumber) { fragColor = vec4(0.0); return; }
137
+ vec2 position = texelFetch(positionsTexture, texel, 0).rg;
138
+ vec2 random = texelFetch(randomValues, texel, 0).rg;
139
+ vec2 nearVelocity = vec2(0.0);
140
+ vec2 farVelocity = vec2(0.0);
141
+ float nearRadius2 = maxStep * maxStep;
142
+ for (int i = 0; i < pointsNumber; i += 1) {
143
+ if (i == selfIndex) continue;
144
+ vec2 other = texelFetch(positionsTexture, pointTexel(i, pointsTextureSize), 0).rg;
145
+ vec2 d = position - other;
146
+ vec2 v = pairwiseVelocity(position, other, random, alpha, repulsion);
147
+ if (dot(d, d) < nearRadius2) nearVelocity += v; else farVelocity += v;
148
+ }
149
+ nearVelocity += nearVelocity * random;
150
+ float speed = length(nearVelocity);
151
+ if (speed > maxStep) nearVelocity *= maxStep / speed;
152
+ fragColor = vec4(farVelocity + nearVelocity, 0.0, 0.0);
153
+ }
154
+ `,K=`${g}
155
+ uniform sampler2D positionsTexture;
156
+ uniform int pointsTextureSize;
157
+ out vec4 vColor;
158
+ ${R}
159
+ void main() {
160
+ vec2 p = texelFetch(positionsTexture, pointTexel(gl_VertexID, pointsTextureSize), 0).rg;
161
+ vColor = vec4(-p, p);
162
+ gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
163
+ gl_PointSize = 1.0;
164
+ }
165
+ `,M=`${g}
166
+ in vec4 vColor;
167
+ out vec4 fragColor;
168
+ void main() { fragColor = vColor; }
169
+ `,Z=`${g}
170
+ uniform sampler2D partialTexture;
171
+ uniform float minExtent;
172
+ uniform float shiftCellsPerAxis;
173
+ uniform vec2 shiftOffset;
174
+ out vec4 bounds;
175
+ void main() {
176
+ vec4 partial = texelFetch(partialTexture, ivec2(0), 0);
177
+ vec2 lo = -partial.xy;
178
+ vec2 hi = partial.zw;
179
+ if (hi.x < lo.x) { lo = vec2(0.0); hi = vec2(0.0); }
180
+ vec2 centre = 0.5 * (lo + hi);
181
+ float extent = max(max(hi.x - lo.x, hi.y - lo.y), minExtent);
182
+ vec2 origin = centre - 0.5 * extent;
183
+ float cell = extent / (shiftCellsPerAxis - 1.0);
184
+ origin -= shiftOffset * cell;
185
+ extent += cell;
186
+ bounds = vec4(origin, extent, 1.0 / extent);
187
+ }
188
+ `,J=`${g}
189
+ uniform sampler2D positionsTexture;
190
+ uniform int pointsTextureSize;
191
+ uniform float levelGridSize;
192
+ out vec4 vColor;
193
+ ${R}
194
+ ${D}
195
+ void main() {
196
+ vec2 p = texelFetch(positionsTexture, pointTexel(gl_VertexID, pointsTextureSize), 0).rg;
197
+ vColor = vec4(p, 1.0, 0.0);
198
+ ivec2 cell = gridCell(p, levelGridSize);
199
+ gl_Position = vec4(2.0 * (vec2(cell) + 0.5) / levelGridSize - 1.0, 0.0, 1.0);
200
+ gl_PointSize = 1.0;
201
+ }
202
+ `,ee=`${g}
203
+ uniform sampler2D positionsTexture;
204
+ uniform sampler2D levelTexture;
205
+ uniform float levelGridSize;
206
+ uniform float isFirstLevel;
207
+ uniform float alpha;
208
+ uniform float repulsion;
209
+ uniform float shellRadius;
210
+ uniform float parentShellRadius;
211
+ out vec4 fragColor;
212
+ ${D}
213
+ vec2 cellVelocity(ivec2 cell, vec2 position) {
214
+ vec4 centermass = texelFetch(levelTexture, cell, 0);
215
+ if (centermass.b <= 0.0) return vec2(0.0);
216
+ vec2 distVector = position - centermass.rg / centermass.b;
217
+ float l = dot(distVector, distVector);
218
+ if (l <= 0.0) return vec2(0.0);
219
+ if (l < 1.0) l = sqrt(l);
220
+ return (alpha * repulsion * centermass.b / sqrt(l)) * normalize(distVector);
221
+ }
222
+ void main() {
223
+ vec2 position = texelFetch(positionsTexture, ivec2(gl_FragCoord.xy), 0).rg;
224
+ int gridSize = int(levelGridSize);
225
+ ivec2 pointCell = gridCell(position, levelGridSize);
226
+ vec2 velocity = vec2(0.0);
227
+ int shell = int(shellRadius);
228
+ if (isFirstLevel > 0.5) {
229
+ for (int j = 0; j < gridSize; j += 1) {
230
+ for (int i = 0; i < gridSize; i += 1) {
231
+ ivec2 cell = ivec2(i, j);
232
+ ivec2 cellDist = abs(cell - pointCell);
233
+ if (max(cellDist.x, cellDist.y) <= shell) continue;
234
+ velocity += cellVelocity(cell, position);
235
+ }
236
+ }
237
+ } else {
238
+ int parentShell = int(parentShellRadius);
239
+ int blockSize = 2 * (2 * parentShell + 1);
240
+ ivec2 base = (pointCell / 2) * 2 - 2 * parentShell;
241
+ for (int j = 0; j < blockSize; j += 1) {
242
+ for (int i = 0; i < blockSize; i += 1) {
243
+ ivec2 cell = base + ivec2(i, j);
244
+ if (any(lessThan(cell, ivec2(0))) || any(greaterThanEqual(cell, ivec2(gridSize)))) continue;
245
+ ivec2 cellDist = abs(cell - pointCell);
246
+ if (max(cellDist.x, cellDist.y) <= shell) continue;
247
+ velocity += cellVelocity(cell, position);
248
+ }
249
+ }
250
+ }
251
+ fragColor = vec4(velocity, 0.0, 0.0);
252
+ }
253
+ `,te=`${g}
254
+ uniform sampler2D positionsTexture;
255
+ uniform sampler2DArray previousSlot;
256
+ uniform int pointsTextureSize;
257
+ uniform float levelGridSize;
258
+ uniform float hasPreviousSlot;
259
+ uniform float randomSeed;
260
+ uniform int previousLayer;
261
+ out vec2 slotData;
262
+ ${R}
263
+ ${D}
264
+ void main() {
265
+ int index = gl_VertexID;
266
+ vec2 p = texelFetch(positionsTexture, pointTexel(index, pointsTextureSize), 0).rg;
267
+ uint h = uint(index) ^ floatBitsToUint(randomSeed);
268
+ h ^= h >> 16u;
269
+ h *= 0x7feb352du;
270
+ h ^= h >> 15u;
271
+ h *= 0x846ca68bu;
272
+ h ^= h >> 16u;
273
+ float hashValue = (float(h >> 8u) + 0.5) / 16777216.0;
274
+ hashValue = 0.001 + hashValue * 0.998;
275
+ ivec2 cell = gridCell(p, levelGridSize);
276
+ if (hasPreviousSlot > 0.5) {
277
+ vec2 previous = texelFetch(previousSlot, ivec3(cell, previousLayer), 0).rg;
278
+ if (previous.x < 0.0 || hashValue <= previous.y) {
279
+ slotData = vec2(-1.0, 1.0);
280
+ gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
281
+ gl_PointSize = 1.0;
282
+ return;
283
+ }
284
+ }
285
+ slotData = vec2(float(index), hashValue);
286
+ gl_Position = vec4(2.0 * (vec2(cell) + 0.5) / levelGridSize - 1.0, hashValue * 2.0 - 1.0, 1.0);
287
+ gl_PointSize = 1.0;
288
+ }
289
+ `,ne=`${g}
290
+ in vec2 slotData;
291
+ out vec4 fragColor;
292
+ void main() { fragColor = vec4(slotData, 0.0, 0.0); }
293
+ `,ie=`${g}
294
+ uniform sampler2D positionsTexture;
295
+ uniform sampler2D levelTexture;
296
+ uniform sampler2D randomValues;
297
+ uniform sampler2DArray slotsEven;
298
+ uniform sampler2DArray slotsOdd;
299
+ uniform int pointsTextureSize;
300
+ uniform float levelGridSize;
301
+ uniform float maxStep;
302
+ uniform float alpha;
303
+ uniform float repulsion;
304
+ uniform int slotCount;
305
+ out vec4 fragColor;
306
+ ${R}
307
+ ${D}
308
+ ${H}
309
+ void main() {
310
+ ivec2 texel = ivec2(gl_FragCoord.xy);
311
+ vec2 position = texelFetch(positionsTexture, texel, 0).rg;
312
+ float selfIndex = float(texel.y * pointsTextureSize + texel.x);
313
+ vec2 random = texelFetch(randomValues, texel, 0).rg;
314
+ int gridSize = int(levelGridSize);
315
+ ivec2 pointCell = gridCell(position, levelGridSize);
316
+ vec2 velocity = vec2(0.0);
317
+ for (int j = -1; j <= 1; j += 1) {
318
+ for (int i = -1; i <= 1; i += 1) {
319
+ ivec2 cell = pointCell + ivec2(i, j);
320
+ if (any(lessThan(cell, ivec2(0))) || any(greaterThanEqual(cell, ivec2(gridSize)))) continue;
321
+ float others = texelFetch(levelTexture, cell, 0).b - ((i == 0 && j == 0) ? 1.0 : 0.0);
322
+ if (others <= 0.0) continue;
323
+ vec2 pairSum = vec2(0.0);
324
+ float sampled = 0.0;
325
+ for (int s = 0; s < slotCount; s += 1) {
326
+ ivec3 layer = ivec3(cell, s >> 1);
327
+ vec2 slot = (s & 1) == 0 ? texelFetch(slotsEven, layer, 0).rg : texelFetch(slotsOdd, layer, 0).rg;
328
+ if (slot.x < 0.0) break;
329
+ if (slot.x == selfIndex) continue;
330
+ vec2 other = texelFetch(positionsTexture, pointTexel(int(slot.x), pointsTextureSize), 0).rg;
331
+ sampled += 1.0;
332
+ pairSum += pairwiseVelocity(position, other, random, alpha, repulsion);
333
+ }
334
+ if (sampled > 0.0) velocity += (others / sampled) * pairSum;
335
+ }
336
+ }
337
+ velocity += velocity * random;
338
+ float speed = length(velocity);
339
+ if (speed > maxStep) velocity *= maxStep / speed;
340
+ fragColor = vec4(velocity, 0.0, 0.0);
341
+ }
342
+ `;var b=class extends Error{},L=class{constructor(e){this.programs=new Map;this.params={...F};this.alpha=0;this.random=_(1);this.n=0;this.side=1;this.positions=null;this.velocity=null;this.pinned=null;this.randomValues=null;this.links=null;this.boundsPartial=null;this.boundsFinal=null;this.levels=[];this.slotArrays=null;this.slotFbos=[];this.slotDepth=null;this.slotCount=0;this.readbackBuffer=new Float32Array(0);this.pbo=null;this.pboBytes=0;this.fence=null;this.pendingCount=0;if(this.gl=e,!e.getExtension("EXT_color_buffer_float"))throw new b("EXT_color_buffer_float is not available");if(!e.getExtension("EXT_float_blend"))throw new b("EXT_float_blend is not available");let t=e.createVertexArray();if(!t)throw new b("cannot create a vertex array");this.vao=t,e.disable(e.DEPTH_TEST),e.disable(e.BLEND),e.disable(e.DITHER),e.getExtension("KHR_parallel_shader_compile"),this.buildPrograms([["update",v,q],["copy",v,$],["gravity",v,Y],["link",v,Q],["allPairs",v,j],["boundsPoint",K,M],["boundsFinal",v,Z],["levelPoint",J,M],["forceLevel",v,ee],["slots",te,ne],["nearField",v,ie]])}get pointCount(){return this.n}get currentAlpha(){return this.alpha}get settled(){return this.alpha<.001}setParams(e){this.params={...e,linkDistRandomVariationRange:[...e.linkDistRandomVariationRange]}}setAlpha(e){this.alpha=e}setGraph(e,t,n,i){let o=this.gl;this.dropPendingRead(),this.random=_(i);let s=e.length>>1,r=C(s);(s!==this.n||r!==this.side||!this.positions)&&(this.disposeGraph(),this.n=s,this.side=r,this.positions=[this.target(r,r),this.target(r,r)],this.velocity=this.target(r,r),this.pinned=this.dataTexture(r,r,null),this.randomValues=this.dataTexture(r,r,null),this.allocateGrid()),this.n=s;let a=new Float32Array(r*r*4);for(let u=0;u<s;u++)a[u*4]=e[u*2],a[u*4+1]=e[u*2+1];this.upload(this.positions[0].texture,r,r,a),this.upload(this.positions[1].texture,r,r,a);let h=new Float32Array(r*r*4);for(let u=0;u<s;u++)h[u*4]=t[u]?1:0;this.upload(this.pinned,r,r,h);let d=new Float32Array(r*r*4);for(let u=0;u<r*r;u++)d[u*4]=(this.random()*2-1)*1e-5,d[u*4+1]=(this.random()*2-1)*1e-5;if(this.upload(this.randomValues,r,r,d),this.links)for(let u of this.links)o.deleteTexture(u.info),o.deleteTexture(u.entries);let p=z(s,n,r,this.random);this.links=[this.linkTextures(p[0]),this.linkTextures(p[1])]}setPins(e,t,n){let i=this.gl;if(!this.positions||!this.pinned)return;let o=new Float32Array(4);for(let s=0;s<e.length;s++){let r=e[s];if(r>=this.n)continue;let a=r%this.side,h=Math.floor(r/this.side);if(o[0]=n[s]?1:0,o[1]=o[2]=o[3]=0,i.bindTexture(i.TEXTURE_2D,this.pinned),i.texSubImage2D(i.TEXTURE_2D,0,a,h,1,1,i.RGBA,i.FLOAT,o),n[s]){o[0]=t[s*2],o[1]=t[s*2+1];for(let d of this.positions)i.bindTexture(i.TEXTURE_2D,d.texture),i.texSubImage2D(i.TEXTURE_2D,0,a,h,1,1,i.RGBA,i.FLOAT,o)}}i.bindTexture(i.TEXTURE_2D,null)}step(){if(!this.positions||this.n===0)return;let{params:e}=this;if(e.gravity>0&&(this.runGravity(),this.integrate()),e.repulsion>0&&(this.runManyBody(),this.integrate()),this.links&&e.linkSpring>0)for(let t of this.links)t.count!==0&&(this.runLinks(t),this.integrate());this.alpha+=(0-this.alpha)*G(e.decay)}readPositions(e){let t=this.gl,n=this.n,i=e&&e.length>=n*2?e:new Float32Array(n*2);if(!this.positions||n===0)return i;let o=Math.ceil(n/this.side),s=this.side*o*4;this.readbackBuffer.length<s&&(this.readbackBuffer=new Float32Array(s)),t.bindFramebuffer(t.FRAMEBUFFER,this.positions[0].fbo),t.readPixels(0,0,this.side,o,t.RGBA,t.FLOAT,this.readbackBuffer),t.bindFramebuffer(t.FRAMEBUFFER,null);let r=this.readbackBuffer;for(let a=0;a<n;a++)i[a*2]=r[a*4],i[a*2+1]=r[a*4+1];return i}beginRead(){let e=this.gl,t=this.n;if(this.dropPendingRead(),!this.positions||t===0)return;let n=Math.ceil(t/this.side),i=this.side*n*16;!this.pbo||this.pboBytes<i?(this.pbo&&e.deleteBuffer(this.pbo),this.pbo=e.createBuffer(),e.bindBuffer(e.PIXEL_PACK_BUFFER,this.pbo),e.bufferData(e.PIXEL_PACK_BUFFER,i,e.STREAM_READ),this.pboBytes=i):e.bindBuffer(e.PIXEL_PACK_BUFFER,this.pbo),e.bindFramebuffer(e.FRAMEBUFFER,this.positions[0].fbo),e.readPixels(0,0,this.side,n,e.RGBA,e.FLOAT,0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindBuffer(e.PIXEL_PACK_BUFFER,null),this.fence=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0),e.flush(),this.pendingCount=t}get readPending(){return this.fence!==null}get readReady(){let e=this.gl;return this.fence?e.getSyncParameter(this.fence,e.SYNC_STATUS)===e.SIGNALED:!1}finishRead(e){let t=this.gl;if(!this.fence||!this.pbo)return null;let n=this.pendingCount,i=e&&e.length>=n*2?e:new Float32Array(n*2),o=Math.ceil(n/this.side)*this.side*4;this.readbackBuffer.length<o&&(this.readbackBuffer=new Float32Array(o)),t.bindBuffer(t.PIXEL_PACK_BUFFER,this.pbo),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,this.readbackBuffer,0,o),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),this.dropPendingRead();let s=this.readbackBuffer;for(let r=0;r<n;r++)i[r*2]=s[r*4],i[r*2+1]=s[r*4+1];return i}dropPendingRead(){this.fence&&this.gl.deleteSync(this.fence),this.fence=null,this.pendingCount=0}dispose(){this.dropPendingRead(),this.pbo&&this.gl.deleteBuffer(this.pbo),this.pbo=null,this.disposeGraph();let e=this.gl;for(let t of this.programs.values())e.deleteProgram(t.program);this.programs.clear(),e.deleteVertexArray(this.vao)}get current(){return this.positions[0]}integrate(){let e=this.use("update");this.bindTarget(this.positions[1]),this.tex(e,"positionsTexture",0,this.current.texture),this.tex(e,"velocityTexture",1,this.velocity.texture),this.tex(e,"pinnedTexture",2,this.pinned),this.f(e,"friction",this.params.friction),this.f(e,"maxStep",4096),this.drawQuad(),this.positions=[this.positions[1],this.positions[0]]}runGravity(){let e=this.use("gravity");this.bindTarget(this.velocity),this.tex(e,"positionsTexture",0,this.current.texture),this.f(e,"gravity",this.params.gravity),this.f(e,"alpha",this.alpha),this.drawQuad()}runLinks(e){let t=this.use("link");this.bindTarget(this.velocity),this.tex(t,"positionsTexture",0,this.current.texture),this.tex(t,"linkInfoTexture",1,e.info),this.tex(t,"linkTexture",2,e.entries),this.f(t,"linkSpring",this.params.linkSpring),this.f(t,"linkDistance",10);let[n,i]=this.params.linkDistRandomVariationRange;this.gl.uniform2f(this.loc(t,"linkDistRandomVariationRange"),n,i),this.f(t,"alpha",this.alpha),this.i(t,"pointsTextureSize",this.side),this.i(t,"linksTextureSize",e.entriesSide),this.drawQuad()}runManyBody(){if(this.n<=4096){let e=this.use("allPairs");this.bindTarget(this.velocity),this.tex(e,"positionsTexture",0,this.current.texture),this.tex(e,"randomValues",1,this.randomValues),this.i(e,"pointsTextureSize",this.side),this.i(e,"pointsNumber",this.n),this.f(e,"alpha",this.alpha),this.f(e,"repulsion",this.params.repulsion),this.f(e,"maxStep",k(this.n)),this.drawQuad();return}this.drawBounds(),this.drawLevels(),this.drawSlots(),this.drawGridForces()}drawBounds(){let e=this.gl,t=this.use("boundsPoint");this.bindTarget(this.boundsPartial,[-1e30,-1e30,-1e30,-1e30]),this.tex(t,"positionsTexture",0,this.current.texture),this.i(t,"pointsTextureSize",this.side),e.enable(e.BLEND),e.blendEquation(e.MAX),e.blendFunc(e.ONE,e.ONE),e.drawArrays(e.POINTS,0,this.n),e.disable(e.BLEND),e.blendEquation(e.FUNC_ADD),t=this.use("boundsFinal"),this.bindTarget(this.boundsFinal),this.tex(t,"partialTexture",0,this.boundsPartial.texture),this.f(t,"minExtent",y(this.n)*.25),this.f(t,"shiftCellsPerAxis",8),e.uniform2f(this.loc(t,"shiftOffset"),this.random(),this.random()),this.drawQuad()}drawLevels(){let e=this.gl,t=this.use("levelPoint");this.tex(t,"positionsTexture",0,this.current.texture),this.tex(t,"dataBoundsTexture",1,this.boundsFinal.texture),this.i(t,"pointsTextureSize",this.side),e.enable(e.BLEND),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE);for(let n of this.levels)this.bindTarget(n,[0,0,0,0]),this.f(t,"levelGridSize",n.size),e.drawArrays(e.POINTS,0,this.n);e.disable(e.BLEND)}drawSlots(){let e=this.gl,t=this.levels[this.levels.length-1],n=this.use("slots");this.tex(n,"positionsTexture",0,this.current.texture),this.tex(n,"dataBoundsTexture",2,this.boundsFinal.texture),this.i(n,"pointsTextureSize",this.side),this.f(n,"levelGridSize",t.size),this.f(n,"randomSeed",this.random()),e.enable(e.DEPTH_TEST),e.depthFunc(e.LESS),e.depthMask(!0);for(let i=0;i<this.slotCount;i++)e.bindFramebuffer(e.FRAMEBUFFER,this.slotFbos[i]),e.viewport(0,0,t.size,t.size),e.clearColor(-1,1,0,0),e.clearDepth(1),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D_ARRAY,this.slotArrays[(i+1)%2]),e.uniform1i(this.loc(n,"previousSlot"),1),this.f(n,"hasPreviousSlot",i===0?0:1),this.i(n,"previousLayer",Math.max(0,i-1)>>1),e.drawArrays(e.POINTS,0,this.n);e.disable(e.DEPTH_TEST),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D_ARRAY,null)}drawGridForces(){let e=this.gl,t=this.levels.length,n=this.n<=25e3;this.bindTarget(this.velocity,[0,0,0,0]),e.enable(e.BLEND),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE);let i=this.use("forceLevel");this.tex(i,"positionsTexture",0,this.current.texture),this.tex(i,"dataBoundsTexture",2,this.boundsFinal.texture),this.f(i,"alpha",this.alpha),this.f(i,"repulsion",this.params.repulsion);for(let r=0;r<t;r++){let a=this.levels[r];this.tex(i,"levelTexture",1,a.texture),this.f(i,"levelGridSize",a.size),this.f(i,"isFirstLevel",r===0?1:0),this.f(i,"shellRadius",I(r,t,n)),this.f(i,"parentShellRadius",r===0?0:I(r-1,t,n)),this.drawQuad()}let o=this.levels[t-1],s=this.use("nearField");this.tex(s,"positionsTexture",0,this.current.texture),this.tex(s,"levelTexture",1,o.texture),this.tex(s,"dataBoundsTexture",2,this.boundsFinal.texture),this.tex(s,"randomValues",3,this.randomValues),e.activeTexture(e.TEXTURE4),e.bindTexture(e.TEXTURE_2D_ARRAY,this.slotArrays[0]),e.uniform1i(this.loc(s,"slotsEven"),4),e.activeTexture(e.TEXTURE5),e.bindTexture(e.TEXTURE_2D_ARRAY,this.slotArrays[1]),e.uniform1i(this.loc(s,"slotsOdd"),5),this.i(s,"pointsTextureSize",this.side),this.f(s,"levelGridSize",o.size),this.f(s,"maxStep",k(this.n)),this.f(s,"alpha",this.alpha),this.f(s,"repulsion",this.params.repulsion),this.i(s,"slotCount",this.slotCount),this.drawQuad(),e.disable(e.BLEND);for(let r of[e.TEXTURE4,e.TEXTURE5])e.activeTexture(r),e.bindTexture(e.TEXTURE_2D_ARRAY,null)}allocateGrid(){let e=this.gl;if(this.n<=4096)return;this.boundsPartial=this.target(1,1),this.boundsFinal=this.target(1,1);let t=V(this.n);for(let s=0;s<t;s++){let r=8*2**s;this.levels.push(this.target(r,r))}let n=y(this.n);this.slotCount=B(this.n);let i=Math.ceil(this.slotCount/2),o=[];for(let s=0;s<2;s++){let r=e.createTexture();e.bindTexture(e.TEXTURE_2D_ARRAY,r),e.texStorage3D(e.TEXTURE_2D_ARRAY,1,e.RG32F,n,n,i),this.nearest(e.TEXTURE_2D_ARRAY),o.push(r)}e.bindTexture(e.TEXTURE_2D_ARRAY,null),this.slotArrays=[o[0],o[1]],this.slotDepth=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,this.slotDepth),e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_COMPONENT24,n,n),e.bindRenderbuffer(e.RENDERBUFFER,null);for(let s=0;s<this.slotCount;s++){let r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTextureLayer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,this.slotArrays[s%2],0,s>>1),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,this.slotDepth),this.checkFramebuffer(),this.slotFbos.push(r)}e.bindFramebuffer(e.FRAMEBUFFER,null)}disposeGraph(){let e=this.gl,t=[...this.positions??[],this.velocity,this.boundsPartial,this.boundsFinal,...this.levels];for(let n of t)n&&(e.deleteFramebuffer(n.fbo),e.deleteTexture(n.texture));for(let n of[this.pinned,this.randomValues])n&&e.deleteTexture(n);if(this.links)for(let n of this.links)e.deleteTexture(n.info),e.deleteTexture(n.entries);for(let n of this.slotFbos)e.deleteFramebuffer(n);if(this.slotArrays)for(let n of this.slotArrays)e.deleteTexture(n);this.slotDepth&&e.deleteRenderbuffer(this.slotDepth),this.positions=null,this.velocity=this.boundsPartial=this.boundsFinal=null,this.pinned=this.randomValues=null,this.links=null,this.levels=[],this.slotFbos=[],this.slotArrays=null,this.slotDepth=null,this.slotCount=0,this.n=0}linkTextures(e){return{info:this.dataTexture(this.side,this.side,e.info),entries:this.dataTexture(e.entriesSide,e.entriesSide,e.entries),entriesSide:e.entriesSide,count:e.entryCount}}dataTexture(e,t,n){let i=this.gl,o=i.createTexture();return i.bindTexture(i.TEXTURE_2D,o),i.texStorage2D(i.TEXTURE_2D,1,i.RGBA32F,e,t),this.nearest(i.TEXTURE_2D),n&&i.texSubImage2D(i.TEXTURE_2D,0,0,0,e,t,i.RGBA,i.FLOAT,n),i.bindTexture(i.TEXTURE_2D,null),o}target(e,t){let n=this.gl,i=this.dataTexture(e,t,null),o=n.createFramebuffer();return n.bindFramebuffer(n.FRAMEBUFFER,o),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,i,0),this.checkFramebuffer(),n.bindFramebuffer(n.FRAMEBUFFER,null),{texture:i,fbo:o,size:e}}checkFramebuffer(){let e=this.gl,t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new b(`framebuffer incomplete (0x${t.toString(16)})`)}upload(e,t,n,i){let o=this.gl;o.bindTexture(o.TEXTURE_2D,e),o.texSubImage2D(o.TEXTURE_2D,0,0,0,t,n,o.RGBA,o.FLOAT,i),o.bindTexture(o.TEXTURE_2D,null)}nearest(e){let t=this.gl;t.texParameteri(e,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(e,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(e,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(e,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}buildPrograms(e){let t=this.gl,n=new Map,i=(r,a)=>{let h=n.get(a);return h||(h=t.createShader(r),t.shaderSource(h,a),t.compileShader(h),n.set(a,h)),h},o=[];for(let[r,a,h]of e){let d=i(t.VERTEX_SHADER,a),p=i(t.FRAGMENT_SHADER,h),u=t.createProgram();t.attachShader(u,d),t.attachShader(u,p),t.linkProgram(u),o.push([r,u,d,p])}let s=null;for(let[r,a,h,d]of o){if(!s&&!t.getProgramParameter(a,t.LINK_STATUS)){let p=[h,d].find(u=>!t.getShaderParameter(u,t.COMPILE_STATUS));s=p?`${r}: shader compile failed: ${t.getShaderInfoLog(p)}`:`${r}: program link failed: ${t.getProgramInfoLog(a)}`}this.programs.set(r,{program:a,uniforms:new Map})}for(let r of n.values())t.deleteShader(r);if(s){for(let r of this.programs.values())t.deleteProgram(r.program);throw this.programs.clear(),new b(s)}}use(e){let t=this.programs.get(e);return this.gl.useProgram(t.program),this.gl.bindVertexArray(this.vao),t}loc(e,t){let n=e.uniforms.get(t);return n===void 0&&(n=this.gl.getUniformLocation(e.program,t),e.uniforms.set(t,n)),n}f(e,t,n){this.gl.uniform1f(this.loc(e,t),n)}i(e,t,n){this.gl.uniform1i(this.loc(e,t),n)}tex(e,t,n,i){let o=this.gl;o.activeTexture(o.TEXTURE0+n),o.bindTexture(o.TEXTURE_2D,i),o.uniform1i(this.loc(e,t),n)}bindTarget(e,t){let n=this.gl;n.bindFramebuffer(n.FRAMEBUFFER,e.fbo),n.viewport(0,0,e.size,e.size),t&&(n.clearColor(t[0],t[1],t[2],t[3]),n.clear(n.COLOR_BUFFER_BIT))}drawQuad(){this.gl.drawArrays(this.gl.TRIANGLES,0,3)}};var ve=1;function xe(){let l={antialias:!1,depth:!1,stencil:!1,alpha:!1,preserveDrawingBuffer:!1,powerPreference:"high-performance"},e=null;if(typeof OffscreenCanvas<"u")e=new OffscreenCanvas(1,1).getContext("webgl2",l);else if(typeof document<"u"){let t=document.createElement("canvas");t.width=t.height=1,e=t.getContext("webgl2",l)}if(!e)throw new Error("WebGL2 is not available");return e}var P=class{constructor(e=xe,t=n=>new L(n)){this.onmessage=null;this.onerror=null;this.sim=null;this.generation=-1;this.terminated=!1;this.unread=0;let n=null;try{this.sim=t(e())}catch(i){n=i instanceof Error?i.message:String(i)}this.deliver(n===null?{type:"ready"}:{type:"error",message:n})}postMessage(e){let t=this.sim;if(!(!t||this.terminated))switch(e.type){case"graph":this.generation=e.generation,t.setGraph(e.xy,e.pinned,e.links,e.seed),t.setAlpha(e.alpha),this.unread=0;break;case"params":t.setParams(e.params);break;case"alpha":t.setAlpha(e.alpha);break;case"pins":t.setPins(e.indices,e.xy,e.pinned);break;case"step":{if(e.generation!==this.generation)break;let n=performance.now();if(t.readPending&&!t.readReady){!t.settled&&this.unread<ve&&(t.step(),this.unread+=1),this.deliver({type:"busy",generation:this.generation,buffer:e.buffer});break}let i=t.readPending?t.finishRead(e.buffer):null,o=t.currentAlpha,s=0;if(t.settled||(t.step(),this.unread+=1,s=1),this.unread>0&&(t.beginRead(),this.unread=0),!i){this.deliver({type:"busy",generation:this.generation,buffer:e.buffer});break}let r=t.settled&&!t.readPending;this.deliver({type:"positions",generation:this.generation,xy:i,alpha:o,settled:r,steps:s,ms:performance.now()-n});break}case"dispose":this.terminate();break}}terminate(){this.terminated||(this.terminated=!0,this.sim?.dispose(),this.sim=null)}deliver(e){queueMicrotask(()=>{this.terminated&&e.type!=="error"||this.onmessage?.({data:e})})}};var U=`// src/layout/webglForce/shaders.ts
343
+ var HEADER = \`#version 300 es
344
+ precision highp float;
345
+ precision highp int;
346
+ precision highp sampler2D;
347
+ precision highp sampler2DArray;
348
+ \`;
349
+ var POINT_TEXEL = \`
350
+ ivec2 pointTexel(int i, int size) { return ivec2(i % size, i / size); }
351
+ \`;
352
+ var GRID_CELL = \`
353
+ uniform sampler2D dataBoundsTexture; // [originX, originY, extent, 1 / extent]
354
+ ivec2 gridCell(vec2 worldPosition, float cellsPerAxis) {
355
+ vec4 dataBox = texelFetch(dataBoundsTexture, ivec2(0), 0);
356
+ float cellsPerUnit = dataBox.w * cellsPerAxis;
357
+ ivec2 lastCell = ivec2(int(cellsPerAxis) - 1);
358
+ return clamp(ivec2(floor((worldPosition - dataBox.xy) * cellsPerUnit)), ivec2(0), lastCell);
359
+ }
360
+ \`;
361
+ var PAIRWISE = \`
362
+ vec2 pairwiseVelocity(vec2 position, vec2 otherPosition, vec2 randomDir, float alpha, float repulsion) {
363
+ vec2 distVector = position - otherPosition;
364
+ float l = dot(distVector, distVector);
365
+ if (l <= 0.0) {
366
+ // Coincident points have no separation direction; kick along this point's
367
+ // own random vector so a pile disperses.
368
+ distVector = randomDir;
369
+ l = dot(distVector, distVector);
370
+ if (l <= 0.0) return vec2(0.0);
371
+ }
372
+ if (l < 1.0) l = sqrt(l);
373
+ float addV = alpha * repulsion / sqrt(l);
374
+ return addV * normalize(distVector);
375
+ }
376
+ \`;
377
+ var QUAD_VS = \`\${HEADER}
378
+ void main() {
379
+ vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));
380
+ gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
381
+ }
382
+ \`;
383
+ var COPY_FS = \`\${HEADER}
384
+ uniform sampler2D source;
385
+ out vec4 fragColor;
386
+ void main() { fragColor = texelFetch(source, ivec2(gl_FragCoord.xy), 0); }
387
+ \`;
388
+ var UPDATE_POSITION_FS = \`\${HEADER}
389
+ uniform sampler2D positionsTexture;
390
+ uniform sampler2D velocityTexture;
391
+ uniform sampler2D pinnedTexture;
392
+ uniform float friction;
393
+ uniform float maxStep;
394
+ out vec4 fragColor;
395
+
396
+ bool isFiniteVector(vec2 v) {
397
+ uvec2 exponent = floatBitsToUint(v) & 0x7f800000u;
398
+ return all(notEqual(exponent, uvec2(0x7f800000u)));
399
+ }
400
+
401
+ void main() {
402
+ ivec2 texel = ivec2(gl_FragCoord.xy);
403
+ vec4 position = texelFetch(positionsTexture, texel, 0);
404
+ vec4 velocity = texelFetch(velocityTexture, texel, 0);
405
+ if (texelFetch(pinnedTexture, texel, 0).r > 0.5 || !isFiniteVector(velocity.rg)) {
406
+ fragColor = position;
407
+ return;
408
+ }
409
+ float largestVelocity = max(abs(velocity.r), abs(velocity.g));
410
+ float largest = largestVelocity * abs(friction);
411
+ if (largest > 0.5 * maxStep) {
412
+ vec2 scaled = largestVelocity > 1.0e30 ? velocity.rg * 1.0e-30 : velocity.rg;
413
+ vec2 direction = scaled / max(abs(scaled.x), abs(scaled.y)) * sign(friction);
414
+ float directionLength = length(direction);
415
+ if (largest > maxStep / directionLength) {
416
+ position.rg += direction * (maxStep / directionLength);
417
+ fragColor = position;
418
+ return;
419
+ }
420
+ }
421
+ position.rg += velocity.rg * friction;
422
+ fragColor = position;
423
+ }
424
+ \`;
425
+ var GRAVITY_FS = \`\${HEADER}
426
+ uniform sampler2D positionsTexture;
427
+ uniform float gravity;
428
+ uniform float alpha;
429
+ out vec4 fragColor;
430
+ void main() {
431
+ vec2 position = texelFetch(positionsTexture, ivec2(gl_FragCoord.xy), 0).rg;
432
+ vec2 distVector = -position;
433
+ float dist = length(distVector);
434
+ vec2 velocity = vec2(0.0);
435
+ if (dist > 0.0) velocity = (alpha * gravity * dist * 0.1) * (distVector / dist);
436
+ fragColor = vec4(velocity, 0.0, 0.0);
437
+ }
438
+ \`;
439
+ var LINK_FS = \`\${HEADER}
440
+ uniform sampler2D positionsTexture;
441
+ uniform sampler2D linkInfoTexture;
442
+ uniform sampler2D linkTexture;
443
+ uniform float linkSpring;
444
+ uniform float linkDistance;
445
+ uniform vec2 linkDistRandomVariationRange;
446
+ uniform float alpha;
447
+ uniform int pointsTextureSize;
448
+ uniform int linksTextureSize;
449
+ out vec4 fragColor;
450
+ \${POINT_TEXEL}
451
+ void main() {
452
+ ivec2 texel = ivec2(gl_FragCoord.xy);
453
+ vec2 position = texelFetch(positionsTexture, texel, 0).rg;
454
+ vec4 info = texelFetch(linkInfoTexture, texel, 0);
455
+ int first = int(info.r);
456
+ int amount = int(info.g);
457
+ vec2 velocity = vec2(0.0);
458
+ for (int k = 0; k < amount; k += 1) {
459
+ vec4 link = texelFetch(linkTexture, pointTexel(first + k, linksTextureSize), 0);
460
+ float restLength = (link.g * (linkDistRandomVariationRange.y - linkDistRandomVariationRange.x)
461
+ + linkDistRandomVariationRange.x) * linkDistance;
462
+ vec2 other = texelFetch(positionsTexture, pointTexel(int(link.r), pointsTextureSize), 0).rg;
463
+ vec2 d = other - (position + velocity);
464
+ float l = length(d);
465
+ l = max(l, restLength * 0.99);
466
+ l = (l - restLength) / l;
467
+ l *= linkSpring * alpha * link.a * link.b;
468
+ velocity += d * l;
469
+ }
470
+ fragColor = vec4(velocity, 0.0, 0.0);
471
+ }
472
+ \`;
473
+ var ALL_PAIRS_FS = \`\${HEADER}
474
+ uniform sampler2D positionsTexture;
475
+ uniform sampler2D randomValues;
476
+ uniform int pointsTextureSize;
477
+ uniform int pointsNumber;
478
+ uniform float alpha;
479
+ uniform float repulsion;
480
+ uniform float maxStep;
481
+ out vec4 fragColor;
482
+ \${POINT_TEXEL}
483
+ \${PAIRWISE}
484
+ void main() {
485
+ ivec2 texel = ivec2(gl_FragCoord.xy);
486
+ int selfIndex = texel.y * pointsTextureSize + texel.x;
487
+ if (selfIndex >= pointsNumber) { fragColor = vec4(0.0); return; }
488
+ vec2 position = texelFetch(positionsTexture, texel, 0).rg;
489
+ vec2 random = texelFetch(randomValues, texel, 0).rg;
490
+ vec2 nearVelocity = vec2(0.0);
491
+ vec2 farVelocity = vec2(0.0);
492
+ float nearRadius2 = maxStep * maxStep;
493
+ for (int i = 0; i < pointsNumber; i += 1) {
494
+ if (i == selfIndex) continue;
495
+ vec2 other = texelFetch(positionsTexture, pointTexel(i, pointsTextureSize), 0).rg;
496
+ vec2 d = position - other;
497
+ vec2 v = pairwiseVelocity(position, other, random, alpha, repulsion);
498
+ if (dot(d, d) < nearRadius2) nearVelocity += v; else farVelocity += v;
499
+ }
500
+ nearVelocity += nearVelocity * random;
501
+ float speed = length(nearVelocity);
502
+ if (speed > maxStep) nearVelocity *= maxStep / speed;
503
+ fragColor = vec4(farVelocity + nearVelocity, 0.0, 0.0);
504
+ }
505
+ \`;
506
+ var BOUNDS_POINT_VS = \`\${HEADER}
507
+ uniform sampler2D positionsTexture;
508
+ uniform int pointsTextureSize;
509
+ out vec4 vColor;
510
+ \${POINT_TEXEL}
511
+ void main() {
512
+ vec2 p = texelFetch(positionsTexture, pointTexel(gl_VertexID, pointsTextureSize), 0).rg;
513
+ vColor = vec4(-p, p);
514
+ gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
515
+ gl_PointSize = 1.0;
516
+ }
517
+ \`;
518
+ var COLOR_FS = \`\${HEADER}
519
+ in vec4 vColor;
520
+ out vec4 fragColor;
521
+ void main() { fragColor = vColor; }
522
+ \`;
523
+ var BOUNDS_FINAL_FS = \`\${HEADER}
524
+ uniform sampler2D partialTexture;
525
+ uniform float minExtent;
526
+ uniform float shiftCellsPerAxis;
527
+ uniform vec2 shiftOffset;
528
+ out vec4 bounds;
529
+ void main() {
530
+ vec4 partial = texelFetch(partialTexture, ivec2(0), 0);
531
+ vec2 lo = -partial.xy;
532
+ vec2 hi = partial.zw;
533
+ if (hi.x < lo.x) { lo = vec2(0.0); hi = vec2(0.0); }
534
+ vec2 centre = 0.5 * (lo + hi);
535
+ float extent = max(max(hi.x - lo.x, hi.y - lo.y), minExtent);
536
+ vec2 origin = centre - 0.5 * extent;
537
+ float cell = extent / (shiftCellsPerAxis - 1.0);
538
+ origin -= shiftOffset * cell;
539
+ extent += cell;
540
+ bounds = vec4(origin, extent, 1.0 / extent);
541
+ }
542
+ \`;
543
+ var LEVEL_POINT_VS = \`\${HEADER}
544
+ uniform sampler2D positionsTexture;
545
+ uniform int pointsTextureSize;
546
+ uniform float levelGridSize;
547
+ out vec4 vColor;
548
+ \${POINT_TEXEL}
549
+ \${GRID_CELL}
550
+ void main() {
551
+ vec2 p = texelFetch(positionsTexture, pointTexel(gl_VertexID, pointsTextureSize), 0).rg;
552
+ vColor = vec4(p, 1.0, 0.0);
553
+ ivec2 cell = gridCell(p, levelGridSize);
554
+ gl_Position = vec4(2.0 * (vec2(cell) + 0.5) / levelGridSize - 1.0, 0.0, 1.0);
555
+ gl_PointSize = 1.0;
556
+ }
557
+ \`;
558
+ var FORCE_LEVEL_FS = \`\${HEADER}
559
+ uniform sampler2D positionsTexture;
560
+ uniform sampler2D levelTexture;
561
+ uniform float levelGridSize;
562
+ uniform float isFirstLevel;
563
+ uniform float alpha;
564
+ uniform float repulsion;
565
+ uniform float shellRadius;
566
+ uniform float parentShellRadius;
567
+ out vec4 fragColor;
568
+ \${GRID_CELL}
569
+ vec2 cellVelocity(ivec2 cell, vec2 position) {
570
+ vec4 centermass = texelFetch(levelTexture, cell, 0);
571
+ if (centermass.b <= 0.0) return vec2(0.0);
572
+ vec2 distVector = position - centermass.rg / centermass.b;
573
+ float l = dot(distVector, distVector);
574
+ if (l <= 0.0) return vec2(0.0);
575
+ if (l < 1.0) l = sqrt(l);
576
+ return (alpha * repulsion * centermass.b / sqrt(l)) * normalize(distVector);
577
+ }
578
+ void main() {
579
+ vec2 position = texelFetch(positionsTexture, ivec2(gl_FragCoord.xy), 0).rg;
580
+ int gridSize = int(levelGridSize);
581
+ ivec2 pointCell = gridCell(position, levelGridSize);
582
+ vec2 velocity = vec2(0.0);
583
+ int shell = int(shellRadius);
584
+ if (isFirstLevel > 0.5) {
585
+ for (int j = 0; j < gridSize; j += 1) {
586
+ for (int i = 0; i < gridSize; i += 1) {
587
+ ivec2 cell = ivec2(i, j);
588
+ ivec2 cellDist = abs(cell - pointCell);
589
+ if (max(cellDist.x, cellDist.y) <= shell) continue;
590
+ velocity += cellVelocity(cell, position);
591
+ }
592
+ }
593
+ } else {
594
+ int parentShell = int(parentShellRadius);
595
+ int blockSize = 2 * (2 * parentShell + 1);
596
+ ivec2 base = (pointCell / 2) * 2 - 2 * parentShell;
597
+ for (int j = 0; j < blockSize; j += 1) {
598
+ for (int i = 0; i < blockSize; i += 1) {
599
+ ivec2 cell = base + ivec2(i, j);
600
+ if (any(lessThan(cell, ivec2(0))) || any(greaterThanEqual(cell, ivec2(gridSize)))) continue;
601
+ ivec2 cellDist = abs(cell - pointCell);
602
+ if (max(cellDist.x, cellDist.y) <= shell) continue;
603
+ velocity += cellVelocity(cell, position);
604
+ }
605
+ }
606
+ }
607
+ fragColor = vec4(velocity, 0.0, 0.0);
608
+ }
609
+ \`;
610
+ var SLOTS_POINT_VS = \`\${HEADER}
611
+ uniform sampler2D positionsTexture;
612
+ uniform sampler2DArray previousSlot;
613
+ uniform int pointsTextureSize;
614
+ uniform float levelGridSize;
615
+ uniform float hasPreviousSlot;
616
+ uniform float randomSeed;
617
+ uniform int previousLayer;
618
+ out vec2 slotData;
619
+ \${POINT_TEXEL}
620
+ \${GRID_CELL}
621
+ void main() {
622
+ int index = gl_VertexID;
623
+ vec2 p = texelFetch(positionsTexture, pointTexel(index, pointsTextureSize), 0).rg;
624
+ uint h = uint(index) ^ floatBitsToUint(randomSeed);
625
+ h ^= h >> 16u;
626
+ h *= 0x7feb352du;
627
+ h ^= h >> 15u;
628
+ h *= 0x846ca68bu;
629
+ h ^= h >> 16u;
630
+ float hashValue = (float(h >> 8u) + 0.5) / 16777216.0;
631
+ hashValue = 0.001 + hashValue * 0.998;
632
+ ivec2 cell = gridCell(p, levelGridSize);
633
+ if (hasPreviousSlot > 0.5) {
634
+ vec2 previous = texelFetch(previousSlot, ivec3(cell, previousLayer), 0).rg;
635
+ if (previous.x < 0.0 || hashValue <= previous.y) {
636
+ slotData = vec2(-1.0, 1.0);
637
+ gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
638
+ gl_PointSize = 1.0;
639
+ return;
640
+ }
641
+ }
642
+ slotData = vec2(float(index), hashValue);
643
+ gl_Position = vec4(2.0 * (vec2(cell) + 0.5) / levelGridSize - 1.0, hashValue * 2.0 - 1.0, 1.0);
644
+ gl_PointSize = 1.0;
645
+ }
646
+ \`;
647
+ var SLOTS_FS = \`\${HEADER}
648
+ in vec2 slotData;
649
+ out vec4 fragColor;
650
+ void main() { fragColor = vec4(slotData, 0.0, 0.0); }
651
+ \`;
652
+ var NEAR_FIELD_FS = \`\${HEADER}
653
+ uniform sampler2D positionsTexture;
654
+ uniform sampler2D levelTexture;
655
+ uniform sampler2D randomValues;
656
+ uniform sampler2DArray slotsEven;
657
+ uniform sampler2DArray slotsOdd;
658
+ uniform int pointsTextureSize;
659
+ uniform float levelGridSize;
660
+ uniform float maxStep;
661
+ uniform float alpha;
662
+ uniform float repulsion;
663
+ uniform int slotCount;
664
+ out vec4 fragColor;
665
+ \${POINT_TEXEL}
666
+ \${GRID_CELL}
667
+ \${PAIRWISE}
668
+ void main() {
669
+ ivec2 texel = ivec2(gl_FragCoord.xy);
670
+ vec2 position = texelFetch(positionsTexture, texel, 0).rg;
671
+ float selfIndex = float(texel.y * pointsTextureSize + texel.x);
672
+ vec2 random = texelFetch(randomValues, texel, 0).rg;
673
+ int gridSize = int(levelGridSize);
674
+ ivec2 pointCell = gridCell(position, levelGridSize);
675
+ vec2 velocity = vec2(0.0);
676
+ for (int j = -1; j <= 1; j += 1) {
677
+ for (int i = -1; i <= 1; i += 1) {
678
+ ivec2 cell = pointCell + ivec2(i, j);
679
+ if (any(lessThan(cell, ivec2(0))) || any(greaterThanEqual(cell, ivec2(gridSize)))) continue;
680
+ float others = texelFetch(levelTexture, cell, 0).b - ((i == 0 && j == 0) ? 1.0 : 0.0);
681
+ if (others <= 0.0) continue;
682
+ vec2 pairSum = vec2(0.0);
683
+ float sampled = 0.0;
684
+ for (int s = 0; s < slotCount; s += 1) {
685
+ ivec3 layer = ivec3(cell, s >> 1);
686
+ vec2 slot = (s & 1) == 0 ? texelFetch(slotsEven, layer, 0).rg : texelFetch(slotsOdd, layer, 0).rg;
687
+ if (slot.x < 0.0) break;
688
+ if (slot.x == selfIndex) continue;
689
+ vec2 other = texelFetch(positionsTexture, pointTexel(int(slot.x), pointsTextureSize), 0).rg;
690
+ sampled += 1.0;
691
+ pairSum += pairwiseVelocity(position, other, random, alpha, repulsion);
692
+ }
693
+ if (sampled > 0.0) velocity += (others / sampled) * pairSum;
694
+ }
695
+ }
696
+ velocity += velocity * random;
697
+ float speed = length(velocity);
698
+ if (speed > maxStep) velocity *= maxStep / speed;
699
+ fragColor = vec4(velocity, 0.0, 0.0);
700
+ }
701
+ \`;
702
+
703
+ // src/layout/webglForce/sizing.ts
704
+ var COARSEST_GRID_SIZE = 8;
705
+ var MAX_GRID_SIZE = 512;
706
+ var ALL_PAIRS_MAX_POINTS = 4096;
707
+ var PRECISE_FAR_FIELD_MAX_POINTS = 25e3;
708
+ var MIN_FINEST_CELL_SIZE = 0.25;
709
+ var NEAR_FIELD_BUDGET = 16e5;
710
+ var NEAR_FIELD_MEMORY_BUDGET = 32 * 1024 * 1024;
711
+ var MIN_SLOTS = 8;
712
+ var MAX_SLOTS = 64;
713
+ var ALPHA_MIN = 1e-3;
714
+ var SIM_LINK_DISTANCE = 10;
715
+ var SIM_SPACE_SIZE = 4096;
716
+ function getFinestGridSize(points) {
717
+ return Math.min(MAX_GRID_SIZE, Math.max(8, 2 ** Math.ceil(Math.log2(2 * Math.sqrt(Math.max(1, points))))));
718
+ }
719
+ function getLevelCount(points) {
720
+ return Math.log2(getFinestGridSize(points) / COARSEST_GRID_SIZE) + 1;
721
+ }
722
+ function getNearFieldSlotCount(points) {
723
+ const tier = points <= 16384 ? 32 : points <= 65536 ? 16 : 8;
724
+ const layerBytes = getFinestGridSize(points) ** 2 * 8;
725
+ const affordable = Math.min(NEAR_FIELD_BUDGET / Math.max(1, points), NEAR_FIELD_MEMORY_BUDGET / layerBytes);
726
+ const affordablePow2 = Math.min(MAX_SLOTS, Math.max(MIN_SLOTS, 2 ** Math.floor(Math.log2(affordable))));
727
+ return Math.min(tier, affordablePow2);
728
+ }
729
+ function getShellRadius(level, levels, precise) {
730
+ return precise && level !== levels - 1 ? 2 : 1;
731
+ }
732
+ function getMaxStep(points) {
733
+ return 2 * SIM_SPACE_SIZE / getFinestGridSize(points);
734
+ }
735
+ function textureSide(count) {
736
+ return Math.max(1, Math.ceil(Math.sqrt(count)));
737
+ }
738
+ function createRandom(seed) {
739
+ let a = seed >>> 0;
740
+ return () => {
741
+ a = a + 1831565813 >>> 0;
742
+ let t = a;
743
+ t = Math.imul(t ^ t >>> 15, t | 1);
744
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
745
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
746
+ };
747
+ }
748
+ function alphaDecayFactor(decayTicks) {
749
+ return 1 - Math.pow(ALPHA_MIN, 1 / Math.max(1, decayTicks));
750
+ }
751
+ function buildLinkTables(n, links, pointsSide, random) {
752
+ const linkCount = links.length >> 1;
753
+ const degree = new Uint32Array(n);
754
+ const valid = new Uint8Array(linkCount);
755
+ for (let l = 0; l < linkCount; l++) {
756
+ const s = links[l * 2], t = links[l * 2 + 1];
757
+ if (s >= n || t >= n || s === t) continue;
758
+ valid[l] = 1;
759
+ degree[s]++;
760
+ degree[t]++;
761
+ }
762
+ const build = (self2) => {
763
+ const offsets = new Uint32Array(n + 1);
764
+ for (let l = 0; l < linkCount; l++) if (valid[l]) offsets[links[l * 2 + self2] + 1]++;
765
+ for (let i = 0; i < n; i++) offsets[i + 1] += offsets[i];
766
+ const entryCount = offsets[n];
767
+ const entriesSide = textureSide(entryCount);
768
+ const entries = new Float32Array(entriesSide * entriesSide * 4);
769
+ const cursor = offsets.slice(0, n);
770
+ for (let l = 0; l < linkCount; l++) {
771
+ if (!valid[l]) continue;
772
+ const p = links[l * 2 + self2];
773
+ const other = links[l * 2 + (1 - self2)];
774
+ const k = cursor[p]++;
775
+ const dOther = degree[other], dSelf = degree[p];
776
+ const sum = dOther + dSelf;
777
+ entries[k * 4] = other;
778
+ entries[k * 4 + 1] = random();
779
+ entries[k * 4 + 2] = sum !== 0 ? dOther / sum : 0.5;
780
+ entries[k * 4 + 3] = Math.sqrt(1 / Math.max(Math.min(dOther, dSelf), 1));
781
+ }
782
+ const info = new Float32Array(pointsSide * pointsSide * 4);
783
+ for (let i = 0; i < n; i++) {
784
+ info[i * 4] = offsets[i];
785
+ info[i * 4 + 1] = offsets[i + 1] - offsets[i];
786
+ }
787
+ return { info, entries, entriesSide, entryCount };
788
+ };
789
+ return [build(0), build(1)];
790
+ }
791
+ var DEFAULT_SIM_PARAMS = {
792
+ repulsion: 1,
793
+ gravity: 0.25,
794
+ linkSpring: 1,
795
+ linkDistRandomVariationRange: [1, 1.2],
796
+ friction: 0.85,
797
+ // The same cooling as the other engines' default alphaDecay 0.01
798
+ // (DEFAULT_FORCE_LAYOUT_CONFIG): about 690 steps, some 11 s at one step a
799
+ // frame, then the layout stops and its nodes hold still to be clicked.
800
+ // cosmos.gl's 5000 kept 100 000 nodes drifting for minutes, and the result
801
+ // looked no better.
802
+ decay: Math.round(Math.log(ALPHA_MIN) / Math.log(1 - 0.01)),
803
+ alpha: 1
804
+ };
805
+
806
+ // src/layout/webglForce/ForceSim.ts
807
+ var ForceSimUnsupportedError = class extends Error {
808
+ };
809
+ var ForceSim = class {
810
+ constructor(gl) {
811
+ this.programs = /* @__PURE__ */ new Map();
812
+ this.params = { ...DEFAULT_SIM_PARAMS };
813
+ this.alpha = 0;
814
+ this.random = createRandom(1);
815
+ this.n = 0;
816
+ this.side = 1;
817
+ this.positions = null;
818
+ this.velocity = null;
819
+ this.pinned = null;
820
+ this.randomValues = null;
821
+ this.links = null;
822
+ // Grid path
823
+ this.boundsPartial = null;
824
+ this.boundsFinal = null;
825
+ this.levels = [];
826
+ this.slotArrays = null;
827
+ this.slotFbos = [];
828
+ this.slotDepth = null;
829
+ this.slotCount = 0;
830
+ this.readbackBuffer = new Float32Array(0);
831
+ /** Asynchronous readback: positions copied into a pixel-pack buffer, a fence after it. */
832
+ this.pbo = null;
833
+ this.pboBytes = 0;
834
+ this.fence = null;
835
+ this.pendingCount = 0;
836
+ this.gl = gl;
837
+ if (!gl.getExtension("EXT_color_buffer_float")) throw new ForceSimUnsupportedError("EXT_color_buffer_float is not available");
838
+ if (!gl.getExtension("EXT_float_blend")) throw new ForceSimUnsupportedError("EXT_float_blend is not available");
839
+ const vao = gl.createVertexArray();
840
+ if (!vao) throw new ForceSimUnsupportedError("cannot create a vertex array");
841
+ this.vao = vao;
842
+ gl.disable(gl.DEPTH_TEST);
843
+ gl.disable(gl.BLEND);
844
+ gl.disable(gl.DITHER);
845
+ gl.getExtension("KHR_parallel_shader_compile");
846
+ this.buildPrograms([
847
+ ["update", QUAD_VS, UPDATE_POSITION_FS],
848
+ ["copy", QUAD_VS, COPY_FS],
849
+ ["gravity", QUAD_VS, GRAVITY_FS],
850
+ ["link", QUAD_VS, LINK_FS],
851
+ ["allPairs", QUAD_VS, ALL_PAIRS_FS],
852
+ ["boundsPoint", BOUNDS_POINT_VS, COLOR_FS],
853
+ ["boundsFinal", QUAD_VS, BOUNDS_FINAL_FS],
854
+ ["levelPoint", LEVEL_POINT_VS, COLOR_FS],
855
+ ["forceLevel", QUAD_VS, FORCE_LEVEL_FS],
856
+ ["slots", SLOTS_POINT_VS, SLOTS_FS],
857
+ ["nearField", QUAD_VS, NEAR_FIELD_FS]
858
+ ]);
859
+ }
860
+ get pointCount() {
861
+ return this.n;
862
+ }
863
+ get currentAlpha() {
864
+ return this.alpha;
865
+ }
866
+ get settled() {
867
+ return this.alpha < ALPHA_MIN;
868
+ }
869
+ setParams(params) {
870
+ this.params = { ...params, linkDistRandomVariationRange: [...params.linkDistRandomVariationRange] };
871
+ }
872
+ /** Alpha for the next steps; a (re)start or a reheat. */
873
+ setAlpha(alpha) {
874
+ this.alpha = alpha;
875
+ }
876
+ /**
877
+ * Replace the graph. \`xy\` holds n positions in simulation units; \`pinned\`
878
+ * one flag per point; \`links\` the pairs \`[s0, t0, s1, t1, \u2026]\` by point index.
879
+ */
880
+ setGraph(xy, pinned, links, seed) {
881
+ const gl = this.gl;
882
+ this.dropPendingRead();
883
+ this.random = createRandom(seed);
884
+ const n = xy.length >> 1;
885
+ const side = textureSide(n);
886
+ if (n !== this.n || side !== this.side || !this.positions) {
887
+ this.disposeGraph();
888
+ this.n = n;
889
+ this.side = side;
890
+ this.positions = [this.target(side, side), this.target(side, side)];
891
+ this.velocity = this.target(side, side);
892
+ this.pinned = this.dataTexture(side, side, null);
893
+ this.randomValues = this.dataTexture(side, side, null);
894
+ this.allocateGrid();
895
+ }
896
+ this.n = n;
897
+ const pos = new Float32Array(side * side * 4);
898
+ for (let i = 0; i < n; i++) {
899
+ pos[i * 4] = xy[i * 2];
900
+ pos[i * 4 + 1] = xy[i * 2 + 1];
901
+ }
902
+ this.upload(this.positions[0].texture, side, side, pos);
903
+ this.upload(this.positions[1].texture, side, side, pos);
904
+ const pin = new Float32Array(side * side * 4);
905
+ for (let i = 0; i < n; i++) pin[i * 4] = pinned[i] ? 1 : 0;
906
+ this.upload(this.pinned, side, side, pin);
907
+ const rnd = new Float32Array(side * side * 4);
908
+ for (let i = 0; i < side * side; i++) {
909
+ rnd[i * 4] = (this.random() * 2 - 1) * 1e-5;
910
+ rnd[i * 4 + 1] = (this.random() * 2 - 1) * 1e-5;
911
+ }
912
+ this.upload(this.randomValues, side, side, rnd);
913
+ if (this.links) for (const l of this.links) {
914
+ gl.deleteTexture(l.info);
915
+ gl.deleteTexture(l.entries);
916
+ }
917
+ const tables = buildLinkTables(n, links, side, this.random);
918
+ this.links = [this.linkTextures(tables[0]), this.linkTextures(tables[1])];
919
+ }
920
+ /** Pin (with a position, in simulation units) or release points. */
921
+ setPins(indices, xy, pinned) {
922
+ const gl = this.gl;
923
+ if (!this.positions || !this.pinned) return;
924
+ const texel = new Float32Array(4);
925
+ for (let k = 0; k < indices.length; k++) {
926
+ const i = indices[k];
927
+ if (i >= this.n) continue;
928
+ const x = i % this.side, y = Math.floor(i / this.side);
929
+ texel[0] = pinned[k] ? 1 : 0;
930
+ texel[1] = texel[2] = texel[3] = 0;
931
+ gl.bindTexture(gl.TEXTURE_2D, this.pinned);
932
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, 1, 1, gl.RGBA, gl.FLOAT, texel);
933
+ if (pinned[k]) {
934
+ texel[0] = xy[k * 2];
935
+ texel[1] = xy[k * 2 + 1];
936
+ for (const p of this.positions) {
937
+ gl.bindTexture(gl.TEXTURE_2D, p.texture);
938
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, 1, 1, gl.RGBA, gl.FLOAT, texel);
939
+ }
940
+ }
941
+ }
942
+ gl.bindTexture(gl.TEXTURE_2D, null);
943
+ }
944
+ /** Run one simulation step and decay alpha. */
945
+ step() {
946
+ if (!this.positions || this.n === 0) return;
947
+ const { params } = this;
948
+ if (params.gravity > 0) {
949
+ this.runGravity();
950
+ this.integrate();
951
+ }
952
+ if (params.repulsion > 0) {
953
+ this.runManyBody();
954
+ this.integrate();
955
+ }
956
+ if (this.links && params.linkSpring > 0) {
957
+ for (const table of this.links) {
958
+ if (table.count === 0) continue;
959
+ this.runLinks(table);
960
+ this.integrate();
961
+ }
962
+ }
963
+ this.alpha += (0 - this.alpha) * alphaDecayFactor(params.decay);
964
+ }
965
+ /**
966
+ * Read the current positions back: x, y per point in simulation units, into
967
+ * \`out\` (length \u2265 2n) or a new array. Synchronous: it waits for the GPU,
968
+ * which is why this runs in a worker.
969
+ */
970
+ readPositions(out) {
971
+ const gl = this.gl;
972
+ const n = this.n;
973
+ const result = out && out.length >= n * 2 ? out : new Float32Array(n * 2);
974
+ if (!this.positions || n === 0) return result;
975
+ const rows = Math.ceil(n / this.side);
976
+ const need = this.side * rows * 4;
977
+ if (this.readbackBuffer.length < need) this.readbackBuffer = new Float32Array(need);
978
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.positions[0].fbo);
979
+ gl.readPixels(0, 0, this.side, rows, gl.RGBA, gl.FLOAT, this.readbackBuffer);
980
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
981
+ const buf = this.readbackBuffer;
982
+ for (let i = 0; i < n; i++) {
983
+ result[i * 2] = buf[i * 4];
984
+ result[i * 2 + 1] = buf[i * 4 + 1];
985
+ }
986
+ return result;
987
+ }
988
+ /**
989
+ * Start an asynchronous read of the current positions: the GPU copies them
990
+ * into a buffer and a fence marks the copy. \`finishRead\` collects them,
991
+ * normally a frame later when the GPU is long done, so the calling thread
992
+ * never waits on the simulation. Replaces a read still pending.
993
+ */
994
+ beginRead() {
995
+ const gl = this.gl;
996
+ const n = this.n;
997
+ this.dropPendingRead();
998
+ if (!this.positions || n === 0) return;
999
+ const rows = Math.ceil(n / this.side);
1000
+ const bytes = this.side * rows * 16;
1001
+ if (!this.pbo || this.pboBytes < bytes) {
1002
+ if (this.pbo) gl.deleteBuffer(this.pbo);
1003
+ this.pbo = gl.createBuffer();
1004
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, this.pbo);
1005
+ gl.bufferData(gl.PIXEL_PACK_BUFFER, bytes, gl.STREAM_READ);
1006
+ this.pboBytes = bytes;
1007
+ } else {
1008
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, this.pbo);
1009
+ }
1010
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.positions[0].fbo);
1011
+ gl.readPixels(0, 0, this.side, rows, gl.RGBA, gl.FLOAT, 0);
1012
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
1013
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
1014
+ this.fence = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
1015
+ gl.flush();
1016
+ this.pendingCount = n;
1017
+ }
1018
+ /** True while a read from \`beginRead\` has not been collected. */
1019
+ get readPending() {
1020
+ return this.fence !== null;
1021
+ }
1022
+ /** True when the pending read's copy has finished on the GPU, so \`finishRead\` will not wait. */
1023
+ get readReady() {
1024
+ const gl = this.gl;
1025
+ if (!this.fence) return false;
1026
+ const status = gl.getSyncParameter(this.fence, gl.SYNC_STATUS);
1027
+ return status === gl.SIGNALED;
1028
+ }
1029
+ /**
1030
+ * Collect the read started by \`beginRead\` into \`out\` (x, y per point, in
1031
+ * simulation units), or null if none is pending. Waits for the GPU only if
1032
+ * the copy has not finished yet.
1033
+ */
1034
+ finishRead(out) {
1035
+ const gl = this.gl;
1036
+ if (!this.fence || !this.pbo) return null;
1037
+ const n = this.pendingCount;
1038
+ const result = out && out.length >= n * 2 ? out : new Float32Array(n * 2);
1039
+ const floats = Math.ceil(n / this.side) * this.side * 4;
1040
+ if (this.readbackBuffer.length < floats) this.readbackBuffer = new Float32Array(floats);
1041
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, this.pbo);
1042
+ gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, this.readbackBuffer, 0, floats);
1043
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
1044
+ this.dropPendingRead();
1045
+ const buf = this.readbackBuffer;
1046
+ for (let i = 0; i < n; i++) {
1047
+ result[i * 2] = buf[i * 4];
1048
+ result[i * 2 + 1] = buf[i * 4 + 1];
1049
+ }
1050
+ return result;
1051
+ }
1052
+ dropPendingRead() {
1053
+ if (this.fence) this.gl.deleteSync(this.fence);
1054
+ this.fence = null;
1055
+ this.pendingCount = 0;
1056
+ }
1057
+ dispose() {
1058
+ this.dropPendingRead();
1059
+ if (this.pbo) this.gl.deleteBuffer(this.pbo);
1060
+ this.pbo = null;
1061
+ this.disposeGraph();
1062
+ const gl = this.gl;
1063
+ for (const p of this.programs.values()) gl.deleteProgram(p.program);
1064
+ this.programs.clear();
1065
+ gl.deleteVertexArray(this.vao);
1066
+ }
1067
+ // \u2500\u2500 Passes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1068
+ get current() {
1069
+ return this.positions[0];
1070
+ }
1071
+ /** velocity \u2192 positions[1], then swap so positions[0] is the newest. */
1072
+ integrate() {
1073
+ const p = this.use("update");
1074
+ this.bindTarget(this.positions[1]);
1075
+ this.tex(p, "positionsTexture", 0, this.current.texture);
1076
+ this.tex(p, "velocityTexture", 1, this.velocity.texture);
1077
+ this.tex(p, "pinnedTexture", 2, this.pinned);
1078
+ this.f(p, "friction", this.params.friction);
1079
+ this.f(p, "maxStep", SIM_SPACE_SIZE);
1080
+ this.drawQuad();
1081
+ this.positions = [this.positions[1], this.positions[0]];
1082
+ }
1083
+ runGravity() {
1084
+ const p = this.use("gravity");
1085
+ this.bindTarget(this.velocity);
1086
+ this.tex(p, "positionsTexture", 0, this.current.texture);
1087
+ this.f(p, "gravity", this.params.gravity);
1088
+ this.f(p, "alpha", this.alpha);
1089
+ this.drawQuad();
1090
+ }
1091
+ runLinks(table) {
1092
+ const p = this.use("link");
1093
+ this.bindTarget(this.velocity);
1094
+ this.tex(p, "positionsTexture", 0, this.current.texture);
1095
+ this.tex(p, "linkInfoTexture", 1, table.info);
1096
+ this.tex(p, "linkTexture", 2, table.entries);
1097
+ this.f(p, "linkSpring", this.params.linkSpring);
1098
+ this.f(p, "linkDistance", SIM_LINK_DISTANCE);
1099
+ const [lo, hi] = this.params.linkDistRandomVariationRange;
1100
+ this.gl.uniform2f(this.loc(p, "linkDistRandomVariationRange"), lo, hi);
1101
+ this.f(p, "alpha", this.alpha);
1102
+ this.i(p, "pointsTextureSize", this.side);
1103
+ this.i(p, "linksTextureSize", table.entriesSide);
1104
+ this.drawQuad();
1105
+ }
1106
+ runManyBody() {
1107
+ if (this.n <= ALL_PAIRS_MAX_POINTS) {
1108
+ const p = this.use("allPairs");
1109
+ this.bindTarget(this.velocity);
1110
+ this.tex(p, "positionsTexture", 0, this.current.texture);
1111
+ this.tex(p, "randomValues", 1, this.randomValues);
1112
+ this.i(p, "pointsTextureSize", this.side);
1113
+ this.i(p, "pointsNumber", this.n);
1114
+ this.f(p, "alpha", this.alpha);
1115
+ this.f(p, "repulsion", this.params.repulsion);
1116
+ this.f(p, "maxStep", getMaxStep(this.n));
1117
+ this.drawQuad();
1118
+ return;
1119
+ }
1120
+ this.drawBounds();
1121
+ this.drawLevels();
1122
+ this.drawSlots();
1123
+ this.drawGridForces();
1124
+ }
1125
+ drawBounds() {
1126
+ const gl = this.gl;
1127
+ let p = this.use("boundsPoint");
1128
+ this.bindTarget(this.boundsPartial, [-1e30, -1e30, -1e30, -1e30]);
1129
+ this.tex(p, "positionsTexture", 0, this.current.texture);
1130
+ this.i(p, "pointsTextureSize", this.side);
1131
+ gl.enable(gl.BLEND);
1132
+ gl.blendEquation(gl.MAX);
1133
+ gl.blendFunc(gl.ONE, gl.ONE);
1134
+ gl.drawArrays(gl.POINTS, 0, this.n);
1135
+ gl.disable(gl.BLEND);
1136
+ gl.blendEquation(gl.FUNC_ADD);
1137
+ p = this.use("boundsFinal");
1138
+ this.bindTarget(this.boundsFinal);
1139
+ this.tex(p, "partialTexture", 0, this.boundsPartial.texture);
1140
+ this.f(p, "minExtent", getFinestGridSize(this.n) * MIN_FINEST_CELL_SIZE);
1141
+ this.f(p, "shiftCellsPerAxis", COARSEST_GRID_SIZE);
1142
+ gl.uniform2f(this.loc(p, "shiftOffset"), this.random(), this.random());
1143
+ this.drawQuad();
1144
+ }
1145
+ drawLevels() {
1146
+ const gl = this.gl;
1147
+ const p = this.use("levelPoint");
1148
+ this.tex(p, "positionsTexture", 0, this.current.texture);
1149
+ this.tex(p, "dataBoundsTexture", 1, this.boundsFinal.texture);
1150
+ this.i(p, "pointsTextureSize", this.side);
1151
+ gl.enable(gl.BLEND);
1152
+ gl.blendEquation(gl.FUNC_ADD);
1153
+ gl.blendFunc(gl.ONE, gl.ONE);
1154
+ for (const level of this.levels) {
1155
+ this.bindTarget(level, [0, 0, 0, 0]);
1156
+ this.f(p, "levelGridSize", level.size);
1157
+ gl.drawArrays(gl.POINTS, 0, this.n);
1158
+ }
1159
+ gl.disable(gl.BLEND);
1160
+ }
1161
+ drawSlots() {
1162
+ const gl = this.gl;
1163
+ const finest = this.levels[this.levels.length - 1];
1164
+ const p = this.use("slots");
1165
+ this.tex(p, "positionsTexture", 0, this.current.texture);
1166
+ this.tex(p, "dataBoundsTexture", 2, this.boundsFinal.texture);
1167
+ this.i(p, "pointsTextureSize", this.side);
1168
+ this.f(p, "levelGridSize", finest.size);
1169
+ this.f(p, "randomSeed", this.random());
1170
+ gl.enable(gl.DEPTH_TEST);
1171
+ gl.depthFunc(gl.LESS);
1172
+ gl.depthMask(true);
1173
+ for (let slot = 0; slot < this.slotCount; slot++) {
1174
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.slotFbos[slot]);
1175
+ gl.viewport(0, 0, finest.size, finest.size);
1176
+ gl.clearColor(-1, 1, 0, 0);
1177
+ gl.clearDepth(1);
1178
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
1179
+ gl.activeTexture(gl.TEXTURE1);
1180
+ gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.slotArrays[(slot + 1) % 2]);
1181
+ gl.uniform1i(this.loc(p, "previousSlot"), 1);
1182
+ this.f(p, "hasPreviousSlot", slot === 0 ? 0 : 1);
1183
+ this.i(p, "previousLayer", Math.max(0, slot - 1) >> 1);
1184
+ gl.drawArrays(gl.POINTS, 0, this.n);
1185
+ }
1186
+ gl.disable(gl.DEPTH_TEST);
1187
+ gl.activeTexture(gl.TEXTURE1);
1188
+ gl.bindTexture(gl.TEXTURE_2D_ARRAY, null);
1189
+ }
1190
+ drawGridForces() {
1191
+ const gl = this.gl;
1192
+ const levels = this.levels.length;
1193
+ const precise = this.n <= PRECISE_FAR_FIELD_MAX_POINTS;
1194
+ this.bindTarget(this.velocity, [0, 0, 0, 0]);
1195
+ gl.enable(gl.BLEND);
1196
+ gl.blendEquation(gl.FUNC_ADD);
1197
+ gl.blendFunc(gl.ONE, gl.ONE);
1198
+ const p = this.use("forceLevel");
1199
+ this.tex(p, "positionsTexture", 0, this.current.texture);
1200
+ this.tex(p, "dataBoundsTexture", 2, this.boundsFinal.texture);
1201
+ this.f(p, "alpha", this.alpha);
1202
+ this.f(p, "repulsion", this.params.repulsion);
1203
+ for (let level = 0; level < levels; level++) {
1204
+ const target = this.levels[level];
1205
+ this.tex(p, "levelTexture", 1, target.texture);
1206
+ this.f(p, "levelGridSize", target.size);
1207
+ this.f(p, "isFirstLevel", level === 0 ? 1 : 0);
1208
+ this.f(p, "shellRadius", getShellRadius(level, levels, precise));
1209
+ this.f(p, "parentShellRadius", level === 0 ? 0 : getShellRadius(level - 1, levels, precise));
1210
+ this.drawQuad();
1211
+ }
1212
+ const finest = this.levels[levels - 1];
1213
+ const q = this.use("nearField");
1214
+ this.tex(q, "positionsTexture", 0, this.current.texture);
1215
+ this.tex(q, "levelTexture", 1, finest.texture);
1216
+ this.tex(q, "dataBoundsTexture", 2, this.boundsFinal.texture);
1217
+ this.tex(q, "randomValues", 3, this.randomValues);
1218
+ gl.activeTexture(gl.TEXTURE4);
1219
+ gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.slotArrays[0]);
1220
+ gl.uniform1i(this.loc(q, "slotsEven"), 4);
1221
+ gl.activeTexture(gl.TEXTURE5);
1222
+ gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.slotArrays[1]);
1223
+ gl.uniform1i(this.loc(q, "slotsOdd"), 5);
1224
+ this.i(q, "pointsTextureSize", this.side);
1225
+ this.f(q, "levelGridSize", finest.size);
1226
+ this.f(q, "maxStep", getMaxStep(this.n));
1227
+ this.f(q, "alpha", this.alpha);
1228
+ this.f(q, "repulsion", this.params.repulsion);
1229
+ this.i(q, "slotCount", this.slotCount);
1230
+ this.drawQuad();
1231
+ gl.disable(gl.BLEND);
1232
+ for (const unit of [gl.TEXTURE4, gl.TEXTURE5]) {
1233
+ gl.activeTexture(unit);
1234
+ gl.bindTexture(gl.TEXTURE_2D_ARRAY, null);
1235
+ }
1236
+ }
1237
+ // \u2500\u2500 Allocation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1238
+ allocateGrid() {
1239
+ const gl = this.gl;
1240
+ if (this.n <= ALL_PAIRS_MAX_POINTS) return;
1241
+ this.boundsPartial = this.target(1, 1);
1242
+ this.boundsFinal = this.target(1, 1);
1243
+ const levels = getLevelCount(this.n);
1244
+ for (let l = 0; l < levels; l++) {
1245
+ const size = COARSEST_GRID_SIZE * 2 ** l;
1246
+ this.levels.push(this.target(size, size));
1247
+ }
1248
+ const finest = getFinestGridSize(this.n);
1249
+ this.slotCount = getNearFieldSlotCount(this.n);
1250
+ const layers = Math.ceil(this.slotCount / 2);
1251
+ const arrays = [];
1252
+ for (let a = 0; a < 2; a++) {
1253
+ const t = gl.createTexture();
1254
+ gl.bindTexture(gl.TEXTURE_2D_ARRAY, t);
1255
+ gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.RG32F, finest, finest, layers);
1256
+ this.nearest(gl.TEXTURE_2D_ARRAY);
1257
+ arrays.push(t);
1258
+ }
1259
+ gl.bindTexture(gl.TEXTURE_2D_ARRAY, null);
1260
+ this.slotArrays = [arrays[0], arrays[1]];
1261
+ this.slotDepth = gl.createRenderbuffer();
1262
+ gl.bindRenderbuffer(gl.RENDERBUFFER, this.slotDepth);
1263
+ gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT24, finest, finest);
1264
+ gl.bindRenderbuffer(gl.RENDERBUFFER, null);
1265
+ for (let slot = 0; slot < this.slotCount; slot++) {
1266
+ const fbo = gl.createFramebuffer();
1267
+ gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
1268
+ gl.framebufferTextureLayer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, this.slotArrays[slot % 2], 0, slot >> 1);
1269
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this.slotDepth);
1270
+ this.checkFramebuffer();
1271
+ this.slotFbos.push(fbo);
1272
+ }
1273
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
1274
+ }
1275
+ disposeGraph() {
1276
+ const gl = this.gl;
1277
+ const targets = [...this.positions ?? [], this.velocity, this.boundsPartial, this.boundsFinal, ...this.levels];
1278
+ for (const t of targets) if (t) {
1279
+ gl.deleteFramebuffer(t.fbo);
1280
+ gl.deleteTexture(t.texture);
1281
+ }
1282
+ for (const t of [this.pinned, this.randomValues]) if (t) gl.deleteTexture(t);
1283
+ if (this.links) for (const l of this.links) {
1284
+ gl.deleteTexture(l.info);
1285
+ gl.deleteTexture(l.entries);
1286
+ }
1287
+ for (const f of this.slotFbos) gl.deleteFramebuffer(f);
1288
+ if (this.slotArrays) for (const t of this.slotArrays) gl.deleteTexture(t);
1289
+ if (this.slotDepth) gl.deleteRenderbuffer(this.slotDepth);
1290
+ this.positions = null;
1291
+ this.velocity = this.boundsPartial = this.boundsFinal = null;
1292
+ this.pinned = this.randomValues = null;
1293
+ this.links = null;
1294
+ this.levels = [];
1295
+ this.slotFbos = [];
1296
+ this.slotArrays = null;
1297
+ this.slotDepth = null;
1298
+ this.slotCount = 0;
1299
+ this.n = 0;
1300
+ }
1301
+ linkTextures(table) {
1302
+ return {
1303
+ info: this.dataTexture(this.side, this.side, table.info),
1304
+ entries: this.dataTexture(table.entriesSide, table.entriesSide, table.entries),
1305
+ entriesSide: table.entriesSide,
1306
+ count: table.entryCount
1307
+ };
1308
+ }
1309
+ dataTexture(w, h, data) {
1310
+ const gl = this.gl;
1311
+ const t = gl.createTexture();
1312
+ gl.bindTexture(gl.TEXTURE_2D, t);
1313
+ gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA32F, w, h);
1314
+ this.nearest(gl.TEXTURE_2D);
1315
+ if (data) gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, w, h, gl.RGBA, gl.FLOAT, data);
1316
+ gl.bindTexture(gl.TEXTURE_2D, null);
1317
+ return t;
1318
+ }
1319
+ target(w, h) {
1320
+ const gl = this.gl;
1321
+ const texture = this.dataTexture(w, h, null);
1322
+ const fbo = gl.createFramebuffer();
1323
+ gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
1324
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
1325
+ this.checkFramebuffer();
1326
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
1327
+ return { texture, fbo, size: w };
1328
+ }
1329
+ checkFramebuffer() {
1330
+ const gl = this.gl;
1331
+ const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
1332
+ if (status !== gl.FRAMEBUFFER_COMPLETE) throw new ForceSimUnsupportedError(\`framebuffer incomplete (0x\${status.toString(16)})\`);
1333
+ }
1334
+ upload(texture, w, h, data) {
1335
+ const gl = this.gl;
1336
+ gl.bindTexture(gl.TEXTURE_2D, texture);
1337
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, w, h, gl.RGBA, gl.FLOAT, data);
1338
+ gl.bindTexture(gl.TEXTURE_2D, null);
1339
+ }
1340
+ nearest(target) {
1341
+ const gl = this.gl;
1342
+ gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1343
+ gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1344
+ gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
1345
+ gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
1346
+ }
1347
+ // \u2500\u2500 Program helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1348
+ buildPrograms(specs) {
1349
+ const gl = this.gl;
1350
+ const shaders = /* @__PURE__ */ new Map();
1351
+ const shader = (type, src) => {
1352
+ let sh = shaders.get(src);
1353
+ if (!sh) {
1354
+ sh = gl.createShader(type);
1355
+ gl.shaderSource(sh, src);
1356
+ gl.compileShader(sh);
1357
+ shaders.set(src, sh);
1358
+ }
1359
+ return sh;
1360
+ };
1361
+ const linked = [];
1362
+ for (const [name, vs, fs] of specs) {
1363
+ const v = shader(gl.VERTEX_SHADER, vs);
1364
+ const f = shader(gl.FRAGMENT_SHADER, fs);
1365
+ const program = gl.createProgram();
1366
+ gl.attachShader(program, v);
1367
+ gl.attachShader(program, f);
1368
+ gl.linkProgram(program);
1369
+ linked.push([name, program, v, f]);
1370
+ }
1371
+ let failure = null;
1372
+ for (const [name, program, v, f] of linked) {
1373
+ if (!failure && !gl.getProgramParameter(program, gl.LINK_STATUS)) {
1374
+ const bad = [v, f].find((sh) => !gl.getShaderParameter(sh, gl.COMPILE_STATUS));
1375
+ failure = bad ? \`\${name}: shader compile failed: \${gl.getShaderInfoLog(bad)}\` : \`\${name}: program link failed: \${gl.getProgramInfoLog(program)}\`;
1376
+ }
1377
+ this.programs.set(name, { program, uniforms: /* @__PURE__ */ new Map() });
1378
+ }
1379
+ for (const sh of shaders.values()) gl.deleteShader(sh);
1380
+ if (failure) {
1381
+ for (const p of this.programs.values()) gl.deleteProgram(p.program);
1382
+ this.programs.clear();
1383
+ throw new ForceSimUnsupportedError(failure);
1384
+ }
1385
+ }
1386
+ use(name) {
1387
+ const p = this.programs.get(name);
1388
+ this.gl.useProgram(p.program);
1389
+ this.gl.bindVertexArray(this.vao);
1390
+ return p;
1391
+ }
1392
+ loc(p, name) {
1393
+ let l = p.uniforms.get(name);
1394
+ if (l === void 0) {
1395
+ l = this.gl.getUniformLocation(p.program, name);
1396
+ p.uniforms.set(name, l);
1397
+ }
1398
+ return l;
1399
+ }
1400
+ f(p, name, v) {
1401
+ this.gl.uniform1f(this.loc(p, name), v);
1402
+ }
1403
+ i(p, name, v) {
1404
+ this.gl.uniform1i(this.loc(p, name), v);
1405
+ }
1406
+ tex(p, name, unit, texture) {
1407
+ const gl = this.gl;
1408
+ gl.activeTexture(gl.TEXTURE0 + unit);
1409
+ gl.bindTexture(gl.TEXTURE_2D, texture);
1410
+ gl.uniform1i(this.loc(p, name), unit);
1411
+ }
1412
+ bindTarget(t, clear) {
1413
+ const gl = this.gl;
1414
+ gl.bindFramebuffer(gl.FRAMEBUFFER, t.fbo);
1415
+ gl.viewport(0, 0, t.size, t.size);
1416
+ if (clear) {
1417
+ gl.clearColor(clear[0], clear[1], clear[2], clear[3]);
1418
+ gl.clear(gl.COLOR_BUFFER_BIT);
1419
+ }
1420
+ }
1421
+ drawQuad() {
1422
+ this.gl.drawArrays(this.gl.TRIANGLES, 0, 3);
1423
+ }
1424
+ };
1425
+
1426
+ // src/layout/webglForce/forceSim.worker.ts
1427
+ var scope = self;
1428
+ var sim = null;
1429
+ var generation = -1;
1430
+ function post(message, transfer) {
1431
+ scope.postMessage(message, transfer);
1432
+ }
1433
+ function init() {
1434
+ try {
1435
+ if (typeof OffscreenCanvas === "undefined") throw new Error("OffscreenCanvas is not available in workers");
1436
+ const canvas = new OffscreenCanvas(1, 1);
1437
+ const gl = canvas.getContext("webgl2", {
1438
+ antialias: false,
1439
+ depth: false,
1440
+ stencil: false,
1441
+ alpha: false,
1442
+ preserveDrawingBuffer: false,
1443
+ powerPreference: "high-performance"
1444
+ });
1445
+ if (!gl) throw new Error("WebGL2 is not available in workers");
1446
+ sim = new ForceSim(gl);
1447
+ post({ type: "ready" });
1448
+ } catch (err) {
1449
+ post({ type: "error", message: err instanceof Error ? err.message : String(err) });
1450
+ }
1451
+ }
1452
+ scope.onmessage = (e) => {
1453
+ const msg = e.data;
1454
+ if (!sim) return;
1455
+ switch (msg.type) {
1456
+ case "graph":
1457
+ generation = msg.generation;
1458
+ sim.setGraph(msg.xy, msg.pinned, msg.links, msg.seed);
1459
+ sim.setAlpha(msg.alpha);
1460
+ break;
1461
+ case "params":
1462
+ sim.setParams(msg.params);
1463
+ break;
1464
+ case "alpha":
1465
+ sim.setAlpha(msg.alpha);
1466
+ break;
1467
+ case "pins":
1468
+ sim.setPins(msg.indices, msg.xy, msg.pinned);
1469
+ break;
1470
+ case "step": {
1471
+ if (msg.generation !== generation) break;
1472
+ const t0 = performance.now();
1473
+ let steps = 0;
1474
+ if (!sim.settled) {
1475
+ sim.step();
1476
+ steps = 1;
1477
+ }
1478
+ const xy = sim.readPositions(msg.buffer);
1479
+ const ms = performance.now() - t0;
1480
+ post({ type: "positions", generation, xy, alpha: sim.currentAlpha, settled: sim.settled, steps, ms }, [xy.buffer]);
1481
+ break;
1482
+ }
1483
+ case "dispose":
1484
+ sim.dispose();
1485
+ sim = null;
1486
+ scope.close();
1487
+ break;
1488
+ }
1489
+ };
1490
+ init();
1491
+ /*! Includes shader code ported from cosmos.gl (https://github.com/cosmosgl/graph).
1492
+ MIT License
1493
+
1494
+ Copyright Contributors to the cosmos.gl project.
1495
+
1496
+ Permission is hereby granted, free of charge, to any person obtaining a copy
1497
+ of this software and associated documentation files (the "Software"), to deal
1498
+ in the Software without restriction, including without limitation the rights
1499
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1500
+ copies of the Software, and to permit persons to whom the Software is
1501
+ furnished to do so, subject to the following conditions:
1502
+
1503
+ The above copyright notice and this permission notice shall be included in all
1504
+ copies or substantial portions of the Software.
1505
+
1506
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1507
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1508
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1509
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1510
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1511
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1512
+ SOFTWARE.
1513
+ */
1514
+ `;var Te=.1,oe=!1,le=class{constructor(e={}){this.mode="cpu";this.graph={layoutNodes:[],layoutEdges:[],renderNeedsUpdate:!1};this.sharedArray=new Float32Array(0);this.isFinish=!0;this.generation=0;this.running=!1;this.inFlight=!1;this.owed=!1;this.alpha=0;this.spaceSize=10;this.idToIndex=new Map;this.pinnedAt=new Map;this.disposed=!1;let{params:t,scale:n}=W(e.config??{});this.params=t,this.scale=n,this.seed=e.seed??1,this.worker=(e.createWorker??(e.thread==="worker"?be:()=>new P))(),this.post({type:"params",params:this.params}),this.readyPromise=new Promise((i,o)=>{this.worker.onerror=s=>o(new Error(s.message||"the layout worker failed to start")),this.worker.onmessage=s=>{let r=s.data;r.type==="ready"?(this.worker.onmessage=a=>this.onMessage(a.data),this.worker.onerror=null,i()):r.type==="error"&&o(new Error(r.message))}})}ready(){return this.readyPromise}start(){if(this.disposed)return;let e=this.graph.layoutNodes,t=e.length,n=this.scale;this.idToIndex=new Map,this.pinnedAt=new Map;let i=new Float32Array(t*2),o=new Uint8Array(t),s=new Float32Array(t*3),r=0,a=this.unplaced(e)?X(t)*n:0,h=_(this.seed^2654435769);for(let f=0;f<t;f++){let c=e[f];this.idToIndex.set(c.id,f);let m=c.position.x,x=c.position.y;if(a>0&&!c.pinned){let T=a*Math.sqrt(h()),E=2*Math.PI*h();m=T*Math.cos(E),x=T*Math.sin(E)}i[f*2]=m/n,i[f*2+1]=x/n,s[f*3]=m,s[f*3+1]=x,r=Math.max(r,Math.abs(m),Math.abs(x)),c.pinned&&(o[f]=1,this.pinnedAt.set(f,[m,x]))}let d=this.graph.layoutEdges,p=new Uint32Array(d.length*2),u=0;for(let f of d){let c=this.idToIndex.get(f.sourceId),m=this.idToIndex.get(f.targetId);c===void 0||m===void 0||c===m||(p[u++]=c,p[u++]=m)}this.sharedArray=s,this.spaceSize=Math.max(10,2*r),this.generation++,this.alpha=this.params.alpha,this.spare=void 0;let A=p.slice(0,u);this.post({type:"graph",generation:this.generation,xy:i,pinned:o,links:A,seed:this.seed,alpha:this.alpha},[i.buffer,o.buffer,A.buffer]),this.graph.renderNeedsUpdate=!0,this.running=t>0,this.isFinish=t===0,this.inFlight=!1,this.owed=!1,this.requestStep()}stop(){this.running=!1,this.isFinish=!0}destroy(){if(!this.disposed){this.disposed=!0,this.running=!1,this.isFinish=!0;try{this.post({type:"dispose"})}catch{}this.worker.terminate()}}pinNodes(e){let t=[],n=[],i=[];for(let o of e){let s=this.idToIndex.get(o.id);if(s===void 0)continue;let r=o.pinned!==!1;t.push(s),n.push(o.position.x/this.scale,o.position.y/this.scale),i.push(r?1:0),r?(this.pinnedAt.set(s,[o.position.x,o.position.y]),s*3+1<this.sharedArray.length&&(this.sharedArray[s*3]=o.position.x,this.sharedArray[s*3+1]=o.position.y)):this.pinnedAt.delete(s)}this.sendPins(t,n,i)}unpinNodes(e){let t=[];for(let n of e){let i=this.idToIndex.get(n);i!==void 0&&(t.push(i),this.pinnedAt.delete(i))}this.sendPins(t,new Array(t.length*2).fill(0),new Array(t.length).fill(0))}getPositions(){return this.sharedArray}getPositionTexture(){return null}getTextureSize(){return 0}getSpaceSize(){return this.spaceSize}tick(){this.inFlight?this.owed=!0:this.requestStep()}readBackPositions(){let e=this.graph.layoutNodes,t=this.sharedArray,n=Math.min(e.length,t.length/3);for(let i=0;i<n;i++)e[i].position.x=t[i*3],e[i].position.y=t[i*3+1],e[i].position.z=0}get needsUpdate(){return this.graph.renderNeedsUpdate}clearNeedsUpdate(){this.graph.renderNeedsUpdate=!1}getDimensions(){return 2}transitionDimensions(e){e===3&&!oe&&(oe=!0,console.warn('[kineviz.gl] forceLayout engine "webgl" is 2D only; the layout stays in the z = 0 plane in 3D.'))}unplaced(e){let t=0;for(let n of e)if(!n.pinned){if(Math.abs(n.position.x)>1||Math.abs(n.position.y)>1)return!1;t++}return t>1}sendPins(e,t,n){if(e.length===0||this.disposed)return;let i={type:"pins",indices:Uint32Array.from(e),xy:Float32Array.from(t),pinned:Uint8Array.from(n)};this.post(i,[i.indices.buffer,i.xy.buffer,i.pinned.buffer]),this.reheat(Te),this.graph.renderNeedsUpdate=!0}reheat(e){this.alpha<e&&(this.alpha=e,this.post({type:"alpha",alpha:e})),this.graph.layoutNodes.length!==0&&(this.running=!0,this.isFinish=!1,this.requestStep())}requestStep(){if(!this.running||this.inFlight||this.disposed)return;this.inFlight=!0;let e=this.spare;this.spare=void 0,this.post({type:"step",generation:this.generation,buffer:e},e?[e.buffer]:void 0)}onMessage(e){if(this.disposed)return;if(e.type==="busy"){if(e.generation!==this.generation)return;this.inFlight=!1,this.owed=!1,e.buffer&&(this.spare=e.buffer);return}if(e.type!=="positions"||e.generation!==this.generation)return;this.inFlight=!1,this.alpha=e.alpha;let t=e.xy,n=this.sharedArray,i=Math.min(n.length/3,t.length>>1),o=this.scale,s=0;for(let r=0;r<i;r++){let a=t[r*2]*o,h=t[r*2+1]*o;n[r*3]=a,n[r*3+1]=h,n[r*3+2]=0;let d=Math.max(Math.abs(a),Math.abs(h));d>s&&(s=d)}for(let[r,[a,h]]of this.pinnedAt)r<i&&(n[r*3]=a,n[r*3+1]=h);if(this.spaceSize=Math.max(10,2*s),this.spare=t,this.graph.renderNeedsUpdate=!0,e.settled){this.running=!1,this.isFinish=!0,this.owed=!1;return}this.owed&&(this.owed=!1,this.requestStep())}post(e,t){this.worker.postMessage(e,t)}},w=null;function be(){if(typeof Worker>"u")throw new Error("Web Workers are not available");if(!w){if(!U)throw new Error("the layout worker source is not bundled");w=URL.createObjectURL(new Blob([U],{type:"application/javascript"}))}return new Worker(w,{type:"module"})}export{le as WebGLForceLayoutController};
1515
+ /*! Includes shader code ported from cosmos.gl (https://github.com/cosmosgl/graph).
1516
+ MIT License
1517
+
1518
+ Copyright Contributors to the cosmos.gl project.
1519
+
1520
+ Permission is hereby granted, free of charge, to any person obtaining a copy
1521
+ of this software and associated documentation files (the "Software"), to deal
1522
+ in the Software without restriction, including without limitation the rights
1523
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1524
+ copies of the Software, and to permit persons to whom the Software is
1525
+ furnished to do so, subject to the following conditions:
1526
+
1527
+ The above copyright notice and this permission notice shall be included in all
1528
+ copies or substantial portions of the Software.
1529
+
1530
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1531
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1532
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1533
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1534
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1535
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1536
+ SOFTWARE.
1537
+ */
1538
+ //# sourceMappingURL=WebGLForceLayoutController-P6NPZ7WK.mjs.map