jelly_physics 0.2.1

2D soft body physics engine based on point masses
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
//! 2D soft body physics engine based on point masses.
//!
//! Bodies are rings of point masses joined by force-based springs; ropes are chains of
//! point masses joined by position-based distance constraints ([`Rope`]).
use std::collections::HashMap;
use std::ops::Range;

use glam::{Vec2, vec2};
use slotmap::DenseSlotMap;

slotmap::new_key_type! {
    /// Stable handle of a [`Body`] in [`World::bodies`]. It stays valid when other bodies are removed.
    pub struct BodyId;
    /// Stable handle of a [`Rope`] in [`World::ropes`]. It stays valid when other ropes are removed.
    pub struct RopeId;
}

/// Lower bound for a body's area, so pressure never divides by a near-zero value.
const MIN_AREA: f32 = 0.5;
/// Small threshold that prevents division by zero.
const EPSILON: f32 = 1e-4;

/// Everything in JellyPhysics is made of point masses: a position, a velocity, a force and a
/// mass. No rotation, no shape. Forces are summed each step.
///
/// Updating velocity first is what makes it "semi-implicit"; it is far more stable for springs
#[derive(Clone, Copy, Debug, Default)]
pub struct PointMass {
    /// World position.
    pub position: Vec2,
    /// Current velocity.
    pub velocity: Vec2,
    /// Force accumulated during the current step.
    pub force: Vec2,
    /// Mass; zero or less means the point is static.
    pub mass: f32,
}

impl PointMass {
    /// Returns `true` if the point is static (its mass is zero or less).
    #[inline]
    pub fn is_static(&self) -> bool {
        self.mass <= 0.0
    }

    /// Returns `1 / mass`, or `0.0` for static points.
    #[inline]
    pub fn inverse_mass(&self) -> f32 {
        if self.is_static() {
            0.0
        } else {
            1.0 / self.mass
        }
    }
}

/// Drag per 1/60 s of simulated time, so the result does not depend on the step size.
fn apply_air_drag(points: &mut [PointMass], drag: f32, dt: f32) {
    let factor = (1.0 - drag).powf(dt * 60.0);

    for point in points {
        point.velocity *= factor;
    }
}

/// Semi-implicit Euler step: updates velocity from force, then position from velocity.
fn integrate(points: &mut [PointMass], dt: f32) {
    for point in points.iter_mut().filter(|point| !point.is_static()) {
        point.velocity += point.force / point.mass * dt;
        point.position += point.velocity * dt;
    }
}

/// Resolves one axis of the bounds: pushes `position` back into `min..=max`, reflects the velocity
/// that points out of the box (scaled by `elasticity`), and scales the sliding velocity along the
/// other axis by `slide`.
#[inline]
fn collide_axis(
    position: &mut f32,
    velocity: &mut f32,
    slide_velocity: &mut f32,
    (min, max): (f32, f32),
    elasticity: f32,
    slide: f32,
) {
    if *position < min {
        *position = min;
        if *velocity < 0.0 {
            *velocity = -*velocity * elasticity;
        }
        *slide_velocity *= slide;
    } else if *position > max {
        *position = max;
        if *velocity > 0.0 {
            *velocity = -*velocity * elasticity;
        }
        *slide_velocity *= slide;
    }
}

/// Keeps the points inside the [`WorldBounds`].
///
/// A point outside is pushed back to the boundary. Its velocity into the side is reflected and
/// scaled by [`Material::elasticity`], and its velocity along the side is reduced by
/// [`Material::friction`] (1 = full stop), the same way [`resolve_contact`] does it.
///
/// Static points are skipped, so a static [`Body`] may extend past the bounds.
fn collide_bounds(points: &mut [PointMass], bounds: Aabb, material: Material, dt: f32) {
    // Friction is applied on every step the point touches a side, so it is scaled to 1/60 s
    // of simulated time to not depend on the step size.
    let slide = (1.0 - material.friction).clamp(0.0, 1.0).powf(dt * 60.0);

    for point in points.iter_mut().filter(|point| !point.is_static()) {
        collide_axis(
            &mut point.position.x,
            &mut point.velocity.x,
            &mut point.velocity.y,
            (bounds.min.x, bounds.max.x),
            material.elasticity,
            slide,
        );
        collide_axis(
            &mut point.position.y,
            &mut point.velocity.y,
            &mut point.velocity.x,
            (bounds.min.y, bounds.max.y),
            material.elasticity,
            slide,
        );
    }
}

/// A soft body is [`PointMass`] values joined by [`Spring`]s. Each spring wants to stay at its rest length:
/// stretch it and it pulls the ends together, squash it and it pushes them apart. A damper
/// slows the ends' relative motion along the spring so it doesn't wobble forever.
///
/// The stiffness and damping are not stored here: they come from the owning body
/// ([`Body::spring_k`], [`Body::spring_damping`]), so changing them takes effect immediately.
#[derive(Clone, Copy, Debug, Default)]
pub struct Spring {
    /// Index of the first end point in [`World::points`].
    pub a: usize,
    /// Index of the second end point in [`World::points`].
    pub b: usize,
    /// Rest length of the spring.
    pub rest: f32,
    /// Key of the owning body in [`World::bodies`]; its spring settings drive this spring.
    pub body: BodyId,
}

/// Ties a rope node to an existing point in [`World::points`], usually a point of a [`Body`].
///
/// The constraint is solved on positions: both the rope node and the target are moved,
/// split by their inverse masses. A static target (`mass == 0`) acts as an immovable anchor.
#[derive(Clone, Copy, Debug, Default)]
pub struct RopeAnchor {
    /// Offset of the rope node inside [`Rope::first`..`first + count`].
    pub node: usize,
    /// Index of the point the node is tied to in [`World::points`].
    pub target: usize,
}

