rusting_engine 1.4.0

Vulkan 3D game engine with GPU-accelerated physics for massive physics-heavy scenes
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
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
//! CPU-side types shared with the hybrid GPU physics bridge.
//!
//! This module does not create Vulkan buffers. It defines stable body IDs,
//! programmable conditions, and the exact event format used for readback.
//!
//! # Latency
//!
//! GPU physics never blocks a frame. The renderer reads events and body
//! state only after the frame that produced them has finished on the GPU,
//! so they normally reach gameplay one to three rendered frames after the
//! fixed tick they describe; [`GpuPhysicsEvent::tick`] and
//! [`GpuStateMirror::tick`] record that tick. Gameplay that needs an answer
//! in the same tick (a jump check, a hit-scan) must use
//! [`SimulationClass::Cpu`](super::SimulationClass) bodies instead.

use std::collections::{BTreeMap, HashMap};
use std::hash::{Hash, Hasher};

use bevy_ecs::change_detection::DetectChanges;
use bevy_ecs::component::Component;
use bevy_ecs::entity::Entity;
use bevy_ecs::lifecycle::RemovedComponents;
use bevy_ecs::prelude::{
    Changed, Commands, IntoScheduleConfigs, Query, Ref, ResMut, Resource, World,
};
use bytemuck::{Pod, Zeroable};
use serde::{Deserialize, Serialize};

use super::{App, AppError, EventQueue, Plugin, ScheduleStage};
use crate::Transform;

/// Maximum number of simple instructions accepted for one condition.
///
/// A fixed limit prevents one object from creating an unexpectedly expensive
/// condition program. Custom compute code remains available for larger logic.
pub const MAX_GPU_CONDITION_INSTRUCTIONS: usize = 64;

/// Stable identity shared by ECS, GPU buffers, commands, and GPU events.
///
/// `slot` locates a table entry. `generation` changes whenever that slot is
/// reused, so a delayed event cannot accidentally target a newer body.
#[repr(C)]
#[derive(
    Component, Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Pod, Zeroable,
)]
pub struct PhysicsId {
    pub slot: u32,
    pub generation: u32,
}

#[derive(Clone, Copy, Debug)]
struct PhysicsSlot {
    generation: u32,
    entity: Option<Entity>,
}

/// Owns the stable mapping between ECS entities and GPU physics IDs.
#[derive(Resource, Clone, Debug, Default)]
pub struct PhysicsIdRegistry {
    slots: Vec<PhysicsSlot>,
    free_slots: Vec<u32>,
    entity_ids: HashMap<Entity, PhysicsId>,
}

impl PhysicsIdRegistry {
    /// Feeds slot generations, owners, and the free list, which decide the
    /// ids later bodies get.
    pub(crate) fn hash_state(&self, hasher: &mut super::StateHasher) {
        for slot in &self.slots {
            hasher.word(u64::from(slot.generation));
            hasher.word(slot.entity.map_or(u64::MAX, Entity::to_bits));
        }
        for slot in &self.free_slots {
            hasher.word(u64::from(*slot));
        }
    }

    /// Returns the existing ID or creates a new stable ID for an entity.
    pub fn assign(&mut self, entity: Entity) -> PhysicsId {
        if let Some(id) = self.entity_ids.get(&entity) {
            return *id;
        }

        let id = if let Some(slot) = self.free_slots.pop() {
            let entry = &mut self.slots[slot as usize];
            entry.entity = Some(entity);
            PhysicsId {
                slot,
                generation: entry.generation,
            }
        } else {
            let slot = self.slots.len() as u32;
            let generation = 1;
            self.slots.push(PhysicsSlot {
                generation,
                entity: Some(entity),
            });
            PhysicsId { slot, generation }
        };

        self.entity_ids.insert(entity, id);
        id
    }

    /// Releases an entity ID and invalidates all delayed events using it.
    pub fn release(&mut self, entity: Entity) -> Option<PhysicsId> {
        let old_id = self.entity_ids.remove(&entity)?;
        let entry = &mut self.slots[old_id.slot as usize];
        entry.entity = None;
        entry.generation = next_generation(entry.generation);
        self.free_slots.push(old_id.slot);
        Some(old_id)
    }

    /// Resolves an ID only when both its slot and generation still match.
    #[must_use]
    pub fn resolve(&self, id: PhysicsId) -> Option<Entity> {
        let entry = self.slots.get(id.slot as usize)?;
        (entry.generation == id.generation)
            .then_some(entry.entity)
            .flatten()
    }

    /// Returns the GPU physics ID currently assigned to an ECS entity.
    #[must_use]
    pub fn id_for(&self, entity: Entity) -> Option<PhysicsId> {
        self.entity_ids.get(&entity).copied()
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.entity_ids.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entity_ids.is_empty()
    }
}

fn next_generation(generation: u32) -> u32 {
    let next = generation.wrapping_add(1);
    if next == 0 {
        1
    } else {
        next
    }
}

/// Numeric name used by shaders when they emit a registered gameplay event.
#[repr(transparent)]
#[derive(
    Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Hash, Serialize,
)]
pub struct GpuEventId(pub u32);

/// Assigns compact IDs to event names used by Rust and custom shaders.
#[derive(Resource, Clone, Debug, Default)]
pub struct GpuEventRegistry {
    names: Vec<String>,
    ids: HashMap<String, GpuEventId>,
}

impl GpuEventRegistry {
    /// Registers a name once and returns the same ID on later calls.
    pub fn register(&mut self, name: impl Into<String>) -> GpuEventId {
        let name = name.into();
        if let Some(id) = self.ids.get(&name) {
            return *id;
        }
        // Zero means "no event" inside GPU buffers.
        let id = GpuEventId((self.names.len() as u32).saturating_add(1));
        self.names.push(name.clone());
        self.ids.insert(name, id);
        id
    }

    #[must_use]
    pub fn id(&self, name: &str) -> Option<GpuEventId> {
        self.ids.get(name).copied()
    }

    #[must_use]
    pub fn name(&self, id: GpuEventId) -> Option<&str> {
        let index = id.0.checked_sub(1)? as usize;
        self.names.get(index).map(String::as_str)
    }
}

/// Physics value that a built-in condition can read on the GPU.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
pub enum GpuStateField {
    PositionX,
    PositionY,
    PositionZ,
    VelocityX,
    VelocityY,
    VelocityZ,
    AngularVelocityX,
    AngularVelocityY,
    AngularVelocityZ,
    ScaleX,
    ScaleY,
    ScaleZ,
    Mass,
    GravityScale,
    Speed,
    Custom(u8),
}

