-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparticles.html
More file actions
2264 lines (1935 loc) · 71.5 KB
/
Copy pathparticles.html
File metadata and controls
2264 lines (1935 loc) · 71.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebGPU Compute Particles</title>
<!-- experiments -->
<!-- Add list of neighbors to particle structure -->
<!-- Flocking, with N nearest neighbors rather than grid -->
<!-- Add coupling constant between grid and particles to control panel -->
<!-- Add firing state, firing behavior, weights for N neighbors to particle -->
<!-- Add letters i/o capability to particles -->
<!-- -->
<style>
body {
display: flex;
margin: 0;
padding: 0;
background: #1a1a1a;
}
#control-panel {
width: 200px;
padding: 20px;
background: #2a2a2a;
color: white;
font-family: Arial, sans-serif;
font-size: 14px;
}
#control-panel h3 {
margin-top: 0;
margin-bottom: 15px;
font-size: 16px;
}
.control-group {
margin-bottom: 10px;
}
.control-group label {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
color: #ccc;
}
.control-group input[type="range"] {
width: 100%;
}
.control-group input[type="number"] {
flex: 1;
padding: 5px;
background: #1a1a1a;
color: white;
border: 1px solid #444;
border-radius: 3px;
font-size: 12px;
}
canvas {
width: calc(100vw - 240px);
height: 100vh;
display: block;
background: black;
}
#statistics {
margin-top: 20px;
padding-top: 20px;
border-top: 1px solid #444;
}
#statistics h4 {
margin-top: 0;
margin-bottom: 10px;
font-size: 14px;
}
#fps-counter {
color: white;
font-family: monospace;
font-size: 12px;
margin-bottom: 8px;
}
#energy-counter {
color: white;
font-family: monospace;
font-size: 12px;
margin-bottom: 8px;
}
#timestamp-counter {
color: white;
font-family: monospace;
font-size: 12px;
}
</style>
</head>
<body>
<div id="control-panel">
<h3>Controls</h3>
<div class="control-group">
<label for="num-particles">Number of Particles: <input type="number" id="num-particles" min="1000" max="10000000" step="1000"></label>
</div>
<div class="control-group">
<label for="drag">Drag: <input type="number" id="drag" step="0.01" value="0.99"></label>
</div>
<div class="control-group">
<label for="decay">Decay: <input type="number" id="decay" step="0.01" value="0.99"></label>
</div>
<div class="control-group">
<label for="show-particles">
<input type="checkbox" id="show-particles" checked>
Show Particles
</label>
</div>
<div class="control-group">
<label for="show-grid">
<input type="checkbox" id="show-grid">
Show Grid
</label>
</div>
<div class="control-group">
<label for="do-flocking">
<input type="checkbox" id="do-flocking" checked>
Do Flocking
</label>
</div>
<div class="control-group">
<label for="color-mode">Color Mode:
<select id="color-mode">
<option value="0">Monochrome</option>
<option value="1" selected>Velocity</option>
<option value="2">Cell</option>
</select>
</label>
</div>
<div class="control-group">
<label for="show-edges">
<input type="checkbox" id="show-edges">
Show Edges
</label>
</div>
<div class="control-group">
<label for="couple-to-grid">
<input type="checkbox" id="couple-to-grid" checked>
Couple to Grid
</label>
</div>
<div class="control-group">
<label for="torus">
<input type="checkbox" id="torus">
Torus
</label>
</div>
<div class="control-group">
<label for="cohesion">Cohesion: <input type="number" id="cohesion" step="0.001" value="0.03"></label>
</div>
<div class="control-group">
<label for="separation-strength">Separation Strength: <input type="number" id="separation-strength" step="0.001" value="0.05"></label>
</div>
<div class="control-group">
<label for="separation-distance">Separation Distance: <input type="number" id="separation-distance" step="0.001" value="0.02"></label>
</div>
<div class="control-group">
<label for="alignment">Alignment: <input type="number" id="alignment" step="0.001" value="0.009"></label>
</div>
<div class="control-group">
<label for="drag-radius">Drag Radius: <input type="number" id="drag-radius" step="0.01" value="0.05" min="0.01" max="1.0"></label>
</div>
<div class="control-group">
<label for="drag-strength">Drag Strength: <input type="number" id="drag-strength" step="0.01" value="0.03" min="0.001" max="50.0"></label>
</div>
<div class="control-group">
<button id="start-stop-btn" style="padding: 8px 16px; font-size: 14px; cursor: pointer;">Stop</button>
</div>
<div id="statistics">
<h4>Statistics</h4>
<div id="fps-counter">FPS: --</div>
<div id="energy-counter">Energy: --</div>
<div id="timestamp-counter">GPU Timing: --</div>
</div>
</div>
<canvas id="gfx" width="1000" height="1000"></canvas>
<script type="module">
// ============================================================================
// FILE STRUCTURE
// ============================================================================
// This file is organized into the following sections:
// 1. Global Configuration & Constants - WebGPU setup, constants
// 2. Simulation Parameters - All editable simulation variables
// 3. Buffer Declarations - GPU buffers for particles, grid, uniforms, etc.
// 4. Shader Definitions - All WGSL shader code (compute & render)
// 5. Initialization Functions - Particle initialization, bind group creation
// 6. Helper Functions - Utility functions for coordinate conversion, etc.
// 7. Event Handlers - Mouse/touch interaction and UI control handlers
// 8. Control Panel Setup - UI initialization and event binding
// 9. Frame Loop & Rendering - Main animation loop
//
// ============================================================================
// GLOBAL CONFIGURATION & CONSTANTS
// ============================================================================
console.log('Startup');
const adapter = await navigator.gpu.requestAdapter();
console.log('Got Adapter');
// Check for timestamp query support
const requiredFeatures = [];
if (adapter.features.has('timestamp-query')) {
requiredFeatures.push('timestamp-query');
console.log('Timestamp queries supported');
} else {
console.warn('Timestamp queries not supported - GPU timing will not be available');
}
const device = await adapter.requestDevice({ requiredFeatures });
console.log('Got Device');
const canvas = document.getElementById('gfx');
const context = canvas.getContext('webgpu');
console.log('Got Got WebGPU context');
const format = navigator.gpu.getPreferredCanvasFormat();
// Function to resize canvas to fill available space
function resizeCanvas() {
const controlPanelWidth = 240; // 200px width + 40px padding
const newWidth = window.innerWidth - controlPanelWidth;
const newHeight = window.innerHeight;
canvas.width = newWidth;
canvas.height = newHeight;
// Reconfigure WebGPU context with new size
context.configure({
device,
format,
width: newWidth,
height: newHeight
});
console.log(`Canvas resized to ${newWidth}x${newHeight}`);
}
// Initial resize
resizeCanvas();
// Resize on window resize
window.addEventListener('resize', () => {
resizeCanvas();
});
let numParticles = 100000;
const MAX_NEIGHBORS = 16; // Maximum number of neighbors per particle for flocking
let particleBuffer, cellIndexBuffer, computeBindGroup, renderBindGroup;
let neighborIndicesBuffer, neighborCountBuffer; // Neighbor list buffers
let renderParamsBuffer; // Uniform buffer for render parameters (monochrome flag)
let edgeBindGroup; // Bind group for edge rendering
let colorParamsBuffer; // Uniform buffer for color mode
let cellParticleListsBuffer; // Maps cells to particle indices for fast neighbor lookup
let frameId = null;
// Timestamp query infrastructure for GPU timing
let timestampQuerySet = null;
let timestampBuffer = null;
let timestampReadbackPending = false;
let lastTimestampReadTime = 0;
const TIMESTAMP_READ_INTERVAL = 1000; // Read timestamps every second
const timestampCounter = document.getElementById('timestamp-counter');
// Initialize timestamp query set if supported
if (device.features.has('timestamp-query')) {
// Create query set with 6 queries:
// 0-1: particle compute (start, end)
// 2-3: findNeighbors (start, end)
// 4-5: flocking (start, end)
timestampQuerySet = device.createQuerySet({
type: 'timestamp',
count: 6,
});
// Create buffer to read back timestamps (6 u64 values = 48 bytes)
timestampBuffer = device.createBuffer({
size: 48,
usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
});
console.log('Created timestamp query infrastructure');
}
// Helper function to create a compute pass with timestamp queries
// queryIndexOffset: 0 for particle compute, 2 for findNeighbors
function createTimedComputePass(encoder, queryIndexOffset = 0) {
if (!timestampQuerySet) {
// Timestamp queries not supported, return normal pass
return encoder.beginComputePass();
}
// Create compute pass with timestamp writes
return encoder.beginComputePass({
timestampWrites: {
querySet: timestampQuerySet,
beginningOfPassWriteIndex: queryIndexOffset,
endOfPassWriteIndex: queryIndexOffset + 1,
},
});
}
// Function to resolve and read back timestamps
function resolveTimestamps(encoder, currentTime) {
if (!timestampQuerySet || !timestampBuffer || !timestampStagingBuffer) {
return false;
}
const shouldReadTimestamp = !timestampReadbackPending &&
(currentTime - lastTimestampReadTime >= TIMESTAMP_READ_INTERVAL);
if (shouldReadTimestamp) {
// Resolve all queries (6 queries) to buffer
encoder.resolveQuerySet(timestampQuerySet, 0, 6, timestampBuffer, 0);
// Copy from timestamp buffer to staging buffer for readback
encoder.copyBufferToBuffer(timestampBuffer, 0, timestampStagingBuffer, 0, 48);
timestampReadbackPending = true;
lastTimestampReadTime = currentTime;
return true;
}
return false;
}
// Staging buffer for timestamp readback
let timestampStagingBuffer = null;
if (timestampBuffer) {
timestampStagingBuffer = device.createBuffer({
size: 48, // 6 u64 values
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
});
}
// ============================================================================
// INITIALIZATION FUNCTIONS
// ============================================================================
function initializeParticles() {
// JS-side data: x, y, vx, vy, r, g, b, _pad (8 floats per particle, 32 bytes)
// vec3<f32> is aligned to 16 bytes in WGSL, so we need padding
const particleData = new Float32Array(numParticles * 8);
for (let i = 0; i < numParticles; i++) {
particleData[i * 8 + 0] = (Math.random() * 2 - 1) * 0.9; // x
particleData[i * 8 + 1] = (Math.random() * 2 - 1) * 0.9; // y
particleData[i * 8 + 2] = (Math.random() * 2 - 1) * 0.1; // vx
particleData[i * 8 + 3] = (Math.random() * 2 - 1) * 0.1; // vy
particleData[i * 8 + 4] = 1.0; // r (will be set by color shader)
particleData[i * 8 + 5] = 1.0; // g
particleData[i * 8 + 6] = 1.0; // b
particleData[i * 8 + 7] = 0.0; // _pad (padding)
}
// GPU buffers
if (particleBuffer) {
particleBuffer.destroy();
}
particleBuffer = device.createBuffer({
size: particleData.byteLength,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(particleBuffer, 0, particleData);
console.log('Wrote particle buffer to GPU');
if (cellIndexBuffer) {
cellIndexBuffer.destroy();
}
cellIndexBuffer = device.createBuffer({
size: numParticles * 4, // one u32 per particle
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
// Neighbor indices buffer: flattened array where each particle has MAX_NEIGHBORS consecutive slots
// Layout: [particle0_neighbor0, particle0_neighbor1, ..., particle0_neighborN-1, particle1_neighbor0, ...]
if (neighborIndicesBuffer) {
neighborIndicesBuffer.destroy();
}
neighborIndicesBuffer = device.createBuffer({
size: numParticles * MAX_NEIGHBORS * 4, // MAX_NEIGHBORS u32s per particle
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
});
// Initialize to invalid indices (numParticles, which is out of bounds)
const neighborInitData = new Uint32Array(numParticles * MAX_NEIGHBORS);
neighborInitData.fill(numParticles); // Use numParticles as invalid marker (out of bounds)
device.queue.writeBuffer(neighborIndicesBuffer, 0, neighborInitData);
console.log('Created neighbor indices buffer');
// Neighbor count buffer: one u32 per particle storing how many valid neighbors it has
if (neighborCountBuffer) {
neighborCountBuffer.destroy();
}
neighborCountBuffer = device.createBuffer({
size: numParticles * 4, // one u32 per particle
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
});
// Initialize to zero
device.queue.writeBuffer(neighborCountBuffer, 0, new Uint32Array(numParticles));
console.log('Created neighbor count buffer');
// Cell-to-particle mapping buffer: for each cell, store indices of particles in that cell
// Note: MAX_PARTICLES_PER_CELL is fixed at shader compile time (512), so we use that value
// If particles exceed this per cell, they will be dropped (but this should be rare with 512)
const MAX_PARTICLES_PER_CELL = window.MAX_PARTICLES_PER_CELL;
if (cellParticleListsBuffer) {
cellParticleListsBuffer.destroy();
}
cellParticleListsBuffer = device.createBuffer({
size: numCells * MAX_PARTICLES_PER_CELL * 4, // u32 per particle index
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
});
// Initialize to invalid indices
const cellListInitData = new Uint32Array(numCells * MAX_PARTICLES_PER_CELL);
cellListInitData.fill(0xFFFFFFFF); // Invalid marker (JavaScript, not WGSL)
device.queue.writeBuffer(cellParticleListsBuffer, 0, cellListInitData);
console.log(`Created cell-to-particle mapping buffer (${MAX_PARTICLES_PER_CELL} particles per cell max)`);
// Store MAX_PARTICLES_PER_CELL globally for shader compilation
window.MAX_PARTICLES_PER_CELL = MAX_PARTICLES_PER_CELL;
// Recreate bind groups with new buffers
computeBindGroup = device.createBindGroup({
layout: computePipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: particleBuffer } },
{ binding: 1, resource: { buffer: cellIndexBuffer } },
{ binding: 2, resource: { buffer: uniformBuffer } },
{ binding: 3, resource: { buffer: gridVelocityBuffer } },
{ binding: 4, resource: { buffer: energySumBuffer } },
{ binding: 5, resource: { buffer: particleCountBuffer } },
],
});
// Create render params uniform buffer (just for monochrome flag)
const renderParamsData = new Float32Array(1);
renderParamsData[0] = monochrome ? 1.0 : 0.0;
renderParamsBuffer = device.createBuffer({
size: renderParamsData.byteLength,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(renderParamsBuffer, 0, renderParamsData);
renderBindGroup = device.createBindGroup({
layout: renderPipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: particleBuffer } },
],
});
// Create edge rendering bind group
edgeBindGroup = device.createBindGroup({
layout: edgePipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: particleBuffer } },
{ binding: 1, resource: { buffer: neighborIndicesBuffer } },
{ binding: 2, resource: { buffer: neighborCountBuffer } },
{ binding: 3, resource: { buffer: uniformBuffer } },
],
});
// Create build cell mapping bind group
buildCellMappingBindGroup = device.createBindGroup({
layout: buildCellMappingPipeline.getBindGroupLayout(0),
entries: [
{ binding: 1, resource: { buffer: cellIndexBuffer } },
{ binding: 4, resource: { buffer: cellParticleListsBuffer } },
{ binding: 5, resource: { buffer: particleCountBuffer } },
],
});
// Create find neighbors bind group
findNeighborsBindGroup = device.createBindGroup({
layout: findNeighborsPipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: particleBuffer } },
{ binding: 1, resource: { buffer: cellIndexBuffer } },
{ binding: 2, resource: { buffer: neighborIndicesBuffer } },
{ binding: 3, resource: { buffer: neighborCountBuffer } },
{ binding: 4, resource: { buffer: cellParticleListsBuffer } },
{ binding: 5, resource: { buffer: particleCountBuffer } },
{ binding: 6, resource: { buffer: uniformBuffer } },
],
});
// Create flocking bind group
flockingBindGroup = device.createBindGroup({
layout: flockingPipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: particleBuffer } },
{ binding: 1, resource: { buffer: neighborIndicesBuffer } },
{ binding: 2, resource: { buffer: neighborCountBuffer } },
{ binding: 3, resource: { buffer: uniformBuffer } },
],
});
// Create color params uniform buffer
const colorParamsData = new Float32Array(1);
colorParamsData[0] = colorMode;
if (colorParamsBuffer) {
colorParamsBuffer.destroy();
}
colorParamsBuffer = device.createBuffer({
size: colorParamsData.byteLength,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(colorParamsBuffer, 0, colorParamsData);
// Create color bind group
colorBindGroup = device.createBindGroup({
layout: colorPipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: particleBuffer } },
{ binding: 1, resource: { buffer: cellIndexBuffer } },
{ binding: 2, resource: { buffer: colorParamsBuffer } },
],
});
// Create mouse interaction bind group
mouseInteractionBindGroup = device.createBindGroup({
layout: mouseInteractionPipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: particleBuffer } },
{ binding: 1, resource: { buffer: mouseParamsBuffer } },
],
});
}
// Grid configuration: cells per direction
const cellsPerDirection = 50;
const numCells = cellsPerDirection * cellsPerDirection;
// Calculate MAX_PARTICLES_PER_CELL at top level for shader compilation
// Use a large fixed value to handle all reasonable particle counts (up to 10M particles)
// This is compiled into shaders, so it can't change at runtime
// For 10M particles / 2500 cells = 4000 average, with clustering we need much more
// 512 should handle most cases (can be increased to 1024 or 2048 if needed)
window.MAX_PARTICLES_PER_CELL = 512; // Fixed value that should handle most cases
const gridVelocityData = new Float32Array(numCells * 2); // Initialize to zero
const gridVelocityBuffer = device.createBuffer({
size: gridVelocityData.byteLength,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(gridVelocityBuffer, 0, gridVelocityData);
console.log('Created grid velocity buffer');
// Particle count buffer: one u32 per cell
const particleCountBuffer = device.createBuffer({
size: numCells * 4, // one u32 (4 bytes) per cell
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
});
// Initialize to zero
device.queue.writeBuffer(particleCountBuffer, 0, new Uint32Array(numCells));
console.log('Created particle count buffer');
// Simulation parameters (easily editable defaults)
let drag = 1.0;
let decay = 1.0;
let dt = 0.016;
let cohesion = 0.5;
let separationStrength = 0.05;
let separationDistance = 0.01;
let alignment = 0.012;
let monochrome = false;
let coupleToGrid = true; // Default to enabled
let torus = false; // Default to disabled (bouncing)
let colorMode = 1; // 0 = monochrome, 1 = velocity, 2 = cell
// Mouse interaction parameters
let mouseDragRadius = 0.05;
let mouseDragStrength = 0.03;
let isMouseDragging = false;
let mousePos = { x: 0, y: 0 }; // In particle coordinate space (-1 to 1)
const uniformData = new Float32Array(32); // Increased to accommodate new parameters
uniformData[0] = dt;
uniformData[1] = drag;
uniformData[2] = decay;
uniformData[3] = cohesion;
uniformData[4] = separationStrength;
uniformData[5] = separationDistance;
uniformData[6] = alignment;
uniformData[7] = coupleToGrid ? 1.0 : 0.0; // Couple to grid flag (f32: 1.0 = true, 0.0 = false)
uniformData[8] = torus ? 1.0 : 0.0; // Torus flag (f32: 1.0 = true, 0.0 = false)
const uniformBuffer = device.createBuffer({
size: uniformData.byteLength,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(uniformBuffer, 0, uniformData);
console.log('Wrote uniform buffer to GPU');
// ============================================================================
// GPU BUFFER DECLARATIONS
// ============================================================================
// All GPU buffers are declared below. Buffers are created once and reused.
//
// Mouse interaction uniform buffer
const mouseParamsData = new Float32Array(6); // mousePos (2), dragRadius, dragStrength, isActive, torus
mouseParamsData[0] = 0.0; // mousePos.x
mouseParamsData[1] = 0.0; // mousePos.y
mouseParamsData[2] = mouseDragRadius;
mouseParamsData[3] = mouseDragStrength;
mouseParamsData[4] = 0.0; // isActive
mouseParamsData[5] = torus ? 1.0 : 0.0; // torus
const mouseParamsBuffer = device.createBuffer({
size: mouseParamsData.byteLength,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(mouseParamsBuffer, 0, mouseParamsData);
console.log('Created mouse params buffer');
// Mouse interaction bind group will be created after particleBuffer is initialized
let mouseInteractionBindGroup;
// Energy sum buffer (atomic u32)
const energySumBuffer = device.createBuffer({
size: 4, // single u32
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
});
// Staging buffer to read back energy
const energyStagingBuffer = device.createBuffer({
size: 4,
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
});
// Initialize energy buffer to zero
device.queue.writeBuffer(energySumBuffer, 0, new Uint32Array([0]));
console.log('Created energy sum buffer');
// ============================================================================
// SHADER DEFINITIONS
// ============================================================================
// All WGSL shader code is defined below. Shaders are organized by function:
// - Compute shaders (particle physics, grid operations, flocking, etc.)
// - Render shaders (particle rendering, grid visualization, edges, etc.)
//
// === Compute Shader (WGSL) ===
//
const computeShaderCode = /* wgsl */`
const CELLS_PER_DIRECTION = ${cellsPerDirection}u;
const CELL_SIZE = 2.0 / f32(CELLS_PER_DIRECTION);
const MAX_CELL_INDEX = ${cellsPerDirection - 1}u;
struct Particle {
pos: vec2<f32>,
vel: vec2<f32>,
color: vec3<f32>,
_pad: f32, // Padding to align struct to 32 bytes (8 floats)
};
@group(0) @binding(0)
var<storage, read_write> particles: array<Particle>;
@group(0) @binding(1)
var<storage, read_write> cellIndices: array<u32>;
@group(0) @binding(3)
var<storage, read_write> gridVelocities: array<vec2<f32>>;
@group(0) @binding(4)
var<storage, read_write> energySum: atomic<u32>;
@group(0) @binding(5)
var<storage, read_write> particleCounts: array<atomic<u32>>;
struct Params {
dt: f32,
drag: f32,
decay: f32,
cohesion: f32,
separationStrength: f32,
separationDistance: f32,
alignment: f32,
coupleToGrid: f32, // 1.0 = true, 0.0 = false
torus: f32, // 1.0 = true, 0.0 = false
};
@group(0) @binding(2)
var<uniform> params: Params;
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
let i = id.x;
if (i >= arrayLength(&particles)) { return; }
var p = particles[i];
// --- physics ---
p.pos += p.vel * params.dt;
// boundary handling: bounce or wrap (torus)
if (params.torus > 0.5) {
// Torus mode: wrap around edges (coordinate range is -1.0 to 1.0, width is 2.0)
// Wrap x coordinate: p.pos.x = ((p.pos.x + 1.0) mod 2.0) - 1.0
p.pos.x = fract((p.pos.x + 1.0) / 2.0) * 2.0 - 1.0;
// Wrap y coordinate
p.pos.y = fract((p.pos.y + 1.0) / 2.0) * 2.0 - 1.0;
} else {
// Bounce mode: reflect velocity
if (abs(p.pos.x) > 1.0) { p.vel.x = -p.vel.x; }
if (abs(p.pos.y) > 1.0) { p.vel.y = -p.vel.y; }
}
// --- grid assignment ---
let gx = clamp(floor((p.pos.x + 1.0) / CELL_SIZE), 0.0, f32(MAX_CELL_INDEX));
let gy = clamp(floor((p.pos.y + 1.0) / CELL_SIZE), 0.0, f32(MAX_CELL_INDEX));
let cellIndex = u32(gy * f32(CELLS_PER_DIRECTION) + gx);
cellIndices[i] = cellIndex;
// Count particle in this cell (atomic increment)
atomicAdd(&particleCounts[cellIndex], 1u);
// --- grid-particle interaction ---
if (params.coupleToGrid > 0.5) {
let gridVel = gridVelocities[cellIndex];
let particleVelBefore = p.vel; // Store original particle velocity
// grid-particle coupling constants
const GRID_TO_PARTICLE = 0.1; // typical 0.1
const PARTICLE_TO_GRID = 0.001; // typical 0.001
// Add grid velocity to particle velocity
let gridVelMagnitude = length(gridVel);
if (gridVelMagnitude > 0.0) {
p.vel += normalize(gridVel) * (PARTICLE_TO_GRID * gridVelMagnitude);
}
// Accumulate particle velocity contribution to grid (will be normalized by count later)
gridVelocities[cellIndex] = gridVel + particleVelBefore * GRID_TO_PARTICLE;
}
// Apply decay proportional to square of velocity
let velSquared = dot(p.vel, p.vel);
p.vel *= (1.0 - velSquared * params.drag);
p.vel *= params.decay;
// Accumulate energy (velocity^2) atomically
// Convert velSquared (0.0-1.0) to u32 in range 1-100
let energyValue = u32(velSquared * 10000.0);
atomicAdd(&energySum, energyValue);
particles[i] = p;
}
`;
const computeModule = device.createShaderModule({ code: computeShaderCode });
const computePipeline = device.createComputePipeline({
layout: 'auto',
compute: { module: computeModule, entryPoint: 'main' },
});
//
// === Grid Decay Compute Shader (WGSL) ===
//
const gridDecayShaderCode = /* wgsl */`
@group(0) @binding(3)
var<storage, read_write> gridVelocities: array<vec2<f32>>;
struct Params {
dt: f32,
drag: f32,
decay: f32,
};
@group(0) @binding(2)
var<uniform> params: Params;
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
let i = id.x;
if (i >= arrayLength(&gridVelocities)) { return; }
// Apply decay factor to grid velocity
gridVelocities[i] *= params.decay;
}
`;
const gridDecayModule = device.createShaderModule({ code: gridDecayShaderCode });
const gridDecayPipeline = device.createComputePipeline({
layout: 'auto',
compute: { module: gridDecayModule, entryPoint: 'main' },
});
const gridDecayBindGroup = device.createBindGroup({
layout: gridDecayPipeline.getBindGroupLayout(0),
entries: [
{ binding: 2, resource: { buffer: uniformBuffer } },
{ binding: 3, resource: { buffer: gridVelocityBuffer } },
],
});
//
// === Velocity Normalization Compute Shader (WGSL) ===
//
const normalizeVelocityShaderCode = /* wgsl */`
@group(0) @binding(0)
var<storage, read_write> gridVelocities: array<vec2<f32>>;
@group(0) @binding(1)
var<storage, read_write> particleCounts: array<atomic<u32>>;
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
let i = id.x;
if (i >= arrayLength(&gridVelocities)) { return; }
// Get particle count for this cell
let count = f32(atomicLoad(&particleCounts[i]));
// Normalize velocity by particle count (avoid division by zero)
if (count > 0.0) {
gridVelocities[i] = gridVelocities[i] / count;
} else {
gridVelocities[i] = vec2<f32>(0.0, 0.0);
}
}
`;
const normalizeVelocityModule = device.createShaderModule({ code: normalizeVelocityShaderCode });
const normalizeVelocityPipeline = device.createComputePipeline({
layout: 'auto',
compute: { module: normalizeVelocityModule, entryPoint: 'main' },
});
const normalizeVelocityBindGroup = device.createBindGroup({
layout: normalizeVelocityPipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: gridVelocityBuffer } },
{ binding: 1, resource: { buffer: particleCountBuffer } },
],
});
//
// === Build Cell-to-Particle Mapping Compute Shader (WGSL) ===
// Builds a list of particle indices for each cell for fast neighbor lookup
//
const buildCellMappingShaderCode = /* wgsl */`
const MAX_PARTICLES_PER_CELL = ${window.MAX_PARTICLES_PER_CELL}u;
@group(0) @binding(1)
var<storage, read> cellIndices: array<u32>;
@group(0) @binding(4)
var<storage, read_write> cellParticleLists: array<u32>; // Flattened: numCells * MAX_PARTICLES_PER_CELL
@group(0) @binding(5)
var<storage, read_write> particleCounts: array<atomic<u32>>;
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
let particleIdx = id.x;
if (particleIdx >= arrayLength(&cellIndices)) { return; }
let cellIdx = cellIndices[particleIdx];
// Get the current count for this cell (atomically)
let slot = atomicAdd(&particleCounts[cellIdx], 1u);
// Check if we have room in this cell's list
if (slot < MAX_PARTICLES_PER_CELL) {
let listBase = cellIdx * MAX_PARTICLES_PER_CELL;
cellParticleLists[listBase + slot] = particleIdx;
}
// If slot >= MAX_PARTICLES_PER_CELL, we've exceeded capacity (shouldn't happen with good estimate)
}
`;
const buildCellMappingModule = device.createShaderModule({ code: buildCellMappingShaderCode });
const buildCellMappingPipeline = device.createComputePipeline({
layout: 'auto',
compute: { module: buildCellMappingModule, entryPoint: 'main' },
});
let buildCellMappingBindGroup; // Will be created in initializeParticles()
//
// === Find Neighbors Compute Shader (WGSL) ===
// Finds the N nearest neighbors for each particle using the grid for spatial acceleration
//
const findNeighborsShaderCode = /* wgsl */`
const CELLS_PER_DIRECTION = ${cellsPerDirection}u;
const MAX_NEIGHBORS = ${MAX_NEIGHBORS}u;
const MAX_PARTICLES_PER_CELL = ${window.MAX_PARTICLES_PER_CELL}u;
struct Particle {
pos: vec2<f32>,
vel: vec2<f32>,
color: vec3<f32>,
_pad: f32, // Padding to align struct to 32 bytes (8 floats)
};
@group(0) @binding(0)
var<storage, read> particles: array<Particle>;
@group(0) @binding(1)
var<storage, read> cellIndices: array<u32>;
@group(0) @binding(2)
var<storage, read_write> neighborIndices: array<u32>;
@group(0) @binding(3)
var<storage, read_write> neighborCounts: array<u32>;
@group(0) @binding(4)
var<storage, read> cellParticleLists: array<u32>; // Flattened: numCells * MAX_PARTICLES_PER_CELL
@group(0) @binding(5)
var<storage, read_write> particleCounts: array<atomic<u32>>; // Count of particles per cell (atomic)
struct Params {
dt: f32,
drag: f32,
decay: f32,
cohesion: f32,
separationStrength: f32,
separationDistance: f32,
alignment: f32,
coupleToGrid: f32,
torus: f32, // 1.0 = true, 0.0 = false
};
@group(0) @binding(6)
var<uniform> params: Params;
// Helper function to calculate toroidal distance squared
fn toroidalDistSq(pos1: vec2<f32>, pos2: vec2<f32>) -> f32 {
var dx = pos2.x - pos1.x;
var dy = pos2.y - pos1.y;
// Wrap distance components for torus (coordinate range is -1.0 to 1.0, width is 2.0)
if (abs(dx) > 1.0) {
dx = dx - sign(dx) * 2.0;
}
if (abs(dy) > 1.0) {
dy = dy - sign(dy) * 2.0;
}
return dx * dx + dy * dy;
}
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
let particleIdx = id.x;
if (particleIdx >= arrayLength(&particles)) { return; }
let p = particles[particleIdx];
let myCell = cellIndices[particleIdx];
// Calculate grid coordinates for this particle's cell
let myGx = myCell % CELLS_PER_DIRECTION;
let myGy = myCell / CELLS_PER_DIRECTION;
// Array to store candidate neighbors with their distances
var nearestIndices: array<u32, MAX_NEIGHBORS>;
var nearestDistances: array<f32, MAX_NEIGHBORS>;
var numFound: u32 = 0u;
// Initialize distances to a large value
for (var i = 0u; i < MAX_NEIGHBORS; i++) {
nearestDistances[i] = 1000000.0; // Large initial distance
nearestIndices[i] = 0xFFFFFFFFu; // Invalid index marker
}
// Check particles in the same cell and 8 adjacent cells (3x3 grid)
for (var dy = 0u; dy < 3u; dy++) {
for (var dx = 0u; dx < 3u; dx++) {
// Convert 0-2 range to -1 to +1 range
var offsetX = i32(dx) - 1;
var offsetY = i32(dy) - 1;
var checkGx = i32(myGx) + offsetX;
var checkGy = i32(myGy) + offsetY;
// Skip if out of bounds
if (checkGx < 0 || checkGx >= i32(CELLS_PER_DIRECTION)) { continue; }
if (checkGy < 0 || checkGy >= i32(CELLS_PER_DIRECTION)) { continue; }
let checkCell = u32(checkGy) * CELLS_PER_DIRECTION + u32(checkGx);
// Get the list of particles in this cell from the pre-built mapping
let cellParticleCountRaw = atomicLoad(&particleCounts[checkCell]);
// Clamp to MAX_PARTICLES_PER_CELL because particles beyond capacity are dropped
let cellParticleCount = min(cellParticleCountRaw, MAX_PARTICLES_PER_CELL);
let listBase = checkCell * MAX_PARTICLES_PER_CELL;
// Iterate only through particles in this cell (much faster!)
for (var slot = 0u; slot < cellParticleCount; slot++) {
let candidateIdx = cellParticleLists[listBase + slot];
if (candidateIdx == particleIdx) { continue; } // Skip self
if (candidateIdx >= arrayLength(&particles)) { continue; } // Skip invalid
let candidate = particles[candidateIdx];
// Use toroidal distance if torus mode is enabled
let distSq = select(
dot(candidate.pos - p.pos, candidate.pos - p.pos),
toroidalDistSq(p.pos, candidate.pos),
params.torus > 0.5
);
// Insert this candidate if it's closer than our current farthest neighbor