@series-inc/rundot-syncplay 6.0.0-rc.87 → 6.0.0-rc.88

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/core/native/physics/box3d_adapter.cpp +346 -62
  2. package/core/native/physics/box3d_adapter.hpp +39 -0
  3. package/core/native/physics/box3d_deformable.cpp +890 -102
  4. package/core/native/physics/box3d_deformable.hpp +7 -0
  5. package/core/native/physics/box3d_step_phase.hpp +36 -0
  6. package/core/native/physics/box3d_world_backend.cpp +2301 -400
  7. package/core/native/physics/deformable_abi.cpp +6 -0
  8. package/core/native/physics/deformable_abi.hpp +2 -0
  9. package/core/native/physics/deformable_geometry.hpp +917 -160
  10. package/core/native/physics/extended_abi_deformables.cpp +0 -127
  11. package/core/native/physics/extended_abi_deformables.hpp +0 -67
  12. package/core/native/physics/physics.cpp +8 -12
  13. package/core/native/physics/physics.hpp +14 -0
  14. package/core/native/physics/step_sort.hpp +122 -0
  15. package/core/native/physics/topology.cpp +2 -0
  16. package/core/native/physics/world.cpp +213 -54
  17. package/core/native/physics/world.hpp +52 -0
  18. package/core/scripts/build-native.mjs +1 -0
  19. package/core/scripts/build-wasm-physics.mjs +35 -2
  20. package/core/scripts/extended-physics-profile.mjs +0 -22
  21. package/core/src/physics/deformable-world.d.mts +3 -0
  22. package/core/src/physics/deformable-world.mjs +59 -1
  23. package/core/src/physics/feature-api.d.mts +2 -2
  24. package/core/src/physics/feature-api.mjs +12 -3
  25. package/core/src/physics/physics-profile-wasm-module.generated.mjs +11 -11
  26. package/core/src/physics/physics-profile.wasm +0 -0
  27. package/core/src/physics/physics-wasm-module.generated.mjs +11 -11
  28. package/core/src/physics/physics.wasm +0 -0
  29. package/core/src/physics/world.mjs +4 -1
  30. package/core/src/physics2d/physics2d-wasm-module.generated.mjs +1 -1
  31. package/core/world.d.ts +3 -0
  32. package/dist/physics/3d.d.ts +7 -2
  33. package/dist/physics/3d.js +2 -1
  34. package/package.json +2 -2
  35. package/third_party/box3d/PROVENANCE.md +30 -3
  36. package/third_party/box3d/UPSTREAM.json +2 -2
  37. package/third_party/box3d/tree/src/mesh.c +14 -3
  38. package/third_party/box3d/tree/src/physics_world.c +7 -4
  39. package/core/native/physics/soft_body.cpp +0 -1449
  40. package/core/native/physics/soft_body.hpp +0 -328
  41. package/core/src/physics/soft-body.d.mts +0 -149
  42. package/core/src/physics/soft-body.mjs +0 -1300
@@ -13,6 +13,7 @@
13
13
 
14
14
  #include "box3d_adapter.hpp"
15
15
  #include "box3d_step_phase.hpp"
16
+ #include "step_sort.hpp"
16
17
 
17
18
  #include "box3d_checkpoint.hpp"
18
19
  #include "box3d_digest.hpp"
@@ -32,6 +33,7 @@
32
33
  #include <atomic>
33
34
  #include <cstdlib>
34
35
  #include <cstring>
36
+ #include <exception>
35
37
  #include <cmath>
36
38
  #include <cfloat>
37
39
  #include <string>
@@ -759,10 +761,12 @@ void resetExtent(Extent& extent) {
759
761
  extent.freeBytes = 0;
760
762
  }
761
763
 