impl GpuStateField {
    fn gpu_code(self) -> u32 {
        match self {
            Self::PositionX => 0,
            Self::PositionY => 1,
            Self::PositionZ => 2,
            Self::VelocityX => 3,
            Self::VelocityY => 4,
            Self::VelocityZ => 5,
            Self::AngularVelocityX => 6,
            Self::AngularVelocityY => 7,
            Self::AngularVelocityZ => 8,
            Self::ScaleX => 9,
            Self::ScaleY => 10,
            Self::ScaleZ => 11,
            Self::Mass => 12,
            Self::GravityScale => 13,
            Self::Speed => 14,
            Self::Custom(index) => 0x100 + u32::from(index),
        }
    }
}

/// Comparison used by one leaf in a GPU condition.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
pub enum GpuComparison {
    Less,
    LessOrEqual,
    Greater,
    GreaterOrEqual,
    Equal,
    NotEqual,
}

impl GpuComparison {
    fn gpu_code(self) -> u32 {
        match self {
            Self::Less => 0,
            Self::LessOrEqual => 1,
            Self::Greater => 2,
            Self::GreaterOrEqual => 3,
            Self::Equal => 4,
            Self::NotEqual => 5,
        }
    }
}

/// One node in a condition tree authored through normal Rust code.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
enum GpuConditionNode {
    Compare {
        field: GpuStateField,
        comparison: GpuComparison,
        value: f32,
    },
    Range {
        field: GpuStateField,
        minimum: f32,
        maximum: f32,
    },
    Colliding,
    Sleeping,
    TimerElapsed(f32),
    And(Box<Self>, Box<Self>),
    Or(Box<Self>, Box<Self>),
    Not(Box<Self>),
}

/// A condition that can be compiled into data evaluated by a compute shader.
///
/// This deliberately stays a Rust builder instead of introducing another
/// scripting language. Truly arbitrary logic can use the custom shader ABI.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct GpuCondition {
    node: GpuConditionNode,
}

impl GpuCondition {
    #[must_use]
    pub fn field(field: GpuStateField) -> GpuFieldCondition {
        GpuFieldCondition { field }
    }

    #[must_use]
    pub fn position_y() -> GpuFieldCondition {
        Self::field(GpuStateField::PositionY)
    }

    #[must_use]
    pub fn velocity_y() -> GpuFieldCondition {
        Self::field(GpuStateField::VelocityY)
    }

    #[must_use]
    pub fn custom(index: u8) -> GpuFieldCondition {
        Self::field(GpuStateField::Custom(index))
    }

    #[must_use]
    pub fn colliding() -> Self {
        Self {
            node: GpuConditionNode::Colliding,
        }
    }

    #[must_use]
    pub fn sleeping() -> Self {
        Self {
            node: GpuConditionNode::Sleeping,
        }
    }

    #[must_use]
    pub fn timer_elapsed(seconds: f32) -> Self {
        Self {
            node: GpuConditionNode::TimerElapsed(seconds.max(0.0)),
        }
    }

    #[must_use]
    pub fn and(self, other: Self) -> Self {
        Self {
            node: GpuConditionNode::And(
                Box::new(self.node),
                Box::new(other.node),
            ),
        }
    }

    #[must_use]
    pub fn or(self, other: Self) -> Self {
        Self {
            node: GpuConditionNode::Or(
                Box::new(self.node),
                Box::new(other.node),
            ),
        }
    }

    #[must_use]
    pub fn inverted(self) -> Self {
        Self {
            node: GpuConditionNode::Not(Box::new(self.node)),
        }
    }

    /// Converts the tree into postfix instructions consumed by the GPU.
    pub fn compile(
        &self,
    ) -> Result<Vec<GpuConditionInstruction>, ConditionError> {
        let mut instructions = Vec::new();
        compile_node(&self.node, &mut instructions)?;
        if instructions.len() > MAX_GPU_CONDITION_INSTRUCTIONS {
            return Err(ConditionError::TooManyInstructions {
                count: instructions.len(),
                maximum: MAX_GPU_CONDITION_INSTRUCTIONS,
            });
        }
        Ok(instructions)
    }
}

impl std::ops::Not for GpuCondition {
    type Output = Self;

    fn not(self) -> Self::Output {
        self.inverted()
    }
}

/// Starts a comparison against one GPU physics value.
#[derive(Clone, Copy, Debug)]
pub struct GpuFieldCondition {
    field: GpuStateField,
}

impl GpuFieldCondition {
    fn compare(self, comparison: GpuComparison, value: f32) -> GpuCondition {
        GpuCondition {
            node: GpuConditionNode::Compare {
                field: self.field,
                comparison,
                value,
            },
        }
    }

    #[must_use]
    pub fn less_than(self, value: f32) -> GpuCondition {
        self.compare(GpuComparison::Less, value)
    }

    #[must_use]
    pub fn less_or_equal(self, value: f32) -> GpuCondition {
        self.compare(GpuComparison::LessOrEqual, value)
    }

    #[must_use]
    pub fn greater_than(self, value: f32) -> GpuCondition {
        self.compare(GpuComparison::Greater, value)
    }

    #[must_use]
    pub fn greater_or_equal(self, value: f32) -> GpuCondition {
        self.compare(GpuComparison::GreaterOrEqual, value)
    }

    #[must_use]
    pub fn equal_to(self, value: f32) -> GpuCondition {
        self.compare(GpuComparison::Equal, value)
    }

    #[must_use]
    pub fn not_equal_to(self, value: f32) -> GpuCondition {
        self.compare(GpuComparison::NotEqual, value)
    }

    #[must_use]
    pub fn inside(self, minimum: f32, maximum: f32) -> GpuCondition {
        GpuCondition {
            node: GpuConditionNode::Range {
                field: self.field,
                minimum: minimum.min(maximum),
                maximum: minimum.max(maximum),
            },
        }
    }
}

/// Operation codes shared with the condition compute shader.
mod condition_opcode {
    pub const COMPARE: u32 = 1;
    pub const RANGE: u32 = 2;
    pub const COLLIDING: u32 = 3;
    pub const SLEEPING: u32 = 4;
    pub const TIMER_ELAPSED: u32 = 5;
    pub const AND: u32 = 16;
    pub const OR: u32 = 17;
    pub const NOT: u32 = 18;
}

/// Fixed-size instruction stored in a GPU condition buffer.
///
/// The four integer words describe the operation. The four float words hold
/// thresholds or future parameters. Keeping this at 32 bytes makes its GLSL
/// `std430` layout simple and predictable.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)]
pub struct GpuConditionInstruction {
    pub opcode: u32,
    pub operand: u32,
    pub flags: u32,
    pub reserved: u32,
    pub values: [f32; 4],
}