/// A chain of point masses joined by position-based distance constraints.
///
/// Unlike a [`Spring`], a rope does not apply forces: after integration its segment lengths
/// are projected directly onto the positions ([`World::fixed_step`]), and the change is fed
/// back into velocity. A rope only resists stretching, so it goes slack when compressed.
/// Its nodes are consecutive in [`World::points`], just like a body's points.
///
/// Rope nodes collide with [`Body`] rings using the same [`Contact`] path as body points
/// (while [`Settings::body_collisions`] is on); use [`Rope::group`] to avoid colliding with
/// a body the rope is tied to.
#[derive(Clone, Debug, Default)]
pub struct Rope {
    /// Index of the rope's first node in [`World::points`].
    pub first: usize,
    /// Number of nodes in the rope.
    pub count: usize,
    /// Rest length of each segment; `rest.len() == count - 1`.
    pub rest: Vec<f32>,
    /// Fraction of the stretch error corrected per solver pass, `0.0..=1.0`. Default: `1.0`.
    pub stiffness: f32,
    /// Constraint solver passes per substep. Default: `4`.
    pub iterations: usize,
    /// Ropes and bodies in the same non-zero group do not collide, unless
    /// [`World::set_group_collision`] says otherwise for that pair. Default: `0`.
    pub group: usize,
    /// Material id used for contacts with bodies. Default: `0`.
    pub material: usize,
    /// Nodes tied to other points (e.g. a body's points or a static anchor).
    pub anchors: Vec<RopeAnchor>,
    /// Bounding box of the rope's nodes, refreshed every step for broad-phase culling.
    pub aabb: Aabb,
}

impl Rope {
    /// The rope's range of indices in [`World::points`].
    #[inline]
    pub fn range(&self) -> Range<usize> {
        self.first..self.first + self.count
    }
}

/// How two materials behave when bodies made of them touch.
///
/// Materials are plain ids stored in [`Body::material`]. The pair is symmetric:
/// `(a, b)` and `(b, a)` share one entry. See [`World::set_material_pair`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Material {
    /// Bounciness of the contact (0 = none, 1 = full).
    pub elasticity: f32,
    /// Friction of the contact.
    pub friction: f32,
}

/// Orders the two material ids so `(a, b)` and `(b, a)` map to the same key.
#[inline]
fn pair_key(a: usize, b: usize) -> (usize, usize) {
    (a.min(b), a.max(b))
}

/// Shifts an index that points past a drained range of [`World::points`].
#[inline]
fn shift_after(range: &Range<usize>, count: usize, index: &mut usize) {
    if *index >= range.end {
        *index -= count;
    }
}

/// A point of one body found inside another body, with the data needed to push it out.
#[derive(Clone, Copy, Debug, Default)]
pub struct Contact {
    /// Index of the penetrating point in [`World::points`].
    pub point: usize,
    /// Index of the first point of the closest edge in [`World::points`].
    pub edge_a: usize,
    /// Index of the second point of the closest edge in [`World::points`].
    pub edge_b: usize,
    /// Position of the closest spot along the edge, from 0 (at [`Contact::edge_a`]) to 1 (at [`Contact::edge_b`]).
    pub edge_t: f32,
    /// Outward unit normal of the closest edge.
    pub normal: Vec2,
    /// Distance from the point to the closest edge.
    pub depth: f32,
    /// Bounciness of this contact, taken from the material pair of the two bodies.
    pub elasticity: f32,
    /// Friction of this contact, taken from the material pair of the two bodies.
    pub friction: f32,
}

/// Axis-aligned bounding box.
#[derive(Clone, Copy, Debug, Default)]
pub struct Aabb {
    /// Bottom-left corner.
    pub min: Vec2,
    /// Top-right corner.
    pub max: Vec2,
}

impl Aabb {
    /// Returns the box enclosing the points, or `None` if there are none.
    pub fn from_points(points: &[PointMass]) -> Option<Self> {
        let (first, rest) = points.split_first()?;
        let start = Self {
            min: first.position,
            max: first.position,
        };

        Some(rest.iter().fold(start, |bounds, point| Self {
            min: bounds.min.min(point.position),
            max: bounds.max.max(point.position),
        }))
    }

    /// Returns `true` if the two boxes overlap (touching counts).
    #[inline]
    pub fn overlaps(&self, other: &Self) -> bool {
        self.min.cmple(other.max).all() && other.min.cmple(self.max).all()
    }

    /// Returns `true` if the point lies inside the box (edges included).
    #[inline]
    pub fn contains(&self, point: Vec2) -> bool {
        point.cmpge(self.min).all() && point.cmple(self.max).all()
    }

    #[inline]
    pub fn center(&self) -> Vec2 {
        (self.min + self.max) * 0.5
    }
}

/// A soft body: a closed ring of consecutive points in [`World::points`] plus its derived state.
#[derive(Clone, Debug, Default)]
pub struct Body {
    /// Index of the body's first point in [`World::points`].
    pub first: usize,
    /// Number of points in the body.
    pub count: usize,
    /// Initial shape, centered on the origin.
    pub rest: Vec<Vec2>,
    /// Current center (mean of the point positions).
    pub center: Vec2,
    /// Current rotation relative to [`Body::rest`], in radians.
    pub angle: f32,
    /// Shape-matching target positions, one per point.
    pub target: Vec<Vec2>,
    /// Gas pressure; `0.0` disables inflation.
    pub gas: f32,
    /// Current polygon area.
    pub area: f32,
    /// Pressure force per point, recomputed each step.
    pub push: Vec<Vec2>,
    /// Bounding box ([`Aabb`]) of the body's points.
    pub aabb: Aabb,
    /// Bodies in the same non-zero group do not collide, unless
    /// [`World::set_group_collision`] says otherwise for that pair of groups.
    pub group: usize,
    /// Material id, used to look up the [`Material`] against other bodies. Default: 0
    pub material: usize,
    /// Tangential force driving the body's spin; `0.0` means no torque.
    pub torque: f32,
    /// Spin speed at which torque fades out; `0.0` means no limit.
    pub max_spin: f32,
    /// Stiffness of this body's edge springs. Default: 100.0
    pub spring_k: f32,
    /// Damping of this body's edge springs. Default: 15.0
    pub spring_damping: f32,
    /// Turns shape matching on or off for this body.
    pub shape_matching_enabled: bool,
    /// Stiffness of this body's shape-matching springs.
    pub shape_matching_k: f32,
    /// Damping of this body's shape-matching springs.
    pub shape_matching_damping: f32,
}

impl Body {
    /// The body's range of indices in [`World::points`].
    #[inline]
    pub fn range(&self) -> Range<usize> {
        self.first..self.first + self.count
    }

    /// Returns `true` if the body is static (checks the mass of its first point).
    #[inline]
    pub fn is_static(&self, points: &[PointMass]) -> bool {
        points[self.first].is_static()
    }
}