764
+ void heapFree(void* allocation) noexcept;
765
+
762
766
  void releaseExtents(WorldSlot& world) {
763
767
  for (std::uint32_t index = 0; index < world.extentCount; ++index) {
764
768
  if (world.extents[index].base != nullptr) {
765
- std::free(world.extents[index].base);
769
+ heapFree(world.extents[index].base);
766
770
  }
767
771
  resetExtent(world.extents[index]);
768
772
  }
@@ -802,16 +806,45 @@ void markFault(WorldSlot& world, const char* reason) {
802
806
  // as well as operator new.
803
807
  void* heapAllocate(std::size_t size) noexcept {
804
808
  if (SYNCPLAY_C_ALLOCATION_FAILS()) return nullptr;
805
- return std::malloc(size);
809
+ void* allocation = std::malloc(size);
810
+ SYNCPLAY_C_HEAP_TAKEN(allocation);
811
+ return allocation;
806
812
  }
807
813
 
808
814
  void* heapAllocateAligned(std::size_t alignment, std::size_t size) noexcept {
809
815
  if (SYNCPLAY_C_ALLOCATION_FAILS()) return nullptr;
810
816
  void* allocation = nullptr;
811
817
  if (posix_memalign(&allocation, alignment, size) != 0) return nullptr;
818
+ SYNCPLAY_C_HEAP_TAKEN(allocation);
812
819
  return allocation;
813
820
  }
814
821
 
822
+ // Frees a block of heapAllocate or heapAllocateAligned (test builds count the bytes that the adapter holds).
823
+ void heapFree(void* allocation) noexcept {
824
+ if (allocation == nullptr) return;
825
+ SYNCPLAY_C_HEAP_GIVEN(allocation);
826
+ std::free(allocation);
827
+ }
828
+
829
+ // The owner of one heapAllocate block that a call holds while it calls code that can throw (a failed scratch block
830
+ // of a canonical save throws std::bad_alloc): every exit frees it. release() hands the block to a longer owner.
831
+ class HeapBuffer {
832
+ public:
833
+ explicit HeapBuffer(std::size_t size) noexcept : data_(static_cast<unsigned char*>(heapAllocate(size))) {}
834
+ ~HeapBuffer() { heapFree(data_); }
835
+ HeapBuffer(const HeapBuffer&) = delete;
836
+ HeapBuffer& operator=(const HeapBuffer&) = delete;
837
+ unsigned char* get() const noexcept { return data_; }
838
+ unsigned char* release() noexcept {
839
+ unsigned char* data = data_;
840
+ data_ = nullptr;
841
+ return data;
842
+ }
843
+
844
+ private:
845
+ unsigned char* data_;
846
+ };
847
+
815
848
  Extent* addExtent(WorldSlot& world, std::size_t minimumBytes = 0);
816
849
 
817
850
  std::int32_t reserveBytes(WorldSlot& world, std::size_t required) {
@@ -1012,7 +1045,7 @@ bool recalculateFreeBytes(Extent& extent) {
1012
1045
  }
1013
1046
 
1014
1047
  void releaseEmptyExtent(WorldSlot& world, std::uint32_t index) {
1015
- std::free(world.extents[index].base);
1048
+ heapFree(world.extents[index].base);
1016
1049
  for (std::uint32_t move = index + 1; move < world.extentCount; ++move) {
1017
1050
  world.extents[move - 1] = world.extents[move];
1018
1051
  }
@@ -1065,19 +1098,57 @@ void slotFree(WorldSlot& world, void* memory) {
1065
1098
  constexpr std::uint32_t kScratchMagic = 0x53435254u;
1066
1099
  int g_scratchDepth = 0;
1067
1100
 
1101
+ // Every live scratch block, in a list through a record at the start of the block, with the scope depth that made it.
1102
+ // A scope that a throw leaves frees the blocks that its read made and still holds: a failed Box3D allocation stops the
1103
+ // C code of the read (b3CreateRecording, syncplay_world_canonical_save) before that code frees its own buffers, and no
1104
+ // world owns a scratch block. The record is the cleanup path that the throw cannot skip.
1105
+ struct ScratchRecord {
1106
+ ScratchRecord* previous;
1107
+ ScratchRecord* next;
1108
+ int depth;
1109
+ };
1110
+ ScratchRecord* g_scratchLive = nullptr;
1111
+
1112
+ void unlinkScratch(ScratchRecord* record) noexcept {
1113
+ if (record->previous != nullptr) record->previous->next = record->next;
1114
+ else g_scratchLive = record->next;
1115
+ if (record->next != nullptr) record->next->previous = record->previous;
1116
+ }
1117
+
1068
1118
  struct ScratchAllocationScope {
1069
- ScratchAllocationScope() { g_scratchDepth += 1; }
1070
- ~ScratchAllocationScope() { g_scratchDepth -= 1; }
1119
+ int exceptions;
1120
+ ScratchAllocationScope() : exceptions(std::uncaught_exceptions()) { g_scratchDepth += 1; }
1121
+ ~ScratchAllocationScope() {
1122
+ if (std::uncaught_exceptions() > exceptions) {
1123
+ ScratchRecord* record = g_scratchLive;
1124
+ while (record != nullptr) {
1125
+ ScratchRecord* next = record->next;
1126
+ if (record->depth >= g_scratchDepth) {
1127
+ unlinkScratch(record);
1128
+ heapFree(record);
1129
+ }
1130
+ record = next;
1131
+ }
1132
+ }
1133
+ g_scratchDepth -= 1;
1134
+ }
1071
1135
  ScratchAllocationScope(const ScratchAllocationScope&) = delete;
1072
1136
  ScratchAllocationScope& operator=(const ScratchAllocationScope&) = delete;
1073
1137
  };
1074
1138
 
1075
1139
  void* scratchAllocate(std::size_t size, std::size_t alignment) {
1076
1140
  const std::size_t align = alignment > kBlockHeaderBytes ? alignment : kBlockHeaderBytes;
1077
- if ((align & (align - 1)) != 0 || size > SIZE_MAX - align - kBlockHeaderBytes) return nullptr;
1078
- auto* base = static_cast<unsigned char*>(heapAllocate(size + align + kBlockHeaderBytes));
1141
+ constexpr std::size_t kRecordBytes = sizeof(ScratchRecord);
1142
+ if ((align & (align - 1)) != 0 || size > SIZE_MAX - align - kBlockHeaderBytes - kRecordBytes) return nullptr;
1143
+ auto* base = static_cast<unsigned char*>(heapAllocate(kRecordBytes + size + align + kBlockHeaderBytes));
1079
1144
  if (base == nullptr) return nullptr;
1080
- const std::uintptr_t first = reinterpret_cast<std::uintptr_t>(base) + kBlockHeaderBytes;
1145
+ auto* record = reinterpret_cast<ScratchRecord*>(base);
1146
+ record->previous = nullptr;
1147
+ record->next = g_scratchLive;
1148
+ record->depth = g_scratchDepth;
1149
+ if (g_scratchLive != nullptr) g_scratchLive->previous = record;
1150
+ g_scratchLive = record;
1151
+ const std::uintptr_t first = reinterpret_cast<std::uintptr_t>(base) + kRecordBytes + kBlockHeaderBytes;
1081
1152
  const std::uintptr_t payload = (first + align - 1) & ~static_cast<std::uintptr_t>(align - 1);
1082
1153
  auto* header = reinterpret_cast<BlockHeader*>(payload - kBlockHeaderBytes);
1083
1154
  header->magic = kScratchMagic;
@@ -1096,6 +1167,7 @@ void* adapterAlloc(std::size_t size, std::int32_t alignment) {
1096
1167
  if (g_scratchDepth > 0) return scratchAllocate(size, static_cast<std::size_t>(alignment));
1097
1168
  WorldSlot* world = activeWorldSlot();
1098
1169
  if (world == nullptr) return nullptr;
1170
+ SYNCPLAY_NOTE_WORLD_ALLOCATION(static_cast<std::uint32_t>(g_activeSlot));
1099
1171
  return slotAllocate(*world, size, static_cast<std::size_t>(alignment));
1100
1172
  }
1101
1173
 
@@ -1105,7 +1177,9 @@ void adapterFree(void* memory, std::size_t size) {
1105
1177
  auto* header =
1106
1178
  reinterpret_cast<BlockHeader*>(static_cast<unsigned char*>(memory) - kBlockHeaderBytes);
1107
1179
  if (header->magic == kScratchMagic) {
1108
- std::free(static_cast<unsigned char*>(memory) - header->offset);
1180
+ auto* record = reinterpret_cast<ScratchRecord*>(static_cast<unsigned char*>(memory) - header->offset);
1181
+ unlinkScratch(record);
1182
+ heapFree(record);
1109
1183
  return;
1110
1184
  }
1111
1185
  WorldSlot* world = activeWorldSlot();
@@ -1691,10 +1765,32 @@ void clearFirstImpacts(WorldSlot& world) {
1691
1765
  // most hits that one step can have (FirstImpactSink).
1692
1766
  // The row table of the first impacts: one row per body of the world. The step sizes it before its first write, so
1693
1767
  // a failed allocation leaves the world as it was (the step is not entered).
1768
+ // The read of the rows (syncplay_adapter_first_impacts_read) orders them through these rows, which keep their size.
1769
+ struct FirstImpactOrder {
1770
+ std::uint32_t source = 0;
1771
+ std::uint32_t bodyA = 0;
1772
+ std::uint32_t bodyB = 0;
1773
+ std::uint32_t childA = 0;
1774
+ std::uint32_t childB = 0;
1775
+ double fraction = 0.0;
1776
+ };
1777
+ std::vector<FirstImpactOrder>& firstImpactOrderRows() {
1778
+ static thread_local std::vector<FirstImpactOrder> rows;
1779
+ return rows;
1780
+ }
1781
+ std::vector<FirstImpactOrder>& firstImpactOrderScratch() {
1782
+ static thread_local std::vector<FirstImpactOrder> scratch;
1783
+ return scratch;
1784
+ }
1785
+
1694
1786
  void reserveFirstImpacts(WorldSlot& world) {
1695
1787
  const b3Counters counters = b3World_GetCounters(world.world);
1696
1788
  const std::size_t bodies = counters.bodyCount > 0 ? static_cast<std::size_t>(counters.bodyCount) : 0u;
1697
1789
  if (world.firstImpacts.rows.size() < bodies) world.firstImpacts.rows.resize(bodies);
1790
+ // The read after the step orders at most one row per body.
1791
+ std::vector<FirstImpactOrder>& order = firstImpactOrderRows();
1792
+ if (order.capacity() < world.firstImpacts.rows.size()) order.reserve(world.firstImpacts.rows.size());
1793
+ ::rundot::kinetix::physics::step_sort::reserveScratch(firstImpactOrderScratch(), world.firstImpacts.rows.size());
1698
1794
  }
1699
1795
 
1700
1796
  void beginFirstImpacts(WorldSlot& world) { clearFirstImpacts(world); }
@@ -2460,6 +2556,20 @@ void sortMoverRows(double* rows, std::uint32_t count) {
2460
2556
  }
2461
2557
  }
2462
2558
 
2559
+ // The sort scratch of the event rows (sortPhysicsEvents). It grows with every event table, so it holds the rows of
2560
+ // any table of this thread.
2561
+ std::vector<PhysicsEventRow>& physicsEventSortScratch() {
2562
+ static thread_local std::vector<PhysicsEventRow> scratch;
2563
+ return scratch;
2564
+ }
2565
+
2566
+ // Grows the event table of a world to `rows` rows, and the sort scratch with it. It allocates: a step calls it before
2567
+ // its first live write (syncplay_adapter_world_reserve_step_rows), or for a row past every bound of that reserve.
2568
+ void growPhysicsEventTable(WorldSlot& world, std::size_t rows) {
2569
+ if (world.physicsEvents.size() < rows) world.physicsEvents.resize(rows);
2570
+ ::rundot::kinetix::physics::step_sort::reserveScratch(physicsEventSortScratch(), world.physicsEvents.size());
2571
+ }
2572
+
2463
2573
  std::int32_t appendPhysicsEvent(WorldSlot& world, std::uint32_t kind, b3ShapeId shapeA,
2464
2574
  b3ShapeId shapeB, b3Pos point = {}, b3Vec3 normal = {},
2465
2575
  double speed = 0.0) {
@@ -2468,8 +2578,8 @@ std::int32_t appendPhysicsEvent(WorldSlot& world, std::uint32_t kind, b3ShapeId
2468
2578
  return kSyncplayAdapterCapacity;
2469
2579
  }
2470
2580
  if (world.physicsEventCount >= world.physicsEvents.size()) {
2471
- world.physicsEvents.resize(std::min<std::size_t>(kSyncplayAdapterMaxPhysicsEvents,
2472
- std::max<std::size_t>(1024, world.physicsEvents.size() * 2)));
2581
+ growPhysicsEventTable(world, std::min<std::size_t>(kSyncplayAdapterMaxPhysicsEvents,
2582
+ std::max<std::size_t>(1024, world.physicsEvents.size() * 2)));
2473
2583
  }
2474
2584
  const std::uint32_t bodyA = b3Shape_IsValid(shapeA) ? logicalIdOfShape(shapeA) : 0;
2475
2585
  const std::uint32_t bodyB = b3Shape_IsValid(shapeB) ? logicalIdOfShape(shapeB) : 0;
@@ -2495,9 +2605,10 @@ std::int32_t appendPhysicsEvent(WorldSlot& world, std::uint32_t kind, b3ShapeId
2495
2605
  }
2496
2606
 
2497
2607
  // A stable sort by kind, body A and body B. A stable sort has one result, so this is the order of the
2498
- // insertion sort that it replaces.
2608
+ // insertion sort that it replaces. It allocates nothing (step_sort.hpp).
2499
2609
  void sortPhysicsEvents(WorldSlot& world) {
2500
- std::stable_sort(world.physicsEvents.begin(), world.physicsEvents.begin() + world.physicsEventCount,
2610
+ PhysicsEventRow* rows = world.physicsEvents.data();
2611
+ ::rundot::kinetix::physics::step_sort::stableSort(rows, rows + world.physicsEventCount, physicsEventSortScratch(),
2501
2612
  [](const PhysicsEventRow& left, const PhysicsEventRow& right) {
2502
2613
  if (left.kind != right.kind) return left.kind < right.kind;
2503
2614
  if (left.bodyA != right.bodyA) return left.bodyA < right.bodyA;
@@ -2850,7 +2961,21 @@ std::int32_t syncplay_adapter_world_create_ex(
2850
2961
  definition.enableContinuous = enableContinuous != 0;
2851
2962
  definition.workerCount = 1;
2852
2963
  definition.enableSleep = enableSleep != 0;
2853
- const b3WorldId worldId = b3CreateWorld(&definition);
2964
+ b3WorldId worldId{};
2965
+ #if defined(__cpp_exceptions)
2966
+ // A failed Box3D allocation throws out of b3CreateWorld (adapterAllocationFailure). The fork takes its world slot
2967
+ // only when the create completes, and the extents of the half-made world are this slot's: free them here, so a
2968
+ // failed create leaves no slot and no memory.
2969
+ try {
2970
+ worldId = b3CreateWorld(&definition);
2971
+ } catch (...) {
2972
+ g_activeSlot = -1;
2973
+ resetSlot(world, slot);
2974
+ throw;
2975
+ }
2976
+ #else
2977
+ worldId = b3CreateWorld(&definition);
2978
+ #endif
2854
2979
  g_activeSlot = -1;
2855
2980
 
2856
2981
  if (!b3World_IsValid(worldId)) {
@@ -6160,6 +6285,37 @@ std::int32_t syncplay_adapter_torque_representable(const double inertia[6], cons
6160
6285
  return kSyncplayAdapterOk;
6161
6286
  }
6162
6287
 
6288
+ std::int32_t syncplay_adapter_world_reserve_step_rows(std::uint32_t slot, std::uint32_t* outRows) {
6289
+ WorldSlot* world = getWorld(slot);
6290
+ if (world == nullptr) return kSyncplayAdapterBadWorld;
6291
+ if (outRows == nullptr) return kSyncplayAdapterBadArgument;
6292
+ *outRows = 0;
6293
+ if (world->inStep) return kSyncplayAdapterStepReentry;
6294
+ // Without a begin, a Box3D contact gives at most an end and a hit, and a sensor overlap at most an end. A contact that
6295
+ // the step creates does not touch (it would begin), so the contacts before the step bound both.
6296
+ const b3Counters counters = b3World_GetCounters(world->world);
6297
+ std::uint64_t rows = 2u * static_cast<std::uint64_t>(std::max(counters.contactCount, 0));
6298
+ if (world->sensorEventsEnabled) {
6299
+ static thread_local std::vector<b3ShapeId> shapes;
6300
+ for (std::uint32_t bodyIndex = 0; bodyIndex < world->bodyCount; ++bodyIndex) {
6301
+ const BodyEntry& entry = world->bodies[bodyIndex];
6302
+ if (!b3Body_IsValid(entry.body)) continue;
6303
+ const int shapeCount = b3Body_GetShapeCount(entry.body);
6304
+ if (shapeCount <= 0) continue;
6305
+ if (shapes.size() < static_cast<std::size_t>(shapeCount)) shapes.resize(static_cast<std::size_t>(shapeCount));
6306
+ const int stored = b3Body_GetShapes(entry.body, shapes.data(), shapeCount);
6307
+ for (int shapeIndex = 0; shapeIndex < stored; ++shapeIndex) {
6308
+ const b3ShapeId shape = shapes[static_cast<std::size_t>(shapeIndex)];
6309
+ if (b3Shape_IsSensor(shape)) rows += static_cast<std::uint64_t>(std::max(b3Shape_GetSensorCapacity(shape), 0));
6310
+ }
6311
+ }
6312
+ }
6313
+ rows = std::min<std::uint64_t>(rows, kSyncplayAdapterMaxPhysicsEvents);
6314
+ growPhysicsEventTable(*world, static_cast<std::size_t>(rows));
6315
+ *outRows = static_cast<std::uint32_t>(rows);
6316
+ return kSyncplayAdapterOk;
6317
+ }
6318
+
6163
6319
  std::int32_t syncplay_adapter_world_step(std::uint32_t slot, double timeStep,
6164
6320
  std::uint32_t subStepCount) {
6165
6321
  // Test builds: every return gives the caller back its own phase.
@@ -7227,6 +7383,11 @@ __attribute__((visibility("default"), used)) const char* syncplay_adapter_fault_
7227
7383
  return g_worlds[slot]->faultReason;
7228
7384
  }
7229
7385
 
7386
+ std::int32_t syncplay_adapter_world_faulted(std::uint32_t slot) {
7387
+ if (slot >= kMaxWorlds || g_worlds[slot] == nullptr) return 0;
7388
+ return g_worlds[slot]->fault ? 1 : 0;
7389
+ }
7390
+
7230
7391
  std::int32_t syncplay_adapter_body_create_box(
7231
7392
  std::uint32_t slot, std::uint32_t logicalId, std::uint32_t type, double halfX, double halfY,
7232
7393
  double halfZ, double positionX, double positionY, double positionZ, double rotationX,
@@ -7561,6 +7722,25 @@ std::int32_t syncplay_adapter_body_read(std::uint32_t slot, std::uint32_t logica
7561
7722
  return kSyncplayAdapterOk;
7562
7723
  }
7563
7724
 
7725
+ std::int32_t syncplay_adapter_body_world_center_read(std::uint32_t slot, std::uint32_t logicalId, double* out) {
7726
+ WorldSlot* world = getWorld(slot);
7727
+ if (world == nullptr) return kSyncplayAdapterBadWorld;
7728
+ if (out == nullptr) return kSyncplayAdapterBadArgument;
7729
+ BodyEntry* entry = findBody(*world, logicalId);
7730
+ if (entry == nullptr) return kSyncplayAdapterBadBody;
7731
+ g_activeSlot = static_cast<int>(slot);
7732
+ const b3Pos center = b3Body_GetWorldCenter(entry->body);
7733
+ const b3MassData mass = b3Body_GetMassData(entry->body);
7734
+ g_activeSlot = -1;
7735
+ out[0] = center.x;
7736
+ out[1] = center.y;
7737
+ out[2] = center.z;
7738
+ out[3] = mass.center.x;
7739
+ out[4] = mass.center.y;
7740
+ out[5] = mass.center.z;
7741
+ return kSyncplayAdapterOk;
7742
+ }
7743
+
7564
7744
  std::int32_t syncplay_adapter_body_copy(std::uint32_t sourceSlot, std::uint32_t targetSlot,
7565
7745
  std::uint32_t logicalId) {
7566
7746
  if (sourceSlot == targetSlot) return kSyncplayAdapterBadArgument;
@@ -7901,11 +8081,18 @@ std::int32_t syncplay_adapter_body_sort(std::uint32_t slot) {
7901
8081
  invalidateContactSnapshot(slot);
7902
8082
  WorldSlot* world = getWorld(slot);
7903
8083
  if (world == nullptr) return kSyncplayAdapterBadWorld;
7904
- std::stable_sort(world->bodies, world->bodies + world->bodyCount,
7905
- [](const BodyEntry& left, const BodyEntry& right) {
7906
- if (left.type != right.type) return left.type < right.type;
7907
- return left.logicalId < right.logicalId;
7908
- });
8084
+ // A logical id names one body, so the keys are unique and std::sort (which allocates nothing) gives the one order
8085
+ // of the stable sort that this replaces. A repeated id fails instead of giving an order of the algorithm.
8086
+ std::sort(world->bodies, world->bodies + world->bodyCount, [](const BodyEntry& left, const BodyEntry& right) {
8087
+ if (left.type != right.type) return left.type < right.type;
8088
+ return left.logicalId < right.logicalId;
8089
+ });
8090
+ for (std::uint32_t index = 1; index < world->bodyCount; ++index) {
8091
+ if (world->bodies[index - 1].logicalId == world->bodies[index].logicalId) {
8092
+ markFault(*world, "body-order-duplicate");
8093
+ return kSyncplayAdapterFault;
8094
+ }
8095
+ }
7909
8096
  for (std::uint32_t index = 0; index < world->bodyCount; ++index) {
7910
8097
  world->bodyIndex[world->bodies[index].logicalId] = static_cast<std::int32_t>(index);
7911
8098
  }
@@ -9540,6 +9727,93 @@ std::int32_t syncplay_adapter_body_ensure_mass_data(
9540
9727
  return status;
9541
9728
  }
9542
9729
 
9730
+ std::int32_t syncplay_adapter_body_ensure_settable(std::uint32_t slot, std::uint32_t logicalId, const double* values,
9731
+ std::uint32_t write, std::uint32_t* outDiffers) {
9732
+ if (outDiffers != nullptr) *outDiffers = 0;
9733
+ WorldSlot* world = getWorld(slot);
9734
+ if (world == nullptr) return kSyncplayAdapterBadWorld;
9735
+ BodyEntry* entry = findBody(*world, logicalId);
9736
+ if (entry == nullptr) return kSyncplayAdapterBadBody;
9737
+ if (values == nullptr) return kSyncplayAdapterBadArgument;
9738
+ // Bit equality: -0 and +0 are different values for the next arithmetic.
9739
+ const auto same = [](double left, double right) { return std::memcmp(&left, &right, sizeof(double)) == 0; };
9740
+ g_activeSlot = static_cast<int>(slot);
9741
+ const bool damping = !same(b3Body_GetLinearDamping(entry->body), values[0])
9742
+ || !same(b3Body_GetAngularDamping(entry->body), values[1]);
9743
+ const bool gravity = !same(b3Body_GetGravityScale(entry->body), values[2]);
9744
+ const bool threshold = !same(b3Body_GetSleepThreshold(entry->body), values[3]);
9745
+ const bool sleepEnabled = b3Body_IsSleepEnabled(entry->body) != (values[4] != 0.0);
9746
+ const bool bullet = b3Body_IsBullet(entry->body) != (values[5] != 0.0);
9747
+ const bool fastRotation = b3Body_IsFastRotationAllowed(entry->body) != (values[6] != 0.0);
9748
+ const std::uint32_t lockBits = static_cast<std::uint32_t>(values[18]);
9749
+ const b3MotionLocks heldLocks = b3Body_GetMotionLocks(entry->body);
9750
+ const std::uint32_t heldBits = (heldLocks.linearX ? 1u : 0u) | (heldLocks.linearY ? 2u : 0u)
9751
+ | (heldLocks.linearZ ? 4u : 0u) | (heldLocks.angularX ? 8u : 0u) | (heldLocks.angularY ? 16u : 0u)
9752
+ | (heldLocks.angularZ ? 32u : 0u);
9753
+ const bool locks = heldBits != lockBits;
9754
+ // The public row holds a safety factor only when its policy bit is set; else the body has the Box3D default.
9755
+ const double safetyFactor = values[19] != 0.0 ? values[20] : b3DefaultBodyDef().safetyFactor;
9756
+ const bool safety = !same(b3Body_GetSafetyFactor(entry->body), safetyFactor);
9757
+ g_activeSlot = -1;
9758
+ bool differs = damping || gravity || threshold || sleepEnabled || bullet || fastRotation || locks || safety;
9759
+ if (write != 0 && differs) {
9760
+ invalidateContactSnapshot(slot);
9761
+ g_activeSlot = static_cast<int>(slot);
9762
+ if (damping) {
9763
+ b3Body_SetLinearDamping(entry->body, values[0]);
9764
+ b3Body_SetAngularDamping(entry->body, values[1]);
9765
+ }
9766
+ if (gravity) b3Body_SetGravityScale(entry->body, values[2]);
9767
+ if (threshold) b3Body_SetSleepThreshold(entry->body, values[3]);
9768
+ if (sleepEnabled) b3Body_EnableSleep(entry->body, values[4] != 0.0);
9769
+ if (bullet) b3Body_SetBullet(entry->body, values[5] != 0.0);
9770
+ if (fastRotation) b3Body_AllowFastRotation(entry->body, values[6] != 0.0);
9771
+ if (safety) b3Body_SetSafetyFactor(entry->body, safetyFactor);
9772
+ // A lock that crosses fixed rotation makes Box3D compute the mass data from the shape density again
9773
+ // (b3Body_SetMotionLocks); the mass data below then holds the public values again, as the build writes them.
9774
+ if (locks) {
9775
+ b3Body_SetMotionLocks(entry->body, {(lockBits & 1u) != 0, (lockBits & 2u) != 0, (lockBits & 4u) != 0,
9776
+ (lockBits & 8u) != 0, (lockBits & 16u) != 0, (lockBits & 32u) != 0});
9777
+ }
9778
+ g_activeSlot = -1;
9779
+ }
9780
+ if (values[7] != 0.0) {
9781
+ g_activeSlot = static_cast<int>(slot);
9782
+ const b3MassData current = b3Body_GetMassData(entry->body);
9783
+ const b3MotionLocks locks = b3Body_GetMotionLocks(entry->body);
9784
+ g_activeSlot = -1;
9785
+ // The values that b3Body_SetMassData leaves (syncplay_adapter_body_ensure_mass_data): a body with fixed rotation
9786
+ // keeps a zero inertia.
9787
+ const bool fixedRotation = locks.angularX && locks.angularY && locks.angularZ;
9788
+ const double ixx = values[9];
9789
+ const double iyy = values[10];
9790
+ const double izz = values[11];
9791
+ const double ixy = values[12];
9792
+ const double ixz = values[13];
9793
+ const double iyz = values[14];
9794
+ const double stored[13] = {
9795
+ values[8], values[15], values[16], values[17],
9796
+ fixedRotation ? 0.0 : ixx, fixedRotation ? 0.0 : ixy, fixedRotation ? 0.0 : ixz,
9797
+ fixedRotation ? 0.0 : ixy, fixedRotation ? 0.0 : iyy, fixedRotation ? 0.0 : iyz,
9798
+ fixedRotation ? 0.0 : ixz, fixedRotation ? 0.0 : iyz, fixedRotation ? 0.0 : izz};
9799
+ const double held[13] = {
9800
+ current.mass, current.center.x, current.center.y, current.center.z,
9801
+ current.inertia.cx.x, current.inertia.cx.y, current.inertia.cx.z,
9802
+ current.inertia.cy.x, current.inertia.cy.y, current.inertia.cy.z,
9803
+ current.inertia.cz.x, current.inertia.cz.y, current.inertia.cz.z};
9804
+ if (std::memcmp(stored, held, sizeof(stored)) != 0) {
9805
+ differs = true;
9806
+ if (write != 0) {
9807
+ const std::int32_t status = syncplay_adapter_body_set_mass_data(
9808
+ slot, logicalId, values[8], ixx, iyy, izz, ixy, ixz, iyz, values[15], values[16], values[17]);
9809
+ if (status != kSyncplayAdapterOk) return status;
9810
+ }
9811
+ }
9812
+ }
9813
+ if (outDiffers != nullptr) *outDiffers = differs ? 1u : 0u;
9814
+ return kSyncplayAdapterOk;
9815
+ }
9816
+
9543
9817
  std::int32_t syncplay_adapter_body_set_linear_velocity(std::uint32_t slot, std::uint32_t logicalId,
9544
9818
  double x, double y, double z) {
9545
9819
  invalidateContactSnapshot(slot);
@@ -9712,6 +9986,19 @@ std::int32_t syncplay_adapter_body_safety_factor_read(std::uint32_t slot,
9712
9986
  return kSyncplayAdapterOk;
9713
9987
  }
9714
9988
 
9989
+ std::int32_t syncplay_adapter_body_sleep_enabled_read(std::uint32_t slot, std::uint32_t logicalId,
9990
+ std::uint32_t* outEnabled) {
9991
+ WorldSlot* world = getWorld(slot);
9992
+ if (world == nullptr) return kSyncplayAdapterBadWorld;
9993
+ if (outEnabled == nullptr) return kSyncplayAdapterBadArgument;
9994
+ BodyEntry* entry = findBody(*world, logicalId);
9995
+ if (entry == nullptr) return kSyncplayAdapterBadBody;
9996
+ g_activeSlot = static_cast<int>(slot);
9997
+ *outEnabled = b3Body_IsSleepEnabled(entry->body) ? 1u : 0u;
9998
+ g_activeSlot = -1;
9999
+ return kSyncplayAdapterOk;
10000
+ }
10001
+
9715
10002
  std::int32_t syncplay_adapter_body_set_bullet(std::uint32_t slot, std::uint32_t logicalId,
9716
10003
  std::uint32_t bullet) {
9717
10004
  WorldSlot* world = getWorld(slot);
@@ -12965,15 +13252,9 @@ std::int32_t syncplay_adapter_first_impacts_read(std::uint32_t slot, double* out
12965
13252
  *outCount = count;
12966
13253
  return kSyncplayAdapterCapacity;
12967
13254
  }
12968
- struct Resolved {
12969
- std::uint32_t source = 0;
12970
- std::uint32_t bodyA = 0;
12971
- std::uint32_t bodyB = 0;
12972
- std::uint32_t childA = 0;
12973
- std::uint32_t childB = 0;
12974
- double fraction = 0.0;
12975
- };
12976
- static thread_local std::vector<Resolved> resolved;
13255
+ using Resolved = FirstImpactOrder;
13256
+ // The step sized both tables for the rows of its world (reserveFirstImpacts), so this read allocates nothing then.
13257
+ std::vector<Resolved>& resolved = firstImpactOrderRows();
12977
13258
  resolved.resize(count);
12978
13259
  g_activeSlot = static_cast<int>(slot);
12979
13260
  // Resolve the two sides of every row and place the answer beside the stored rows, so the order of
@@ -12992,7 +13273,8 @@ std::int32_t syncplay_adapter_first_impacts_read(std::uint32_t slot, double* out
12992
13273
  }
12993
13274
  g_activeSlot = -1;
12994
13275
  // A stable sort by the published row: the order of the insertion sort that it replaces.
12995
- std::stable_sort(resolved.begin(), resolved.end(), [](const Resolved& left, const Resolved& right) {
13276
+ ::rundot::kinetix::physics::step_sort::stableSort(resolved, firstImpactOrderScratch(),
13277
+ [](const Resolved& left, const Resolved& right) {
12996
13278
  if (left.fraction != right.fraction) return left.fraction < right.fraction;
12997
13279
  if (left.bodyA != right.bodyA) return left.bodyA < right.bodyA;
12998
13280
  if (left.bodyB != right.bodyB) return left.bodyB < right.bodyB;
@@ -14163,7 +14445,7 @@ void releaseRetainedChunk(RetainedStore& store, std::uint32_t index) {
14163
14445
  if (!chunk.inUse || chunk.references == 0) return;
14164
14446
  chunk.references -= 1;
14165
14447
  if (chunk.references == 0) {
14166
- std::free(chunk.data);
14448
+ heapFree(chunk.data);
14167
14449
  chunk = RetainedChunk{};
14168
14450
  }
14169
14451
  }
@@ -14198,16 +14480,15 @@ std::int32_t storeRetainedChunk(RetainedStore& store, const unsigned char hash[3
14198
14480
  if (index > static_cast<std::uint32_t>(std::numeric_limits<std::int32_t>::max())) return -1;
14199
14481
  if (index == store.chunks.size() && !growRetainedRows(store.chunks)) return -1;
14200
14482
  const std::uint32_t ceiling = size + size / kRetainedLzTok + 32;
14201
- auto* compact = static_cast<unsigned char*>(heapAllocate(ceiling));
14202
- if (compact == nullptr) return -1;
14203
- const std::uint32_t compactSize = retainedLzEncode(data, size, compact, ceiling);
14483
+ HeapBuffer compact(ceiling);
14484
+ if (compact.get() == nullptr) return -1;
14485
+ const std::uint32_t compactSize = retainedLzEncode(data, size, compact.get(), ceiling);
14204
14486
  RetainedChunk& chunk = store.chunks[index];
14205
14487
  if (compactSize != 0) {
14206
- chunk.data = compact;
14488
+ chunk.data = compact.release();
14207
14489
  chunk.size = compactSize;
14208
14490
  chunk.codec = kRetainedCodecLz;
14209
14491
  } else {
14210
- std::free(compact);
14211
14492
  chunk.data = static_cast<unsigned char*>(heapAllocate(size));
14212
14493
  if (chunk.data == nullptr) return -1;
14213
14494
  std::memcpy(chunk.data, data, size);
@@ -15023,12 +15304,11 @@ std::int32_t syncplay_adapter_canonical_strong_digest(std::uint32_t slot,
15023
15304
  std::uint32_t size = 0;
15024
15305
  const std::int32_t sizeStatus = syncplay_adapter_canonical_size(slot, &size);
15025
15306
  if (sizeStatus != kSyncplayAdapterOk) return sizeStatus;
15026
- auto* bytes = static_cast<unsigned char*>(heapAllocate(size));
15027
- if (bytes == nullptr) return kSyncplayAdapterCapacity;
15307
+ const HeapBuffer bytes(size);
15308
+ if (bytes.get() == nullptr) return kSyncplayAdapterCapacity;
15028
15309
  std::uint32_t written = 0;
15029
- const std::int32_t saveStatus = syncplay_adapter_canonical_save(slot, bytes, size, &written);
15030
- const bool hashed = saveStatus == kSyncplayAdapterOk && strongDigest(bytes, written, out);
15031
- std::free(bytes);
15310
+ const std::int32_t saveStatus = syncplay_adapter_canonical_save(slot, bytes.get(), size, &written);
15311
+ const bool hashed = saveStatus == kSyncplayAdapterOk && strongDigest(bytes.get(), written, out);
15032
15312
  if (saveStatus != kSyncplayAdapterOk) return saveStatus;
15033
15313
  return hashed ? kSyncplayAdapterOk : kSyncplayAdapterCheckpointCorrupt;
15034
15314
  }
@@ -15069,7 +15349,8 @@ std::int32_t syncplay_adapter_retained_create(std::uint32_t slot,
15069
15349
  #else
15070
15350
  checkpoint.chunks.assign(chunkCount, 0);
15071
15351
  #endif
15072
- auto* bytes = static_cast<unsigned char*>(heapAllocate(size));
15352
+ const HeapBuffer image(size);
15353
+ unsigned char* const bytes = image.get();
15073
15354
  if (bytes == nullptr) {
15074
15355
  checkpoint = RetainedCheckpoint{};
15075
15356
  return kSyncplayAdapterCapacity;
@@ -15077,7 +15358,6 @@ std::int32_t syncplay_adapter_retained_create(std::uint32_t slot,
15077
15358
  std::uint32_t written = 0;
15078
15359
  const std::int32_t saveStatus = syncplay_adapter_checkpoint_save(slot, bytes, size, &written);
15079
15360
  if (saveStatus != kSyncplayAdapterOk) {
15080
- std::free(bytes);
15081
15361
  checkpoint = RetainedCheckpoint{};
15082
15362
  return saveStatus;
15083
15363
  }
@@ -15092,7 +15372,6 @@ std::int32_t syncplay_adapter_retained_create(std::uint32_t slot,
15092
15372
  releaseRetainedChunk(store, checkpoint.chunks[release]);
15093
15373
  }
15094
15374
  checkpoint = RetainedCheckpoint{};
15095
- std::free(bytes);
15096
15375
  return kSyncplayAdapterCheckpointCorrupt;
15097
15376
  }
15098
15377
  const std::int32_t chunkIndex = storeRetainedChunk(store, hash, bytes + offset, chunkSize);
@@ -15101,7 +15380,6 @@ std::int32_t syncplay_adapter_retained_create(std::uint32_t slot,
15101
15380
  releaseRetainedChunk(store, checkpoint.chunks[release]);
15102
15381
  }
15103
15382
  checkpoint = RetainedCheckpoint{};
15104
- std::free(bytes);
15105
15383
  return kSyncplayAdapterCapacity;
15106
15384
  }
15107
15385
  checkpoint.chunks[index] = static_cast<std::uint32_t>(chunkIndex);
@@ -15111,7 +15389,6 @@ std::int32_t syncplay_adapter_retained_create(std::uint32_t slot,
15111
15389
  checkpoint.size = size;
15112
15390
  store.liveCheckpoints += 1;
15113
15391
  store.logicalBytes += size;
15114
- std::free(bytes);
15115
15392
  *outHandle = (slot << kRetainedHandleRowBits) | (row + 1);
15116
15393
  return kSyncplayAdapterOk;
15117
15394
  }
@@ -15125,16 +15402,15 @@ std::int32_t syncplay_adapter_retained_restore(std::uint32_t slot,
15125
15402
  const RetainedCheckpoint* found = retainedRowOf(handle, &store, &owner);
15126
15403
  if (found == nullptr || owner != slot) return kSyncplayAdapterBadArgument;
15127
15404
  const RetainedCheckpoint& checkpoint = *found;
15128
- auto* bytes = static_cast<unsigned char*>(heapAllocate(checkpoint.size));
15405
+ const HeapBuffer image(checkpoint.size);
15406
+ unsigned char* const bytes = image.get();
15129
15407
  if (bytes == nullptr) return kSyncplayAdapterCapacity;
15130
15408
  for (std::uint32_t index = 0; index < checkpoint.chunks.size(); ++index) {
15131
15409
  if (checkpoint.chunks[index] >= store->chunks.size()) {
15132
- std::free(bytes);
15133
15410
  return kSyncplayAdapterCheckpointCorrupt;
15134
15411
  }
15135
15412
  const RetainedChunk& chunk = store->chunks[checkpoint.chunks[index]];
15136
15413
  if (!chunk.inUse || chunk.references == 0) {
15137
- std::free(bytes);
15138
15414
  return kSyncplayAdapterCheckpointCorrupt;
15139
15415
  }
15140
15416
  const std::uint32_t offset = index * kRetainedChunkBytes;
@@ -15142,24 +15418,19 @@ std::int32_t syncplay_adapter_retained_restore(std::uint32_t slot,
15142
15418
  offset + kRetainedChunkBytes <= checkpoint.size ? kRetainedChunkBytes
15143
15419
  : checkpoint.size - offset;
15144
15420
  if (chunk.rawSize != chunkSize) {
15145
- std::free(bytes);
15146
15421
  return kSyncplayAdapterCheckpointCorrupt;
15147
15422
  }
15148
15423
  if (chunk.codec == kRetainedCodecLz) {
15149
15424
  if (!retainedLzDecode(chunk.data, chunk.size, bytes + offset, chunkSize, chunkSize)) {
15150
- std::free(bytes);
15151
15425
  return kSyncplayAdapterCheckpointCorrupt;
15152
15426
  }
15153
15427
  } else if (chunk.size == chunkSize) {
15154
15428
  std::memcpy(bytes + offset, chunk.data, chunkSize);
15155
15429
  } else {
15156
- std::free(bytes);
15157
15430
  return kSyncplayAdapterCheckpointCorrupt;
15158
15431
  }
15159
15432
  }
15160
- const std::int32_t status = syncplay_adapter_checkpoint_restore(slot, bytes, checkpoint.size);
15161
- std::free(bytes);
15162
- return status;
15433
+ return syncplay_adapter_checkpoint_restore(slot, bytes, checkpoint.size);
15163
15434
  }
15164
15435
 
15165
15436
  std::int32_t syncplay_adapter_retained_release(std::uint32_t handle) {
@@ -15481,15 +15752,14 @@ std::int32_t syncplay_adapter_canonical_restore_ex(std::uint32_t slot, const voi
15481
15752
  std::uint32_t backupSize = 0;
15482
15753
  const std::int32_t backupSizeStatus = syncplay_adapter_checkpoint_size(slot, &backupSize);
15483
15754
  if (backupSizeStatus != kSyncplayAdapterOk) return backupSizeStatus;
15484
- auto* backup = static_cast<unsigned char*>(heapAllocate(backupSize));
15485
- if (backup == nullptr) return kSyncplayAdapterCapacity;
15755
+ HeapBuffer backupImage(backupSize);
15756
+ if (backupImage.get() == nullptr) return kSyncplayAdapterCapacity;
15486
15757
  std::uint32_t backupWritten = 0;
15487
15758
  const std::int32_t backupStatus =
15488
- syncplay_adapter_checkpoint_save(slot, backup, backupSize, &backupWritten);
15489
- if (backupStatus != kSyncplayAdapterOk) {
15490
- std::free(backup);
15491
- return backupStatus;
15492
- }
15759
+ syncplay_adapter_checkpoint_save(slot, backupImage.get(), backupSize, &backupWritten);
15760
+ if (backupStatus != kSyncplayAdapterOk) return backupStatus;
15761
+ // From here the rollback below owns the backup.
15762
+ unsigned char* const backup = backupImage.release();
15493
15763
 
15494
15764
  // Scope guard of the restore. The backup and the registry ownership are process state, so every exit
15495
15765
  // after this point puts the backup back and settles the record as an aborted restore. The
@@ -15512,7 +15782,7 @@ std::int32_t syncplay_adapter_canonical_restore_ex(std::uint32_t slot, const voi
15512
15782
  if (forkRestored) settleCanonicalRestore(*world, slot, false);
15513
15783
  world->canonicalImport = false;
15514
15784
  }
15515
- std::free(backup);
15785
+ heapFree(backup);
15516
15786
  }
15517
15787
  } rollback{world, slot, backup, backupWritten, false, false};
15518
15788
 
@@ -15716,6 +15986,20 @@ std::int32_t syncplay_adapter_set_filter_identity(
15716
15986
  return kSyncplayAdapterOk;
15717
15987
  }
15718
15988
 
15989
+ #if defined(SYNCPLAY_STEP_ALLOCATION_PHASES)
15990
+ SyncplayAdapterResourcesForTest syncplay_adapter_resources_for_test() {
15991
+ SyncplayAdapterResourcesForTest resources{};
15992
+ for (std::uint32_t slot = 0; slot < kMaxWorlds; ++slot) {
15993
+ if (g_reserved[slot]) resources.reservedIds += 1;
15994
+ if (g_worlds[slot] == nullptr) continue;
15995
+ if (g_worlds[slot]->inUse) resources.worldsInUse += 1;
15996
+ resources.extents += g_worlds[slot]->extentCount;
15997
+ }
15998
+ for (const ScratchRecord* record = g_scratchLive; record != nullptr; record = record->next) resources.scratchBlocks += 1;
15999
+ return resources;
16000
+ }
16001
+ #endif
16002
+
15719
16003
  std::uint32_t syncplay_adapter_extent_count(std::uint32_t slot) {
15720
16004
  if (slot >= kMaxWorlds || g_worlds[slot] == nullptr) return 0;
15721
16005
  return g_worlds[slot]->extentCount;