fn compile_node(
    node: &GpuConditionNode,
    output: &mut Vec<GpuConditionInstruction>,
) -> Result<(), ConditionError> {
    let instruction = match node {
        GpuConditionNode::Compare {
            field,
            comparison,
            value,
        } => GpuConditionInstruction {
            opcode: condition_opcode::COMPARE,
            operand: field.gpu_code(),
            flags: comparison.gpu_code(),
            values: [*value, 0.0, 0.0, 0.0],
            ..Default::default()
        },
        GpuConditionNode::Range {
            field,
            minimum,
            maximum,
        } => GpuConditionInstruction {
            opcode: condition_opcode::RANGE,
            operand: field.gpu_code(),
            values: [*minimum, *maximum, 0.0, 0.0],
            ..Default::default()
        },
        GpuConditionNode::Colliding => GpuConditionInstruction {
            opcode: condition_opcode::COLLIDING,
            ..Default::default()
        },
        GpuConditionNode::Sleeping => GpuConditionInstruction {
            opcode: condition_opcode::SLEEPING,
            ..Default::default()
        },
        GpuConditionNode::TimerElapsed(seconds) => GpuConditionInstruction {
            opcode: condition_opcode::TIMER_ELAPSED,
            values: [*seconds, 0.0, 0.0, 0.0],
            ..Default::default()
        },
        GpuConditionNode::And(left, right) => {
            compile_node(left, output)?;
            compile_node(right, output)?;
            GpuConditionInstruction {
                opcode: condition_opcode::AND,
                ..Default::default()
            }
        }
        GpuConditionNode::Or(left, right) => {
            compile_node(left, output)?;
            compile_node(right, output)?;
            GpuConditionInstruction {
                opcode: condition_opcode::OR,
                ..Default::default()
            }
        }
        GpuConditionNode::Not(inner) => {
            compile_node(inner, output)?;
            GpuConditionInstruction {
                opcode: condition_opcode::NOT,
                ..Default::default()
            }
        }
    };
    output.push(instruction);
    if output.len() > MAX_GPU_CONDITION_INSTRUCTIONS {
        return Err(ConditionError::TooManyInstructions {
            count: output.len(),
            maximum: MAX_GPU_CONDITION_INSTRUCTIONS,
        });
    }
    Ok(())
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConditionError {
    TooManyInstructions { count: usize, maximum: usize },
}

impl std::fmt::Display for ConditionError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::TooManyInstructions { count, maximum } => write!(
                formatter,
                "GPU condition has {count} instructions; maximum is {maximum}"
            ),
        }
    }
}

impl std::error::Error for ConditionError {}

/// Decides when a true/false condition produces an event.
#[repr(u32)]
#[derive(
    Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
)]
pub enum GpuEventMode {
    #[default]
    OnEnter = 0,
    OnExit = 1,
    WhileTrue = 2,
    Once = 3,
}

/// Selects the four floats copied into an event without another readback.
#[repr(u32)]
#[derive(
    Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
)]
pub enum GpuEventPayload {
    #[default]
    None = 0,
    Position = 1,
    Velocity = 2,
    AngularVelocity = 3,
    Contact = 4,
    Custom = 5,
}

/// One authored rule attached to one body or a prepared body group.
#[derive(
    Component, Clone, Debug, Default, Deserialize, PartialEq, Serialize,
)]
pub struct GpuPhysicsWatch {
    pub rules: Vec<GpuPhysicsRule>,
}

/// GPU rules assigned to reusable object classes.
///
/// One rule can target 10,000 objects without also changing unrelated GPU
/// bodies. Objects may belong to more than one class.
#[derive(Resource, Clone, Debug, Default, PartialEq)]
pub struct GpuPhysicsClassWatches {
    /// Rules stored under their authored class name.
    pub classes: BTreeMap<String, Vec<GpuPhysicsRule>>,
}

impl GpuPhysicsClassWatches {
    /// Adds one rule to a class without registering it twice.
    pub fn add(&mut self, class: impl Into<String>, rule: GpuPhysicsRule) {
        let class = class.into();
        let class = class.trim();
        if class.is_empty() {
            return;
        }
        let rules = self.classes.entry(class.to_owned()).or_default();
        if !rules.contains(&rule) {
            rules.push(rule);
        }
    }
}

/// Configures which event is emitted when a GPU condition changes.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct GpuPhysicsRule {
    pub event: String,
    pub condition: GpuCondition,
    pub mode: GpuEventMode,
    pub payload: GpuEventPayload,
    pub cooldown_seconds: f32,
}

impl GpuPhysicsRule {
    #[must_use]
    pub fn new(event: impl Into<String>, condition: GpuCondition) -> Self {
        Self {
            event: event.into(),
            condition,
            mode: GpuEventMode::OnEnter,
            payload: GpuEventPayload::None,
            cooldown_seconds: 0.0,
        }
    }

    #[must_use]
    pub fn mode(mut self, mode: GpuEventMode) -> Self {
        self.mode = mode;
        self
    }

    #[must_use]
    pub fn payload(mut self, payload: GpuEventPayload) -> Self {
        self.payload = payload;
        self
    }

    #[must_use]
    pub fn cooldown(mut self, seconds: f32) -> Self {
        self.cooldown_seconds = seconds.max(0.0);
        self
    }
}

/// Exact event bytes copied from a GPU readback buffer.
///
/// The tick is split into two words because 64-bit shader integers are not a
/// baseline feature on low-end Vulkan devices.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)]
pub struct RawGpuPhysicsEvent {
    pub body_slot: u32,
    pub body_generation: u32,
    pub event_id: u32,
    pub flags: u32,
    pub tick_low: u32,
    pub tick_high: u32,
    pub payload_kind: u32,
    pub reserved: u32,
    pub payload: [f32; 4],
}

impl RawGpuPhysicsEvent {
    #[must_use]
    pub fn physics_id(self) -> PhysicsId {
        PhysicsId {
            slot: self.body_slot,
            generation: self.body_generation,
        }
    }

    #[must_use]
    pub fn tick(self) -> u64 {
        u64::from(self.tick_low) | (u64::from(self.tick_high) << 32)
    }
}