/// A spring tying a chassis point to a body's center.
#[derive(Clone, Copy, Debug, Default)]
pub struct BodyJoint {
    /// Chassis point in [`World::points`]
    pub point: usize,
    /// Attached body in [`World::bodies`].
    pub body: BodyId,
    /// Spring stiffness.
    pub k: f32,
    /// Spring damping.
    pub damping: f32,
}

/// Simulation parameters and settings
#[derive(Clone, Copy, Debug)]
pub struct Settings {
    /// Velocity lost per 1/60 s of simulated time, independent of step size. Default: 0.004
    pub air_drag: f32,
    /// Whether body-vs-body collisions are enabled. Default: `true`.
    pub body_collisions: bool,
    /// Whether collisions with [`World::bounds`] are enabled. Default: `true`.
    pub world_bound_collisions: bool,
    /// Default world material
    pub default_material: Material,
    /// Fixed physics step in seconds. Default: `1/60`.
    pub time_step: f32,
    /// Substeps per [`Settings::time_step`]; raise it if springs jitter. Default: `4`.
    pub iterations: usize,
    /// Frames longer than this (seconds) are treated as this long. Default: `0.1`.
    pub max_frame_time: f32,
    /// Upper bound on physics steps per frame. Default: `32`.
    pub max_steps_per_frame: usize,
    /// Global gravity. Default: `{x: 0, y: -9.8}`
    pub gravity: Vec2,
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            air_drag: 0.004,
            body_collisions: true,
            world_bound_collisions: true,
            default_material: Material {
                elasticity: 0.5,
                friction: 0.5,
            },
            time_step: 1.0 / 60.0,
            iterations: 4,
            max_frame_time: 0.1,
            max_steps_per_frame: 32,
            gravity: vec2(0.0, -9.8),
        }
    }
}

/// The simulation world: points, springs, bodies, contacts, joints and settings.
#[derive(Clone, Debug)]
pub struct World {
    /// All [`PointMass`] values; each [`Body`] owns a consecutive range of them.
    pub points: Vec<PointMass>,
    /// [`Spring`]s between points.
    pub springs: Vec<Spring>,
    /// [`Body`] values, addressed by [`BodyId`].
    pub bodies: DenseSlotMap<BodyId, Body>,
    /// [`Rope`] values, addressed by [`RopeId`].
    pub ropes: DenseSlotMap<RopeId, Rope>,
    /// [`Contact`] values.
    pub contacts: Vec<Contact>,
    /// [`BodyJoint`]s between chassis points and bodies.
    pub joints: Vec<BodyJoint>,
    /// Box that keeps the points inside the world, including the floor, the walls and the ceiling.
    /// Default: [`World::DEFAULT_BOUNDS`]
    pub bounds: Aabb,
    /// Material of [`World::bounds`]. Default: [`World::DEFAULT_BOUNDS_MATERIAL`]
    pub bounds_material: Material,
    /// Per-material-pair contact data, keyed by the sorted material ids.
    pub material_pairs: HashMap<(usize, usize), Material>,
    /// Explicit collision rules per group pair, keyed by the sorted group ids.
    /// A pair that is not in the map follows the default rule (same non-zero group: no collision).
    pub group_collisions: HashMap<(usize, usize), bool>,
    /// The point currently held by the mouse or touch.
    pub grab: Grab,
    /// Simulation parameters and settings
    pub settings: Settings,
    /// Frame time not yet consumed by steps.
    accumulator: f32,
}

impl Default for World {
    fn default() -> Self {
        Self {
            points: Vec::new(),
            springs: Vec::new(),
            bodies: DenseSlotMap::with_key(),
            ropes: DenseSlotMap::with_key(),
            contacts: Vec::new(),
            joints: Vec::new(),
            bounds: Self::DEFAULT_BOUNDS,
            bounds_material: Self::DEFAULT_BOUNDS_MATERIAL,
            material_pairs: HashMap::new(),
            group_collisions: HashMap::new(),
            grab: Grab::default(),
            settings: Settings::default(),
            accumulator: 0.0,
        }
    }
}

impl World {
    /// Default [`World::bounds`] Default: `min(0,0) max(16, 9)`
    pub const DEFAULT_BOUNDS: Aabb = Aabb {
        min: vec2(0.0, 0.0),
        max: vec2(16.0, 9.0),
    };

    /// Default [`World::bounds_material`]: a little bouncy and moderately rough.
    pub const DEFAULT_BOUNDS_MATERIAL: Material = Material {
        elasticity: 0.2,
        friction: 0.5,
    };

    /// Adds a single [`PointMass`] and returns its index in [`World::points`].
    pub fn add_point(&mut self, position: Vec2, velocity: Vec2, mass: f32) -> usize {
        let index = self.points.len();
        self.points.push(PointMass {
            position,
            velocity,
            force: Vec2::ZERO,
            mass,
        });
        index
    }

    /// Adds a closed ring of points, ordered counter-clockwise, and returns its key in [`World::bodies`].
    /// `mass == 0.0` makes the body static.
    pub fn add_body(&mut self, shape: &[Vec2], origin: Vec2, mass: f32) -> BodyId {
        // An empty shape would divide by zero (NaN centroid) and break [`PointMass::is_static`], so fail early.
        assert!(
            !shape.is_empty(),
            "Bir gövde en az bir noktaya sahip olmalı"
        );

        // Number of points, used both in the loops and in [`Body::count`].
        let count = shape.len();

        // Mean of the vertices, i.e. the shape's center; [`Body::rest`] is centered on it.
        let centroid = shape.iter().copied().sum::<Vec2>() / count as f32;

        // The body's points are consecutive in [`World::points`], so the first index plus `count` is enough.
        let first = self.points.len();

        // Rest shape ([`Body::rest`]) is stored relative to the center; [`derive_frame`] compares it to the current points.
        let rest: Vec<Vec2> = shape.iter().map(|&point| point - centroid).collect();

        // One [`PointMass`] per vertex at `origin + vertex`, added with [`World::add_point`].
        for &point in shape {
            self.add_point(origin + point, Vec2::ZERO, mass);
        }

        // The body is inserted before its springs, because every [`Spring`] stores the key of its owner.
        let key = self.bodies.insert(Body {
            first,
            count,
            rest,
            // [`Body::target`] and [`Body::push`] are preallocated to `count` so per-step fills never allocate.
            target: vec![Vec2::ZERO; count],
            push: vec![Vec2::ZERO; count],
            // [`Body::gas`] pressure: `0.0` disables inflation.
            spring_k: 100.0,
            spring_damping: 15.0,
            shape_matching_enabled: true,
            shape_matching_k: 400.,
            shape_matching_damping: 15.0,
            gas: 40.0,
            // The remaining fields stay at their defaults until the first [`World::step`].
            ..Body::default()
        });

        // Connect neighbors with springs via [`World::add_spring`]; `(i + 1) % count` closes the ring.
        for i in 0..count {
            self.add_spring(key, first + i, first + (i + 1) % count);
        }

        key
    }

