@series-inc/rundot-syncplay 6.0.0-rc.19 → 6.0.0-rc.20

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 (114) hide show
  1. package/README.md +130 -0
  2. package/core/native/instance_ledger.hpp +21 -0
  3. package/core/native/physics/abi.cpp +5 -0
  4. package/core/native/physics/abi.hpp +2 -0
  5. package/core/native/physics/capsule_triangle_native.inc +14 -11
  6. package/core/native/physics/certified_sum.hpp +218 -0
  7. package/core/native/physics/checkpoint_schema.hpp +379 -0
  8. package/core/native/physics/constraint_rows.cpp +2 -2
  9. package/core/native/physics/constraint_rows.hpp +4 -1
  10. package/core/native/physics/exact/exact-applied.hpp +57 -1
  11. package/core/native/physics/exact/word-core.hpp +1 -0
  12. package/core/native/physics/geometry_memory.hpp +160 -122
  13. package/core/native/physics/geometry_store.cpp +194 -4
  14. package/core/native/physics/geometry_store.hpp +33 -2
  15. package/core/native/physics/material_pose.hpp +96 -24
  16. package/core/native/physics/physics.cpp +294 -9
  17. package/core/native/physics/physics.hpp +73 -1
  18. package/core/native/physics/world.cpp +3110 -487
  19. package/core/native/physics/world.hpp +367 -5
  20. package/core/native/physics/world_abi.cpp +2798 -810
  21. package/core/native/physics/world_abi.hpp +269 -5
  22. package/core/native/physics/world_digest_visitor.hpp +277 -0
  23. package/core/native/physics/world_strong_digest.hpp +557 -0
  24. package/core/native/physics2d/commands.cpp +32 -11
  25. package/core/native/physics2d/owned_abi.cpp +1243 -1212
  26. package/core/native/physics2d/owned_abi.hpp +70 -55
  27. package/core/native/sha256/sha256_compress_unsigned.hpp +68 -0
  28. package/core/native/sha256/sha256_fips_constants.hpp +24 -0
  29. package/core/native/sha256/sha256_length.hpp +56 -0
  30. package/core/native/sha256/sha256_memo.hpp +48 -0
  31. package/core/native/sha256/sha256_sink.hpp +234 -0
  32. package/core/physics2d-owned.d.ts +292 -168
  33. package/core/runtime.d.ts +112 -34
  34. package/core/scripts/build-native.mjs +10 -0
  35. package/core/scripts/build-wasm-physics.mjs +104 -15
  36. package/core/src/kinetix-owned-runtime-adapter.mjs +115 -54
  37. package/core/src/kinetix-runtime-adapter-utils.mjs +1 -0
  38. package/core/src/kinetix-runtime-contract.mjs +19 -9
  39. package/core/src/kinetix-runtime-identity.mjs +12 -1
  40. package/core/src/kinetix-state-report.mjs +36 -0
  41. package/core/src/physics/abi-constants.mjs +3 -2
  42. package/core/src/physics/buoyancy.d.mts +132 -59
  43. package/core/src/physics/distance.d.mts +160 -7
  44. package/core/src/physics/feature-api.d.mts +13 -585
  45. package/core/src/physics/gear.d.mts +544 -301
  46. package/core/src/physics/mass-properties.d.mts +114 -3
  47. package/core/src/physics/physics-profile-wasm-module.generated.mjs +48 -0
  48. package/core/src/physics/physics-wasm-module.generated.mjs +34 -6
  49. package/core/src/physics/powertrain.d.mts +256 -226
  50. package/core/src/physics/pulley.d.mts +92 -349
  51. package/core/src/physics/rope.d.mts +230 -29
  52. package/core/src/physics/surface-velocity.d.mts +152 -196
  53. package/core/src/physics/voxel-cooking.d.mts +35 -19
  54. package/core/src/physics/voxel-cooking.mjs +55 -0
  55. package/core/src/physics/voxel-swept-quad.mjs +110 -0
  56. package/core/src/physics/wasm-instance.mjs +142 -26
  57. package/core/src/physics/world.d.mts +59 -0
  58. package/core/src/physics/world.mjs +1365 -201
  59. package/core/src/physics2d/collision.d.mts +13 -11
  60. package/core/src/physics2d/feature-api.d.mts +207 -1
  61. package/core/src/physics2d/owned-transport.mjs +189 -108
  62. package/core/src/physics2d/owned-world.mjs +3 -8
  63. package/core/src/physics2d/particle-fluid.d.mts +139 -30
  64. package/core/src/physics2d/particle-fluid.mjs +67 -31
  65. package/core/src/physics2d/physics2d-wasm-module.generated.mjs +21 -4
  66. package/core/src/physics2d/submerged-geometry.d.mts +35 -16
  67. package/core/src/runtime.mjs +9 -0
  68. package/core/src/shared/bytes.d.mts +2 -0
  69. package/core/src/shared/bytes.mjs +33 -0
  70. package/core/src/shared/sha256.d.mts +3 -0
  71. package/core/src/shared/sha256.mjs +81 -116
  72. package/core/units.d.ts +50 -0
  73. package/core/world.d.ts +142 -1
  74. package/dist/authority-room.js +18 -12
  75. package/dist/game-byte-section.d.ts +36 -0
  76. package/dist/game-byte-section.js +350 -0
  77. package/dist/lag-compensation3d.js +11 -10
  78. package/dist/modules/character-3d.d.ts +16 -1
  79. package/dist/modules/character-3d.js +42 -5
  80. package/dist/modules/combat.js +6 -5
  81. package/dist/movement3d-revision1.d.ts +2 -0
  82. package/dist/movement3d-revision1.js +973 -0
  83. package/dist/movement3d.d.ts +53 -3
  84. package/dist/movement3d.js +899 -245
  85. package/dist/networked-client.d.ts +4 -0
  86. package/dist/networked-client.js +21 -4
  87. package/dist/physics/2d.d.ts +10 -3
  88. package/dist/physics/2d.js +8 -3
  89. package/dist/physics/3d.d.ts +402 -181
  90. package/dist/physics/3d.js +1217 -337
  91. package/dist/physics/edit-result-graph.d.ts +36 -0
  92. package/dist/physics/edit-result-graph.js +141 -0
  93. package/dist/physics/game-codec3d.d.ts +41 -0
  94. package/dist/physics/game-codec3d.js +544 -0
  95. package/dist/physics/installed-checkpoint3d.d.ts +13 -0
  96. package/dist/physics/installed-checkpoint3d.js +120 -0
  97. package/dist/physics/installed-runtime3d.d.ts +51 -0
  98. package/dist/physics/installed-runtime3d.js +372 -0
  99. package/dist/physics/installed-state-commitment3d.d.ts +2 -0
  100. package/dist/physics/installed-state-commitment3d.js +24 -0
  101. package/dist/physics/units.d.ts +24 -23
  102. package/dist/physics/units.js +22 -0
  103. package/dist/physics/vehicle-state3d.d.ts +93 -0
  104. package/dist/physics/vehicle-state3d.js +1183 -0
  105. package/dist/physics/voxel-body-state.d.ts +61 -0
  106. package/dist/physics/voxel-body-state.js +410 -0
  107. package/dist/r3f-render-adapter.d.ts +1 -1
  108. package/dist/replay.js +7 -9
  109. package/dist/runtime-room-metadata.d.ts +2 -8
  110. package/dist/runtime-room-metadata.js +6 -13
  111. package/dist/session-snapshot.d.ts +13 -4
  112. package/dist/session-snapshot.js +33 -33
  113. package/dist/session-wire.js +8 -20
  114. package/package.json +9 -3