/// One change CPU gameplay asks the GPU simulation to make to a body.
///
/// Spawning, despawning, solver changes, and watch-rule changes need no
/// command: edit the ECS components and the next extraction rebuilds the
/// GPU tables while keeping every surviving body's simulated state.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GpuBodyCommand {
    /// Moves the body; its velocity is kept.
    Teleport(Transform),
    SetVelocity {
        linear: [f32; 3],
        angular: [f32; 3],
    },
    /// Instant change of momentum, in newton-seconds. Dynamic bodies only.
    Impulse([f32; 3]),
    /// Force in newtons applied for one fixed tick. Dynamic bodies only.
    Force([f32; 3]),
    /// Replaces the four custom values that conditions and shaders read.
    SetCustomValues([f32; 4]),
    /// Reads the body's full state back once, as a [`GpuStateMirror`], even
    /// when its [`PhysicsSyncMode`] does not read state back.
    ReadState,
}

/// Commands waiting for the next render extraction, in submission order.
///
/// A command applies before the GPU simulates the tick after the one that
/// was completed when it was pushed: one pushed during fixed tick `n` (when
/// `FrameTime::fixed_tick` reads `n - 1`), or in `Update` right after tick
/// `n - 1`, applies before GPU tick `n`. That holds however many ticks a
/// frame batches. Commands apply in order per body; the renderer rejects
/// commands whose body generation is stale.
#[derive(Resource, Clone, Debug, Default, PartialEq)]
pub struct GpuPhysicsCommands {
    pub commands: Vec<(PhysicsId, GpuBodyCommand)>,
    /// GPU tick each command applies before, parallel to `commands`. The
    /// engine fills it after every fixed tick and at extraction; a command
    /// without an entry applies before the next GPU tick.
    pub apply_ticks: Vec<u64>,
    /// Reads every GPU body's full state back once after the next step.
    /// Meant for debugging, save states, and tests: it copies the whole
    /// simulation, so keep it off the per-frame gameplay path.
    pub read_all_states: bool,
    /// Discards the simulated GPU state and restarts every body from its
    /// authored ECS components, with rule edge and cooldown state cleared.
    /// This is Stop for a play session: the authored scene is the snapshot,
    /// so no state is read back. Commands in the same batch apply after the
    /// reset, which lets [`Self::restore`] resume a saved mid-play state.
    pub reset_to_authored: bool,
}

impl GpuPhysicsCommands {
    pub fn push(&mut self, body: PhysicsId, command: GpuBodyCommand) {
        self.commands.push((body, command));
    }

    /// Puts a body back into a state read earlier, for example one captured
    /// with [`Self::read_all_states`] when Play was paused.
    pub fn restore(&mut self, body: PhysicsId, state: &GpuStateMirror) {
        self.push(body, GpuBodyCommand::Teleport(state.transform));
        self.push(
            body,
            GpuBodyCommand::SetVelocity {
                linear: state.linear_velocity,
                angular: state.angular_velocity,
            },
        );
        if let Some(values) = state.custom_values {
            self.push(body, GpuBodyCommand::SetCustomValues(values));
        }
    }
}

/// Gives every command pushed since the last call the tick after the
/// current `FrameTime::fixed_tick`; see [`GpuPhysicsCommands`].
pub(super) fn stamp_gpu_commands(world: &mut World) {
    let tick = world.resource::<super::FrameTime>().fixed_tick + 1;
    if let Some(mut commands) = world.get_resource_mut::<GpuPhysicsCommands>() {
        let length = commands.commands.len();
        if commands.apply_ticks.len() != length {
            commands.apply_ticks.resize(length, tick);
        }
    }
}

/// Requests a one-shot snapshot of every GPU body in an object class.
///
/// Each member's state arrives together, one to three frames later, as a
/// [`GpuStateMirror`] carrying the same tick. Returns how many bodies were
/// requested. Use it when gameplay needs more than events for a group,
/// without paying [`PhysicsSyncMode::SelectedState`] every tick.
pub fn request_gpu_class_snapshot(world: &mut World, class: &str) -> usize {
    let members = world
        .query::<(&PhysicsId, &super::ObjectClasses)>()
        .iter(world)
        .filter(|(_, classes)| classes.contains(class))
        .map(|(id, _)| *id)
        .collect::<Vec<_>>();
    let mut commands = world.resource_mut::<GpuPhysicsCommands>();
    for &id in &members {
        commands.push(id, GpuBodyCommand::ReadState);
    }
    members.len()
}

/// Version of the GPU physics ABI in `src/shaders/physics_abi.glsl`: the body
/// state, command, and event layouts, the push constants, the bindings, and
/// `emit_event`. GLSL sees it as `RUSTING_PHYSICS_ABI_VERSION`. It changes
/// whenever a custom shader written for the old layout would break.
pub const GPU_PHYSICS_ABI_VERSION: u32 = 1;

/// Custom GLSL that runs over every GPU body after each fixed step.
///
/// `glsl` must define `void condition(inout PhysicsState body)`. It sees the
/// ABI in `src/shaders/physics_abi.glsl` (the `PhysicsState` layout, the `pc`
/// push constants with `dt`, `elapsed`, and the tick) and reports with the
/// same `emit_event(body, event_id, payload_kind, payload)` as built-in rules.
/// `EVENTS[i]` is the [`GpuEventId`] of `events[i]`, registered by name, so
/// Rust receives these as ordinary [`GpuPhysicsEvent`]s. Changes to `body`
/// are written back, so a hook can also steer the simulation.
///
/// The renderer compiles the source at runtime with `glslc` (from the Vulkan
/// SDK or shaderc; set `RUSTING_GLSLC` to use another path). A shader that
/// fails to compile is skipped and its error kept; see
/// `SceneRenderer::condition_shader_errors`. The event buffer reserves one
/// event per body, tick, and shader; more are counted as lost.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct GpuConditionShader {
    pub events: Vec<String>,
    pub glsl: String,
}

/// Custom condition shaders, dispatched in list order after the built-in step.
#[derive(Resource, Clone, Debug, Default, PartialEq)]
pub struct GpuConditionShaders(pub Vec<GpuConditionShader>);

impl GpuConditionShader {
    /// Registers the events and returns the GLSL the renderer compiles after
    /// the shared ABI: an `EVENTS` table followed by the user's code.
    #[must_use]
    pub fn resolve(&self, registry: &mut GpuEventRegistry) -> String {
        let ids = self
            .events
            .iter()
            .map(|name| format!("{}u", registry.register(name.clone()).0))
            .collect::<Vec<_>>();
        let table = if ids.is_empty() {
            String::new()
        } else {
            format!(
                "const uint EVENTS[{}] = uint[]({});\n",
                ids.len(),
                ids.join(", ")
            )
        };
        format!("{table}#line 1\n{}", self.glsl)
    }
}

/// Sent when GPU events were lost because the per-frame event buffer reached
/// its memory budget. `WhileTrue` rules fire again on the next tick, but
/// `OnEnter`/`OnExit` edges are gone; resynchronize from body state
/// ([`PhysicsSyncMode::SelectedState`]) if gameplay depends on them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GpuPhysicsEventsLost {
    pub count: u64,
}