    /// Adds a [`Spring`] owned by `body` between two existing [`World::points`], resting at their
    /// current distance. Its stiffness and damping come from [`Body::spring_k`] and [`Body::spring_damping`].
    pub fn add_spring(&mut self, body: BodyId, a: usize, b: usize) {
        let rest = self.points[a].position.distance(self.points[b].position);
        self.springs.push(Spring { a, b, rest, body });
    }

    /// Adds a rope with one node at each position in `nodes` (two or more), returning its
    /// key in [`World::ropes`]. Each segment rests at the initial distance between its nodes.
    pub fn add_rope(&mut self, nodes: &[Vec2], mass: f32) -> RopeId {
        assert!(nodes.len() >= 2, "Bir ip en az iki noktaya sahip olmalı");

        let first = self.points.len();
        for &position in nodes {
            self.add_point(position, Vec2::ZERO, mass);
        }

        let rest = nodes
            .windows(2)
            .map(|pair| pair[0].distance(pair[1]))
            .collect();

        self.ropes.insert(Rope {
            first,
            count: nodes.len(),
            rest,
            stiffness: 1.0,
            iterations: 4,
            group: 0,
            material: 0,
            anchors: Vec::new(),
            aabb: Aabb::default(),
        })
    }

    /// Convenience wrapper for [`World::add_rope`]: a straight rope with `segments` segments.
    pub fn add_straight_rope(
        &mut self,
        start: Vec2,
        end: Vec2,
        segments: usize,
        mass: f32,
    ) -> RopeId {
        assert!(segments >= 1, "Bir ip en az bir segmente sahip olmalı");

        let nodes: Vec<Vec2> = (0..=segments)
            .map(|i| start.lerp(end, i as f32 / segments as f32))
            .collect();
        self.add_rope(&nodes, mass)
    }

    /// Ties rope node `node` (an offset from [`Rope::first`]) to `target`, any point in
    /// [`World::points`]. Both ends are moved by the constraint according to their masses,
    /// so tying a rope to a body pulls on that body too. Returns `false` if either index is invalid.
    pub fn anchor_rope(&mut self, rope: RopeId, node: usize, target: usize) -> bool {
        let Some(current) = self.ropes.get(rope) else {
            return false;
        };
        if node >= current.count || target >= self.points.len() {
            return false;
        }

        self.ropes[rope].anchors.push(RopeAnchor { node, target });
        true
    }

    /// Sets the stiffness and damping of the edge springs of every body in [`World::bodies`].
    pub fn set_all_springs(&mut self, k: f32, damping: f32) {
        for body in self.bodies.values_mut() {
            body.spring_k = k;
            body.spring_damping = damping;
        }
    }

    /// Sets how bodies of materials `a` and `b` behave when they touch.
    /// The order of `a` and `b` does not matter; `(a, b)` and `(b, a)` are the same pair.
    pub fn set_material_pair(&mut self, a: usize, b: usize, pair: Material) {
        self.material_pairs.insert(pair_key(a, b), pair);
    }

    /// Returns the pair data for materials `a` and `b`. If no pair was set, falls back to
    /// [`Settings::default_material`].
    pub fn material_pair(&self, a: usize, b: usize) -> Material {
        self.material_pairs
            .get(&pair_key(a, b))
            .copied()
            .unwrap_or(self.settings.default_material)
    }

    /// Sets whether bodies (and ropes) of groups `a` and `b` collide, overriding the default rule.
    /// The order of `a` and `b` does not matter; `(a, b)` and `(b, a)` are the same pair.
    ///
    /// Use it to let a body ignore some groups but not others, e.g. a chassis (group 1) that does
    /// not collide with two tyres in groups 2 and 3, while the tyres still collide with each other.
    /// `a == b` is allowed too: `set_group_collision(3, 3, true)` makes group 3 collide with itself.
    pub fn set_group_collision(&mut self, a: usize, b: usize, collide: bool) {
        self.group_collisions.insert(pair_key(a, b), collide);
    }

    /// Returns `true` if bodies of groups `a` and `b` collide: the rule set with
    /// [`World::set_group_collision`] if there is one, otherwise "same non-zero group does not collide".
    pub fn groups_collide(&self, a: usize, b: usize) -> bool {
        match self.group_collisions.get(&pair_key(a, b)) {
            Some(&collide) => collide,
            None => a == 0 || a != b,
        }
    }

    /// Removes the body with its points and springs, and fixes every point index that pointed past them.
    /// Returns `false` if `key` was already removed.
    ///
    /// Call it between steps, never in the middle of [`World::step`].
    pub fn remove_body(&mut self, key: BodyId) -> bool {
        let Some(removed) = self.bodies.remove(key) else {
            return false;
        };
        let range = removed.range();
        let count = removed.count;

        self.points.drain(range.clone());

        // Only the removed body's springs touch its points, so the rest just shift.
        self.springs.retain(|spring| spring.body != key);
        for spring in &mut self.springs {
            if spring.a >= range.end {
                spring.a -= count;
            }
            if spring.b >= range.end {
                spring.b -= count;
            }
        }

        for body in self.bodies.values_mut() {
            if body.first >= range.end {
                body.first -= count;
            }
        }

        // Drop joints attached to the removed body or anchored on one of its points.
        self.joints
            .retain(|joint| joint.body != key && !range.contains(&joint.point));
        for joint in &mut self.joints {
            if joint.point >= range.end {
                joint.point -= count;
            }
        }

        // A rope tied to a removed body point loses that anchor; its own nodes stay valid.
        for rope in self.ropes.values_mut() {
            shift_after(&range, count, &mut rope.first);
            rope.anchors
                .retain(|anchor| !range.contains(&anchor.target));
            for anchor in &mut rope.anchors {
                shift_after(&range, count, &mut anchor.target);
            }
        }

        if self.grab.active {
            if range.contains(&self.grab.point) {
                self.grab.active = false;
            } else if self.grab.point >= range.end {
                self.grab.point -= count;
            }
        }

        // Contacts hold point indices; they are rebuilt on the next step anyway.
        self.contacts.clear();

        true
    }