package/README.md CHANGED
@@ -463,6 +463,41 @@ The 2D engine supports circle, box, capsule, polygon, segment, chain, piecewise
463
463
  contour loops, and circular quadrant arcs with the free-side collision rule and
464
464
  strict deterministic query tie-ordering.
465
465
 
466
+ Store logical body IDs in checkpointed game state. A hit has `bodyId`. A
467
+ contact has `bodyA` and `bodyB`. Keep an application `Map` from these `bigint`
468
+ IDs to entities. Each contact then uses `entities.get(contact.bodyA)` and
469
+ `entities.get(contact.bodyB)`. It requires no body-name scan.
470
+
471
+ Resolve a fresh handle with `world.resolveBody(id)` after a restore. Old
472
+ handles are stale. Transfer IDs as decimal strings if the game codec does not
473
+ support `bigint`. Convert them with `BigInt(text)`, never `Number(text)`.
474
+ Rebuild the lookup from the restored game state before processing contacts.
475
+ Physics checkpoints do not contain the application's entity table. Transfer
476
+ and restore both parts of the same frame.
477
+
478
+ ### Grab servo revision 2
479
+
480
+ Set `behaviorRevision: 2` to use gravity compensation, target velocity,
481
+ angular damping, and the corrected local anchor. Revision 2 rotates the local
482
+ anchor with the body orientation. Existing calls use revision 1.
483
+
484
+ Use `createGrabServoState3D()` and `stepGrabServo3D()` for explicit game state.
485
+ Store the returned state with the physics checkpoint. The object wrapper
486
+ provides `capture()` and `restore()` for the same state. Restore both parts of
487
+ the same frame. The servo resolves the body ID after a physics restore.
488
+
489
+ Force and acceleration limits apply to the total force in revision 2.
490
+ This includes gravity compensation. Torque limits apply to total torque.
491
+ One scale applies to all three components. A limit can reduce compensation,
492
+ so the body can fall. The default force limit is 1000 N. A 150 kg body under
493
+ 9.81 m/s² gravity requires more than this limit to hold its position.
494
+ Choose limits for the body's mass and gravity. A binding limit cannot promise
495
+ position holding. Revision 1 keeps its earlier acceleration-limit rule.
496
+
497
+ Include the helper revision in canonical session configuration and the game
498
+ deterministic version. Store targets, tuning, force limits, release state,
499
+ and body IDs in checkpointed game state.
500
+
466
501
  The TypeScript facade does not contain a second solver. Both dimensions run in
