-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1644 lines (1490 loc) · 69.5 KB
/
Copy pathmain.js
File metadata and controls
1644 lines (1490 loc) · 69.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
/*
* Copyright (c) 2024 OneNok_HK
* Licensed under the MIT License. See LICENSE file in the project root for full license information.
*/
console.log("main.js loaded successfully")
// =============== 實用小函數區域 ===============
/**
* 一次性控制臺輸出函數,只會輸出一次指定訊息
* @param {string} key 唯一鍵值
* @param {string} message 要輸出的訊息
*/
const onceConsole = (() => {
const printed = new Set();
return (key, ...message) => {
if (!printed.has(key)) {
console.log(...message);
printed.add(key);
}
};
})();
// 創建 Web Worker
let worker = new Worker('particleWorker_multithread_fixed.js');
// 用戶可控制數據的初始化
const gameState = {
// 粒子系統基本設置
distMax: null,
distMin: 0,
forceMax: 1,
forceMin: -1,
distRandMax: 300,
distRandMin: 10,
forceRandMax: 1,
forceRandMin: -1,
isLockedParticleForce: false, // 是否鎖定粒子力
isLockedParticleDistance: false, // 是否鎖定粒子距離
threadMode: 'multithread',
particleTypes: 3,
particleCounts: [250, 250, 250],
particleColors: [
'hsl(0, 100%, 50%)', // 紅色
'hsl(120, 100%, 50%)', // 綠色
'hsl(240, 100%, 50%)' // 藍色
],
//particleGroups: [],
sharedMemory: null,
// 交互矩陣
forceMatrix: [
[1, 0.5, 0],
[0, 1, 0.5],
[0.5, 0, 1]
],
distanceMatrix: [
[300, 300, 300],
[300, 300, 300],
[300, 300, 300]
],
// 物理參數
tHalf: 0.020, // 摩擦半衰期
dt: 1 / 144, // 時間步長
// 顯示設置
isThrough: false, // 無邊界模式
// 滑鼠交互
mouseForce: 100,
// 其他設置
enableParticleAffcetRadiusShow: false,
selectedParticleIndex: null,
selectedParticleId: null,
selectedParticleType: null,
nearbyParticlesList: [],
ballRadius: 1.5,
RadiusShow: [true, true, true],
// 更新控制
updateInterval: 0, // 0 為無上限
isMovingCanvas: false
};
document.addEventListener('DOMContentLoaded', () => {
console.log("DOMContentLoaded")
// 添加變量
let nextParticleId = 0; // 用於生成唯一的粒子 ID
let frameCount = 0;
let lastTime = performance.now();
let fps = 0;
let performanceDataLocal = {
updateIntervalCountsTimes: 0,
totalTimeAll: [],
totalTimeMax: 0,
totalTimeAverage: 0,
gAffectCalcTimeAll: [],
gAffectCalcTimeMax: 0,
gAffectCalcTimeAverage: 0,
positionUpdateTimeAll: [],
positionUpdateTimeMax: 0,
positionUpdateTimeAverage: 0,
particleCollisionTimeAll: [],
particleCollisionTimeMax: 0,
particleCollisionTimeAverage: 0,
ParticleAffcetCalcTimeAll: [],
ParticleAffcetCalcTimeMax: 0,
ParticleAffcetCalcTimeAverage: 0
};
let performanceData = {
totalTime: 0,
gAffectCalcTime: 0,
gAffectCalcCountsTimes: 0,
particleSkippedCountsTimes: 0,
positionUpdateTime: 0,
positionUpdateCountsTimes: 0,
ParticleAffcetCalcTime: 0,
particleCollisionTime: 0,
particleCollisionCountsTimes: 0,
};
let totalTimeAverageUpdateMs = 1000;
let gAffectCalcTimeAverageUpdateMs = 1000;
let positionUpdateTimeAverageUpdateMs = 1000;
let ParticleAffcetCalcTimeAverageUpdateMs = 1000;
let particleCollisionTimeAverageUpdateMs = 1000;
let totalTimeAverageUpdateLastTime = 0;
let gAffectCalcTimeAverageUpdateLastTime = 0;
let positionUpdateTimeAverageUpdateLastTime = 0;
let ParticleAffcetCalcTimeAverageUpdateLastTime = 0;
let particleCollisionTimeAverageUpdateLastTime = 0;
const canvas2d = document.getElementById("board2d");
gameState.distMax = Math.floor(Math.min(canvas2d.width, canvas2d.height) / 20) * 10;
console.log(`canvas2d.width: ${canvas2d.width}, canvas2d.height: ${canvas2d.height}`);
const ctx = canvas2d.getContext("2d");
function draw(sharedMemory) {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas2d.width, canvas2d.height);
for (let type = 0; type < gameState.particleTypes; type++) {
for (let i = 0; i < gameState.particleCounts[type]; i++) {
let p;
try {
p = sharedMemory.getParticle(type, i);
onceConsole(`draw particle ${type}`, JSON.stringify(p));
}
catch (e) {
console.error(p)
console.error(e)
throw new Error("");
}
ctx.beginPath();
ctx.arc(p.x, p.y, gameState.ballRadius, 0, Math.PI * 2);
switch (type) {
case 0:
onceConsole("type 0", JSON.stringify(p));
break;
case 1:
onceConsole("type 1", JSON.stringify(p));
break;
case 2:
onceConsole("type 2", JSON.stringify(p));
break;
}
if (gameState.enableParticleAffcetRadiusShow) {
if (gameState.selectedParticleId === null) {
ctx.fillStyle = 'gray';
ctx.fill();
ctx.closePath();
} else if (p.id === gameState.selectedParticleId) {
let isXOverflow = false;
let isYOverflow = false;
let newx = p.x;
let newy = p.y;
ctx.fillStyle = 'rgba(255, 255, 255, 1)';
ctx.fill();
ctx.closePath();
for (let i = 0; i < gameState.RadiusShow.length; i++) {
if (gameState.RadiusShow[i]) {
hsl = gameState.particleColors[i];
h = hsl.match(/hsl\((\d+),\s*\d+%,\s*\d+%\)/)[1];
hsla = `hsla(${h}, 100%, 50%, 0.3)`;
radius = gameState.distanceMatrix[gameState.selectedParticleType][i];
ctx.beginPath();
ctx.arc(p.x, p.y, radius, 0, Math.PI * 2);
ctx.fillStyle = hsla;
ctx.fill();
ctx.closePath();
if (throughCheckbox.checked) {
isXOverflow = false;
isYOverflow = false;
newx = p.x;
newy = p.y;
if ((p.x < radius || p.x > canvas2d.width - radius)) {
isXOverflow = true;
newx = p.x < radius ? p.x + canvas2d.width : p.x - canvas2d.width;
ctx.beginPath();
ctx.arc(newx, p.y, radius, 0, Math.PI * 2);
ctx.fillStyle = hsla;
ctx.fill();
ctx.closePath();
}
if ((p.y < radius || p.y > canvas2d.height - radius)) {
isYOverflow = true;
newy = p.y < radius ? p.y + canvas2d.height : p.y - canvas2d.height;
ctx.beginPath();
ctx.arc(p.x, newy, radius, 0, Math.PI * 2);
ctx.fillStyle = hsla;
ctx.fill();
ctx.closePath();
}
if (isXOverflow && isYOverflow) {
ctx.beginPath();
ctx.arc(newx, newy, radius, 0, Math.PI * 2);
ctx.fillStyle = hsla;
ctx.fill();
ctx.closePath();
}
}
}
}
} else {
if (gameState.RadiusShow[p.type]) {
ctx.fillStyle = (gameState.nearbyParticlesList[p.type] || []).includes(p) ? p.color : 'gray';
ctx.fill();
ctx.closePath();
}
}
} else {
ctx.fillStyle = p.color;
ctx.fill();
ctx.closePath();
}
//drawVectorArrow(p.x, p.y, p.vx, p.vy); // 繪製速度向量箭頭
};
};
}
function drawWarningCanvasMoving() {
const canvasWidth = canvas2d.width;
const canvasHeight = canvas2d.height;
ctx.fillStyle = 'rgba(255, 255, 0, 0.2)'; // Yellow background like console.warn
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
ctx.font = 'bold 20px monospace'; // Console-like font
ctx.fillStyle = '#000'; // Dark text
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillText('⚠️ 畫布正在移動中', canvasWidth / 2, canvasHeight / 2, canvasWidth); // Added warning emoji and using fillText for solid text
}
function drawVectorArrow(x, y, vx, vy) {
if (!(vx || vy)) return;
ctx.save();
ctx.strokeStyle = 'white';
ctx.lineWidth = 1.5;
var headlen = 2; // 箭頭長度
var angle = Math.atan2(vy, vx);
let dx = vx * 10;
let dy = vy * 10;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + dx, y + dy);
// 左側箭頭
ctx.moveTo(x + dx, y + dy);
ctx.lineTo(
x + dx - headlen * Math.cos(angle - Math.PI / 6),
y + dy - headlen * Math.sin(angle - Math.PI / 6)
);
// 右側箭頭
ctx.moveTo(x + dx, y + dy);
ctx.lineTo(
x + dx - headlen * Math.cos(angle + Math.PI / 6),
y + dy - headlen * Math.sin(angle + Math.PI / 6)
);
ctx.stroke();
ctx.restore();
}
// --SharedMemoryManager類處理所有共享內存的分配和管理--
class SharedMemoryManager {
constructor(particleTypes, particleCounts) {
this.particleTypes = particleTypes;
this.particleCounts = particleCounts;
this.buffers = {};
this.views = {};
// 為每種粒子類型創建獨立的緩衝區
this.buffers.particleGroups = [];
this.views.particleGroups = [];
for (let i = 0; i < particleTypes; i++) {
const count = particleCounts[i];
// 每個粒子需要 5 個 Int32 (x, y, vx, vy, id)
// 額外分配 2 個 Int32 用於存儲 color 和 type
const bufferSize = (count * 5 + 2) * Int32Array.BYTES_PER_ELEMENT;
this.buffers.particleGroups[i] = new SharedArrayBuffer(bufferSize);
// 創建視圖
this.views.particleGroups[i] = {
x: new Int32Array(this.buffers.particleGroups[i], 0, count),
y: new Int32Array(this.buffers.particleGroups[i], count * Int32Array.BYTES_PER_ELEMENT, count),
vx: new Int32Array(this.buffers.particleGroups[i], 2 * count * Int32Array.BYTES_PER_ELEMENT, count),
vy: new Int32Array(this.buffers.particleGroups[i], 3 * count * Int32Array.BYTES_PER_ELEMENT, count),
id: new Int32Array(this.buffers.particleGroups[i], 4 * count * Int32Array.BYTES_PER_ELEMENT, count),
color: new Int32Array(this.buffers.particleGroups[i], 5 * count * Int32Array.BYTES_PER_ELEMENT, 1), // 存儲 color
type: new Int32Array(this.buffers.particleGroups[i], (5 * count + 1) * Int32Array.BYTES_PER_ELEMENT, 1) // 存儲 type
};
}
// 創建同步計數器緩衝區
this.buffers.sync = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * particleTypes);
this.views.sync = new Int32Array(this.buffers.sync);
}
// 新增:設置 color 和 type
setParticleTypeColor(type, color) {
const view = this.views.particleGroups[type];
Atomics.store(view.color, 0, this.hslToInt(color)); // 存儲 color
Atomics.store(view.type, 0, type); // 存儲 type
console.log(`setParticleTypeColor: ${type},color: ${color}, intcolor: ${this.hslToInt(color)}`);
}
// 新增:獲取 color 和 type
getParticleTypeColor(type) {
const view = this.views.particleGroups[type];
return {
color: this.intToHsl(Atomics.load(view.color, 0)), // 讀取 color
type: Atomics.load(view.type, 0) // 讀取 type
};
}
// 新增:將 HSL 字串轉換為整數
hslToInt(hsl) {
const match = hsl.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/);
if (!match) return 0;
return parseInt(match[1]); // 只存儲色相值
}
// 新增:將整數轉換回 HSL 字串
intToHsl(hue) {
return `hsl(${hue}, 100%, 50%)`;
}
// 獲取指定類型的粒子緩衝區
getParticleBuffer(type) {
return this.buffers.particleGroups[type];
}
//
getParticleGroup() {
return this.views.particleGroups;
}
// 獲取指定類型的粒子視圖
getParticleView(type) {
return this.views.particleGroups[type];
}
// 獲取同步計數器緩衝區
getSyncBuffer() {
return this.buffers.sync;
}
// 獲取同步計數器視圖
getSyncView() {
return this.views.sync;
}
// 清除所有數據
clear() {
// 清除所有粒子數據
for (let i = 0; i < this.particleTypes; i++) {
const view = this.views.particleGroups[i];
view.x.fill(0);
view.y.fill(0);
view.vx.fill(0);
view.vy.fill(0);
view.id.fill(0);
}
// 清除同步計數器
this.views.sync.fill(0);
}
// 獲取所有緩衝區
getBuffers() {
return {
particleGroups: this.buffers.particleGroups,
sync: this.buffers.sync
};
}
// 獲取所有視圖
getViews() {
return {
particleGroups: this.views.particleGroups,
sync: this.views.sync
};
}
// 新增:直接新增粒子
addParticle(type, particle, index) {
const view = this.views.particleGroups[type];
storeAtomicFloat(view.x, index, particle.x);
storeAtomicFloat(view.y, index, particle.y);
storeAtomicFloat(view.vx, index, particle.vx);
storeAtomicFloat(view.vy, index, particle.vy);
Atomics.store(view.color, 0, this.hslToInt(particle.color)); // 存儲 color
Atomics.store(view.id, index, particle.id);
Atomics.store(view.type, 0, type); // 存儲 type
}
// 新增:獲取粒子
getParticle(type, index) {
const view = this.views.particleGroups[type];
return {
x: loadAtomicFloat(view.x, index),
y: loadAtomicFloat(view.y, index),
vx: loadAtomicFloat(view.vx, index),
vy: loadAtomicFloat(view.vy, index),
color: this.intToHsl(Atomics.load(view.color, 0)),
type: Atomics.load(view.type, 0),
id: Atomics.load(view.id, index)
};
}
// 修改 create 函數直接使用 SharedMemoryManager
create(type, count) {
for (let i = 0; i < count; i++) {
this.addParticle(type, {
x: rX(),
y: rY(),
vx: 0,
vy: 0,
color: gameState.particleColors[type],
id: nextParticleId++
}, i);
}
}
}
// 修改 ParticleData 類以配合新的 SharedMemoryManager
/*class ParticleData {
constructor(type, sharedMemoryManager) {
this.count = sharedMemoryManager.particleCounts[type];
this.particleData = sharedMemoryManager.getParticleView(type);
this.syncCounter = sharedMemoryManager.getSyncView()[type];
this.sharedMemoryManager = sharedMemoryManager;
Atomics.store(this.particleData.color, 0, this.sharedMemoryManager.hslToInt(gameState.particleColors[type]));
Atomics.store(this.particleData.type, 0, type);
}
add(particle, index) {
storeAtomicFloat(this.particleData.x, index, particle.x);
storeAtomicFloat(this.particleData.y, index, particle.y);
storeAtomicFloat(this.particleData.vx, index, particle.vx);
storeAtomicFloat(this.particleData.vy, index, particle.vy);
Atomics.store(this.particleData.id, index, particle.id);
}
getParticle(index) {
return {
x: loadAtomicFloat(this.particleData.x, index),
y: loadAtomicFloat(this.particleData.y, index),
vx: loadAtomicFloat(this.particleData.vx, index),
vy: loadAtomicFloat(this.particleData.vy, index),
color: this.sharedMemoryManager.intToHsl(Atomics.load(this.particleData.color, 0)), // 使用共享內存中的 color
type: Atomics.load(this.particleData.type, 0), // 使用共享內存中的 type
id: Atomics.load(this.particleData.id, index)
};
}
clear() {
this.particleData.x.fill(0);
this.particleData.y.fill(0);
this.particleData.vx.fill(0);
this.particleData.vy.fill(0);
this.particleData.color.fill(0);
this.particleData.type.fill(0);
this.particleData.id.fill(0);
}
getData() {
return this.particleData;
}
getSyncCounter() {
return this.syncCounter;
}
// 新增:獲取粒子數量
getCount() {
return this.count;
}
// 新增:更新指定索引的粒子數據
updateParticle(index, particle) {
this.add(particle, index);
}
}*/
// 添加atomicFloat輔助函數
function storeAtomicFloat(array, index, value) {
return Atomics.store(array, index, Math.round(value * 1000));
}
function loadAtomicFloat(array, index) {
return Atomics.load(array, index) / 1000;
}
// >>> 生成指定類型的粒子組 <<<
/*function create(count, c, type, sharedMemory) {
// 創建 ParticleData 實例來管理共享內存
const particleData = new ParticleData(type, sharedMemory);
// 直接在共享內存中創建粒子
for (let i = 0; i < count; i++) {
const x = rX();
const y = rY();
const id = nextParticleId++;
particleData.add({
x,
y,
vx: 0,
vy: 0,
id
}, i);
}
return particleData;
}*/
// >>> 生成隨機X坐標 <<<
function rX() {
return Math.random() * (canvas2d.width - 100) + 50; // 隨機X坐標
}
// >>> 生成隨機Y坐標 <<<
function rY() {
return Math.random() * (canvas2d.height - 100) + 50; // 隨機Y坐標
}
// 初始化遊戲函數修改
function initGame() {
gameState.sharedMemory = new SharedMemoryManager(gameState.particleTypes, gameState.particleCounts);
// --初始化矩陣和粒子--
nextParticleId = 0; // 重置 id 計數器
for (let type = 0; type < gameState.particleTypes; type++) {
gameState.sharedMemory.create(type, gameState.particleCounts[type]);
}
//gameState.particleGroups = sharedMemory.; // 粒子類型
//console.log("gameState.particleGroups: " + JSON.stringify(gameState.particleGroups))
// 重置性能數據
Object.keys(performanceDataLocal).forEach(key => {
if (performanceDataLocal[key] instanceof Array) {
performanceDataLocal[key] = [];
} else {
performanceDataLocal[key] = 0;
}
});
// 發送初始化消息給 worker
worker.postMessage({
type: 'init',
particleCounts: gameState.particleCounts,
canvasWidth: canvas2d.width,
canvasHeight: canvas2d.height,
//particleGroups: gameState.particleGroups,
particleTypes: gameState.particleTypes,
performanceData: performanceData,
ballRadius: gameState.ballRadius,
sharedMemory: gameState.sharedMemory,
});
}
// 隨機化值
function randomizeValues() {
if (!gameState.isLockedParticleForce) {
document.querySelectorAll('.particle-force').forEach(p => {
const value = (Math.random() * (gameState.forceRandMax - gameState.forceRandMin) + gameState.forceRandMin).toFixed(1);
p.value = value;
p.dispatchEvent(new Event('input'));
});
}
if (!gameState.isLockedParticleDistance) {
document.querySelectorAll('.particle-distance').forEach(p => {
const value = Math.floor(Math.random() * (gameState.distRandMax - gameState.distRandMin)) + gameState.distRandMin;
p.value = value;
p.dispatchEvent(new Event('input'));
});
}
updateRules();
}
// 隨機化並重新開始
function randomizeAndRestart() {
randomizeValues();
initGame();
}
function update() {
// 更新所選單元格的顯示
draw(gameState.sharedMemory);
if (gameState.isMovingCanvas) {
drawWarningCanvasMoving();
}
if (performanceData.totalTime > performanceDataLocal.totalTimeMax) {
performanceDataLocal.totalTimeMax = performanceData.totalTime;
}
if (performanceData.gAffectCalcTime > performanceDataLocal.gAffectCalcTimeMax) {
performanceDataLocal.gAffectCalcTimeMax = performanceData.gAffectCalcTime;
}
if (performanceData.positionUpdateTime > performanceDataLocal.positionUpdateTimeMax) {
performanceDataLocal.positionUpdateTimeMax = performanceData.positionUpdateTime;
}
if (performanceData.particleCollisionTime > performanceDataLocal.particleCollisionTimeMax) {
performanceDataLocal.particleCollisionTimeMax = performanceData.particleCollisionTime;
}
if (performanceData.ParticleAffcetCalcTime > performanceDataLocal.ParticleAffcetCalcTimeMax) {
performanceDataLocal.ParticleAffcetCalcTimeMax = performanceData.ParticleAffcetCalcTime;
}
performanceDataLocal.totalTimeAll.push(performanceData.totalTime);
performanceDataLocal.gAffectCalcTimeAll.push(performanceData.gAffectCalcTime);
performanceDataLocal.positionUpdateTimeAll.push(performanceData.positionUpdateTime);
performanceDataLocal.particleCollisionTimeAll.push(performanceData.particleCollisionTime);
performanceDataLocal.ParticleAffcetCalcTimeAll.push(performanceData.ParticleAffcetCalcTime);
// 更新性能數據顯示
document.getElementById('total-time').textContent = performanceData.totalTime.toFixed(2);
if (performance.now() - totalTimeAverageUpdateLastTime >= totalTimeAverageUpdateMs) {
performanceDataLocal.totalTimeAverage = performanceDataLocal.totalTimeAll.reduce((a, b) => a + b, 0) / performanceDataLocal.totalTimeAll.length;
document.getElementById('total-time-average').textContent = performanceDataLocal.totalTimeAverage.toFixed(2);
performanceDataLocal.totalTimeAll = [];
totalTimeAverageUpdateLastTime = performance.now();
}
document.getElementById('total-time-max').textContent = performanceDataLocal.totalTimeMax.toFixed(2);
document.getElementById('g-Affect-Calc-time').textContent = performanceData.gAffectCalcTime.toFixed(2);
if (performance.now() - gAffectCalcTimeAverageUpdateLastTime >= gAffectCalcTimeAverageUpdateMs) {
performanceDataLocal.gAffectCalcTimeAverage = performanceDataLocal.gAffectCalcTimeAll.reduce((a, b) => a + b, 0) / performanceDataLocal.gAffectCalcTimeAll.length;
document.getElementById('g-Affect-Calc-time-average').textContent = performanceDataLocal.gAffectCalcTimeAverage.toFixed(2);
performanceDataLocal.gAffectCalcTimeAll = [];
gAffectCalcTimeAverageUpdateLastTime = performance.now();
}
document.getElementById('g-Affect-Calc-time-max').textContent = performanceDataLocal.gAffectCalcTimeMax.toFixed(2);
document.getElementById('g-Affect-Calc-time-single-average').textContent = performanceData.gAffectCalcCountsTimes > 0 ? ((performanceDataLocal.gAffectCalcTimeAverage / (performanceData.gAffectCalcCountsTimes - performanceData.particleSkippedCountsTimes)).toFixed(6)) : '不適用';
document.getElementById('g-Affect-Calc-time-run-per-update').textContent = performanceData.gAffectCalcCountsTimes;
document.getElementById('particleSkippedCountsTimes').textContent = performanceData.particleSkippedCountsTimes;
document.getElementById('particleValidCountsTimes').textContent = performanceData.gAffectCalcCountsTimes - performanceData.particleSkippedCountsTimes;
document.getElementById('position-update-time').textContent = performanceData.positionUpdateTime.toFixed(2);
if (performance.now() - positionUpdateTimeAverageUpdateLastTime >= positionUpdateTimeAverageUpdateMs) {
performanceDataLocal.positionUpdateTimeAverage = performanceDataLocal.positionUpdateTimeAll.reduce((a, b) => a + b, 0) / performanceDataLocal.positionUpdateTimeAll.length;
document.getElementById('position-update-time-average').textContent = performanceDataLocal.positionUpdateTimeAverage.toFixed(2);
performanceDataLocal.positionUpdateTimeAll = [];
positionUpdateTimeAverageUpdateLastTime = performance.now();
}
document.getElementById('position-update-time-max').textContent = performanceDataLocal.positionUpdateTimeMax.toFixed(2);
document.getElementById('position-update-time-single-average').textContent = performanceData.positionUpdateCountsTimes > 0 ? ((performanceDataLocal.positionUpdateTimeAverage / performanceData.positionUpdateCountsTimes).toFixed(4)) : '不適用';
document.getElementById('position-update-time-run-per-update').textContent = performanceData.positionUpdateCountsTimes;
document.getElementById('particle-collision-time').textContent = performanceData.particleCollisionTime.toFixed(2);
if (performance.now() - particleCollisionTimeAverageUpdateLastTime >= particleCollisionTimeAverageUpdateMs) {
performanceDataLocal.particleCollisionTimeAverage = performanceDataLocal.particleCollisionTimeAll.reduce((a, b) => a + b, 0) / performanceDataLocal.particleCollisionTimeAll.length;
document.getElementById('particle-collision-time-average').textContent = performanceDataLocal.particleCollisionTimeAverage.toFixed(2);
performanceDataLocal.particleCollisionTimeAll = [];
particleCollisionTimeAverageUpdateLastTime = performance.now();
}
document.getElementById('particle-collision-time-max').textContent = performanceDataLocal.particleCollisionTimeMax.toFixed(2);
document.getElementById('particle-collision-time-single-average').textContent = performanceData.particleCollisionCountsTimes > 0 ? ((performanceDataLocal.particleCollisionTimeAverage / performanceData.particleCollisionCountsTimes).toFixed(6)) : '不適用';
document.getElementById('particle-collision-time-run-per-update').textContent = performanceData.particleCollisionCountsTimes;
document.getElementById('Particle-Affect-Calc-time').textContent = performanceData.ParticleAffcetCalcTime.toFixed(2);
if (performance.now() - ParticleAffcetCalcTimeAverageUpdateLastTime >= ParticleAffcetCalcTimeAverageUpdateMs) {
performanceDataLocal.ParticleAffcetCalcTimeAverage = performanceDataLocal.ParticleAffcetCalcTimeAll.reduce((a, b) => a + b, 0) / performanceDataLocal.ParticleAffcetCalcTimeAll.length;
document.getElementById('Particle-Affect-Calc-time-average').textContent = performanceDataLocal.ParticleAffcetCalcTimeAverage.toFixed(2);
performanceDataLocal.ParticleAffcetCalcTimeAll = [];
ParticleAffcetCalcTimeAverageUpdateLastTime = performance.now();
}
document.getElementById('Particle-Affect-Calc-time-max').textContent = performanceDataLocal.ParticleAffcetCalcTimeMax.toFixed(2);
// 更新選中粒子的屬性顯示
if (gameState.enableParticleAffcetRadiusShow) {
const propertyElement = document.getElementById('selectedParticleProperty');
if (gameState.selectedParticleId !== null && gameState.selectedParticleType !== null) {
// 在 sharedMemory 中查找選中的粒子
let selectedParticle = null;
let found = false;
for (let i = 0; i < gameState.particleCounts[gameState.selectedParticleType]; i++) {
const p = gameState.sharedMemory.getParticle(gameState.selectedParticleType, i);
if (p.id === gameState.selectedParticleId) {
selectedParticle = p;
found = true;
break;
}
}
if (found && selectedParticle) {
const properties = [
`\n`,
`類型: ${selectedParticle.type + 1}`,
`位置: (${selectedParticle.x.toFixed(2)}, ${selectedParticle.y.toFixed(2)})`,
`速度: (${selectedParticle.vx.toFixed(2)}, ${selectedParticle.vy.toFixed(2)})`,
`顏色: ${selectedParticle.color}`,
// 這裡 isOutside 屬性如果沒有可以移除或自定義
typeof selectedParticle.isOutside !== "undefined" ? `是否在邊界外: ${selectedParticle.isOutside ? '是' : '否'}` : ''
];
propertyElement.innerHTML = properties.filter(Boolean).join('<br>');
} else {
propertyElement.textContent = '找不到選中的粒子';
}
} else {
propertyElement.textContent = '未選中粒子';
}
}
// 計算並顯示 FPS
frameCount++;
const currentTime = performance.now();
if (currentTime - lastTime >= 1000) {
fps = Math.round((frameCount * 1000) / (currentTime - lastTime));
document.getElementById('fps').textContent = fps;
frameCount = 0;
lastTime = currentTime;
}
gameUPS = performanceDataLocal.updateIntervalCountsTimes;
document.getElementById('gameUPS').textContent = gameUPS;
let totalTimeAddShowContent = '';
const totalTimeAddShowContentList = [Number(performanceDataLocal.gAffectCalcTimeAverage.toFixed(2)), Number(performanceDataLocal.positionUpdateTimeAverage.toFixed(2)), Number(performanceDataLocal.particleCollisionTimeAverage.toFixed(2)), Number(performanceDataLocal.ParticleAffcetCalcTimeAverage.toFixed(2))];
totalTimeAddShowContent += `${totalTimeAddShowContentList.join(' + ')}<br><br>`;
let sum = 0;
for (let i = 2; i <= totalTimeAddShowContentList.length; i++) {
sum = totalTimeAddShowContentList.slice(0, i).reduce((a, b) => a + b, 0);
totalTimeAddShowContent += `${Number(sum.toFixed(2))}${totalTimeAddShowContentList.slice(i).length > 0 ? ` + ${totalTimeAddShowContentList.slice(i).join(' + ')}` : ''}<br><br>`;
}
document.getElementById('total-time-add-show').innerHTML = totalTimeAddShowContent;
requestAnimationFrame(() => {
worker.postMessage({ type: 'canUpdate' });
update();
});
}
// 接收來自 Worker 的消息
worker.onmessage = function (e) {
if (e.data.type === 'update') {
//console.log(`before performanceDataLocal.totalTimeAverage: ${performanceDataLocal.totalTimeAverage}`);
performanceData = e.data.performanceData;
//console.log(`after performanceDataLocal.totalTimeAverage: ${performanceDataLocal.totalTimeAverage}`);
if (gameState.enableParticleAffcetRadiusShow) {
gameState.nearbyParticlesList = e.data.nearbyParticlesList;
for (let i = 0; i < gameState.nearbyParticlesList.length; i++) {
//console.log(`gameState.nearbyParticlesList[${i}]: ${gameState.nearbyParticlesList[i]}`);
document.getElementById(`particle-nearby-particles-${i}`).textContent = `範圍內的類型${i + 1}粒子數量: ${gameState.nearbyParticlesList[i] ? gameState.nearbyParticlesList[i].length : 0}`;
}
}
}
if (e.data.type === 'setMovingCanvas') {
gameState.isMovingCanvas = e.data.isMovingCanvas;
}
if (e.data.type === 'updateUpdateIntervalCountsTimes') {
performanceDataLocal.updateIntervalCountsTimes = e.data.updateIntervalCountsTimes;
}
};
// 控制板切換
const toggleButton = document.getElementById('toggle-controls');
const controlPanel = document.getElementById('controls');
toggleButton.addEventListener('click', () => {
controlPanel.classList.toggle('visible');
if (controlPanel.classList.contains('visible')) {
toggleButton.style.right = '310px';
toggleButton.textContent = '✕';
} else {
toggleButton.style.right = '10px';
toggleButton.textContent = '☰';
}
updateCanvasSize();
});
// 自動隱藏切換按鈕
let hideTimeout;
document.addEventListener('mousemove', () => {
toggleButton.style.opacity = '0.5';
clearTimeout(hideTimeout);
hideTimeout = setTimeout(() => {
toggleButton.style.opacity = '0';
}, 3000);
});
// 匯出規則
function exportRules() {
const rules = {};
// 添加規則
rules['forceMatrix'] = gameState.forceMatrix;
rules['distanceMatrix'] = gameState.distanceMatrix;
// 添加粒子數量
rules['particleCounts'] = gameState.particleCounts;
// 添加粒子類型
rules['particleTypes'] = gameState.particleTypes;
// 添加粒子顏色
rules['particleColors'] = gameState.particleColors;
// 添加穿透模式狀態
rules['isThrough'] = gameState.isThrough;
rules['tHalf'] = gameState.tHalf;
rules['dt'] = gameState.dt;
rules['mouseForce'] = gameState.mouseForce;
// 添加顏色
const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(rules));
const downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", "particle_rules.json");
document.body.appendChild(downloadAnchorNode);
downloadAnchorNode.click();
downloadAnchorNode.remove();
}
// 導入規則
function importRules(shouldRestart) {
const fileInput = document.getElementById('import-file');
fileInput.value = '';
fileInput.dataset.shouldRestart = shouldRestart;
fileInput.click();
}
function handleFileSelect(event) {
//console.log('handleFileSelect');
const file = event.target.files[0];
const shouldRestart = event.target.dataset.shouldRestart === 'true';
if (file) {
const reader = new FileReader();
reader.onload = function (e) {
const rules = JSON.parse(e.target.result);
Object.keys(rules).forEach(id => {
if (id === 'isThrough') {
// 設置穿透模式狀態
gameState.isThrough = rules[id];
} else if (id === 'particleCounts') {
gameState.particleCounts = rules[id];
} else if (id === 'particleTypes') {
gameState.particleTypes = rules[id];
} else if (id === 'particleColors') {
gameState.particleColors = rules[id];
} else if (id === 'tHalf') {
gameState.tHalf = rules[id];
} else if (id === 'dt') {
gameState.dt = rules[id];
} else if (id === 'mouseForce') {
gameState.mouseForce = rules[id];
} else if (/force(Matrix)*?/.test(id)) {
gameState.forceMatrix = rules[id];
} else if (/distance(Matrix)*?/.test(id)) {
gameState.distanceMatrix = rules[id];
}
});
//console.log('updateParticleSystem');
updateParticleSystem();
//console.log('updateEveryThing');
updateEveryThing();
if (shouldRestart) {
setTimeout(initGame, 100);
}
};
reader.readAsText(file);
}
}
// 為匯出規則添加事件監聽器
document.getElementById('export-rules').addEventListener('click', exportRules);
// 為導入規則添加事件監聽器
document.getElementById('import-rules').addEventListener('click', () => importRules(false));
// 為導入規則並重新開始添加事件監聽器
document.getElementById('import-rules-and-restart').addEventListener('click', () => importRules(true));
// 為導入文件添加事件監聽器
document.getElementById('import-file').addEventListener('change', handleFileSelect);
let mouseX = 0;
let mouseY = 0;
let isMouseDown = false;
let isUpdateMouse = false;
let isUpdateMouseDownUp = false;
// 穿透模式切換
const throughCheckbox = document.getElementById("isThrough");
throughCheckbox.addEventListener('change', () => {
gameState.isThrough = throughCheckbox.checked;
worker.postMessage({ type: 'setThrough', isThrough: gameState.isThrough });
});
// 運算模式切換
const threadModeSelect = document.getElementById("threadMode");
// 初始化選擇值
threadModeSelect.value = gameState.threadMode;
// 添加事件監聽器
threadModeSelect.addEventListener('change', async () => {
const newMode = threadModeSelect.value;
const currentMode = gameState.threadMode;
if (newMode === currentMode) return;
gameState.threadMode = newMode;
// 終止當前 worker
if (worker) {
worker.terminate();
}
// 根據選擇的模式初始化相應的 worker
switch (newMode) {
case "multithread":
worker = new Worker('particleWorker_multithread_fixed.js');
break;
case "multithread_gpu":
// 預留給 GPU 加速模式
console.log("GPU acceleration mode is under development");
return;
case "multithread_wasm":
// 預留給 WebAssembly 模式
console.log("WebAssembly mode is under development");
return;
default:
console.error("Unknown thread mode:", newMode);
return;
}
// 初始化新的 worker
worker.postMessage({
type: 'changeThreadInit',
particleCounts: gameState.particleCounts,
canvasWidth: canvas2d.width,
canvasHeight: canvas2d.height,
//particleGroups: gameState.particleGroups,
particleTypes: gameState.particleTypes,
performanceData: performanceData,
ballRadius: gameState.ballRadius,
sharedMemory: gameState.sharedMemory,
});
// 更新所有相關狀態
updateEveryThing();
});
// 添加按鈕事件監聽器
document.getElementById('randomize-button').addEventListener('click', randomizeValues);
document.getElementById('restart-button').addEventListener('click', initGame);
document.getElementById('randomize-and-restart-button').addEventListener('click', randomizeAndRestart);
document.addEventListener("keydown", function (event) {
if (event.key === "r") {
randomizeValues();
}
if (event.key === "s") {
initGame();
}
if (event.key === "f") {
randomizeAndRestart();
}
if (event.key === "x") {
isUpdateMouseDownUp = false;
}
if (event.key === "z") {
isUpdateMouse = false;
}
if (event.key === "t") {
throughCheckbox.checked = !throughCheckbox.checked;
throughCheckbox.dispatchEvent(new Event('change'));
}
if (event.key === "m") {
const currentIndex = threadModeSelect.selectedIndex;
let nextIndex = (currentIndex + 1) % threadModeSelect.options.length;
let nextOption = threadModeSelect.options[nextIndex];
while (nextOption.disabled) {
nextIndex = (nextIndex + 1) % threadModeSelect.options.length;
nextOption = threadModeSelect.options[nextIndex];
}
threadModeSelect.selectedIndex = nextIndex;
threadModeSelect.dispatchEvent(new Event('change'));
}
});
// 添加滑鼠事件監聽器
canvas2d.addEventListener('mousedown', (e) => {
if (!gameState.enableParticleAffcetRadiusShow) {
isUpdateMouseDownUp = true;
isUpdateMouse = true;
isMouseDown = true;
updateMousePosition(e);
}