/// Safe Rust event delivered after a raw GPU event resolves to a live entity.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GpuPhysicsEvent {
    pub entity: Entity,
    pub physics_id: PhysicsId,
    pub event_id: GpuEventId,
    pub tick: u64,
    pub flags: u32,
    pub payload_kind: u32,
    pub payload: [f32; 4],
}

/// Reports how many readback events were accepted or rejected.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct GpuEventRouteReport {
    pub delivered: usize,
    pub stale: usize,
    pub unknown_event: usize,
}

/// How much GPU simulation data one body sends back to the CPU.
///
/// Synchronization is a cost chosen per body. It is never a hidden copy of
/// the whole scene. Bodies without this component use `Events`.
#[derive(
    Component,
    Clone,
    Copy,
    Debug,
    Default,
    Deserialize,
    PartialEq,
    Eq,
    Hash,
    Serialize,
)]
pub enum PhysicsSyncMode {
    /// Nothing returns: watch rules are not evaluated for this body.
    None,
    /// Only the events of the body's watch rules return.
    #[default]
    Events,
    /// Events, plus pose and velocities in [`GpuStateMirror`] every physics
    /// frame.
    SelectedState,
    /// Like `SelectedState`, plus the body's custom values.
    FullState,
}

impl PhysicsSyncMode {
    /// Bytes copied back per body and fixed tick when state is read back.
    /// The renderer asserts this matches its packed body layout.
    pub const STATE_READBACK_BYTES: u64 = 144;

    #[must_use]
    pub fn reads_back_state(self) -> bool {
        matches!(self, Self::SelectedState | Self::FullState)
    }
}

/// GPU state of one body, copied back after its frame finished.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GpuStateSample {
    pub physics_id: PhysicsId,
    /// Fixed tick the GPU had simulated when the copy was taken.
    pub tick: u64,
    pub transform: Transform,
    pub linear_velocity: [f32; 3],
    pub angular_velocity: [f32; 3],
    /// Present only for [`PhysicsSyncMode::FullState`] bodies.
    pub custom_values: Option<[f32; 4]>,
}

/// Newest GPU state read back for a `SelectedState` or `FullState` body.
///
/// The authored `Transform` stays as it is: writing the delayed GPU pose into
/// it would count as an edit and restart the body from that older pose. Read
/// the simulated pose here, and check its age before trusting it for
/// same-tick gameplay decisions.
#[derive(Component, Clone, Copy, Debug, PartialEq)]
pub struct GpuStateMirror {
    /// Fixed tick the GPU had simulated when this state was produced.
    pub tick: u64,
    pub transform: Transform,
    pub linear_velocity: [f32; 3],
    pub angular_velocity: [f32; 3],
    pub custom_values: Option<[f32; 4]>,
}

impl GpuStateMirror {
    /// Fixed ticks between this state and `current_tick`; GPU state usually
    /// reaches the CPU one to three frames late.
    #[must_use]
    pub fn age_ticks(&self, current_tick: u64) -> u64 {
        current_tick.saturating_sub(self.tick)
    }
}

/// Lets the engine choose CPU or GPU simulation for this body.
///
/// [`allocate_auto_simulation`] decides once, writes the choice into
/// `PhysicsBody::simulation`, and records it in `decision` so tools can show
/// why. Remove this component to pick the class by hand again; set
/// `decision` to `None` to ask for a new decision. A body that is `None` or
/// `Static` when it is decided stays that way.
#[derive(
    Component,
    Clone,
    Copy,
    Debug,
    Default,
    PartialEq,
    Eq,
    Serialize,
    Deserialize,
)]
pub struct AutoSimulation {
    /// Filled in by the engine; not saved.
    #[serde(skip)]
    pub decision: Option<AllocationDecision>,
}

/// The class an [`AutoSimulation`] body got and why.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AllocationDecision {
    pub class: super::SimulationClass,
    pub reason: AllocationReason,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AllocationReason {
    /// The body was `None` or `Static`; nothing to allocate.
    NotDynamic,
    /// No GPU physics backend is connected.
    NoGpuBackend,
    /// Custom solvers run only on the GPU.
    CustomSolver,
    /// Gameplay moves kinematic bodies every frame on the CPU.
    Kinematic,
    /// Sensors and mesh colliders exist only in the CPU solver.
    CpuOnlyCollider,
    /// Reading the full state back every tick costs more than simulating
    /// the body on the CPU.
    ReadsStateEveryTick,
    /// Fewer flexible bodies than [`AutoAllocationPolicy::gpu_min_bodies`].
    FewBodies,
    /// At least [`AutoAllocationPolicy::gpu_min_bodies`] flexible bodies.
    ManyBodies,
    /// The last measured CPU physics time was over budget.
    CpuOverBudget,
}

/// Thresholds used by [`allocate_auto_simulation`].
#[derive(Resource, Clone, Copy, Debug, PartialEq)]
pub struct AutoAllocationPolicy {
    /// Flexible `AutoSimulation` bodies at which they all go to the GPU.
    pub gpu_min_bodies: usize,
    /// CPU physics time per frame above which new bodies go to the GPU.
    pub cpu_physics_budget: std::time::Duration,
}

impl Default for AutoAllocationPolicy {
    fn default() -> Self {
        Self {
            gpu_min_bodies: 256,
            cpu_physics_budget: std::time::Duration::from_millis(4),
        }
    }
}

/// A class this body must have regardless of the scene, if any.
fn required_class(
    body: &super::PhysicsBody,
    rigid: Option<&super::RigidBody>,
    collider: Option<&super::Collider>,
    sync: Option<&PhysicsSyncMode>,
    gpu: bool,
) -> Option<AllocationDecision> {
    use super::SimulationClass::{Cpu, Gpu};
    let decide = |class, reason| Some(AllocationDecision { class, reason });
    if !body.participates_in_dynamic_simulation() {
        return decide(body.simulation, AllocationReason::NotDynamic);
    }
    if !gpu {
        return decide(Cpu, AllocationReason::NoGpuBackend);
    }
    if body.solver == super::PhysicsSolver::Custom {
        return decide(Gpu, AllocationReason::CustomSolver);
    }
    if rigid.is_some_and(|rigid| rigid.kind == super::RigidBodyKind::Kinematic)
    {
        return decide(Cpu, AllocationReason::Kinematic);
    }
    if collider.is_some_and(|collider| {
        collider.sensor
            || matches!(
                collider.shape,
                super::ColliderShape::ConvexMesh
                    | super::ColliderShape::TriangleMesh
            )
    }) {
        return decide(Cpu, AllocationReason::CpuOnlyCollider);
    }
    if sync.is_some_and(|sync| sync.reads_back_state()) {
        return decide(Cpu, AllocationReason::ReadsStateEveryTick);
    }
    None
}