467
502
  the canonical C++ core compiled to WASM. The internal solver algorithm, state
468
503
  layout, WASM boundary, schedule, and checkpoint representation can change when
@@ -478,3 +513,98 @@ the [3D guide](https://github.com/series-ai/venus/blob/develop/packages/sdk-docs
478
513
  the [RC1 migration helper](https://github.com/series-ai/venus/blob/develop/packages/sdk-docs/rundot-developer-platform/api/SYNCPLAY-RC1-MIGRATION.md).
479
514
  Physical-phone performance remains a release gate. Do not infer phone results
480
515
  from desktop measurements.
516
+
517
+ Restore the physics world before you restore a grab servo state. Revision 2 accepts
518
+ an active state whose body was removed in the same tick. Its next step changes
519
+ the state to `released` with reason `body-removed`. That step applies no force.
520
+ `isBroken()` reads the current condition. It does not change the captured state.
521
+
522
+ Revision 1 keeps its body handle until you restore the servo state. A physics
523
+ restore makes the old handle stale. Restore both states before the next step.
524
+
525
+ ### SI types in the next RC
526
+
527
+ The next RC requires SI constructors at typed physics call sites. Replace plain
528
+ numbers with the constructor for each quantity. Use meters for positions,
529
+ kilograms for mass, metersPerSecond for linear velocity, and newtons for force.
530
+ Use frameVelocity and frameGravity for frame quantities. Each constructor keeps
531
+ the bits of a finite input. It rejects NaN and infinity.
532
+
533
+ This change can produce TypeScript errors in existing games. Update those call
534
+ sites when you upgrade the SDK. Revision 1 helper behavior remains selected by
535
+ default. The revision 1 tests compare complete results with the previous RC.
536
+ New helper behavior requires an explicit revision selection.
537
+
538
+ ### Shape-preserving body changes
539
+
540
+ Use `world.setBodyTransform(idOrHandle, { position, orientation })` to change a pose.
541
+ Use `meters()` for each position component.
542
+ The world normalizes the quaternion.
543
+ The operation keeps the shape, mass, inertia, logical ID, and velocities.
544
+ An identical normalized pose preserves sleep and the mutation revision.
545
+ A changed pose wakes the affected dynamic joint group.
546
+
547
+ Use `world.setBodyLinearDamping(idOrHandle, factor)` to change linear damping.
548
+ The factor is the fraction of velocity kept per tick.
549
+ Its range is 0 through 1.
550
+ The operation preserves sleep.
551
+ Use `world.wakeBody(idOrHandle)` to wake a dynamic body without a velocity change.
552
+ Resolve a new handle after a checkpoint restore, or use the logical ID.
553
+
554
+ ### Batch motion output
555
+
556
+ `world.writeBodyMotionInto(poses, velocities, ids, status)` returns the body count,
557
+ mutation `revision`, and `restoreEpoch`.
558
+ Use `Float64Array` for poses and velocities.
559
+ Use `BigUint64Array` for logical IDs.
560
+ Use `Uint8Array` for status.
561
+ The output orders bodies by ascending logical ID.
562
+
563
+ Each pose has seven values: x, y, z, qx, qy, qz, qw.
564
+ Each velocity has six values: vx, vy, vz, wx, wy, wz.
565
+ Positions use meters.
566
+ Linear velocities use meters per second.
567
+ Angular velocities use radians per second.
568
+ Quaternion components have no unit.
569
+
570
+ Status bits 0 and 1 contain the body kind: static 0, dynamic 1, or kinematic 2.
571
+ Bit 2 means trigger.
572
+ Bit 3 means sensor.
573
+ Bit 4 means sleeping.
574
+ Bit 5 means angular motion is enabled.
575
+ The operation checks all buffers before it writes a value.
576
+ It preserves the unused output suffix.
577
+
578
+
579
+ Engine RPM values use `turnsPerMinute(value)`.
580
+ The powertrain reverse-gear check takes `metersPerSecond(value)`.
581
+ These constructors preserve finite values and reject NaN and infinity.
582
+
583
+ The 2D particle emitter preserves a supplied particle ID.
584
+ An omitted ID or zero requests the next automatic ID.
585
+ A supplied ID must be unique and from 1 through 4294967294.
586
+ Particle records stay in increasing ID order.
587
+
588
+ `createVoxelBody3D` creates a native body and immutable voxel state.
589
+ Store the returned state in the captured game state.
590
+ `carveVoxelBody3D` stages a cut and publishes one body edit after cooking succeeds.
591
+ Use its returned state for the next cut.
592
+ `paintVoxelBody3D` changes material IDs and keeps the same collision children.
593
+ `hydrateVoxelBodyState3D` checks the stored partition against the restored native body.
594
+ It does not replace that partition with a full cook.
595
+
596
+ Body-level sphere, capsule, and swept-quad regions use body-local meters.
597
+ Box regions use integer cell indices.
598
+ The body API accounts for `originOffset` in SI regions.
599
+ Occupancy must contain only zero and one.
600
+ Each occupied cell keeps its initial mass when a cut removes other cells.
601
+ A cut preserves the velocity of retained material when the center of mass changes.
602
+ Locked velocity components stay zero.
603
+
604
+ A removed voxel state keeps only its body ID, format, revision, and removed status.
605
+ Hydration checks that its revision is positive and its body ID is absent.
606
+ This absence check does not prove which world first allocated the removed ID.
607
+
608
+ `voxelBodyDigest3D(state)` returns the cached SHA-256 content digest. Creation, edits, and hydration compute this digest once per immutable root. Repeated reads do not scan cells or cooked children. The digest includes the body ID, revision, dimensions, occupancy, materials, child IDs and descriptors, next ID, cell mass, origin offset, and child limit. Hydrate a copied or decoded root before you read its digest or use it in carve, paint, or remove. These operations accept only roots registered by this module instance. If two package copies load, hydrate the root in the receiving copy.
609
+
610
+ Pass the current voxel root to each edit. Native validation detects differences in geometry and mass. It cannot detect a stale root that differs only in paint. Keep the returned root in canonical game state. Use that root for each later cut, paint, or removal.
@@ -88,6 +88,9 @@ struct CallerRange {
88
88
  std::size_t bytes = 0;
89
89
  std::size_t alignment = 1;
90
90
  RangeRole role = RangeRole::Input;
91
+ // elementBytes == 0 keeps a legacy range. A nonzero value must match bytes.
92
+ std::uint64_t count = 0;
93
+ std::uint64_t elementBytes = 0;
91
94
  };
92
95
 
93
96
  enum class LeaseStatus : std::uint8_t { Ok, UnknownLease, Busy };
@@ -128,8 +131,26 @@ inline bool validRole(RangeRole role) noexcept {
128
131
  return role == RangeRole::Input || role == RangeRole::Output;
129
132
  }
130
133
 
134
+ // Reject a count whose product does not fit in size_t. elementBytes == 0 is legacy.
135
+ inline bool countedProduct(std::uint64_t count, std::uint64_t elementBytes, std::size_t& bytes) noexcept {
136
+ if (elementBytes == 0) {
137
+ bytes = 0;
138
+ return count == 0;
139
+ }
140
+ if (elementBytes > static_cast<std::uint64_t>(std::numeric_limits<std::size_t>::max())) return false;
141
+ const auto element = static_cast<std::size_t>(elementBytes);
142
+ if (count > static_cast<std::uint64_t>(std::numeric_limits<std::size_t>::max() / element)) return false;
143
+ bytes = static_cast<std::size_t>(count) * element;
144
+ return true;
145
+ }
146
+
131
147
  inline bool makeRange(const CallerRange& range, std::uintptr_t& begin, std::uintptr_t& end) noexcept {
132
148
  if (!validRole(range.role)) return false;
149
+ if (range.elementBytes != 0) {
150
+ std::size_t product = 0;
151
+ if (!countedProduct(range.count, range.elementBytes, product)) return false;
152
+ if (product != range.bytes) return false;
153
+ }
133
154
  if (range.bytes == 0) {
134
155
  begin = reinterpret_cast<std::uintptr_t>(range.data);
135
156
  end = begin;
@@ -1,4 +1,5 @@
1
1
  #include "abi.hpp"
2
+ #include "certified_sum.hpp"
2
3
 
3
4
  #include <algorithm>
4
5
  #include <array>
@@ -9,6 +10,10 @@ extern "C" std::uint32_t rundot_kinetix_physics_abi_version() {
9
10
  return rundot::kinetix::physics::kAbiVersion;
10
11
  }
11
12
 
13
+ extern "C" std::uint32_t rundot_kinetix_numeric_environment_valid() {
14
+ return rundot::kinetix::physics::certified_sum::numericEnvironmentValid() ? 1u : 0u;
15
+ }
16
+
12
17
  extern "C" std::uint32_t rundot_kinetix_physics_body_stride() {
13
18
  return rundot::kinetix::physics::kBodyStride;
14
19
  }
@@ -128,4 +128,6 @@ std::int32_t rundot_kinetix_physics_shape_cast(
128
128
  const double* query_data,
129
129
  std::uint32_t query_values);
130
130
 
131
+ std::uint32_t rundot_kinetix_numeric_environment_valid();
132
+
131
133
  }
@@ -22,8 +22,11 @@ template<class T>void append(SolverOperation& operation,std::vector<T>& list,T v
22
22
  }
23
23
  list.push_back(std::move(value));
24
24
  }
25
- double sum(SolverOperation& operation,std::initializer_list<double> values){
26
- work(operation,values.size());auto& op=arithmetic(operation);exact_dyadic::Dyadic total;
25
+ double sum(SolverOperation& operation,std::initializer_list<double> values,certified_sum::SumSite site){
26
+ work(operation,values.size());auto& op=arithmetic(operation);
27
+ double certified=0;
28
+ if(certified_sum::selectCertifiedSum(site,values,certified))return certified;
29
+ exact_dyadic::Dyadic total;
27
30
  for(const auto value:values){exact_dyadic::Atom atom;exact_dyadic::Dyadic term;
28
31
  if(exact_dyadic::Atom::validate(std::bit_cast<std::uint64_t>(value),atom)!=exact_dyadic::Status::Ok)throw TriangleNativeFailure{tp::Failure::InvalidInput};
29
32
  if(op.fromAtom(atom,term)!=exact_dyadic::Status::Ok||op.sum(total,term,total)!=exact_dyadic::Status::Ok)throw TriangleNativeFailure{tp::Failure::ArithmeticExhausted};
@@ -37,15 +40,15 @@ double sum(SolverOperation& operation,std::initializer_list<double> values){
37
40
  tp::Point worldPoint(SolverOperation& operation,const Collision& collision,std::uint32_t point){
38
41
  const auto* basis=std::get_if<TriangleManifoldBasis>(&collision.coordinates);
39
42
  if(basis==nullptr||collision.pointCount>basis->midpoints.size()||point>=collision.pointCount)throw TriangleNativeFailure{tp::Failure::InvalidInput};
40
- tp::Point result;for(unsigned axis=0;axis<3;++axis)result[axis]=sum(operation,{basis->anchor[axis],basis->shapeOffset[axis],basis->midpoints[point][axis]});return result;
43
+ tp::Point result;for(unsigned axis=0;axis<3;++axis)result[axis]=sum(operation,{basis->anchor[axis],basis->shapeOffset[axis],basis->midpoints[point][axis]},certified_sum::SumSite::WorldPoint);return result;
41
44
  }
42
45
  std::array<Vec3,2> levers(SolverOperation& operation,const TriangleContactBasis& basis,const Body& a,const Body& b){
43
46
  std::array<Vec3,2> output;
44
47
  for(unsigned endpoint=0;endpoint<2;++endpoint){const auto& body=endpoint==0?a:b;
45
48
  const auto center=rotateByOrientation(body,{body.centerOfMassX,body.centerOfMassY,body.centerOfMassZ});
46
- output[endpoint]={sum(operation,{basis.anchor[0],basis.shapeOffset[0],basis.midpoint[0],-body.x,-center.x}),
47
- sum(operation,{basis.anchor[1],basis.shapeOffset[1],basis.midpoint[1],-body.y,-center.y}),
48
- sum(operation,{basis.anchor[2],basis.shapeOffset[2],basis.midpoint[2],-body.z,-center.z})};
49
+ output[endpoint]={sum(operation,{basis.anchor[0],basis.shapeOffset[0],basis.midpoint[0],-body.x,-center.x},certified_sum::SumSite::TriangleLever),
50
+ sum(operation,{basis.anchor[1],basis.shapeOffset[1],basis.midpoint[1],-body.y,-center.y},certified_sum::SumSite::TriangleLever),
51
+ sum(operation,{basis.anchor[2],basis.shapeOffset[2],basis.midpoint[2],-body.z,-center.z},certified_sum::SumSite::TriangleLever)};
49
52
  }
50
53
  return output;
51
54
  }
@@ -192,10 +195,10 @@ Collision observeGeometry(SolverOperation& operation,const Body& capsule,const B
192
195
  if(node.offset>total||node.count>total-node.offset)throw TriangleNativeFailure{tp::Failure::InvalidInput};
193
196
  auto point=[&](std::uint32_t pointIndex){work(operation);if(pointIndex>=node.count)throw TriangleNativeFailure{tp::Failure::InvalidInput};
194
197
  const auto at=(std::size_t(node.offset)+pointIndex)*3;
195
- const Vec3 local{sum(operation,{node.translation.x,payload[at]}),sum(operation,{node.translation.y,payload[at+1]}),sum(operation,{node.translation.z,payload[at+2]})};
198
+ const Vec3 local{sum(operation,{node.translation.x,payload[at]},certified_sum::SumSite::LocalTranslation),sum(operation,{node.translation.y,payload[at+1]},certified_sum::SumSite::LocalTranslation),sum(operation,{node.translation.z,payload[at+2]},certified_sum::SumSite::LocalTranslation)};
196
199
  const auto rotated=rotateByOrientation(geometry,local);
197
- return tp::Point{sum(operation,{geometry.x,geometry.shapeOffsetX,rotated.x,-capsule.x,-capsule.shapeOffsetX}),
198
- sum(operation,{geometry.y,geometry.shapeOffsetY,rotated.y,-capsule.y,-capsule.shapeOffsetY}),sum(operation,{geometry.z,geometry.shapeOffsetZ,rotated.z,-capsule.z,-capsule.shapeOffsetZ})};
200
+ return tp::Point{sum(operation,{geometry.x,geometry.shapeOffsetX,rotated.x,-capsule.x,-capsule.shapeOffsetX},certified_sum::SumSite::WorldRelative),
201
+ sum(operation,{geometry.y,geometry.shapeOffsetY,rotated.y,-capsule.y,-capsule.shapeOffsetY},certified_sum::SumSite::WorldRelative),sum(operation,{geometry.z,geometry.shapeOffsetZ,rotated.z,-capsule.z,-capsule.shapeOffsetZ},certified_sum::SumSite::WorldRelative)};
199
202
  };
200
203
  auto triangle=[&](std::uint32_t a,std::uint32_t b,std::uint32_t c,std::uint64_t triangleIndex){work(operation);input.triangle={point(a),point(b),point(c)};input.immutableTraversalOrdinal=ordinal(std::uint64_t(node.offset)+geometry.geometryFeatureOffset,triangleIndex);
201
204
  if(separatedBounds(operation,input))return;
@@ -246,7 +249,7 @@ Collision observeGeometry(SolverOperation& operation,const Body& capsule,const B
246
249
  const bool complex=kind==3||kind==4||kind==5||kind==6;
247
250
  if(complex){if(offset<previousEnd||offset>node.count||size>node.count-offset)throw TriangleNativeFailure{tp::Failure::InvalidInput};previousEnd=offset+size;}
248
251
  else if(offset||size||format)throw TriangleNativeFailure{tp::Failure::InvalidInput};
249
- const Vec3 translation{sum(operation,{node.translation.x,payload[at+1]}),sum(operation,{node.translation.y,payload[at+2]}),sum(operation,{node.translation.z,payload[at+3]})};
252
+ const Vec3 translation{sum(operation,{node.translation.x,payload[at+1]},certified_sum::SumSite::CompoundChild),sum(operation,{node.translation.y,payload[at+2]},certified_sum::SumSite::CompoundChild),sum(operation,{node.translation.z,payload[at+3]},certified_sum::SumSite::CompoundChild)};
250
253
  if(!complex){
251
254
  const auto translated=rotateByOrientation(geometry,translation);
252
255
  const double cX=geometry.x+geometry.shapeOffsetX+translated.x-(capsule.x+capsule.shapeOffsetX);
@@ -267,7 +270,7 @@ Collision observeGeometry(SolverOperation& operation,const Body& capsule,const B
267
270
  Body localCapsule=capsule;localCapsule.x=localCapsule.y=localCapsule.z=0.;localCapsule.shapeOffsetX=localCapsule.shapeOffsetY=localCapsule.shapeOffsetZ=0.;
268
271
  Body child=geometry;child.shape=node.kind;child.shape0=node.parameters[0];child.shape1=node.parameters[1];child.shape2=node.parameters[2];
269
272
  const auto translated=rotateByOrientation(geometry,node.translation);
270
- child.x=sum(operation,{geometry.x,geometry.shapeOffsetX,translated.x,-capsule.x,-capsule.shapeOffsetX});child.y=sum(operation,{geometry.y,geometry.shapeOffsetY,translated.y,-capsule.y,-capsule.shapeOffsetY});child.z=sum(operation,{geometry.z,geometry.shapeOffsetZ,translated.z,-capsule.z,-capsule.shapeOffsetZ});
273
+ child.x=sum(operation,{geometry.x,geometry.shapeOffsetX,translated.x,-capsule.x,-capsule.shapeOffsetX},certified_sum::SumSite::ChildPose);child.y=sum(operation,{geometry.y,geometry.shapeOffsetY,translated.y,-capsule.y,-capsule.shapeOffsetY},certified_sum::SumSite::ChildPose);child.z=sum(operation,{geometry.z,geometry.shapeOffsetZ,translated.z,-capsule.z,-capsule.shapeOffsetZ},certified_sum::SumSite::ChildPose);
271
274
  child.shapeOffsetX=child.shapeOffsetY=child.shapeOffsetZ=0.;
272
275
  const double p0=child.shape0,p1=child.shape1,p2=child.shape2;
273
276
  const double childRadius=child.shape==ShapeKind::Box?std::sqrt(p0*p0+p1*p1+p2*p2):(child.shape==ShapeKind::Sphere?p0:(p0+p1));
@@ -0,0 +1,218 @@
1
+ #pragma once
2
+
3
+ #include <bit>
4
+ #include <cstddef>
5
+ #include <cstdint>
6
+ #include <initializer_list>
7
+ #include <limits>
8
+
9
+ #if defined(__clang__)
10
+ #pragma float_control(precise, on, push)
11
+ #pragma clang fp reassociate(off) contract(off)
12
+ #elif defined(__GNUC__)
13
+ #pragma GCC push_options
14
+ #pragma GCC optimize("no-fast-math", "fp-contract=off")
15
+ #else
16
+ #error "certified sum requires a compiler with precise floating-point control"
17
+ #endif
18
+
19
+ namespace rundot::kinetix::physics::certified_sum {
20
+
21
+ static_assert(std::numeric_limits<double>::is_iec559,
22
+ "certified sum requires IEC 559 binary64");
23
+ #ifdef __FLT_EVAL_METHOD__
24
+ static_assert(__FLT_EVAL_METHOD__ == 0, "certified sum requires FLT_EVAL_METHOD 0");
25
+ #else
26
+ static_assert(sizeof(double) == 0, "certified sum requires a defined FLT_EVAL_METHOD");
27
+ #endif
28
+ #if defined(__FAST_MATH__)
29
+ static_assert(sizeof(double) == 0, "certified sum rejects fast-math");
30
+ #endif
31
+ #if defined(__FINITE_MATH_ONLY__) && __FINITE_MATH_ONLY__
32
+ static_assert(sizeof(double) == 0, "certified sum rejects finite-math-only");
33
+ #endif
34
+ static_assert(std::bit_cast<std::uint64_t>(std::numeric_limits<double>::denorm_min()) == 1u,
35
+ "binary64 min subnormal must be the integer 1");
36
+
37
+ // 2^-60. The biased exponent is 1023-60. The probe compares this bit pattern.
38
+ inline constexpr std::uint64_t kTwoSumProbeResidualBits =
39
+ static_cast<std::uint64_t>(1023 - 60) << 52;
40
+ // 2 * 2^-1074 = 2^-1073. This bit pattern is not computed by a floating add.
41
+ inline constexpr std::uint64_t kTwoMinSubnormalBits = 2u;
42
+ inline constexpr std::uint64_t kNearestProbeBits = 0x3ff0000000000001u;
43
+ inline constexpr std::uint64_t kEvenTieProbeBits = 0x3ff0000000000000u;
44
+ inline constexpr std::uint64_t kOddTieProbeBits = 0x3ff0000000000002u;
45
+
46
+ enum class SumSite : std::uint8_t {
47
+ WorldPoint = 0,
48
+ TriangleLever = 1,
49
+ LocalTranslation = 2,
50
+ WorldRelative = 3,
51
+ CompoundChild = 4,
52
+ ChildPose = 5,
53
+ Count = 6
54
+ };
55
+
56
+ inline bool binary64NonFinite(double value) noexcept {
57
+ const auto bits = std::bit_cast<std::uint64_t>(value);
58
+ return ((bits >> 52) & 0x7ffu) == 0x7ffu;
59
+ }
60
+
61
+ struct EnvironmentProbe {
62
+ std::uint64_t residualBits = 0;
63
+ std::uint64_t subnormalBits = 0;
64
+ std::uint64_t nearestBits = 0;
65
+ std::uint64_t evenTieBits = 0;
66
+ std::uint64_t oddTieBits = 0;
67
+ bool cancellationRejected = false;
68
+ bool valid = false;
69
+ };
70
+
71
+ inline bool certifyExactSum(const double* values, std::size_t count, double& output) noexcept;
72
+
73
+ // Check residuals, subnormals, and the rounding mode on each call.
74
+ inline EnvironmentProbe environmentProbe() noexcept {
75
+ volatile double one = 1.0;
76
+ volatile double tiny = 0x1p-60;
77
+ volatile double rounded = one + tiny;
78
+ volatile double virt = rounded - one;
79
+ volatile double recovered = rounded - virt;
80
+ volatile double low = one - recovered;
81
+ volatile double high = tiny - virt;
82
+ volatile double residual = low + high;
83
+ volatile double unit = std::numeric_limits<double>::denorm_min();
84
+ volatile double subnormalSum = unit + unit;
85
+ volatile double aboveHalfUlp = 0x1.8p-53;
86
+ volatile double nearestSum = one + aboveHalfUlp;
87
+ volatile double halfUlp = 0x1p-53;
88
+ volatile double evenTie = one + halfUlp;
89
+ volatile double odd = std::bit_cast<double>(kNearestProbeBits);
90
+ volatile double oddTie = odd + halfUlp;
91
+ const double cancellationValues[]{tiny, one, -one};
92
+ double cancellationOutput = 42.0;
93
+ const bool cancellationAccepted = certifyExactSum(cancellationValues, 3, cancellationOutput);
94
+ EnvironmentProbe probe;
95
+ probe.residualBits = std::bit_cast<std::uint64_t>(static_cast<double>(residual));
96
+ probe.subnormalBits = std::bit_cast<std::uint64_t>(static_cast<double>(subnormalSum));
97
+ probe.nearestBits = std::bit_cast<std::uint64_t>(static_cast<double>(nearestSum));
98
+ probe.evenTieBits = std::bit_cast<std::uint64_t>(static_cast<double>(evenTie));
99
+ probe.oddTieBits = std::bit_cast<std::uint64_t>(static_cast<double>(oddTie));
100
+ probe.cancellationRejected = !cancellationAccepted && cancellationOutput == 42.0;
101
+ probe.valid = probe.residualBits == kTwoSumProbeResidualBits
102
+ && probe.subnormalBits == kTwoMinSubnormalBits
103
+ && probe.nearestBits == kNearestProbeBits
104
+ && probe.evenTieBits == kEvenTieProbeBits
105
+ && probe.oddTieBits == kOddTieProbeBits
106
+ && probe.cancellationRejected;
107
+ return probe;
108
+ }
109
+
110
+ inline bool numericEnvironmentValid() noexcept {
111
+ return environmentProbe().valid;
112
+ }
113
+
114
+ inline bool certifyExactSum(const double* values, std::size_t count, double& output) noexcept {
115
+ if (values == nullptr && count != 0) return false;
116
+ std::size_t last = count;
117
+ for (std::size_t index = 0; index < count; ++index) {
118
+ if (binary64NonFinite(values[index])) return false;
119
+ if (!(values[index] == 0.0)) last = index;
120
+ }
121
+ if (last == count) {
122
+ output = 0.0;
123
+ return true;
124
+ }
125
+ double total = 0.0;
126
+ bool seen = false;
127
+ for (std::size_t index = 0; index < count; ++index) {
128
+ const double value = values[index];
129
+ if (value == 0.0) continue;
130
+ if (!seen) {
131
+ total = value;
132
+ seen = true;
133
+ if (index == last) {
134
+ output = 0.0;
135
+ if (!(total == 0.0)) output = total;
136
+ return true;
137
+ }
138
+ continue;
139
+ }
140
+ if (index == last) {
141
+ // The last active add is round-to-nearest-even of the exact sum.
142
+ volatile double result = total + value;
143
+ if (binary64NonFinite(result)) return false;
144
+ const double rounded = result;
145
+ output = 0.0;
146
+ if (!(rounded == 0.0)) output = rounded;
147
+ return true;
148
+ }
149
+ // TwoSum. A residual other than 0 means this add is not exact.
150
+ volatile double rounded = total + value;
151
+ if (binary64NonFinite(rounded)) return false;
152
+ volatile double virt = rounded - total;
153
+ if (binary64NonFinite(virt)) return false;
154
+ volatile double recovered = rounded - virt;
155
+ volatile double low = total - recovered;
156
+ volatile double high = value - virt;
157
+ volatile double residual = low + high;
158
+ if (binary64NonFinite(low) || binary64NonFinite(high) || binary64NonFinite(residual)
159
+ || !(residual == 0.0)) return false;
160
+ total = rounded;
161
+ }
162
+ return false;
163
+ }
164
+
165
+ #if defined(RUNDOT_CERTIFIED_SUM_TEST_COUNTERS)
166
+ struct SumSiteCounters {
167
+ std::uint64_t accepted[static_cast<unsigned>(SumSite::Count)]{};
168
+ std::uint64_t fallback[static_cast<unsigned>(SumSite::Count)]{};
169
+ };
170
+
171
+ inline SumSiteCounters& sumSiteCounters() noexcept {
172
+ static SumSiteCounters counters;
173
+ return counters;
174
+ }
175
+
176
+ inline bool& forceLegacySum() noexcept {
177
+ static bool force = false;
178
+ return force;
179
+ }
180
+
181
+ inline void resetSumSiteCounters() noexcept {
182
+ sumSiteCounters() = {};
183
+ }
184
+
185
+ inline void noteSumSite(SumSite site, bool accepted) noexcept {
186
+ const auto index = static_cast<unsigned>(site);
187
+ if (index >= static_cast<unsigned>(SumSite::Count)) return;
188
+ if (accepted) ++sumSiteCounters().accepted[index];
189
+ else ++sumSiteCounters().fallback[index];
190
+ }
191
+ #endif
192
+
193
+ inline bool selectCertifiedSum(SumSite site, const double* values, std::size_t count, double& output) noexcept {
194
+ double staged = 0.0;
195
+ const bool certified = numericEnvironmentValid() && certifyExactSum(values, count, staged);
196
+ #if defined(RUNDOT_CERTIFIED_SUM_TEST_COUNTERS)
197
+ const bool useFast = certified && !forceLegacySum();
198
+ noteSumSite(site, useFast);
199
+ #else
200
+ (void)site;
201
+ const bool useFast = certified;
202
+ #endif
203
+ if (!useFast) return false;
204
+ output = staged;
205
+ return true;
206
+ }
207
+
208
+ inline bool selectCertifiedSum(SumSite site, std::initializer_list<double> values, double& output) noexcept {
209
+ return selectCertifiedSum(site, values.begin(), values.size(), output);
210
+ }
211
+
212
+ }
213
+
214
+ #if defined(__clang__)
215
+ #pragma float_control(pop)
216
+ #elif defined(__GNUC__)
217
+ #pragma GCC pop_options
218
+ #endif