-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebgl-renderer.js
More file actions
1762 lines (1442 loc) · 80.4 KB
/
webgl-renderer.js
File metadata and controls
1762 lines (1442 loc) · 80.4 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
// Ultra-High-Performance WebGL Renderer with Transform Feedback
class WebGLRenderer {
constructor(canvas) {
this.canvas = canvas;
this.gl = canvas.getContext('webgl2', {
powerPreference: 'high-performance',
antialias: true,
premultipliedAlpha: false,
alpha: false
});
if (!this.gl) throw new Error('WebGL2 not supported');
// Log WebGL renderer info for debugging GPU selection
const ext = this.gl.getExtension('WEBGL_debug_renderer_info');
if (ext) {
const vendor = this.gl.getParameter(ext.UNMASKED_VENDOR_WEBGL);
const renderer = this.gl.getParameter(ext.UNMASKED_RENDERER_WEBGL);
console.log('WebGL Vendor:', vendor);
console.log('WebGL Renderer:', renderer);
}
this.triangleCount = 1000;
this.linearVelocityScale = 0.01;
this.angularVelocityScale = 0.01;
this.saturation = 0.5;
this.Collision = true;
this.triangleCoverage = 40; // Percentage of screen covered by triangles (1-100%)
this.gravity = false;
this.gravityStrength = 0.01; // Gravity acceleration
this.triangleMass = 1.0; // Mass affects collision behavior
this.viscosity = 0.0; // Air resistance/damping
// Triangle size configuration for adaptive sizing
this.baseTriangleSize = 0.01;
this.minTriangleSize = 0.001;
this.maxTriangleSize = 0.15;
this.canvasWidth = 1;
this.canvasHeight = 1;
// Spatial grid parameters for optimized collision detection
this.restitution = 1.0; // Perfect elastic collisions for energy conservation (was 0.8)
this.gridSize = 0.1; // Size of each spatial grid cell
this.gridWidth = 20; // Number of grid cells in X direction
this.gridHeight = 20; // Number of grid cells in Y direction
// Stacking physics parameters (only used when gravity is enabled)
this.stackingRestitution = 0.3; // Lower restitution for stable stacking
this.staticFriction = 0.6; // Static friction coefficient for resting contacts
this.kineticFriction = 0.4; // Kinetic friction coefficient for sliding
this.restingContactThreshold = 0.05; // Speed threshold for resting vs dynamic collision
this.sleepThreshold = 0.001; // Speed below which objects are considered stationary
// Initialize arrays immediately to prevent undefined access
this.positions = new Float32Array(this.triangleCount * 2);
this.velocities = new Float32Array(this.triangleCount * 2);
this.rotations = new Float32Array(this.triangleCount);
this.angularVelocities = new Float32Array(this.triangleCount);
this.colors = new Float32Array(this.triangleCount * 3);
// Transform Feedback system for GPU collision detection
this.useGPUCollision = true;
this.currentPhysicsBuffer = null;
this.nextPhysicsBuffer = null;
// Debug mode: disable GPU collision temporarily
this.debugMode = false; // RE-ENABLE GPU PHYSICS FOR TESTING
// Safety: track if GPU system is working
this.gpuSystemFailed = false;
this.lastSuccessfulUpdate = performance.now();
// Pause state to control rendering and GPU processing
this.paused = false;
this.init();
}
init() {
const gl = this.gl;
// Rendering shader (standard approach)
const renderVsSource = `#version 300 es
in vec2 a_position;
in vec2 a_instance_position;
in float a_instance_rotation;
in vec3 a_instance_color;
uniform float u_saturation;
out vec3 v_color;
void main() {
// Apply rotation to the triangle vertex
float c = cos(a_instance_rotation);
float s = sin(a_instance_rotation);
mat2 rotation = mat2(c, -s, s, c);
vec2 rotatedPos = rotation * a_position;
gl_Position = vec4(rotatedPos + a_instance_position, 0.0, 1.0);
// Apply saturation: interpolate between grayscale and original color
vec3 gray = vec3(dot(a_instance_color, vec3(0.299, 0.587, 0.114)));
v_color = mix(gray, a_instance_color, u_saturation);
}
`;
const renderFsSource = `#version 300 es
precision highp float;
in vec3 v_color;
out vec4 fragColor;
void main() {
fragColor = vec4(v_color, 1.0);
}
`;
// Compile render program
const renderVertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(renderVertexShader, renderVsSource);
gl.compileShader(renderVertexShader);
// Check vertex shader compilation
if (!gl.getShaderParameter(renderVertexShader, gl.COMPILE_STATUS)) {
console.error('Vertex shader compilation failed:', gl.getShaderInfoLog(renderVertexShader));
throw new Error('Failed to compile vertex shader');
}
const renderFragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(renderFragmentShader, renderFsSource);
gl.compileShader(renderFragmentShader);
// Check fragment shader compilation
if (!gl.getShaderParameter(renderFragmentShader, gl.COMPILE_STATUS)) {
console.error('Fragment shader compilation failed:', gl.getShaderInfoLog(renderFragmentShader));
throw new Error('Failed to compile fragment shader');
}
this.renderProgram = gl.createProgram();
gl.attachShader(this.renderProgram, renderVertexShader);
gl.attachShader(this.renderProgram, renderFragmentShader);
gl.linkProgram(this.renderProgram);
// Check program linking
if (!gl.getProgramParameter(this.renderProgram, gl.LINK_STATUS)) {
console.error('Program linking failed:', gl.getProgramInfoLog(this.renderProgram));
throw new Error('Failed to link shader program');
}
this.renderSaturationUniform = gl.getUniformLocation(this.renderProgram, 'u_saturation');
// Create buffers
this.createBuffers();
// Create GPU collision detection system
this.createGPUCollisionSystem();
// Set up vertex attributes
this.setupRenderAttributes();
// Initialize data
this.initializeTriangleData();
gl.clearColor(0, 0, 0, 1);
}
// NEW: Create GPU-based collision detection system using Transform Feedback
createGPUCollisionSystem() {
const gl = this.gl;
// Physics + collision compute shader in vertex shader with Transform Feedback
const physicsVsSource = `#version 300 es
// Current state inputs
in vec2 a_position;
in vec2 a_velocity;
in float a_rotation;
in float a_angular_velocity;
// Triangle data as 2D textures for efficient collision queries
uniform sampler2D u_position_texture;
uniform sampler2D u_velocity_texture;
uniform float u_triangle_count;
uniform float u_collision_distance;
uniform float u_texture_width;
uniform float u_texture_height;
uniform float u_delta_time;
uniform float u_gravity_strength;
uniform float u_viscosity;
uniform float u_mass;
uniform float u_bounce_enabled;
uniform float u_gravity_enabled;
uniform float u_restitution; // Normal restitution coefficient
uniform float u_stacking_restitution; // Lower restitution for stacking when gravity is on
uniform float u_static_friction; // Static friction coefficient
uniform float u_kinetic_friction; // Kinetic friction coefficient
uniform float u_resting_threshold; // Speed threshold for resting contact detection
uniform float u_sleep_threshold; // Speed threshold for sleeping objects
// Spatial grid parameters for optimized collision detection
uniform float u_grid_size; // Size of each grid cell
uniform float u_grid_width; // Number of cells in X direction
uniform float u_grid_height; // Number of cells in Y direction
// Transform feedback outputs - everything computed on GPU
out vec2 v_new_position;
out vec2 v_new_velocity;
out float v_new_rotation;
out float v_new_angular_velocity;
// Spatial grid helper functions
ivec2 getGridCell(vec2 pos) {
// Convert world position to grid coordinates
vec2 gridPos = (pos + 1.0) / u_grid_size; // Normalize from [-1,1] to [0, 2/grid_size]
return ivec2(floor(gridPos.x), floor(gridPos.y));
}
int getTriangleIndex(ivec2 gridCell, int cellOffset) {
// This is a simplified approach - in a full implementation,
// we'd need a proper spatial hash table
// For now, we'll check all triangles but prioritize nearby ones
return cellOffset;
}
void main() {
vec2 pos = a_position;
vec2 vel = a_velocity;
float rot = a_rotation;
float angVel = a_angular_velocity;
// Basic physics updates (match CPU version time scaling)
if (u_gravity_enabled > 0.5 && u_gravity_strength > 0.0) {
vel.y -= u_gravity_strength * u_delta_time * 60.0;
}
if (u_viscosity > 0.0) {
float damping = max(0.0, 1.0 - (u_viscosity * u_delta_time * 60.0));
vel *= damping;
angVel *= damping;
}
pos += vel * u_delta_time * 60.0;
rot += angVel * u_delta_time * 60.0;
// Boundary collisions with gravity-dependent behavior
bool hitBoundary = false;
float boundaryRestitution = u_gravity_enabled > 0.5 ? u_stacking_restitution : u_restitution;
if (pos.x > 1.0) {
vel.x = -abs(vel.x) * boundaryRestitution;
pos.x = 1.0;
hitBoundary = true;
} else if (pos.x < -1.0) {
vel.x = abs(vel.x) * boundaryRestitution;
pos.x = -1.0;
hitBoundary = true;
}
if (pos.y > 1.0) {
vel.y = -abs(vel.y) * boundaryRestitution;
pos.y = 1.0;
hitBoundary = true;
} else if (pos.y < -1.0) {
vel.y = abs(vel.y) * boundaryRestitution;
pos.y = -1.0;
hitBoundary = true;
// Special handling for ground contact when gravity is on
if (u_gravity_enabled > 0.5) {
// Apply ground friction for horizontal movement
if (abs(vel.y) < u_resting_threshold) {
vel.y = 0.0; // Stop small bounces
vel.x *= (1.0 - u_kinetic_friction * 0.5); // Apply friction
}
}
}
// Add a tiny bit of randomness to break potential synchronization
if (hitBoundary) {
float triangleId = float(gl_VertexID);
vel *= 1.0 + sin(triangleId * 0.1) * 0.001; // Reduced randomness
}
// Spatial grid-based triangle-triangle collision detection
if (u_bounce_enabled > 0.5 && u_triangle_count > 1.0) {
// Get current triangle's grid cell
ivec2 myGridCell = getGridCell(pos);
// Check triangles in current cell and 8 adjacent cells (3x3 grid)
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
ivec2 checkCell = myGridCell + ivec2(dx, dy);
// Skip cells outside grid bounds
if (checkCell.x < 0 || checkCell.x >= int(u_grid_width) ||
checkCell.y < 0 || checkCell.y >= int(u_grid_height)) {
continue;
}
// For now, check all triangles (simplified spatial partitioning)
int triangleCount = int(u_triangle_count);
for (int i = 0; i < triangleCount; i++) {
if (i == gl_VertexID) continue;
// Efficient 2D texture lookup for other triangle data
float texX = mod(float(i), u_texture_width);
float texY = floor(float(i) / u_texture_width);
vec2 texCoord = vec2((texX + 0.5) / u_texture_width, (texY + 0.5) / u_texture_height);
vec2 otherPos = texture(u_position_texture, texCoord).xy;
// Skip if other triangle is not in current search cell
ivec2 otherGridCell = getGridCell(otherPos);
if (otherGridCell != checkCell) continue;
vec2 otherVel = texture(u_velocity_texture, texCoord).xy;
vec2 delta = pos - otherPos;
float distSq = dot(delta, delta);
if (distSq < u_collision_distance * u_collision_distance && distSq > 0.0001) {
float dist = sqrt(distSq);
vec2 normal = delta / dist;
vec2 relativeVel = vel - otherVel;
float relativeSpeed = dot(relativeVel, normal);
if (relativeSpeed < 0.0) { // Approaching
// Choose restitution based on gravity state and contact type
float effectiveRestitution = u_restitution;
if (u_gravity_enabled > 0.5) {
// When gravity is on, use stacking physics
if (abs(relativeSpeed) < u_resting_threshold) {
// Resting contact - use lower restitution for energy dissipation
effectiveRestitution = u_stacking_restitution;
} else {
// Dynamic collision - blend between normal and stacking restitution
effectiveRestitution = mix(u_stacking_restitution, u_restitution, 0.5);
}
}
// ENERGY CONSERVATION: Only process collision if this triangle has lower ID
if (gl_VertexID < i) {
// Standardized collision response with gravity-dependent restitution
float impulse = -(1.0 + effectiveRestitution) * relativeSpeed * 0.5;
vec2 impulseVec = impulse * normal;
// Apply normal impulse
vel += impulseVec / u_mass;
// Apply friction when gravity is enabled
if (u_gravity_enabled > 0.5) {
// Calculate tangential component for friction
vec2 tangent = relativeVel - dot(relativeVel, normal) * normal;
float tangentSpeed = length(tangent);
if (tangentSpeed > 0.0001) {
vec2 tangentDir = tangent / tangentSpeed;
// Apply friction based on contact type
float frictionCoeff = abs(relativeSpeed) < u_resting_threshold ?
u_static_friction : u_kinetic_friction;
float frictionImpulse = min(abs(impulse) * frictionCoeff,
tangentSpeed * 0.5);
vel -= frictionImpulse * tangentDir / u_mass;
}
}
// Reduced rotational effects for stability
float rotationalFactor = u_gravity_enabled > 0.5 ? 0.01 : 0.02;
angVel += impulse * rotationalFactor / u_mass;
// Small position correction to prevent penetration when gravity is on
if (u_gravity_enabled > 0.5) {
float penetration = u_collision_distance - dist;
if (penetration > 0.0) {
pos += normal * penetration * 0.1; // 10% correction
}
}
}
// Only process one collision per frame to avoid instability
dy = 2; dx = 2; // Break out of nested loops
break;
}
}
}
}
}
}
// Apply sleeping behavior when gravity is on
if (u_gravity_enabled > 0.5) {
float speed = length(vel);
if (speed < u_sleep_threshold && abs(angVel) < u_sleep_threshold * 10.0) {
// Object is nearly stationary - reduce to zero for stability
vel = vec2(0.0, 0.0);
angVel = 0.0;
}
}
v_new_position = pos;
v_new_velocity = vel;
v_new_rotation = rot;
v_new_angular_velocity = angVel;
gl_Position = vec4(0.0); // Dummy - we only care about transform feedback
}
`;
// Minimal fragment shader for transform feedback (required but not used)
const physicsFsSource = `#version 300 es
precision highp float;
out vec4 fragColor;
void main() {
fragColor = vec4(0.0); // Not used - we only care about transform feedback
}
`;
// Create physics shader program with transform feedback
const physicsVertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(physicsVertexShader, physicsVsSource);
gl.compileShader(physicsVertexShader);
if (!gl.getShaderParameter(physicsVertexShader, gl.COMPILE_STATUS)) {
console.error('Physics vertex shader compilation failed:', gl.getShaderInfoLog(physicsVertexShader));
throw new Error('Failed to compile physics vertex shader');
}
const physicsFragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(physicsFragmentShader, physicsFsSource);
gl.compileShader(physicsFragmentShader);
if (!gl.getShaderParameter(physicsFragmentShader, gl.COMPILE_STATUS)) {
console.error('Physics fragment shader compilation failed:', gl.getShaderInfoLog(physicsFragmentShader));
throw new Error('Failed to compile physics fragment shader');
}
this.physicsProgram = gl.createProgram();
gl.attachShader(this.physicsProgram, physicsVertexShader);
gl.attachShader(this.physicsProgram, physicsFragmentShader);
// Set up transform feedback varyings BEFORE linking
const varyings = ['v_new_position', 'v_new_velocity', 'v_new_rotation', 'v_new_angular_velocity'];
gl.transformFeedbackVaryings(this.physicsProgram, varyings, gl.INTERLEAVED_ATTRIBS);
gl.linkProgram(this.physicsProgram);
if (!gl.getProgramParameter(this.physicsProgram, gl.LINK_STATUS)) {
console.error('Physics program linking failed:', gl.getProgramInfoLog(this.physicsProgram));
throw new Error('Failed to link physics shader program');
}
// Get uniform locations for physics program
this.physicsUniforms = {
triangleCount: gl.getUniformLocation(this.physicsProgram, 'u_triangle_count'),
collisionDistance: gl.getUniformLocation(this.physicsProgram, 'u_collision_distance'),
deltaTime: gl.getUniformLocation(this.physicsProgram, 'u_delta_time'),
gravityStrength: gl.getUniformLocation(this.physicsProgram, 'u_gravity_strength'),
viscosity: gl.getUniformLocation(this.physicsProgram, 'u_viscosity'),
mass: gl.getUniformLocation(this.physicsProgram, 'u_mass'),
bounceEnabled: gl.getUniformLocation(this.physicsProgram, 'u_bounce_enabled'),
gravityEnabled: gl.getUniformLocation(this.physicsProgram, 'u_gravity_enabled'),
positionTexture: gl.getUniformLocation(this.physicsProgram, 'u_position_texture'),
velocityTexture: gl.getUniformLocation(this.physicsProgram, 'u_velocity_texture'),
textureWidth: gl.getUniformLocation(this.physicsProgram, 'u_texture_width'),
textureHeight: gl.getUniformLocation(this.physicsProgram, 'u_texture_height'),
restitution: gl.getUniformLocation(this.physicsProgram, 'u_restitution'),
stackingRestitution: gl.getUniformLocation(this.physicsProgram, 'u_stacking_restitution'),
staticFriction: gl.getUniformLocation(this.physicsProgram, 'u_static_friction'),
kineticFriction: gl.getUniformLocation(this.physicsProgram, 'u_kinetic_friction'),
restingThreshold: gl.getUniformLocation(this.physicsProgram, 'u_resting_threshold'),
sleepThreshold: gl.getUniformLocation(this.physicsProgram, 'u_sleep_threshold'),
gridSize: gl.getUniformLocation(this.physicsProgram, 'u_grid_size'),
gridWidth: gl.getUniformLocation(this.physicsProgram, 'u_grid_width'),
gridHeight: gl.getUniformLocation(this.physicsProgram, 'u_grid_height')
};
// Create transform feedback object
this.transformFeedback = gl.createTransformFeedback();
}
// NEW: Create dual buffers for ping-pong physics computation
createPhysicsBuffers() {
const gl = this.gl;
// Validate triangle count for physics buffers
if (this.triangleCount <= 0) {
return; // Skip physics buffer creation for invalid triangle count
}
// Calculate optimal 2D texture dimensions for physics data
const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
const maxTriangles = maxTextureSize * maxTextureSize; // 2D texture capacity
if (this.triangleCount > maxTriangles) {
// For extremely large triangle counts, disable GPU physics and use CPU instead
this.useGPUCollision = false;
this.gpuSystemFailed = true;
console.warn(`Triangle count ${this.triangleCount} exceeds 2D texture capacity ${maxTriangles}`);
return;
} else {
// Re-enable GPU physics if triangle count is within limits
this.useGPUCollision = true;
this.gpuSystemFailed = false;
}
// Calculate 2D texture dimensions - use square texture when possible for optimal memory layout
this.textureWidth = Math.ceil(Math.sqrt(this.triangleCount));
this.textureHeight = Math.ceil(this.triangleCount / this.textureWidth);
// Ensure texture dimensions don't exceed maximum
if (this.textureWidth > maxTextureSize || this.textureHeight > maxTextureSize) {
// Use maximum width and calculate height
this.textureWidth = maxTextureSize;
this.textureHeight = Math.ceil(this.triangleCount / maxTextureSize);
if (this.textureHeight > maxTextureSize) {
this.useGPUCollision = false;
this.gpuSystemFailed = true;
console.warn('Triangle count exceeds maximum 2D texture capacity');
return;
}
}
console.log(`Physics 2D texture: ${this.textureWidth}x${this.textureHeight} for ${this.triangleCount} triangles`);
console.log(`Max triangles supported: ${maxTriangles.toLocaleString()}`);
// Store total texture capacity for validation
this.textureCapacity = this.textureWidth * this.textureHeight;
// Each triangle needs: position(2) + velocity(2) + rotation(1) + angVel(1) = 6 floats
const dataSize = this.triangleCount * 6 * 4; // 6 floats per triangle * 4 bytes per float
// Create dual buffers for ping-pong (no CPU involvement)
this.physicsBufferA = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.physicsBufferA);
gl.bufferData(gl.ARRAY_BUFFER, dataSize, gl.DYNAMIC_DRAW);
this.physicsBufferB = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.physicsBufferB);
gl.bufferData(gl.ARRAY_BUFFER, dataSize, gl.DYNAMIC_DRAW);
// Create 2D textures for collision detection data access
// Position texture: RG32F stores (x, y) position data
this.positionTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, this.positionTexture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RG32F, this.textureWidth, this.textureHeight, 0, gl.RG, gl.FLOAT, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
// Velocity texture: RG32F stores (vx, vy) velocity data
this.velocityTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, this.velocityTexture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RG32F, this.textureWidth, this.textureHeight, 0, gl.RG, gl.FLOAT, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
// DON'T upload initial data here - arrays are still zeros
// Initial data will be uploaded after initializeTriangleData() is called
this.currentPhysicsBuffer = this.physicsBufferA;
this.nextPhysicsBuffer = this.physicsBufferB;
}
// NEW: Upload initial physics data to GPU buffers
uploadInitialPhysicsData() {
const gl = this.gl;
// Skip if no triangles or physics buffers weren't created
if (this.triangleCount <= 0 || !this.physicsBufferA || !this.physicsBufferB) {
return;
}
// Pack data: position(2) + velocity(2) + rotation(1) + angVel(1) = 6 floats per triangle
const physicsData = new Float32Array(this.triangleCount * 6);
for (let i = 0; i < this.triangleCount; i++) {
const baseIndex = i * 6;
physicsData[baseIndex] = this.positions[i * 2]; // pos.x
physicsData[baseIndex + 1] = this.positions[i * 2 + 1]; // pos.y
physicsData[baseIndex + 2] = this.velocities[i * 2]; // vel.x
physicsData[baseIndex + 3] = this.velocities[i * 2 + 1]; // vel.y
physicsData[baseIndex + 4] = this.rotations[i]; // rotation
physicsData[baseIndex + 5] = this.angularVelocities[i]; // angular velocity
}
// Upload to both buffers
gl.bindBuffer(gl.ARRAY_BUFFER, this.physicsBufferA);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, physicsData);
gl.bindBuffer(gl.ARRAY_BUFFER, this.physicsBufferB);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, physicsData);
// Update 2D textures for collision detection with proper layout
// Create 2D texture data arrays from 1D position/velocity arrays
const positionTextureData = this.createTextureDataFromArray(this.positions);
const velocityTextureData = this.createTextureDataFromArray(this.velocities);
gl.bindTexture(gl.TEXTURE_2D, this.positionTexture);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.textureWidth, this.textureHeight, gl.RG, gl.FLOAT, positionTextureData);
gl.bindTexture(gl.TEXTURE_2D, this.velocityTexture);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.textureWidth, this.textureHeight, gl.RG, gl.FLOAT, velocityTextureData);
}
// Helper function to convert 1D triangle data arrays to 2D texture layout
createTextureDataFromArray(sourceArray) {
// sourceArray contains pairs of values (x,y) for positions or (vx,vy) for velocities
// We need to arrange them in a 2D texture layout
// Safety check for texture dimensions
if (!this.textureWidth || !this.textureHeight) {
console.warn('Texture dimensions not set, falling back to 1D layout');
return sourceArray;
}
const textureData = new Float32Array(this.textureWidth * this.textureHeight * 2); // RG format = 2 components
for (let i = 0; i < this.triangleCount; i++) {
// Calculate 2D texture coordinates from triangle index
const texX = i % this.textureWidth;
const texY = Math.floor(i / this.textureWidth);
const texIndex = (texY * this.textureWidth + texX) * 2; // *2 for RG format
// Copy data from source array to texture position
if (i * 2 + 1 < sourceArray.length) {
textureData[texIndex] = sourceArray[i * 2]; // R component
textureData[texIndex + 1] = sourceArray[i * 2 + 1]; // G component
}
}
return textureData;
}
// NEW: Run GPU-based collision detection with Transform Feedback (Zero CPU involvement)
runGPUCollisionDetection(deltaTime) {
const gl = this.gl;
// Skip if no triangles or physics system not ready
if (this.triangleCount <= 0 || !this.currentPhysicsBuffer || !this.nextPhysicsBuffer) {
return;
}
gl.useProgram(this.physicsProgram);
// Set uniforms
gl.uniform1f(this.physicsUniforms.triangleCount, this.triangleCount);
// Use different collision distance based on gravity state for better stacking
const triangleSize = this.calculateTriangleSize();
const collisionDistance = this.gravity ?
triangleSize * 2.2 : // Larger boundary for proper stacking (beyond exterior radius)
triangleSize / Math.sqrt(3) * 2.0; // Original calculation for elastic physics
gl.uniform1f(this.physicsUniforms.collisionDistance, collisionDistance);
gl.uniform1f(this.physicsUniforms.deltaTime, deltaTime);
gl.uniform1f(this.physicsUniforms.gravityStrength, this.gravityStrength);
gl.uniform1f(this.physicsUniforms.viscosity, this.viscosity);
gl.uniform1f(this.physicsUniforms.mass, this.triangleMass);
gl.uniform1f(this.physicsUniforms.bounceEnabled, this.Collision ? 1.0 : 0.0);
gl.uniform1f(this.physicsUniforms.gravityEnabled, this.gravity ? 1.0 : 0.0);
gl.uniform1f(this.physicsUniforms.textureWidth, this.textureWidth);
gl.uniform1f(this.physicsUniforms.textureHeight, this.textureHeight);
gl.uniform1f(this.physicsUniforms.restitution, this.restitution);
gl.uniform1f(this.physicsUniforms.stackingRestitution, this.stackingRestitution);
gl.uniform1f(this.physicsUniforms.staticFriction, this.staticFriction);
gl.uniform1f(this.physicsUniforms.kineticFriction, this.kineticFriction);
gl.uniform1f(this.physicsUniforms.restingThreshold, this.restingContactThreshold);
gl.uniform1f(this.physicsUniforms.sleepThreshold, this.sleepThreshold);
gl.uniform1f(this.physicsUniforms.gridSize, this.gridSize);
gl.uniform1f(this.physicsUniforms.gridWidth, this.gridWidth);
gl.uniform1f(this.physicsUniforms.gridHeight, this.gridHeight);
// Bind textures for collision detection
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, this.positionTexture);
gl.uniform1i(this.physicsUniforms.positionTexture, 0);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, this.velocityTexture);
gl.uniform1i(this.physicsUniforms.velocityTexture, 1);
// Set up input vertex attributes from current physics buffer
gl.bindBuffer(gl.ARRAY_BUFFER, this.currentPhysicsBuffer);
const stride = 6 * 4; // 6 floats * 4 bytes per float
// Position attribute - CRITICAL: Reset divisor to 0 for per-vertex data
const aPosition = gl.getAttribLocation(this.physicsProgram, 'a_position');
if (aPosition >= 0) {
gl.enableVertexAttribArray(aPosition);
gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, stride, 0);
gl.vertexAttribDivisor(aPosition, 0); // Each vertex gets its own data, not instanced
} else {
console.error("Could not find a_position attribute");
}
// Velocity attribute - CRITICAL: Reset divisor to 0 for per-vertex data
const aVelocity = gl.getAttribLocation(this.physicsProgram, 'a_velocity');
if (aVelocity >= 0) {
gl.enableVertexAttribArray(aVelocity);
gl.vertexAttribPointer(aVelocity, 2, gl.FLOAT, false, stride, 2 * 4);
gl.vertexAttribDivisor(aVelocity, 0); // Each vertex gets its own data, not instanced
} else {
console.error("Could not find a_velocity attribute");
}
// Rotation attribute - CRITICAL: Reset divisor to 0 for per-vertex data
const aRotation = gl.getAttribLocation(this.physicsProgram, 'a_rotation');
if (aRotation >= 0) {
gl.enableVertexAttribArray(aRotation);
gl.vertexAttribPointer(aRotation, 1, gl.FLOAT, false, stride, 4 * 4);
gl.vertexAttribDivisor(aRotation, 0); // Each vertex gets its own data, not instanced
} else {
console.error("Could not find a_rotation attribute");
}
// Angular velocity attribute - CRITICAL: Reset divisor to 0 for per-vertex data
const aAngularVelocity = gl.getAttribLocation(this.physicsProgram, 'a_angular_velocity');
if (aAngularVelocity >= 0) {
gl.enableVertexAttribArray(aAngularVelocity);
gl.vertexAttribPointer(aAngularVelocity, 1, gl.FLOAT, false, stride, 5 * 4);
gl.vertexAttribDivisor(aAngularVelocity, 0); // Each vertex gets its own data, not instanced
} else {
console.error("Could not find a_angular_velocity attribute");
}
// Set up transform feedback to write to next physics buffer
gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, this.transformFeedback);
gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, this.nextPhysicsBuffer);
// Disable rasterization (we only want transform feedback)
gl.enable(gl.RASTERIZER_DISCARD);
// Run physics and collision detection on GPU
gl.beginTransformFeedback(gl.POINTS);
gl.drawArrays(gl.POINTS, 0, this.triangleCount);
gl.endTransformFeedback();
// Re-enable rasterization
gl.disable(gl.RASTERIZER_DISCARD);
// Unbind transform feedback to allow buffer reading
gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null);
// Ping-pong: swap buffers (zero copy operation)
[this.currentPhysicsBuffer, this.nextPhysicsBuffer] = [this.nextPhysicsBuffer, this.currentPhysicsBuffer];
// Update rendering data from current physics buffer (minimal data extraction)
this.updateRenderingDataFromGPU();
}
// NEW: Extract minimal data from GPU for rendering (positions and rotations only)
updateRenderingDataFromGPU() {
const gl = this.gl;
// Skip if no triangles or buffer not ready
if (this.triangleCount <= 0 || !this.currentPhysicsBuffer) {
return;
}
try {
// Read the entire physics buffer at once for efficiency
gl.bindBuffer(gl.ARRAY_BUFFER, this.currentPhysicsBuffer);
// Read all physics data at once (more efficient than individual reads)
const physicsData = new Float32Array(this.triangleCount * 6);
gl.getBufferSubData(gl.ARRAY_BUFFER, 0, physicsData);
// Validate the data makes sense
let hasValidData = true;
for (let i = 0; i < physicsData.length; i++) {
if (!isFinite(physicsData[i])) {
console.error(`Invalid physics data at index ${i}: ${physicsData[i]}`);
hasValidData = false;
break;
}
}
if (!hasValidData) {
return;
}
// Extract positions and rotations from the physics data
const tempPositions = new Float32Array(this.triangleCount * 2);
const tempRotations = new Float32Array(this.triangleCount);
const tempVelocities = new Float32Array(this.triangleCount * 2);
for (let i = 0; i < this.triangleCount; i++) {
const baseIndex = i * 6;
// Extract position with bounds checking
const posX = physicsData[baseIndex];
const posY = physicsData[baseIndex + 1];
tempPositions[i * 2] = Math.max(-3, Math.min(3, posX)); // Wider position bounds
tempPositions[i * 2 + 1] = Math.max(-3, Math.min(3, posY)); // Wider position bounds
// Extract velocities with reasonable limits
const velX = physicsData[baseIndex + 2];
const velY = physicsData[baseIndex + 3];
tempVelocities[i * 2] = Math.max(-1, Math.min(1, velX)); // Higher velocity limits
tempVelocities[i * 2 + 1] = Math.max(-1, Math.min(1, velY)); // Higher velocity limits
// Extract rotation
tempRotations[i] = physicsData[baseIndex + 4]; // rotation
}
// Update 2D position texture for next collision detection frame
const positionTextureData = this.createTextureDataFromArray(tempPositions);
gl.bindTexture(gl.TEXTURE_2D, this.positionTexture);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.textureWidth, this.textureHeight, gl.RG, gl.FLOAT, positionTextureData);
// Update 2D velocity texture for next collision detection frame
const velocityTextureData = this.createTextureDataFromArray(tempVelocities);
gl.bindTexture(gl.TEXTURE_2D, this.velocityTexture);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.textureWidth, this.textureHeight, gl.RG, gl.FLOAT, velocityTextureData);
// Update rendering buffers with proper data
gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, tempPositions);
gl.bindBuffer(gl.ARRAY_BUFFER, this.rotationBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, tempRotations);
// Update internal arrays for consistency (used by parameter setters)
this.positions.set(tempPositions);
this.rotations.set(tempRotations);
this.velocities.set(tempVelocities);
// Mark successful update
this.lastSuccessfulUpdate = performance.now();
this.gpuSystemFailed = false;
} catch (error) {
console.error("Error updating rendering data from GPU:", error);
this.gpuSystemFailed = true;
// Fall back to keeping current data
}
}
setupRenderAttributes() {
const gl = this.gl;
gl.useProgram(this.renderProgram);
// Vertex positions
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
const aPosition = gl.getAttribLocation(this.renderProgram, 'a_position');
if (aPosition >= 0) {
gl.enableVertexAttribArray(aPosition);
gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0);
}
// Instance positions
gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
const aInstancePosition = gl.getAttribLocation(this.renderProgram, 'a_instance_position');
if (aInstancePosition >= 0) {
gl.enableVertexAttribArray(aInstancePosition);
gl.vertexAttribPointer(aInstancePosition, 2, gl.FLOAT, false, 0, 0);
gl.vertexAttribDivisor(aInstancePosition, 1);
}
// Instance rotations
gl.bindBuffer(gl.ARRAY_BUFFER, this.rotationBuffer);
const aInstanceRotation = gl.getAttribLocation(this.renderProgram, 'a_instance_rotation');
if (aInstanceRotation >= 0) {
gl.enableVertexAttribArray(aInstanceRotation);
gl.vertexAttribPointer(aInstanceRotation, 1, gl.FLOAT, false, 0, 0);
gl.vertexAttribDivisor(aInstanceRotation, 1);
}
// Instance colors
gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
const aInstanceColor = gl.getAttribLocation(this.renderProgram, 'a_instance_color');
if (aInstanceColor >= 0) {
gl.enableVertexAttribArray(aInstanceColor);
gl.vertexAttribPointer(aInstanceColor, 3, gl.FLOAT, false, 0, 0);
gl.vertexAttribDivisor(aInstanceColor, 1);
}
}
initializeTriangleData() {
const gl = this.gl;
// Initialize data with more distinct values to ensure uniqueness
for (let i = 0; i < this.triangleCount; i++) {
// Use triangle index to ensure different initial conditions
const angle = (i / this.triangleCount) * Math.PI * 2;
this.positions[i * 2] = Math.cos(angle) * 0.2 + randomFloat(-0.1, 0.1);
this.positions[i * 2 + 1] = Math.sin(angle) * 0.2 + randomFloat(-0.1, 0.1);
// Velocities pointing in different directions
const velAngle = angle + Math.PI / 4;
this.velocities[i * 2] = Math.cos(velAngle) * this.linearVelocityScale;
this.velocities[i * 2 + 1] = Math.sin(velAngle) * this.linearVelocityScale;
this.rotations[i] = randomFloat(0, Math.PI * 2);
this.angularVelocities[i] = randomFloat(-1, 1) * this.angularVelocityScale;
this.colors[i * 3] = Math.random();
this.colors[i * 3 + 1] = Math.random();
this.colors[i * 3 + 2] = Math.random();
}
// Upload initial data to rendering buffers
gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.positions);
gl.bindBuffer(gl.ARRAY_BUFFER, this.rotationBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.rotations);
gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.colors);
// CRITICAL FIX: Upload initial data to GPU physics buffers
if (this.physicsBufferA && this.physicsBufferB) {
this.uploadInitialPhysicsData();
}
}
calculateTriangleSize() {
// Calculate adaptive triangle size based on canvas area and triangle count
// Use configurable coverage percentage instead of fixed 1/5
// Our coordinate system is normalized from -1 to 1, so total area = 4
const normalizedCanvasArea = 4; // 2 * 2 (width * height in normalized coords)
const targetTotalArea = normalizedCanvasArea * (this.triangleCoverage / 100);
const areaPerTriangle = targetTotalArea / this.triangleCount;
// Our triangle vertices form: (0, size), (-size, -size), (size, -size)
// This creates a triangle with base = 2*size and height = 2*size
// Triangle area = 0.5 * base * height = 0.5 * 2*size * 2*size = 2*size²
// So: 2*size² = areaPerTriangle
// Therefore: size = sqrt(areaPerTriangle / 2)
const triangleSize = Math.sqrt(areaPerTriangle / 2);
// Apply min/max limits
const adaptiveSize = Math.max(this.minTriangleSize,
Math.min(this.maxTriangleSize, triangleSize));
return adaptiveSize;
}
updateTriangleGeometry() {
const gl = this.gl;
const size = this.calculateTriangleSize();
// Triangle geometry with adaptive size
const vertices = new Float32Array([
0.0, size,
-size, -size,
size, -size
]);
if (this.vertexBuffer) {
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, vertices);
} else {
this.vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.DYNAMIC_DRAW);
}
}
createBuffers() {
const gl = this.gl;
// Simple standard buffer approach (not transform feedback)
// Instance position buffer
this.positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, this.positions, gl.DYNAMIC_DRAW);
// Instance rotation buffer
this.rotationBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.rotationBuffer);
gl.bufferData(gl.ARRAY_BUFFER, this.rotations, gl.DYNAMIC_DRAW);
// Instance color buffer
this.colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, this.colors, gl.STATIC_DRAW);
// Triangle geometry with adaptive sizing
this.updateTriangleGeometry();
// Create physics buffers for GPU collision detection