/// Gives every undecided [`AutoSimulation`] body a class.
///
/// Hard requirements come first (see [`AllocationReason`]); the other
/// "flexible" bodies go to the GPU when there are at least
/// `gpu_min_bodies` of them or the last frame's CPU physics was over
/// budget, else to the CPU.
// ponytail: decisions stick; a decided body never migrates between CPU and
// GPU, because that needs a live state handoff. Add one if scenes grow
// past the threshold long after they start.
pub fn allocate_auto_simulation(world: &mut World) {
    use super::SimulationClass::{Cpu, Gpu};
    let policy = world
        .get_resource::<AutoAllocationPolicy>()
        .copied()
        .unwrap_or_default();
    let gpu = world
        .get_resource::<super::PhysicsBackendStatus>()
        .is_some_and(|status| status.gpu_dynamic_available);
    let over_budget = world
        .get_resource::<super::CpuFrameTimings>()
        .is_some_and(|timings| timings.physics > policy.cpu_physics_budget);
    let mut query = world.query::<(
        Entity,
        &AutoSimulation,
        &super::PhysicsBody,
        Option<&super::RigidBody>,
        Option<&super::Collider>,
        Option<&PhysicsSyncMode>,
    )>();
    let mut flexible = 0;
    let mut pending = Vec::new();
    for (entity, auto, body, rigid, collider, sync) in query.iter(world) {
        let required = if auto.decision.is_none() {
            // Judge the authored class, not a previous decision.
            required_class(body, rigid, collider, sync, gpu)
        } else {
            auto.decision.filter(|decision| {
                decision.reason != AllocationReason::FewBodies
                    && decision.reason != AllocationReason::ManyBodies
                    && decision.reason != AllocationReason::CpuOverBudget
            })
        };
        flexible += usize::from(required.is_none());
        if auto.decision.is_none() {
            pending.push((entity, required));
        }
    }
    for (entity, required) in pending {
        let decision = required.unwrap_or(if over_budget {
            AllocationDecision {
                class: Gpu,
                reason: AllocationReason::CpuOverBudget,
            }
        } else if flexible >= policy.gpu_min_bodies {
            AllocationDecision {
                class: Gpu,
                reason: AllocationReason::ManyBodies,
            }
        } else {
            AllocationDecision {
                class: Cpu,
                reason: AllocationReason::FewBodies,
            }
        });
        let mut entity = world.entity_mut(entity);
        if let Some(mut auto) = entity.get_mut::<AutoSimulation>() {
            auto.decision = Some(decision);
        }
        if let Some(mut body) = entity.get_mut::<super::PhysicsBody>() {
            if body.simulation != decision.class {
                body.simulation = decision.class;
            }
        }
    }
}

/// Keeps a CPU collider standing in for this GPU body, so CPU queries and
/// CPU bodies can find it without reading the whole body back.
///
/// The proxy is a separate `Static` entity marked [`GpuProxyOf`]. The body's
/// `place_on` event (with a `Position` payload) creates or moves it and
/// `remove_on` removes it; removing this component or the body removes it
/// too. Its pose is as old as the event (usually one to three frames) and
/// reaches CPU queries on the next fixed step. GPU bodies never collide with
/// proxies.
#[derive(Component, Clone, Copy, Debug, PartialEq)]
pub struct GpuQueryProxy {
    pub collider: super::Collider,
    pub layers: super::CollisionLayers,
    pub place_on: GpuEventId,
    pub remove_on: Option<GpuEventId>,
}

/// Marks the CPU proxy entity of a GPU body; see [`GpuQueryProxy`].
#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
pub struct GpuProxyOf(pub Entity);

/// Places, moves and removes [`GpuQueryProxy`] proxies from this frame's
/// GPU events, in their delivery order.
fn sync_gpu_query_proxies(world: &mut World) {
    let mut proxies = world
        .query::<(Entity, &GpuProxyOf)>()
        .iter(world)
        .map(|(proxy, owner)| (owner.0, proxy))
        .collect::<HashMap<_, _>>();
    proxies.retain(|owner, proxy| {
        let alive = world.get::<GpuQueryProxy>(*owner).is_some();
        if !alive {
            world.despawn(*proxy);
        }
        alive
    });
    let events = world
        .resource::<EventQueue<GpuPhysicsEvent>>()
        .iter()
        .copied()
        .collect::<Vec<_>>();
    for event in events {
        let Some(settings) = world.get::<GpuQueryProxy>(event.entity).copied()
        else {
            continue;
        };
        if Some(event.event_id) == settings.remove_on {
            if let Some(proxy) = proxies.remove(&event.entity) {
                world.despawn(proxy);
            }
            continue;
        }
        if event.event_id != settings.place_on
            || event.payload_kind != GpuEventPayload::Position as u32
        {
            continue;
        }
        // The body's authored rotation and scale, at the reported position.
        let mut transform = world
            .get::<Transform>(event.entity)
            .copied()
            .unwrap_or_default();
        transform.position =
            [event.payload[0], event.payload[1], event.payload[2]];
        let parts = (
            transform,
            settings.collider,
            settings.layers,
            super::PhysicsBody {
                simulation: super::SimulationClass::Static,
                ..super::PhysicsBody::default()
            },
            GpuProxyOf(event.entity),
        );
        match proxies.get(&event.entity) {
            Some(&proxy) => {
                world.entity_mut(proxy).insert(parts);
            }
            None => {
                let proxy = world.spawn(parts).id();
                proxies.insert(event.entity, proxy);
            }
        }
    }
}

/// Writes read-back GPU state into [`GpuStateMirror`] on live entities.
///
/// Samples for removed bodies (stale generation) are counted and ignored, and
/// an older sample never replaces a newer one.
pub fn apply_gpu_state_samples(
    world: &mut World,
    samples: &[GpuStateSample],
) -> GpuEventRouteReport {
    let mut report = GpuEventRouteReport::default();
    for sample in samples {
        let entity = world
            .resource::<PhysicsIdRegistry>()
            .resolve(sample.physics_id);
        let Some(mut entity) =
            entity.and_then(|entity| world.get_entity_mut(entity).ok())
        else {
            report.stale += 1;
            continue;
        };
        if entity
            .get::<GpuStateMirror>()
            .is_some_and(|mirror| mirror.tick > sample.tick)
        {
            continue;
        }
        entity.insert(GpuStateMirror {
            tick: sample.tick,
            transform: sample.transform,
            linear_velocity: sample.linear_velocity,
            angular_velocity: sample.angular_velocity,
            custom_values: sample.custom_values,
        });
        report.delivered += 1;
    }
    report
}

