-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsketch.js
More file actions
4608 lines (4228 loc) · 162 KB
/
Copy pathsketch.js
File metadata and controls
4608 lines (4228 loc) · 162 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
/* global planck, CONNECT_LEVEL_DATA */
const BASE_WIDTH = 1024;
const BASE_HEIGHT = 768;
const LEVEL_INDEX_PATH = "data/levels/index.json";
const LEVEL_DATA_PATH = "data/levels/levels.json";
const LEVEL_FILES_DIR = "data/levels";
const EDITOR_TEST_LEVEL_KEY = "connect_editor_test_level_v1";
const EDITOR_LOAD_LEVEL_KEY = "connect_editor_load_level_v1";
const EDITOR_TEST_QUERY_PARAM = "editor_test";
const CUSTOM_LEVELS_KEY = "connect_custom_levels_v1";
const CUSTOM_LEVEL_META_KEY = "connect_custom_level_meta_v1";
const LEVEL_MENU_FILTER_KEY = "connect_level_menu_filter_v1";
const MAX_PLAYER_NAME_LENGTH = 10;
const SCORE_KEY = "connect_scores_v1";
const PREVIEW_KEY = "connect_level_preview_";
const ID_RANDOM_RANGE = 1e9;
const COLOR_BLACK = 0;
const COLOR_WHITE = 255;
const COLOR_GRAY_MID = 127;
const COLOR_GRAY_LIGHT = 200;
const COLOR_SUCCESS_RGB = [0, 255, 0];
const COLOR_ERROR_RGB = [255, 0, 0];
const COLOR_PLAYER_A_RGB = [255, 255, 0];
const COLOR_PLAYER_B_RGB = [0, 0, 255];
const ALPHA_OPAQUE = 255;
const ALPHA_DIM = 127;
const MENU_LEVEL_CARD_GAP_PX = 5;
const MENU_DRAG_THRESHOLD_PX = 3;
const MENU_SCROLL_STEP_PX = 100;
const MENU_SCROLLBAR_BOTTOM_AREA_MIDPOINT = 0.5;
const LEVEL_PREVIEW_RENDER_WIDTH = Math.round(BASE_WIDTH);
const LEVEL_PREVIEW_RENDER_HEIGHT = Math.round((LEVEL_PREVIEW_RENDER_WIDTH * BASE_HEIGHT) / BASE_WIDTH);
const SAVED_PREVIEW_WIDTH = 320;
const SAVED_PREVIEW_HEIGHT = Math.round((SAVED_PREVIEW_WIDTH * BASE_HEIGHT) / BASE_WIDTH);
const PARTICLE_LIFE_FRAMES = 80;
const PARTICLE_DAMPING = 0.93;
const PARTICLES_ON_CONNECT = 40;
const PARTICLES_ON_FAIL = 70;
const BOX_FIXTURE_DEF = { density: 5.0, friction: 0.3, restitution: 0.1 };
const CIRCLE_FIXTURE_DEF = { density: 1.0, friction: 0.2, restitution: 0.1 };
const DRAWN_LINE_FIXTURE_DEF = { density: 5.0, friction: 0.1, restitution: 0.01 };
const CUSTOM_SHAPE_CIRCLE_FIXTURE_DEF = { density: 5.0, friction: 0.2, restitution: 0 };
const ARC_BOX_FIXTURE_DEF = { density: 5.0, friction: 0.3, restitution: 0.1 };
const RIGID_GROUP_FIXTURE_DEF = { density: 5.0, friction: 0.3, restitution: 0.1 };
const ARC_BOX_SEGMENTS = 28;
const ARC_BOX_MAX_CUT = 0.95;
const ARC_SIDE_TOP = "top";
const ARC_SIDE_RIGHT = "right";
const ARC_SIDE_BOTTOM = "bottom";
const ARC_SIDE_LEFT = "left";
const ARC_SIDE_ORDER = [ARC_SIDE_TOP, ARC_SIDE_RIGHT, ARC_SIDE_BOTTOM, ARC_SIDE_LEFT];
const DRAW_COLLISION_STEP_FACTOR = 0.35;
const DRAW_COLLISION_CLEARANCE_PX = 1;
const PHYSICS_TIME_STEP_SEC = 1 / 60;
const PHYSICS_MAX_FRAME_DT_SEC = 1 / 15;
const PHYSICS_MAX_SUB_STEPS = 4;
const PHYSICS_VELOCITY_ITERATIONS = 12;
const PHYSICS_POSITION_ITERATIONS = 8;
const ROTOR_GEAR_TEETH = 9;
const ROTOR_GEAR_OUTER_SCALE = 1.03;
const ROTOR_GEAR_INNER_RATIO = 0.78;
const ROTOR_GEAR_CORE_RATIO = 0.45;
const DEFAULT_ROTOR_MOTOR_SPEED_DEG = 180;
const DEFAULT_ROTOR_MOTOR_DIRECTION = 1;
const DEFAULT_ROTOR_MOTOR_TORQUE = 1000000000;
const MODE_PLAY = 1;
const MODE_RESULT = 2;
const MODE_MENU = 4;
let box2d;
let canvasRenderer;
// Lists for game objects and effects.
let circles = [], boxes = [], arcBoxes = [], rigidGroups = [], lines = [], rotors = [], particles = [], cShapes = [];
// List with coordinates of the currently drawn line and collision test points.
let linePos = [], linePosTest = [];
// Toggle physics, drawing permission, level completion, and debug info.
let physics = false, drawPermit = false, levelUp = false, info = false;
// Width of the drawn line and diameter of the balls.
let d = 0, circleR = 0;
// Location and size of the current button.
let buttonX = 0, buttonY = 0, buttonW = 0;
// Current level and game mode.
let level = 0, gameMode = MODE_MENU;
let imgX = 0, imgY = 0, imgW = 0, imgH = 0, imgScroll = 0;
let selectedLevel = -1;
let levelDefs = [];
let levelData = null;
let levelImg = [];
let levelDefaultImg = [];
let levelImgDataUrl = [];
let levelDefaultImgDataUrl = [];
let levelsLoadingFromSources = false;
let menuOpenPending = false;
let timeStart = 0, time = 0, totalLines = 0;
let minTime = 0, minLines = 0;
let playerMinTime = null, playerMinLines = null;
let runSetGlobalTimeRecord = false, runSetGlobalLineRecord = false;
let player = null;
let viewportScale = 1;
let isTouchDevice = false;
let touchInteractionInProgress = false;
let multiTouchBlockActive = false;
let activeTouchUiButton = null;
let playerNameFieldRect = { x: 0, y: 0, w: 0, h: 0 };
let playerPrevButtonRect = { x: 0, y: 0, w: 0, h: 0 };
let playerNextButtonRect = { x: 0, y: 0, w: 0, h: 0 };
let playerDeleteButtonRect = { x: 0, y: 0, w: 0, h: 0 };
let playerCircleContactThisStep = false;
let menuButtonRect = { x: 0, y: 0, w: 0, h: 0 };
let menuButtonArmed = false;
let resetButtonArmed = false;
let menuDragMode = "none"; // "none" | "levels" | "scrollbar"
let menuDragMoved = false;
let menuDragStartX = 0;
let menuDragStartY = 0;
let menuScrollbarGrabOffsetX = 0;
let scoreStore = { rows: [], activeRowId: null };
let editorTestMode = false;
let htmlMenuUi = null;
let htmlMenuVisible = false;
let htmlMenuScrollLeft = 0;
let levelMenuFilter = "default";
class B2D {
// Adapter to mimic Processing's Box2D helper API in p5.js.
constructor() {
this.scale = 10;
this.world = null;
this.stepAccumulator = 0;
}
createWorld() {
this.world = new planck.World({ gravity: { x: 0, y: -20 } });
if (this.world && typeof this.world.on === "function") {
this.world.on("begin-contact", (contact) => {
if (isPlayerCircleContact(contact)) playerCircleContactThisStep = true;
});
}
}
step(frameDtSec = PHYSICS_TIME_STEP_SEC) {
if (!this.world) return;
playerCircleContactThisStep = false;
const rawDt = Number(frameDtSec);
const clampedDt = Number.isFinite(rawDt)
? Math.max(0, Math.min(PHYSICS_MAX_FRAME_DT_SEC, rawDt))
: PHYSICS_TIME_STEP_SEC;
this.stepAccumulator += clampedDt;
let subSteps = 0;
while (this.stepAccumulator >= PHYSICS_TIME_STEP_SEC && subSteps < PHYSICS_MAX_SUB_STEPS) {
this.world.step(PHYSICS_TIME_STEP_SEC, PHYSICS_VELOCITY_ITERATIONS, PHYSICS_POSITION_ITERATIONS);
this.stepAccumulator -= PHYSICS_TIME_STEP_SEC;
subSteps++;
}
if (this.stepAccumulator > PHYSICS_TIME_STEP_SEC * PHYSICS_MAX_SUB_STEPS) {
this.stepAccumulator = PHYSICS_TIME_STEP_SEC;
}
}
pxToW(v) { return v / this.scale; }
wToPx(v) { return v * this.scale; }
p2w(x, y) {
if (typeof x === "object") return planck.Vec2(x.x / this.scale, -x.y / this.scale);
return planck.Vec2(x / this.scale, -y / this.scale);
}
w2p(v) { return createVector(v.x * this.scale, -v.y * this.scale); }
getBodyPos(body) { return this.w2p(body.getPosition()); }
destroy(body) { if (body && this.world) this.world.destroyBody(body); }
}
function setBodyContinuousCollision(body, enabled = true) {
if (!body) return;
if (enabled && typeof body.setBullet === "function") body.setBullet(true);
}
function distSq(x0, y0, x1, y1) {
const dx = x1 - x0;
const dy = y1 - y0;
return dx * dx + dy * dy;
}
function screenPointFromBody(body) {
const pos = body?.getPosition?.();
if (!pos) return null;
return {
x: box2d.wToPx(pos.x),
y: -box2d.wToPx(pos.y),
};
}
function bodyWithinRadiusPx(body, x, y, radiusPx) {
const p = screenPointFromBody(body);
if (!p) return false;
return distSq(p.x, p.y, x, y) <= radiusPx * radiusPx;
}
function isPlayerCircleContact(contact) {
if (!contact || circles.length < 2) return false;
const bodyA = contact.getFixtureA()?.getBody?.();
const bodyB = contact.getFixtureB()?.getBody?.();
if (!bodyA || !bodyB) return false;
const c0 = circles[0]?.body;
const c1 = circles[1]?.body;
if (!c0 || !c1) return false;
return (bodyA === c0 && bodyB === c1) || (bodyA === c1 && bodyB === c0);
}
class Box {
constructor(x, y, w, h, st, a = 0) {
// Coordinates, size, and static/dynamic mode for a box body.
this.x = x; this.y = y; this.w = w; this.h = h; this.st = st;
this.a = Number(a) || 0;
this.boundR = Math.hypot(w / 2, h / 2);
this.c = st ? color(COLOR_GRAY_LIGHT) : color(COLOR_GRAY_MID);
this.body = box2d.world.createBody({ type: st ? "static" : "dynamic", position: box2d.p2w(x, y), angle: -radians(this.a) });
if (!st) setBodyContinuousCollision(this.body, true);
this.body.createFixture(planck.Box(box2d.pxToW(w / 2), box2d.pxToW(h / 2)), { ...BOX_FIXTURE_DEF });
this.body.setUserData(this);
}
contains(x, y, dia) {
// Checks if coordinates are inside this box.
const brushR = Math.max(0, Number(dia) || 0) / 2;
if (!bodyWithinRadiusPx(this.body, x, y, this.boundR + brushR)) return false;
const p = box2d.p2w(x, y);
for (let f = this.body.getFixtureList(); f; f = f.getNext()) if (f.testPoint(p)) return true;
return false;
}
delete() { box2d.destroy(this.body); }
done() {
const p = box2d.getBodyPos(this.body);
if (p.x < -this.w * 2 || p.x > width + this.w * 2 || p.y > height + this.h * 2) { this.delete(); return true; }
return false;
}
draw() {
const p = box2d.getBodyPos(this.body);
push(); translate(p.x, p.y); rotate(-this.body.getAngle()); noStroke(); fill(this.c); rect(0, 0, this.w, this.h); pop();
}
}
function normalizeArcSideMaybe(side) {
const s = String(side || "").toLowerCase();
if (s === ARC_SIDE_TOP) return ARC_SIDE_TOP;
if (s === ARC_SIDE_RIGHT) return ARC_SIDE_RIGHT;
if (s === ARC_SIDE_BOTTOM) return ARC_SIDE_BOTTOM;
if (s === ARC_SIDE_LEFT) return ARC_SIDE_LEFT;
return null;
}
function normalizeArcSide(side) {
return normalizeArcSideMaybe(side) || ARC_SIDE_TOP;
}
function normalizeArcSides(value, fallbackSide = ARC_SIDE_TOP) {
const out = [];
const seen = new Set();
const pushSide = (raw) => {
const side = normalizeArcSideMaybe(raw);
if (!side || seen.has(side)) return;
seen.add(side);
out.push(side);
};
if (Array.isArray(value)) {
for (const side of value) pushSide(side);
return ARC_SIDE_ORDER.filter((side) => seen.has(side));
}
if (typeof value === "string") {
const tokens = value.split(/[\s,|/]+/).filter(Boolean);
if (tokens.length > 1) {
for (const token of tokens) pushSide(token);
} else {
pushSide(value);
}
const ordered = ARC_SIDE_ORDER.filter((side) => seen.has(side));
if (ordered.length > 0) return ordered;
return fallbackSide == null ? [] : [normalizeArcSide(fallbackSide)];
}
if (value != null) {
pushSide(value);
const ordered = ARC_SIDE_ORDER.filter((side) => seen.has(side));
if (ordered.length > 0) return ordered;
}
return fallbackSide == null ? [] : [normalizeArcSide(fallbackSide)];
}
function clampArcCut(value) {
const raw = Number(value) || 0;
return Math.max(-ARC_BOX_MAX_CUT, Math.min(ARC_BOX_MAX_CUT, raw));
}
function normalizeRotorMotorSpeedDeg(value) {
const raw = Number(value);
if (!Number.isFinite(raw)) return DEFAULT_ROTOR_MOTOR_SPEED_DEG;
return Math.max(0, Math.abs(raw));
}
function normalizeRotorMotorDirection(value) {
if (typeof value === "string") {
const v = value.trim().toLowerCase();
if (v === "-1" || v === "ccw" || v === "counterclockwise" || v === "counter-clockwise" || v === "left") return -1;
if (v === "1" || v === "cw" || v === "clockwise" || v === "right") return 1;
}
const raw = Number(value);
if (!Number.isFinite(raw)) return DEFAULT_ROTOR_MOTOR_DIRECTION;
return raw < 0 ? -1 : 1;
}
function normalizeRotorMotorTorque(value) {
const raw = Number(value);
if (!Number.isFinite(raw)) return DEFAULT_ROTOR_MOTOR_TORQUE;
return Math.max(0, raw);
}
function getArcNormalSpan(w, h, side) {
const s = normalizeArcSide(side);
return s === ARC_SIDE_TOP || s === ARC_SIDE_BOTTOM ? h : w;
}
function positiveAngleSpan(start, end) {
let span = (end - start) % (Math.PI * 2);
if (span < 0) span += Math.PI * 2;
return span;
}
function sampleArcThroughPoint(center, radius, startPoint, endPoint, targetPoint, segments = ARC_BOX_SEGMENTS) {
const a1 = Math.atan2(startPoint.y - center.y, startPoint.x - center.x);
const a2 = Math.atan2(endPoint.y - center.y, endPoint.x - center.x);
const ccwSpan = positiveAngleSpan(a1, a2);
const cwSpan = ccwSpan - Math.PI * 2;
const ccwMid = a1 + ccwSpan / 2;
const cwMid = a1 + cwSpan / 2;
const ccwPoint = { x: center.x + Math.cos(ccwMid) * radius, y: center.y + Math.sin(ccwMid) * radius };
const cwPoint = { x: center.x + Math.cos(cwMid) * radius, y: center.y + Math.sin(cwMid) * radius };
const useCCW = dist(ccwPoint.x, ccwPoint.y, targetPoint.x, targetPoint.y) <= dist(cwPoint.x, cwPoint.y, targetPoint.x, targetPoint.y);
const span = useCCW ? ccwSpan : cwSpan;
const steps = Math.max(6, Math.round(segments));
const points = [];
for (let i = 0; i <= steps; i++) {
const a = a1 + (span * i) / steps;
points.push({
x: center.x + Math.cos(a) * radius,
y: center.y + Math.sin(a) * radius,
});
}
return points;
}
function buildArcSidePoints(width, height, cut, side, segments = ARC_BOX_SEGMENTS) {
const s = normalizeArcSide(side);
const halfW = width / 2;
const halfH = height / 2;
const tl = { x: -halfW, y: -halfH };
const tr = { x: halfW, y: -halfH };
const br = { x: halfW, y: halfH };
const bl = { x: -halfW, y: halfH };
let p1;
let p2;
let inward;
if (s === ARC_SIDE_TOP) {
p1 = tl;
p2 = tr;
inward = { x: 0, y: 1 };
} else if (s === ARC_SIDE_RIGHT) {
p1 = tr;
p2 = br;
inward = { x: -1, y: 0 };
} else if (s === ARC_SIDE_BOTTOM) {
p1 = br;
p2 = bl;
inward = { x: 0, y: -1 };
} else {
p1 = bl;
p2 = tl;
inward = { x: 1, y: 0 };
}
const depthAbs = Math.abs(clampArcCut(cut)) * getArcNormalSpan(width, height, s);
if (depthAbs <= 1e-6) return [p1, p2];
const chord = dist(p1.x, p1.y, p2.x, p2.y);
// Keep sagitta under half the side length to avoid >180deg arcs that bulge outside the box.
const maxByChord = Math.max(0.0001, chord * 0.4999);
const notchDepth = Math.max(0.0001, Math.min(depthAbs, getArcNormalSpan(width, height, s) * ARC_BOX_MAX_CUT, maxByChord));
const radius = (chord * chord) / (8 * notchDepth) + notchDepth / 2;
const centerOffset = radius - notchDepth;
const midpoint = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
const sign = clampArcCut(cut) >= 0 ? 1 : -1;
const bulge = { x: inward.x * sign, y: inward.y * sign };
const center = {
x: midpoint.x - bulge.x * centerOffset,
y: midpoint.y - bulge.y * centerOffset,
};
const target = {
x: midpoint.x + bulge.x * notchDepth,
y: midpoint.y + bulge.y * notchDepth,
};
return sampleArcThroughPoint(center, radius, p1, p2, target, segments);
}
function buildArcBoxLocalPoints(w, h, cut, sides, segments = ARC_BOX_SEGMENTS) {
const width = Math.max(1, Number(w) || 1);
const height = Math.max(1, Number(h) || 1);
const sideList = normalizeArcSides(sides, ARC_SIDE_TOP);
const activeSides = new Set(sideList);
const halfW = width / 2;
const halfH = height / 2;
const tl = { x: -halfW, y: -halfH };
const tr = { x: halfW, y: -halfH };
const br = { x: halfW, y: halfH };
const bl = { x: -halfW, y: halfH };
const depth = clampArcCut(cut);
if (Math.abs(depth) <= 1e-6 || activeSides.size < 1) return [tl, tr, br, bl];
const out = [tl];
const edges = [
{ side: ARC_SIDE_TOP, end: tr },
{ side: ARC_SIDE_RIGHT, end: br },
{ side: ARC_SIDE_BOTTOM, end: bl },
{ side: ARC_SIDE_LEFT, end: tl },
];
for (const edge of edges) {
if (!activeSides.has(edge.side)) {
out.push(edge.end);
continue;
}
const arcPoints = buildArcSidePoints(width, height, depth, edge.side, segments);
for (let i = 1; i < arcPoints.length; i++) out.push(arcPoints[i]);
}
if (out.length > 1) {
const last = out[out.length - 1];
if (dist(last.x, last.y, tl.x, tl.y) < 1e-6) out.pop();
}
return out;
}
function polygonAreaSigned(points) {
let area = 0;
for (let i = 0; i < points.length; i++) {
const a = points[i];
const b = points[(i + 1) % points.length];
area += a.x * b.y - b.x * a.y;
}
return area / 2;
}
function pointInTriangle2D(p, a, b, c) {
const v0x = c.x - a.x;
const v0y = c.y - a.y;
const v1x = b.x - a.x;
const v1y = b.y - a.y;
const v2x = p.x - a.x;
const v2y = p.y - a.y;
const den = v0x * v1y - v1x * v0y;
if (Math.abs(den) < 1e-9) return false;
const u = (v2x * v1y - v1x * v2y) / den;
const v = (v0x * v2y - v2x * v0y) / den;
return u >= 1e-8 && v >= 1e-8 && u + v <= 1 - 1e-8;
}
function triangulateSimplePolygon(points) {
if (!Array.isArray(points) || points.length < 3) return [];
const verts = points
.map((p) => ({ x: Number(p.x), y: Number(p.y) }))
.filter((p) => Number.isFinite(p.x) && Number.isFinite(p.y));
if (verts.length < 3) return [];
const area = polygonAreaSigned(verts);
if (Math.abs(area) < 1e-8) return [];
const orientation = area > 0 ? 1 : -1;
const indices = verts.map((_v, i) => i);
const triangles = [];
let guard = 0;
while (indices.length > 3 && guard < 4000) {
guard++;
let clipped = false;
for (let i = 0; i < indices.length; i++) {
const prevIdx = indices[(i - 1 + indices.length) % indices.length];
const currIdx = indices[i];
const nextIdx = indices[(i + 1) % indices.length];
const a = verts[prevIdx];
const b = verts[currIdx];
const c = verts[nextIdx];
const cross = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
if (cross * orientation <= 1e-8) continue;
let hasInnerPoint = false;
for (let j = 0; j < indices.length; j++) {
const testIdx = indices[j];
if (testIdx === prevIdx || testIdx === currIdx || testIdx === nextIdx) continue;
if (pointInTriangle2D(verts[testIdx], a, b, c)) {
hasInnerPoint = true;
break;
}
}
if (hasInnerPoint) continue;
triangles.push([a, b, c]);
indices.splice(i, 1);
clipped = true;
break;
}
if (!clipped) return [];
}
if (indices.length === 3) {
triangles.push([verts[indices[0]], verts[indices[1]], verts[indices[2]]]);
}
return triangles;
}
class ArcBox {
constructor(x, y, w, h, cut, sides, st, a = 0) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.cut = clampArcCut(cut);
this.sides = normalizeArcSides(sides, ARC_SIDE_TOP);
this.side = this.sides[0];
this.st = st;
this.a = Number(a) || 0;
this.boundR = Math.hypot(w / 2, h / 2);
this.c = st ? color(COLOR_GRAY_LIGHT) : color(COLOR_GRAY_MID);
this.localPoints = buildArcBoxLocalPoints(w, h, this.cut, this.sides);
this.body = box2d.world.createBody({ type: st ? "static" : "dynamic", position: box2d.p2w(x, y), angle: -radians(this.a) });
if (!st) setBodyContinuousCollision(this.body, true);
const triangles = triangulateSimplePolygon(this.localPoints);
if (triangles.length > 0) {
for (const tri of triangles) {
const verts = tri.map((v) => box2d.p2w(v.x, v.y));
this.body.createFixture(planck.Polygon(verts), { ...ARC_BOX_FIXTURE_DEF });
}
} else {
this.body.createFixture(planck.Box(box2d.pxToW(w / 2), box2d.pxToW(h / 2)), { ...ARC_BOX_FIXTURE_DEF });
}
this.body.setUserData(this);
}
contains(x, y) {
if (!bodyWithinRadiusPx(this.body, x, y, this.boundR)) return false;
const p = box2d.p2w(x, y);
for (let f = this.body.getFixtureList(); f; f = f.getNext()) if (f.testPoint(p)) return true;
return false;
}
delete() { box2d.destroy(this.body); }
done() {
const p = box2d.getBodyPos(this.body);
if (p.x < -this.w * 2 || p.x > width + this.w * 2 || p.y > height + this.h * 2) { this.delete(); return true; }
return false;
}
draw() {
const p = box2d.getBodyPos(this.body);
push();
translate(p.x, p.y);
rotate(-this.body.getAngle());
noStroke();
fill(this.c);
beginShape();
for (const v of this.localPoints) vertex(v.x, v.y);
endShape(CLOSE);
pop();
}
}
function normalizeRigidGroupPart(rawPart) {
if (!rawPart || typeof rawPart !== "object") return null;
const t = String(rawPart.type || "").toLowerCase();
const rawW = Number(rawPart.w);
const rawH = Number(rawPart.h);
const w = Math.max(1e-6, Number.isFinite(rawW) ? Math.abs(rawW) : 0.2);
const h = Math.max(1e-6, Number.isFinite(rawH) ? Math.abs(rawH) : 0.05);
if (t === "box") {
return {
type: "box",
x: Number.isFinite(rawPart.x) ? rawPart.x : 0,
y: Number.isFinite(rawPart.y) ? rawPart.y : 0,
w,
h,
angle: Number.isFinite(rawPart.angle) ? rawPart.angle : 0,
};
}
if (t === "arcbox") {
const sides = normalizeArcSides(rawPart.sides ?? rawPart.side, ARC_SIDE_TOP);
return {
type: "arcbox",
x: Number.isFinite(rawPart.x) ? rawPart.x : 0,
y: Number.isFinite(rawPart.y) ? rawPart.y : 0,
w,
h,
cut: clampArcCut(rawPart.cut),
sides,
side: sides[0],
angle: Number.isFinite(rawPart.angle) ? rawPart.angle : 0,
};
}
if (t === "shape") {
return {
type: "shape",
x: Number.isFinite(rawPart.x) ? rawPart.x : 0,
y: Number.isFinite(rawPart.y) ? rawPart.y : 0,
w,
h,
edges: Math.max(3, Number(rawPart.edges) || 6),
angle: Number.isFinite(rawPart.angle) ? rawPart.angle : 0,
};
}
return null;
}
function rotatePointXY(x, y, angleRad) {
const c = Math.cos(angleRad);
const s = Math.sin(angleRad);
return { x: x * c - y * s, y: x * s + y * c };
}
function rigidGroupPartRadiusPx(part) {
if (!part) return 0;
const px = Number(part.x) || 0;
const py = Number(part.y) || 0;
let localR = 0;
if (part.type === "box" || part.type === "arcbox") {
localR = Math.hypot((Number(part.w) || 0) / 2, (Number(part.h) || 0) / 2);
} else if (part.type === "shape") {
const e = Math.max(3, Number(part.edges) || 6);
if (e > 8) localR = (Number(part.w) + Number(part.h)) / 2;
else localR = Math.hypot(Number(part.w) || 0, Number(part.h) || 0);
}
return Math.hypot(px, py) + localR;
}
function drawRigidGroupPart(part) {
push();
translate(part.x, part.y);
rotate(radians(Number(part.angle) || 0));
if (part.type === "box") {
rect(0, 0, part.w, part.h);
pop();
return;
}
if (part.type === "arcbox") {
const pts = buildArcBoxLocalPoints(part.w, part.h, part.cut, part.sides ?? part.side);
beginShape();
for (const p of pts) vertex(p.x, p.y);
endShape(CLOSE);
pop();
return;
}
if (part.type === "shape") {
const e = Math.max(3, Number(part.edges) || 6);
if (e <= 8) {
beginShape();
for (let i = 0; i < e; i++) {
const a = radians(i * (360 / e));
vertex(cos(a) * part.w, sin(a) * part.h);
}
endShape(CLOSE);
} else {
ellipse(0, 0, part.w + part.h, part.w + part.h);
}
}
pop();
}
class RigidGroup {
constructor(x, y, parts, st, a = 0) {
this.x = x;
this.y = y;
this.st = Boolean(st);
this.a = Number(a) || 0;
this.c = this.st ? color(COLOR_GRAY_LIGHT) : color(COLOR_GRAY_MID);
this.parts = (Array.isArray(parts) ? parts : [])
.map(normalizeRigidGroupPart)
.filter(Boolean);
this.boundR = 0;
for (const part of this.parts) this.boundR = Math.max(this.boundR, rigidGroupPartRadiusPx(part));
if (this.boundR <= 0) this.boundR = 20;
this.body = box2d.world.createBody({ type: this.st ? "static" : "dynamic", position: box2d.p2w(x, y), angle: -radians(this.a) });
if (!this.st) setBodyContinuousCollision(this.body, true);
for (const part of this.parts) {
if (part.type === "box") {
const center = box2d.p2w(part.x, part.y);
this.body.createFixture(
planck.Box(box2d.pxToW(part.w / 2), box2d.pxToW(part.h / 2), center, -radians(Number(part.angle) || 0)),
{ ...RIGID_GROUP_FIXTURE_DEF }
);
continue;
}
if (part.type === "arcbox") {
const local = buildArcBoxLocalPoints(part.w, part.h, part.cut, part.sides ?? part.side);
const partAngle = radians(Number(part.angle) || 0);
const transformed = local.map((p) => {
const r = rotatePointXY(p.x, p.y, partAngle);
return { x: r.x + part.x, y: r.y + part.y };
});
const tris = triangulateSimplePolygon(transformed);
if (tris.length > 0) {
for (const tri of tris) {
const verts = tri.map((v) => box2d.p2w(v.x, v.y));
this.body.createFixture(planck.Polygon(verts), { ...RIGID_GROUP_FIXTURE_DEF });
}
}
continue;
}
if (part.type === "shape") {
const e = Math.max(3, Number(part.edges) || 6);
if (e <= 8) {
const verts = [];
const partAngle = radians(Number(part.angle) || 0);
for (let i = 0; i < e; i++) {
const a = radians(i * (360 / e));
const vx = cos(a) * part.w;
const vy = sin(a) * part.h;
const r = rotatePointXY(vx, vy, partAngle);
verts.push(box2d.p2w(r.x + part.x, r.y + part.y));
}
this.body.createFixture(planck.Polygon(verts), { ...RIGID_GROUP_FIXTURE_DEF });
} else {
const center = box2d.p2w(part.x, part.y);
this.body.createFixture(planck.Circle(center, box2d.pxToW((part.w + part.h) / 2)), { ...RIGID_GROUP_FIXTURE_DEF });
}
}
}
// Fallback in case fixtures failed to build.
if (!this.body.getFixtureList()) {
this.body.createFixture(planck.Box(box2d.pxToW(10), box2d.pxToW(10)), { ...RIGID_GROUP_FIXTURE_DEF });
}
this.body.setUserData(this);
}
contains(x, y) {
if (!bodyWithinRadiusPx(this.body, x, y, this.boundR)) return false;
const p = box2d.p2w(x, y);
for (let f = this.body.getFixtureList(); f; f = f.getNext()) if (f.testPoint(p)) return true;
return false;
}
delete() { box2d.destroy(this.body); }
done() {
const p = box2d.getBodyPos(this.body);
if (p.x < -this.boundR * 2 || p.x > width + this.boundR * 2 || p.y > height + this.boundR * 2) { this.delete(); return true; }
return false;
}
draw() {
const p = box2d.getBodyPos(this.body);
push();
translate(p.x, p.y);
rotate(-this.body.getAngle());
noStroke();
fill(this.c);
for (const part of this.parts) drawRigidGroupPart(part);
pop();
}
}
class Circle {
constructor(x, y, r, c) {
// Coordinates, radius, and color for a dynamic circle body.
this.x = x; this.y = y; this.r = r; this.c = c; this.pos = createVector(x, y);
this.body = box2d.world.createBody({ type: "dynamic", position: box2d.p2w(x, y) });
setBodyContinuousCollision(this.body, true);
this.body.createFixture(planck.Circle(box2d.pxToW(r)), { ...CIRCLE_FIXTURE_DEF });
this.body.setUserData(this);
}
delete() { box2d.destroy(this.body); }
change() { this.c = color(...COLOR_SUCCESS_RGB); }
contains(x, y, dia) {
// Checks if coordinates are inside this circle.
const p = screenPointFromBody(this.body);
if (!p) return false;
this.pos.x = p.x;
this.pos.y = p.y;
const radius = this.r + (Number(dia) || 0) / 2;
return distSq(p.x, p.y, x, y) < radius * radius;
}
done() {
const p = box2d.getBodyPos(this.body);
if (p.x < -this.r * 2 || p.x > width + this.r * 2 || p.y > height + this.r * 2) { this.delete(); return true; }
return false;
}
draw() {
this.pos = box2d.getBodyPos(this.body);
push(); translate(this.pos.x, this.pos.y); rotate(-this.body.getAngle()); if (info) fill(COLOR_GRAY_MID, ALPHA_DIM); else fill(this.c); noStroke(); ellipse(0, 0, this.r * 2, this.r * 2); if (info) { stroke(COLOR_BLACK); line(0, 0, this.r, 0); } pop();
}
}
class LineBody {
constructor(points, h) {
// Width and height of the rectangles that compose the drawn line.
this.h = h;
// Broad-phase radius around the body's origin for quick rejection.
this.boundR = this.h / 2;
// List of drawn coordinates.
this.lineDot = points.map((p) => createVector(p.x, p.y));
// List of body-local offsets for each coordinate.
this.offset = [planck.Vec2(0, 0)];
this.offsetPx = [{ x: 0, y: 0 }];
// List of center coordinates used to draw the connecting rectangles.
this.center = [planck.Vec2(0, 0)];
this.centerPx = [{ x: 0, y: 0 }];
// List of segment vectors and per-segment angles.
this.l = [planck.Vec2(0, 0)];
this.segmentWidthPx = [0];
this.angle = [0];
this.body = box2d.world.createBody({ type: "dynamic", position: box2d.p2w(this.lineDot[0].x, this.lineDot[0].y) });
setBodyContinuousCollision(this.body, true);
// Creates one circle shape at the first coordinate.
this.body.createFixture(planck.Circle(box2d.pxToW(this.h / 2)), { ...DRAWN_LINE_FIXTURE_DEF });
const origin = box2d.p2w(this.lineDot[0].x, this.lineDot[0].y);
for (let i = 1; i < this.lineDot.length; i++) {
const o = box2d.p2w(this.lineDot[i].x, this.lineDot[i].y);
const local = planck.Vec2(o.x - origin.x, o.y - origin.y);
this.offset.push(local);
this.offsetPx.push({ x: box2d.wToPx(local.x), y: -box2d.wToPx(local.y) });
this.boundR = Math.max(this.boundR, box2d.wToPx(Math.hypot(local.x, local.y)) + this.h / 2);
const lv = planck.Vec2(this.offset[i - 1].x - this.offset[i].x, this.offset[i - 1].y - this.offset[i].y);
this.l.push(lv);
const w = Math.sqrt(lv.x * lv.x + lv.y * lv.y);
this.segmentWidthPx.push(box2d.wToPx(w));
const c = planck.Vec2((this.offset[i - 1].x + this.offset[i].x) * 0.5, (this.offset[i - 1].y + this.offset[i].y) * 0.5);
this.center.push(c);
this.centerPx.push({ x: box2d.wToPx(c.x), y: -box2d.wToPx(c.y) });
this.angle.push(Math.atan2(lv.y, lv.x));
this.body.createFixture(planck.Circle(this.offset[i], box2d.pxToW(this.h / 2)), { ...DRAWN_LINE_FIXTURE_DEF });
this.body.createFixture(planck.Box(w / 2, box2d.pxToW(this.h / 2), c, this.angle[i]), { ...DRAWN_LINE_FIXTURE_DEF });
}
this.body.setUserData(this);
}
containsPoint(x, y) {
const p = box2d.p2w(x, y);
for (let f = this.body.getFixtureList(); f; f = f.getNext()) if (f.testPoint(p)) return true;
return false;
}
contains(x, y, dia = 0) {
// Checks whether the point/brush overlaps this drawn line body.
const brushR = Math.max(0, Number(dia) || 0) / 2;
const pos = box2d.getBodyPos(this.body);
const maxR = this.boundR + brushR;
const dx = x - pos.x;
const dy = y - pos.y;
if (dx * dx + dy * dy > maxR * maxR) return false;
if (this.containsPoint(x, y)) return true;
if (brushR <= 0) return false;
const dxy = brushR * 0.7071;
if (this.containsPoint(x - brushR, y)) return true;
if (this.containsPoint(x + brushR, y)) return true;
if (this.containsPoint(x, y - brushR)) return true;
if (this.containsPoint(x, y + brushR)) return true;
if (this.containsPoint(x - dxy, y - dxy)) return true;
if (this.containsPoint(x + dxy, y - dxy)) return true;
if (this.containsPoint(x - dxy, y + dxy)) return true;
if (this.containsPoint(x + dxy, y + dxy)) return true;
return false;
}
delete() { box2d.destroy(this.body); }
done() {
// Checks if the line is farther off-screen than its max span.
const p = screenPointFromBody(this.body);
if (!p) return false;
const margin = this.boundR + this.h;
if (p.x < -margin || p.x > width + margin || p.y > height + margin) { this.delete(); return true; }
return false;
}
draw() {
// Draws line circles/rectangles according to Box2D physics.
const pos = box2d.getBodyPos(this.body);
push(); translate(pos.x, pos.y); rotate(-this.body.getAngle()); noStroke(); if (info) fill(COLOR_GRAY_MID, ALPHA_DIM); else fill(COLOR_GRAY_MID);
// Draw first point.
ellipse(this.offsetPx[0].x, this.offsetPx[0].y, this.h, this.h);
for (let i = 1; i < this.lineDot.length; i++) {
push(); translate(this.centerPx[i].x, this.centerPx[i].y); rotate(-this.angle[i]); rect(0, 0, this.segmentWidthPx[i], this.h); pop();
ellipse(this.offsetPx[i].x, this.offsetPx[i].y, this.h, this.h);
}
pop();
}
}
class CustomShape {
constructor(x, y, w, h, e, st, a = 0) {
// Location, size, edges (<=8 polygon, >8 circle), and static/dynamic mode.
this.x = x; this.y = y; this.w = w; this.h = h; this.e = max(3, e); this.st = st;
this.c = st ? color(COLOR_GRAY_LIGHT) : color(COLOR_GRAY_MID);
this.a = Number(a) || 0;
this.boundR = this.e <= 8 ? Math.hypot(w, h) : (w + h) / 2;
this.body = box2d.world.createBody({ type: st ? "static" : "dynamic", position: box2d.p2w(x, y), angle: -radians(this.a) });
if (!st) setBodyContinuousCollision(this.body, true);
if (this.e <= 8) {
const verts = [];
for (let i = 0; i < this.e; i++) {
const a = radians(i * (360 / this.e));
const v = p5.Vector.fromAngle(a);
verts.push(box2d.p2w(v.x * w, v.y * h));
}
this.body.createFixture(planck.Polygon(verts), 1);
} else {
this.body.createFixture(planck.Circle(box2d.pxToW((w + h) / 2)), { ...CUSTOM_SHAPE_CIRCLE_FIXTURE_DEF });
}
this.body.setUserData(this);
}
contains(x, y) {
// Checks if coordinates are inside this shape.
if (!bodyWithinRadiusPx(this.body, x, y, this.boundR)) return false;
const p = box2d.p2w(x, y);
for (let f = this.body.getFixtureList(); f; f = f.getNext()) if (f.testPoint(p)) return true;
return false;
}
delete() { box2d.destroy(this.body); }
done() {
const p = box2d.getBodyPos(this.body);
if (p.x < -this.w * 2 || p.x > width + this.w * 2 || p.y > height + this.h * 2) { this.delete(); return true; }
return false;
}
draw() {
const p = box2d.getBodyPos(this.body);
push(); translate(p.x, p.y); rotate(-this.body.getAngle()); noStroke(); fill(this.c);
if (this.e <= 8) {
const f = this.body.getFixtureList();
if (f && f.getShape().getType() === "polygon") {
beginShape();
for (const v of f.getShape().m_vertices) { const pv = box2d.w2p(v); vertex(pv.x, pv.y); }
endShape(CLOSE);
}
} else ellipse(0, 0, this.w + this.h, this.w + this.h);
pop();
}
}
class Rotor {
constructor(
x,
y,
w,
h,
e,
motor,
a = 0,
parts = [],
motorSpeedDeg = DEFAULT_ROTOR_MOTOR_SPEED_DEG,
motorDirection = DEFAULT_ROTOR_MOTOR_DIRECTION,
motorTorque = DEFAULT_ROTOR_MOTOR_TORQUE
) {
// Coordinates and size of the rotating core plus optional attached parts.
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.e = max(3, Number(e) || 4);
this.a = Number(a) || 0;
this.motor = Boolean(motor);
this.motorSpeedDeg = normalizeRotorMotorSpeedDeg(motorSpeedDeg);
this.motorDirection = normalizeRotorMotorDirection(motorDirection);
this.motorTorque = normalizeRotorMotorTorque(motorTorque);
this.parts = (Array.isArray(parts) ? parts : [])
.map(normalizeRigidGroupPart)
.filter(Boolean);
this.boundR = Math.hypot(this.w, this.h);
for (const part of this.parts) this.boundR = Math.max(this.boundR, rigidGroupPartRadiusPx(part));
const initialAngle = -radians(this.a);
this.fixture = new Box(x, y, h / 2, h / 2, true);
this.body = box2d.world.createBody({ type: "dynamic", position: box2d.p2w(x, y), angle: initialAngle });
this.addCoreFixture();
for (const part of this.parts) this.addPartFixture(part);
if (!this.body.getFixtureList()) {
this.body.createFixture(planck.Box(box2d.pxToW(10), box2d.pxToW(10)), { ...RIGID_GROUP_FIXTURE_DEF });
}
box2d.world.createJoint(planck.RevoluteJoint(
{
// Box2D/Planck positive angular velocity appears opposite to our screen-space clockwise label.
motorSpeed: -radians(this.motorSpeedDeg) * this.motorDirection,
maxMotorTorque: this.motorTorque,
enableMotor: this.motor
},
this.fixture.body,
this.body,
this.fixture.body.getWorldCenter()
));
}
addCoreFixture() {
if (this.e === 4) {