    /// Removes the rope with its nodes, and fixes every point index that pointed past them.
    /// Anchors tied to the removed nodes are dropped. Returns `false` if `key` was already removed.
    ///
    /// Call it between steps, never in the middle of [`World::step`].
    pub fn remove_rope(&mut self, key: RopeId) -> bool {
        let Some(removed) = self.ropes.remove(key) else {
            return false;
        };
        let range = removed.first..removed.first + removed.count;
        let count = removed.count;

        self.points.drain(range.clone());

        self.springs
            .retain(|spring| !range.contains(&spring.a) && !range.contains(&spring.b));
        for spring in &mut self.springs {
            shift_after(&range, count, &mut spring.a);
            shift_after(&range, count, &mut spring.b);
        }

        for body in self.bodies.values_mut() {
            shift_after(&range, count, &mut body.first);
        }

        self.joints.retain(|joint| !range.contains(&joint.point));
        for joint in &mut self.joints {
            shift_after(&range, count, &mut joint.point);
        }

        for rope in self.ropes.values_mut() {
            shift_after(&range, count, &mut rope.first);
            rope.anchors
                .retain(|anchor| !range.contains(&anchor.target));
            for anchor in &mut rope.anchors {
                shift_after(&range, count, &mut anchor.target);
            }
        }

        if self.grab.active {
            if range.contains(&self.grab.point) {
                self.grab.active = false;
            } else {
                shift_after(&range, count, &mut self.grab.point);
            }
        }

        self.contacts.clear();
        true
    }

    /// Removes everything from the world and resets [`World::settings`], [`World::bounds`] and
    /// [`World::bounds_material`] to their defaults.
    pub fn clear(&mut self) {
        self.points.clear();
        self.springs.clear();
        self.bodies.clear();
        self.ropes.clear();
        self.contacts.clear();
        self.joints.clear();
        self.bounds = Self::DEFAULT_BOUNDS;
        self.bounds_material = Self::DEFAULT_BOUNDS_MATERIAL;
        self.material_pairs.clear();
        self.group_collisions.clear();
        self.grab = Grab::default();
        self.settings = Settings::default();
        self.accumulator = 0.0;
    }

    /// Returns the body's points from [`World::points`]. Since this takes `&self`, the returned slice's lifetime
    /// is tied to `self` automatically; no explicit lifetime is needed.
    pub fn body_points(&self, body: &Body) -> &[PointMass] {
        &self.points[body.range()]
    }

    /// Advances the world by `frame_time` seconds, whatever the display refresh rate is.
    pub fn step(&mut self, frame_time: f32) {
        let settings = self.settings;

        // [`Settings::iterations`] only makes the step finer; the simulated time stays the same.
        let sub_dt = settings.time_step / settings.iterations.max(1) as f32;

        self.accumulator += frame_time.min(settings.max_frame_time);

        let mut steps = 0;
        while self.accumulator >= sub_dt && steps < settings.max_steps_per_frame {
            self.fixed_step(sub_dt);
            self.accumulator -= sub_dt;
            steps += 1;
        }

        // The cap was hit: drop the leftover time instead of carrying a debt.
        if self.accumulator >= sub_dt {
            self.accumulator = 0.0;
        }
    }

    /// Resets each point's force to gravity times its mass.
    fn apply_gravity(&mut self) {
        for point in &mut self.points {
            point.force = self.settings.gravity * point.mass;
        }
    }

    /// Adds each spring's force to its two end points (equal and opposite).
    /// Stiffness and damping are read from the spring's owning [`Body`].
    fn apply_springs(&mut self) {
        for spring in &self.springs {
            if self.points[spring.a].is_static() && self.points[spring.b].is_static() {
                continue;
            }

            let Some(body) = self.bodies.get(spring.body) else {
                continue;
            };

            let force = spring_force(
                self.points[spring.a],
                self.points[spring.b],
                spring.rest,
                body.spring_k,
                body.spring_damping,
            );

            self.points[spring.a].force += force;
            self.points[spring.b].force -= force;
        }
    }

    /// Projects each rope's segment and anchor constraints onto the current positions.
    ///
    /// This is position-based dynamics: after [`integrate`] has predicted the new positions,
    /// corrections are applied directly to them, split by inverse mass. The position change is
    /// then added to velocity (`Δp / dt`) so the solver's work is not lost on the next step.
    fn solve_ropes(&mut self, dt: f32) {
        for rope in self.ropes.values_mut() {
            let mut touched: Vec<usize> = Vec::with_capacity(rope.count + rope.anchors.len());
            touched.extend(rope.range());
            touched.extend(rope.anchors.iter().map(|anchor| anchor.target));
            touched.sort_unstable();
            touched.dedup();

            let before: Vec<Vec2> = touched.iter().map(|&i| self.points[i].position).collect();
            let stiffness = rope.stiffness.clamp(0.0, 1.0);
            let iterations = rope.iterations.max(1);

            for _ in 0..iterations {
                for i in 0..rope.rest.len() {
                    project_constraint(
                        &mut self.points,
                        rope.first + i,
                        rope.first + i + 1,
                        rope.rest[i],
                        stiffness,
                        true, // a rope segment goes slack when compressed
                    );
                }
                for anchor in &rope.anchors {
                    project_constraint(
                        &mut self.points,
                        rope.first + anchor.node,
                        anchor.target,
                        0.0,
                        stiffness,
                        false, // an anchor is always active
                    );
                }
            }

            for (&index, &old) in touched.iter().zip(&before) {
                let point = &mut self.points[index];
                if !point.is_static() {
                    point.velocity += (point.position - old) / dt;
                }
            }
        }
    }