/// One compiled rule copied into the renderer-facing physics snapshot.
#[derive(Clone, Debug, PartialEq)]
pub struct ExtractedGpuPhysicsRule {
    pub event_id: GpuEventId,
    pub instructions: Vec<GpuConditionInstruction>,
    pub mode: GpuEventMode,
    pub payload: GpuEventPayload,
    pub cooldown_seconds: f32,
}

/// GPU-owned body data prepared without exposing Vulkan buffers to ECS.
#[derive(Clone, Debug, PartialEq)]
pub struct ExtractedGpuPhysicsBody {
    pub entity: Entity,
    pub physics_id: PhysicsId,
    pub transform: Transform,
    pub rigid_body: super::RigidBody,
    /// Solver selected for this GPU body, including the Space attractor mode.
    pub solver: super::PhysicsSolver,
    /// Collides against [`super::GpuCollider`]s unless the solver is
    /// `NoCollision`. Full, Simplified and Space bodies also collide with
    /// each other.
    pub collider: Option<(super::Collider, super::CollisionLayers)>,
    /// Solver hook file of a `PhysicsSolver::Custom` body; see
    /// [`custom_solver_id`]. `None` for every other solver.
    pub custom_shader: Option<String>,
    pub rules: Vec<ExtractedGpuPhysicsRule>,
    pub sync: PhysicsSyncMode,
}

/// Identifies a custom solver file on the GPU. The native shader stores it
/// in `properties.w` of every body that uses the file, and the solver's
/// wrapper runs `solve(body)` only for those bodies. 24 bits so the id stays
/// exact as an `f32`.
// ponytail: FNV-1a hash; two paths could collide (1 in 16M). Hand out
// indices from a registry if a project ever has many solver files.
#[must_use]
pub fn custom_solver_id(path: &str) -> u32 {
    let hash = path.bytes().fold(0x811c_9dc5_u32, |hash, byte| {
        (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193)
    });
    (hash & 0x00ff_ffff).max(1)
}

/// Wraps a custom solver file as a condition shader that runs its
/// `void solve(inout PhysicsState body)` for the bodies that selected it.
/// The built-in step still applies commands and watch rules to those bodies
/// but leaves their motion to `solve`.
#[must_use]
pub fn custom_solver_source(path: &str, glsl: &str) -> String {
    format!(
        "const uint SOLVER_ID = {}u;\n#line 1\n{glsl}\n\
         void condition(inout PhysicsState body) {{\n\
         if (uint(body.properties.w) == SOLVER_ID) solve(body);\n}}\n",
        custom_solver_id(path)
    )
}

/// Returns a cheap signature of every GPU body's extracted inputs.
///
/// GPU-owned swarms keep their state after setup, so their complete CPU
/// descriptions do not need to be cloned and compared on every render frame.
/// Watch rules and class lists are covered by their change ticks rather than
/// by hashing their contents.
// ponytail: a tick bumps on any mutable access, even without a real edit; the
// full extraction that follows still compares contents before a rebuild.
pub(super) fn simple_gpu_physics_signature(world: &mut World) -> u64 {
    let mut hasher = super::FastHasher::default();
    world
        .resource_ref::<GpuPhysicsClassWatches>()
        .last_changed()
        .get()
        .hash(&mut hasher);
    let mut count = 0_u64;
    let mut query = world.query::<(
        Entity,
        &PhysicsId,
        &Transform,
        &super::PhysicsBody,
        Option<&super::RigidBody>,
        Option<Ref<super::ObjectClasses>>,
        Option<Ref<GpuPhysicsWatch>>,
        Option<&PhysicsSyncMode>,
        Option<Ref<super::Collider>>,
        Option<Ref<super::CollisionLayers>>,
    )>();
    for (
        entity,
        id,
        transform,
        body,
        rigid_body,
        classes,
        watch,
        sync,
        collider,
        layers,
    ) in query.iter(world)
    {
        if !body.uses_gpu() {
            continue;
        }
        count += 1;
        sync.copied().unwrap_or_default().hash(&mut hasher);
        classes
            .map(|classes| classes.last_changed().get())
            .hash(&mut hasher);
        watch
            .map(|watch| watch.last_changed().get())
            .hash(&mut hasher);
        collider
            .map(|collider| collider.last_changed().get())
            .hash(&mut hasher);
        layers
            .map(|layers| layers.last_changed().get())
            .hash(&mut hasher);
        entity.to_bits().hash(&mut hasher);
        id.hash(&mut hasher);
        for value in transform
            .position
            .into_iter()
            .chain(transform.rotation)
            .chain(transform.scale)
        {
            value.to_bits().hash(&mut hasher);
        }
        let solver = match body.solver {
            super::PhysicsSolver::Full => 0_u8,
            super::PhysicsSolver::Simplified => 1,
            super::PhysicsSolver::NoCollision => 2,
            super::PhysicsSolver::Custom => 3,
            super::PhysicsSolver::Space => 4,
        };
        solver.hash(&mut hasher);
        body.custom_shader.hash(&mut hasher);
        let rigid_body = rigid_body.copied().unwrap_or_default();
        (rigid_body.kind as u8).hash(&mut hasher);
        rigid_body.mass.to_bits().hash(&mut hasher);
        rigid_body.gravity_scale.to_bits().hash(&mut hasher);
        for value in rigid_body
            .linear_velocity
            .into_iter()
            .chain(rigid_body.angular_velocity)
        {
            value.to_bits().hash(&mut hasher);
        }
    }
    count.hash(&mut hasher);
    hasher.finish()
}