    /// Runs one physics step with a fixed `dt`; called by [`World::step`].
    //
    /// Small steps keep stiff [`Spring`]s stable
    pub fn fixed_step(&mut self, dt: f32) {
        let settings = self.settings;

        self.apply_gravity();
        self.apply_springs();

        // [`World::bodies`] and [`World::points`] are separate fields, so they can be borrowed at the same time.
        for body in self.bodies.values_mut() {
            let points = &mut self.points[body.range()];

            derive_frame(body, points);
            if body.shape_matching_enabled {
                apply_shape_matching(body, points);
            }
            if body.gas > 0.0 && !points[0].is_static() {
                apply_pressure(body, points);
            }
            if body.torque != 0.0 {
                apply_torque(body, points);
            }
        }

        for joint in &self.joints {
            let Some(body) = self.bodies.get(joint.body) else {
                continue;
            };
            apply_joint(&mut self.points, body, joint);
        }

        apply_grab_spring(self.grab, &mut self.points);
        integrate(&mut self.points, dt);
        apply_air_drag(&mut self.points, settings.air_drag, dt);
        self.solve_ropes(dt);

        if settings.body_collisions {
            self.collide_bodies();
        }

        if settings.world_bound_collisions {
            collide_bounds(&mut self.points, self.bounds, self.bounds_material, dt);
        }
    }

    /// Updates the body and rope AABBs and refills [`World::contacts`].
    /// [`World::contacts`] is cleared on every call, but its capacity is kept.
    fn find_contacts(&mut self) {
        for body in self.bodies.values_mut() {
            if let Some(bounds) = Aabb::from_points(&self.points[body.range()]) {
                body.aabb = bounds;
            }
        }
        for rope in self.ropes.values_mut() {
            if let Some(bounds) = Aabb::from_points(&self.points[rope.range()]) {
                rope.aabb = bounds;
            }
        }

        self.contacts.clear();

        for (a_key, a) in self.bodies.iter() {
            let a_static = a.is_static(&self.points);

            for (b_key, b) in self.bodies.iter() {
                if a_key == b_key || !a.aabb.overlaps(&b.aabb) {
                    continue;
                }
                if !self.groups_collide(a.group, b.group) {
                    continue;
                }
                if a_static && b.is_static(&self.points) {
                    continue;
                }

                // One [`World::material_pair`] lookup per body pair; every [`Contact`] between them shares the result.
                let pair = self.material_pair(a.material, b.material);

                let ring = &self.points[b.range()];

                for (offset, point) in self.points[a.range()].iter().enumerate() {
                    let position = point.position;
                    if !b.aabb.contains(position) || !point_in_polygon(position, ring) {
                        continue;
                    }

                    if let Some(mut contact) = closest_edge(position, ring, b.first) {
                        contact.point = a.first + offset;
                        contact.elasticity = pair.elasticity;
                        contact.friction = pair.friction;
                        self.contacts.push(contact);
                    }
                }
            }
        }

        // Rope nodes use the same contact path as body points: they are pushed out of
        // any body they penetrate, and the body's ring receives the opposite impulse.
        for rope in self.ropes.values() {
            for body in self.bodies.values() {
                if !rope.aabb.overlaps(&body.aabb) {
                    continue;
                }
                if !self.groups_collide(rope.group, body.group) {
                    continue;
                }

                let pair = self.material_pair(rope.material, body.material);
                let ring = &self.points[body.range()];

                for offset in 0..rope.count {
                    let index = rope.first + offset;
                    let position = self.points[index].position;
                    if !body.aabb.contains(position) || !point_in_polygon(position, ring) {
                        continue;
                    }

                    if let Some(mut contact) = closest_edge(position, ring, body.first) {
                        contact.point = index;
                        contact.elasticity = pair.elasticity;
                        contact.friction = pair.friction;
                        self.contacts.push(contact);
                    }
                }
            }
        }
    }

    /// Calls [`World::find_contacts`] and resolves each [`Contact`].
    fn collide_bodies(&mut self) {
        self.find_contacts();

        for &contact in &self.contacts {
            resolve_contact(&mut self.points, contact);
        }
    }
}

/// Returns the force on `a`.
///
/// The force on `b` is its negative.
pub fn spring_force(a: PointMass, b: PointMass, rest: f32, k: f32, damping: f32) -> Vec2 {
    let delta = a.position - b.position;
    let distance = delta.length();
    if distance < EPSILON {
        return Vec2::ZERO;
    }

    let direction = delta / distance;
    let stretch = rest - distance;
    let closing_speed = (a.velocity - b.velocity).dot(direction);
    direction * (k * stretch - damping * closing_speed)
}

/// Moves two points so their distance becomes `rest`, splitting the correction by inverse mass.
///
/// With `slack` the constraint only applies while the points are farther apart than `rest`
/// (a rope segment); otherwise it applies at any distance (an anchor, where `rest == 0`).
/// Static points (`inverse_mass == 0`) do not move, but still resist the other end.
fn project_constraint(
    points: &mut [PointMass],
    a: usize,
    b: usize,
    rest: f32,
    stiffness: f32,
    slack: bool,
) {
    if a == b {
        return;
    }

    let inv_a = points[a].inverse_mass();
    let inv_b = points[b].inverse_mass();
    let inv_sum = inv_a + inv_b;
    if inv_sum <= 0.0 {
        return;
    }

    let delta = points[b].position - points[a].position;
    let distance = delta.length();
    if distance < EPSILON || (slack && distance <= rest) {
        return;
    }

    let correction = delta * ((distance - rest) / distance * stiffness.clamp(0.0, 1.0) / inv_sum);
    points[a].position += correction * inv_a;
    points[b].position -= correction * inv_b;
}

/// Computes [`Body::center`] and [`Body::angle`] from the body's points and fills [`Body::target`].
fn derive_frame(body: &mut Body, points: &[PointMass]) {
    if points.is_empty() {
        return;
    }

    let center = points.iter().map(|point| point.position).sum::<Vec2>() / points.len() as f32;

    let (sin_sum, cos_sum) = points.iter().zip(&body.rest).fold(
        (0.0_f32, 0.0_f32),
        |(sin_sum, cos_sum), (point, rest)| {
            let current = point.position - center;
            (
                sin_sum + rest.perp_dot(current),
                cos_sum + rest.dot(current),
            )
        },
    );

    body.center = center;
    body.angle = sin_sum.atan2(cos_sum);

    // Compute the rotation once instead of calling sin/cos for every [`PointMass`].
    let rotation = Vec2::from_angle(body.angle);
    for (target, rest) in body.target.iter_mut().zip(&body.rest) {
        *target = center + rotation.rotate(*rest);
    }
}