/// Collects GPU bodies and compiles their authored rules for rendering.
pub(super) fn extract_gpu_physics_bodies(
    world: &mut World,
) -> Vec<ExtractedGpuPhysicsBody> {
    let class_watches = world.resource::<GpuPhysicsClassWatches>().clone();
    let needs_class_lookup = !class_watches.classes.is_empty();
    let raw = {
        let mut query = world.query::<(
            Entity,
            &PhysicsId,
            &Transform,
            &super::PhysicsBody,
            Option<&super::RigidBody>,
            Option<&super::ObjectClasses>,
            Option<&GpuPhysicsWatch>,
            Option<&PhysicsSyncMode>,
            Option<&super::Collider>,
            Option<&super::CollisionLayers>,
        )>();
        query
            .iter(world)
            .filter(|(_, _, _, body, ..)| body.uses_gpu())
            .map(
                |(
                    entity,
                    id,
                    transform,
                    body,
                    rigid_body,
                    classes,
                    watch,
                    sync,
                    collider,
                    layers,
                )| {
                    let sync = sync.copied().unwrap_or_default();
                    let watched = sync != PhysicsSyncMode::None;
                    (
                        entity,
                        *id,
                        *transform,
                        body.solver,
                        (body.solver == super::PhysicsSolver::Custom)
                            .then(|| body.custom_shader.clone())
                            .flatten(),
                        rigid_body.copied().unwrap_or_default(),
                        (needs_class_lookup && watched)
                            .then(|| classes.cloned().unwrap_or_default()),
                        watch.filter(|_| watched).cloned().unwrap_or_default(),
                        sync,
                        collider.map(|collider| {
                            (*collider, layers.copied().unwrap_or_default())
                        }),
                    )
                },
            )
            .collect::<Vec<_>>()
    };

    let mut extracted = Vec::with_capacity(raw.len());
    world.resource_scope(
        |_, mut events: bevy_ecs::prelude::Mut<GpuEventRegistry>| {
            for (
                entity,
                physics_id,
                transform,
                solver,
                custom_shader,
                rigid_body,
                classes,
                watch,
                sync,
                collider,
            ) in raw
            {
                let mut authored_rules = watch.rules;
                if let Some(classes) = classes {
                    for class in classes.names {
                        if let Some(class_rules) =
                            class_watches.classes.get(&class)
                        {
                            for rule in class_rules {
                                if !authored_rules.contains(rule) {
                                    authored_rules.push(rule.clone());
                                }
                            }
                        }
                    }
                }
                let rules = authored_rules
                    .into_iter()
                    .filter_map(|rule| {
                        let instructions = rule.condition.compile().ok()?;
                        Some(ExtractedGpuPhysicsRule {
                            event_id: events.register(rule.event),
                            instructions,
                            mode: rule.mode,
                            payload: rule.payload,
                            cooldown_seconds: rule.cooldown_seconds,
                        })
                    })
                    .collect();
                extracted.push(ExtractedGpuPhysicsBody {
                    entity,
                    physics_id,
                    transform,
                    rigid_body,
                    solver,
                    collider,
                    custom_shader,
                    rules,
                    sync,
                });
            }
        },
    );
    extracted.sort_by_key(|body| body.physics_id.slot);
    extracted
}

/// Converts raw readback bytes into frame-bounded Rust gameplay events.
///
/// Delayed events with stale body generations are counted and ignored. This
/// is normal when an object is deleted while older GPU work is still running.
pub fn route_gpu_physics_events(
    world: &mut World,
    raw_events: &[RawGpuPhysicsEvent],
) -> GpuEventRouteReport {
    let resolved = {
        let ids = world.resource::<PhysicsIdRegistry>();
        raw_events
            .iter()
            .map(|raw| (*raw, ids.resolve(raw.physics_id())))
            .collect::<Vec<_>>()
    };
    let known_events = world.resource::<GpuEventRegistry>();
    let mut routed = Vec::with_capacity(resolved.len());
    let mut report = GpuEventRouteReport::default();
    for (raw, entity) in resolved {
        let Some(entity) = entity else {
            report.stale += 1;
            continue;
        };
        let event_id = GpuEventId(raw.event_id);
        if known_events.name(event_id).is_none() {
            report.unknown_event += 1;
            continue;
        }
        routed.push(GpuPhysicsEvent {
            entity,
            physics_id: raw.physics_id(),
            event_id,
            tick: raw.tick(),
            flags: raw.flags,
            payload_kind: raw.payload_kind,
            payload: raw.payload,
        });
        report.delivered += 1;
    }
    // The GPU appends events with an atomic counter, so their buffer order
    // changes from run to run. Deliver them in a fixed order instead.
    routed.sort_by_key(|event| {
        (
            event.tick,
            event.physics_id.slot,
            event.physics_id.generation,
            event.event_id.0,
            event.flags,
        )
    });
    let mut events = world.resource_mut::<EventQueue<GpuPhysicsEvent>>();
    for event in routed {
        events.send(event);
    }
    report
}

/// Installs CPU-side resources needed by the asynchronous physics bridge.
#[derive(Clone, Copy, Debug, Default)]
pub struct HybridPhysicsPlugin;

impl Plugin for HybridPhysicsPlugin {
    fn build(&self, app: &mut App) -> Result<(), AppError> {
        if !app.world().contains_resource::<PhysicsIdRegistry>() {
            app.insert_resource(PhysicsIdRegistry::default());
        }
        if !app.world().contains_resource::<GpuEventRegistry>() {
            app.insert_resource(GpuEventRegistry::default());
        }
        if !app.world().contains_resource::<GpuPhysicsClassWatches>() {
            app.insert_resource(GpuPhysicsClassWatches::default());
        }
        if !app.world().contains_resource::<GpuPhysicsCommands>() {
            app.insert_resource(GpuPhysicsCommands::default());
        }
        if !app.world().contains_resource::<GpuConditionShaders>() {
            app.insert_resource(GpuConditionShaders::default());
        }
        if !app.world().contains_resource::<AutoAllocationPolicy>() {
            app.insert_resource(AutoAllocationPolicy::default());
        }
        app.add_event::<GpuPhysicsEvent>()
            .add_event::<GpuPhysicsEventsLost>()
            .add_systems(
                ScheduleStage::PostUpdate,
                (allocate_auto_simulation, maintain_gpu_physics_ids).chain(),
            )
            .add_systems(ScheduleStage::Update, sync_gpu_query_proxies);
        Ok(())
    }
}

/// Adds IDs only when a physics body changes and releases removed IDs.
///
/// GPU simulation does not change the ECS body component every render frame,
/// so a stable swarm costs no CPU work here after its setup frame.
fn maintain_gpu_physics_ids(
    mut commands: Commands,
    changed_bodies: Query<
        (Entity, &super::PhysicsBody),
        Changed<super::PhysicsBody>,
    >,
    mut removed_bodies: RemovedComponents<super::PhysicsBody>,
    mut registry: ResMut<PhysicsIdRegistry>,
) {
    // Removal messages also cover despawned entities. Releasing the registry
    // entry is enough because a despawned entity cannot keep its component.
    for entity in removed_bodies.read() {
        registry.release(entity);
    }

    for (entity, body) in &changed_bodies {
        if body.uses_gpu() {
            let id = registry.assign(entity);
            commands.entity(entity).insert(id);
        } else {
            registry.release(entity);
            commands.entity(entity).remove::<PhysicsId>();
        }
    }
}