/// Pulls each [`PointMass`] toward its shape-matching target ([`Body::target`]) with a damped [`Spring`].
fn apply_shape_matching(body: &Body, points: &mut [PointMass]) {
    let mean_velocity = mean_velocity(points);

    for (point, &position) in points.iter_mut().zip(&body.target) {
        let target = PointMass {
            position,
            velocity: mean_velocity,
            ..PointMass::default()
        };
        point.force += spring_force(
            *point,
            target,
            0.0,
            body.shape_matching_k,
            body.shape_matching_damping,
        );
    }
}

/// Iterates over each edge of the ring of [`PointMass`] values as a `(start, end)` pair.
/// The last edge wraps around to the start.
fn edges(ring: &[PointMass]) -> impl Iterator<Item = (&PointMass, &PointMass)> {
    ring.iter().zip(ring.iter().cycle().skip(1))
}

/// Signed area of the polygon (shoelace formula); positive for counter-clockwise order.
pub fn polygon_area(points: &[PointMass]) -> f32 {
    if points.len() < 3 {
        return 0.0;
    }

    let sum: f32 = edges(points)
        .map(|(a, b)| a.position.perp_dot(b.position))
        .sum();

    sum * 0.5
}

/// Adds outward gas pressure forces ([`Body::gas`]) on the body's edges, split between each edge's end points.
fn apply_pressure(body: &mut Body, points: &mut [PointMass]) {
    body.area = polygon_area(points).abs().max(MIN_AREA);
    body.push.fill(Vec2::ZERO);

    let count = points.len();
    if count < 2 {
        return;
    }

    for i in 0..count {
        let j = (i + 1) % count;
        let edge = points[j].position - points[i].position;
        let edge_length = edge.length();

        if edge_length < EPSILON {
            continue;
        }

        // Outward-facing normal (assuming counter-clockwise order).
        let normal = vec2(edge.y, -edge.x) / edge_length;
        let force = normal * (body.gas * edge_length / body.area);
        body.push[i] += force * 0.5;
        body.push[j] += force * 0.5;
    }

    for (point, push) in points.iter_mut().zip(&body.push) {
        point.force += *push;
    }
}

/// Stiffness of the spring that pulls the grabbed point toward the cursor.
const GRAB_STIFFNESS: f32 = 400.0;
/// Damping of the grab spring.
const GRAB_DAMPING: f32 = 20.0;

/// State ([`World::grab`]) of the point currently held by the mouse (or touch).
///
/// # Examples
///
/// Macroquad example (needs `macroquad` in the calling crate)
///
/// ```ignore
/// use jelly_physics::{World, nearest_point};
/// use macroquad::prelude::*;
///
/// fn grab(world: &mut World, mouse: Vec2) {
///     if is_mouse_button_pressed(MouseButton::Left) {
///         if let Some(index) = nearest_point(&world.points, mouse, 0.5) {
///             world.grab.active = true;
///             world.grab.point = index;
///             world.grab.target = mouse;
///         }
///     }
///     if !is_mouse_button_down(MouseButton::Left) {
///         world.grab.active = false;
///     } else if world.grab.active {
///         world.grab.target = mouse;
///     }
/// }
/// ```
#[derive(Clone, Copy, Debug, Default)]
pub struct Grab {
    /// Whether a point is currently being held.
    pub active: bool,
    /// Index of the held point in [`World::points`].
    pub point: usize,
    /// World position the point is pulled toward (usually the cursor).
    pub target: Vec2,
}

/// Pulls the grabbed point toward [`Grab::target`] with a damped [`Spring`].
///
/// The [`Spring`] has zero rest length, so the point is dragged all the way to
/// the target. The result is added to the point's [`PointMass::force`], so [`apply_grab_spring`] must run
/// before [`integrate`] in the same step. Does nothing if no point is grabbed
/// or the stored index is out of range.
fn apply_grab_spring(grab: Grab, points: &mut [PointMass]) {
    // [`Grab::active`] is false: nothing is being held.
    if !grab.active {
        return;
    }

    // Guard against a stale index (e.g. [`World::clear`] was called while grabbing).
    let Some(&point) = points.get(grab.point) else {
        return;
    };

    // The cursor acts as an immovable anchor: zero [`PointMass::velocity`], default [`PointMass::mass`].
    let anchor = PointMass {
        position: grab.target,
        ..PointMass::default()
    };

    // Rest length `0.0`: the spring is relaxed only when the point sits on the target.
    points[grab.point].force += spring_force(point, anchor, 0.0, GRAB_STIFFNESS, GRAB_DAMPING);
}

/// Returns the index of the nearest [`World::points`] entry to `at` within `max_dist`, or `None` if none is close enough.
pub fn nearest_point(points: &[PointMass], at: Vec2, max_dist: f32) -> Option<usize> {
    points
        .iter()
        .enumerate()
        .map(|(index, point)| (index, point.position.distance(at)))
        .filter(|(_, distance)| *distance < max_dist)
        .min_by(|a, b| a.1.total_cmp(&b.1))
        .map(|(index, _)| index)
}

/// Returns `true` if `point` is inside the polygon formed by the `ring` of [`PointMass`] values (ray casting).
pub fn point_in_polygon(point: Vec2, ring: &[PointMass]) -> bool {
    if ring.len() < 3 {
        return false;
    }

    let mut inside = false;
    for (a, b) in edges(ring) {
        let (a, b) = (a.position, b.position);

        if (a.y > point.y) != (b.y > point.y) {
            let cross_x = a.x + (point.y - a.y) / (b.y - a.y) * (b.x - a.x);
            if point.x < cross_x {
                inside = !inside;
            }
        }
    }
    inside
}

/// Finds the ring edge closest to `point` and returns it as a [`Contact`] (with `point` left unset).
/// `first` is the index of the ring's first point in [`World::points`].
pub fn closest_edge(point: Vec2, ring: &[PointMass], first: usize) -> Option<Contact> {
    let mut closest: Option<Contact> = None;

    for (i, (a, b)) in edges(ring).enumerate() {
        let edge = b.position - a.position;
        let length_squared = edge.length_squared();

        if length_squared < EPSILON * EPSILON {
            continue;
        }

        let t = ((point - a.position).dot(edge) / length_squared).clamp(0.0, 1.0);
        let distance = point.distance(a.position + edge * t);

        if closest.is_none_or(|contact| distance < contact.depth) {
            closest = Some(Contact {
                edge_a: first + i,
                edge_b: first + (i + 1) % ring.len(),
                edge_t: t,
                normal: vec2(edge.y, -edge.x) / length_squared.sqrt(),
                depth: distance,
                ..Contact::default()
            });
        }
    }

    closest
}

/// Pushes the point out of the edge and applies the [`Contact`] bounce and friction impulse.
///
/// Three different [`PointMass`] values can't be borrowed mutably from the same slice at once,
/// so the points are copied, modified, and written back at the end.
fn resolve_contact(points: &mut [PointMass], contact: Contact) {
    let (elasticity, friction) = (contact.elasticity, contact.friction);

    let mut point = points[contact.point];
    let mut edge_a = points[contact.edge_a];
    let mut edge_b = points[contact.edge_b];

    let weight_a = 1.0 - contact.edge_t;
    let weight_b = contact.edge_t;
    let inv_point = point.inverse_mass();
    let edge_mass = edge_a.mass + edge_b.mass;
    let inv_edge = if edge_mass > 0.0 {
        1.0 / edge_mass
    } else {
        0.0
    };
    let inv_sum = inv_point + inv_edge;

    if inv_sum <= 0.0 {
        return;
    }

    point.position += contact.normal * (contact.depth * inv_point / inv_sum);
    let edge_move = contact.normal * (contact.depth * inv_edge / inv_sum);
    edge_a.position -= edge_move * weight_a;
    edge_b.position -= edge_move * weight_b;

    let relative_velocity =
        point.velocity - (edge_a.velocity * weight_a + edge_b.velocity * weight_b);
    let approach = relative_velocity.dot(contact.normal);

    if approach < 0.0 {
        let tangent = contact.normal.perp();
        let bounce = -(1.0 + elasticity) * approach / inv_sum;
        let rub = -relative_velocity.dot(tangent) * friction / inv_sum;
        let impulse = contact.normal * bounce + tangent * rub;

        point.velocity += impulse * inv_point;
        edge_a.velocity -= impulse * (inv_edge * weight_a);
        edge_b.velocity -= impulse * (inv_edge * weight_b);
    }

    points[contact.point] = point;
    points[contact.edge_a] = edge_a;
    points[contact.edge_b] = edge_b;
}

/// Returns the mean [`PointMass::velocity`] of the points.
pub fn mean_velocity(points: &[PointMass]) -> Vec2 {
    if points.is_empty() {
        return Vec2::ZERO;
    }

    points.iter().map(|point| point.velocity).sum::<Vec2>() / points.len() as f32
}

/// Builds an axis-aligned rectangle (4 vertices) centered at `center` with size `w` x `h`.
pub fn make_rectangle(center: Vec2, w: f32, h: f32) -> Vec<Vec2> {
    let hx = w * 0.5;
    let hy = h * 0.5;
    vec![
        center + vec2(-hx, -hy),
        center + vec2(hx, -hy),
        center + vec2(hx, hy),
        center + vec2(-hx, hy),
    ]
}

/// Builds a rectangle whose corners are beveled (cropped) at 45 degrees, i.e. an octagon,
/// centered at `center` with size `w` x `h`. The cut size scales with the shorter side.
pub fn make_rounded_rectangle(center: Vec2, w: f32, h: f32) -> Vec<Vec2> {
    let hx = w * 0.5;
    let hy = h * 0.5;
    let cut = (w.min(h) * 0.25).min(hx).min(hy).max(0.0);
    vec![
        center + vec2(-hx + cut, -hy),
        center + vec2(hx - cut, -hy),
        center + vec2(hx, -hy + cut),
        center + vec2(hx, hy - cut),
        center + vec2(hx - cut, hy),
        center + vec2(-hx + cut, hy),
        center + vec2(-hx, hy - cut),
        center + vec2(-hx, -hy + cut),
    ]
}

/// Builds a regular polygon approximating a circle centered at `center` with radius `r`.
/// `n` is clamped to at least 3 so the result is always a valid polygon.
pub fn make_regular_polygon(center: Vec2, r: f32, n: usize) -> Vec<Vec2> {
    let segments = n.max(3);
    (0..segments)
        .map(|i| {
            let angle = i as f32 / segments as f32 * std::f32::consts::TAU;
            center + Vec2::from_angle(angle) * r
        })
        .collect()
}

/// Springs the chassis point to [`Body::center`]. The reaction force is shared equally
/// among the body's points ([`Body::count`]). The body is only borrowed, not cloned.
fn apply_joint(points: &mut [PointMass], body: &Body, joint: &BodyJoint) {
    let center = PointMass {
        position: body.center,
        velocity: mean_velocity(&points[body.range()]),
        ..PointMass::default()
    };

    let force = spring_force(points[joint.point], center, 0.0, joint.k, joint.damping);
    points[joint.point].force += force;

    let share = force / body.count as f32;
    for point in &mut points[body.range()] {
        point.force -= share;
    }
}

/// Counter-clockwise unit vector perpendicular to the radius from the center,
/// or `None` if the radius is too short.
fn tangent_of(radius: Vec2) -> Option<Vec2> {
    let distance = radius.length();
    (distance > EPSILON).then(|| radius.perp() / distance)
}

/// Applies tangential force to every point to spin the body, fading out as it nears [`Body::max_spin`].
fn apply_torque(body: &Body, points: &mut [PointMass]) {
    if points.is_empty() {
        return;
    }

    let mean_velocity = mean_velocity(points);
    let spin = points
        .iter()
        .filter_map(|point| {
            let tangent = tangent_of(point.position - body.center)?;
            Some((point.velocity - mean_velocity).dot(tangent))
        })
        .sum::<f32>()
        / points.len() as f32;

    let direction = body.torque.signum();
    let strength = if body.max_spin > 0.0 {
        (1.0 - spin * direction / body.max_spin).clamp(0.0, 1.0)
    } else {
        1.0
    };

    for point in points {
        if let Some(tangent) = tangent_of(point.position - body.center) {
            point.force += tangent * (body.torque * strength);
        }
    }
}

#[cfg(test)]
mod tests;